Java Examples for java.net.URLDecoder

The following java examples will help you to understand the usage of java.net.URLDecoder. These source code samples are taken from different open source projects.

Example 1
Project: android-sdk-sources-for-api-level-23-master  File: URLDecoderTest.java View source code
/**
     * java.net.URLDecoder#decode(java.lang.String)
     */
public void test_decodeLjava_lang_String() throws Exception {
    final String URL = "http://" + Support_Configuration.HomeAddress;
    final String URL2 = "telnet://justWantToHaveFun.com:400";
    final String URL3 = "file://myServer.org/a file with spaces.jpg";
    assertTrue("1. Incorrect encoding/decoding", URLDecoder.decode(URLEncoder.encode(URL)).equals(URL));
    assertTrue("2. Incorrect encoding/decoding", URLDecoder.decode(URLEncoder.encode(URL2)).equals(URL2));
    assertTrue("3. Incorrect encoding/decoding", URLDecoder.decode(URLEncoder.encode(URL3)).equals(URL3));
}
Example 2
Project: ARTPart-master  File: URLDecoderTest.java View source code
/**
     * java.net.URLDecoder#decode(java.lang.String)
     */
public void test_decodeLjava_lang_String() throws Exception {
    final String URL = "http://" + Support_Configuration.HomeAddress;
    final String URL2 = "telnet://justWantToHaveFun.com:400";
    final String URL3 = "file://myServer.org/a file with spaces.jpg";
    assertTrue("1. Incorrect encoding/decoding", URLDecoder.decode(URLEncoder.encode(URL)).equals(URL));
    assertTrue("2. Incorrect encoding/decoding", URLDecoder.decode(URLEncoder.encode(URL2)).equals(URL2));
    assertTrue("3. Incorrect encoding/decoding", URLDecoder.decode(URLEncoder.encode(URL3)).equals(URL3));
}
Example 3
Project: bluetooth_social-master  File: HttpUtils.java View source code
public static Map<String, String> decodeByDecodeNames(List<String> decodeNames, Map<String, String> map) {
    Set<String> keys = map.keySet();
    Iterator<String> it = keys.iterator();
    while (it.hasNext()) {
        String key = it.next();
        String value = map.get(key);
        for (String decodeName : decodeNames) {
            if (key.equals(decodeName)) {
                value = URLDecoder.decode(value);
                map.put(key, value);
            }
        }
    }
    return map;
}
Example 4
Project: hoko-android-master  File: DeferredDeeplinkingBroadcastReceiver.java View source code
@Override
public void onReceive(Context context, Intent intent) {
    try {
        String referrer = intent.getExtras().getString("referrer");
        referrer = URLDecoder.decode(referrer, "UTF-8");
        Uri uri = Uri.parse(referrer);
        HokoLog.d("Opening deferred deeplink " + uri.toString());
        Hoko.deeplinking().openDeferredURL(uri.toString());
    } catch (Exception e) {
        HokoLog.e(e);
    }
}
Example 5
Project: java-saml-master  File: NaiveUrlEncodeTest.java View source code
@Test
public void testDemonstratingUrlEncodingNotCanonical() throws UnsupportedEncodingException {
    String theString = "Hello World!";
    String naiveEncoded = NaiveUrlEncoder.encode(theString);
    String propperEncoded = Util.urlEncoder(theString);
    Assert.assertNotEquals("Encoded versions should differ", naiveEncoded, propperEncoded);
    Assert.assertEquals("Decoded versions equal", URLDecoder.decode(naiveEncoded, "UTF-8"), URLDecoder.decode(propperEncoded, "UTF-8"));
}
Example 6
Project: LaunchMyPack-master  File: Path.java View source code
public static String getApplicationDirectory() {
    String jarDir = null;
    try {
        CodeSource codeSource = Path.class.getProtectionDomain().getCodeSource();
        File jarFile = new File(URLDecoder.decode(codeSource.getLocation().toURI().getPath(), "UTF-8"));
        jarDir = jarFile.getParentFile().getPath();
    } catch (URISyntaxException ex) {
        ex.printStackTrace();
    } catch (UnsupportedEncodingException ex) {
        ex.printStackTrace();
    }
    return jarDir + "/";
}
Example 7
Project: rootbeer1-master  File: CurrJarName.java View source code
public String get() {
    try {
        String path = CurrJarName.class.getProtectionDomain().getCodeSource().getLocation().getPath();
        String ret = URLDecoder.decode(path, "UTF-8");
        File file = new File(ret);
        if (file.getName().equals("ant.jar")) {
            return "Rootbeer.jar";
        }
        if (file.getName().equals("classes")) {
            return "Rootbeer.jar";
        }
        return ret;
    } catch (Exception ex) {
        ex.printStackTrace();
        return "Rootbeer.jar";
    }
}
Example 8
Project: sequenceiq-samples-master  File: AwsCredentialsFactory.java View source code
public AWSCredentials createSimpleAWSCredentials(String accessKey, String secretAccessKey) {
    String aKey = accessKey;
    String sAccessKey = secretAccessKey;
    try {
        aKey = URLDecoder.decode(aKey, ("UTF-8"));
        sAccessKey = URLDecoder.decode(sAccessKey, ("UTF-8"));
    } catch (UnsupportedEncodingException e) {
        System.out.println(aKey + ":" + sAccessKey + e.getMessage());
    }
    return new SimpleAWSCredentials(aKey, sAccessKey);
}
Example 9
Project: sqlpower-library-master  File: ZealousURLEncoderTest.java View source code
public static void main(String[] args) throws Exception {
    String first;
    try {
        first = args[0];
    } catch (Exception e) {
        first = "This is a stock test string.  You can supply your own on the command-line!";
    }
    String second = ca.sqlpower.util.ZealousURLEncoder.zealousEncode(first);
    String third = java.net.URLDecoder.decode(second);
    System.out.println("       Your original string: " + first);
    System.out.println("       Your string, encoded: " + second);
    System.out.println("The encoded, decoded string: " + third);
}
Example 10
Project: jdk7u-jdk-master  File: URLDecoderArgs.java View source code
public static void main(String[] args) {
    try {
        String s1 = URLDecoder.decode("Hello World", null);
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException("NPE should have been thrown");
    } catch (NullPointerException e) {
        try {
            String s2 = URLDecoder.decode("Hello World", "");
        } catch (UnsupportedEncodingException ee) {
            return;
        }
        throw new RuntimeException("empty string was accepted as encoding name");
    }
    throw new RuntimeException("null reference was accepted as encoding name");
}
Example 11
Project: ManagedRuntimeInitiative-master  File: URLDecoderArgs.java View source code
public static void main(String[] args) {
    try {
        String s1 = URLDecoder.decode("Hello World", null);
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException("NPE should have been thrown");
    } catch (NullPointerException e) {
        try {
            String s2 = URLDecoder.decode("Hello World", "");
        } catch (UnsupportedEncodingException ee) {
            return;
        }
        throw new RuntimeException("empty string was accepted as encoding name");
    }
    throw new RuntimeException("null reference was accepted as encoding name");
}
Example 12
Project: openjdk-master  File: URLDecoderArgs.java View source code
public static void main(String[] args) {
    try {
        String s1 = URLDecoder.decode("Hello World", null);
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException("NPE should have been thrown");
    } catch (NullPointerException e) {
        try {
            String s2 = URLDecoder.decode("Hello World", "");
        } catch (UnsupportedEncodingException ee) {
            return;
        }
        throw new RuntimeException("empty string was accepted as encoding name");
    }
    throw new RuntimeException("null reference was accepted as encoding name");
}
Example 13
Project: openjdk8-jdk-master  File: URLDecoderArgs.java View source code
public static void main(String[] args) {
    try {
        String s1 = URLDecoder.decode("Hello World", null);
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException("NPE should have been thrown");
    } catch (NullPointerException e) {
        try {
            String s2 = URLDecoder.decode("Hello World", "");
        } catch (UnsupportedEncodingException ee) {
            return;
        }
        throw new RuntimeException("empty string was accepted as encoding name");
    }
    throw new RuntimeException("null reference was accepted as encoding name");
}
Example 14
Project: VarexJ-master  File: JPF_java_net_URLDecoder.java View source code
@MJI
public int decode__Ljava_lang_String_2Ljava_lang_String_2__Ljava_lang_String_2(MJIEnv env, int clsObjRef, int sRef, int encRef, FeatureExpr ctx) {
    String s = env.getStringObject(ctx, sRef);
    String enc = env.getStringObject(ctx, encRef);
    try {
        String e = URLDecoder.decode(s, enc);
        return env.newString(ctx, e);
    } catch (UnsupportedEncodingException x) {
        env.throwException(ctx, "java.io.UnsupportedEncodingException", x.getMessage());
        return MJIEnv.NULL;
    }
}
Example 15
Project: FURCAS-master  File: CompilationHelper.java View source code
public static String getSourceRoot(Class<?> c) {
    try {
        String classContainerPath = URLDecoder.decode(c.getProtectionDomain().getCodeSource().getLocation().getPath(), "UTF-8");
        if (!classContainerPath.endsWith(".jar")) {
            classContainerPath += "bin/";
        }
        return new File(classContainerPath).getCanonicalPath();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
Example 16
Project: jetty-hadoop-fix-master  File: EncodedHttpURITest.java View source code
public void testNonURIAscii() throws Exception {
    String url = "http://www.foo.com/mañana";
    byte[] asISO = url.getBytes("ISO-8859-1");
    String str = new String(asISO, "ISO-8859-1");
    //use a non UTF-8 charset as the encoding and url-escape as per
    //http://www.w3.org/TR/html40/appendix/notes.html#non-ascii-chars
    String s = URLEncoder.encode(url, "ISO-8859-1");
    EncodedHttpURI uri = new EncodedHttpURI("ISO-8859-1");
    //parse it, using the same encoding
    uri.parse(s);
    //decode the url encoding
    String d = URLDecoder.decode(uri.getCompletePath(), "ISO-8859-1");
    assertEquals(url, d);
}
Example 17
Project: JNAerator-master  File: ClassUtils.java View source code
public static URL getClassPath(Class<?> c) {
    String classFile = c.getName().replace('.', '/') + ".class";
    URL url = c.getClassLoader().getResource(classFile);
    if (url == null)
        return null;
    if (url.getProtocol().equals("jar")) {
        String urlFile = url.getFile();
        int i = urlFile.indexOf("!");
        if (i > 0) {
            try {
                URL jarURL = new URL(URLDecoder.decode(urlFile.substring(0, i), "UTF-8"));
                return jarURL;
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
    String urlString = url.toString();
    if (urlString.endsWith(classFile)) {
        try {
            return new URL(urlString.substring(0, urlString.length() - classFile.length()));
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }
    return null;
}
Example 18
Project: lemon-master  File: GetFileServlet.java View source code
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String requestUri = request.getRequestURI();
    requestUri = requestUri.substring(request.getContextPath().length());
    requestUri = requestUri.substring("/userfiles".length());
    String fileName = baseDir + URLDecoder.decode(requestUri, "UTF-8");
    IoUtils.copyFileToOutputStream(fileName, response.getOutputStream());
}
Example 19
Project: miso-java-master  File: EncodedHttpURITest.java View source code
public void testNonURIAscii() throws Exception {
    String url = "http://www.foo.com/mañana";
    byte[] asISO = url.getBytes("ISO-8859-1");
    String str = new String(asISO, "ISO-8859-1");
    //use a non UTF-8 charset as the encoding and url-escape as per
    //http://www.w3.org/TR/html40/appendix/notes.html#non-ascii-chars
    String s = URLEncoder.encode(url, "ISO-8859-1");
    EncodedHttpURI uri = new EncodedHttpURI("ISO-8859-1");
    //parse it, using the same encoding
    uri.parse(s);
    //decode the url encoding
    String d = URLDecoder.decode(uri.getCompletePath(), "ISO-8859-1");
    assertEquals(url, d);
}
Example 20
Project: ngrinder-master  File: ArchLoaderInitTest.java View source code
@Test
public void testArchLoader() throws ArchNotSupportedException, ArchLoaderException, UnsupportedEncodingException {
    AgentConfig agentConfig = new AgentConfig.NullAgentConfig(1).init();
    System.out.println(System.getProperty("java.library.path"));
    ArchLoaderInit archLoaderInit = new ArchLoaderInit();
    archLoaderInit.init(agentConfig.getHome().getNativeDirectory());
    Sigar sigar = new Sigar();
    sigar.getNativeLibrary();
    final String name = Charset.defaultCharset().name();
    System.out.println(name);
    System.out.println(URLDecoder.decode("D:\\nGrinder%20%ec%9a%b4%ec%98%81\\nGrinder%203" + ".3%20Release%20Package\\ngrinder-monitor\\lib\\sigar-native-1" + ".0.jar", name));
    ;
}
Example 21
Project: openshift-nexus-master  File: EncodedHttpURITest.java View source code
public void testNonURIAscii() throws Exception {
    String url = "http://www.foo.com/mañana";
    byte[] asISO = url.getBytes("ISO-8859-1");
    String str = new String(asISO, "ISO-8859-1");
    //use a non UTF-8 charset as the encoding and url-escape as per
    //http://www.w3.org/TR/html40/appendix/notes.html#non-ascii-chars
    String s = URLEncoder.encode(url, "ISO-8859-1");
    EncodedHttpURI uri = new EncodedHttpURI("ISO-8859-1");
    //parse it, using the same encoding
    uri.parse(s);
    //decode the url encoding
    String d = URLDecoder.decode(uri.getCompletePath(), "ISO-8859-1");
    assertEquals(url, d);
}
Example 22
Project: quhao-master  File: ActivityVO.java View source code
public ActivityVO build(Activity a) {
    this.activityId = a.id();
    this.mid = a.mid;
    this.cityCode = a.cityCode;
    //		this.image = a.image;
    Logger.debug(a.image);
    try {
        this.image = URLDecoder.decode(a.image, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        ExceptionUtil.getTrace(e);
    }
    Logger.debug(this.image);
    this.start = a.start;
    this.end = a.end;
    this.enable = a.enable;
    return this;
}
Example 23
Project: railo-master  File: URLDecode.java View source code
public static String call(PageContext pc, String str, String encoding) throws ExpressionException {
    try {
        return java.net.URLDecoder.decode(str, encoding);
    } catch (Throwable t) {
        try {
            return URLDecoder.decode(str, encoding, true);
        } catch (UnsupportedEncodingException uee) {
            throw new ExpressionException(uee.getMessage());
        }
    }
/*try {
			return URLDecoder.decode(str,encoding);
		} catch (UnsupportedEncodingException e) {
			throw new ExpressionException(e.getMessage());
		}*/
}
Example 24
Project: restrepo-master  File: EncodedHttpURITest.java View source code
public void testNonURIAscii() throws Exception {
    String url = "http://www.foo.com/mañana";
    byte[] asISO = url.getBytes("ISO-8859-1");
    String str = new String(asISO, "ISO-8859-1");
    //use a non UTF-8 charset as the encoding and url-escape as per
    //http://www.w3.org/TR/html40/appendix/notes.html#non-ascii-chars
    String s = URLEncoder.encode(url, "ISO-8859-1");
    EncodedHttpURI uri = new EncodedHttpURI("ISO-8859-1");
    //parse it, using the same encoding
    uri.parse(s);
    //decode the url encoding
    String d = URLDecoder.decode(uri.getCompletePath(), "ISO-8859-1");
    assertEquals(url, d);
}
Example 25
Project: ribbon-master  File: Resources.java View source code
public static URL getResource(String resourceName) {
    URL url = null;
    // attempt to load from the context classpath
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    if (loader != null) {
        url = loader.getResource(resourceName);
    }
    if (url == null) {
        // attempt to load from the system classpath
        url = ClassLoader.getSystemResource(resourceName);
    }
    if (url == null) {
        try {
            resourceName = URLDecoder.decode(resourceName, "UTF-8");
            url = (new File(resourceName)).toURI().toURL();
        } catch (Exception e) {
            logger.error("Problem loading resource", e);
        }
    }
    return url;
}
Example 26
Project: TracDroid-master  File: WikiViewClient.java View source code
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
    try {
        String strName = url.substring(url.lastIndexOf("/") + 1);
        strName = java.net.URLDecoder.decode(strName, "UTF-8");
        m_baseClass.loadWikiPage(strName, url, false);
        return true;
    } catch (UnsupportedEncodingException ex) {
        ex.printStackTrace();
    }
    return true;
}
Example 27
Project: uzlee-master  File: Utils.java View source code
public static Map<String, String> getUriQueryParameter(String url) {
    Map<String, String> query_pairs = new HashMap<>();
    String query = url.substring(url.indexOf('?') + 1);
    String[] pairs = query.split("&");
    for (String pair : pairs) {
        int idx = pair.indexOf("=");
        if (idx > -1) {
            try {
                query_pairs.put(URLDecoder.decode(pair.substring(0, idx), "UTF-8"), URLDecoder.decode(pair.substring(idx + 1), "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        } else {
            query_pairs.put(pair, null);
        }
    }
    return query_pairs;
}
Example 28
Project: vnluser-master  File: ItemTrackingProcessor.java View source code
@Override
protected DataService process(HttpRequestEvent e) {
    System.out.println("UserTrackingProcessor " + e);
    try {
        String url = e.param("url");
        String referer = e.param("referer");
        String title = e.param("title");
        String html = URLDecoder.decode(e.param("html"), "UTF-8");
        System.out.println(url);
        System.out.println(referer);
        System.out.println(title);
        System.out.println(html);
    } catch (Exception e1) {
    }
    return EMPTY;
}
Example 29
Project: WCFrameWork-master  File: DefaultParamTranslater.java View source code
@Override
public Object translate(ActionInvocationContext ctx) {
    // 原始Param
    Object original = getParam(ctx);
    if (original == null) {
        return ClassWrapper.getWrapper(getParamType()).getDefaultValue();
    }
    Object transformed = convertIfNecessary(original, getParamType(), getMethodParam());
    if (transformed != null && String.class.isInstance(transformed)) {
        try {
            String string = transformed.toString();
            string = URLDecoder.decode(string, getAction().getEncoding());
            return string;
        } catch (UnsupportedEncodingException e) {
        }
    }
    return transformed;
}
Example 30
Project: Wupsi-master  File: ComputationsResource.java View source code
@GET
@Produces("application/json")
public String index(@PathParam("sid") String systemIdd) {
    String systemId = java.net.URLDecoder.decode(systemIdd);
    Wupsifer w = Wupsifer.getInstance();
    SCSCPClient client = w.getClients().get(systemId);
    if (null == client)
        return "[]";
    List<Computation> cc = client.getComputations();
    DateFormat df = DateFormat.getInstance();
    JSONStringer js = new JSONStringer();
    try {
        // Begin array
        js.array();
        for (Computation c : cc) {
            js.object();
            js.key("id").value(c.getToken());
            js.key("startedAt").value(df.format(c.getStartedAt()));
            js.key("finishedAt").value(df.format(c.getStartedAt()));
            js.endObject();
        }
        js.endArray();
    // end array
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }
    return js.toString();
}
Example 31
Project: android_libcore-master  File: URLDecoderTest.java View source code
/**
     * @tests java.net.URLDecoder#decode(java.lang.String)
     */
@TestTargetNew(level = TestLevel.COMPLETE, notes = "", method = "decode", args = { java.lang.String.class })
public void test_decodeLjava_lang_String() throws Exception {
    // Test for method java.lang.String
    // java.net.URLDecoder.decode(java.lang.String)
    final String URL = "http://" + Support_Configuration.HomeAddress;
    final String URL2 = "telnet://justWantToHaveFun.com:400";
    final String URL3 = "file://myServer.org/a file with spaces.jpg";
    assertTrue("1. Incorrect encoding/decoding", URLDecoder.decode(URLEncoder.encode(URL)).equals(URL));
    assertTrue("2. Incorrect encoding/decoding", URLDecoder.decode(URLEncoder.encode(URL2)).equals(URL2));
    assertTrue("3. Incorrect encoding/decoding", URLDecoder.decode(URLEncoder.encode(URL3)).equals(URL3));
}
Example 32
Project: Sesat-master  File: Decoder.java View source code
//function for infotext, must decode before stripping string
public String yip_decoder(String s, int length) {
    try {
        s = java.net.URLDecoder.decode(s, "UTF-8");
        if (s.length() < length) {
            length = s.length();
            s = s.substring(0, length);
        } else {
            /* Make sure we are not cutting the string in the middle of a HTML tag. */
            if (s.indexOf("<", length) > s.indexOf(">", length)) {
                length = s.indexOf(">", length) + 1;
                s = s.substring(0, length);
            } else {
                s = s.substring(0, length) + "..";
            }
        }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return s;
}
Example 33
Project: 1314-2-common-master  File: FormUrlEncoded.java View source code
// TODO assumes Content-Length present and UTF-8 charset
public static Map<String, String> retrieveFrom(HttpServletRequest req) throws IOException {
    Map<String, String> map = new HashMap<String, String>();
    byte[] bytes = new byte[req.getContentLength()];
    req.getInputStream().read(bytes);
    String content = new String(bytes);
    String[] pairs = content.split("&");
    for (String pair : pairs) {
        String[] kvp = pair.split("=");
        map.put(URLDecoder.decode(kvp[0], "UTF-8"), URLDecoder.decode(kvp[1], "UTF-8"));
    }
    return map;
}
Example 34
Project: 5.2.0.RC-master  File: JarFileUtils.java View source code
/**
	 * 从jar文件中读�文件
	 * @param url 该文件在jar中的路径
	 * @return 文件内容
	 */
public static <T> String readFile(Class<T> clazz, String url) throws Exception {
    String currentJarPath = URLDecoder.decode(clazz.getProtectionDomain().getCodeSource().getLocation().getFile(), "UTF-8");
    JarFile currentJar = new JarFile(currentJarPath);
    JarEntry dbEntry = currentJar.getJarEntry(url);
    InputStream in = currentJar.getInputStream(dbEntry);
    byte[] bs;
    StringBuffer buffer = new StringBuffer();
    int count = 1;
    while (count > 0) {
        bs = new byte[1024];
        count = in.read(bs, 0, 1024);
        buffer.append(new String(bs, "UTF-8"));
    }
    return buffer.toString().trim();
}
Example 35
Project: BingAds-Java-SDK-master  File: URLExtensions.java View source code
public static Map<String, String> parseQueryStringArgs(String input) {
    try {
        final Map<String, String> query_pairs = new LinkedHashMap<String, String>();
        if (input == null || input.length() == 0) {
            return query_pairs;
        }
        final String[] pairs = input.split("&");
        for (String pair : pairs) {
            final int idx = pair.indexOf("=");
            final String key = idx > 0 ? URLDecoder.decode(pair.substring(0, idx), "UTF-8") : pair;
            final String value = idx > 0 && pair.length() > idx + 1 ? URLDecoder.decode(pair.substring(idx + 1), "UTF-8") : null;
            query_pairs.put(key, value);
        }
        return query_pairs;
    } catch (UnsupportedEncodingException e) {
        throw new IllegalArgumentException(e);
    }
}
Example 36
Project: ClassesVersionChecker-master  File: ClassPathUtil.java View source code
@Nullable
public static File getClassFile(@NotNull final Class<?> clazz) throws IOException {
    String path = "/" + clazz.getName().replace('.', '/') + ".class";
    final URL url = clazz.getResource(path);
    if (url == null) {
        return null;
    }
    String urlStr = URLDecoder.decode(url.toExternalForm().replace("+", "%2B"), "UTF-8");
    int startIndex = urlStr.indexOf(':');
    while (startIndex >= 0 && urlStr.charAt(startIndex + 1) != '/') {
        startIndex = urlStr.indexOf(':', startIndex + 1);
    }
    if (startIndex >= 0) {
        urlStr = urlStr.substring(startIndex + 1);
    }
    if (urlStr.startsWith("/") && urlStr.indexOf(":") == 2) {
        urlStr = urlStr.substring(1);
    }
    return new File(urlStr);
}
Example 37
Project: CZD_Android_Lib-master  File: CookieUtil.java View source code
public static Map<String, String> decode(String cookiedata, int encode, String key) {
    Map<String, String> result = new HashMap<String, String>();
    try {
        cookiedata = URLDecoder.decode(cookiedata, "utf-8");
        String decoded = "";
        if (encode == ENCODE_BLOWFISH) {
            decoded = Blowfish.getInstance(key).decrypt(cookiedata);
        } else if (encode == ENCODE_RIJNDAEL) {
            decoded = Rijndael.decrypt(cookiedata, key.getBytes());
        }
        if (decoded != null && !decoded.equals("")) {
            String[] sdecoded = decoded.split("¤");
            for (String string : sdecoded) {
                String[] a = string.split("\\|");
                result.put(a[0], a[1]);
            }
        }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return result;
}
Example 38
Project: deepnighttwo-master  File: PrintChar.java View source code
public static void main(String[] args) throws UnsupportedEncodingException {
    DateFormat format = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, Locale.CHINA);
    System.out.println(format.format(new Date()));
    // ☆★▢▣▤▥▦▧▨▩☬☭☮☯
    char ch = '=';
    System.out.println((int) ch);
    for (int i = -100; i < 100; i++) {
        int sd = ch;
        sd += i;
        char nch = (char) sd;
        System.out.print(nch);
    }
    String str = "asdfasdfasdf%1Sasdf";
    System.out.println(String.format(str, "FFFFFFFFFFFFFFFFFFFFFFFFFFF"));
    System.out.println(URLDecoder.decode(str1, "UTF-8"));
}
Example 39
Project: deltaspike-solder-master  File: OpenIdUsersServlet.java View source code
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String prefix = opBean.get().getUsersUrlPrefix();
    if (!request.getRequestURL().toString().startsWith(prefix)) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND, "Only accepting requests for URLs starting with " + prefix);
        return;
    }
    String userNamePart = request.getRequestURL().substring(prefix.length());
    String userName = URLDecoder.decode(userNamePart, "UTF-8");
    if (providerSpi.get().userExists(userName)) {
        response.setContentType("application/xrds+xml");
        opBean.get().writeClaimedIdentifierXrds(response.getWriter(), opBean.get().getOpLocalIdentifierForUserName(userName));
    } else {
        response.sendError(HttpServletResponse.SC_NOT_FOUND, "User " + userName + " does not exist.");
    }
}
Example 40
Project: extended-objects-master  File: FileDatastoreFactory.java View source code
@Override
public EmbeddedNeo4jDatastore createGraphDatabaseService(URI uri, Properties properties) throws MalformedURLException {
    String path;
    try {
        path = URLDecoder.decode(uri.toURL().getPath(), "UTF-8");
    } catch (UnsupportedEncodingException e) {
        throw new MalformedURLException(e.getMessage());
    }
    GraphDatabaseBuilder databaseBuilder = new GraphDatabaseFactory().newEmbeddedDatabaseBuilder(new File(path));
    Properties neo4jProperties = Neo4jPropertyHelper.getNeo4jProperties(properties);
    for (String name : neo4jProperties.stringPropertyNames()) {
        databaseBuilder.setConfig(name, neo4jProperties.getProperty(name));
    }
    GraphDatabaseService graphDatabaseService = databaseBuilder.newGraphDatabase();
    return new EmbeddedNeo4jDatastore(graphDatabaseService);
}
Example 41
Project: fensy-master  File: ClassUtils.java View source code
/**
     * 扫æ??给定包的所有类
     * 
     * @param packageName
     *            包å??
     * @param recursive
     *            是�递归�包
     * @return
     */
public static Collection<String> getClassNames(String packageName, boolean recursive) {
    String packagePath = packageName.replace('.', File.separatorChar);
    URL url = ClassUtils.class.getClassLoader().getResource(packagePath);
    String path = null;
    try {
        // 处�空格等特殊字符
        path = URLDecoder.decode(url.getPath(), "utf-8");
    } catch (UnsupportedEncodingException e) {
    }
    Collection<File> files = FileUtils.listFiles(new File(path), new String[] { "class" }, recursive);
    Collection<String> classNames = new HashSet<String>();
    for (File file : files) {
        String name = StringUtils.substringAfterLast(file.getPath(), packagePath);
        classNames.add(packageName + StringUtils.substringBeforeLast(name.replace(File.separatorChar, '.'), ".class"));
    }
    return classNames;
}
Example 42
Project: Geekr-master  File: URLTool.java View source code
public static Bundle decodeURL(String arg) {
    Bundle params = new Bundle();
    if (!StringUtils.isNullOrEmpty(arg)) {
        String[] array = arg.split("&");
        for (String str : array) {
            String[] keyValue = str.split("=");
            try {
                params.putString(URLDecoder.decode(keyValue[0], "UTF-8"), URLDecoder.decode(keyValue[1], "UTF-8"));
            } catch (UnsupportedEncodingException e) {
            }
        }
    }
    return params;
}
Example 43
Project: geoserver-2.0.x-master  File: GeneralizationInfosProviderImpl.java View source code
protected URL deriveURLFromSourceObject(Object source) throws IOException {
    if (source == null)
        throw new IOException("Cannot read from null");
    if (source instanceof String) {
        File f = GeoserverDataDirectory.findDataFile((String) source);
        URL url = null;
        if (f.exists()) {
            url = f.toURI().toURL();
        } else {
            url = new URL((String) source);
        }
        url = new URL(URLDecoder.decode(url.toExternalForm(), "UTF8"));
        return url;
    }
    throw new IOException("Cannot read from " + source);
}
Example 44
Project: geoserver-master  File: GeneralizationInfosProviderImpl.java View source code
protected URL deriveURLFromSourceObject(Object source) throws IOException {
    if (source == null) {
        throw new IOException("Cannot read from null");
    }
    if (source instanceof String) {
        String path = (String) source;
        GeoServerResourceLoader loader = GeoServerExtensions.bean(GeoServerResourceLoader.class);
        File f = loader.url(path);
        URL url = null;
        if (f != null && f.exists()) {
            url = f.toURI().toURL();
        } else {
            url = new URL(path);
        }
        url = new URL(URLDecoder.decode(url.toExternalForm(), "UTF8"));
        return url;
    }
    throw new IOException("Cannot read from " + source);
}
Example 45
Project: geoserver-old-master  File: GeneralizationInfosProviderImpl.java View source code
protected URL deriveURLFromSourceObject(Object source) throws IOException {
    if (source == null)
        throw new IOException("Cannot read from null");
    if (source instanceof String) {
        File f = GeoserverDataDirectory.findDataFile((String) source);
        URL url = null;
        if (f.exists()) {
            url = f.toURI().toURL();
        } else {
            url = new URL((String) source);
        }
        url = new URL(URLDecoder.decode(url.toExternalForm(), "UTF8"));
        return url;
    }
    throw new IOException("Cannot read from " + source);
}
Example 46
Project: geoserver_trunk-master  File: GeneralizationInfosProviderImpl.java View source code
protected URL deriveURLFromSourceObject(Object source) throws IOException {
    if (source == null)
        throw new IOException("Cannot read from null");
    if (source instanceof String) {
        File f = GeoserverDataDirectory.findDataFile((String) source);
        URL url = null;
        if (f.exists()) {
            url = f.toURI().toURL();
        } else {
            url = new URL((String) source);
        }
        url = new URL(URLDecoder.decode(url.toExternalForm(), "UTF8"));
        return url;
    }
    throw new IOException("Cannot read from " + source);
}
Example 47
Project: gosu-lang-master  File: ResourceFileResolver.java View source code
public File resolveURLToFile(String fileName, URL url) {
    if (url == null) {
        return null;
    }
    String urlFile = URLDecoder.decode(url.getFile());
    if (urlFile.startsWith("file:/")) {
        // Windows style
        urlFile = urlFile.substring(6, urlFile.length() - fileName.length() - 2);
        if (!new File(urlFile).exists()) {
            // Unix style
            urlFile = url.getFile().substring(5, url.getFile().length() - fileName.length() - 2);
        }
    } else if (urlFile.startsWith("file:")) {
        // Windows style
        urlFile = urlFile.substring(5, urlFile.length() - fileName.length() - 2);
    } else {
        // Windows style
        urlFile = urlFile.substring(1, urlFile.length() - fileName.length());
        if (!new File(urlFile).exists()) {
            // Unix style (e.g. /home/foo/bar/Class.gs)
            urlFile = url.getFile().substring(0, url.getFile().length() - fileName.length());
        }
    }
    return new File(urlFile);
}
Example 48
Project: iMatrix6.0.0Dev-master  File: JarFileUtils.java View source code
/**
	 * 从jar文件中读�文件
	 * @param url 该文件在jar中的路径
	 * @return 文件内容
	 */
public static <T> String readFile(Class<T> clazz, String url) throws Exception {
    String currentJarPath = URLDecoder.decode(clazz.getProtectionDomain().getCodeSource().getLocation().getFile(), "UTF-8");
    JarFile currentJar = new JarFile(currentJarPath);
    JarEntry dbEntry = currentJar.getJarEntry(url);
    InputStream in = currentJar.getInputStream(dbEntry);
    byte[] bs;
    StringBuffer buffer = new StringBuffer();
    int count = 1;
    while (count > 0) {
        bs = new byte[1024];
        count = in.read(bs, 0, 1024);
        buffer.append(new String(bs, "UTF-8"));
    }
    return buffer.toString().trim();
}
Example 49
Project: inspectIT-master  File: UrlEncodingPropagator.java View source code
/**
	 * {@inheritDoc}
	 */
@Override
protected Iterable<Entry<String, String>> extractBaggage(TextMap carrier) {
    if ((null == carrier) || (null == carrier.iterator())) {
        return null;
    }
    Map<String, String> map = new HashMap<String, String>();
    for (Entry<String, String> entry : carrier) {
        try {
            map.put(entry.getKey(), URLDecoder.decode(entry.getValue(), UTF_8));
        } catch (UnsupportedEncodingException e) {
            map.put(entry.getKey(), entry.getValue());
        }
    }
    return map.entrySet();
}
Example 50
Project: ishacrmserver-master  File: MandrillWebhookServlet.java View source code
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    Logger logger = Logger.getLogger(MandrillWebhookServlet.class.getName());
    try {
        resp.setContentType("text/plain");
        StringBuilder builder = new StringBuilder();
        String line = null;
        BufferedReader reader = req.getReader();
        while ((line = reader.readLine()) != null) builder.append(line);
        String postData = URLDecoder.decode(builder.toString(), "UTF-8");
        logger.info("post data: [" + postData + "]");
        Mail.processWebhookEvents(postData);
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "Exception occured", ex);
    }
}
Example 51
Project: jedit_cc4401-master  File: TestUtils.java View source code
/**
     * @param class1
     * @return
     */
public static File findSourceForClass(final Class<?> clazz) throws IOException {
    //find this source file
    //get class file
    final String className = clazz.getName();
    final URL location = clazz.getProtectionDomain().getCodeSource().getLocation();
    final File file = new File(URLDecoder.decode(location.getFile(), System.getProperty("file.encoding")));
    //find project root.
    String root = null;
    File current = file;
    while (current != null) {
        if (current.isDirectory() && new File(current, "pom.xml").exists()) {
            root = current.getAbsolutePath();
            break;
        }
        current = current.getParentFile();
    }
    final String relativePath = className.replace('.', File.separatorChar) + ".java";
    return findByRelativePath(new File(root), relativePath);
}
Example 52
Project: jubula.core-master  File: URLDecode.java View source code
@Override
public String evaluate(String[] arguments) throws InvalidDataException {
    try {
        validateParamCount(arguments, 1);
        String string = arguments[0];
        //$NON-NLS-1$
        return URLDecoder.decode(string, "UTF-8");
    } catch (IllegalArgumentExceptionUnsupportedEncodingException |  e) {
        throw new InvalidDataException(e.getLocalizedMessage(), MessageIDs.E_FUNCTION_EVAL_ERROR);
    }
}
Example 53
Project: kickmaterial-master  File: QueryParamsExtractor.java View source code
public static Map<String, String> splitQuery(URL url) throws UnsupportedEncodingException {
    Map<String, String> queryPairs = new LinkedHashMap<>();
    String query = url.getQuery();
    String[] pairs = query.split("&");
    String charsetName = "UTF-8";
    for (String pair : pairs) {
        int idx = pair.indexOf("=");
        String key = URLDecoder.decode(pair.substring(0, idx), charsetName);
        String value = URLDecoder.decode(pair.substring(idx + 1), charsetName);
        queryPairs.put(key, value);
    }
    return queryPairs;
}
Example 54
Project: mdrill-master  File: ColsDefine.java View source code
public static String decodeString(String args) {
    try {
        return new String(java.net.URLDecoder.decode(args, "UTF-8").getBytes("UTF-8"), "UTF-8");
    } catch (Throwable e) {
        try {
            return new String(java.net.URLDecoder.decode(args, "GBK").getBytes("UTF-8"), "UTF-8");
        } catch (Throwable e2) {
            return args;
        }
    }
}
Example 55
Project: multimedia-geotagging-master  File: TextUtil.java View source code
public static Set<String> parse(String text, Set<String> terms) {
    if ((text != null) || (text != "")) {
        try {
            text = URLDecoder.decode(text, "UTF-8");
            text = deAccent(text);
            // removes redundant white spaces
            text = text.trim();
            text = text.replaceAll("[\\p{Punct}&&[^\\,]]", "");
            text = text.replaceAll("[0-9]+", "");
            text = text.toLowerCase();
            text = text.replaceAll("\\s{2,}", " ");
            text = text.replaceAll("\\,{2,}", ",");
            text = text.trim();
            for (String term : text.split(",")) {
                if (!term.replaceAll(" ", "").matches("[0-9]+") && !term.isEmpty()) {
                    terms.add(term.trim());
                    for (String interm : term.split(" ")) {
                        if (!interm.matches("[0-9]+")) {
                            terms.add(interm);
                        }
                    }
                }
            }
        } catch (UnsupportedEncodingException exception) {
        } catch (IllegalArgumentException exception) {
        }
    }
    return terms;
}
Example 56
Project: openwayback-master  File: UriTranscoder.java View source code
@Override
public String process(final String uriAsString) {
    Matcher m = getMatcher(uriAsString);
    StringBuilder result = new StringBuilder(uriAsString);
    while (m.find()) {
        int start = m.start(1);
        int end = m.end(1);
        try {
            String decodedGroup = URLDecoder.decode(uriAsString.substring(start, end), getSourceEncoding());
            result.replace(start, end, URLEncoder.encode(decodedGroup, getTargetEncoding()));
        } catch (UnsupportedEncodingException e) {
            LOGGER.log(Level.SEVERE, e.getLocalizedMessage(), e);
        }
    }
    return result.toString();
}
Example 57
Project: passrepo-master  File: QueryStringParser.java View source code
private String getValue() {
    if (paramValue == null) {
        if (paramNameEnd == paramEnd) {
            return null;
        }
        try {
            paramValue = URLDecoder.decode(queryString.substring(paramNameEnd + 1, paramEnd));
        } catch (Exception ex) {
            throw new Error(ex);
        }
    }
    return paramValue;
}
Example 58
Project: PayPal-Java-SDK-master  File: NVPUtil.java View source code
/**
	 * Utility method used to decode the nvp response String
	 * 
	 * @param nvpString
	 * @return Map
	 * @throws UnsupportedEncodingException
	 */
public static Map<String, String> decode(String nvpString) throws UnsupportedEncodingException {
    String[] nmValPairs = nvpString.split("&");
    Map<String, String> response = new HashMap<String, String>();
    // parse the string and load into the object
    for (String nmVal : nmValPairs) {
        String[] field = nmVal.split("=");
        response.put(URLDecoder.decode(field[0], Constants.ENCODING_FORMAT), (field.length > 1) ? URLDecoder.decode(field[1].trim(), Constants.ENCODING_FORMAT) : "");
    }
    return response;
}
Example 59
Project: Photato-master  File: PathHelper.java View source code
public static Tuple<String, Map<String, String>> splitPathAndQuery(String pathAndQuery) {
    String path;
    String query;
    int p = pathAndQuery.indexOf("?");
    if (p == -1) {
        path = pathAndQuery;
        query = null;
    } else {
        path = pathAndQuery.substring(0, p);
        query = pathAndQuery.substring(p + 1);
    }
    while (path.startsWith("/")) {
        path = path.substring(1);
    }
    try {
        return new Tuple<>(URLDecoder.decode(path, "UTF-8"), PathHelper.splitQuery(query));
    } catch (UnsupportedEncodingException ex) {
        return null;
    }
}
Example 60
Project: polly-master  File: ShipType.java View source code
public static ShipType byPrefix(String shipName) {
    try {
        //$NON-NLS-1$
        shipName = URLDecoder.decode(shipName, "ISO-8859-1");
    } catch (UnsupportedEncodingException e) {
        return UNKNOWN;
    }
    // HACK: Evilest encoding hack of all times
    if (shipName.startsWith("bäähhhh")) {
        //$NON-NLS-1$
        return KREUZER;
    } else if (shipName.contains("bäähhhh")) {
        //$NON-NLS-1$
        return SCHLACHTKREUZER;
    } else if (shipName.startsWith("Zerst")) {
        //$NON-NLS-1$
        return ZERRI;
    }
    for (final ShipType st : ShipType.values()) {
        if (shipName.startsWith(st.name)) {
            return st;
        }
    }
    return UNKNOWN;
}
Example 61
Project: quick-junit-master  File: MockitoEntry.java View source code
public IPath getPath() {
    Bundle bundle = Platform.getBundle("org.mockito");
    URL entry = bundle.getEntry("mockito.jar");
    String fileURL = null;
    try {
        fileURL = URLDecoder.decode(FileLocator.toFileURL(entry).getFile(), "UTF-8");
    } catch (IOException e) {
    }
    return new Path(fileURL);
}
Example 62
Project: sdk-core-java-master  File: NVPUtil.java View source code
/**
	 * Utility method used to decode the nvp response String
	 * 
	 * @param nvpString
	 * @return Map
	 * @throws UnsupportedEncodingException
	 */
public static Map<String, String> decode(String nvpString) throws UnsupportedEncodingException {
    String[] nmValPairs = nvpString.split("&");
    Map<String, String> response = new HashMap<String, String>();
    // parse the string and load into the object
    for (String nmVal : nmValPairs) {
        String[] field = nmVal.split("=");
        response.put(URLDecoder.decode(field[0], Constants.ENCODING_FORMAT), (field.length > 1) ? URLDecoder.decode(field[1].trim(), Constants.ENCODING_FORMAT) : "");
    }
    return response;
}
Example 63
Project: servlet-safety-master  File: UriFragmentNormalizer.java View source code
@Override
public String normalize(String fragment) throws ValidationException {
    try {
        String lastDecoded = fragment;
        for (int i = MAX_DECODE_DEPTH; i >= 0; i--) {
            final String decoded = URLDecoder.decode(lastDecoded, DEFAULT_CHARSET);
            if (decoded.indexOf(REPLACEMENT_CHARACTER) != -1) {
                throw new ValidationException(fragment, "cannot contain invalid UTF-8 codepoints");
            }
            if (lastDecoded.equals(decoded)) {
                return URLEncoder.encode(lastDecoded, DEFAULT_CHARSET);
            }
            lastDecoded = decoded;
        }
        throw new ValidationException(fragment, "was encoded " + MAX_DECODE_DEPTH + " or more times");
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    } catch (IllegalArgumentException e) {
        throw new ValidationException(fragment, "had un-decodable characters");
    }
}
Example 64
Project: toobs-master  File: AjaxURLFragment.java View source code
/**
     * Generates a URL string to go in an HTML image map.
     *
     * @param urlText  the URL.
     * 
     * @return The formatted text
     */
public String generateURLFragment(String urlText) {
    String decoded;
    String category = "";
    String baseChart = "";
    String chartMod = "";
    String chartParams = "";
    try {
        decoded = URLDecoder.decode(urlText, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        decoded = urlText;
    }
    int catIdx = decoded.indexOf("category=");
    if (catIdx != -1) {
        category = decoded.substring(catIdx + 9);
    }
    String[] split = urlText.split("\\?");
    int spIdx = split[0].indexOf("SinglePlot");
    if (spIdx != -1) {
        chartMod = "SinglePlot";
    } else {
        spIdx = split[0].indexOf(".xchart");
    }
    baseChart = split[0].substring(0, spIdx);
    if (split.length > 1) {
        chartParams = split[1];
    }
    return " href=\"javascript:void(0)\" baseChart=\"" + baseChart + "\" chartMod=\"" + chartMod + "\" params=\"" + chartParams + "\" class=\"ajaxMapArea\" category=\"" + category + "\"";
}
Example 65
Project: wheelmap-android-master  File: POIPermaLinkMapActivity.java View source code
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    String uri = this.getIntent().getDataString();
    String[] uriArray = uri.split("\\?");
    uri = uriArray[0];
    String uriAdress = uriArray[1];
    WheelmapApp app = (WheelmapApp) getApplication();
    uriArray = uri.split(":");
    uri = uriArray[1];
    uriArray = uri.split(",");
    double lat = Double.parseDouble(uriArray[0]);
    double lon = Double.parseDouble(uriArray[1]);
    app.setGeoLat(lat);
    app.setGeoLon(lon);
    uriArray = uriAdress.split("=");
    uriAdress = uriArray[1];
    uri = uriAdress.replaceAll("\\+", " ");
    String result = null;
    try {
        result = java.net.URLDecoder.decode(uri, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    app.setAddressString(result);
    startActivity(new Intent(this, StartupActivity.class));
}
Example 66
Project: wicket-master  File: UrlDecoder.java View source code
/**
	 * @param s
	 *            string to decode
	 * @param enc
	 *            encoding to decode with
	 * @return decoded string
	 * @see java.net.URLDecoder#decode(String, String)
	 */
public String decode(final String s, final String enc) {
    if (Strings.isEmpty(s)) {
        return s;
    }
    int numChars = s.length();
    StringBuilder sb = new StringBuilder(numChars > 500 ? numChars / 2 : numChars);
    int i = 0;
    if (enc.length() == 0) {
        throw new RuntimeException(new UnsupportedEncodingException("URLDecoder: empty string enc parameter"));
    }
    char c;
    byte[] bytes = null;
    while (i < numChars) {
        c = s.charAt(i);
        switch(c) {
            case '+':
                sb.append(decodePlus ? ' ' : '+');
                i++;
                break;
            case '%':
                /*
					 * Starting with this instance of %, process all consecutive substrings of the
					 * form %xy. Each substring %xy will yield a byte. Convert all consecutive bytes
					 * obtained this way to whatever character(s) they represent in the provided
					 * encoding.
					 */
                try {
                    // of remaining bytes
                    if (bytes == null) {
                        bytes = new byte[(numChars - i) / 3];
                    }
                    int pos = 0;
                    while (((i + 2) < numChars) && (c == '%')) {
                        bytes[pos++] = (byte) Integer.parseInt(s.substring(i + 1, i + 3), 16);
                        i += 3;
                        if (i < numChars) {
                            c = s.charAt(i);
                        }
                    }
                    // "%x" will cause an exception to be thrown
                    if ((i < numChars) && (c == '%')) {
                        LOG.info("Incomplete trailing escape (%) pattern in '%s'. The escape character (%) will be ignored.", s);
                        i++;
                        break;
                    }
                    try {
                        sb.append(new String(bytes, 0, pos, enc));
                    } catch (UnsupportedEncodingException e) {
                        throw new RuntimeException(e);
                    }
                } catch (NumberFormatException e) {
                    LOG.info("Illegal hex characters in escape (%) pattern in '{}'. " + "The escape character (%) will be ignored. NumberFormatException: {} ", s, e.getMessage());
                    i++;
                }
                break;
            default:
                sb.append(c);
                i++;
                break;
        }
    }
    // that way none will come through
    return sb.toString().replace("\0", "NULL");
}
Example 67
Project: Xtest-master  File: BodyImplCustom.java View source code
/**
     * Returns the file name of this test
     * 
     * @return The file name of this test
     */
public String getFileName() {
    Resource eResource = eResource();
    String result = "File name unknown";
    if (eResource != null) {
        URI uri = eResource.getURI();
        try {
            result = URLDecoder.decode(uri.lastSegment(), "UTF-8");
        } catch (UnsupportedEncodingException e) {
        }
    }
    return result;
}
Example 68
Project: iaf-master  File: ShowFlowDiagram.java View source code
private String doGet(IPipeLineSession session) throws PipeRunException {
    String adapterName = null;
    String uri = (String) session.get("uri");
    if (StringUtils.isNotEmpty(uri)) {
        String[] split = uri.split("/");
        if (split.length > 2) {
            adapterName = split[2];
        }
    }
    File flowFile;
    if (StringUtils.isNotEmpty(adapterName)) {
        String adapterFileName = FileUtils.encodeFileName(java.net.URLDecoder.decode(adapterName)) + ".svg";
        flowFile = new File(adapterFlowDir, adapterFileName);
    } else {
        String configurationName = (String) session.get("configuration");
        if (StringUtils.isEmpty(configurationName) || configurationName.equalsIgnoreCase("*ALL*")) {
            String configFileName = "_ALL_.svg";
            flowFile = new File(configFlowDir, configFileName);
        } else {
            String configFileName = FileUtils.encodeFileName(java.net.URLDecoder.decode(configurationName)) + ".svg";
            flowFile = new File(configFlowDir, configFileName);
        }
    }
    if (flowFile.exists()) {
        return flowFile.getPath();
    } else {
        return null;
    }
}
Example 69
Project: XR3Player-master  File: Downloader.java View source code
/**
     * Main Method
     * 
     * @param args
     */
public static void main(String[] args) {
    System.out.println("Extension is :" + InfoTool.getFileExtension("http://i12.photobucket.com/albums/a206/zxc6/1_zps3e6rjofn.jpg"));
    String result = null;
    try {
        result = java.net.URLDecoder.decode("https://t2.kn3.net/taringa/1/6/4/4/2/2/STEELMAX/176x132_22A.jpg", "UTF-8");
        System.out.println(result);
    } catch (UnsupportedEncodingException ex) {
        ex.printStackTrace();
    }
    URL dl = null;
    File fl = null;
    String x = null;
    OutputStream os = null;
    InputStream is = null;
    ProgressListener progressListener = new ProgressListener();
    try {
        fl = new File(System.getProperty("user.home").replace("\\", "/") + "/Desktop/image.zip");
        dl = new URL(java.net.URLDecoder.decode("https://sourceforge.net/projects/xr3player/files/XR3Player%20Update%2043.zip/download", "UTF-8"));
        os = new FileOutputStream(fl);
        is = dl.openStream();
        // http://i12.photobucket.com/albums/a206/zxc6/1_zps3e6rjofn.jpg
        // System.out.println("Extension is
        // :"+InfoTool.getFileExtension("http://i12.photobucket.com/albums/a206/zxc6/1_zps3e6rjofn.jpg"));
        DownloadProgressListener dcount = new DownloadProgressListener(os);
        dcount.setListener(progressListener);
        URLConnection connection = dl.openConnection();
        // this line give you the total length of source stream as a String.
        // you may want to convert to integer and store this value to
        // calculate percentage of the progression.
        System.out.println("Content Length:" + connection.getHeaderField("Content-Length"));
        System.out.println("Content Length with different way:" + connection.getContentType());
        System.out.println("\n");
        // begin transfer by writing to dcount, not os.
        IOUtils.copy(is, dcount);
    } catch (Exception e) {
        System.out.println(e);
    } finally {
        IOUtils.closeQuietly(os);
        IOUtils.closeQuietly(is);
    }
}
Example 70
Project: galeb2-router-master  File: GetMatcherHandler.java View source code
/* (non-Javadoc)
     * @see org.vertx.java.core.Handler#handle(java.lang.Object)
     */
@Override
public void handle(HttpServerRequest req) {
    final ServerResponse serverResponse = new ServerResponse(req).setLog(log);
    ManagerService managerService = new ManagerService(classId, log).setRequest(req).setResponse(serverResponse);
    if (httpServerName == null) {
        httpServerName = req.headers().contains(HttpHeaders.HOST) ? req.headers().get(HttpHeaders.HOST) : "SERVER";
        Server.setHttpServerName(httpServerName);
    }
    if (!managerService.checkUriOk()) {
        return;
    }
    String uriBase = "";
    String id = "";
    String message = "";
    if (req.params() != null) {
        uriBase = req.params().contains("param0") ? req.params().get("param0") : "";
        id = req.params().contains("param1") ? req.params().get("param1") : "";
    }
    try {
        uriBase = java.net.URLDecoder.decode(uriBase, "UTF-8");
        id = java.net.URLDecoder.decode(id, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        serverResponse.setStatusCode(HttpCode.BAD_REQUEST).setId(id).endResponse();
        log.error("Unsupported Encoding");
        return;
    }
    switch(uriBase) {
        case "version":
            message = new JsonObject().putNumber("version", farm.getVersion()).encodePrettily();
            break;
        case "farm":
            message = farm.toJson().encodePrettily();
            break;
        case "virtualhost":
            message = farm.getVirtualhostJson(id);
            break;
        case "backend":
            message = farm.getBackendJson(id);
            break;
        case "backendpool":
            message = farm.getBackendPoolJson(id);
            break;
        case "rule":
            message = farm.getRuleJson(id);
            break;
        default:
            message = "";
            break;
    }
    int statusCode = HttpCode.OK;
    if ("".equals(message) || "{}".equals(message) || "[ ]".equals(message)) {
        statusCode = HttpCode.NOT_FOUND;
        message = HttpCode.getMessage(statusCode, true);
    }
    serverResponse.setStatusCode(statusCode).setMessage(message).setId(id).endResponse();
    log.info(String.format("GET /%s", uriBase));
}
Example 71
Project: geode-master  File: UriUtils.java View source code
/**
   * Decodes the encoded String value using the specified encoding (such as UTF-8). It is assumed
   * the String value was encoded with the URLEncoder using the specified encoding. This method
   * handles UnsupportedEncodingException by just returning the encodedValue. Since it is possible
   * for a String value to have been encoded multiple times, the String value is decoded until the
   * value stops changing (in other words, until the value is completely decoded).
   * <p/>
   * 
   * @param encodedValue the encoded String value to decode.
   * @param encoding a String value specifying the encoding.
   * @return the decoded value of the String. If the encoding is unsupported, then the encodedValue
   *         is returned.
   * @see java.net.URLDecoder
   */
public static String decode(String encodedValue, final String encoding) {
    try {
        if (encodedValue != null) {
            String previousEncodedValue;
            do {
                previousEncodedValue = encodedValue;
                encodedValue = URLDecoder.decode(encodedValue, encoding);
            } while (!encodedValue.equals(previousEncodedValue));
        }
        return encodedValue;
    } catch (UnsupportedEncodingException ignore) {
        return encodedValue;
    }
}
Example 72
Project: VUE-master  File: Utilities.java View source code
public static String expectedValue(org.w3c.dom.Element element, String tag) throws org.xml.sax.SAXParseException {
    String expected = null;
    org.w3c.dom.NodeList nameNodeList = element.getElementsByTagName(tag);
    int numNodes = nameNodeList.getLength();
    if (numNodes > 0) {
        org.w3c.dom.Element e = (org.w3c.dom.Element) nameNodeList.item(0);
        try {
            expected = e.getFirstChild().getNodeValue();
            //System.out.println("before decode " + expected + " after " + java.net.URLDecoder.decode(expected,"ISO-8859-1"));
            expected = java.net.URLDecoder.decode(expected, "ISO-8859-1");
        } catch (Exception ex) {
        }
    }
    return expected;
}
Example 73
Project: WebDAVForDomino-master  File: MOVE.java View source code
/**
	 * (non-Javadoc)
	 * 
	 * @see biz.taoconsulting.dominodav.methods.AbstractDAVMethod#action()
	 */
protected void action() {
    // check if locked - locked files / foldes should not be moved... (???)
    // TODO fix the path mess
    IDAVRepository rep = this.getRepository();
    // Resource-Path is stripped by the repository name!
    // String curPath = (String)
    // this.getHeaderValues().get("resource-path");
    // uri is the unique identifier on the host includes servlet and
    // repository but not server
    String curURI = (String) this.getHeaderValues().get("uri");
    LockManager lm = this.getLockManager();
    IDAVResource resource;
    String des = (String) this.getReq().getHeader("Destination");
    // ""), "");
    try {
        curURI = java.net.URLDecoder.decode(curURI, "UTF-8");
        des = java.net.URLDecoder.decode(des, "UTF-8");
    } catch (Exception e) {
    }
    LOGGER.info("DESTINATION ADDRESS=" + des);
    try {
        resource = rep.getResource(curURI);
        if (lm.isLocked(resource)) {
            this.setHTTPStatus(423);
            return;
        } else {
            if (resource.isReadOnly()) {
                this.setHTTPStatus(HttpServletResponse.SC_FORBIDDEN);
            } else {
                this.setHTTPStatus(rep.moveResource(curURI, des));
                return;
            }
        }
    } catch (DAVNotFoundException e) {
        this.setErrorMessage("Resource not found" + curURI, 404);
        return;
    }
}
Example 74
Project: AcademicTorrents-Downloader-master  File: ExternalLoginCookieListener.java View source code
public void changed(StatusTextEvent event) {
    if (event.text.startsWith(AZCOOKIEMSG)) {
        String uriEncodedCookies = event.text.substring(AZCOOKIEMSG.length());
        try {
            String cookies = URLDecoder.decode(uriEncodedCookies, "UTF-8");
            if (listener != null) {
                listener.cookiesFound(cookies);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Example 75
Project: accumulo-recipes-master  File: UriUtils.java View source code
public static Multimap<String, String> splitQuery(String query) throws UnsupportedEncodingException {
    Multimap<String, String> query_pairs = LinkedListMultimap.create();
    String[] pairs = query.split("&");
    for (String pair : pairs) {
        int idx = pair.indexOf("=");
        query_pairs.put(URLDecoder.decode(pair.substring(0, idx), "UTF-8"), URLDecoder.decode(pair.substring(idx + 1), "UTF-8"));
    }
    return query_pairs;
}
Example 76
Project: ache-master  File: BuildModelTest.java View source code
private Page readOnePageFromFolder(String positiveFolder) throws Exception {
    File[] allPositivePages = (new File(positiveFolder)).listFiles();
    assertThat(allPositivePages.length, is(6));
    String positiveFileName = allPositivePages[0].getName();
    String fileContent = new String(Files.readAllBytes(Paths.get(allPositivePages[0].getAbsolutePath())));
    Page samplePositivePage = new Page(new URL(URLDecoder.decode(positiveFileName, "UTF-8")), fileContent);
    return samplePositivePage;
}
Example 77
Project: AIDR-master  File: UserAccountRepositoryImpl.java View source code
@Override
public List<UserAccount> getUsers(String query, Integer start, Integer limit) {
    Criteria criteria = getHibernateTemplate().getSessionFactory().getCurrentSession().createCriteria(UserAccount.class);
    if (StringUtils.hasText(query)) {
        String wildcard = '%' + URLDecoder.decode(query.trim()) + '%';
        criteria.add(Restrictions.ilike("userName", wildcard));
    }
    if (start != null) {
        criteria.setFirstResult(start);
    }
    if (limit != null) {
        criteria.setMaxResults(limit);
    }
    return (List<UserAccount>) criteria.list();
}
Example 78
Project: Ak47-master  File: HttpUtil.java View source code
/**
     * Convert body of HTTP to {@code Map<String, String>}, such as:
     * 
     *  {@code wd=&zxmode=1&json=1&p=3&bs=test%20ak47   ===>}   
     *                            Map {
     *                                wd: ""
     *                                zxmode: "1"
     *                                json: "1"
     *                                p: "3"
     *                                bs: "test ak47"
     *                            }
     * 
     * 将Http的body转化为Map
     * 
     * @param body string of http body
     * @return map of http body
     * @throws UnsupportedEncodingException 
     */
public static Map<String, String> body2Map(String body) throws UnsupportedEncodingException {
    Map<String, String> bodyMap = new HashMap<String, String>();
    String[] nvs = body.split("&");
    for (String nv : nvs) {
        if (nv.length() > 0) {
            String[] ns = nv.split("=", 2);
            if (ns.length == 2) {
                String name = ns[0];
                String value = URLDecoder.decode(ns[1], Ak47Constants.DEFAULT_ENCODING);
                if (name.length() > 0) {
                    bodyMap.put(name, value);
                }
            }
        }
    }
    return bodyMap;
}
Example 79
Project: aliyun-odps-java-sdk-master  File: PipeCombiner.java View source code
@Override
String getPipeCommand(JobConf job) {
    String str = job.get("stream.combine.streamprocessor");
    try {
        if (str != null) {
            return URLDecoder.decode(str, "UTF-8");
        }
    } catch (UnsupportedEncodingException e) {
        System.err.println("stream.combine.streamprocessor" + " in jobconf not found");
    }
    return null;
}
Example 80
Project: aluesarjat-master  File: LogAnalysis.java View source code
public static void main(String[] args) throws IOException {
    LineIterator lines = FileUtils.lineIterator(new File("doc/alllogs"));
    Map<String, MutableInt> queries = new HashMap<String, MutableInt>();
    //        Set<String> uniqueQueries = new HashSet<String>();
    while (lines.hasNext()) {
        String line = lines.nextLine();
        if (line.contains("/sparql?")) {
            // strip start
            line = line.substring(line.indexOf("query=") + 6);
            // strip end
            if (line.contains("HTTP/1.1")) {
                line = line.substring(0, line.indexOf("HTTP/1.1") - 1);
            }
            // url decode
            line = URLDecoder.decode(line, "UTF-8");
            // strip extra parameters
            if (line.contains("&")) {
                line = line.substring(0, line.indexOf("&"));
            }
            // remove PREFIX lines
            line = line.replaceAll("PREFIX[^\n]+\n", "").replaceAll("&type=json", "");
            MutableInt counter = queries.get(line);
            if (counter == null) {
                counter = new MutableInt(0);
                queries.put(line, counter);
            }
            counter.increment();
        }
    }
    lines.close();
    // print results
    for (Map.Entry<String, MutableInt> entry : queries.entrySet()) {
        System.out.println(entry.getKey());
        System.out.println("executed : " + entry.getValue() + " times");
        System.out.println();
    }
}
Example 81
Project: Android-Funny-Feed-master  File: ByteArrayHttpClient.java View source code
public static byte[] get(final String urlString) {
    InputStream in = null;
    try {
        final String decodedUrl = URLDecoder.decode(urlString, "UTF-8");
        final URL url = new URL(decodedUrl);
        final Request request = new Request.Builder().url(url).build();
        final Response response = client.newCall(request).execute();
        in = response.body().byteStream();
        return IOUtils.toByteArray(in);
    } catch (final MalformedURLException e) {
        Log.d(TAG, "Malformed URL", e);
    } catch (final OutOfMemoryError e) {
        Log.d(TAG, "Out of memory", e);
    } catch (final UnsupportedEncodingException e) {
        Log.d(TAG, "Unsupported encoding", e);
    } catch (final IOException e) {
        Log.d(TAG, "IO exception", e);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (final IOException ignored) {
            }
        }
    }
    return null;
}
Example 82
Project: Android-Templates-And-Utilities-master  File: GcmIntentService.java View source code
@Override
protected void onHandleIntent(Intent intent) {
    Logcat.d("received message " + intent.getExtras());
    // get message type
    GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
    String messageType = gcm.getMessageType(intent);
    // handle messages
    Bundle extras = intent.getExtras();
    if (!extras.isEmpty()) {
        if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
            Logcat.d("send error " + extras.toString());
        } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
            Logcat.d("deleted messages on server " + extras.toString());
        } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
            Logcat.d("received " + extras.toString());
            // get type
            String type = intent.getStringExtra("type");
            if (type != null) {
                if (type.equals("message")) {
                    try {
                        // decode
                        String text = intent.getStringExtra("text");
                        if (text != null)
                            text = URLDecoder.decode(text, "UTF-8");
                    // TODO
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    // release the wake lock provided by the WakefulBroadcastReceiver
    GcmBroadcastReceiver.completeWakefulIntent(intent);
}
Example 83
Project: androidwisprclient-master  File: HTTPLogger.java View source code
protected Map<String, String> parseUrl(String url) throws MalformedURLException {
    Log.d(TAG, "url to parse:" + url);
    Map<String, String> res = new HashMap<String, String>();
    String query = new URL(url).getQuery();
    String[] params = query.split("&");
    for (String param : params) {
        String[] split = param.split("=");
        res.put(split[0], URLDecoder.decode(split[1]));
    }
    return res;
}
Example 84
Project: api-client-java-master  File: UtilsTest.java View source code
public static Map<String, String> parseQuery(String query) throws IOException {
    Map<String, String> map = new HashMap<String, String>();
    String[] entries = query.split("&");
    for (String entry : entries) {
        String[] sides = entry.split("=");
        if (sides.length != 2) {
            throw new IOException("Invalid Query String");
        }
        String key = URLDecoder.decode(sides[0], "UTF-8");
        String value = URLDecoder.decode(sides[1], "UTF-8");
        map.put(key, value);
    }
    return map;
}
Example 85
Project: apt-maven-plugin-master  File: ClassPathUtils.java View source code
public static List<String> getClassPath(URLClassLoader cl) {
    try {
        List<String> paths = new ArrayList<String>();
        if (cl.getURLs().length == 1 && cl.getURLs()[0].getPath().contains("surefirebooter")) {
            // extract MANIFEST.MF Class-Path entry, since the Java Compiler doesn't handle
            // manifest only jars in the classpath correctly
            URL url = cl.findResource("META-INF/MANIFEST.MF");
            Manifest manifest = new Manifest(url.openStream());
            String classpath = (String) manifest.getMainAttributes().getValue("Class-Path");
            for (String entry : classpath.split(" ")) {
                URL entryUrl = new URL(entry);
                String decodedPath = URLDecoder.decode(entryUrl.getPath(), "UTF-8");
                paths.add(new File(decodedPath).getAbsolutePath());
            }
        } else {
            for (URL url : cl.getURLs()) {
                String decodedPath = URLDecoder.decode(url.getPath(), "UTF-8");
                paths.add(new File(decodedPath).getAbsolutePath());
            }
        }
        return paths;
    } catch (UnsupportedEncodingException e) {
        throw new CodegenException(e);
    } catch (IOException e) {
        throw new CodegenException(e);
    }
}
Example 86
Project: archive-commons-master  File: URLParserTest.java View source code
public void testParse() throws URIException, UnsupportedEncodingException {
    System.out.format("O(%s) E(%s)\n", "%66", URLDecoder.decode("%66", "UTF-8"));
    dumpParse("http://www.archive.org/index.html#foo");
    dumpParse("http://www.archive.org/");
    dumpParse("http://www.archive.org");
    dumpParse("http://www.archive.org?");
    dumpParse("http://www.archive.org:8080/index.html?query#foo");
    dumpParse("http://www.archive.org:8080/index.html?#foo");
    dumpParse("http://www.archive.org:8080?#foo");
    dumpParse("http://bŸcher.ch:8080?#foo");
    dumpParse("dns:bŸcher.ch");
}
Example 87
Project: basic-algorithm-operations-master  File: URLEncDecTest.java View source code
public void testEncode() throws Exception {
    String orig, encoded, decoded;
    for (int i = 0; i < encoding.length; i++) {
        System.out.println("\nEncoding: " + encoding[i]);
        for (int j = 0; j < data.length; j++) {
            orig = data[j];
            encoded = URLEncoder.encode(orig, encoding[i]);
            System.out.println(encoded);
            decoded = URLDecoder.decode(encoded, encoding[i]);
            assertTrue(decoded.equals(orig));
        }
    }
}
Example 88
Project: bbs.newgxu.cn-master  File: UploadItemsAction.java View source code
public String searchUploadItems() throws Exception {
    MessageList m = new MessageList();
    model.getPagination().setActionName(getActionName());
    model.getPagination().setParamMap(getParameterMap());
    System.out.println(URLDecoder.decode(model.getNick(), "UTF-8"));
    System.out.println(model.getPagination().getRequestString());
    try {
        userService.searchUserUploadItems(model);
        return SUCCESS;
    } catch (BBSException e) {
        m.addMessage(e.getMessage());
        Util.putMessageList(m, getSession());
        return ERROR;
    }
}
Example 89
Project: bigpetstore-master  File: PipeCombiner.java View source code
String getPipeCommand(JobConf job) {
    String str = job.get("stream.combine.streamprocessor");
    try {
        if (str != null) {
            return URLDecoder.decode(str, "UTF-8");
        }
    } catch (UnsupportedEncodingException e) {
        System.err.println("stream.combine.streamprocessor" + " in jobconf not found");
    }
    return null;
}
Example 90
Project: BitMate-master  File: ExternalLoginCookieListener.java View source code
public void changed(StatusTextEvent event) {
    if (event.text.startsWith(AZCOOKIEMSG)) {
        String uriEncodedCookies = event.text.substring(AZCOOKIEMSG.length());
        try {
            String cookies = URLDecoder.decode(uriEncodedCookies, "UTF-8");
            if (listener != null) {
                listener.cookiesFound(cookies);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Example 91
Project: BitTorrentApp-master  File: URLUtils.java View source code
public static Map<String, String> splitQuery(String query) throws UnsupportedEncodingException {
    Map<String, String> query_pairs = new LinkedHashMap<String, String>();
    String[] pairs = query.split("&");
    for (String pair : pairs) {
        int idx = pair.indexOf("=");
        query_pairs.put(URLDecoder.decode(pair.substring(0, idx), "UTF-8"), URLDecoder.decode(pair.substring(idx + 1), "UTF-8"));
    }
    return query_pairs;
}
Example 92
Project: BlinkCoder-master  File: UserHandler.java View source code
@Override
public void handle(String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled) {
    // 动�生�的sitemap.xml和rss的xml
    if (target.contains(".") && !target.endsWith(".xml")) {
        return;
    }
    Cookie[] cookies = request.getCookies();
    if (ArrayUtils.isNotEmpty(cookies)) {
        for (Cookie cookie : cookies) {
            if ("blinkcoder".equals(cookie.getName())) {
                String loginKey = cookie.getValue();
                String key = null;
                try {
                    key = new String(DesKit.decrypt(Base64.decodeBase64(URLDecoder.decode(loginKey, "UTF-8").getBytes()), myConstants.COOKIE_ENCRYPT_KEY));
                } catch (Exception e) {
                    key = null;
                }
                if (StringUtils.isNotEmpty(key) && key.contains("|")) {
                    String[] fieldArray = key.split("\\|");
                    int id = Integer.parseInt(fieldArray[0]);
                    String openid = fieldArray[1];
                    User user = User.dao.Get(id);
                    if (openid != null && user != null && openid.equals(user.get("openid"))) {
                        request.setAttribute("g_user", user);
                    }
                }
                break;
            }
        }
    }
    nextHandler.handle(target, request, response, isHandled);
}
Example 93
Project: breeze.server.java-master  File: TestHarnessServlet.java View source code
private void writeFileTo(String fileName, HttpServletResponse response) {
    FileInputStream fileIn = null;
    ServletOutputStream out = null;
    try {
        File file = new File(_testCaseDir, URLDecoder.decode(fileName, "UTF-8"));
        if (!file.exists()) {
            // 404.
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        String contentType = getServletContext().getMimeType(file.getName());
        if (contentType == null) {
            contentType = "application/octet-stream";
        }
        response.setBufferSize(BUFFER_SIZE);
        response.setContentType(contentType);
        response.setHeader("Content-Length", String.valueOf(file.length()));
        fileIn = new FileInputStream(file);
        out = response.getOutputStream();
        byte[] outputByte = new byte[BUFFER_SIZE];
        int x;
        while ((x = fileIn.read(outputByte, 0, BUFFER_SIZE)) != -1) {
            out.write(outputByte, 0, x);
        }
        out.flush();
    } catch (Exception e) {
        throw new RuntimeException("Unable to read: " + fileName, e);
    } finally {
        close(fileIn);
        close(out);
    }
}
Example 94
Project: callingruby-master  File: GetPathObject.java View source code
public static String getPathForObject(Object obj) {
    URL url = getURLForObject(obj);
    if (url.getProtocol().equals("jar")) {
        try {
            JarURLConnection jarCon = (JarURLConnection) url.openConnection();
            url = jarCon.getJarFileURL();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    try {
        File file = new File(URLDecoder.decode(url.getPath(), "UTF-8"));
        if (file.isFile()) {
            return file.getParent();
        }
        return file.getPath();
    } catch (UnsupportedEncodingException e) {
        System.out.println("Urldecoding error: " + e.getMessage());
        e.printStackTrace();
        return "";
    }
}
Example 95
Project: CampusFeedv2-master  File: ScraperHandler.java View source code
public static Result scrapedPage() {
    JsonNode request = request().body().asJson();
    // get all data
    String url = request.get("url").textValue();
    String url_decoded = null;
    try {
        url_decoded = URLDecoder.decode(url, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        return internalServerError();
    }
    int event_id = EventManager.createFromScrapedPage(request);
    if (event_id == -1) {
        return internalServerError();
    } else {
        try (Connection conn = DB.getConnection()) {
            PreparedStatement stmt = conn.prepareStatement("INSERT INTO CampusFeed.Scraper (scrape_url,event_id) VALUES (?,?)");
            stmt.setString(1, url_decoded);
            stmt.setInt(2, event_id);
            stmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
            return internalServerError();
        }
        return ok("success");
    }
}
Example 96
Project: cap-master  File: FileLoader.java View source code
private File getNextFile(URL resource) throws UnsupportedEncodingException {
    String fileNameDecoded = URLDecoder.decode(resource.getFile(), "UTF-8");
    // Check for a JAR file - they'll be returned with names that look like:
    // file:/Users/RogerHughes/.m2/repository/log4j/log4j/1.2.16/log4j-1.2.16.jar!/org/apache/log4j
    Matcher m = fileNamePattern.matcher(fileNameDecoded);
    if (m.matches()) {
        fileNameDecoded = fileNameDecoded.substring(fileNameDecoded.indexOf(":") + 1, fileNameDecoded.indexOf("!"));
    }
    return new File(fileNameDecoded);
}
Example 97
Project: captaindebug-master  File: FileLoader.java View source code
private File getNextFile(URL resource) throws UnsupportedEncodingException {
    String fileNameDecoded = URLDecoder.decode(resource.getFile(), "UTF-8");
    // Check for a JAR file - they'll be returned with names that look like:
    // file:/Users/RogerHughes/.m2/repository/log4j/log4j/1.2.16/log4j-1.2.16.jar!/org/apache/log4j
    Matcher m = fileNamePattern.matcher(fileNameDecoded);
    if (m.matches()) {
        fileNameDecoded = fileNameDecoded.substring(fileNameDecoded.indexOf(":") + 1, fileNameDecoded.indexOf("!"));
    }
    return new File(fileNameDecoded);
}
Example 98
Project: Carolina-Digital-Repository-master  File: IRODSStageResolver.java View source code
@Override
public boolean exists(URI locationURI) {
    try {
        if ("irods".equalsIgnoreCase(locationURI.getScheme())) {
            IRODSFileFactory ff = IRODSFileSystem.instance().getIRODSFileFactory(irodsAccount);
            IRODSFile file = ff.instanceIRODSFile(URLDecoder.decode(locationURI.getRawPath(), "UTF-8"));
            return file.exists();
        } else {
            return super.exists(locationURI);
        }
    } catch (JargonException e) {
        log.warn("Trouble checking existence of path in irods: {}", locationURI, e);
        return false;
    } catch (UnsupportedEncodingException e) {
        throw new Error(e);
    }
}
Example 99
Project: cassandra-migration-master  File: UrlUtils.java View source code
/**
     * Retrieves the file path of this URL, with any trailing slashes removed.
     *
     * @param url The URL to get the file path for.
     * @return The file path.
     */
public static String toFilePath(URL url) {
    try {
        String filePath = new File(URLDecoder.decode(url.getPath().replace("+", "%2b"), "UTF-8")).getAbsolutePath();
        if (filePath.endsWith("/")) {
            return filePath.substring(0, filePath.length() - 1);
        }
        return filePath;
    } catch (UnsupportedEncodingException e) {
        throw new IllegalStateException("Can never happen", e);
    }
}
Example 100
Project: cdh-mesos-master  File: PipeCombiner.java View source code
String getPipeCommand(JobConf job) {
    String str = job.get("stream.combine.streamprocessor");
    try {
        if (str != null) {
            return URLDecoder.decode(str, "UTF-8");
        }
    } catch (UnsupportedEncodingException e) {
        System.err.println("stream.combine.streamprocessor" + " in jobconf not found");
    }
    return null;
}
Example 101
Project: cdh3u3-with-mesos-master  File: PipeCombiner.java View source code
String getPipeCommand(JobConf job) {
    String str = job.get("stream.combine.streamprocessor");
    try {
        if (str != null) {
            return URLDecoder.decode(str, "UTF-8");
        }
    } catch (UnsupportedEncodingException e) {
        System.err.println("stream.combine.streamprocessor" + " in jobconf not found");
    }
    return null;
}