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:com.msopentech.odatajclient.proxy.api.impl.Container.java

private int processEntityContext(final EntityTypeInvocationHandler handler, int pos,
        final TransactionItems items, final List<EntityLinkDesc> delayedUpdates,
        final ODataChangeset changeset) {

    LOG.debug("Process '{}'", handler);

    items.put(handler, null);//  w w w . jav a2 s  .  com

    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 = EntityContainerFactory.getContext().entityContext()
                    .getStatus(target);

            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, changeset);
                    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));
        }
    }

    // insert into the batch
    LOG.debug("{}: Insert '{}' into the batch", pos, handler);
    batch(handler, entity, changeset);

    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());
            batchUpdate(handler, targetURI, entity, changeset);
            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");

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

            // 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());

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

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

    return pos;
}

From source file:de.fhg.iais.asc.xslt.binaries.download.Downloader.java

public void downloadBinary(URI uri, File target) {
    InputStream contentStream = null;
    try {//w w  w.j av  a  2  s  .co  m
        ClientResponse response = Downloader.client.resource(uri).get(ClientResponse.class);
        int retries = 0;
        while (!checkStatusCode(response) && retries < MAX_DOWNLOAD_RETRIES) {
            ++retries;
            try {
                Thread.sleep(DOWNLOAD_BINARY_TIMEOUT);
            } catch (InterruptedException e) {
                LOG.debug("Sleeping thread interrupted!");
            }

            response = Downloader.client.resource(uri).get(ClientResponse.class);
        }

        if (!checkStatusCode(response)) {
            String msg = "Downloading of \"" + uri.toASCIIString() + "\" failed with status "
                    + response.getStatus();
            throw new AscTechnicalErrorException(msg);
        }

        contentStream = response.getEntityInputStream();

        if (contentStream == null) {
            throw new IOException("No response entity");
        }

        writeStreamToFile(contentStream, target);

        if (!checkContentLength(target)) {
            String msg = "Content of response \"" + uri.toASCIIString() + "\" has a length of zero!";
            throw new AscTechnicalErrorException(msg);
        }
    } catch (Exception e) {
        if (target.exists() && !target.delete()) {
            LOG.warn(String.format("Could not delete invalid file \"%s\"", target.getAbsolutePath()));
        }

        String msg = "Exception downloading \"" + uri.toASCIIString() + "\"";
        LOG.error(msg, e);
        throw AscTechnicalErrorException.wrap(msg, e);
    } finally {
        IOUtils.closeQuietly(contentStream);
    }
}

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

@Override
public URI createDocument(InputStream docContent, String fileExtension, String mediaType)
        throws DocumentException {

    URI newDocUri = this.generateUniqueDocumentUri();
    try {/*from  w w  w  .j  av  a  2  s  .co m*/
        URI internalDocUri = this.getDocumentInternalUri(newDocUri);
        File docDir = new File(internalDocUri);
        FileUtil.createDirIfNotExists(docDir);
        File file = new File(
                new StringBuilder(docDir.getAbsolutePath()).append("/index.").append(fileExtension).toString());
        FileOutputStream out = new FileOutputStream(file);
        FileUtil.createDirIfNotExists(file.getParentFile());
        int size = IOUtils.copy(docContent, out);
        log.info("Document internal URI - " + internalDocUri.toASCIIString() + " - " + size + " bytes.");
        storeMediaType(file.getAbsolutePath(), mediaType);
    } catch (IOException e) {
        throw new DocumentException("Unable to add document to service.", e);
    }

    // Generate Event
    this.getEventBus().post(new DocumentCreatedEvent(new Date(), newDocUri));

    return newDocUri;
}

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

private EntityInvocationHandler(final Object entityKey, final ClientEntity entity, final URI entitySetURI,
        final Class<?> typeRef, final AbstractService<?> service) {

    super(typeRef, entity, service);

    final Object key = entityKey == null ? CoreUtils.getKey(getClient(), this, typeRef, entity) : entityKey;

    if (entity.getEditLink() != null) {
        this.baseURI = entity.getEditLink();
        this.uri = getClient().newURIBuilder(baseURI.toASCIIString());
    } else if (key != null) {
        final URIBuilder uriBuilder = CoreUtils.buildEditLink(getClient(), entitySetURI.toASCIIString(), key);

        this.uri = uriBuilder;
        this.baseURI = this.uri.build();
        entity.setEditLink(this.baseURI);
    } else {/*from  ww  w .  ja v  a 2  s  .  c o  m*/
        this.baseURI = null;
        this.uri = null;
    }

    this.internal = entity;
    getEntity().setMediaEntity(typeRef.getAnnotation(EntityType.class).hasStream());

    this.uuid = new EntityUUID(entitySetURI, typeRef, key);
}

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

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

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

    if (tree.has(Constants.VALUE) && tree.get(Constants.VALUE).isArray()) {
        throw new JsonParseException("Expected OData Entity, found EntitySet", parser.getCurrentLocation());
    }/*  w w w  .ja  v a  2s  .  com*/

    final Entity entity = new Entity();

    final 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) {
        entity.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_ETAG)) {
        entity.setETag(tree.get(Constants.JSON_ETAG).textValue());
        tree.remove(Constants.JSON_ETAG);
    }

    if (tree.hasNonNull(Constants.JSON_TYPE)) {
        entity.setType(new EdmTypeInfo.Builder().setTypeExpression(tree.get(Constants.JSON_TYPE).textValue())
                .build().internal());
        tree.remove(Constants.JSON_TYPE);
    }

    if (tree.hasNonNull(Constants.JSON_ID)) {
        entity.setId(URI.create(tree.get(Constants.JSON_ID).textValue()));
        tree.remove(Constants.JSON_ID);
    }

    if (tree.hasNonNull(Constants.JSON_READ_LINK)) {
        final Link link = new Link();
        link.setRel(Constants.SELF_LINK_REL);
        link.setHref(tree.get(Constants.JSON_READ_LINK).textValue());
        entity.setSelfLink(link);

        tree.remove(Constants.JSON_READ_LINK);
    }

    if (tree.hasNonNull(Constants.JSON_EDIT_LINK)) {
        final Link link = new Link();
        if (serverMode) {
            link.setRel(Constants.EDIT_LINK_REL);
        }
        link.setHref(tree.get(Constants.JSON_EDIT_LINK).textValue());
        entity.setEditLink(link);

        tree.remove(Constants.JSON_EDIT_LINK);
    }

    if (tree.hasNonNull(Constants.JSON_MEDIA_READ_LINK)) {
        entity.setMediaContentSource(URI.create(tree.get(Constants.JSON_MEDIA_READ_LINK).textValue()));
        tree.remove(Constants.JSON_MEDIA_READ_LINK);
    }
    if (tree.hasNonNull(Constants.JSON_MEDIA_EDIT_LINK)) {
        entity.setMediaContentSource(URI.create(tree.get(Constants.JSON_MEDIA_EDIT_LINK).textValue()));
        tree.remove(Constants.JSON_MEDIA_EDIT_LINK);
    }
    if (tree.hasNonNull(Constants.JSON_MEDIA_CONTENT_TYPE)) {
        entity.setMediaContentType(tree.get(Constants.JSON_MEDIA_CONTENT_TYPE).textValue());
        tree.remove(Constants.JSON_MEDIA_CONTENT_TYPE);
    }
    if (tree.hasNonNull(Constants.JSON_MEDIA_ETAG)) {
        entity.setMediaETag(tree.get(Constants.JSON_MEDIA_ETAG).textValue());
        tree.remove(Constants.JSON_MEDIA_ETAG);
    }

    final Set<String> toRemove = new HashSet<String>();

    final Map<String, List<Annotation>> annotations = new HashMap<String, List<Annotation>>();
    for (final Iterator<Map.Entry<String, JsonNode>> itor = tree.fields(); itor.hasNext();) {
        final Map.Entry<String, JsonNode> field = itor.next();
        final Matcher customAnnotation = CUSTOM_ANNOTATION.matcher(field.getKey());

        links(field, entity, toRemove, tree, parser.getCodec());
        if (field.getKey().endsWith(getJSONAnnotation(Constants.JSON_MEDIA_READ_LINK))) {
            final Link link = new Link();
            link.setTitle(getTitle(field));
            link.setRel(Constants.NS_MEDIA_READ_LINK_REL + getTitle(field));
            link.setType(Constants.MEDIA_EDIT_LINK_TYPE);
            link.setHref(field.getValue().textValue());
            entity.getMediaEditLinks().add(link);

            if (tree.has(link.getTitle() + getJSONAnnotation(Constants.JSON_MEDIA_ETAG))) {
                link.setMediaETag(
                        tree.get(link.getTitle() + getJSONAnnotation(Constants.JSON_MEDIA_ETAG)).asText());
                toRemove.add(link.getTitle() + getJSONAnnotation(Constants.JSON_MEDIA_ETAG));
            }

            if (tree.has(link.getTitle() + getJSONAnnotation(Constants.JSON_MEDIA_CONTENT_TYPE))) {
                link.setType(tree.get(link.getTitle() + getJSONAnnotation(Constants.JSON_MEDIA_CONTENT_TYPE))
                        .asText());
                toRemove.add(link.getTitle() + getJSONAnnotation(Constants.JSON_MEDIA_CONTENT_TYPE));
            }

            toRemove.add(field.getKey());
            toRemove.add(setInline(field.getKey(), getJSONAnnotation(Constants.JSON_MEDIA_READ_LINK), tree,
                    parser.getCodec(), link));
        } else if (field.getKey().endsWith(getJSONAnnotation(Constants.JSON_MEDIA_EDIT_LINK))) {
            final Link link = getOrCreateMediaLink(entity, getTitle(field));
            link.setRel(Constants.NS_MEDIA_EDIT_LINK_REL + getTitle(field));
            link.setHref(field.getValue().textValue());
            toRemove.add(field.getKey());
            toRemove.add(setInline(field.getKey(), getJSONAnnotation(Constants.JSON_MEDIA_EDIT_LINK), tree,
                    parser.getCodec(), link));
        } else if (field.getKey().endsWith(getJSONAnnotation(Constants.JSON_MEDIA_CONTENT_TYPE))) {
            final Link link = getOrCreateMediaLink(entity, getTitle(field));
            link.setType(field.getValue().asText());
            toRemove.add(field.getKey());
        } else if (field.getKey().endsWith(getJSONAnnotation(Constants.JSON_MEDIA_ETAG))) {
            final Link link = getOrCreateMediaLink(entity, getTitle(field));
            link.setMediaETag(field.getValue().asText());
            toRemove.add(field.getKey());
        } 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()));

            entity.getOperations().add(operation);

            toRemove.add(field.getKey());
        } else if (customAnnotation.matches() && !"odata".equals(customAnnotation.group(2))) {
            final Annotation annotation = new Annotation();
            annotation.setTerm(customAnnotation.group(2) + "." + customAnnotation.group(3));
            try {
                value(annotation, field.getValue(), parser.getCodec());
            } catch (final EdmPrimitiveTypeException e) {
                throw new IOException(e);
            }

            if (!annotations.containsKey(customAnnotation.group(1))) {
                annotations.put(customAnnotation.group(1), new ArrayList<Annotation>());
            }
            annotations.get(customAnnotation.group(1)).add(annotation);
        }
    }

    for (Link link : entity.getNavigationLinks()) {
        if (annotations.containsKey(link.getTitle())) {
            link.getAnnotations().addAll(annotations.get(link.getTitle()));
            for (Annotation annotation : annotations.get(link.getTitle())) {
                toRemove.add(link.getTitle() + "@" + annotation.getTerm());
            }
        }
    }
    for (Link link : entity.getMediaEditLinks()) {
        if (annotations.containsKey(link.getTitle())) {
            link.getAnnotations().addAll(annotations.get(link.getTitle()));
            for (Annotation annotation : annotations.get(link.getTitle())) {
                toRemove.add(link.getTitle() + "@" + annotation.getTerm());
            }
        }
    }

    tree.remove(toRemove);

    try {
        populate(entity, entity.getProperties(), tree, parser.getCodec());
    } catch (final EdmPrimitiveTypeException e) {
        throw new IOException(e);
    }

    return new ResWrap<Entity>(contextURL, metadataETag, entity);
}

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

@Override
public List<URI> importServices(URI servicesContentLocation, 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.");
    }//from ww w .jav a  2s  .c o  m

    // Obtain the file extension to use
    String fileExtension = findFileExtensionToUse(mediaType, isNativeFormat);

    List<Service> services = null;
    List<URI> importedServices = new ArrayList<URI>();
    URI sourceDocUri = null;
    InputStream localStream = null;
    try {
        // 1st Store the document
        sourceDocUri = this.docManager.createDocument(servicesContentLocation, fileExtension, mediaType);
        if (sourceDocUri == null) {
            throw new ServiceException("Unable to save service document. Operation aborted.");
        }

        // 2nd Parse and Transform the document
        // The original stream may be a one-of stream so save it first and read locally
        services = getServicesFromRemoteLocation(mediaType, isNativeFormat, servicesContentLocation);

        // 3rd - Store the resulting MSM services. There may be more than one
        URI serviceUri = null;
        if (services != null && !services.isEmpty()) {
            log.info("Importing {} services", services.size());
            for (Service service : services) {
                // The service is being imported -> update the source
                URI originalSource = service.getSource();
                service.setSource(sourceDocUri);
                for (Operation op : service.getOperations()) {
                    if (op.getSource().equals(originalSource)) {
                        op.setSource(sourceDocUri);
                    }
                    if (op.getSource().toASCIIString().contains(originalSource.toASCIIString())) {
                        String subPath = op.getSource().toASCIIString().replace(originalSource.toASCIIString(),
                                "");
                        try {
                            op.setSource(new URI(new StringBuilder(sourceDocUri.toASCIIString()).append(subPath)
                                    .toString()));
                        } catch (URISyntaxException e) {
                            e.printStackTrace();
                        }
                    }
                }

                serviceUri = this.serviceManager.addService(service);
                if (serviceUri != null) {
                    importedServices.add(serviceUri);
                }
            }
        }

        // 4th Log it was all done correctly
        // TODO: log to the system and notify observers
        log.info("Source document imported: {}", sourceDocUri.toASCIIString());

    } finally {
        // Rollback if something went wrong
        if ((services == null || (services != null && services.size() != importedServices.size()))
                && sourceDocUri != null) {
            this.docManager.deleteDocument(sourceDocUri);
            for (URI svcUri : importedServices) {
                this.serviceManager.deleteService(svcUri);
            }
            log.warn("There were problems importing the service. Changes undone.");
        }

        if (localStream != null)
            try {
                localStream.close();
            } catch (IOException e) {
                log.error("Error closing the service content stream", e);
            }
    }

    return importedServices;
}

From source file:org.nimbustools.messaging.gt4_0_elastic.v2008_05_05.image.defaults.DefaultRepository.java

protected VMFile getRootFile(String imageID, String ownerID) throws CannotTranslateException {

    if (imageID == null) {
        throw new CannotTranslateException("Request is missing image ID");
    }//from w w w. j ava2s . c  o  m

    if (ownerID == null) {
        throw new CannotTranslateException("Request is missing image ID");
    }

    String baseDir = this.getBaseDirectory();
    if (baseDir == null) {
        throw new CannotTranslateException("base directory missing");
    }

    final String imageURIstr = baseDir + "/" + ownerID + "/" + imageID;
    URI imageURI;
    try {
        imageURI = new URI(imageURIstr);
    } catch (URISyntaxException e) {
        throw new CannotTranslateException(e.getMessage(), e);
    }

    if (this.scheme != null && this.scheme.equals("scp")) {
        baseDir = baseDir.replaceFirst("gsiftp", "http");
        final URL url;
        try {
            url = new URL(baseDir);
        } catch (MalformedURLException e) {
            throw new CannotTranslateException("unexpected, invalid URL: " + imageURI.toASCIIString(), e);
        }
        if (url.getPort() != 22) {
            String newurl = "scp://";
            newurl += url.getHost();
            newurl += ":22";
            newurl += url.getPath() + "/" + ownerID + "/" + imageID;
            try {
                imageURI = new URI(newurl);
            } catch (URISyntaxException e) {
                throw new CannotTranslateException(e.getMessage(), e);
            }
        }
    }

    final _VMFile file = this.repr._newVMFile();
    file.setRootFile(true);
    file.setDiskPerms(VMFile.DISKPERMS_ReadWrite);
    file.setMountAs(this.getRootFileMountAs());
    file.setURI(imageURI);
    return file;
}

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

@Override
public URI createDocument(URI docRemoteLocation, String fileExtension, String mediaType)
        throws DocumentException {

    log.debug("Creating document from {} - File extension: {}", docRemoteLocation, fileExtension);
    URI newDocUri = this.generateUniqueDocumentUri();
    try {/*from ww w  .  j a v a  2 s . com*/
        URI internalDocUri = this.getDocumentInternalUri(newDocUri);
        File docDir = new File(internalDocUri);
        FileUtil.createDirIfNotExists(docDir);
        File file = new File(
                new StringBuilder(docDir.getAbsolutePath()).append("/index.").append(fileExtension).toString());
        FileOutputStream out = new FileOutputStream(file);
        FileUtil.createDirIfNotExists(file.getParentFile());
        int size = IOUtils.copy(docRemoteLocation.toURL().openStream(), out);
        log.info("Document internal URI - " + internalDocUri.toASCIIString() + " - " + size + " bytes.");
        storeMediaType(file.getAbsolutePath(), mediaType);
        if (fileExtension.equals("json")) {
            storeSwaggerApiDeclarations(file, docDir.getAbsolutePath(), docRemoteLocation, mediaType);
        }
    } catch (IOException e) {
        throw new DocumentException("Unable to add document to service.", e);
    }

    // Generate Event
    this.getEventBus().post(new DocumentCreatedEvent(new Date(), newDocUri));

    return newDocUri;
}

From source file:org.apache.syncope.client.console.topology.Topology.java

public Topology() {
    modal = new BaseModal<>("resource-modal");
    body.add(modal.size(Modal.Size.Large));
    modal.setWindowClosedCallback(new ModalWindow.WindowClosedCallback() {

        private static final long serialVersionUID = 8804221891699487139L;

        @Override//from  w  ww  . j  av  a 2  s. com
        public void onClose(final AjaxRequestTarget target) {
            modal.show(false);
        }
    });

    final TopologyWebSocketBehavior websocket = new TopologyWebSocketBehavior();
    body.add(websocket);

    togglePanel = new TopologyTogglePanel("toggle", getPageReference());
    body.add(togglePanel);

    // -----------------------------------------
    // Add Zoom panel
    // -----------------------------------------
    final ActionsPanel<Serializable> zoomActionPanel = new ActionsPanel<>("zoom", null);

    zoomActionPanel.add(new ActionLink<Serializable>() {

        private static final long serialVersionUID = -3722207913631435501L;

        @Override
        public void onClick(final AjaxRequestTarget target, final Serializable ignore) {
            target.appendJavaScript("zoomIn($('#drawing')[0]);");
        }
    }, ActionLink.ActionType.ZOOM_IN, StandardEntitlement.CONNECTOR_LIST).disableIndicator().hideLabel();
    zoomActionPanel.add(new ActionLink<Serializable>() {

        private static final long serialVersionUID = -3722207913631435501L;

        @Override
        public void onClick(final AjaxRequestTarget target, final Serializable ignore) {
            target.appendJavaScript("zoomOut($('#drawing')[0]);");
        }
    }, ActionLink.ActionType.ZOOM_OUT, StandardEntitlement.CONNECTOR_LIST).disableIndicator().hideLabel();

    body.add(zoomActionPanel);
    // -----------------------------------------

    // -----------------------------------------
    // Add Syncope (root topologynode)
    // -----------------------------------------
    final TopologyNode syncopeTopologyNode = new TopologyNode(ROOT_NAME, ROOT_NAME, TopologyNode.Kind.SYNCOPE);
    syncopeTopologyNode.setX(origX);
    syncopeTopologyNode.setY(origY);

    final URI uri = WebClient.client(BaseRestClient.getSyncopeService()).getBaseURI();
    syncopeTopologyNode.setHost(uri.getHost());
    syncopeTopologyNode.setPort(uri.getPort());

    body.add(topologyNodePanel("syncope", syncopeTopologyNode));

    final Map<Serializable, Map<Serializable, TopologyNode>> connections = new HashMap<>();
    final Map<Serializable, TopologyNode> syncopeConnections = new HashMap<>();
    connections.put(syncopeTopologyNode.getKey(), syncopeConnections);

    // required to retrieve parent positions
    final Map<String, TopologyNode> servers = new HashMap<>();
    final Map<String, TopologyNode> connectors = new HashMap<>();
    // -----------------------------------------

    // -----------------------------------------
    // Add Connector Servers
    // -----------------------------------------
    final ListView<URI> connectorServers = new ListView<URI>("connectorServers",
            csModel.getObject().getLeft()) {

        private static final long serialVersionUID = 6978621871488360380L;

        private final int size = csModel.getObject().getLeft().size() + 1;

        @Override
        protected void populateItem(final ListItem<URI> item) {
            int kx = size >= 4 ? 800 : (200 * size);

            int x = (int) Math.round(origX + kx * Math.cos(Math.PI + Math.PI * (item.getIndex() + 1) / size));
            int y = (int) Math.round(origY + 100 * Math.sin(Math.PI + Math.PI * (item.getIndex() + 1) / size));

            final URI location = item.getModelObject();
            final String url = location.toASCIIString();

            final TopologyNode topologynode = new TopologyNode(url, url, TopologyNode.Kind.CONNECTOR_SERVER);

            topologynode.setHost(location.getHost());
            topologynode.setPort(location.getPort());
            topologynode.setX(x);
            topologynode.setY(y);

            servers.put(String.class.cast(topologynode.getKey()), topologynode);

            item.add(topologyNodePanel("cs", topologynode));

            syncopeConnections.put(url, topologynode);
            connections.put(url, new HashMap<>());
        }
    };

    connectorServers.setOutputMarkupId(true);
    body.add(connectorServers);
    // -----------------------------------------

    // -----------------------------------------
    // Add File Paths
    // -----------------------------------------
    final ListView<URI> filePaths = new ListView<URI>("filePaths", csModel.getObject().getRight()) {

        private static final long serialVersionUID = 6978621871488360380L;

        private final int size = csModel.getObject().getRight().size() + 1;

        @Override
        protected void populateItem(final ListItem<URI> item) {
            int kx = size >= 4 ? 800 : (200 * size);

            int x = (int) Math.round(origX + kx * Math.cos(Math.PI * (item.getIndex() + 1) / size));
            int y = (int) Math.round(origY + 100 * Math.sin(Math.PI * (item.getIndex() + 1) / size));

            final URI location = item.getModelObject();
            final String url = location.toASCIIString();

            final TopologyNode topologynode = new TopologyNode(url, url, TopologyNode.Kind.FS_PATH);

            topologynode.setHost(location.getHost());
            topologynode.setPort(location.getPort());
            topologynode.setX(x);
            topologynode.setY(y);

            servers.put(String.class.cast(topologynode.getKey()), topologynode);

            item.add(topologyNodePanel("fp", topologynode));

            syncopeConnections.put(url, topologynode);
            connections.put(url, new HashMap<>());
        }
    };

    filePaths.setOutputMarkupId(true);
    body.add(filePaths);
    // -----------------------------------------

    // -----------------------------------------
    // Add Connector Intances
    // -----------------------------------------
    final List<List<ConnInstanceTO>> allConns = new ArrayList<>(connModel.getObject().values());

    final ListView<List<ConnInstanceTO>> conns = new ListView<List<ConnInstanceTO>>("conns", allConns) {

        private static final long serialVersionUID = 697862187148836036L;

        @Override
        protected void populateItem(final ListItem<List<ConnInstanceTO>> item) {

            final int size = item.getModelObject().size() + 1;

            final ListView<ConnInstanceTO> conns = new ListView<ConnInstanceTO>("conns",
                    item.getModelObject()) {

                private static final long serialVersionUID = 6978621871488360381L;

                @Override
                protected void populateItem(final ListItem<ConnInstanceTO> item) {
                    final ConnInstanceTO conn = item.getModelObject();

                    final TopologyNode topologynode = new TopologyNode(conn.getKey(),
                            StringUtils.isBlank(conn.getDisplayName()) // [SYNCOPE-1233]
                                    ? conn.getBundleName()
                                    : conn.getDisplayName(),
                            TopologyNode.Kind.CONNECTOR);

                    // Define the parent note
                    final TopologyNode parent = servers.get(conn.getLocation());

                    // Set the position
                    int kx = size >= 6 ? 800 : (130 * size);

                    final double hpos;
                    if (conn.getLocation().startsWith(CONNECTOR_SERVER_LOCATION_PREFIX)) {
                        hpos = Math.PI;
                    } else {
                        hpos = 0.0;
                    }

                    int x = (int) Math.round((parent == null ? origX : parent.getX())
                            + kx * Math.cos(hpos + Math.PI * (item.getIndex() + 1) / size));
                    int y = (int) Math.round((parent == null ? origY : parent.getY())
                            + 100 * Math.sin(hpos + Math.PI * (item.getIndex() + 1) / size));

                    topologynode.setConnectionDisplayName(conn.getBundleName());
                    topologynode.setX(x);
                    topologynode.setY(y);

                    connectors.put(String.class.cast(topologynode.getKey()), topologynode);
                    item.add(topologyNodePanel("conn", topologynode));

                    // Update connections
                    final Map<Serializable, TopologyNode> remoteConnections;

                    if (connections.containsKey(conn.getLocation())) {
                        remoteConnections = connections.get(conn.getLocation());
                    } else {
                        remoteConnections = new HashMap<>();
                        connections.put(conn.getLocation(), remoteConnections);
                    }
                    remoteConnections.put(conn.getKey(), topologynode);
                }
            };

            conns.setOutputMarkupId(true);
            item.add(conns);
        }
    };

    conns.setOutputMarkupId(true);
    body.add(conns);
    // -----------------------------------------

    // -----------------------------------------
    // Add Resources
    // -----------------------------------------
    final Collection<String> adminConns = new HashSet<>();
    connModel.getObject().values().forEach(connInstances -> {
        adminConns.addAll(connInstances.stream().map(EntityTO::getKey).collect(Collectors.toList()));
    });

    final Set<String> adminRes = new HashSet<>();
    final List<String> connToBeProcessed = new ArrayList<>();
    resModel.getObject().stream().filter((resourceTO) -> (adminConns.contains(resourceTO.getConnector())))
            .forEachOrdered(resourceTO -> {
                final TopologyNode topologynode = new TopologyNode(resourceTO.getKey(), resourceTO.getKey(),
                        TopologyNode.Kind.RESOURCE);
                final Map<Serializable, TopologyNode> remoteConnections;
                if (connections.containsKey(resourceTO.getConnector())) {
                    remoteConnections = connections.get(resourceTO.getConnector());
                } else {
                    remoteConnections = new HashMap<>();
                    connections.put(resourceTO.getConnector(), remoteConnections);
                }
                remoteConnections.put(topologynode.getKey(), topologynode);

                adminRes.add(resourceTO.getKey());

                if (!connToBeProcessed.contains(resourceTO.getConnector())) {
                    connToBeProcessed.add(resourceTO.getConnector());
                }
            });

    final ListView<String> resources = new ListView<String>("resources", connToBeProcessed) {

        private static final long serialVersionUID = 697862187148836038L;

        @Override
        protected void populateItem(final ListItem<String> item) {
            final String connectorKey = item.getModelObject();

            final ListView<TopologyNode> innerListView = new ListView<TopologyNode>("resources",
                    new ArrayList<>(connections.get(connectorKey).values())) {

                private static final long serialVersionUID = -3447760771863754342L;

                private final int size = getModelObject().size() + 1;

                @Override
                protected void populateItem(final ListItem<TopologyNode> item) {
                    final TopologyNode topologynode = item.getModelObject();
                    final TopologyNode parent = connectors.get(connectorKey);

                    // Set position
                    int kx = size >= 16 ? 800 : (48 * size);
                    int ky = size < 4 ? 100 : size < 6 ? 350 : 750;

                    final double hpos;
                    if (parent == null || parent.getY() < syncopeTopologyNode.getY()) {
                        hpos = Math.PI;
                    } else {
                        hpos = 0.0;
                    }

                    int x = (int) Math.round((parent == null ? origX : parent.getX())
                            + kx * Math.cos(hpos + Math.PI * (item.getIndex() + 1) / size));
                    int y = (int) Math.round((parent == null ? origY : parent.getY())
                            + ky * Math.sin(hpos + Math.PI * (item.getIndex() + 1) / size));

                    topologynode.setX(x);
                    topologynode.setY(y);

                    item.add(topologyNodePanel("res", topologynode));
                }
            };

            innerListView.setOutputMarkupId(true);
            item.add(innerListView);
        }
    };

    resources.setOutputMarkupId(true);
    body.add(resources);
    // -----------------------------------------

    // -----------------------------------------
    // Create connections
    // -----------------------------------------
    final WebMarkupContainer jsPlace = new WebMarkupContainerNoVeil("jsPlace");
    jsPlace.setOutputMarkupId(true);
    body.add(jsPlace);

    jsPlace.add(new Behavior() {

        private static final long serialVersionUID = 2661717818979056044L;

        @Override
        public void renderHead(final Component component, final IHeaderResponse response) {
            final StringBuilder jsPlumbConf = new StringBuilder();
            jsPlumbConf.append(String.format(Locale.US, "activate(%.2f);", 0.68f));

            createConnections(connections).forEach(str -> {
                jsPlumbConf.append(str);
            });

            response.render(OnDomReadyHeaderItem.forScript(jsPlumbConf.toString()));
        }
    });

    jsPlace.add(new AbstractAjaxTimerBehavior(Duration.seconds(2)) {

        private static final long serialVersionUID = -4426283634345968585L;

        @Override
        protected void onTimer(final AjaxRequestTarget target) {
            if (websocket.connCheckDone(adminConns) && websocket.resCheckDone(adminRes)) {
                stop(target);
            }

            target.appendJavaScript("checkConnection()");

            if (getUpdateInterval().seconds() < 5.0) {
                setUpdateInterval(Duration.seconds(5));
            } else if (getUpdateInterval().seconds() < 10.0) {
                setUpdateInterval(Duration.seconds(10));
            } else if (getUpdateInterval().seconds() < 15.0) {
                setUpdateInterval(Duration.seconds(15));
            } else if (getUpdateInterval().seconds() < 20.0) {
                setUpdateInterval(Duration.seconds(20));
            } else if (getUpdateInterval().seconds() < 30.0) {
                setUpdateInterval(Duration.seconds(30));
            } else if (getUpdateInterval().seconds() < 60.0) {
                setUpdateInterval(Duration.seconds(60));
            }
        }
    });
    // -----------------------------------------

    newlyCreatedContainer = new WebMarkupContainer("newlyCreatedContainer");
    newlyCreatedContainer.setOutputMarkupId(true);
    body.add(newlyCreatedContainer);

    newlyCreated = new ListView<TopologyNode>("newlyCreated", new ArrayList<TopologyNode>()) {

        private static final long serialVersionUID = 4949588177564901031L;

        @Override
        protected void populateItem(final ListItem<TopologyNode> item) {
            item.add(topologyNodePanel("el", item.getModelObject()));
        }
    };
    newlyCreated.setOutputMarkupId(true);
    newlyCreated.setReuseItems(true);

    newlyCreatedContainer.add(newlyCreated);
}

From source file:com.amytech.android.library.utils.asynchttp.AsyncHttpClient.java

/**
 * Will encode url, if not disabled, and adds params on the end of it
 *
 * @param url/*  ww w  .jav  a2  s  .com*/
 *            String with URL, should be valid URL without params
 * @param params
 *            RequestParams to be appended on the end of URL
 * @param shouldEncodeUrl
 *            whether url should be encoded (replaces spaces with %20)
 * @return encoded url if requested with params appended if any available
 */
public static String getUrlWithQueryString(boolean shouldEncodeUrl, String url, RequestParams params) {
    if (url == null)
        return null;

    if (shouldEncodeUrl) {
        try {
            String decodedURL = URLDecoder.decode(url, "UTF-8");
            URL _url = new URL(decodedURL);
            URI _uri = new URI(_url.getProtocol(), _url.getUserInfo(), _url.getHost(), _url.getPort(),
                    _url.getPath(), _url.getQuery(), _url.getRef());
            url = _uri.toASCIIString();
        } catch (Exception ex) {
            // Should not really happen, added just for sake of validity
            Log.e(LOG_TAG, "getUrlWithQueryString encoding URL", ex);
        }
    }

    if (params != null) {
        // Construct the query string and trim it, in case it
        // includes any excessive white spaces.
        String paramString = params.getParamString().trim();

        // Only add the query string if it isn't empty and it
        // isn't equal to '?'.
        if (!paramString.equals("") && !paramString.equals("?")) {
            url += url.contains("?") ? "&" : "?";
            url += paramString;
        }
    }

    return url;
}