Example usage for java.net URI toASCIIString

List of usage examples for java.net URI toASCIIString

Introduction

In this page you can find the example usage for java.net URI toASCIIString.

Prototype

public String toASCIIString() 

Source Link

Document

Returns the content of this URI as a US-ASCII string.

Usage

From source file:org.apache.synapse.transport.nhttp.Axis2HttpRequest.java

/**
 * Create and return a new HttpPost request to the destination EPR
 *
 * @return the HttpRequest to be sent out
 * @throws IOException in error retrieving the <code>HttpRequest</code>
 *///w w  w  .  j  av  a 2s  .  c  o m
public HttpRequest getRequest() throws IOException, HttpException {
    String httpMethod = (String) msgContext.getProperty(Constants.Configuration.HTTP_METHOD);
    if (httpMethod == null) {
        httpMethod = "POST";
    }
    endpointURLPrefix = (String) msgContext.getProperty(NhttpConstants.ENDPOINT_PREFIX);

    boolean forceHTTP10 = msgContext.isPropertyTrue(NhttpConstants.FORCE_HTTP_1_0);
    HttpVersion httpver = forceHTTP10 ? HttpVersion.HTTP_1_0 : HttpVersion.HTTP_1_1;

    HttpRequest httpRequest;

    try {
        if ("POST".equals(httpMethod) || "PUT".equals(httpMethod) || "PATCH".equals(httpMethod)) {

            URI uri = rewriteRequestURI(new URI(epr.getAddress()));
            BasicHttpEntityEnclosingRequest requestWithEntity = new BasicHttpEntityEnclosingRequest(httpMethod,
                    uri.toASCIIString(), httpver);

            BasicHttpEntity entity = new BasicHttpEntity();

            if (forceHTTP10) {
                setStreamAsTempData(entity);
            } else {
                entity.setChunked(chunked);
                if (!chunked) {
                    setStreamAsTempData(entity);
                }
            }
            requestWithEntity.setEntity(entity);
            requestWithEntity.setHeader(HTTP.CONTENT_TYPE,
                    messageFormatter.getContentType(msgContext, format, msgContext.getSoapAction()));
            httpRequest = requestWithEntity;

        } else if ("GET".equals(httpMethod) || "DELETE".equals(httpMethod)) {

            URL url = messageFormatter.getTargetAddress(msgContext, format, new URL(epr.getAddress()));

            URI uri = rewriteRequestURI(url.toURI());
            httpRequest = new BasicHttpRequest(httpMethod, uri.toASCIIString(), httpver);
            /*GETs and DELETEs do not need Content-Type headers because they do not have payloads*/
            //httpRequest.setHeader(HTTP.CONTENT_TYPE, messageFormatter.getContentType(
            //        msgContext, format, msgContext.getSoapAction()));

        } else {
            URI uri = rewriteRequestURI(new URI(epr.getAddress()));
            httpRequest = new BasicHttpRequest(httpMethod, uri.toASCIIString(), httpver);
        }

    } catch (URISyntaxException ex) {
        throw new HttpException(ex.getMessage(), ex);
    }

    // set any transport headers
    Object o = msgContext.getProperty(MessageContext.TRANSPORT_HEADERS);
    if (o != null && o instanceof Map) {
        Map headers = (Map) o;
        for (Object header : headers.keySet()) {
            Object value = headers.get(header);
            if (header instanceof String && value != null && value instanceof String) {
                if (!HTTPConstants.HEADER_HOST.equalsIgnoreCase((String) header)) {
                    httpRequest.setHeader((String) header, (String) value);

                    String excessProp = NhttpConstants.EXCESS_TRANSPORT_HEADERS;

                    Map map = (Map) msgContext.getProperty(excessProp);
                    if (map != null && map.get(header) != null) {
                        log.debug("Number of excess values for " + header + " header is : "
                                + ((Collection) (map.get(header))).size());

                        for (Iterator iterator = map.keySet().iterator(); iterator.hasNext();) {
                            String key = (String) iterator.next();

                            for (String excessVal : (Collection<String>) map.get(key)) {
                                httpRequest.addHeader((String) header, (String) excessVal);
                            }

                        }
                    }

                } else {
                    if (msgContext.getProperty(NhttpConstants.REQUEST_HOST_HEADER) != null) {
                        httpRequest.setHeader((String) header,
                                (String) msgContext.getProperty(NhttpConstants.REQUEST_HOST_HEADER));
                    }
                }

            }
        }
    }

    // if the message is SOAP 11 (for which a SOAPAction is *required*), and
    // the msg context has a SOAPAction or a WSA-Action (give pref to SOAPAction)
    // use that over any transport header that may be available
    String soapAction = msgContext.getSoapAction();
    if (soapAction == null) {
        soapAction = msgContext.getWSAAction();
    }
    if (soapAction == null) {
        msgContext.getAxisOperation().getInputAction();
    }

    if (msgContext.isSOAP11() && soapAction != null && soapAction.length() >= 0) {
        Header existingHeader = httpRequest.getFirstHeader(HTTPConstants.HEADER_SOAP_ACTION);
        if (existingHeader != null) {
            httpRequest.removeHeader(existingHeader);
        }
        httpRequest.setHeader(HTTPConstants.HEADER_SOAP_ACTION,
                messageFormatter.formatSOAPAction(msgContext, null, soapAction));
    }

    if (NHttpConfiguration.getInstance().isKeepAliveDisabled()
            || msgContext.isPropertyTrue(NhttpConstants.NO_KEEPALIVE)) {
        httpRequest.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE);
    }

    return httpRequest;
}

From source file:org.apache.olingo.ext.proxy.commons.EntityInvocationHandler.java

public EntityUUID updateUUID(final URI entitySetURI, final Class<?> type, final Object key) {
    this.uuid = new EntityUUID(entitySetURI, type, key);

    if (this.uri == null) {
        final URIBuilder uriBuilder = getEntity().getEditLink() == null
                ? CoreUtils.buildEditLink(getClient(), entitySetURI.toASCIIString(), key)
                : getClient().newURIBuilder(getEntity().getEditLink().toASCIIString());

        this.uri = uriBuilder;
        this.baseURI = this.uri == null ? null : this.uri.build();
    }/*  ww  w .  j a  va2s.  co m*/

    return this.uuid;
}

From source file:com.msopentech.odatajclient.proxy.api.impl.SequentialContainer.java

private int processEntityContext(EntityTypeInvocationHandler handler, int pos, TransactionItems items,
        List<EntityLinkDesc> delayedUpdates) {
    LOG.debug("Process '{}'", handler);
    items.put(handler, null);/*from www .  ja  v  a 2  s  .  c  o  m*/

    final ODataEntity entity = handler.getEntity();
    entity.getNavigationLinks().clear();

    final AttachedEntityStatus currentStatus = EntityContainerFactory.getContext().entityContext()
            .getStatus(handler);

    if (AttachedEntityStatus.DELETED != currentStatus) {
        entity.getProperties().clear();
        EngineUtils.addProperties(client, factory.getMetadata(), handler.getPropertyChanges(), entity);
    }

    for (Map.Entry<NavigationProperty, Object> property : handler.getLinkChanges().entrySet()) {
        final ODataLinkType type = Collection.class.isAssignableFrom(property.getValue().getClass())
                ? ODataLinkType.ENTITY_SET_NAVIGATION
                : ODataLinkType.ENTITY_NAVIGATION;

        final Set<EntityTypeInvocationHandler> toBeLinked = new HashSet<EntityTypeInvocationHandler>();
        final String serviceRoot = factory.getServiceRoot();

        for (Object proxy : type == ODataLinkType.ENTITY_SET_NAVIGATION ? (Collection) property.getValue()
                : Collections.singleton(property.getValue())) {

            final EntityTypeInvocationHandler target = (EntityTypeInvocationHandler) Proxy
                    .getInvocationHandler(proxy);

            final AttachedEntityStatus status;

            try {
                status = EntityContainerFactory.getContext().entityContext().getStatus(target);
            } catch (IllegalStateException e) {
                // this case takes place if we iterate through collection and current item does not have any changes
                // TODO find another way to look for changes in collection
                continue;
            }

            final URI editLink = target.getEntity().getEditLink();

            if ((status == AttachedEntityStatus.ATTACHED || status == AttachedEntityStatus.LINKED)
                    && !target.isChanged()) {
                entity.addLink(buildNavigationLink(property.getKey().name(),
                        URIUtils.getURI(serviceRoot, editLink.toASCIIString()), type));
            } else {
                if (!items.contains(target)) {
                    pos = processEntityContext(target, pos, items, delayedUpdates);
                    pos++;
                }

                final Integer targetPos = items.get(target);
                if (targetPos == null) {
                    // schedule update for the current object
                    LOG.debug("Schedule '{}' from '{}' to '{}'", type.name(), handler, target);
                    toBeLinked.add(target);
                } else if (status == AttachedEntityStatus.CHANGED) {
                    entity.addLink(buildNavigationLink(property.getKey().name(),
                            URIUtils.getURI(serviceRoot, editLink.toASCIIString()), type));
                } else {
                    // create the link for the current object
                    LOG.debug("'{}' from '{}' to (${}) '{}'", type.name(), handler, targetPos, target);

                    entity.addLink(
                            buildNavigationLink(property.getKey().name(), URI.create("$" + targetPos), type));
                }
            }
        }

        if (!toBeLinked.isEmpty()) {
            delayedUpdates.add(new EntityLinkDesc(property.getKey().name(), handler, toBeLinked, type));
        }
    }

    // commit to server
    LOG.debug("{}: Send '{}' to service", pos, handler);
    send(handler, entity);

    items.put(handler, pos);
    int startingPos = pos;

    if (handler.getEntity().isMediaEntity()) {

        // update media properties
        if (!handler.getPropertyChanges().isEmpty()) {
            final URI targetURI = currentStatus == AttachedEntityStatus.NEW ? URI.create("$" + startingPos)
                    : URIUtils.getURI(factory.getServiceRoot(),
                            handler.getEntity().getEditLink().toASCIIString());
            update(handler, targetURI, entity);
            pos++;
            items.put(handler, pos);
        }

        // update media content
        if (handler.getStreamChanges() != null) {
            final URI targetURI = currentStatus == AttachedEntityStatus.NEW
                    ? URI.create("$" + startingPos + "/$value")
                    : URIUtils.getURI(factory.getServiceRoot(),
                            handler.getEntity().getEditLink().toASCIIString() + "/$value");

            updateMediaEntity(handler, targetURI, handler.getStreamChanges());

            // update media info (use null key)
            pos++;
            items.put(null, pos);
        }
    }

    for (Map.Entry<String, InputStream> streamedChanges : handler.getStreamedPropertyChanges().entrySet()) {
        final URI targetURI = currentStatus == AttachedEntityStatus.NEW ? URI.create("$" + startingPos)
                : URIUtils.getURI(factory.getServiceRoot(),
                        EngineUtils.getEditMediaLink(streamedChanges.getKey(), entity).toASCIIString());

        updateMediaResource(handler, targetURI, streamedChanges.getValue());

        // update media info (use null key)
        pos++;
        items.put(handler, pos);
    }

    return pos;
}

From source file:org.apache.fop.afp.AFPResourceManager.java

/**
 * Creates an included resource object by loading the contained object from a file.
 * @param resourceName the name of the resource
 * @param uri the URI for the resource//www. ja va  2s. com
 * @param accessor resource accessor to access the resource with
 * @param resourceObjectType the resource object type ({@link ResourceObject}.*)
 * @throws IOException if an I/O error occurs while loading the resource
 */
public void createIncludedResource(String resourceName, URI uri, ResourceAccessor accessor,
        byte resourceObjectType) throws IOException {
    AFPResourceLevel resourceLevel = new AFPResourceLevel(AFPResourceLevel.PRINT_FILE);

    AFPResourceInfo resourceInfo = new AFPResourceInfo();
    resourceInfo.setLevel(resourceLevel);
    resourceInfo.setName(resourceName);
    resourceInfo.setUri(uri.toASCIIString());

    String objectName = includeNameMap.get(resourceInfo);
    if (objectName == null) {
        if (log.isDebugEnabled()) {
            log.debug("Adding included resource: " + resourceName);
        }
        IncludedResourceObject resourceContent = new IncludedResourceObject(resourceName, accessor, uri);

        ResourceObject resourceObject = factory.createResource(resourceName);
        resourceObject.setDataObject(resourceContent);
        resourceObject.setType(resourceObjectType);

        ResourceGroup resourceGroup = streamer.getResourceGroup(resourceLevel);
        resourceGroup.addObject(resourceObject);
        // record mapping of resource info to data object resource name
        includeNameMap.put(resourceInfo, resourceName);
    } else {
        //skip, already created
    }
}

From source file:org.apache.olingo.client.core.serialization.JsonEntitySetDeserializer.java

protected ResWrap<EntityCollection> doDeserialize(final JsonParser parser) throws IOException {

    final ObjectNode tree = (ObjectNode) parser.getCodec().readTree(parser);

    if (!tree.has(Constants.VALUE)) {
        return null;
    }/*from   ww  w .j a  v a  2s .  c o m*/

    final EntityCollection entitySet = new EntityCollection();

    URI contextURL;
    if (tree.hasNonNull(Constants.JSON_CONTEXT)) {
        contextURL = URI.create(tree.get(Constants.JSON_CONTEXT).textValue());
        tree.remove(Constants.JSON_CONTEXT);
    } else if (tree.hasNonNull(Constants.JSON_METADATA)) {
        contextURL = URI.create(tree.get(Constants.JSON_METADATA).textValue());
        tree.remove(Constants.JSON_METADATA);
    } else {
        contextURL = null;
    }
    if (contextURL != null) {
        entitySet.setBaseURI(
                URI.create(StringUtils.substringBefore(contextURL.toASCIIString(), Constants.METADATA)));
    }

    final String metadataETag;
    if (tree.hasNonNull(Constants.JSON_METADATA_ETAG)) {
        metadataETag = tree.get(Constants.JSON_METADATA_ETAG).textValue();
        tree.remove(Constants.JSON_METADATA_ETAG);
    } else {
        metadataETag = null;
    }

    if (tree.hasNonNull(Constants.JSON_COUNT)) {
        entitySet.setCount(tree.get(Constants.JSON_COUNT).asInt());
        tree.remove(Constants.JSON_COUNT);
    }
    if (tree.hasNonNull(Constants.JSON_NEXT_LINK)) {
        entitySet.setNext(URI.create(tree.get(Constants.JSON_NEXT_LINK).textValue()));
        tree.remove(Constants.JSON_NEXT_LINK);
    }
    if (tree.hasNonNull(Constants.JSON_DELTA_LINK)) {
        entitySet.setDeltaLink(URI.create(tree.get(Constants.JSON_DELTA_LINK).textValue()));
        tree.remove(Constants.JSON_DELTA_LINK);
    }

    if (tree.hasNonNull(Constants.VALUE)) {
        final JsonEntityDeserializer entityDeserializer = new JsonEntityDeserializer(serverMode);
        for (JsonNode jsonNode : tree.get(Constants.VALUE)) {
            entitySet.getEntities()
                    .add(entityDeserializer.doDeserialize(jsonNode.traverse(parser.getCodec())).getPayload());
        }
        tree.remove(Constants.VALUE);
    }
    final Set<String> toRemove = new HashSet<String>();
    // any remaining entry is supposed to be an annotation or is ignored
    for (final Iterator<Map.Entry<String, JsonNode>> itor = tree.fields(); itor.hasNext();) {
        final Map.Entry<String, JsonNode> field = itor.next();
        if (field.getKey().charAt(0) == '@') {
            final Annotation annotation = new Annotation();
            annotation.setTerm(field.getKey().substring(1));

            try {
                value(annotation, field.getValue(), parser.getCodec());
            } catch (final EdmPrimitiveTypeException e) {
                throw new IOException(e);
            }
            entitySet.getAnnotations().add(annotation);
        } else if (field.getKey().charAt(0) == '#') {
            final Operation operation = new Operation();
            operation.setMetadataAnchor(field.getKey());

            final ObjectNode opNode = (ObjectNode) tree.get(field.getKey());
            operation.setTitle(opNode.get(Constants.ATTR_TITLE).asText());
            operation.setTarget(URI.create(opNode.get(Constants.ATTR_TARGET).asText()));
            entitySet.getOperations().add(operation);
            toRemove.add(field.getKey());
        }
    }
    tree.remove(toRemove);
    return new ResWrap<EntityCollection>(contextURL, metadataETag, entitySet);
}

From source file:org.texai.torrent.TrackerTest.java

/** Tests the HTTP request and response messages. */
@SuppressWarnings({ "ThrowableResultIgnored", "null" })
private void httpClient() {
    final ClientBootstrap clientBootstrap = new ClientBootstrap(new NioClientSocketChannelFactory(
            Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));

    // configure the client pipeline
    final Object clientResume_lock = new Object();
    final AbstractHTTPResponseHandler httpResponseHandler = new MockHTTPResponseHandler(clientResume_lock);
    final X509SecurityInfo x509SecurityInfo = KeyStoreTestUtils.getClientX509SecurityInfo();
    final ChannelPipeline channelPipeline = HTTPClientPipelineFactory.getPipeline(httpResponseHandler,
            x509SecurityInfo);/*from   w w  w  . j  av  a  2 s . c  o m*/
    clientBootstrap.setPipeline(channelPipeline);
    LOGGER.info("pipeline: " + channelPipeline.toString());

    // start the connection attempt
    ChannelFuture channelFuture = clientBootstrap.connect(new InetSocketAddress("localhost", SERVER_PORT));

    // wait until the connection attempt succeeds or fails
    final Channel channel = channelFuture.awaitUninterruptibly().getChannel();
    if (!channelFuture.isSuccess()) {
        channelFuture.getCause().printStackTrace();
        fail(channelFuture.getCause().getMessage());
    }
    LOGGER.info("HTTP client connected");

    URI uri = null;
    HttpRequest httpRequest;
    String host;

    // send the statistics request
    try {
        uri = new URI("https://localhost:" + SERVER_PORT + "/torrent-tracker/statistics");
    } catch (URISyntaxException ex) {
        fail(ex.getMessage());
    }
    httpRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.toASCIIString());
    host = uri.getHost() == null ? "localhost" : uri.getHost();
    httpRequest.setHeader(HttpHeaders.Names.HOST, host);
    httpRequest.setHeader(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    LOGGER.info("httpRequest ...\n" + httpRequest);
    channel.write(httpRequest);

    // wait for the request message to be sent
    channelFuture.awaitUninterruptibly();
    if (!channelFuture.isSuccess()) {
        channelFuture.getCause().printStackTrace();
        fail(channelFuture.getCause().getMessage());
    }

    // send the scrape request
    try {
        uri = new URI("https://localhost:" + SERVER_PORT + "/torrent-tracker/scrape");
    } catch (URISyntaxException ex) {
        fail(ex.getMessage());
    }
    httpRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.toASCIIString());
    host = uri.getHost() == null ? "localhost" : uri.getHost();
    httpRequest.setHeader(HttpHeaders.Names.HOST, host);
    httpRequest.setHeader(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
    LOGGER.info("httpRequest ...\n" + httpRequest);
    channel.write(httpRequest);

    // wait for the request message to be sent
    channelFuture.awaitUninterruptibly();
    if (!channelFuture.isSuccess()) {
        channelFuture.getCause().printStackTrace();
        fail(channelFuture.getCause().getMessage());
    }

    // send the announce request
    final byte[] myPeerIdBytes = { 0x14, 0x13, 0x12, 0x11, 0x10, 0x0F, 0x0E, 0x0D, 0x0C, 0x0B, 0x0A, 0x09, 0x08,
            0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01 };
    final int nbrBytesUploaded = 0;
    final int nbrBytesDownloaded = 0;
    final int nbrBytesLeftToDownloaded = 1024;
    final String event = "started";
    final String myIPAddress = NetworkUtils.getLocalHostAddress().getHostAddress();
    final StringBuilder stringBuilder = new StringBuilder();
    stringBuilder.append("https://localhost:");
    stringBuilder.append(SERVER_PORT);
    stringBuilder.append("/torrent-tracker/announce");
    stringBuilder.append('?');
    stringBuilder.append("info_hash=");
    stringBuilder.append(new String((new URLCodec()).encode(INFO_HASH)));
    stringBuilder.append("&peer_id=");
    stringBuilder.append(new String((new URLCodec()).encode(myPeerIdBytes)));
    stringBuilder.append("&port=");
    stringBuilder.append(SERVER_PORT);
    stringBuilder.append("&uploaded=");
    stringBuilder.append(nbrBytesUploaded);
    stringBuilder.append("&downloaded=");
    stringBuilder.append(nbrBytesDownloaded);
    stringBuilder.append("&left=");
    stringBuilder.append(nbrBytesLeftToDownloaded);
    stringBuilder.append("&event=");
    stringBuilder.append(event);
    stringBuilder.append("&ip=");
    stringBuilder.append(myIPAddress);
    try {
        uri = new URI(stringBuilder.toString());
    } catch (URISyntaxException ex) {
        fail(ex.getMessage());
    }
    httpRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.toASCIIString());
    host = uri.getHost() == null ? "localhost" : uri.getHost();
    httpRequest.setHeader(HttpHeaders.Names.HOST, host);
    httpRequest.setHeader(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
    LOGGER.info("httpRequest ...\n" + httpRequest);
    channel.write(httpRequest);

    // wait for the request message to be sent
    channelFuture.awaitUninterruptibly();
    if (!channelFuture.isSuccess()) {
        channelFuture.getCause().printStackTrace();
        fail(channelFuture.getCause().getMessage());
    }

    // the message response handler will signal this thread when the test exchanges are completed
    synchronized (clientResume_lock) {
        try {
            clientResume_lock.wait();
        } catch (InterruptedException ex) {
        }
    }
    LOGGER.info("releasing HTTP client resources");
    channel.close();
    clientBootstrap.releaseExternalResources();
}

From source file:eu.planets_project.tb.gui.backing.data.DigitalObjectCompare.java

private void recordIdentifyMeasurement(MeasurementEventImpl me, IdentifyResult ir, String dob) {
    for (URI fmt : ir.getTypes()) {
        MeasurementImpl m = new MeasurementImpl(IdentifyWorkflow.MEASURE_IDENTIFY_FORMAT);
        m.setValue(fmt.toASCIIString());
        m.setTarget(new MeasurementTarget());
        m.getTarget().setType(TargetType.DIGITAL_OBJECT);
        m.getTarget().getDigitalObjects().add(dob);
        me.addMeasurement(m);//from w w  w.ja  va2 s.c  om

    }
    // Also record the method:
    if (ir.getMethod() != null) {
        MeasurementImpl m = new MeasurementImpl(IdentifyWorkflow.MEASURE_IDENTIFY_METHOD);
        m.setValue(ir.getMethod().name());
        m.setTarget(new MeasurementTarget());
        m.getTarget().setType(TargetType.DIGITAL_OBJECT);
        m.getTarget().getDigitalObjects().add(dob);
        me.addMeasurement(m);
    }
}

From source file:org.apache.fop.afp.AFPResourceManager.java

/**
 * Creates an included resource extracting the named resource from an external source.
 * @param resourceName the name of the resource
 * @param uri the URI for the resource//from www . ja v a  2 s. c  om
 * @param accessor resource accessor to access the resource with
 * @throws IOException if an I/O error occurs while loading the resource
 */
public void createIncludedResourceFromExternal(final String resourceName, final URI uri,
        final ResourceAccessor accessor) throws IOException {

    AFPResourceLevel resourceLevel = new AFPResourceLevel(AFPResourceLevel.PRINT_FILE);

    AFPResourceInfo resourceInfo = new AFPResourceInfo();
    resourceInfo.setLevel(resourceLevel);
    resourceInfo.setName(resourceName);
    resourceInfo.setUri(uri.toASCIIString());

    String resource = includeNameMap.get(resourceInfo);
    if (resource == null) {

        ResourceGroup resourceGroup = streamer.getResourceGroup(resourceLevel);

        //resourceObject delegates write commands to copyNamedResource()
        //The included resource may already be wrapped in a resource object
        AbstractNamedAFPObject resourceObject = new AbstractNamedAFPObject(null) {

            @Override
            protected void writeContent(OutputStream os) throws IOException {
                InputStream inputStream = null;
                try {
                    inputStream = accessor.createInputStream(uri);
                    BufferedInputStream bin = new BufferedInputStream(inputStream);
                    AFPResourceUtil.copyNamedResource(resourceName, bin, os);
                } finally {
                    IOUtils.closeQuietly(inputStream);
                }
            }

            //bypass super.writeStart
            @Override
            protected void writeStart(OutputStream os) throws IOException {
            }

            //bypass super.writeEnd
            @Override
            protected void writeEnd(OutputStream os) throws IOException {
            }
        };

        resourceGroup.addObject(resourceObject);

        includeNameMap.put(resourceInfo, resourceName);

    }
}

From source file:org.apache.hadoop.gateway.dispatch.DefaultDispatchTest.java

@Test(timeout = TestUtils.SHORT_TIMEOUT)
public void testGetDispatchUrl() throws Exception {
    HttpServletRequest request;/*from   w w w  . j av a2  s  .  co  m*/
    Dispatch dispatch;
    String path;
    String query;
    URI uri;

    dispatch = new DefaultDispatch();

    path = "http://test-host:42/test-path";
    request = EasyMock.createNiceMock(HttpServletRequest.class);
    EasyMock.expect(request.getRequestURI()).andReturn(path).anyTimes();
    EasyMock.expect(request.getRequestURL()).andReturn(new StringBuffer(path)).anyTimes();
    EasyMock.expect(request.getQueryString()).andReturn(null).anyTimes();
    EasyMock.replay(request);
    uri = dispatch.getDispatchUrl(request);
    assertThat(uri.toASCIIString(), is("http://test-host:42/test-path"));

    path = "http://test-host:42/test,path";
    request = EasyMock.createNiceMock(HttpServletRequest.class);
    EasyMock.expect(request.getRequestURI()).andReturn(path).anyTimes();
    EasyMock.expect(request.getRequestURL()).andReturn(new StringBuffer(path)).anyTimes();
    EasyMock.expect(request.getQueryString()).andReturn(null).anyTimes();
    EasyMock.replay(request);
    uri = dispatch.getDispatchUrl(request);
    assertThat(uri.toASCIIString(), is("http://test-host:42/test,path"));

    path = "http://test-host:42/test%2Cpath";
    request = EasyMock.createNiceMock(HttpServletRequest.class);
    EasyMock.expect(request.getRequestURI()).andReturn(path).anyTimes();
    EasyMock.expect(request.getRequestURL()).andReturn(new StringBuffer(path)).anyTimes();
    EasyMock.expect(request.getQueryString()).andReturn(null).anyTimes();
    EasyMock.replay(request);
    uri = dispatch.getDispatchUrl(request);
    assertThat(uri.toASCIIString(), is("http://test-host:42/test%2Cpath"));

    path = "http://test-host:42/test%2Cpath";
    query = "test%26name=test%3Dvalue";
    request = EasyMock.createNiceMock(HttpServletRequest.class);
    EasyMock.expect(request.getRequestURI()).andReturn(path).anyTimes();
    EasyMock.expect(request.getRequestURL()).andReturn(new StringBuffer(path)).anyTimes();
    EasyMock.expect(request.getQueryString()).andReturn(query).anyTimes();
    EasyMock.replay(request);
    uri = dispatch.getDispatchUrl(request);
    assertThat(uri.toASCIIString(), is("http://test-host:42/test%2Cpath?test%26name=test%3Dvalue"));

}

From source file:org.emergent.android.weave.syncadapter.SyncCache.java

public boolean updateLastSync(URI uri, String engineName, Date lastSyncDate) {
    Log.d(TAG, "SyncCache.updateLastSync()");
    if (lastSyncDate == null) {
        Log.w(TAG, "lastSyncDate was null");
        return false;
    }/*from  www.  ja va  2 s  . co  m*/

    long lastSync = lastSyncDate.getTime();
    SQLiteDatabase db = null;
    try {
        String uriStr = uri.toASCIIString();
        db = m_helper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(MgColumns.LAST_MODIFIED, lastSync);
        long updateCount = db.update(META_GLOBAL_TABLE_NAME, values,
                MgColumns.NODE_URI + " = ? AND " + MgColumns.ENGINE_NAME + " = ?",
                new String[] { uriStr, engineName });
        assert updateCount < 2 : "Should not be able to update more than one row by constraints!";
        return updateCount > 0;
    } finally {
        if (db != null)
            try {
                db.close();
            } catch (Exception ignored) {
            }
    }
}