Example usage for java.net MalformedURLException getMessage

List of usage examples for java.net MalformedURLException getMessage

Introduction

In this page you can find the example usage for java.net MalformedURLException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:com.redhat.rcm.version.Cli.java

private VersionManagerSession initSession() throws VManException {
    SSLUtils.initSSLContext(truststorePath);

    loadConfiguration();//from www.  jav a2 s  .  com

    loadBomList();

    loadPlugins();

    loadAndNormalizeModifications();

    final Logger logger = LoggerFactory.getLogger(getClass());
    logger.info("modifications = " + join(modders, " "));

    final SessionBuilder builder = new SessionBuilder(workspace, reports).withVersionSuffix(versionSuffix)
            .withVersionModifier(versionModifier).withRemovedPlugins(removedPlugins)
            .withRemovedTests(removedTests).withExtensionsWhitelist(extensionsWhitelist).withModders(modders)
            .withPreserveFiles(preserveFiles).withStrict(strict).withCoordinateRelocations(relocatedCoords)
            .withPropertyMappings(propertyMappings).withExcludedModulePoms(pomExcludeModules)
            .withUseEffectivePoms(useEffectivePoms).withUserProperties(reportProperties);

    final VersionManagerSession session = builder.build();

    if (remoteRepositories != null) {
        try {
            session.setRemoteRepositories(remoteRepositories);
        } catch (final MalformedURLException e) {
            throw new VManException("Cannot initialize remote repositories: %s. Error: %s", e,
                    remoteRepositories, e.getMessage());
        }
    }

    if (settings != null) {
        session.setSettingsXml(settings);
    }

    if (localRepository == null) {
        localRepository = new File(workspace, "local-repository");
    }

    session.setLocalRepositoryDirectory(localRepository);

    if (capturePom != null) {
        session.setCapturePom(capturePom);
    }

    return session;
}

From source file:telecom.sudparis.eu.paas.core.server.ressources.manager.application.ApplicationManagerRessource.java

/**
 * {@inheritDoc}//  w  w w .  jav a  2 s. c o  m
 */
@Override
public Response restartApplication(String appid) {
    try {
        CloudFoundryClient client = null;

        try {
            client = new CloudFoundryClient(new CloudCredentials(TEST_USER_EMAIL, TEST_USER_PASS),
                    new URL(ccUrl));
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        if (client == null) {
            System.out.println("Failed to create Client");
        } else {
            client.login();
            ApplicationType app = ApplicationPool.INSTANCE.getApp(appid);
            String appName = app.getAppName();
            client.restartApplication(appName);
            client.logout();
        }
        return describeApplication(appid);
    } catch (Exception e) {
        System.out.println("Failed to restart the application: " + e.getMessage());
        e.printStackTrace();
        error.setValue("Failed to restart the application: " + e.getMessage());
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error)
                .type(MediaType.APPLICATION_XML_TYPE).build();
    }
}

From source file:org.georchestra.security.Proxy.java

private void handleRequest(HttpServletRequest request, HttpServletResponse finalResponse,
        RequestType requestType, String sURL, boolean localProxy) {
    HttpClientBuilder htb = HttpClients.custom().disableRedirectHandling();

    RequestConfig config = RequestConfig.custom().setSocketTimeout(this.httpClientTimeout).build();
    htb.setDefaultRequestConfig(config);

    ////w  w  w.  j av a2 s.c  om
    // Handle http proxy for external request.
    // Proxy must be configured by system variables (e.g.: -Dhttp.proxyHost=proxy -Dhttp.proxyPort=3128)
    htb.setRoutePlanner(new SystemDefaultRoutePlanner(ProxySelector.getDefault()));
    HttpClient httpclient = htb.build();

    HttpResponse proxiedResponse = null;
    int statusCode = 500;

    try {
        URL url = null;
        try {
            url = new URL(sURL);
        } catch (MalformedURLException e) { // not an url
            finalResponse.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
            return;
        }

        // HTTP protocol is required
        if (!"http".equalsIgnoreCase(url.getProtocol()) && !"https".equalsIgnoreCase(url.getProtocol())) {
            finalResponse.sendError(HttpServletResponse.SC_BAD_REQUEST,
                    "HTTP protocol expected. \"" + url.getProtocol() + "\" used.");
            return;
        }

        // check if proxy must filter on final host
        if (!strategyForFilteringRequests.allowRequest(url)) {
            finalResponse.sendError(HttpServletResponse.SC_BAD_REQUEST,
                    "Host \"" + url.getHost() + "\" is not allowed to be requested");
            return;
        }

        logger.debug("Final request -- " + sURL);

        HttpRequestBase proxyingRequest = makeRequest(request, requestType, sURL);
        headerManagement.configureRequestHeaders(request, proxyingRequest);

        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            Header[] originalHeaders = proxyingRequest.getHeaders("sec-org");
            String org = "";
            for (Header originalHeader : originalHeaders) {
                org = originalHeader.getValue();
            }
            // no OGC SERVICE log if request going through /proxy/?url=
            if (!request.getRequestURI().startsWith("/sec/proxy/")) {
                String[] roles = new String[] { "" };
                try {
                    Header[] rolesHeaders = proxyingRequest.getHeaders("sec-roles");
                    if (rolesHeaders.length > 0) {
                        roles = rolesHeaders[0].getValue().split(";");
                    }
                } catch (Exception e) {
                    logger.error("Unable to compute roles");
                }
                statsLogger.info(OGCServiceMessageFormatter.format(authentication.getName(), sURL, org, roles));

            }

        } catch (Exception e) {
            logger.error("Unable to log the request into the statistics logger", e);
        }

        if (localProxy) {
            //
            // Hack for geoserver
            // Should not be here. We must use a ProxyTarget class and
            // define
            // if Host header should be forwarded or not.
            //
            request.getHeader("Host");
            proxyingRequest.setHeader("Host", request.getHeader("Host"));

            if (logger.isDebugEnabled()) {
                logger.debug("Host header set to: " + proxyingRequest.getFirstHeader("Host").getValue()
                        + " for proxy request.");
            }
        }
        proxiedResponse = executeHttpRequest(httpclient, proxyingRequest);
        StatusLine statusLine = proxiedResponse.getStatusLine();
        statusCode = statusLine.getStatusCode();
        String reasonPhrase = statusLine.getReasonPhrase();

        if (reasonPhrase != null && statusCode > 399) {
            if (logger.isWarnEnabled()) {
                logger.warn("Error occurred. statuscode: " + statusCode + ", reason: " + reasonPhrase);
            }

            if (statusCode == 401) {
                //
                // Handle case of basic authentication.
                //
                Header authHeader = proxiedResponse.getFirstHeader("WWW-Authenticate");
                finalResponse.setHeader("WWW-Authenticate",
                        (authHeader == null) ? "Basic realm=\"Authentication required\""
                                : authHeader.getValue());
            }

            // 403 and 404 are handled by specific JSP files provided by the
            // security-proxy webapp
            if ((statusCode == 404) || (statusCode == 403)) {
                finalResponse.sendError(statusCode);
                return;
            }
        }

        headerManagement.copyResponseHeaders(request, request.getRequestURI(), proxiedResponse, finalResponse,
                this.targets);

        if (statusCode == 302 || statusCode == 301) {
            adjustLocation(request, proxiedResponse, finalResponse);
        }
        // get content type

        String contentType = null;
        if (proxiedResponse.getEntity() != null && proxiedResponse.getEntity().getContentType() != null) {
            contentType = proxiedResponse.getEntity().getContentType().getValue();
            logger.debug("content-type detected: " + contentType);
        }

        // content type has to be valid
        if (isCharsetRequiredForContentType(contentType)) {
            doHandleRequestCharsetRequired(request, finalResponse, requestType, proxiedResponse, contentType);
        } else {
            logger.debug("charset not required for contentType: " + contentType);
            doHandleRequest(request, finalResponse, requestType, proxiedResponse);
        }
    } catch (IOException e) {
        // connection problem with the host
        logger.error("Exception occured when trying to connect to the remote host: ", e);
        try {
            finalResponse.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        } catch (IOException e2) {
            // error occured while trying to return the
            // "service unavailable status"
            finalResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    } finally {
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:org.kie.remote.tests.base.unit.GetIgnoreRule.java

@Override
public Statement apply(Statement base, FrameworkMethod method, Object target) {
    Statement result = base;//from   w  w w. ja  v  a 2  s  .c o m
    if (hasConditionalIgnoreAnnotation(method)) {
        IgnoreIfGETFails anno = method.getAnnotation(IgnoreIfGETFails.class);
        String urlString = anno.getUrl();
        String message = "Ignored because [GET] " + urlString + " failed.";
        boolean liveServer = false;
        try {
            new URL(urlString);
            liveServer = true;
        } catch (MalformedURLException e) {
            liveServer = false;
            message = "Ignored because [" + urlString + "] is not a valid URL.";
        }

        if (anno.getUserName() == null || anno.getUserName().isEmpty()) {
            liveServer = false;
            message = "Ignored because user name was empty or null.";
        }

        if (anno.getPassword() == null || anno.getPassword().isEmpty()) {
            liveServer = false;
            message = "Ignored because password was empty or null.";
        }

        if (liveServer) {
            try {
                Response response = Request.Get(urlString).addHeader(HttpHeaders.AUTHORIZATION,
                        basicAuthenticationHeader(anno.getUserName(), anno.getPassword())).execute();

                int code = response.returnResponse().getStatusLine().getStatusCode();
                if (code > 401) {
                    liveServer = false;
                    message = "Ignored because [GET] " + urlString + " returned " + code;
                }
            } catch (HttpHostConnectException hhce) {
                liveServer = false;
                message = "Ignored because server is not available: " + hhce.getMessage();
            } catch (Exception e) {
                liveServer = false;
                message = "Ignored because [GET] " + urlString + " threw: " + e.getMessage();
            }
        }
        if (!liveServer) {
            result = new IgnoreStatement(message);
        }
    }
    return result;
}

From source file:com.wwpass.connection.WWPassConnection.java

private InputStream makeRequest(String method, String command, Map<String, ?> parameters)
        throws IOException, WWPassProtocolException {
    String commandUrl = SpfeURL + command + ".xml";
    //String command_url = SpfeURL + command + ".json";

    StringBuilder sb = new StringBuilder();
    URLCodec codec = new URLCodec();

    @SuppressWarnings("unchecked")
    Map<String, Object> localParams = (Map<String, Object>) parameters;

    for (Map.Entry<String, Object> entry : localParams.entrySet()) {
        sb.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
        sb.append("=");
        if (entry.getValue() instanceof String) {
            sb.append(URLEncoder.encode((String) entry.getValue(), "UTF-8"));
        } else {//from   w w  w. j av  a  2  s .  c  om
            sb.append(new String(codec.encode((byte[]) entry.getValue())));
        }
        sb.append("&");
    }
    String paramsString = sb.toString();
    sb = null;
    if ("GET".equalsIgnoreCase(method)) {
        commandUrl += "?" + paramsString;
    } else if ("POST".equalsIgnoreCase(method)) {

    } else {
        throw new IllegalArgumentException("Method " + method + " not supported.");
    }

    HttpsURLConnection conn = null;
    try {
        URL url = new URL(commandUrl);
        conn = (HttpsURLConnection) url.openConnection();
        conn.setReadTimeout(timeoutMs);
        conn.setSSLSocketFactory(SPFEContext.getSocketFactory());
        if ("POST".equalsIgnoreCase(method)) {
            conn.setDoOutput(true);
            OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
            writer.write(paramsString);
            writer.flush();
        }
        InputStream in = conn.getInputStream();
        return getReplyData(in);
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException("Command-parameters combination is invalid: " + e.getMessage());
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}

From source file:com.roamprocess1.roaming4world.ui.messages.MessageActivity.java

public int uploadFile(String sourceFileUri, String fileName) {

    String upLoadServerUri = "";
    upLoadServerUri = "http://ip.roaming4world.com/esstel/file-transfer/file_upload.php";

    HttpURLConnection conn = null;
    DataOutputStream dos = null;/*w  ww  . j  ava 2  s . c  o  m*/
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;
    File sourceFile = new File(sourceFileUri);
    if (!sourceFile.isFile()) {
        Log.e("uploadFile", "Source File Does not exist");
        return 0;
    }
    try { // open a URL connection to the Servlet
        FileInputStream fileInputStream = new FileInputStream(sourceFile);
        URL url = new URL(upLoadServerUri);
        conn = (HttpURLConnection) url.openConnection(); // Open a HTTP
        // connection to
        // the URL
        conn.setDoInput(true); // Allow Inputs
        conn.setDoOutput(true); // Allow Outputs
        conn.setUseCaches(false); // Don't use a Cached Copy
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("ENCTYPE", "multipart/form-data");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
        conn.setRequestProperty("uploaded_file", sourceFileUri);

        dos = new DataOutputStream(conn.getOutputStream());

        dos.writeBytes(twoHyphens + boundary + lineEnd);
        dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\"" + multimediaMsg
                + fileName + "\"" + lineEnd);
        dos.writeBytes(lineEnd);

        bytesAvailable = fileInputStream.available(); // create a buffer of
        // maximum size

        bufferSize = Math.min(bytesAvailable, maxBufferSize);

        buffer = new byte[bufferSize];

        // read file and write it into form...
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);

        while (bytesRead > 0) {
            dos.write(buffer, 0, bufferSize);
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        }

        // send multipart form data necesssary after file data...
        dos.writeBytes(lineEnd);
        dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

        // Responses from the server (code and message)
        serverResponseCode = conn.getResponseCode();
        String serverResponseMessage = conn.getResponseMessage();

        Log.i("uploadFile", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);

        // close the streams //
        fileInputStream.close();
        dos.flush();
        dos.close();

    } catch (MalformedURLException ex) {
        ex.printStackTrace();
        Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
    } catch (Exception e) {
        e.printStackTrace();
        Log.e("Upload file to server Exception", "Exception : " + e.getMessage(), e);
    }
    return serverResponseCode;

}

From source file:com.redhat.red.build.koji.KojiClient.java

protected UploadResponse upload(InputStream stream, String filepath, String uploadDir, KojiSessionInfo session)
        throws KojiClientException {
    CloseableHttpClient client = null;/* www .  j  a  v a  2  s.c  o m*/
    try {
        client = httpFactory.createClient(config.getKojiSiteConfig());

        String url = sessionUrlBuilder(session, () -> {
            Map<String, Object> params = new HashMap<>();

            try {
                params.put(UPLOAD_DIR_PARAM, encodeParam(UPLOAD_DIR_PARAM, uploadDir));
                params.put(UPLOAD_CHECKSUM_TYPE_PARAM, ADLER_32_CHECKSUM);
                params.put(UPLOAD_FILENAME_PARAM, encodeParam(UPLOAD_FILENAME_PARAM, filepath));
                params.put(UPLOAD_OFFSET_PARAM, Integer.toString(0));
                params.put(UPLOAD_OVERWRITE_PARAM, Integer.toString(1));
            } catch (MalformedURLException e) {
                params.put(EMBEDDED_ERROR_PARAM, e);
            }

            return params;
        }).buildUrl(config.getKojiURL()).throwError().get();

        HttpPost request = new HttpPost(url);
        request.setEntity(new InputStreamEntity(stream));

        CloseableHttpResponse response = client.execute(request);

        if (response.getStatusLine().getStatusCode() == 200) {
            return bindery.parse(response.getEntity().getContent(), UploadResponse.class);
        } else {
            throw new KojiClientException("Failed to upload: %s to dir: %s. Server response: %s", filepath,
                    uploadDir, response.getStatusLine());
        }
    } catch (IOException | JHttpCException | XmlRpcException e) {
        throw new KojiClientException("Failed to upload: %s to dir: %s. Reason: %s", e, filepath, uploadDir,
                e.getMessage());
    } finally {
        closeQuietly(client);
    }
}

From source file:telecom.sudparis.eu.paas.core.server.ressources.manager.application.ApplicationManagerRessource.java

/**
 * {@inheritDoc}//from  ww  w .  j  a v a2s  .c  o  m
 */
@Override
public Response stopApplication(String appid) {
    try {
        CloudFoundryClient client = null;

        try {
            client = new CloudFoundryClient(new CloudCredentials(TEST_USER_EMAIL, TEST_USER_PASS),
                    new URL(ccUrl));
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        if (client == null) {
            System.out.println("Failed to create Client");
        } else {
            client.login();
            ApplicationType app = ApplicationPool.INSTANCE.getApp(appid);
            String appName = app.getAppName();
            if (client.getApplication(appName).getState() == AppState.STARTED)
                client.stopApplication(appName);
            client.logout();
        }
        return describeApplication(appid);
    } catch (Exception e) {
        System.out.println("Failed to stop the application: " + e.getMessage());
        e.printStackTrace();
        error.setValue("Failed to stop the application: " + e.getMessage());
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error)
                .type(MediaType.APPLICATION_XML_TYPE).build();
    }
}

From source file:telecom.sudparis.eu.paas.core.server.ressources.manager.application.ApplicationManagerRessource.java

/**
 * {@inheritDoc}/*from  w w  w .ja v a  2s  .  c om*/
 */
@Override
public Response deleteApplications() {
    try {
        copyDeployedApps2Pool();
        CloudFoundryClient client = null;

        try {
            client = new CloudFoundryClient(new CloudCredentials(TEST_USER_EMAIL, TEST_USER_PASS),
                    new URL(ccUrl));
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        if (client == null) {
            System.out.println("Failed to create Client");
        } else {
            client.login();
            client.deleteAllApplications();
            // appPool.INSTANCE.removeAll();
            ApplicationPool.INSTANCE.removeAll();
            client.logout();
        }

        or.setValue("All applications were succefully deleted");
        return Response.status(Response.Status.OK).entity(or).type(MediaType.APPLICATION_XML_TYPE).build();
    } catch (Exception e) {
        System.out.println("Failed to delete all the applications: " + e.getMessage());
        e.printStackTrace();
        error.setValue("Failed to delete all the applications: " + e.getMessage());
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(error)
                .type(MediaType.APPLICATION_XML_TYPE).build();
    }
}

From source file:jproxy.ProxyControl.java

/**
 * Detect Header manager in subConfigs,/*  ww  w  .j  a va 2s .c o m*/
 * Find(if any) Authorization header
 * Construct Authentication object
 * Removes Authorization if present 
 *
 * @param subConfigs {@link TestElement}[]
 * @param sampler {@link HTTPSamplerBase}
 * @return {@link Authorization}
 */
private Authorization createAuthorization(final TestElement[] subConfigs, HTTPSamplerBase sampler) {
    Header authHeader = null;
    Authorization authorization = null;
    // Iterate over subconfig elements searching for HeaderManager
    for (TestElement te : subConfigs) {
        if (te instanceof HeaderManager) {
            @SuppressWarnings("unchecked") // headers should only contain the correct classes
            List<TestElementProperty> headers = (ArrayList<TestElementProperty>) ((HeaderManager) te)
                    .getHeaders().getObjectValue();
            for (Iterator<?> iterator = headers.iterator(); iterator.hasNext();) {
                TestElementProperty tep = (TestElementProperty) iterator.next();
                if (tep.getName().equals(HTTPConstants.HEADER_AUTHORIZATION)) {
                    //Construct Authorization object from HEADER_AUTHORIZATION
                    authHeader = (Header) tep.getObjectValue();
                    String[] authHeaderContent = authHeader.getValue().split(" ");//$NON-NLS-1$
                    String authType = null;
                    String authCredentialsBase64 = null;
                    if (authHeaderContent.length >= 2) {
                        authType = authHeaderContent[0];
                        authCredentialsBase64 = authHeaderContent[1];
                        authorization = new Authorization();
                        try {
                            authorization.setURL(sampler.getUrl().toExternalForm());
                        } catch (MalformedURLException e) {
                            log.error("Error filling url on authorization, message:" + e.getMessage(), e);
                            authorization.setURL("${AUTH_BASE_URL}");//$NON-NLS-1$
                        }
                        // if HEADER_AUTHORIZATION contains "Basic"
                        // then set Mechanism.BASIC_DIGEST, otherwise Mechanism.KERBEROS
                        authorization.setMechanism(authType.equals(BASIC_AUTH) || authType.equals(DIGEST_AUTH)
                                ? AuthManager.Mechanism.BASIC_DIGEST
                                : AuthManager.Mechanism.KERBEROS);
                        if (BASIC_AUTH.equals(authType)) {
                            String authCred = new String(Base64.decodeBase64(authCredentialsBase64));
                            String[] loginPassword = authCred.split(":"); //$NON-NLS-1$
                            authorization.setUser(loginPassword[0]);
                            authorization.setPass(loginPassword[1]);
                        } else {
                            // Digest or Kerberos
                            authorization.setUser("${AUTH_LOGIN}");//$NON-NLS-1$
                            authorization.setPass("${AUTH_PASSWORD}");//$NON-NLS-1$

                        }
                    }
                    // remove HEADER_AUTHORIZATION from HeaderManager 
                    // because it's useless after creating Authorization object
                    iterator.remove();
                }
            }
        }
    }
    return authorization;
}