List of usage examples for java.net URL getPath
public String getPath()
From source file:com.egt.core.util.Utils.java
public static String getAttachedFileName(URL url) { String sep = System.getProperties().getProperty("file.separator"); String pdq = EA.getString(EAC.CONTENT_ROOT_DIR) + url.getPath(); Bitacora.trace(pdq);/*from w w w. j a va 2 s.c o m*/ return pdq.replace('\\', '/').replace("/", sep); }
From source file:ips1ap101.lib.core.util.Utils.java
public static String getAttachedFileName(URL url) { return EA.getContentRootDir() + url.getPath(); }
From source file:com.echopf.ECHOQuery.java
/** * Sends a HTTP request with optional request contents/parameters. * @param path a request url path// ww w . jav a 2s. co m * @param httpMethod a request method (GET/POST/PUT/DELETE) * @param data request contents/parameters * @param multipart use multipart/form-data to encode the contents * @throws ECHOException */ public static InputStream requestRaw(String path, String httpMethod, JSONObject data, boolean multipart) throws ECHOException { final String secureDomain = ECHO.secureDomain; if (secureDomain == null) throw new IllegalStateException("The SDK is not initialized.Please call `ECHO.initialize()`."); String baseUrl = new StringBuilder("https://").append(secureDomain).toString(); String url = new StringBuilder(baseUrl).append("/").append(path).toString(); HttpsURLConnection httpClient = null; try { URL urlObj = new URL(url); StringBuilder apiUrl = new StringBuilder(baseUrl).append(urlObj.getPath()).append("/rest_api=1.0/"); // Append the QueryString contained in path boolean isContainQuery = urlObj.getQuery() != null; if (isContainQuery) apiUrl.append("?").append(urlObj.getQuery()); // Append the QueryString from data if (httpMethod.equals("GET") && data != null) { boolean firstItem = true; Iterator<?> iter = data.keys(); while (iter.hasNext()) { if (firstItem && !isContainQuery) { firstItem = false; apiUrl.append("?"); } else { apiUrl.append("&"); } String key = (String) iter.next(); String value = data.optString(key); apiUrl.append(key); apiUrl.append("="); apiUrl.append(value); } } URL urlConn = new URL(apiUrl.toString()); httpClient = (HttpsURLConnection) urlConn.openConnection(); } catch (IOException e) { throw new ECHOException(e); } final String appId = ECHO.appId; final String appKey = ECHO.appKey; final String accessToken = ECHO.accessToken; if (appId == null || appKey == null) throw new IllegalStateException("The SDK is not initialized.Please call `ECHO.initialize()`."); InputStream responseInputStream = null; try { httpClient.setRequestMethod(httpMethod); httpClient.addRequestProperty("X-ECHO-APP-ID", appId); httpClient.addRequestProperty("X-ECHO-APP-KEY", appKey); // Set access token if (accessToken != null && !accessToken.isEmpty()) httpClient.addRequestProperty("X-ECHO-ACCESS-TOKEN", accessToken); // Build content if (!httpMethod.equals("GET") && data != null) { httpClient.setDoOutput(true); httpClient.setChunkedStreamingMode(0); // use default chunk size if (multipart == false) { // application/json httpClient.addRequestProperty("CONTENT-TYPE", "application/json"); BufferedWriter wrBuffer = new BufferedWriter( new OutputStreamWriter(httpClient.getOutputStream())); wrBuffer.write(data.toString()); wrBuffer.close(); } else { // multipart/form-data final String boundary = "*****" + UUID.randomUUID().toString() + "*****"; final String twoHyphens = "--"; final String lineEnd = "\r\n"; final int maxBufferSize = 1024 * 1024 * 3; httpClient.setRequestMethod("POST"); httpClient.addRequestProperty("CONTENT-TYPE", "multipart/form-data; boundary=" + boundary); final DataOutputStream outputStream = new DataOutputStream(httpClient.getOutputStream()); try { JSONObject postData = new JSONObject(); postData.putOpt("method", httpMethod); postData.putOpt("data", data); new Object() { public void post(JSONObject data, List<String> currentKeys) throws JSONException, IOException { Iterator<?> keys = data.keys(); while (keys.hasNext()) { String key = (String) keys.next(); List<String> newKeys = new ArrayList<String>(currentKeys); newKeys.add(key); Object val = data.get(key); // convert JSONArray into JSONObject if (val instanceof JSONArray) { JSONArray array = (JSONArray) val; JSONObject val2 = new JSONObject(); for (Integer i = 0; i < array.length(); i++) { val2.putOpt(i.toString(), array.get(i)); } val = val2; } // build form-data name String name = ""; for (int i = 0; i < newKeys.size(); i++) { String key2 = newKeys.get(i); name += (i == 0) ? key2 : "[" + key2 + "]"; } if (val instanceof ECHOFile) { ECHOFile file = (ECHOFile) val; if (file.getLocalBytes() == null) continue; InputStream fileInputStream = new ByteArrayInputStream( file.getLocalBytes()); if (fileInputStream != null) { String mimeType = URLConnection .guessContentTypeFromName(file.getFileName()); // write header outputStream.writeBytes(twoHyphens + boundary + lineEnd); outputStream.writeBytes("Content-Disposition: form-data; name=\"" + name + "\"; filename=\"" + file.getFileName() + "\"" + lineEnd); outputStream.writeBytes("Content-Type: " + mimeType + lineEnd); outputStream.writeBytes("Content-Transfer-Encoding: binary" + lineEnd); outputStream.writeBytes(lineEnd); // write content int bytesAvailable, bufferSize, bytesRead; do { bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); byte[] buffer = new byte[bufferSize]; bytesRead = fileInputStream.read(buffer, 0, bufferSize); if (bytesRead <= 0) break; outputStream.write(buffer, 0, bufferSize); } while (true); fileInputStream.close(); outputStream.writeBytes(lineEnd); } } else if (val instanceof JSONObject) { this.post((JSONObject) val, newKeys); } else { String data2 = null; try { // in case of boolean boolean bool = data.getBoolean(key); data2 = bool ? "true" : ""; } catch (JSONException e) { // if the value is not a Boolean or the String "true" or "false". data2 = val.toString().trim(); } // write header outputStream.writeBytes(twoHyphens + boundary + lineEnd); outputStream.writeBytes( "Content-Disposition: form-data; name=\"" + name + "\"" + lineEnd); outputStream .writeBytes("Content-Type: text/plain; charset=UTF-8" + lineEnd); outputStream.writeBytes("Content-Length: " + data2.length() + lineEnd); outputStream.writeBytes(lineEnd); // write content byte[] bytes = data2.getBytes(); for (int i = 0; i < bytes.length; i++) { outputStream.writeByte(bytes[i]); } outputStream.writeBytes(lineEnd); } } } }.post(postData, new ArrayList<String>()); } catch (JSONException e) { throw new ECHOException(e); } finally { outputStream.writeBytes(twoHyphens + boundary + lineEnd); outputStream.flush(); outputStream.close(); } } } else { httpClient.addRequestProperty("CONTENT-TYPE", "application/json"); } if (httpClient.getResponseCode() != -1 /*== HttpURLConnection.HTTP_OK*/) { responseInputStream = httpClient.getInputStream(); } } catch (IOException e) { // get http response code int errorCode = -1; try { errorCode = httpClient.getResponseCode(); } catch (IOException e1) { throw new ECHOException(e1); } // get error contents JSONObject responseObj; try { String jsonStr = ECHOQuery.getResponseString(httpClient.getErrorStream()); responseObj = new JSONObject(jsonStr); } catch (JSONException e1) { if (errorCode == 404) { throw new ECHOException(ECHOException.RESOURCE_NOT_FOUND, "Resource not found."); } throw new ECHOException(ECHOException.INVALID_JSON_FORMAT, "Invalid JSON format."); } // if (responseObj != null) { int code = responseObj.optInt("error_code"); String message = responseObj.optString("error_message"); if (code != 0 || !message.equals("")) { JSONObject details = responseObj.optJSONObject("error_details"); if (details == null) { throw new ECHOException(code, message); } else { throw new ECHOException(code, message, details); } } } throw new ECHOException(e); } return responseInputStream; }
From source file:net.rptools.lib.FileUtil.java
/** * Given a URL this method determines the content type of the URL (if possible) and then returns a Reader with the * appropriate character encoding.//from w ww . j ava 2s.c o m * * @param url * the source of the data stream * @return String representing the data * @throws IOException */ public static Reader getURLAsReader(URL url) throws IOException { InputStreamReader isr = null; URLConnection conn = null; // We're assuming character here, but it could be bytes. Perhaps we should // check the MIME type returned by the network server? conn = url.openConnection(); if (log.isDebugEnabled()) { String type = URLConnection.guessContentTypeFromName(url.getPath()); log.debug("result from guessContentTypeFromName(" + url.getPath() + ") is " + type); type = getContentType(conn.getInputStream()); // Now make a guess and change 'encoding' to match the content type... } isr = new InputStreamReader(conn.getInputStream(), "UTF-8"); return isr; }
From source file:com.nary.io.FileUtils.java
/** * This only works on WLS 9.x, which unpacks WARs to a temp directory, but still returns null from context.getRealPath() and request.getRealPath(). This method returns null if the resource does not exist, unlike context.getRealPath() and request.getRealPath() *///from w w w . j av a 2 s. co m private static String getWebLogicRealPath(String path) { try { java.net.URL url = cfEngine.thisServletContext.getResource(path); if ((url != null) && (url.getProtocol().equalsIgnoreCase("file"))) { return url.getPath(); } } catch (java.net.MalformedURLException ignore) { } return null; }
From source file:co.cask.cdap.security.server.ExternalLDAPAuthenticationServerSSLTest.java
@BeforeClass public static void beforeClass() throws Exception { URL certUrl = ExternalLDAPAuthenticationServerSSLTest.class.getClassLoader().getResource("cert.jks"); Assert.assertNotNull(certUrl);/*w w w. j av a2 s . co m*/ String authHandlerConfigBase = Constants.Security.AUTH_HANDLER_CONFIG_BASE; CConfiguration cConf = CConfiguration.create(); SConfiguration sConf = SConfiguration.create(); cConf.set(Constants.Security.AUTH_SERVER_BIND_ADDRESS, "127.0.0.1"); cConf.set(Constants.Security.SSL.EXTERNAL_ENABLED, "true"); cConf.set(Constants.Security.AuthenticationServer.SSL_PORT, "0"); cConf.set(authHandlerConfigBase.concat("useLdaps"), "true"); cConf.set(authHandlerConfigBase.concat("ldapsVerifyCertificate"), "false"); sConf.set(Constants.Security.AuthenticationServer.SSL_KEYSTORE_PATH, certUrl.getPath()); configuration = cConf; sConfiguration = sConf; String keystorePassword = sConf.get(Constants.Security.AuthenticationServer.SSL_KEYSTORE_PASSWORD); KeyStoreKeyManager keyManager = new KeyStoreKeyManager(certUrl.getFile(), keystorePassword.toCharArray()); SSLUtil sslUtil = new SSLUtil(keyManager, new TrustAllTrustManager()); ldapListenerConfig = InMemoryListenerConfig.createLDAPSConfig("LDAP", InetAddress.getByName("127.0.0.1"), ldapPort, sslUtil.createSSLServerSocketFactory(), sslUtil.createSSLSocketFactory()); testServer = new ExternalLDAPAuthenticationServerSSLTest(); testServer.setup(); }
From source file:com.datatorrent.stram.StramMiniClusterTest.java
@BeforeClass public static void setup() throws InterruptedException, IOException { LOG.info("Starting up YARN cluster"); conf = StramClientUtils.addDTDefaultResources(conf); conf.setInt(YarnConfiguration.RM_SCHEDULER_MINIMUM_ALLOCATION_MB, 64); conf.setInt("yarn.nodemanager.vmem-pmem-ratio", 20); // workaround to avoid containers being killed because java allocated too much vmem conf.setStrings("yarn.scheduler.capacity.root.queues", "default"); conf.setStrings("yarn.scheduler.capacity.root.default.capacity", "100"); StringBuilder adminEnv = new StringBuilder(1024); if (System.getenv("JAVA_HOME") == null) { adminEnv.append("JAVA_HOME=").append(System.getProperty("java.home")); adminEnv.append(","); }/*from ww w. java 2 s . c o m*/ adminEnv.append("MALLOC_ARENA_MAX=4"); // see MAPREDUCE-3068, MAPREDUCE-3065 adminEnv.append(","); adminEnv.append("CLASSPATH=").append(getTestRuntimeClasspath()); conf.set(YarnConfiguration.NM_ADMIN_USER_ENV, adminEnv.toString()); if (yarnCluster == null) { yarnCluster = new MiniYARNCluster(StramMiniClusterTest.class.getName(), 1, 1, 1); yarnCluster.init(conf); yarnCluster.start(); } conf = yarnCluster.getConfig(); URL url = Thread.currentThread().getContextClassLoader().getResource("yarn-site.xml"); if (url == null) { LOG.error("Could not find 'yarn-site.xml' dummy file in classpath"); throw new RuntimeException("Could not find 'yarn-site.xml' dummy file in classpath"); } File confFile = new File(url.getPath()); yarnCluster.getConfig().set("yarn.application.classpath", confFile.getParent()); OutputStream os = new FileOutputStream(confFile); LOG.debug("Conf file: {}", confFile); yarnCluster.getConfig().writeXml(os); os.close(); try { Thread.sleep(2000); } catch (InterruptedException e) { LOG.info("setup thread sleep interrupted. message=" + e.getMessage()); } }
From source file:gate.util.Files.java
/** * Convert a file: URL to a <code>java.io.File</code>. First tries to parse * the URL's toExternalForm as a URI and create the File object from that * URI. If this fails, just uses the path part of the URL. This handles * URLs that contain spaces or other unusual characters, both as literals and * when encoded as (e.g.) %20./*from w ww . ja v a 2 s . co m*/ * * @exception IllegalArgumentException if the URL is not convertable into a * File. */ public static File fileFromURL(URL theURL) throws IllegalArgumentException { try { URI uri = new URI(theURL.toExternalForm()); return new File(uri); } catch (URISyntaxException use) { try { URI uri = new URI(theURL.getProtocol(), null, theURL.getPath(), null, null); return new File(uri); } catch (URISyntaxException use2) { throw new IllegalArgumentException("Cannot convert " + theURL + " to a file path"); } } }
From source file:name.yumao.douyu.http.PlaylistDownloader.java
private static void downloadInternal(URL segmentUrl, String outFile) { FileOutputStream out = null;// w w w .j a v a 2s. c o m InputStream is = null; try { byte[] buffer = new byte[512]; is = segmentUrl.openStream(); if (outFile != null) { File file = new File(outFile); if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } out = new FileOutputStream(outFile, file.exists()); } else { String path = segmentUrl.getPath(); int pos = path.lastIndexOf('/'); out = new FileOutputStream(path.substring(++pos), false); } logger.info("Downloading segment:" + segmentUrl + "\r"); int read; while ((read = is.read(buffer)) >= 0) { out.write(buffer, 0, read); } } catch (Exception e) { e.printStackTrace(); } finally { try { is.close(); out.close(); } catch (IOException e) { e.printStackTrace(); } } }
From source file:com.adguard.commons.web.UrlUtils.java
/** * Extracts path and query from the url/*from w w w . ja v a 2 s . c o m*/ * * @param url Url * @return path and query */ public static String getPathAndQuery(URL url) { String path = url.getPath(); String query = url.getQuery(); if (StringUtils.isNotEmpty(query)) { return path + "?" + query; } return path; }