Example usage for java.net URISyntaxException URISyntaxException

List of usage examples for java.net URISyntaxException URISyntaxException

Introduction

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

Prototype

public URISyntaxException(String input, String reason) 

Source Link

Document

Constructs an instance from the given input string and reason.

Usage

From source file:org.openmidaas.library.MIDaaS.java

/**
 * This methods initializes the library. It first checks to see if the 
 * device is already registered. If it is, it calls the onSuccess()
 * method. Otherwise, it tries to register the device with the server and calls
 * onSuccess() or onError() accordingly. 
 * @param context - the Android context. 
 * @param attributeServerUrl - the attribute server that verifies and releases attributes. If null, the 
 * default server is used. This is defined in the Constants.java file. 
 * @param initCallback - the Initialization callback. 
 * @throws URISyntaxException /*from  w  w w  . jav a  2 s  . c om*/
 */
public static void initialize(final Context context, final String attributeServerUrl,
        final InitializationCallback initCallback) throws URISyntaxException {
    if (context == null) {
        MIDaaS.logError(TAG, "context is null");
        throw new IllegalArgumentException("Context cannot be null");
    }
    if (initCallback == null) {
        MIDaaS.logError(TAG, "initialization callback is null");
        throw new IllegalArgumentException("InitializationCallback cannot be null");
    }
    mContext = context.getApplicationContext();
    /* *** initialization routines *** */
    logDebug(TAG, "Initializing library");
    if (attributeServerUrl == null || attributeServerUrl.isEmpty()) {
        ConnectionManager.setNetworkFactory(new AndroidNetworkFactory(Constants.AVP_SB_BASE_URL));
    } else {
        URI uri = new URI(attributeServerUrl);
        // check to see if we have a complete URL
        if (uri.isAbsolute()) {
            // since we're using the URI class, check that the scheme is http or https. 
            if (uri.getScheme().equals("http") || uri.getScheme().equals("https")) {
                ConnectionManager.setNetworkFactory(new AndroidNetworkFactory(attributeServerUrl));
            } else {
                MIDaaS.logError(TAG, "Unknown URI scheme: " + uri.getScheme());
                throw new URISyntaxException(attributeServerUrl, "Unknown URI scheme: " + uri.getScheme());
            }
        } else {
            MIDaaS.logError(TAG, "URI appears to be incomplete: " + attributeServerUrl);
            throw new URISyntaxException(attributeServerUrl,
                    "URI appears to be incomplete: " + attributeServerUrl);
        }
    }
    // we will use a SQLITE database to persist attributes. 
    AttributePersistenceCoordinator.setPersistenceDelegate(new AttributeDBPersistence());
    // set the authentication strategy to level0 device authentication 
    AuthenticationManager.getInstance().setDeviceAuthenticationStrategy(new SKDeviceAuthentication());
    // we will use our access token strategy that depends on level 0 device authentication
    AuthenticationManager.getInstance().setAccessTokenStrategy(new AVSAccessTokenStrategy());
    logDebug(TAG, "Checking to see if device is registered.");
    WorkQueueManager.getInstance().addWorkerToQueue(new WorkQueueManager.Worker() {
        @Override
        public void execute() {
            DeviceRegistrar.setDeviceRegistrationDelegate(new AVSDeviceRegistration());
            DeviceRegistrar.registerDevice(initCallback);
        }
    });
}

From source file:URISupport.java

/**
 * @param uri/*from w ww. java2s.  co m*/
 * @param rc
 * @param ssp
 * @param p
 * @throws URISyntaxException
 */
private static void parseComposite(URI uri, CompositeData rc, String ssp) throws URISyntaxException {
    String componentString;
    String params;

    if (!checkParenthesis(ssp)) {
        throw new URISyntaxException(uri.toString(), "Not a matching number of '(' and ')' parenthesis");
    }

    int p;
    int intialParen = ssp.indexOf("(");
    if (intialParen == 0) {
        rc.host = ssp.substring(0, intialParen);
        p = rc.host.indexOf("/");
        if (p >= 0) {
            rc.path = rc.host.substring(p);
            rc.host = rc.host.substring(0, p);
        }
        p = ssp.lastIndexOf(")");
        componentString = ssp.substring(intialParen + 1, p);
        params = ssp.substring(p + 1).trim();

    } else {
        componentString = ssp;
        params = "";
    }

    String components[] = splitComponents(componentString);
    rc.components = new URI[components.length];
    for (int i = 0; i < components.length; i++) {
        rc.components[i] = new URI(components[i].trim());
    }

    p = params.indexOf("?");
    if (p >= 0) {
        if (p > 0) {
            rc.path = stripPrefix(params.substring(0, p), "/");
        }
        rc.parameters = parseQuery(params.substring(p + 1));
    } else {
        if (params.length() > 0) {
            rc.path = stripPrefix(params, "/");
        }
        rc.parameters = emptyMap();
    }
}

From source file:org.eclipse.aether.transport.http.HttpTransporter.java

HttpTransporter(RemoteRepository repository, RepositorySystemSession session) throws NoTransporterException {
    if (!"http".equalsIgnoreCase(repository.getProtocol())
            && !"https".equalsIgnoreCase(repository.getProtocol())) {
        throw new NoTransporterException(repository);
    }/*from   w w w .  j av a 2  s . c  om*/
    try {
        baseUri = new URI(repository.getUrl()).parseServerAuthority();
        if (baseUri.isOpaque()) {
            throw new URISyntaxException(repository.getUrl(), "URL must not be opaque");
        }
        server = URIUtils.extractHost(baseUri);
        if (server == null) {
            throw new URISyntaxException(repository.getUrl(), "URL lacks host name");
        }
    } catch (URISyntaxException e) {
        throw new NoTransporterException(repository, e.getMessage(), e);
    }
    proxy = toHost(repository.getProxy());

    repoAuthContext = AuthenticationContext.forRepository(session, repository);
    proxyAuthContext = AuthenticationContext.forProxy(session, repository);

    state = new LocalState(session, repository, new SslConfig(session, repoAuthContext));

    headers = ConfigUtils.getMap(session, Collections.emptyMap(),
            ConfigurationProperties.HTTP_HEADERS + "." + repository.getId(),
            ConfigurationProperties.HTTP_HEADERS);

    DefaultHttpClient client = new DefaultHttpClient(state.getConnectionManager());

    configureClient(client.getParams(), session, repository, proxy);

    client.setCredentialsProvider(toCredentialsProvider(server, repoAuthContext, proxy, proxyAuthContext));

    this.client = new DecompressingHttpClient(client);
}

From source file:org.apache.marmotta.platform.core.services.prefix.PrefixServiceImpl.java

@Override
public synchronized void add(String prefix, String namespace)
        throws IllegalArgumentException, URISyntaxException {
    if (cache.containsKey(prefix)) {
        log.error("prefix " + prefix + " already managed");
        throw new IllegalArgumentException(
                "prefix " + prefix + " already managed, use forceAdd() if you'd like to force its rewrite");
    } else {/*from   ww w.  java  2s .  c  o m*/
        String validatedNamespace = validateNamespace(namespace);
        if (validatedNamespace != null) {
            try {
                cache.put(prefix, validatedNamespace);
                configurationService.setConfiguration(CONFIGURATION_PREFIX + "." + prefix, validatedNamespace);
            } catch (IllegalArgumentException e) {
                log.error("namespace " + validatedNamespace + " is already bound to '"
                        + getPrefix(validatedNamespace)
                        + "' prefix, use forceAdd() if you'd like to force its rewrite");
                throw new IllegalArgumentException("namespace " + validatedNamespace + " is already bound to '"
                        + getPrefix(validatedNamespace) + "' prefix");
            }
        } else {
            log.error("Namespace <" + namespace + "> is not valid");
            throw new URISyntaxException(namespace, "Namespace <" + namespace + "> is not valid");
        }
    }
}

From source file:org.openhab.habdroid.ui.OpenHABWriteTagActivity.java

@Override
public void onNewIntent(Intent intent) {
    if (mSitemapPage == null) {
        return;/*  w ww  .jav a2 s  .  co  m*/
    }

    Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
    //do something with tagFromIntent
    Log.d(TAG, "NFC TAG = " + tagFromIntent.toString());
    Log.d(TAG, "Writing page " + mSitemapPage + " to tag");

    TextView writeTagMessage = findViewById(R.id.write_tag_message);

    try {
        URI sitemapURI = new URI(mSitemapPage);
        if (!sitemapURI.getPath().startsWith("/rest/sitemaps")) {
            throw new URISyntaxException(mSitemapPage, "Expected a sitemap URL");
        }
        StringBuilder uriToWrite = new StringBuilder("openhab://sitemaps");
        uriToWrite.append(sitemapURI.getPath().substring(14));
        if (!TextUtils.isEmpty(mItem) && !TextUtils.isEmpty(mCommand)) {
            uriToWrite.append("?item=").append(mItem).append("&command=").append(mCommand);
        }
        writeTagMessage.setText(R.string.info_write_tag_progress);
        writeTag(tagFromIntent, uriToWrite.toString());
    } catch (URISyntaxException e) {
        Log.e(TAG, e.getMessage());
        writeTagMessage.setText(R.string.info_write_failed);
    }
}

From source file:eu.trentorise.smartcampus.protocolcarrier.Communicator.java

private static HttpRequestBase buildRequest(MessageRequest msgRequest, String appToken, String authToken)
        throws URISyntaxException, UnsupportedEncodingException {
    String host = msgRequest.getTargetHost();
    if (host == null)
        throw new URISyntaxException(host, "null URI");
    if (!host.endsWith("/"))
        host += '/';
    String address = msgRequest.getTargetAddress();
    if (address == null)
        address = "";
    if (address.startsWith("/"))
        address = address.substring(1);/* ww w.j  a va 2  s . c  o m*/
    String uriString = host + address;
    try {
        URL url = new URL(uriString);
        URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(),
                url.getQuery(), url.getRef());
        uriString = uri.toURL().toString();
    } catch (MalformedURLException e) {
        throw new URISyntaxException(uriString, e.getMessage());
    }
    if (msgRequest.getQuery() != null)
        uriString += "?" + msgRequest.getQuery();

    //      new URI(uriString);

    HttpRequestBase request = null;
    if (msgRequest.getMethod().equals(Method.POST)) {
        HttpPost post = new HttpPost(uriString);
        HttpEntity httpEntity = null;
        if (msgRequest.getRequestParams() != null) {
            // if body and requestparams are either not null there is an
            // exception
            if (msgRequest.getBody() != null && msgRequest != null) {
                throw new IllegalArgumentException("body and requestParams cannot be either populated");
            }
            httpEntity = new MultipartEntity();

            for (RequestParam param : msgRequest.getRequestParams()) {
                if (param.getParamName() == null || param.getParamName().trim().length() == 0) {
                    throw new IllegalArgumentException("paramName cannot be null or empty");
                }
                if (param instanceof FileRequestParam) {
                    FileRequestParam fileparam = (FileRequestParam) param;
                    ((MultipartEntity) httpEntity).addPart(param.getParamName(), new ByteArrayBody(
                            fileparam.getContent(), fileparam.getContentType(), fileparam.getFilename()));
                }
                if (param instanceof ObjectRequestParam) {
                    ObjectRequestParam objectparam = (ObjectRequestParam) param;
                    ((MultipartEntity) httpEntity).addPart(param.getParamName(),
                            new StringBody(convertObject(objectparam.getVars())));
                }
            }
            // mpe.addPart("file",
            // new ByteArrayBody(msgRequest.getFileContent(), ""));
            // post.setEntity(mpe);
        }
        if (msgRequest.getBody() != null) {
            httpEntity = new StringEntity(msgRequest.getBody(), Constants.CHARSET);
            ((StringEntity) httpEntity).setContentType(msgRequest.getContentType());
        }
        post.setEntity(httpEntity);
        request = post;
    } else if (msgRequest.getMethod().equals(Method.PUT)) {
        HttpPut put = new HttpPut(uriString);
        if (msgRequest.getBody() != null) {
            StringEntity se = new StringEntity(msgRequest.getBody(), Constants.CHARSET);
            se.setContentType(msgRequest.getContentType());
            put.setEntity(se);
        }
        request = put;
    } else if (msgRequest.getMethod().equals(Method.DELETE)) {
        request = new HttpDelete(uriString);
    } else {
        // default: GET
        request = new HttpGet(uriString);
    }

    Map<String, String> headers = new HashMap<String, String>();

    // default headers
    if (appToken != null) {
        headers.put(RequestHeader.APP_TOKEN.toString(), appToken);
    }
    if (authToken != null) {
        // is here for compatibility
        headers.put(RequestHeader.AUTH_TOKEN.toString(), authToken);
        headers.put(RequestHeader.AUTHORIZATION.toString(), "Bearer " + authToken);
    }
    headers.put(RequestHeader.ACCEPT.toString(), msgRequest.getContentType());

    if (msgRequest.getCustomHeaders() != null) {
        headers.putAll(msgRequest.getCustomHeaders());
    }

    for (String key : headers.keySet()) {
        request.addHeader(key, headers.get(key));
    }

    return request;
}

From source file:com.altiscale.TcpProxy.HostPort.java

public HostPort parseServerString(String server) throws URISyntaxException {
    URI uri = new URI("my://" + server);
    String host = uri.getHost();/*from  ww w .  jav  a 2s.  c  om*/
    int port = uri.getPort();
    if (uri.getHost() == null) {
        throw new URISyntaxException(uri.toString(), "URI must have at least a hostname.");
    }
    // Library sets port to -1 if it was missing in String server.
    return new HostPort(host, port);
}

From source file:com.microsoftopentechnologies.windowsazurestorage.WAStorageClient.java

/**
 * Returns reference of Windows Azure cloud blob container.
 *
 * @param accName storage account name/*from  w  ww . j  ava2 s.  c  om*/
 * @param key storage account primary access key
 * @param blobURL blob service endpoint url
 * @param containerName name of the container
 * @param createCnt Indicates if container needs to be created
 * @param allowRetry sets retry policy
 * @param cntPubAccess Permissions for container
 * @return reference of CloudBlobContainer
 * @throws URISyntaxException
 * @throws StorageException
 */
private static CloudBlobContainer getBlobContainerReference(StorageAccountInfo storageAccount,
        String containerName, boolean createCnt, boolean allowRetry, Boolean cntPubAccess)
        throws URISyntaxException, StorageException, MalformedURLException, IOException {

    CloudStorageAccount cloudStorageAccount;
    CloudBlobClient serviceClient;
    CloudBlobContainer container;
    StorageCredentialsAccountAndKey credentials;
    String accName = storageAccount.getStorageAccName();
    String blobURL = storageAccount.getBlobEndPointURL();

    credentials = new StorageCredentialsAccountAndKey(accName, storageAccount.getStorageAccountKey());

    if (Utils.isNullOrEmpty(blobURL) || blobURL.equals(Constants.DEF_BLOB_URL)) {
        cloudStorageAccount = new CloudStorageAccount(credentials);
    } else {
        String endpointSuffix = getEndpointSuffix(blobURL);
        if (Utils.isNullOrEmpty(endpointSuffix))
            throw new URISyntaxException(blobURL, "The blob endpoint is not correct!");
        cloudStorageAccount = new CloudStorageAccount(credentials, false, endpointSuffix);
    }

    serviceClient = cloudStorageAccount.createCloudBlobClient();
    if (!allowRetry) {
        // Setting no retry policy
        RetryNoRetry rnr = new RetryNoRetry();
        // serviceClient.setRetryPolicyFactory(rnr);
        serviceClient.getDefaultRequestOptions().setRetryPolicyFactory(rnr);
    }

    container = serviceClient.getContainerReference(containerName);

    boolean cntExists = container.exists();

    if (createCnt && !cntExists) {
        container.createIfNotExists(null, Utils.updateUserAgent());
    }

    // Apply permissions only if container is created newly
    if (!cntExists && cntPubAccess != null) {
        // Set access permissions on container.
        BlobContainerPermissions cntPerm;
        cntPerm = new BlobContainerPermissions();
        if (cntPubAccess) {
            cntPerm.setPublicAccess(BlobContainerPublicAccessType.CONTAINER);
        } else {
            cntPerm.setPublicAccess(BlobContainerPublicAccessType.OFF);
        }
        container.uploadPermissions(cntPerm);
    }

    return container;
}

From source file:org.objectweb.proactive.extensions.vfsprovider.client.ProActiveFileName.java

private static String getServerVFSRootURL(String serverURL)
        throws URISyntaxException, UnknownProtocolException {
    final int dotIndex = serverURL.indexOf(':');
    if (dotIndex == -1) {
        throw new URISyntaxException(serverURL, "Could not find URL scheme");
    }//from  w  w w  .jav  a2  s .  c  o  m
    final String schemeString = serverURL.substring(0, dotIndex);
    final String remainingPart = serverURL.substring(dotIndex);
    checkServerScheme(schemeString);
    return URIHelper.convertToEncodedURIString(getVFSSchemeForServerScheme(schemeString) + remainingPart
            + SERVICE_AND_FILE_PATH_SEPARATOR + SEPARATOR_CHAR);
}

From source file:com.altiscale.TcpProxy.HostPort.java

public void parseServerStringAndAdd(String server) throws URISyntaxException {
    HostPort hostPort = parseServerString(server);
    if (hostPort.port == -1) {
        throw new URISyntaxException(server, "No port specified for server in server list.");
    }/* w  w  w.j a v  a2 s .c o  m*/
    serverHostPortList.add(hostPort);
}