Search in sources :

Example 76 with MalformedURLException

use of java.net.MalformedURLException in project OpenAM by OpenRock.

the class AMSetupUtils method getRemoteServerInfo.

/**
     * Obtains misc config data from a remote OpenAM server:
     * <ul>
     *     <li>OpendDJ admin port</li>
     *     <li>config basedn</li>
     *     <li>replication ready flag</li>
     *     <li>OpenDJ replication port or OpenDJ suggested port</li>
     * </ul>
     *
     * @param serverUrl URL string representing the remote OpenAM server.
     * @param userId The admin user id on remote server, (only amadmin).
     * @param password The admin password.
     * @return A {@code Map} of config parameters.
     * @throws ConfigurationException for the following error code:
     * <ul>
     *     <li>400=Bad Request - user id/password param missing</li>
     *     <li>401=Unauthorized - invalid credentials</li>
     *     <li>405=Method Not Allowed - only POST is honored</li>
     *     <li>408=Request Timeout - requested timed out</li>
     *     <li>500=Internal Server Error</li>
     *     <li>701=File Not Found - incorrect deploy/server uri</li>
     *     <li>702=Connection Error - failed to connect</li>
     * </ul>
     */
public static Map<String, String> getRemoteServerInfo(String serverUrl, String userId, String password) throws ConfigurationException {
    HttpURLConnection connection = null;
    try {
        connection = openConnection(serverUrl + "/getServerInfo.jsp");
        writeToConnection(connection, "IDToken1=" + URLEncoder.encode(userId, "UTF-8") + "&IDToken2=" + URLEncoder.encode(password, "UTF-8"));
        // Remove any additional /n's from the result, often seen at the beginning of the response.
        return BootstrapData.queryStringToMap(readFromConnection(connection).replace("\n", ""));
    } catch (IllegalArgumentException e) {
        debug.warning("AMSetupUtils.getRemoteServerInfo()", e);
        throw newConfigurationException("702");
    } catch (IOException e) {
        debug.warning("AMSetupUtils.getRemoteServerInfo()", e);
        if (e instanceof FileNotFoundException) {
            throw newConfigurationException("701");
        } else if (e instanceof SSLHandshakeException || e instanceof MalformedURLException || e instanceof UnknownHostException || e instanceof ConnectException) {
            throw newConfigurationException("702");
        } else {
            int status = 0;
            if (connection != null) {
                try {
                    status = connection.getResponseCode();
                } catch (Exception ignored) {
                }
            }
            if (status == 400 || status == 401 || status == 405 || status == 408) {
                throw newConfigurationException(String.valueOf(status));
            } else {
                throw new ConfiguratorException(e.getMessage());
            }
        }
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) HttpURLConnection(java.net.HttpURLConnection) UnknownHostException(java.net.UnknownHostException) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) ConnectException(java.net.ConnectException) MalformedURLException(java.net.MalformedURLException) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) FileNotFoundException(java.io.FileNotFoundException) ConfigurationException(com.sun.identity.common.configuration.ConfigurationException) ConnectException(java.net.ConnectException)

Example 77 with MalformedURLException

use of java.net.MalformedURLException in project OpenAM by OpenRock.

the class RequestTokenRequest method postReqTokenRequest.

/**
     * POST method for creating a request for a Request Token
     * @param content representation for the resource
     * @return an HTTP response with content of the updated or created resource.
     */
@POST
@Consumes("application/x-www-form-urlencoded")
@Produces("application/x-www-form-urlencoded")
public Response postReqTokenRequest(@Context HttpContext hc, String content) {
    boolean sigIsOk = false;
    OAuthResourceManager oauthResMgr = OAuthResourceManager.getInstance();
    try {
        OAuthServerRequest request = new OAuthServerRequest(hc.getRequest());
        OAuthParameters params = new OAuthParameters();
        params.readRequest(request);
        String tok = params.getToken();
        if ((tok != null) && (!tok.contentEquals("")))
            throw new WebApplicationException(new Throwable(OAUTH_TOKEN + " MUST not be present."), BAD_REQUEST);
        String conskey = params.getConsumerKey();
        if (conskey == null) {
            throw new WebApplicationException(new Throwable("Consumer key is missing."), BAD_REQUEST);
        }
        String signatureMethod = params.getSignatureMethod();
        if (signatureMethod == null) {
            throw new WebApplicationException(new Throwable("Signature Method is missing."), BAD_REQUEST);
        }
        String callback = params.get(OAUTH_CALLBACK);
        if ((callback == null) || (callback.isEmpty())) {
            throw new WebApplicationException(new Throwable("Callback URL is missing."), BAD_REQUEST);
        }
        if (!callback.equals(OAUTH_OOB)) {
            try {
                URL url = new URL(callback);
            } catch (MalformedURLException me) {
                throw new WebApplicationException(new Throwable("Callback URL is not valid."), BAD_REQUEST);
            }
        }
        Map<String, String> searchMap = new HashMap<String, String>();
        searchMap.put(CONSUMER_KEY, conskey);
        List<Consumer> consumers = oauthResMgr.searchConsumers(searchMap);
        if ((consumers != null) && (!consumers.isEmpty())) {
            cons = consumers.get(0);
        }
        if (cons == null) {
            throw new WebApplicationException(new Throwable("Consumer key invalid or service not registered"), BAD_REQUEST);
        }
        String secret = null;
        if (signatureMethod.equalsIgnoreCase(RSA_SHA1.NAME)) {
            secret = cons.getConsRsakey();
        } else {
            secret = cons.getConsSecret();
        }
        OAuthSecrets secrets = new OAuthSecrets().consumerSecret(secret).tokenSecret("");
        try {
            sigIsOk = OAuthSignature.verify(request, params, secrets);
        } catch (OAuthSignatureException ex) {
            Logger.getLogger(RequestTokenRequest.class.getName()).log(Level.SEVERE, null, ex);
        }
        if (!sigIsOk)
            throw new WebApplicationException(new Throwable("Signature invalid."), BAD_REQUEST);
        // We're good to go.
        RequestToken rt = new RequestToken();
        rt.setConsumerId(cons);
        String baseUri = context.getBaseUri().toString();
        if (baseUri.endsWith("/")) {
            baseUri = baseUri.substring(0, baseUri.length() - 1);
        }
        URI loc = URI.create(baseUri + PathDefs.REQUEST_TOKENS_PATH + "/" + new UniqueRandomString().getString());
        rt.setReqtUri(loc.toString());
        rt.setReqtSecret(new UniqueRandomString().getString());
        // Same value for now
        rt.setReqtVal(loc.toString());
        // Set the callback URL
        rt.setCallback(callback);
        //oauthResMgr.createConsumer(null, cons);
        oauthResMgr.createRequestToken(null, rt);
        String resp = OAUTH_TOKEN + "=" + rt.getReqtVal() + "&" + OAUTH_TOKEN_SECRET + "=" + rt.getReqtSecret() + "&" + OAUTH_CALLBACK_CONFIRMED + "=true";
        return Response.created(loc).entity(resp).type(MediaType.APPLICATION_FORM_URLENCODED).build();
    } catch (OAuthServiceException e) {
        Logger.getLogger(RequestTokenRequest.class.getName()).log(Level.SEVERE, null, e);
        throw new WebApplicationException(e);
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) UniqueRandomString(com.sun.identity.oauth.service.util.UniqueRandomString) WebApplicationException(javax.ws.rs.WebApplicationException) HashMap(java.util.HashMap) UniqueRandomString(com.sun.identity.oauth.service.util.UniqueRandomString) URI(java.net.URI) URL(java.net.URL) OAuthServerRequest(com.sun.jersey.oauth.server.OAuthServerRequest) Consumer(com.sun.identity.oauth.service.models.Consumer) RequestToken(com.sun.identity.oauth.service.models.RequestToken) OAuthParameters(com.sun.jersey.oauth.signature.OAuthParameters) OAuthSignatureException(com.sun.jersey.oauth.signature.OAuthSignatureException) OAuthSecrets(com.sun.jersey.oauth.signature.OAuthSecrets) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces)

Example 78 with MalformedURLException

use of java.net.MalformedURLException in project OpenAM by OpenRock.

the class ClientBase method callServiceURL.

public RESTResponse callServiceURL(String url, String postData) throws MalformedURLException, IOException {
    URL serviceURL = null;
    HttpURLConnection urlConnect = null;
    DataOutputStream output = null;
    BufferedReader reader = null;
    RESTResponse response = new RESTResponse();
    ArrayList returnList = new ArrayList();
    try {
        serviceURL = new URL(url);
        urlConnect = HttpURLConnectionManager.getConnection(serviceURL);
        urlConnect.setRequestMethod("POST");
        urlConnect.setDoOutput(true);
        urlConnect.setUseCaches(false);
        urlConnect.setConnectTimeout(10000);
        urlConnect.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        // send(post) data
        output = new DataOutputStream(urlConnect.getOutputStream());
        output.writeBytes(postData);
        output.flush();
        output.close();
        output = null;
        // read response
        response.setResponseCode(urlConnect.getResponseCode());
        reader = new BufferedReader(new InputStreamReader(urlConnect.getInputStream()));
        String line;
        while ((line = reader.readLine()) != null) {
            returnList.add(line);
        }
    } catch (java.io.FileNotFoundException ex) {
        throw ex;
    } catch (IOException ex) {
        InputStream is = urlConnect.getErrorStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line = null;
        while ((line = br.readLine()) != null) {
            returnList.add(line);
        }
        Debug.getInstance(DEBUG_NAME).error("ClientBase.callServiceURL: " + "IOException from server", ex);
    } finally {
        if (output != null) {
            try {
                output.close();
            } catch (Exception ex) {
            }
        }
        if (reader != null) {
            try {
                reader.close();
            } catch (Exception ex) {
            }
        }
    }
    response.setContent(returnList);
    return response;
}
Also used : InputStreamReader(java.io.InputStreamReader) DataOutputStream(java.io.DataOutputStream) BufferedInputStream(java.io.BufferedInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) IOException(java.io.IOException) URL(java.net.URL) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) HttpURLConnection(java.net.HttpURLConnection) BufferedReader(java.io.BufferedReader)

Example 79 with MalformedURLException

use of java.net.MalformedURLException in project OpenAM by OpenRock.

the class ServiceBase method isServerRunning.

/**
     * Method to check if the server instance is running
     *
     * @param url server instance URL
     * @return <code>true</code> if server instance is running
     */
protected static boolean isServerRunning(URL url) {
    boolean isSvrRunning = false;
    try {
        URLConnection uc = HttpURLConnectionManager.getConnection(url);
        BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
        isSvrRunning = true;
    } catch (MalformedURLException mfe) {
        Debug.getInstance(DEBUG_NAME).error("ServiceBase.isServerRunning : " + "Exception in getting server URL", mfe);
    } catch (IOException ioe) {
        Debug.getInstance(DEBUG_NAME).error("ServiceBase.isServerRunning : " + "Exception in connecting to server URL", ioe);
    }
    return isSvrRunning;
}
Also used : MalformedURLException(java.net.MalformedURLException) InputStreamReader(java.io.InputStreamReader) BufferedReader(java.io.BufferedReader) IOException(java.io.IOException) HttpURLConnection(java.net.HttpURLConnection) URLConnection(java.net.URLConnection) HttpsURLConnection(javax.net.ssl.HttpsURLConnection)

Example 80 with MalformedURLException

use of java.net.MalformedURLException in project android_frameworks_base by ResurrectionRemix.

the class OSUManager method doRemediate.

private void doRemediate(String url, Network network, HomeSP homeSP, boolean policy) throws IOException {
    synchronized (mWifiNetworkAdapter) {
        OSUThread existing = mServiceThreads.get(homeSP.getFQDN());
        if (existing != null) {
            if (System.currentTimeMillis() - existing.getLaunchTime() > REMEDIATION_TIMEOUT) {
                throw new IOException("Ignoring recurring remediation request");
            } else {
                existing.connect(null);
            }
        }
        try {
            OSUThread osuThread = new OSUThread(url, this, getKeyManager(homeSP, mKeyStore), homeSP, policy ? FLOW_POLICY : FLOW_REMEDIATION);
            osuThread.start();
            osuThread.connect(network);
            mServiceThreads.put(homeSP.getFQDN(), osuThread);
        } catch (MalformedURLException me) {
            throw new IOException("Failed to start remediation: " + me);
        }
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException)

Aggregations

MalformedURLException (java.net.MalformedURLException)3838 URL (java.net.URL)2885 IOException (java.io.IOException)1194 File (java.io.File)910 ArrayList (java.util.ArrayList)372 InputStream (java.io.InputStream)367 HttpURLConnection (java.net.HttpURLConnection)295 URISyntaxException (java.net.URISyntaxException)270 URI (java.net.URI)239 InputStreamReader (java.io.InputStreamReader)226 BufferedReader (java.io.BufferedReader)208 HashMap (java.util.HashMap)200 URLClassLoader (java.net.URLClassLoader)168 Map (java.util.Map)166 URLConnection (java.net.URLConnection)148 FileNotFoundException (java.io.FileNotFoundException)137 Matcher (java.util.regex.Matcher)132 Test (org.junit.Test)129 UnsupportedEncodingException (java.io.UnsupportedEncodingException)119 Pattern (java.util.regex.Pattern)113