List of usage examples for java.net MalformedURLException getMessage
public String getMessage()
From source file:com.dell.asm.asmcore.asmmanager.util.ProxyUtil.java
public static String getNetworkServiceURL() { try {//from w w w. java2 s . com return new URL("http", HOST, PORT, NETWORK_SERVICE_PATH).toString(); } catch (MalformedURLException e) { logger.error(e.getMessage()); } return null; }
From source file:com.dell.asm.asmcore.asmmanager.util.ProxyUtil.java
private static String getALCMServiceURL() { try {/*from w ww . j av a 2 s. c om*/ return new URL("http", HOST, PORT, ALCM_PATH).toString(); } catch (MalformedURLException e) { logger.error(e.getMessage()); } return null; }
From source file:com.dell.asm.asmcore.asmmanager.util.ProxyUtil.java
/** * Compose the URL of the JRAF webapp//from ww w. jav a 2 s . c o m * * @return JRAF webapp URL */ public static String getJrafUrl() { try { return new URL("http", HOST, PORT, JRAF_APP_PATH).toString(); } catch (MalformedURLException e) { logger.error(e.getMessage()); } return null; }
From source file:de.egore911.versioning.deployer.performer.PerformExtraction.java
private static boolean extract(String uri, List<ExtractionPair> extractions) { URL url;/*www . ja v a 2 s .c o m*/ try { url = new URL(uri); } catch (MalformedURLException e) { LOG.error("Invalid URI: {}", e.getMessage(), e); return false; } try { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); int response = connection.getResponseCode(); int lastSlash = uri.lastIndexOf('/'); if (lastSlash < 0) { LOG.error("Invalid URI: {}", uri); return false; } int lastDot = uri.lastIndexOf('.'); if (lastDot < 0) { LOG.error("Invalid URI: {}", uri); return false; } File downloadFile = File.createTempFile(uri.substring(lastSlash + 1), uri.substring(lastDot + 1)); downloadFile.deleteOnExit(); if (response == HttpURLConnection.HTTP_OK) { try (InputStream in = connection.getInputStream(); FileOutputStream out = new FileOutputStream(downloadFile)) { IOUtils.copy(in, out); } LOG.debug("Downloaded {} to {}", url, downloadFile.getAbsolutePath()); Set<ExtractionPair> usedExtractions = new HashSet<>(); // Perform extractions try (ZipFile zipFile = new ZipFile(downloadFile)) { Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); // Only extract files if (entry.isDirectory()) { continue; } for (ExtractionPair extraction : extractions) { String sourcePattern = extraction.source; if (FilenameUtils.wildcardMatch(entry.getName(), sourcePattern)) { usedExtractions.add(extraction); LOG.debug("Found matching file {} for source pattern {}", entry.getName(), sourcePattern); String filename = getSourcePatternMatch(entry.getName(), sourcePattern); // Workaround: If there is no matcher in 'sourcePattern' it will return the // complete path. Strip it down to the filename if (filename.equals(entry.getName())) { int lastIndexOf = filename.lastIndexOf('/'); if (lastIndexOf >= 0) { filename = filename.substring(lastIndexOf + 1); } } String name = UrlUtil.concatenateUrlWithSlashes(extraction.destination, filename); FileUtils.forceMkdir(new File(name).getParentFile()); try (InputStream in = zipFile.getInputStream(entry); FileOutputStream out = new FileOutputStream(name)) { IOUtils.copy(in, out); } LOG.debug("Extracted {} to {} from {}", entry.getName(), name, uri); } } } } for (ExtractionPair extraction : extractions) { if (!usedExtractions.contains(extraction)) { LOG.debug("Extraction {} to {} not used on {}", extraction.source, extraction.destination, uri); } } return true; } else { LOG.error("Could not download file: {}", uri); return false; } } catch (IOException e) { LOG.error("Could not download file: {}", e.getMessage(), e); return false; } }
From source file:eu.betaas.taas.taasvmmanager.configuration.TaaSVMMAnagerConfiguration.java
private static void downloadBaseImages() { URL website;//from ww w.jav a 2 s. c o m ReadableByteChannel rbc; FileOutputStream fos; logger.info("Downloading default VM images."); try { website = new URL(baseImagesURL); rbc = Channels.newChannel(website.openStream()); fos = new FileOutputStream(baseImagesPath); logger.info("Downloading base image from " + baseImagesURL); //new DownloadUpdater(baseComputeImageX86Path, baseImagesURL).start(); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); } catch (MalformedURLException e) { logger.error("Error downloading images: bad URL."); logger.error(e.getMessage()); } catch (IOException e) { logger.error("Error downloading images: IO exception."); logger.error(e.getMessage()); } logger.info("Completed!"); }
From source file:de.adorsys.oauth.authdispatcher.FixedServletUtils.java
/** * Creates a new HTTP request from the specified HTTP servlet request. * * @param sr The servlet request. Must not be * {@code null}./*from w ww .j a v a2s . c o m*/ * @param maxEntityLength The maximum entity length to accept, -1 for * no limit. * * @return The HTTP request. * * @throws IllegalArgumentException The the servlet request method is * not GET, POST, PUT or DELETE or the * content type header value couldn't * be parsed. * @throws IOException For a POST or PUT body that * couldn't be read due to an I/O * exception. */ public static HTTPRequest createHTTPRequest(final HttpServletRequest sr, final long maxEntityLength) throws IOException { HTTPRequest.Method method = HTTPRequest.Method.valueOf(sr.getMethod().toUpperCase()); String urlString = reconstructRequestURLString(sr); URL url; try { url = new URL(urlString); } catch (MalformedURLException e) { throw new IllegalArgumentException("Invalid request URL: " + e.getMessage() + ": " + urlString, e); } HTTPRequest request = new HTTPRequest(method, url); try { request.setContentType(sr.getContentType()); } catch (ParseException e) { throw new IllegalArgumentException("Invalid Content-Type header value: " + e.getMessage(), e); } Enumeration<String> headerNames = sr.getHeaderNames(); while (headerNames.hasMoreElements()) { final String headerName = headerNames.nextElement(); request.setHeader(headerName, sr.getHeader(headerName)); } if (method.equals(HTTPRequest.Method.GET) || method.equals(HTTPRequest.Method.DELETE)) { request.setQuery(sr.getQueryString()); } else if (method.equals(HTTPRequest.Method.POST) || method.equals(HTTPRequest.Method.PUT)) { if (maxEntityLength > 0 && sr.getContentLength() > maxEntityLength) { throw new IOException("Request entity body is too large, limit is " + maxEntityLength + " chars"); } Map<String, String[]> parameterMap = sr.getParameterMap(); StringBuilder builder = new StringBuilder(); if (!parameterMap.isEmpty()) { for (Entry<String, String[]> entry : parameterMap.entrySet()) { String key = entry.getKey(); String[] value = entry.getValue(); if (value.length > 0 && value[0] != null) { String encoded = URLEncoder.encode(value[0], "UTF-8"); builder = builder.append(key).append('=').append(encoded).append('&'); } } String queryString = StringUtils.substringBeforeLast(builder.toString(), "&"); request.setQuery(queryString); } else { // read body StringBuilder body = new StringBuilder(256); BufferedReader reader = sr.getReader(); char[] cbuf = new char[256]; int readChars; while ((readChars = reader.read(cbuf)) != -1) { body.append(cbuf, 0, readChars); if (maxEntityLength > 0 && body.length() > maxEntityLength) { throw new IOException( "Request entity body is too large, limit is " + maxEntityLength + " chars"); } } reader.close(); request.setQuery(body.toString()); } } return request; }
From source file:com.apifest.oauth20.LifecycleEventHandlers.java
@SuppressWarnings("unchecked") public static void loadLifecycleHandlers(URLClassLoader classLoader, String customJar) { try {//from w ww . j ava 2s. c o m if (classLoader != null) { JarFile jarFile = new JarFile(customJar); Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); if (entry.isDirectory() || !entry.getName().endsWith(".class")) { continue; } // remove .class String className = entry.getName().substring(0, entry.getName().length() - 6); className = className.replace('/', '.'); try { // REVISIT: check for better solution if (className.startsWith("org.jboss.netty") || className.startsWith("org.apache.log4j") || className.startsWith("org.apache.commons")) { continue; } Class<?> clazz = classLoader.loadClass(className); if (clazz.isAnnotationPresent(OnRequest.class) && LifecycleHandler.class.isAssignableFrom(clazz)) { requestEventHandlers.add((Class<LifecycleHandler>) clazz); log.debug("preIssueTokenHandler added {}", className); } if (clazz.isAnnotationPresent(OnResponse.class) && LifecycleHandler.class.isAssignableFrom(clazz)) { responseEventHandlers.add((Class<LifecycleHandler>) clazz); log.debug("postIssueTokenHandler added {}", className); } if (clazz.isAnnotationPresent(OnException.class) && ExceptionEventHandler.class.isAssignableFrom(clazz)) { exceptionHandlers.add((Class<ExceptionEventHandler>) clazz); log.debug("exceptionHandlers added {}", className); } } catch (ClassNotFoundException e1) { // continue } } } } catch (MalformedURLException e) { log.error("cannot load lifecycle handlers", e); } catch (IOException e) { log.error("cannot load lifecycle handlers", e); } catch (IllegalArgumentException e) { log.error(e.getMessage()); } }
From source file:de.adorsys.oauth.server.FixedServletUtils.java
/** * Creates a new HTTP request from the specified HTTP servlet request. * * @param servletRequest The servlet request. Must not be * {@code null}.//from ww w . j a va 2 s. c o m * @param maxEntityLength The maximum entity length to accept, -1 for * no limit. * * @return The HTTP request. * * @throws IllegalArgumentException The the servlet request method is * not GET, POST, PUT or DELETE or the * content type header value couldn't * be parsed. * @throws IOException For a POST or PUT body that * couldn't be read due to an I/O * exception. */ public static HTTPRequest createHTTPRequest(final HttpServletRequest servletRequest, final long maxEntityLength) throws IOException { HTTPRequest.Method method = HTTPRequest.Method.valueOf(servletRequest.getMethod().toUpperCase()); String urlString = reconstructRequestURLString(servletRequest); URL url; try { url = new URL(urlString); } catch (MalformedURLException e) { throw new IllegalArgumentException("Invalid request URL: " + e.getMessage() + ": " + urlString, e); } HTTPRequest request = new HTTPRequest(method, url); try { request.setContentType(servletRequest.getContentType()); } catch (ParseException e) { throw new IllegalArgumentException("Invalid Content-Type header value: " + e.getMessage(), e); } Enumeration<String> headerNames = servletRequest.getHeaderNames(); while (headerNames.hasMoreElements()) { final String headerName = headerNames.nextElement(); request.setHeader(headerName, servletRequest.getHeader(headerName)); } if (method.equals(HTTPRequest.Method.GET) || method.equals(HTTPRequest.Method.DELETE)) { request.setQuery(servletRequest.getQueryString()); } else if (method.equals(HTTPRequest.Method.POST) || method.equals(HTTPRequest.Method.PUT)) { if (maxEntityLength > 0 && servletRequest.getContentLength() > maxEntityLength) { throw new IOException("Request entity body is too large, limit is " + maxEntityLength + " chars"); } Map<String, String[]> parameterMap = servletRequest.getParameterMap(); StringBuilder builder = new StringBuilder(); if (!parameterMap.isEmpty()) { for (Entry<String, String[]> entry : parameterMap.entrySet()) { String key = entry.getKey(); String[] value = entry.getValue(); if (value.length > 0 && value[0] != null) { String encoded = URLEncoder.encode(value[0], "UTF-8"); builder = builder.append(key).append('=').append(encoded).append('&'); } } String queryString = StringUtils.substringBeforeLast(builder.toString(), "&"); request.setQuery(queryString); } else { // read body StringBuilder body = new StringBuilder(256); BufferedReader reader = servletRequest.getReader(); reader.reset(); char[] cbuf = new char[256]; int readChars; while ((readChars = reader.read(cbuf)) != -1) { body.append(cbuf, 0, readChars); if (maxEntityLength > 0 && body.length() > maxEntityLength) { throw new IOException( "Request entity body is too large, limit is " + maxEntityLength + " chars"); } } reader.reset(); // reader.close(); request.setQuery(body.toString()); } } return request; }
From source file:eu.trentorise.smartcampus.protocolcarrier.Communicator.java
private static HttpRequestBase buildRequest(MessageRequest msgRequest, String appToken, String authToken) throws URISyntaxException, UnsupportedEncodingException { String host = msgRequest.getTargetHost(); if (host == null) throw new URISyntaxException(host, "null URI"); if (!host.endsWith("/")) host += '/'; String address = msgRequest.getTargetAddress(); if (address == null) address = ""; if (address.startsWith("/")) address = address.substring(1);//from w ww .ja v a 2 s . c o m String uriString = host + address; try { URL url = new URL(uriString); URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef()); uriString = uri.toURL().toString(); } catch (MalformedURLException e) { throw new URISyntaxException(uriString, e.getMessage()); } if (msgRequest.getQuery() != null) uriString += "?" + msgRequest.getQuery(); // new URI(uriString); HttpRequestBase request = null; if (msgRequest.getMethod().equals(Method.POST)) { HttpPost post = new HttpPost(uriString); HttpEntity httpEntity = null; if (msgRequest.getRequestParams() != null) { // if body and requestparams are either not null there is an // exception if (msgRequest.getBody() != null && msgRequest != null) { throw new IllegalArgumentException("body and requestParams cannot be either populated"); } httpEntity = new MultipartEntity(); for (RequestParam param : msgRequest.getRequestParams()) { if (param.getParamName() == null || param.getParamName().trim().length() == 0) { throw new IllegalArgumentException("paramName cannot be null or empty"); } if (param instanceof FileRequestParam) { FileRequestParam fileparam = (FileRequestParam) param; ((MultipartEntity) httpEntity).addPart(param.getParamName(), new ByteArrayBody( fileparam.getContent(), fileparam.getContentType(), fileparam.getFilename())); } if (param instanceof ObjectRequestParam) { ObjectRequestParam objectparam = (ObjectRequestParam) param; ((MultipartEntity) httpEntity).addPart(param.getParamName(), new StringBody(convertObject(objectparam.getVars()))); } } // mpe.addPart("file", // new ByteArrayBody(msgRequest.getFileContent(), "")); // post.setEntity(mpe); } if (msgRequest.getBody() != null) { httpEntity = new StringEntity(msgRequest.getBody(), Constants.CHARSET); ((StringEntity) httpEntity).setContentType(msgRequest.getContentType()); } post.setEntity(httpEntity); request = post; } else if (msgRequest.getMethod().equals(Method.PUT)) { HttpPut put = new HttpPut(uriString); if (msgRequest.getBody() != null) { StringEntity se = new StringEntity(msgRequest.getBody(), Constants.CHARSET); se.setContentType(msgRequest.getContentType()); put.setEntity(se); } request = put; } else if (msgRequest.getMethod().equals(Method.DELETE)) { request = new HttpDelete(uriString); } else { // default: GET request = new HttpGet(uriString); } Map<String, String> headers = new HashMap<String, String>(); // default headers if (appToken != null) { headers.put(RequestHeader.APP_TOKEN.toString(), appToken); } if (authToken != null) { // is here for compatibility headers.put(RequestHeader.AUTH_TOKEN.toString(), authToken); headers.put(RequestHeader.AUTHORIZATION.toString(), "Bearer " + authToken); } headers.put(RequestHeader.ACCEPT.toString(), msgRequest.getContentType()); if (msgRequest.getCustomHeaders() != null) { headers.putAll(msgRequest.getCustomHeaders()); } for (String key : headers.keySet()) { request.addHeader(key, headers.get(key)); } return request; }
From source file:com.cws.esolutions.core.listeners.CoreServiceInitializer.java
/** * Initializes the core service in a standalone mode - used for applications outside of a container or when * run as a standalone jar.//www.ja va 2s .com * * @param configFile - The service configuration file to utilize * @param logConfig - The logging configuration file to utilize * @param loadSecurity - Flag to start security * @param startConnections - Flag to start connections * @throws CoreServiceException @{link com.cws.esolutions.core.exception.CoreServiceException} * if an exception occurs during initialization */ public static void initializeService(final String configFile, final String logConfig, final boolean loadSecurity, final boolean startConnections) throws CoreServiceException { URL xmlURL = null; JAXBContext context = null; Unmarshaller marshaller = null; SecurityConfig secConfig = null; CoreConfigurationData configData = null; SecurityConfigurationData secConfigData = null; if (loadSecurity) { secConfigData = SecurityServiceBean.getInstance().getConfigData(); secConfig = secConfigData.getSecurityConfig(); } final String serviceConfig = (StringUtils.isBlank(configFile)) ? System.getProperty("coreConfigFile") : configFile; final String loggingConfig = (StringUtils.isBlank(logConfig)) ? System.getProperty("coreLogConfig") : logConfig; try { try { DOMConfigurator.configure(Loader.getResource(loggingConfig)); } catch (NullPointerException npx) { try { DOMConfigurator.configure(FileUtils.getFile(loggingConfig).toURI().toURL()); } catch (NullPointerException npx1) { System.err.println("Unable to load logging configuration. No logging enabled!"); System.err.println(""); npx1.printStackTrace(); } } xmlURL = CoreServiceInitializer.class.getClassLoader().getResource(serviceConfig); if (xmlURL == null) { // try loading from the filesystem xmlURL = FileUtils.getFile(configFile).toURI().toURL(); } context = JAXBContext.newInstance(CoreConfigurationData.class); marshaller = context.createUnmarshaller(); configData = (CoreConfigurationData) marshaller.unmarshal(xmlURL); CoreServiceInitializer.appBean.setConfigData(configData); if (startConnections) { Map<String, DataSource> dsMap = CoreServiceInitializer.appBean.getDataSources(); if (DEBUG) { DEBUGGER.debug("dsMap: {}", dsMap); } if (dsMap == null) { dsMap = new HashMap<String, DataSource>(); } for (DataSourceManager mgr : configData.getResourceConfig().getDsManager()) { if (!(dsMap.containsKey(mgr.getDsName()))) { StringBuilder sBuilder = new StringBuilder() .append("connectTimeout=" + mgr.getConnectTimeout() + ";") .append("socketTimeout=" + mgr.getConnectTimeout() + ";") .append("autoReconnect=" + mgr.getAutoReconnect() + ";") .append("zeroDateTimeBehavior=convertToNull"); if (DEBUG) { DEBUGGER.debug("StringBuilder: {}", sBuilder); } BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName(mgr.getDriver()); dataSource.setUrl(mgr.getDataSource()); dataSource.setUsername(mgr.getDsUser()); dataSource.setConnectionProperties(sBuilder.toString()); dataSource.setPassword(PasswordUtils.decryptText(mgr.getDsPass(), mgr.getSalt(), secConfig.getSecretAlgorithm(), secConfig.getIterations(), secConfig.getKeyBits(), secConfig.getEncryptionAlgorithm(), secConfig.getEncryptionInstance(), configData.getAppConfig().getEncoding())); if (DEBUG) { DEBUGGER.debug("BasicDataSource: {}", dataSource); } dsMap.put(mgr.getDsName(), dataSource); } } if (DEBUG) { DEBUGGER.debug("dsMap: {}", dsMap); } CoreServiceInitializer.appBean.setDataSources(dsMap); } } catch (JAXBException jx) { jx.printStackTrace(); throw new CoreServiceException(jx.getMessage(), jx); } catch (MalformedURLException mux) { mux.printStackTrace(); throw new CoreServiceException(mux.getMessage(), mux); } }