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:hudson.plugins.dimensionsscm.DimensionsAPI.java

private static String encodeUrl(String host, String page, String query)
        throws MalformedURLException, URISyntaxException {
    String urlStr = "";
    if (page != null && page.length() > 0 && host != null && host.length() > 0 && query != null
            && query.length() > 0) {
        URI uri = new URI("http", host, page, query, null);
        urlStr = uri.toASCIIString();
    }//  w  ww  . j a v  a 2  s . c o  m
    return urlStr;
}

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

protected int processEntityContext(final EntityInvocationHandler handler, int pos, final TransactionItems items,
        final List<EntityLinkDesc> delayedUpdates, final PersistenceChanges changeset) {
    int posNumber = pos;
    items.put(handler, null);//from w w  w.  jav  a 2s  .  c om

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

    final AttachedEntityStatus currentStatus = service.getContext().entityContext().getStatus(handler);
    LOG.debug("Process '{}({})'", handler, currentStatus);

    if (AttachedEntityStatus.DELETED != currentStatus) {
        entity.getProperties().clear();
        CoreUtils.addProperties(service.getClient(), handler.getPropertyChanges(), entity);

        entity.getAnnotations().clear();
        CoreUtils.addAnnotations(service.getClient(), handler.getAnnotations(), entity);

        for (Map.Entry<String, AnnotatableInvocationHandler> entry : handler.getPropAnnotatableHandlers()
                .entrySet()) {
            CoreUtils.addAnnotations(service.getClient(), entry.getValue().getAnnotations(),
                    entity.getProperty(entry.getKey()));
        }
    }

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

        final Set<EntityInvocationHandler> toBeLinked = new HashSet<EntityInvocationHandler>();

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

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

            final AttachedEntityStatus status;
            if (!service.getContext().entityContext().isAttached(target)) {
                status = resolveNavigationLink(property.getKey(), target);
            } else {
                status = service.getContext().entityContext().getStatus(target);
            }

            LOG.debug("Found link to '{}({})'", target, status);

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

            if ((status == AttachedEntityStatus.ATTACHED || status == AttachedEntityStatus.LINKED)
                    && !target.isChanged()) {
                LOG.debug("Add link to '{}'", target);
                entity.addLink(buildNavigationLink(property.getKey().name(),
                        URIUtils.getURI(service.getClient().getServiceRoot(), editLink.toASCIIString()), type));
            } else {
                if (!items.contains(target)) {
                    posNumber = processEntityContext(target, posNumber, items, delayedUpdates, changeset);
                    posNumber++;
                }

                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) {
                    LOG.debug("Changed: '{}' from '{}' to (${}) '{}'", type.name(), handler, targetPos, target);
                    entity.addLink(buildNavigationLink(property.getKey().name(),
                            URIUtils.getURI(service.getClient().getServiceRoot(), 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));
        }

        if (property.getValue() instanceof Proxy) {
            final InvocationHandler target = Proxy.getInvocationHandler(property.getValue());

            if (target instanceof EntityCollectionInvocationHandler) {
                for (String ref : ((EntityCollectionInvocationHandler<?>) target).referenceItems) {
                    delayedUpdates.add(new EntityLinkDesc(property.getKey().name(), handler, ref));
                }
            }
        }
    }

    for (Map.Entry<String, AnnotatableInvocationHandler> entry : handler.getNavPropAnnotatableHandlers()
            .entrySet()) {

        CoreUtils.addAnnotations(service.getClient(), entry.getValue().getAnnotations(),
                entity.getNavigationLink(entry.getKey()));
    }

    final AttachedEntityStatus processedStatus = queue(handler, entity, changeset);
    if (processedStatus != null) {
        // insert into the process queue
        LOG.debug("{}: Insert '{}' into the process queue", posNumber, handler);
        items.put(handler, posNumber);
    } else {
        posNumber--;
    }

    if (processedStatus != AttachedEntityStatus.DELETED) {
        int startingPos = posNumber;

        if (handler.getEntity().isMediaEntity() && handler.isChanged()) {
            // update media properties
            if (!handler.getPropertyChanges().isEmpty()) {
                final URI targetURI = currentStatus == AttachedEntityStatus.NEW ? URI.create("$" + startingPos)
                        : URIUtils.getURI(service.getClient().getServiceRoot(),
                                handler.getEntity().getEditLink().toASCIIString());
                queueUpdate(handler, targetURI, entity, changeset);
                posNumber++;
                items.put(handler, posNumber);
                LOG.debug("{}: Update media properties for '{}' into the process queue", posNumber, handler);
            }

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

                queueUpdateMediaEntity(handler, targetURI, handler.getStreamChanges(), changeset);

                // update media info (use null key)
                posNumber++;
                items.put(null, posNumber);
                LOG.debug("{}: Update media info for '{}' into the process queue", posNumber, handler);
            }
        }

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

            queueUpdateMediaResource(handler, targetURI, streamedChanges.getValue(), changeset);

            // update media info (use null key)
            posNumber++;
            items.put(handler, posNumber);
            LOG.debug("{}: Update media info (null key) for '{}' into the process queue", posNumber, handler);
        }
    }

    return posNumber;
}

From source file:org.apache.fop.apps.FOURIResolver.java

/**
 * Checks if the given base URL is acceptable. It also normalizes the URL.
 * @param base the base URL to check/*from   w ww.  j a v  a  2  s .c o  m*/
 * @return the normalized URL
 * @throws MalformedURLException if there's a problem with a file URL
 */
public String checkBaseURL(String base) throws MalformedURLException {
    // replace back slash with forward slash to ensure windows file:/// URLS are supported
    base = base.replace('\\', '/');
    if (!base.endsWith("/")) {
        // The behavior described by RFC 3986 regarding resolution of relative
        // references may be misleading for normal users:
        // file://path/to/resources + myResource.res -> file://path/to/myResource.res
        // file://path/to/resources/ + myResource.res -> file://path/to/resources/myResource.res
        // We assume that even when the ending slash is missing, users have the second
        // example in mind
        base += "/";
    }
    File dir = new File(base);
    if (dir.isDirectory()) {
        return dir.toURI().toASCIIString();
    } else {
        URI baseURI;
        try {
            baseURI = new URI(base);
            String scheme = baseURI.getScheme();
            boolean directoryExists = true;
            if ("file".equals(scheme)) {
                dir = FileUtils.toFile(baseURI.toURL());
                directoryExists = dir.isDirectory();
            }
            if (scheme == null || !directoryExists) {
                String message = "base " + base + " is not a valid directory";
                if (throwExceptions) {
                    throw new MalformedURLException(message);
                }
                log.error(message);
            }
            return baseURI.toASCIIString();
        } catch (URISyntaxException e) {
            //TODO not ideal: our base URLs are actually base URIs.
            throw new MalformedURLException(e.getMessage());
        }
    }
}

From source file:org.myrobotlab.service.Speech.java

public void speakGoogle(String toSpeak) {

    if (!fileCacheInitialized) {
        boolean success = (new File("audioFile/google/" + language + "/" + voiceName)).mkdirs();
        if (!success) {
            log.debug("could not create directory: audioFile/google/" + language + "/" + voiceName);
        } else {// w w  w.j  a  va 2s. co m
            fileCacheInitialized = true;
        }
    }

    // Sanitize the filename so it can be properly cached.
    String cashFilename = toSpeak;
    cashFilename = cleanFilename(cashFilename);
    String utteranceHash = hashFilename(cashFilename);
    addToUtteranceMapping(cashFilename, utteranceHash);

    String audioFileName = "audioFile/google/" + language + "/" + voiceName + "/" + utteranceHash + ".mp3";
    File f = new File(audioFileName);
    log.info(f + (f.exists() ? " is found " : " is missing "));

    if (!f.exists()) {
        try {
            // if the mp3 file does not exist fetch it from google
            /*
             * HashMap<String, String> params = new HashMap<String,
             * String>(); params.put("voice", voiceName); params.put("txt",
             * toSpeak); params.put("speakButton", "SPEAK");
             */
            // rel="noreferrer"
            // http://translate.google.com/translate_tts?tl=en&q=text
            // http://translate.google.com/translate_tts?tl=fr&q=Bonjour
            // http://translate.google.com/translate_tts?tl=en&q=hello%20there%20my%20good%20friend

            client = new DefaultHttpClient();

            if (googleProxyHost != null) {
                HttpHost proxy = new HttpHost(googleProxyHost, googleProxyPort);
                client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
            }

            String baseURI = String.format(googleURI, language);
            //URI uri = new URI("http", null, "translate.google.com", 80,
            //"/translate_tts", "tl=" + language + "&q=" + toSpeak, null);

            log.info(baseURI + URLEncoder.encode(toSpeak, "UTF-8"));
            URI uri = new URI(baseURI + URLEncoder.encode(toSpeak, "UTF-8"));
            //log.info(baseURI + URLEncoder.encode(toSpeak,"ISO8859-15"));
            //URI uri = new URI(baseURI + URLEncoder.encode(toSpeak,"ISO8859-15"));
            //log.info(baseURI + toSpeak.replaceAll(" ", "%20"));
            //URI uri = new URI(baseURI + toSpeak.replaceAll(" ", "%20"));

            log.info(uri.toASCIIString());
            // HTTPClient.HTTPData data =
            // HTTPClient.get(uri.toASCIIString());

            HttpGet request = new HttpGet(uri.toASCIIString());
            HttpResponse response = client.execute(request);

            byte[] data = getByteArrayFromResponse(response);

            FileOutputStream fos = new FileOutputStream(audioFileName);
            fos.write(data);
            fos.close();

        } catch (Exception e) {
            Logging.logError(e);
        }

    }

    invoke("isSpeaking", true);
    invoke("saying", toSpeak);
    audioFile.playFile(audioFileName, true);
    sleep(afterSpeechPause);// important pause after speech
    invoke("isSpeaking", false);
}

From source file:org.teiid.olingo.TeiidODataJsonSerializer.java

public SerializerResult complexCollection(final ServiceMetadata metadata, final EdmComplexType type,
        final Property result, final ContextURL contextURL, final URI nextLink) throws SerializerException {
    CircleStreamBuffer buffer = new CircleStreamBuffer();
    try {/* w  w w .j  a  va  2  s  .c om*/
        JsonGenerator json = new JsonFactory().createGenerator(buffer.getOutputStream());
        json.writeStartObject();

        if (contextURL != null && (isODataMetadataFull || !isODataMetadataNone)) {
            json.writeStringField(Constants.JSON_CONTEXT, ContextURLBuilder.create(contextURL).toASCIIString());
        }
        json.writeFieldName(Constants.VALUE);
        json.writeStartArray();
        for (Object value : result.asCollection()) {
            json.writeStartObject();
            writeComplexValue(metadata, type, ((ComplexValue) value).getValue(), null, json, null,
                    (ComplexValue) value, null, result.getName());
            json.writeEndObject();
        }
        json.writeEndArray();

        if (nextLink != null) {
            json.writeStringField(Constants.JSON_NEXT_LINK, nextLink.toASCIIString());
        }

        json.close();
    } catch (final IOException e) {
        throw new SerializerException("An I/O exception occurred.", e,
                SerializerException.MessageKeys.IO_EXCEPTION);
    }
    return SerializerResultImpl.with().content(buffer.getInputStream()).build();
}

From source file:org.apache.taverna.scufl2.translator.t2flow.T2FlowParser.java

public Unmarshaller getUnmarshaller() {
    Unmarshaller u = unmarshaller.get();
    if (!isValidating() && u.getSchema() != null) {
        u.setSchema(null);//from w ww  .  j a va  2s  .c  o m
    } else if (isValidating() && u.getSchema() == null) {
        // Load and set schema to validate against
        Schema schema;
        try {
            SchemaFactory schemaFactory = SchemaFactory.newInstance(W3C_XML_SCHEMA_NS_URI);
            List<URI> schemas = getAdditionalSchemas();
            URL t2flowExtendedXSD = T2FlowParser.class.getResource(T2FLOW_EXTENDED_XSD);
            schemas.add(t2flowExtendedXSD.toURI());

            List<Source> schemaSources = new ArrayList<>();
            for (URI schemaUri : schemas)
                schemaSources.add(new StreamSource(schemaUri.toASCIIString()));
            Source[] sources = schemaSources.toArray(new Source[schemaSources.size()]);
            schema = schemaFactory.newSchema(sources);
        } catch (SAXException e) {
            throw new RuntimeException("Can't load schemas", e);
        } catch (URISyntaxException | NullPointerException e) {
            throw new RuntimeException("Can't find schemas", e);
        }
        u.setSchema(schema);
    }
    return u;
}

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

@Override
public Entity getEntity(final ClientEntity odataEntity) {
    final Entity entity = new Entity();

    entity.setType(odataEntity.getTypeName() == null ? null : odataEntity.getTypeName().toString());

    // -------------------------------------------------------------
    // Add edit and self link
    // -------------------------------------------------------------
    final URI odataEditLink = odataEntity.getEditLink();
    if (odataEditLink != null) {
        final Link editLink = new Link();
        editLink.setTitle(entity.getType());
        editLink.setHref(odataEditLink.toASCIIString());
        editLink.setRel(Constants.EDIT_LINK_REL);
        entity.setEditLink(editLink);/* w  w  w.java  2  s.  c  om*/
    }

    if (odataEntity.isReadOnly()) {
        final Link selfLink = new Link();
        selfLink.setTitle(entity.getType());
        selfLink.setHref(odataEntity.getLink().toASCIIString());
        selfLink.setRel(Constants.SELF_LINK_REL);
        entity.setSelfLink(selfLink);
    }
    // -------------------------------------------------------------

    links(odataEntity, entity);

    // -------------------------------------------------------------
    // Append edit-media links
    // -------------------------------------------------------------
    for (ClientLink link : odataEntity.getMediaEditLinks()) {
        LOG.debug("Append edit-media link\n{}", link);
        entity.getMediaEditLinks().add(getLink(link));
    }
    // -------------------------------------------------------------

    if (odataEntity.isMediaEntity()) {
        entity.setMediaContentSource(odataEntity.getMediaContentSource());
        entity.setMediaContentType(odataEntity.getMediaContentType());
        entity.setMediaETag(odataEntity.getMediaETag());
    }

    for (ClientProperty property : odataEntity.getProperties()) {
        entity.getProperties().add(getProperty(property));
    }

    entity.setId(odataEntity.getId());
    annotations(odataEntity, entity);
    return entity;
}

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

@Override
public ClientDelta getODataDelta(final ResWrap<Delta> resource) {
    final URI base = resource.getContextURL() == null ? resource.getPayload().getBaseURI()
            : ContextURLParser.parse(resource.getContextURL()).getServiceRoot();

    final URI next = resource.getPayload().getNext();

    final ClientDelta delta = next == null ? client.getObjectFactory().newDelta()
            : client.getObjectFactory().newDelta(URIUtils.getURI(base, next.toASCIIString()));

    if (resource.getPayload().getCount() != null) {
        delta.setCount(resource.getPayload().getCount());
    }// w  w  w  . ja  va2 s .c  om

    if (resource.getPayload().getDeltaLink() != null) {
        delta.setDeltaLink(URIUtils.getURI(base, resource.getPayload().getDeltaLink()));
    }

    for (Entity entityResource : resource.getPayload().getEntities()) {
        add(delta, getODataEntity(
                new ResWrap<Entity>(resource.getContextURL(), resource.getMetadataETag(), entityResource)));
    }
    for (DeletedEntity deletedEntity : resource.getPayload().getDeletedEntities()) {
        final ClientDeletedEntityImpl impl = new ClientDeletedEntityImpl();
        impl.setId(URIUtils.getURI(base, deletedEntity.getId()));
        impl.setReason(Reason.valueOf(deletedEntity.getReason().name()));

        delta.getDeletedEntities().add(impl);
    }

    odataAnnotations(resource.getPayload(), delta);

    for (DeltaLink link : resource.getPayload().getAddedLinks()) {
        final ClientDeltaLink impl = new ClientDeltaLinkImpl();
        impl.setRelationship(link.getRelationship());
        impl.setSource(URIUtils.getURI(base, link.getSource()));
        impl.setTarget(URIUtils.getURI(base, link.getTarget()));

        odataAnnotations(link, impl);

        delta.getAddedLinks().add(impl);
    }
    for (DeltaLink link : resource.getPayload().getDeletedLinks()) {
        final ClientDeltaLink impl = new ClientDeltaLinkImpl();
        impl.setRelationship(link.getRelationship());
        impl.setSource(URIUtils.getURI(base, link.getSource()));
        impl.setTarget(URIUtils.getURI(base, link.getTarget()));

        odataAnnotations(link, impl);

        delta.getDeletedLinks().add(impl);
    }

    return delta;
}

From source file:uk.ac.open.kmi.iserve.sal.manager.impl.RegistryManagerImpl.java

/**
 * Registers all the services found on a given source document. This operation takes care of performing the
 * appropriate format transformation. The source document is not stored on the server. For keeping a copy of the
 * source document within the server use @see importServices instead.
 *
 * @param sourceDocumentUri//  w  w  w  . ja v  a 2 s.c om
 * @param mediaType
 * @return the List of URIs of the services registered
 * @throws SalException
 */
@Override
public List<URI> registerServices(URI sourceDocumentUri, String mediaType) throws SalException {

    boolean isNativeFormat = MediaType.NATIVE_MEDIATYPE_SYNTAX_MAP.containsKey(mediaType);
    // Throw error if Format Unsupported
    if (!isNativeFormat && !this.serviceTransformationEngine.canTransform(mediaType)) {
        log.error("The media type {} is not natively supported and has no suitable transformer.", mediaType);
        throw new ServiceException("Unable to import service. Format unsupported.");
    }

    List<URI> registeredServices = new ArrayList<URI>();

    log.debug("Registering services from document: {}", sourceDocumentUri.toASCIIString());
    // 1st Obtain the document and parse/transform it
    List<Service> services = getServicesFromRemoteLocation(mediaType, isNativeFormat, sourceDocumentUri);

    if (services != null && !services.isEmpty()) {
        log.debug("Services found: {}. Registering ...", services.size());
        URI serviceUri;
        for (Service service : services) {
            // 2nd Add the service
            serviceUri = this.serviceManager.addService(service);
            if (serviceUri != null) {
                registeredServices.add(serviceUri);
            }
        }
    }

    if (registeredServices.size() != services.size()) {
        log.warn("Found {} services in document {} but only imported {} services", services.size(),
                sourceDocumentUri, registeredServices.size());
    }

    return registeredServices;
}

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

protected <S extends EntityType<?>> void deleteEntity(final EntityInvocationHandler handler,
        final URI entitySetURI) {
    final EntityContext entityContext = getContext().entityContext();

    final URI baseURI = entitySetURI == null ? handler.getEntitySetURI() : entitySetURI;

    if (baseURI == null) {
        throw new IllegalStateException("Entity base URI not available");
    }//from  w w w  . j av  a 2 s . com

    final String name = handler.getUUID().getType()
            .getAnnotation(org.apache.olingo.ext.proxy.api.annotations.EntityType.class).name();

    final String namespace = handler.getUUID().getType().getAnnotation(Namespace.class).value();

    final ClientEntity template;

    final URI entityURI;
    if (handler.getEntityURI() == null || handler.getUUID().getKey() == null) {
        template = service.getClient().getObjectFactory().newEntity(new FullQualifiedName(namespace, name));
        CoreUtils.addProperties(getClient(), handler.getPropertyChanges(), template);
        final Object key = CoreUtils.getKey(getClient(), handler, handler.getUUID().getType(), template);

        entityURI = CoreUtils.buildEditLink(getClient(), baseURI.toASCIIString(), key).build();
        template.setEditLink(entityURI);
    } else {
        entityURI = handler.getEntityURI();
        template = handler.getEntity();
    }

    // https://issues.apache.org/jira/browse/OLINGO-395
    if (entityContext.isAttached(handler)) {
        entityContext.addFurtherDeletes(entityURI);
    } else {
        if (handler.getUUID().getKey() == null) {
            // objects created ad-hoc to generate deletion requests
            handler.updateEntityUUID(baseURI, handler.getUUID().getType(), template);
        } else {
            handler.updateUUID(baseURI, handler.getUUID().getType(), handler.getUUID().getKey());
        }
        entityContext.attach(handler, AttachedEntityStatus.DELETED, true);
    }
}