Example usage for java.net URISyntaxException printStackTrace

List of usage examples for java.net URISyntaxException printStackTrace

Introduction

In this page you can find the example usage for java.net URISyntaxException printStackTrace.

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:org.opendatakit.aggregate.externalservice.AbstractExternalService.java

protected HttpResponse sendHttpRequest(String method, String url, HttpEntity entity,
        List<NameValuePair> qparams, CallingContext cc) throws IOException {

    HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, SOCKET_ESTABLISHMENT_TIMEOUT_MILLISECONDS);
    HttpConnectionParams.setSoTimeout(httpParams, SERVICE_TIMEOUT_MILLISECONDS);

    // setup client
    HttpClientFactory factory = (HttpClientFactory) cc.getBean(BeanDefs.HTTP_CLIENT_FACTORY);
    HttpClient client = factory.createHttpClient(httpParams);

    // support redirecting to handle http: => https: transition
    HttpClientParams.setRedirecting(httpParams, true);
    // support authenticating
    HttpClientParams.setAuthenticating(httpParams, true);

    // redirect limit is set to some unreasonably high number
    // resets of the socket cause a retry up to MAX_REDIRECTS times,
    // so we should be careful not to set this too high...
    httpParams.setParameter(ClientPNames.MAX_REDIRECTS, 32);
    httpParams.setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);

    // context holds authentication state machine, so it cannot be
    // shared across independent activities.
    HttpContext localContext = new BasicHttpContext();

    localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
    localContext.setAttribute(ClientContext.CREDS_PROVIDER, credsProvider);

    HttpUriRequest request = null;/*from  w w w  .j  a v a 2s. c o  m*/
    if (entity == null && (POST.equals(method) || PATCH.equals(method) || PUT.equals(method))) {
        throw new IllegalStateException("No body supplied for POST, PATCH or PUT request");
    } else if (entity != null && !(POST.equals(method) || PATCH.equals(method) || PUT.equals(method))) {
        throw new IllegalStateException("Body was supplied for GET or DELETE request");
    }

    URI nakedUri;
    try {
        nakedUri = new URI(url);
    } catch (Exception e) {
        e.printStackTrace();
        throw new IllegalStateException(e);
    }

    if (qparams == null) {
        qparams = new ArrayList<NameValuePair>();
    }
    URI uri;
    try {
        uri = new URI(nakedUri.getScheme(), nakedUri.getUserInfo(), nakedUri.getHost(), nakedUri.getPort(),
                nakedUri.getPath(), URLEncodedUtils.format(qparams, HtmlConsts.UTF8_ENCODE), null);
    } catch (URISyntaxException e1) {
        e1.printStackTrace();
        throw new IllegalStateException(e1);
    }
    System.out.println(uri.toString());

    if (GET.equals(method)) {
        HttpGet get = new HttpGet(uri);
        request = get;
    } else if (DELETE.equals(method)) {
        HttpDelete delete = new HttpDelete(uri);
        request = delete;
    } else if (PATCH.equals(method)) {
        HttpPatch patch = new HttpPatch(uri);
        patch.setEntity(entity);
        request = patch;
    } else if (POST.equals(method)) {
        HttpPost post = new HttpPost(uri);
        post.setEntity(entity);
        request = post;
    } else if (PUT.equals(method)) {
        HttpPut put = new HttpPut(uri);
        put.setEntity(entity);
        request = put;
    } else {
        throw new IllegalStateException("Unexpected request method");
    }

    HttpResponse resp = client.execute(request);
    return resp;
}

From source file:org.opendatakit.common.security.spring.Oauth2ResourceFilter.java

private Map<String, Object> getJsonResponse(String url, String accessToken) {

    Map<String, Object> nullData = new HashMap<String, Object>();

    // OK if we got here, we have a valid token.
    // Issue the request...
    URI nakedUri;//from www.ja  va  2s  .co  m
    try {
        nakedUri = new URI(url);
    } catch (URISyntaxException e2) {
        e2.printStackTrace();
        logger.error(e2.toString());
        return nullData;
    }

    List<NameValuePair> qparams = new ArrayList<NameValuePair>();
    qparams.add(new BasicNameValuePair("access_token", accessToken));
    URI uri;
    try {
        uri = new URI(nakedUri.getScheme(), nakedUri.getUserInfo(), nakedUri.getHost(), nakedUri.getPort(),
                nakedUri.getPath(), URLEncodedUtils.format(qparams, "UTF-8"), null);
    } catch (URISyntaxException e1) {
        e1.printStackTrace();
        logger.error(e1.toString());
        return nullData;
    }

    // DON'T NEED clientId on the toke request...
    // addCredentials(clientId, clientSecret, nakedUri.getHost());
    // setup request interceptor to do preemptive auth
    // ((DefaultHttpClient) client).addRequestInterceptor(getPreemptiveAuth(), 0);

    HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, SERVICE_TIMEOUT_MILLISECONDS);
    HttpConnectionParams.setSoTimeout(httpParams, SOCKET_ESTABLISHMENT_TIMEOUT_MILLISECONDS);
    // support redirecting to handle http: => https: transition
    HttpClientParams.setRedirecting(httpParams, true);
    // support authenticating
    HttpClientParams.setAuthenticating(httpParams, true);

    httpParams.setParameter(ClientPNames.MAX_REDIRECTS, 1);
    httpParams.setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
    // setup client
    HttpClient client = httpClientFactory.createHttpClient(httpParams);

    HttpGet httpget = new HttpGet(uri);
    logger.info(httpget.getURI().toString());

    HttpResponse response = null;
    try {
        response = client.execute(httpget, new BasicHttpContext());
        int statusCode = response.getStatusLine().getStatusCode();

        if (statusCode != HttpStatus.SC_OK) {
            logger.error("not 200: " + statusCode);
            return nullData;
        } else {
            HttpEntity entity = response.getEntity();

            if (entity != null && entity.getContentType().getValue().toLowerCase().contains("json")) {
                BufferedReader reader = null;
                InputStreamReader isr = null;
                try {
                    reader = new BufferedReader(isr = new InputStreamReader(entity.getContent()));
                    @SuppressWarnings("unchecked")
                    Map<String, Object> userData = mapper.readValue(reader, Map.class);
                    return userData;
                } finally {
                    if (reader != null) {
                        try {
                            reader.close();
                        } catch (IOException e) {
                            // ignore
                        }
                    }
                    if (isr != null) {
                        try {
                            isr.close();
                        } catch (IOException e) {
                            // ignore
                        }
                    }
                }
            } else {
                logger.error("unexpected body");
                return nullData;
            }
        }
    } catch (IOException e) {
        logger.error(e.toString());
        return nullData;
    } catch (Exception e) {
        logger.error(e.toString());
        return nullData;
    }
}

From source file:info.rmapproject.core.model.impl.openrdf.ORMapDiscoTest.java

/**
 * Test method for {@link info.rmapproject.core.model.impl.openrdf.ORMapDiSCO#getTypeStatement()}.
 * @throws RMapDefectiveArgumentException 
 * @throws RMapException //from w w  w .ja  v a2  s  . c o m
 */
@Test
public void testGetTypeStatement() throws RMapException, RMapDefectiveArgumentException {
    List<java.net.URI> resourceList = new ArrayList<java.net.URI>();
    try {
        resourceList.add(new java.net.URI("http://rmap-info.org"));
        resourceList.add(new java.net.URI("https://rmap-project.atlassian.net/wiki/display/RMAPPS/RMap+Wiki"));
        RMapIri author = ORAdapter.openRdfIri2RMapIri(creatorIRI);
        ORMapDiSCO disco = new ORMapDiSCO(author, resourceList);
        Statement stmt = disco.getTypeStatement();
        assertEquals(disco.getId().getStringValue(), stmt.getSubject().stringValue());
        assertEquals(RDF.TYPE, stmt.getPredicate());
        assertEquals(RMAP.DISCO, stmt.getObject());
    } catch (URISyntaxException e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
}

From source file:org.xwiki.android.test.utils.xmlrpc.RestClient.java

/**
 * Perform HTTP Get method execution and return the response as a String
 *
 * @param Uri URL of XWiki RESTful API//from   ww w.j  a  v a  2  s  .c o  m
 * @return Response data of the HTTP connection as a String
 */
public HttpResponse getRequest(String Uri) throws IOException, RestException {

    BufferedReader in = null;
    HttpGet request = new HttpGet();
    String responseText = new String();

    try {
        URI requestUri = new URI(Uri);
        request.setURI(requestUri);
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }
    log.debug("Request URL :" + Uri);
    try {

        HttpResponse response = client.execute(request);
        log.debug("Response status", response.getStatusLine().toString());
        in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        StringBuffer sb = new StringBuffer("");
        String line = "";
        String NL = System.getProperty("line.separator");
        while ((line = in.readLine()) != null) {
            sb.append(line + NL);
        }
        responseText = sb.toString();
        log.debug("Response", "response: " + responseText);
        validate(response.getStatusLine().getStatusCode());
        return response;
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        return null;
    } finally {
        if (in != null) {
            in.close();
        }
    }
}

From source file:edu.cornell.med.icb.goby.modes.GenericToolsDriver.java

/**
 * Retrieve the class names of the likely modes.
 *
 * @return the list of class names//  w  w w  .  j ava 2  s .  co m
 */
private List<String> modesClassNamesList() {
    final List<String> modesList = new LinkedList<String>();
    try {
        final String modesPackage = ClassUtils.getPackageName(getClass());
        final String[] files = new ResourceFinder().getResourceListing(getClass());
        for (final String file : files) {
            if (file.endsWith("Mode.class")) {
                // Keep only classes whose class name end in "Mode"
                final String modeClassName = modesPackage + "." + file.substring(0, file.length() - 6);
                modesList.add(modeClassName);
            }
        }
    } catch (URISyntaxException e) {
        System.err.println("Could not list mode class names URISyntaxException: " + e.getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        System.err.println("Could not list mode class names IOException: " + e.getMessage());
        e.printStackTrace();
    }
    return modesList;
}

From source file:info.rmapproject.core.model.impl.openrdf.ORMapDiscoTest.java

/**
 * Test method for {@link info.rmapproject.core.model.impl.openrdf.ORMapDiSCO#getDiscoContext()}.
 * @throws RMapDefectiveArgumentException 
 * @throws RMapException //from w w  w  .  j  a  v a2s.c o m
 */
@Test
public void testGetDiscoContext() throws RMapException, RMapDefectiveArgumentException {
    List<java.net.URI> resourceList = new ArrayList<java.net.URI>();
    try {
        resourceList.add(new java.net.URI("http://rmap-info.org"));
        resourceList.add(new java.net.URI("https://rmap-project.atlassian.net/wiki/display/RMAPPS/RMap+Wiki"));
        RMapIri author = ORAdapter.openRdfIri2RMapIri(creatorIRI);
        ORMapDiSCO disco = new ORMapDiSCO(author, resourceList);
        IRI context = disco.getDiscoContext();
        Model model = new LinkedHashModel();
        for (Statement stm : model) {
            assertEquals(context, stm.getContext());
        }
    } catch (URISyntaxException e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
}

From source file:org.xwiki.android.test.utils.xmlrpc.RestClient.java

/**
 * Perform HTTP Put method execution and return its response status
 *
 * @param Uri     URL of XWiki RESTful API
 * @param content content to be posted to the server
 * @return status code of the Put method execution
 * @throws IOException/*w  w w  .  j a  va2  s . c  o m*/
 * @throws RestException
 */
public HttpResponse putRequest(String Uri, String content) throws IOException, RestException {

    HttpPut request = new HttpPut();

    try {
        log.debug("Request URL :" + Uri);
        System.out.println(Uri);
        URI requestUri = new URI(Uri);
        request.setURI(requestUri);
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }

    try {
        log.debug("Put content", "content=" + content);
        StringEntity se = new StringEntity(content, "UTF-8");

        se.setContentType("application/xml");
        // se.setContentType("text/plain");
        request.setEntity(se);
        request.setHeader("Content-Type", "application/xml;charset=UTF-8");

        HttpResponse response = client.execute(request);
        log.debug("Response status", response.getStatusLine().toString());
        EntityUtils.consume(response.getEntity());//close the stream to releas resources. //TODO: [ignore since test utils.]ideally this should be closed after content is read (if needed) by requester. So move it to PageOps etc.
        validate(response.getStatusLine().getStatusCode());
        return response;

    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        throw new IOException(e);
    }

    return null;
}

From source file:info.rmapproject.core.model.impl.openrdf.ORMapDiscoTest.java

/**
 * Test method for {@link info.rmapproject.core.model.impl.openrdf.ORMapDiSCO#setDescription(RMapValue)}.
 * @throws RMapDefectiveArgumentException 
 * @throws RMapException //from  w ww.  j  a  va 2s.c  o m
 */
@Test
public void testSetDescription() throws RMapException, RMapDefectiveArgumentException {
    List<java.net.URI> resourceList = new ArrayList<java.net.URI>();
    try {
        resourceList.add(new java.net.URI("http://rmap-info.org"));
        resourceList.add(new java.net.URI("https://rmap-project.atlassian.net/wiki/display/RMAPPS/RMap+Wiki"));
        RMapIri author = ORAdapter.openRdfIri2RMapIri(creatorIRI);
        ORMapDiSCO disco = new ORMapDiSCO(author, resourceList);
        Literal desc = vf.createLiteral("this is a description");
        RMapValue rdesc = ORAdapter.openRdfValue2RMapValue(desc);
        disco.setDescription(rdesc);
        RMapValue gDesc = disco.getDescription();
        assertEquals(rdesc.getStringValue(), gDesc.getStringValue());
        Statement descSt = disco.getDescriptonStatement();
        assertEquals(desc, descSt.getObject());
    } catch (URISyntaxException e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
}

From source file:com.oDesk.api.OAuthClient.java

/**
 * Send signed GET OAuth request/*  www .j a  va2 s.c o  m*/
 * 
 * @param   url Relative URL
 * @param   type Type of HTTP request (HTTP method)
 * @param   params Hash of parameters
 * @throws   JSONException If JSON object is invalid or request was abnormal
 * @return   {@link JSONObject} JSON Object that contains data from response
 * */
private JSONObject sendGetRequest(String url, Integer type, HashMap<String, String> params)
        throws JSONException {
    String fullUrl = getFullUrl(url);
    HttpGet request = new HttpGet(fullUrl);

    if (params != null) {
        URI uri;
        String query = "";
        try {
            URIBuilder uriBuilder = new URIBuilder(request.getURI());

            // encode values and add them to the request
            for (Map.Entry<String, String> entry : params.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                // to prevent double encoding, we need to create query string ourself
                // uriBuilder.addParameter(key, URLEncoder.encode(value).replace("%3B", ";"));
                query = query + key + "=" + value + "&";
            }
            uriBuilder.setCustomQuery(query);
            uri = uriBuilder.build();

            ((HttpRequestBase) request).setURI(uri);
        } catch (URISyntaxException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    try {
        mOAuthConsumer.sign(request);
    } catch (OAuthException e) {
        e.printStackTrace();
    }

    return oDeskRestClient.getJSONObject(request, type);
}

From source file:info.rmapproject.core.model.impl.openrdf.ORMapDiscoTest.java

/**
 * Test method for {@link info.rmapproject.core.model.impl.openrdf.ORMapDiSCO#setCreator(RMapIri)}.
 * @throws RMapDefectiveArgumentException 
 * @throws RMapException /* w  w w  .  j  a  v  a2 s . c  om*/
 */
@Test
public void testSetCreator() throws RMapException, RMapDefectiveArgumentException {
    List<java.net.URI> resourceList = new ArrayList<java.net.URI>();
    try {
        resourceList.add(new java.net.URI("http://rmap-info.org"));
        resourceList.add(new java.net.URI("https://rmap-project.atlassian.net/wiki/display/RMAPPS/RMap+Wiki"));
        RMapIri author = ORAdapter.openRdfIri2RMapIri(creatorIRI);
        ORMapDiSCO disco = new ORMapDiSCO(author, resourceList);
        assertEquals(author.toString(), disco.getCreator().getStringValue());
        try {
            RMapIri author2 = ORAdapter.openRdfIri2RMapIri(creatorIRI2);
            disco.setCreator(author2);
            assertEquals(author2.toString(), disco.getCreator().getStringValue());
        } catch (RMapException r) {
            fail(r.getMessage());
        }

    } catch (URISyntaxException e) {
        e.printStackTrace();
        fail(e.getMessage());
    }

}