Example usage for java.net URISyntaxException getMessage

List of usage examples for java.net URISyntaxException getMessage

Introduction

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

Prototype

public String getMessage() 

Source Link

Document

Returns a string describing the parse error.

Usage

From source file:com.silverpeas.export.ical.ical4j.ICal4JICalCodec.java

@Override
@SuppressWarnings("unchecked")
public String encode(List<CalendarEvent> events) {

    if (events == null || events.isEmpty()) {
        throw new IllegalArgumentException("The calendar events must be defined to encode them");
    }//from  w ww  .j  a  v a2 s  . com
    Calendar calendarIcs = new Calendar();
    calendarIcs.getProperties().add(new ProdId("-//Silverpeas//iCal4j 1.1//FR"));
    calendarIcs.getProperties().add(Version.VERSION_2_0);
    calendarIcs.getProperties().add(CalScale.GREGORIAN);
    List<VEvent> iCalEvents = new ArrayList<VEvent>();
    ByteArrayOutputStream output = new ByteArrayOutputStream(10240);
    for (CalendarEvent event : events) {
        Date startDate = anICal4JDateCodec().encode(event.getStartDate());
        Date endDate = anICal4JDateCodec().encode(event.getEndDate());
        VEvent iCalEvent;
        if (event.isOnAllDay() && startDate.equals(endDate)) {
            iCalEvent = new VEvent(startDate, event.getTitle());
        } else {
            iCalEvent = new VEvent(startDate, endDate, event.getTitle());
        }

        // Generate UID
        iCalEvent.getProperties().add(generator.generateUid());

        // Add recurring data if any
        if (event.isRecurring()) {
            CalendarEventRecurrence eventRecurrence = event.getRecurrence();
            Recur recur = anICal4JRecurrenceCodec().encode(eventRecurrence);
            iCalEvent.getProperties().add(new RRule(recur));
            iCalEvent.getProperties().add(exceptionDatesFrom(eventRecurrence));
        }
        // Add Description
        iCalEvent.getProperties().add(new Description(event.getDescription()));
        // Add Classification
        iCalEvent.getProperties().add(new Clazz(event.getAccessLevel()));
        // Add Priority
        iCalEvent.getProperties().add(new Priority(event.getPriority()));

        // Add location if any
        if (!event.getLocation().isEmpty()) {
            iCalEvent.getProperties().add(new Location(event.getLocation()));
        }

        // Add event URL if any
        if (event.getUrl() != null) {
            try {
                iCalEvent.getProperties().add(new Url(event.getUrl().toURI()));
            } catch (URISyntaxException ex) {
                throw new EncodingException(ex.getMessage(), ex);
            }
        }

        // Add Categories
        TextList categoryList = new TextList(event.getCategories().asArray());
        if (!categoryList.isEmpty()) {
            iCalEvent.getProperties().add(new Categories(categoryList));
        }
        // Add attendees
        for (String attendee : event.getAttendees().asList()) {
            try {
                iCalEvent.getProperties().add(new Attendee(attendee));
            } catch (URISyntaxException ex) {
                throw new EncodingException("Malformed attendee URI: " + attendee, ex);
            }
        }

        iCalEvents.add(iCalEvent);
    }
    calendarIcs.getComponents().addAll(iCalEvents);
    CalendarOutputter outputter = new CalendarOutputter();
    try {
        outputter.output(calendarIcs, output);
        return output.toString(CharEncoding.UTF_8);
    } catch (Exception ex) {
        throw new EncodingException("The encoding of the events in iCal formatted text has failed!", ex);
    } finally {
        IOUtils.closeQuietly(output);
    }
}

From source file:tech.beshu.ror.httpclient.ApacheHttpCoreClient.java

@Override
public CompletableFuture<RRHttpResponse> send(RRHttpRequest request) {

    CompletableFuture<HttpResponse> promise = new CompletableFuture<>();
    URI uri;//from   www  .j  a v a  2 s  .c  o m
    HttpRequestBase hcRequest;
    try {
        if (request.getMethod() == HttpMethod.POST) {
            uri = new URIBuilder(request.getUrl().toASCIIString()).build();
            hcRequest = new HttpPost(uri);
            List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
            request.getQueryParams().entrySet()
                    .forEach(x -> urlParameters.add(new BasicNameValuePair(x.getKey(), x.getValue())));
            ((HttpPost) hcRequest).setEntity(new UrlEncodedFormEntity(urlParameters));

        } else {
            uri = new URIBuilder(request.getUrl().toASCIIString()).addParameters(request.getQueryParams()
                    .entrySet().stream().map(e -> new BasicNameValuePair(e.getKey(), e.getValue()))
                    .collect(Collectors.toList())).build();
            hcRequest = new HttpGet(uri);
        }
    } catch (URISyntaxException e) {
        throw context.rorException(e.getClass().getSimpleName() + ": " + e.getMessage());
    } catch (UnsupportedEncodingException e) {
        throw context.rorException(e.getClass().getSimpleName() + ": " + e.getMessage());
    }

    request.getHeaders().entrySet().forEach(e -> hcRequest.addHeader(e.getKey(), e.getValue()));

    AccessController.doPrivileged((PrivilegedAction<Void>) () -> {

        hcHttpClient.execute(hcRequest, new FutureCallback<HttpResponse>() {

            public void completed(final HttpResponse hcResponse) {
                int statusCode = hcResponse.getStatusLine().getStatusCode();
                logger.debug("HTTP REQ SUCCESS with status: " + statusCode + " " + request);
                promise.complete(hcResponse);
            }

            public void failed(final Exception ex) {
                logger.debug("HTTP REQ FAILED " + request);
                logger.info("HTTP client failed to connect: " + request + " reason: " + ex.getMessage());
                promise.completeExceptionally(ex);
            }

            public void cancelled() {
                promise.completeExceptionally(new RuntimeException("HTTP REQ CANCELLED: " + request));
            }
        });
        return null;
    });

    return promise.thenApply(hcResp -> new RRHttpResponse(hcResp.getStatusLine().getStatusCode(), () -> {
        try {
            return hcResp.getEntity().getContent();
        } catch (IOException e) {
            throw new RuntimeException("Cannot read content", e);
        }
    }));

}

From source file:com.cws.esolutions.core.utils.NetworkUtils.java

/**
 * Creates an HTTP connection to a provided website and returns the data back
 * to the requestor./* w  w  w .  j  a va 2  s  .  com*/
 *
 * @param hostName - The fully qualified URL for the host desired. MUST be
 *     prefixed with http/https:// as necessary
 * @param methodType - GET or POST, depending on what is necessary
 * @return A object containing the response data
 * @throws UtilityException {@link com.cws.esolutions.core.utils.exception.UtilityException} if an error occurs processing
 */
public static final synchronized Object executeHttpConnection(final URL hostName, final String methodType)
        throws UtilityException {
    final String methodName = NetworkUtils.CNAME
            + "#executeHttpConnection(final URL hostName, final String methodType) throws UtilityException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", hostName);
        DEBUGGER.debug("Value: {}", methodType);
    }

    RequestConfig requestConfig = null;
    CloseableHttpClient httpClient = null;
    CredentialsProvider credsProvider = null;
    CloseableHttpResponse httpResponse = null;

    final HttpClientParams httpParams = new HttpClientParams();
    final HTTPConfig httpConfig = appBean.getConfigData().getHttpConfig();
    final ProxyConfig proxyConfig = appBean.getConfigData().getProxyConfig();

    if (DEBUG) {
        DEBUGGER.debug("HttpClient: {}", httpClient);
        DEBUGGER.debug("HttpClientParams: {}", httpParams);
        DEBUGGER.debug("HTTPConfig: {}", httpConfig);
        DEBUGGER.debug("ProxyConfig: {}", proxyConfig);
    }
    try {
        final URI requestURI = new URIBuilder().setScheme(hostName.getProtocol()).setHost(hostName.getHost())
                .setPort(hostName.getPort()).build();

        if (StringUtils.isNotEmpty(httpConfig.getTrustStoreFile())) {
            System.setProperty("javax.net.ssl.trustStoreType",
                    (StringUtils.isNotEmpty(httpConfig.getTrustStoreType()) ? httpConfig.getTrustStoreType()
                            : "jks"));
            System.setProperty("javax.net.ssl.trustStore", httpConfig.getTrustStoreFile());
            System.setProperty("javax.net.ssl.trustStorePassword",
                    PasswordUtils.decryptText(httpConfig.getTrustStorePass(), httpConfig.getTrustStoreSalt(),
                            secBean.getConfigData().getSecurityConfig().getEncryptionAlgorithm(),
                            secBean.getConfigData().getSecurityConfig().getIterations(),
                            secBean.getConfigData().getSecurityConfig().getKeyBits(),
                            secBean.getConfigData().getSecurityConfig().getEncryptionAlgorithm(),
                            secBean.getConfigData().getSecurityConfig().getEncryptionInstance(),
                            appBean.getConfigData().getSystemConfig().getEncoding()));
        }

        if (StringUtils.isNotEmpty(httpConfig.getKeyStoreFile())) {
            System.setProperty("javax.net.ssl.keyStoreType",
                    (StringUtils.isNotEmpty(httpConfig.getKeyStoreType()) ? httpConfig.getKeyStoreType()
                            : "jks"));
            System.setProperty("javax.net.ssl.keyStore", httpConfig.getKeyStoreFile());
            System.setProperty("javax.net.ssl.keyStorePassword",
                    PasswordUtils.decryptText(httpConfig.getKeyStorePass(), httpConfig.getKeyStoreSalt(),
                            secBean.getConfigData().getSecurityConfig().getEncryptionAlgorithm(),
                            secBean.getConfigData().getSecurityConfig().getIterations(),
                            secBean.getConfigData().getSecurityConfig().getKeyBits(),
                            secBean.getConfigData().getSecurityConfig().getEncryptionAlgorithm(),
                            secBean.getConfigData().getSecurityConfig().getEncryptionInstance(),
                            appBean.getConfigData().getSystemConfig().getEncoding()));
        }

        if (proxyConfig.isProxyServiceRequired()) {
            if (DEBUG) {
                DEBUGGER.debug("ProxyConfig: {}", proxyConfig);
            }

            if (StringUtils.isEmpty(proxyConfig.getProxyServerName())) {
                throw new UtilityException(
                        "Configuration states proxy usage is required, but no proxy is configured.");
            }

            if (proxyConfig.isProxyAuthRequired()) {
                List<String> authList = new ArrayList<String>();
                authList.add(AuthPolicy.BASIC);
                authList.add(AuthPolicy.DIGEST);
                authList.add(AuthPolicy.NTLM);

                if (DEBUG) {
                    DEBUGGER.debug("authList: {}", authList);
                }

                requestConfig = RequestConfig.custom()
                        .setConnectionRequestTimeout(
                                (int) TimeUnit.SECONDS.toMillis(httpConfig.getConnTimeout()))
                        .setConnectTimeout((int) TimeUnit.SECONDS.toMillis(httpConfig.getConnTimeout()))
                        .setContentCompressionEnabled(Boolean.TRUE)
                        .setProxy(new HttpHost(proxyConfig.getProxyServerName(),
                                proxyConfig.getProxyServerPort()))
                        .setProxyPreferredAuthSchemes(authList).build();

                if (DEBUG) {
                    DEBUGGER.debug("requestConfig: {}", requestConfig);
                }

                String proxyPwd = PasswordUtils.decryptText(proxyConfig.getProxyPassword(),
                        proxyConfig.getProxyPwdSalt(),
                        secBean.getConfigData().getSecurityConfig().getEncryptionAlgorithm(),
                        secBean.getConfigData().getSecurityConfig().getIterations(),
                        secBean.getConfigData().getSecurityConfig().getKeyBits(),
                        secBean.getConfigData().getSecurityConfig().getEncryptionAlgorithm(),
                        secBean.getConfigData().getSecurityConfig().getEncryptionInstance(),
                        appBean.getConfigData().getSystemConfig().getEncoding());

                if (DEBUG) {
                    DEBUGGER.debug("proxyPwd: {}", proxyPwd);
                }

                if (StringUtils.equals(NetworkUtils.PROXY_AUTH_TYPE_BASIC, proxyConfig.getProxyAuthType())) {
                    credsProvider = new SystemDefaultCredentialsProvider();
                    credsProvider.setCredentials(
                            new AuthScope(proxyConfig.getProxyServerName(), proxyConfig.getProxyServerPort()),
                            new UsernamePasswordCredentials(proxyConfig.getProxyUserId(), proxyPwd));
                } else if (StringUtils.equals(NetworkUtils.PROXY_AUTH_TYPE_NTLM,
                        proxyConfig.getProxyAuthType())) {
                    credsProvider = new SystemDefaultCredentialsProvider();
                    credsProvider.setCredentials(
                            new AuthScope(proxyConfig.getProxyServerName(), proxyConfig.getProxyServerPort()),
                            new NTCredentials(proxyConfig.getProxyUserId(), proxyPwd,
                                    InetAddress.getLocalHost().getHostName(),
                                    proxyConfig.getProxyAuthDomain()));
                }

                if (DEBUG) {
                    DEBUGGER.debug("httpClient: {}", httpClient);
                }
            }
        }

        synchronized (new Object()) {
            httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();

            if (StringUtils.equalsIgnoreCase(methodType, "POST")) {
                HttpPost httpMethod = new HttpPost(requestURI);
                httpMethod.setConfig(requestConfig);

                httpResponse = httpClient.execute(httpMethod);
            } else {
                HttpGet httpMethod = new HttpGet(requestURI);
                httpMethod.setConfig(requestConfig);

                httpResponse = httpClient.execute(httpMethod);
            }

            int responseCode = httpResponse.getStatusLine().getStatusCode();

            if (DEBUG) {
                DEBUGGER.debug("responseCode: {}", responseCode);
            }

            if (responseCode != 200) {
                ERROR_RECORDER.error("HTTP Response Code received NOT 200: " + responseCode);

                throw new UtilityException("HTTP Response Code received NOT 200: " + responseCode);
            }

            return httpResponse.getEntity().toString();
        }
    } catch (ConnectException cx) {
        throw new UtilityException(cx.getMessage(), cx);
    } catch (UnknownHostException ux) {
        throw new UtilityException(ux.getMessage(), ux);
    } catch (SocketException sx) {
        throw new UtilityException(sx.getMessage(), sx);
    } catch (IOException iox) {
        throw new UtilityException(iox.getMessage(), iox);
    } catch (URISyntaxException usx) {
        throw new UtilityException(usx.getMessage(), usx);
    } finally {
        if (httpResponse != null) {
            try {
                httpResponse.close();
            } catch (IOException iox) {
            } // dont do anything with it
        }
    }
}

From source file:org.dataconservancy.ui.it.support.CreatePersonRequest.java

public HttpPost asHttpPost() {
    if (!personSet) {
        throw new IllegalStateException("Person not set: call setPerson(Person) first.");
    }//from   w w w.ja v  a2 s.co  m

    HttpPost post = null;
    try {
        post = new HttpPost(urlConfig.getAddCollectionUrl().toURI());
    } catch (URISyntaxException e) {
        throw new RuntimeException(e.getMessage(), e);
    }

    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("person.id", id));
    params.add(new BasicNameValuePair("person.firstNames", firstNames));
    params.add(new BasicNameValuePair("person.lastNames", lastNames));
    params.add(new BasicNameValuePair("person.middleNames", middleNames));
    params.add(new BasicNameValuePair("person.prefix", prefix));
    params.add(new BasicNameValuePair("person.suffix", suffix));
    params.add(new BasicNameValuePair("person.preferredPubName", preferredPubName));
    params.add(new BasicNameValuePair("person.bio", bio));
    params.add(new BasicNameValuePair("person.website", website));
    params.add(new BasicNameValuePair("person.password", password));
    params.add(new BasicNameValuePair("person.emailAddress", emailAddress));
    params.add(new BasicNameValuePair("person.phoneNumber", phoneNumber));
    params.add(new BasicNameValuePair("person.jobTitle", jobTitle));
    params.add(new BasicNameValuePair("person.department", department));
    params.add(new BasicNameValuePair("person.city", city));
    params.add(new BasicNameValuePair("person.state", state));
    params.add(new BasicNameValuePair("person.instCompany", instCompany));
    params.add(new BasicNameValuePair("person.instCompanyWebsite", instCompanyWebsite));
    params.add(new BasicNameValuePair("person.registrationStatus", registrationStatus.toString()));
    params.add(new BasicNameValuePair("person.externalStorageLinked", Boolean.toString(externalStorageLinked)));
    params.add(new BasicNameValuePair("person.dropboxAppKey", dropboxAppKey));
    params.add(new BasicNameValuePair("person.dropboxAppSecret", dropboxAppSecret));
    params.add(new BasicNameValuePair(STRIPES_EVENT, "Add Person"));

    HttpEntity entity = null;

    try {
        entity = new UrlEncodedFormEntity(params, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e.getMessage(), e);
    }

    post.setEntity(entity);

    return post;
}

From source file:fr.letroll.ttorrentandroid.client.tracker.HTTPTrackerClient.java

/**
 * Build, send and process a tracker announce request.
 *
 * <p>//from www .  j  a va  2  s .c  o  m
 * This function first builds an announce request for the specified event
 * with all the required parameters. Then, the request is made to the
 * tracker and the response analyzed.
 * </p>
 *
 * <p>
 * All registered {@link AnnounceResponseListener} objects are then fired
 * with the decoded payload.
 * </p>
 *
 * @param event The announce event type (can be AnnounceEvent.NONE for
 * periodic updates).
 * @param inhibitEvents Prevent event listeners from being notified.
 */
@Override
public void announce(AnnounceResponseListener listener, TorrentMetadataProvider torrent, URI tracker,
        TrackerMessage.AnnounceEvent event, boolean inhibitEvents) throws AnnounceException {
    LOG.info("Announcing{} to tracker {} with {}U/{}D/{}L bytes...",
            new Object[] { TrackerClient.formatAnnounceEvent(event), tracker, torrent.getUploaded(),
                    torrent.getDownloaded(), torrent.getLeft() });

    try {
        HTTPAnnounceRequestMessage message = new HTTPAnnounceRequestMessage(torrent.getInfoHash(),
                getEnvironment().getLocalPeerId(), getPeerAddresses(), torrent.getUploaded(),
                torrent.getDownloaded(), torrent.getLeft(), true, false, event,
                AnnounceRequestMessage.DEFAULT_NUM_WANT);
        URI target = message.toURI(tracker);
        HttpGet request = new HttpGet(target);
        HttpResponseCallback callback = new HttpResponseCallback(listener, request, tracker);
        httpclient.execute(request, callback);
    } catch (URISyntaxException mue) {
        throw new AnnounceException("Invalid announce URI (" + mue.getMessage() + ")", mue);
    } catch (IOException ioe) {
        throw new AnnounceException("Error building announce request (" + ioe.getMessage() + ")", ioe);
    }
}

From source file:com.threewks.thundr.http.service.gae.HttpResponseImpl.java

@Override
public URI getUri() {
    try {/*from  w w  w . j av a 2  s .  c o  m*/
        // final url is only non-null when we follow redirects
        URL finalUrl = response().getFinalUrl();
        return finalUrl == null ? url.toURI() : finalUrl.toURI();
    } catch (URISyntaxException e) {
        throw new HttpResponseException(e, "Uri cannot be parsed: %s", e.getMessage());
    }
}

From source file:spaceRedirectStrategy.java

public URI getLocationURI(final HttpRequest request, final HttpResponse response, final HttpContext context)
        throws ProtocolException {
    if (response == null) {
        throw new IllegalArgumentException("HTTP response may not be null");
    }/*from  w  w w. j a  v  a2s.c o m*/
    //get the location header to find out where to redirect to
    Header locationHeader = response.getFirstHeader("location");
    if (locationHeader == null) {
        // got a redirect response, but no location header
        throw new ProtocolException(
                "Received redirect response " + response.getStatusLine() + " but no location header");
    }
    String location = locationHeader.getValue().replaceAll(" ", "%20");
    ;
    if (this.log.isDebugEnabled()) {
        this.log.debug("Redirect requested to location '" + location + "'");
    }

    URI uri = createLocationURI(location);

    HttpParams params = response.getParams();
    // rfc2616 demands the location value be a complete URI
    // Location       = "Location" ":" absoluteURI
    if (!uri.isAbsolute()) {
        if (params.isParameterTrue(ClientPNames.REJECT_RELATIVE_REDIRECT)) {
            throw new ProtocolException("Relative redirect location '" + uri + "' not allowed");
        }
        // Adjust location URI
        HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
        if (target == null) {
            throw new IllegalStateException("Target host not available " + "in the HTTP context");
        }
        try {
            URI requestURI = new URI(request.getRequestLine().getUri());
            URI absoluteRequestURI = URIUtils.rewriteURI(requestURI, target, true);
            uri = URIUtils.resolve(absoluteRequestURI, uri);
        } catch (URISyntaxException ex) {
            throw new ProtocolException(ex.getMessage(), ex);
        }
    }

    if (params.isParameterFalse(ClientPNames.ALLOW_CIRCULAR_REDIRECTS)) {

        RedirectLocations redirectLocations = (RedirectLocations) context.getAttribute(REDIRECT_LOCATIONS);

        if (redirectLocations == null) {
            redirectLocations = new RedirectLocations();
            context.setAttribute(REDIRECT_LOCATIONS, redirectLocations);
        }

        URI redirectURI;
        if (uri.getFragment() != null) {
            try {
                HttpHost target = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
                redirectURI = URIUtils.rewriteURI(uri, target, true);
            } catch (URISyntaxException ex) {
                throw new ProtocolException(ex.getMessage(), ex);
            }
        } else {
            redirectURI = uri;
        }

        if (redirectLocations.contains(redirectURI)) {
            throw new CircularRedirectException("Circular redirect to '" + redirectURI + "'");
        } else {
            //redirectLocations.add(redirectURI);
        }
    }

    return uri;
}

From source file:com.turn.ttorrent.tracker.client.HTTPTrackerClient.java

/**
 * Build, send and process a tracker announce request.
 *
 * <p>// w w w . j  a  v a 2  s . co m
 * This function first builds an announce request for the specified event
 * with all the required parameters. Then, the request is made to the
 * tracker and the response analyzed.
 * </p>
 *
 * <p>
 * All registered {@link AnnounceResponseListener} objects are then fired
 * with the decoded payload.
 * </p>
 *
 * @param event The announce event type (can be AnnounceEvent.NONE for
 * periodic updates).
 * @param inhibitEvents Prevent event listeners from being notified.
 */
@Override
public void announce(AnnounceResponseListener listener, TorrentMetadataProvider torrent, URI tracker,
        TrackerMessage.AnnounceEvent event, boolean inhibitEvents) throws AnnounceException {
    LOG.info("Announcing{} to tracker {} with {}U/{}D/{}L bytes...",
            new Object[] { TrackerClient.formatAnnounceEvent(event), tracker, torrent.getUploaded(),
                    torrent.getDownloaded(), torrent.getLeft() });

    try {
        HTTPAnnounceRequestMessage message = new HTTPAnnounceRequestMessage(torrent.getInfoHash(),
                getLocalPeerId(), getLocalPeerAddresses(), torrent.getUploaded(), torrent.getDownloaded(),
                torrent.getLeft(), true, false, event, AnnounceRequestMessage.DEFAULT_NUM_WANT);
        URI target = message.toURI(tracker);
        HttpGet request = new HttpGet(target);
        HttpResponseCallback callback = new HttpResponseCallback(listener, request, tracker, event);
        httpclient.execute(request, callback);
    } catch (URISyntaxException mue) {
        throw new AnnounceException("Invalid announce URI (" + mue.getMessage() + ")", mue);
    } catch (IOException ioe) {
        throw new AnnounceException("Error building announce request (" + ioe.getMessage() + ")", ioe);
    }
}

From source file:de.iteratec.iteraplan.businesslogic.exchange.visio.informationflow.VisioInformationFlowExport.java

private static URI createGxlTypeURI(String typeIdentifier) {
    try {/* www.  j  a v a2 s . com*/
        return new URI(GXL_SCHEMA_URI + typeIdentifier);
    } catch (URISyntaxException e) {
        // should never happen
        LOGGER.error(e.getMessage(), e);
        return null;
    }
}

From source file:org.wso2.carbon.http2.transport.Http2TransportSender.java

/**
 * Handels requests come from Axis2 Engine
 *
 * @param msgCtx/*from w  w w  . j  av  a2s .co m*/
 * @param targetEPR
 * @param trpOut
 * @throws AxisFault
 */
public void sendMessage(MessageContext msgCtx, String targetEPR, OutTransportInfo trpOut) throws AxisFault {
    try {
        if (targetEPR.toLowerCase().contains("http2://")) {
            targetEPR = targetEPR.replaceFirst("http2://", "http://");
        } else if (targetEPR.toLowerCase().contains("https2://")) {
            targetEPR = targetEPR.replaceFirst("https2://", "https://");
        }
        URI uri = new URI(targetEPR);
        String scheme = uri.getScheme() != null ? uri.getScheme() : "http";
        String hostname = uri.getHost();
        int port = uri.getPort();
        if (port == -1) {
            // use default
            if ("http".equals(scheme)) {
                port = 80;
            } else if ("https".equals(scheme)) {
                port = 443;
            }
        }
        HttpHost target = new HttpHost(hostname, port, scheme);
        boolean secure = "https".equals(target.getSchemeName());

        HttpHost proxy = proxyConfig.selectProxy(target);

        msgCtx.setProperty(PassThroughConstants.PROXY_PROFILE_TARGET_HOST, target.getHostName());

        HttpRoute route;
        if (proxy != null) {
            route = new HttpRoute(target, null, proxy, secure);
        } else {
            route = new HttpRoute(target, null, secure);
        }
        Http2TargetRequestUtil util = new Http2TargetRequestUtil(targetConfiguration, route);
        msgCtx.setProperty(Http2Constants.PASSTHROUGH_TARGET, util);

        if (msgCtx.getProperty(PassThroughConstants.PASS_THROUGH_PIPE) == null) {
            Pipe pipe = new Pipe(targetConfiguration.getBufferFactory().getBuffer(), "Test",
                    targetConfiguration);
            msgCtx.setProperty(PassThroughConstants.PASS_THROUGH_PIPE, pipe);
            msgCtx.setProperty(PassThroughConstants.MESSAGE_BUILDER_INVOKED, Boolean.TRUE);
        }

        Http2ClientHandler clientHandler = connectionFactory.getChannelHandler(target);

        String tenantDomain = (msgCtx.getProperty(MultitenantConstants.TENANT_DOMAIN) == null) ? null
                : (String) msgCtx.getProperty(MultitenantConstants.TENANT_DOMAIN);
        String dispatchSequence = (msgCtx.getProperty(Http2Constants.HTTP2_DISPATCH_SEQUENCE) == null) ? null
                : (String) msgCtx.getProperty(Http2Constants.HTTP2_DISPATCH_SEQUENCE);
        String errorSequence = (msgCtx.getProperty(Http2Constants.HTTP2_ERROR_SEQUENCE) == null) ? null
                : (String) msgCtx.getProperty(Http2Constants.HTTP2_ERROR_SEQUENCE);
        InboundResponseSender responseSender = (msgCtx
                .getProperty(InboundEndpointConstants.INBOUND_ENDPOINT_RESPONSE_WORKER) == null) ? null
                        : (InboundResponseSender) msgCtx
                                .getProperty(InboundEndpointConstants.INBOUND_ENDPOINT_RESPONSE_WORKER);
        boolean serverPushEnabled = (msgCtx
                .getProperty(Http2Constants.HTTP2_PUSH_PROMISE_REQEUST_ENABLED) == null) ? false
                        : (boolean) msgCtx.getProperty(Http2Constants.HTTP2_PUSH_PROMISE_REQEUST_ENABLED);

        clientHandler.setResponseReceiver(tenantDomain, dispatchSequence, errorSequence, responseSender,
                targetConfiguration, serverPushEnabled);
        clientHandler.channelWrite(msgCtx);

    } catch (URISyntaxException e) {
        log.error("Error parsing the http2 endpoint url");
        throw new AxisFault(e.getMessage());
    }
}