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:net.es.sense.rm.api.SenseRmController.java

/**
 * Submits a proposed model delta to the Resource Manager based on the model
 * identified by modelId within the deltaRequest.
 *
 * Operation: POST /api/sense/v1/deltas/* w  ww .  j  av a2 s .  c  o m*/
 *
 * @param accept
 * @param deltaRequest
 * @param encode
 * @param model
 * @return
 * @throws java.net.URISyntaxException
 */
@ApiOperation(value = "Submits a proposed model delta to the Resource Manager based on the model "
        + "identified by id.", notes = "The Resource Manager must verify the proposed model change, confirming "
                + "(201 Created), rejecting (500 Internal Server Error), or proposing an "
                + "optional counter-offer (200 OK).", response = DeltaResource.class)
@ApiResponses(value = {
        @ApiResponse(code = HttpConstants.OK_CODE, message = HttpConstants.OK_DELTA_COUNTER_MSG, response = DeltaRequest.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class),
                @ResponseHeader(name = HttpConstants.LAST_MODIFIED_NAME, description = HttpConstants.LAST_MODIFIED_DESC, response = String.class) }),
        @ApiResponse(code = HttpConstants.CREATED_CODE, message = HttpConstants.CREATED_MSG, response = DeltaResource.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class),
                @ResponseHeader(name = HttpConstants.LAST_MODIFIED_NAME, description = HttpConstants.LAST_MODIFIED_DESC, response = String.class) }),
        @ApiResponse(code = HttpConstants.BAD_REQUEST_CODE, message = HttpConstants.BAD_REQUEST_MSG, response = Error.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class) }),
        @ApiResponse(code = HttpConstants.FORBIDDEN_CODE, message = HttpConstants.FORBIDDEN_MSG, response = Error.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class) }),
        @ApiResponse(code = HttpConstants.NOT_FOUND_CODE, message = HttpConstants.NOT_FOUND_MSG, response = Error.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class) }),
        @ApiResponse(code = HttpConstants.NOT_ACCEPTABLE_CODE, message = HttpConstants.NOT_ACCEPTABLE_MSG, response = Error.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class) }),
        @ApiResponse(code = HttpConstants.CONFLICT_CODE, message = HttpConstants.CONFLICT_MSG, response = Error.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class) }),
        @ApiResponse(code = HttpConstants.INTERNAL_ERROR_CODE, message = HttpConstants.INTERNAL_ERROR_MSG, response = Error.class, responseHeaders = {
                @ResponseHeader(name = HttpConstants.CONTENT_TYPE_NAME, description = HttpConstants.CONTENT_TYPE_DESC, response = String.class) }), })
@RequestMapping(value = "/deltas", method = RequestMethod.POST, consumes = {
        MediaType.APPLICATION_JSON_VALUE }, produces = { MediaType.APPLICATION_JSON_VALUE })
public ResponseEntity<?> propagateDelta(
        @RequestHeader(value = HttpConstants.ACCEPT_NAME, defaultValue = MediaType.APPLICATION_JSON_VALUE) @ApiParam(value = HttpConstants.ACCEPT_MSG, required = false) String accept,
        @RequestParam(value = HttpConstants.MODEL_NAME, defaultValue = HttpConstants.MODEL_TURTLE) @ApiParam(value = HttpConstants.MODEL_MSG, required = false) String model,
        @RequestParam(value = HttpConstants.ENCODE_NAME, defaultValue = "false") @ApiParam(value = HttpConstants.ENCODE_MSG, required = false) boolean encode,
        @RequestBody @ApiParam(value = "A JSON structure-containing the model reduction and/or addition "
                + " elements. If provided, the model reduction element is applied first, "
                + " followed by the model addition element.", required = true) DeltaRequest deltaRequest)
        throws URISyntaxException {

    final URI location = ServletUriComponentsBuilder.fromCurrentRequestUri().build().toUri();

    log.info(
            "[SenseRmController] POST operation = {}, accept = {}, deltaId = {}, modelId = {}, deltaRequest = {}",
            location, accept, deltaRequest.getId(), model, deltaRequest);

    // If the requester did not specify a delta id then we need to create one.
    if (Strings.isNullOrEmpty(deltaRequest.getId())) {
        deltaRequest.setId(UuidHelper.getUUID());
        log.info("[SenseRmController] assigning delta id = {}", deltaRequest.getId());
    }

    try {
        if (encode) {
            if (!Strings.isNullOrEmpty(deltaRequest.getAddition())) {
                deltaRequest.setAddition(Decoder.decode(deltaRequest.getAddition()));
            }

            if (!Strings.isNullOrEmpty(deltaRequest.getReduction())) {
                deltaRequest.setReduction(Decoder.decode(deltaRequest.getReduction()));
            }
        }

        // We need to return the current location of this resource in the response header.
        final HttpHeaders headers = new HttpHeaders();

        // Query for the requested delta.
        DeltaResponse response = driver.propagateDelta(deltaRequest, model).get();
        if (response == null || response.getStatus() != Status.CREATED) {
            return toResponseEntity(headers, response);
        }

        DeltaResource delta = response.getDelta().get();

        String contentLocation = UrlHelper.append(location.toASCIIString(), delta.getId());

        log.info("[SenseRmController] Delta id = {}, lastModified = {}, content-location = {}", delta.getId(),
                delta.getLastModified(), contentLocation);

        long lastModified = XmlUtilities.xmlGregorianCalendar(delta.getLastModified()).toGregorianCalendar()
                .getTimeInMillis();

        delta.setHref(contentLocation);
        if (encode) {
            if (!Strings.isNullOrEmpty(delta.getAddition())) {
                delta.setAddition(Encoder.encode(delta.getAddition()));
            }

            if (!Strings.isNullOrEmpty(delta.getReduction())) {
                delta.setReduction(Encoder.encode(delta.getReduction()));
            }

            if (!Strings.isNullOrEmpty(delta.getResult())) {
                delta.setResult(Encoder.encode(delta.getResult()));
            }
        }

        headers.add("Content-Location", contentLocation);
        headers.setLastModified(lastModified);

        log.info("[SenseRmController] Delta returning id = {}, creationTime = {}", delta.getId(),
                delta.getLastModified());

        return new ResponseEntity<>(delta, headers, HttpStatus.CREATED);
    } catch (InterruptedException | ExecutionException | IOException | DatatypeConfigurationException ex) {
        log.error("pullModel failed", ex);
        Error error = Error.builder().error(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase())
                .error_description(ex.getMessage()).build();
        return new ResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

From source file:net.sf.taverna.t2.security.credentialmanager.impl.CredentialManagerImpl.java

/**
 * Delete a username and password pair for the given service URI from the
 * Keystore./*  w w w.  ja  v a2 s.  co  m*/
 */
@Override
public void deleteUsernameAndPasswordForService(URI serviceURI) throws CMException {
    /*
     * Need to make sure we are initialized before we do anything else, as
     * the Credential Manager can be created but not initialized.
     */
    initialize();

    String uriString = serviceURI.toASCIIString();
    deleteUsernameAndPasswordForService(uriString);
}

From source file:net.sf.taverna.t2.security.credentialmanager.impl.CredentialManagerImpl.java

/**
 * Insert a username and password pair for the given service URI in the
 * Keystore.// www .j  a  v  a  2s .c o m
 * <p>
 * Effectively, this method inserts a new secret key entry in the Keystore,
 * where key contains <USERNAME>"\000"<PASSWORD> string, i.e. password is
 * prepended with the username and separated by a \000 character (which
 * hopefully will not appear in the username).
 * <p>
 * Username and password string is saved in the Keystore as byte array using
 * SecretKeySpec (which constructs a secret key from the given byte array
 * but does not check if the given bytes indeed specify a secret key of the
 * specified algorithm).
 * <p>
 * An alias used to identify the username and password entry is constructed
 * as "password#"<SERVICE_URL> using the service URL this username/password
 * pair is to be used for.
 * 
 * @param usernamePassword
 *            The {@link UsernamePassword} to store
 * @param serviceURI
 *            The (possibly normalized) URI to store the credentials under
 * @throws CMException
 *             If the credentials could not be stored
 * @return the alias under which this username and password entry was saved
 *         in the Keystore
 */
@Override
public String addUsernameAndPasswordForService(UsernamePassword usernamePassword, URI serviceURI)
        throws CMException {
    /*
     * Need to make sure we are initialized before we do anything else, as
     * the Credential Manager can be created but not initialized.
     */
    initialize();

    String uriString = serviceURI.toASCIIString();
    String alias = saveUsernameAndPasswordForService(usernamePassword.getUsername(),
            String.valueOf(usernamePassword.getPassword()), uriString);
    return alias;
}

From source file:org.apache.taverna.security.credentialmanager.impl.CredentialManagerImpl.java

/**
 * Get a username and password pair for the given service's URI, or null if
 * it does not exit.//from   ww w. ja  va  2  s.  c o m
 * <p>
 * If the username and password are not available in the Keystore, it will
 * invoke implementations of the {@link ServiceUsernameAndPasswordProvider}
 * interface asking the user (typically through the UI) or resolving
 * hard-coded credentials.
 * <p>
 * If the parameter <code>useURIPathRecursion</code> is true, then the
 * Credential Manager will also attempt to look for stored credentials for
 * each of the parent fragments of the URI.
 * 
 * @param serviceURI
 *            The URI of the service for which we are providing the username
 *            and password
 * @param useURIPathRecursion
 *            Whether to look for any username and passwords stored in the
 *            Keystore for the parent fragments of the service URI (for
 *            example, we are looking for the credentials for service
 *            http://somehost/some-fragment but we already have credentials
 *            stored for http://somehost which can be reused)
 * @param requestingMessage
 *            The message to be presented to the user when asking for the
 *            username and password, normally useful for UI providers that
 *            pop up dialogs, can be ignored otherwise
 * @return username and password pair for the given service
 * @throws CMException
 *             if anything goes wrong during Keystore lookup, etc.
 */
@Override
public UsernamePassword getUsernameAndPasswordForService(URI serviceURI, boolean usePathRecursion,
        String requestingMessage) throws CMException {
    // Need to make sure we are initialized before we do anything else
    // as Credential Manager can be created but not initialized
    initialize();

    synchronized (keystore) {
        SecretKeySpec passwordKey = null;
        LinkedHashSet<URI> possibleServiceURIsToLookup = getPossibleServiceURIsToLookup(serviceURI,
                usePathRecursion);
        Map<URI, URI> allServiceURIs = getFragmentMappedURIsForAllUsernameAndPasswordPairs();

        try {
            for (URI lookupURI : possibleServiceURIsToLookup) {
                URI mappedURI = allServiceURIs.get(lookupURI);
                if (mappedURI == null)
                    continue;

                // We found it - get the username and password in the
                // Keystore associated with this service URI
                String alias = null;
                alias = "password#" + mappedURI.toASCIIString();
                passwordKey = (((SecretKeySpec) keystore.getKey(alias, masterPassword.toCharArray())));
                if (passwordKey == null) {
                    // Unexpected, it was just there in the map!
                    logger.warn("Could not find alias " + alias + " for known uri " + lookupURI
                            + ", just deleted?");
                    // Remember we went outside synchronized(keystore) while
                    // looping
                    continue;
                }
                String unpasspair = new String(passwordKey.getEncoded(), UTF_8);
                /*
                 * decoded key contains string
                 * <USERNAME><SEPARATOR_CHARACTER><PASSWORD>
                 */

                int separatorAt = unpasspair.indexOf(USERNAME_AND_PASSWORD_SEPARATOR_CHARACTER);
                if (separatorAt < 0)
                    throw new CMException("Invalid credentials stored for " + lookupURI);

                String username = unpasspair.substring(0, separatorAt);
                String password = unpasspair.substring(separatorAt + 1);

                UsernamePassword usernamePassword = new UsernamePassword();
                usernamePassword.setUsername(username);
                usernamePassword.setPassword(password.toCharArray());
                return usernamePassword;
            }

            // Nothing found in the Keystore, let's lookup using the service
            // username and password providers
            for (ServiceUsernameAndPasswordProvider provider : serviceUsernameAndPasswordProviders) {
                UsernamePassword usernamePassword = provider.getServiceUsernameAndPassword(serviceURI,
                        requestingMessage);
                if (usernamePassword == null)
                    continue;
                if (usernamePassword.isShouldSave()) {
                    URI uri = serviceURI;
                    if (usePathRecursion)
                        uri = normalizeServiceURI(serviceURI);
                    addUsernameAndPasswordForService(usernamePassword, uri);
                }
                return usernamePassword;
            }
            // Giving up
            return null;
        } catch (Exception ex) {
            String exMessage = "Failed to get the username and password pair for service " + serviceURI
                    + " from the Keystore";
            logger.error(exMessage, ex);
            throw new CMException(exMessage, ex);
        }
    }
}

From source file:ddf.catalog.CatalogFrameworkImpl.java

/**
 * Retrieves a resource using the specified URI assuming this catalog framework has a
 * {@link ResourceReader} with a scheme that matches the scheme in the specified URI.
 * // w ww. j  a v a2  s.  co  m
 * @param resourceUri
 * @param properties
 * @return the {@link ResourceResponse}
 * @throws ResourceNotFoundException
 *             if a {@link ResourceReader} with the input URI's scheme is not found
 */
protected ResourceResponse getResourceUsingResourceReader(URI resourceUri, Map<String, Serializable> properties)
        throws ResourceNotFoundException {
    final String methodName = "getResourceUsingResourceReader";
    logger.entry(methodName);
    ResourceResponse resource = null;

    if (resourceUri == null) {
        throw new ResourceNotFoundException("Unable to find resource due to null URI");
    }

    Iterator<ResourceReader> iterator = resourceReaders.iterator();
    while (iterator.hasNext() && resource == null) {
        ResourceReader reader = iterator.next();

        String scheme = resourceUri.getScheme();
        if (reader.getSupportedSchemes().contains(scheme)) {
            try {
                logger.debug("Found an acceptable resource reader (" + reader.getId() + ") for URI "
                        + resourceUri.toASCIIString());
                resource = reader.retrieveResource(resourceUri, properties);
                if (resource == null) {
                    logger.info("Resource returned from ResourceReader " + reader.getId()
                            + " was null.  Checking other readers for URI: " + resourceUri);
                }
            } catch (ResourceNotFoundException e) {
                logger.debug("Enterprise Search: Product not found using resource reader with name "
                        + reader.getId());
            } catch (ResourceNotSupportedException e) {
                logger.debug("Enterprise Search: Product not found using resource reader with name "
                        + reader.getId());
            } catch (IOException ioe) {
                logger.debug("Enterprise Search: Product not found using resource reader with name "
                        + reader.getId());
            }
        }
    }
    if (resource == null) {
        throw new ResourceNotFoundException(
                "Resource Readers could not find resource (or returned null resource) for URI: "
                        + resourceUri.toASCIIString() + ". Scheme: " + resourceUri.getScheme());
    }
    logger.debug("Received resource, sending back: " + resource.getResource().getName());
    logger.exit(methodName);
    return resource;
}

From source file:eu.abc4trust.smartcard.HardwareSmartcard.java

private PseudonymWithMetadata getPseudonym(int pin, URI pseudonymUID, int nextPseuBlobUriId,
        ByteArrayOutputStream accumulatedPseuBytes, PseudonymSerializer serializer) {
    System.out.println("Accumulated this many bytes: " + accumulatedPseuBytes.size());
    URI nextPseuBlobUri = URI.create(pseudonymUID.toASCIIString() + "_" + nextPseuBlobUriId);
    System.out.println("getting this uri: " + nextPseuBlobUri.toASCIIString());
    SmartcardBlob scBlob = this.getBlob(pin, nextPseuBlobUri);
    if (scBlob == null) {
        return serializer.unserializePseudonym(accumulatedPseuBytes.toByteArray(), pseudonymUID);
    }/* www  .  j a  va 2 s  .  c  om*/
    byte[] blob = scBlob.blob;
    accumulatedPseuBytes.write(blob, 0, blob.length);
    if (blob.length < MAX_BLOB_BYTES) {
        return serializer.unserializePseudonym(accumulatedPseuBytes.toByteArray(), pseudonymUID);
    } else {
        //next round
        return getPseudonym(pin, pseudonymUID, nextPseuBlobUriId + 1, accumulatedPseuBytes, serializer);
    }
}

From source file:eu.abc4trust.smartcard.HardwareSmartcard.java

private Credential getCredential(int pin, URI credentialId, int nextCredBlobUriId,
        ByteArrayOutputStream accumulatedCredBytes, CredentialSerializer serializer) {
    System.out.println("Accumulated this many bytes: " + accumulatedCredBytes.size());
    URI nextCredBlobUri = URI.create(credentialId.toASCIIString() + "_" + nextCredBlobUriId);
    System.out.println("getting this uri: " + nextCredBlobUri.toASCIIString());
    SmartcardBlob scBlob = this.getBlob(pin, nextCredBlobUri);
    if (scBlob == null) {
        return serializer.unserializeCredential(accumulatedCredBytes.toByteArray(), credentialId,
                this.getDeviceURI(pin));
    }//w  w w  .  j a v a 2 s  . c om
    byte[] blob = scBlob.blob;
    accumulatedCredBytes.write(blob, 0, blob.length);
    if (blob.length < MAX_BLOB_BYTES) {
        //return new CredentialSerializerGzipXml().unserializeCredential(accumulatedCredBytes.toByteArray());
        return serializer.unserializeCredential(accumulatedCredBytes.toByteArray(), credentialId,
                this.getDeviceURI(pin));
    } else {
        //next round
        return getCredential(pin, credentialId, nextCredBlobUriId + 1, accumulatedCredBytes, serializer);
    }
}

From source file:net.sf.taverna.t2.security.credentialmanager.impl.CredentialManagerImpl.java

/**
 * Get a username and password pair for the given service's URI, or null if
 * it does not exit.//  w ww.j av a  2 s  . co m
 * <p>
 * If the username and password are not available in the Keystore, it will
 * invoke implementations of the {@link ServiceUsernameAndPasswordProvider}
 * interface asking the user (typically through the UI) or resolving
 * hard-coded credentials.
 * <p>
 * If the parameter <code>useURIPathRecursion</code> is true, then the
 * Credential Manager will also attempt to look for stored credentials for
 * each of the parent fragments of the URI.
 * 
 * @param serviceURI
 *            The URI of the service for which we are providing the username
 *            and password
 * @param useURIPathRecursion
 *            Whether to look for any username and passwords stored in the
 *            Keystore for the parent fragments of the service URI (for
 *            example, we are looking for the credentials for service
 *            http://somehost/some-fragment but we already have credentials
 *            stored for http://somehost which can be reused)
 * @param requestingMessage
 *            The message to be presented to the user when asking for the
 *            username and password, normally useful for UI providers that
 *            pop up dialogs, can be ignored otherwise
 * @return username and password pair for the given service
 * @throws CMException
 *             if anything goes wrong during Keystore lookup, etc.
 */
@Override
public UsernamePassword getUsernameAndPasswordForService(URI serviceURI, boolean usePathRecursion,
        String requestingMessage) throws CMException {
    /*
     * Need to make sure we are initialized before we do anything else, as
     * the Credential Manager can be created but not initialized.
     */
    initialize();

    synchronized (keystore) {
        SecretKeySpec passwordKey = null;
        LinkedHashSet<URI> possibleServiceURIsToLookup = getPossibleServiceURIsToLookup(serviceURI,
                usePathRecursion);
        Map<URI, URI> allServiceURIs = getFragmentMappedURIsForAllUsernameAndPasswordPairs();

        try {
            for (URI lookupURI : possibleServiceURIsToLookup) {
                URI mappedURI = allServiceURIs.get(lookupURI);
                if (mappedURI == null)
                    continue;

                /*
                 * We found it - get the username and password in the
                 * Keystore associated with this service URI
                 */
                String alias = "password#" + mappedURI.toASCIIString();
                passwordKey = (SecretKeySpec) keystore.getKey(alias, masterPassword.toCharArray());
                if (passwordKey == null) {
                    // Unexpected, it was just there in the map!
                    logger.warn("Could not find alias " + alias + " for known uri " + lookupURI
                            + ", just deleted?");
                    /*
                     * Remember we went outside synchronized(keystore) while
                     * looping
                     */
                    continue;
                }
                String unpasspair = new String(passwordKey.getEncoded(), UTF_8);
                /*
                 * decoded key contains string
                 * <USERNAME><SEPARATOR_CHARACTER><PASSWORD>
                 */

                int separatorAt = unpasspair.indexOf(USERNAME_AND_PASSWORD_SEPARATOR_CHARACTER);
                if (separatorAt < 0)
                    throw new CMException("Invalid credentials stored for " + lookupURI);

                String username = unpasspair.substring(0, separatorAt);
                String password = unpasspair.substring(separatorAt + 1);

                UsernamePassword usernamePassword = new UsernamePassword();
                usernamePassword.setUsername(username);
                usernamePassword.setPassword(password.toCharArray());
                return usernamePassword;
            }

            // Nothing found in the Keystore, let's lookup using the service
            // username and password providers
            for (ServiceUsernameAndPasswordProvider provider : serviceUsernameAndPasswordProviders) {
                UsernamePassword usernamePassword = provider.getServiceUsernameAndPassword(serviceURI,
                        requestingMessage);
                if (usernamePassword == null)
                    continue;
                if (usernamePassword.isShouldSave()) {
                    URI uri = serviceURI;
                    if (usePathRecursion)
                        uri = normalizeServiceURI(serviceURI);
                    addUsernameAndPasswordForService(usernamePassword, uri);
                }
                return usernamePassword;
            }
            // Giving up
            return null;
        } catch (Exception ex) {
            String exMessage = "Failed to get the username and password pair for service " + serviceURI
                    + " from the Keystore";
            logger.error(exMessage, ex);
            throw new CMException(exMessage, ex);
        }
    }
}

From source file:org.panbox.desktop.common.gui.PanboxClientGUI.java

/**
 * helper method for handling CSP-side access control configuration, after
 * having invited or removed single users from or to a share.
 * /*from w w w  .  jav  a  2 s. c  o m*/
 * @param share
 *            share for whichparticipant list has changed
 * @param shareHasParticipants
 *            <code>true</code> if folder has just been shared initially and
 *            participants have only been added
 */
private void handleCSPShareParticipantConfiguration(PanboxShare share, boolean shareHasParticipants,
        List<PanboxGUIContact> selectedcontacts) {
    if (share instanceof DropboxPanboxShare) {
        DropboxAdapterFactory dbxFac = (DropboxAdapterFactory) CSPAdapterFactory
                .getInstance(StorageBackendType.DROPBOX);
        DropboxAPIIntegration dbIntegration = (DropboxAPIIntegration) dbxFac.getAPIAdapter();

        // before we continue, first check if directory has already been
        // synced to csp
        String shareid = FilenameUtils.getName(share.getPath());
        boolean shareIsOnline, shareConfigured = false;
        try {
            shareIsOnline = ((shareid != null) && (shareid.length() > 0)
                    && dbIntegration.exists("/" + shareid));
        } catch (CSPApiException e) {
            logger.error("Could not determine if share with path " + share.getPath() + " and shareid: "
                    + shareid + " has already been uploaded!");
            shareIsOnline = false;
        }

        if (shareIsOnline) {
            String message = bundle.getString("PanboxClientGUI.openDropboxShareConfig");
            JCheckBox copyToClipboard = new JCheckBox(bundle.getString("PanboxClientGUI.copyEmailToClipboard"));
            Object[] params = new Object[] { message, copyToClipboard };

            int res = JOptionPane.showConfirmDialog(this, params,
                    bundle.getString("PanboxClientGUI.openShareConfig"), JOptionPane.YES_NO_OPTION);

            if (res == JOptionPane.YES_OPTION) {
                if (copyToClipboard.isSelected()) {
                    String emails = PanboxGUIContact.getMailAsSepteratedValues(selectedcontacts, ";",
                            StorageBackendType.DROPBOX);
                    // copy the email of the selected contact into the
                    // clipboard
                    DesktopApi.copyToClipboard(emails.toString(), false);
                }

                try {
                    if (shareHasParticipants) {
                        // shows configuration page for shares with existing
                        // users in case of dropbox
                        dbIntegration.removeUser(shareid);
                    } else {
                        // shows initial setup page for new shares
                        dbIntegration.inviteUser(shareid);
                    }
                    shareConfigured = true;
                } catch (Exception e) {
                    logger.error("handleCSPShareParticipantConfiguration: Error opening share configuration",
                            e);
                    JOptionPane.showMessageDialog(this,
                            bundle.getString("PanboxClientGUI.errorOpeningShareConfig"),
                            bundle.getString("error"), JOptionPane.ERROR_MESSAGE);
                }
            }
        } else {
            // JOptionPane
            // .showMessageDialog(
            // this,
            // bundle.getString("PublishIdentitiesDialog.fileNotFoundInCloudStorage"),
            // bundle.getString("PublishIdentitiesDialog.fileNotFound"),
            // JOptionPane.WARNING_MESSAGE);
        }

        if (Settings.getInstance().isMailtoSchemeSupported()) {
            // now, offer to send panbox share invitation link
            String message;
            if (shareConfigured) {
                message = bundle.getString("PanboxClientGUI.sendInvitationLink.message");
            } else {
                if (shareIsOnline) {
                    message = bundle.getString("PanboxClientGUI.sendInvitationLinkNotConfigured.message");
                } else {
                    message = bundle.getString("PanboxClientGUI.sendInvitationLinkNoSync.message");
                }
            }

            int ret = JOptionPane.showConfirmDialog(this, message,
                    bundle.getString("PanboxClientGUI.InvitationLink.title"), JOptionPane.YES_NO_OPTION);
            if (ret == JOptionPane.YES_OPTION) {
                String emails = PanboxGUIContact.getMailAsSepteratedValues(selectedcontacts, ",",
                        StorageBackendType.DROPBOX);

                String mailto = "mailto:" + emails + "?subject="
                        + bundle.getString("client.mailTo.shareInvitationSubject") + "&body="
                        + PanboxURICmdShareInvitation.getPanboxLink(share.getUuid().toString(),
                                share.getType().name());

                DesktopApi.browse(URI.create(mailto));
            }
        } else {
            // offer to copy panbox share invitation link to
            // clipboard
            String message;
            if (shareConfigured) {
                message = bundle.getString("PanboxClientGUI.copyInvitationLink.message");
            } else {
                if (shareIsOnline) {
                    message = bundle.getString("PanboxClientGUI.copyInvitationLinkNotConfigured.message");
                } else {
                    message = bundle.getString("PanboxClientGUI.copyInvitationLinkNoSync.message");
                }
            }

            int ret = JOptionPane.showConfirmDialog(this, message,
                    bundle.getString("PanboxClientGUI.InvitationLink.title"), JOptionPane.YES_NO_OPTION);
            if (ret == JOptionPane.YES_OPTION) {
                URI uri = PanboxURICmdShareInvitation.getPanboxLink(share.getUuid().toString(),
                        share.getType().name());

                DesktopApi.copyToClipboard(uri.toASCIIString(), true);

                JOptionPane.showMessageDialog(this,
                        bundle.getString("PanboxClientGUI.copyInvitationLink.info") + "\n"
                                + uri.toASCIIString(),
                        bundle.getString("PanboxClientGUI.InvitationLink.title"),
                        JOptionPane.INFORMATION_MESSAGE);
            }

        }

    } else {
        logger.warn("handleCSPShareParticipantConfiguration: Unknown share type!");
    }
}

From source file:org.exoplatform.outlook.OutlookServiceImpl.java

/**
 * Inits the document link./*from  www  .  j  a v a 2  s  .c o  m*/
 *
 * @param siteType the site type
 * @param driveName the drive name
 * @param portalName the portal name
 * @param nodeURI the node URI
 * @param node the node
 * @throws OutlookException the outlook exception
 */
protected void initDocumentLink(SiteType siteType, String driveName, String portalName, String nodeURI,
        HierarchyNode node) throws OutlookException {
    // WebDAV URL
    initWebDAVLink(node);

    // Portal URL
    // Code adapted from ECMS's PermlinkActionComponent.getPermlink()

    String npath = node.getPath().replaceAll("/+", "/");

    String path = new StringBuilder().append(driveName).append(npath).toString();
    PortalRequestContext portalRequest = Util.getPortalRequestContext();
    if (portalRequest != null) {
        NodeURL nodeURL = portalRequest.createURL(NodeURL.TYPE);
        NavigationResource resource = new NavigationResource(siteType, portalName, nodeURI);
        nodeURL.setResource(resource);
        nodeURL.setQueryParameterValue("path", path);

        HttpServletRequest request = portalRequest.getRequest();
        try {
            URI requestUri = new URI(request.getScheme(), null, request.getServerName(),
                    request.getServerPort(), null, null, null);

            StringBuilder url = new StringBuilder();
            url.append(requestUri.toASCIIString());
            url.append(nodeURL.toString());
            node.setUrl(url.toString());
        } catch (URISyntaxException e) {
            throw new OutlookException("Error creating server URL " + request.getRequestURI().toString(), e);
        }
    } else {
        LOG.warn("Portal request not found. Node URL will be its WebDAV link. Node: " + node.getPath());
        node.setUrl(node.getWebdavUrl());
    }
}