Search in sources :

Example 26 with URISyntaxException

use of java.net.URISyntaxException in project hibernate-orm by hibernate.

the class JpaDescriptorParser method mappingFilesUnchanged.

private boolean mappingFilesUnchanged(Collection<String> mappingFileNames) {
    boolean mappingFilesUnchanged = false;
    FileTimeStampChecker fileStampCheck = new FileTimeStampChecker();
    for (String mappingFile : mappingFileNames) {
        try {
            URL url = this.getClass().getResource(mappingFile);
            if (url == null) {
                continue;
            }
            File file = new File(url.toURI());
            context.logMessage(Diagnostic.Kind.OTHER, "Check file  " + mappingFile);
            if (file.exists()) {
                fileStampCheck.add(mappingFile, file.lastModified());
            }
        } catch (URISyntaxException e) {
            // in doubt return false
            return false;
        }
    }
    FileTimeStampChecker serializedTimeStampCheck = loadTimeStampCache();
    if (serializedTimeStampCheck.equals(fileStampCheck)) {
        context.logMessage(Diagnostic.Kind.OTHER, "XML parsing will be skipped due to unchanged xml files");
        mappingFilesUnchanged = true;
    } else {
        saveTimeStampCache(fileStampCheck);
    }
    return mappingFilesUnchanged;
}
Also used : FileTimeStampChecker(org.hibernate.jpamodelgen.util.FileTimeStampChecker) URISyntaxException(java.net.URISyntaxException) File(java.io.File) URL(java.net.URL)

Example 27 with URISyntaxException

use of java.net.URISyntaxException in project Signal-Android by WhisperSystems.

the class QuickResponseService method onHandleIntent.

@Override
protected void onHandleIntent(Intent intent, @Nullable MasterSecret masterSecret) {
    if (!TelephonyManager.ACTION_RESPOND_VIA_MESSAGE.equals(intent.getAction())) {
        Log.w(TAG, "Received unknown intent: " + intent.getAction());
        return;
    }
    if (masterSecret == null) {
        Log.w(TAG, "Got quick response request when locked...");
        Toast.makeText(this, R.string.QuickResponseService_quick_response_unavailable_when_Signal_is_locked, Toast.LENGTH_LONG).show();
        return;
    }
    try {
        Rfc5724Uri uri = new Rfc5724Uri(intent.getDataString());
        String content = intent.getStringExtra(Intent.EXTRA_TEXT);
        String numbers = uri.getPath();
        if (numbers.contains("%")) {
            numbers = URLDecoder.decode(numbers);
        }
        Recipients recipients = RecipientFactory.getRecipientsFromString(this, numbers, false);
        Optional<RecipientsPreferences> preferences = DatabaseFactory.getRecipientPreferenceDatabase(this).getRecipientsPreferences(recipients.getIds());
        int subscriptionId = preferences.isPresent() ? preferences.get().getDefaultSubscriptionId().or(-1) : -1;
        long expiresIn = preferences.isPresent() ? preferences.get().getExpireMessages() * 1000 : 0;
        if (!TextUtils.isEmpty(content)) {
            if (recipients.isSingleRecipient()) {
                MessageSender.send(this, masterSecret, new OutgoingTextMessage(recipients, content, expiresIn, subscriptionId), -1, false);
            } else {
                MessageSender.send(this, masterSecret, new OutgoingMediaMessage(recipients, new SlideDeck(), content, System.currentTimeMillis(), subscriptionId, expiresIn, ThreadDatabase.DistributionTypes.DEFAULT), -1, false);
            }
        }
    } catch (URISyntaxException e) {
        Toast.makeText(this, R.string.QuickResponseService_problem_sending_message, Toast.LENGTH_LONG).show();
        Log.w(TAG, e);
    }
}
Also used : OutgoingTextMessage(org.thoughtcrime.securesms.sms.OutgoingTextMessage) Rfc5724Uri(org.thoughtcrime.securesms.util.Rfc5724Uri) Recipients(org.thoughtcrime.securesms.recipients.Recipients) OutgoingMediaMessage(org.thoughtcrime.securesms.mms.OutgoingMediaMessage) RecipientsPreferences(org.thoughtcrime.securesms.database.RecipientPreferenceDatabase.RecipientsPreferences) SlideDeck(org.thoughtcrime.securesms.mms.SlideDeck) URISyntaxException(java.net.URISyntaxException)

Example 28 with URISyntaxException

use of java.net.URISyntaxException in project jersey by jersey.

the class RedirectHandler method doRedirect.

private void doRedirect(final HttpResponse httpResponse, final CompletionHandler<HttpResponse> completionHandler) {
    // get location header
    String locationString = null;
    final List<String> locationHeader = httpResponse.getHeader("Location");
    if (locationHeader != null && !locationHeader.isEmpty()) {
        locationString = locationHeader.get(0);
    }
    if (locationString == null || locationString.isEmpty()) {
        completionHandler.failed(new RedirectException(LocalizationMessages.REDIRECT_NO_LOCATION()));
        return;
    }
    URI location;
    try {
        location = new URI(locationString);
        if (!location.isAbsolute()) {
            // location is not absolute, we need to resolve it.
            URI baseUri = lastRequestUri;
            location = baseUri.resolve(location.normalize());
        }
    } catch (URISyntaxException e) {
        completionHandler.failed(new RedirectException(LocalizationMessages.REDIRECT_ERROR_DETERMINING_LOCATION(), e));
        return;
    }
    // infinite loop detection
    boolean alreadyRequested = !redirectUriHistory.add(location);
    if (alreadyRequested) {
        completionHandler.failed(new RedirectException(LocalizationMessages.REDIRECT_INFINITE_LOOP()));
        return;
    }
    // maximal number of redirection
    if (redirectUriHistory.size() > maxRedirects) {
        completionHandler.failed(new RedirectException(LocalizationMessages.REDIRECT_LIMIT_REACHED(maxRedirects)));
        return;
    }
    String method = originalHttpRequest.getMethod();
    Map<String, List<String>> headers = originalHttpRequest.getHeaders();
    if (httpResponse.getStatusCode() == 303 && !method.equals(Constants.HEAD)) {
        // in case of 303 we rewrite every method except HEAD to GET
        method = Constants.GET;
        // remove entity-transport headers if present
        headers.remove(Constants.CONTENT_LENGTH);
        headers.remove(Constants.TRANSFER_ENCODING_HEADER);
    }
    HttpRequest httpRequest = HttpRequest.createBodyless(method, location);
    httpRequest.getHeaders().putAll(headers);
    lastRequestUri = location;
    httpConnectionPool.send(httpRequest, completionHandler);
}
Also used : List(java.util.List) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI)

Example 29 with URISyntaxException

use of java.net.URISyntaxException in project rest.li by linkedin.

the class DegraderLoadBalancerStrategyV3 method checkQuarantineState.

/**
   * checkQuarantineState decides if the D2Quarantine can be enabled or not, by health
   * checking all the trackerClients once. It enables quarantine only if at least one of the
   * clients return success for the checking.
   *
   * The reasons for this checking include:
   *
   * . The default method "OPTIONS" is not always enabled by the service
   * . The user can config any path/method for checking. We do a sanity checking to
   *   make sure the configuration is correct, and service/host responds in time.
   *   Otherwise the host can be kept in quarantine forever if we blindly enable it.
   *
   * This check actually can warm up the R2 connection pool by making a connection to
   * each trackerClient. However since the check happens before any real requests are sent,
   * it generally takes much longer time to get the results, due to different warming up
   * requirements. Therefore the checking will be retried in next update if current check
   * fails.

   *
   * This function is supposed to be protected by the update lock.
   *
   * @param clients
   * @param config
   */
private void checkQuarantineState(List<TrackerClientUpdater> clients, DegraderLoadBalancerStrategyConfig config) {
    Callback<None> healthCheckCallback = new Callback<None>() {

        @Override
        public void onError(Throwable e) {
            // Do nothing as the quarantine is disabled by default
            _rateLimitedLogger.error("Error to enable quarantine. Health checking failed for service {}: ", _state._serviceName, e);
        }

        @Override
        public void onSuccess(None result) {
            if (_state._enableQuarantine.compareAndSet(false, true)) {
                _log.info("Quarantine is enabled for service {}", _state._serviceName);
            }
        }
    };
    // Ideally we would like to healthchecking all the service hosts (ie all TrackerClients) because
    // this can help to warm up the R2 connections to the service hosts, thus speed up the initial access
    // speed when d2client starts to access those hosts. However this can expose/expedite the problem that
    // the d2client host needs too many connections or file handles to all the hosts, when the downstream
    // services have large amount of hosts. Before that problem is addressed, we limit the number of hosts
    // for pre-healthchecking to a small number
    clients.stream().limit(MAX_HOSTS_TO_CHECK_QUARANTINE).forEach(client -> {
        try {
            HealthCheck healthCheckClient = _state.getHealthCheckClient(client);
            if (healthCheckClient == null) {
                healthCheckClient = new HealthCheckClientBuilder().setHealthCheckOperations(config.getHealthCheckOperations()).setHealthCheckPath(config.getHealthCheckPath()).setServicePath(config.getServicePath()).setClock(config.getClock()).setLatency(config.getQuarantineLatency()).setMethod(config.getHealthCheckMethod()).setClient(client.getTrackerClient()).build();
                _state.putHealthCheckClient(client, healthCheckClient);
            }
            healthCheckClient.checkHealth(healthCheckCallback);
        } catch (URISyntaxException e) {
            _log.error("Error to build healthCheckClient ", e);
        }
    });
    // also remove the entries that the corresponding trackerClientUpdaters do not exist anymore
    for (TrackerClientUpdater client : _state._healthCheckMap.keySet()) {
        if (!clients.contains(client)) {
            _state._healthCheckMap.remove(client);
        }
    }
}
Also used : Callback(com.linkedin.common.callback.Callback) HealthCheck(com.linkedin.d2.balancer.util.healthcheck.HealthCheck) HealthCheckClientBuilder(com.linkedin.d2.balancer.util.healthcheck.HealthCheckClientBuilder) URISyntaxException(java.net.URISyntaxException) None(com.linkedin.common.util.None)

Example 30 with URISyntaxException

use of java.net.URISyntaxException in project javaee7-samples by javaee-samples.

the class PersonSessionBean method initDB.

@PostConstruct
private void initDB() {
    try {
        // Get an instance of Couchbase
        List<URI> hosts = Arrays.asList(new URI("http://localhost:8091/pools"));
        // Get an instance of Couchbase
        // Name of the Bucket to connect to
        String bucket = "default";
        // Password of the bucket (empty) string if none
        String password = "";
        // Connect to the Cluster
        client = new CouchbaseClient(hosts, bucket, password);
    } catch (URISyntaxException | IOException ex) {
        Logger.getLogger(PersonSessionBean.class.getName()).log(Level.SEVERE, null, ex);
    }
}
Also used : URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) URI(java.net.URI) CouchbaseClient(com.couchbase.client.CouchbaseClient) PostConstruct(javax.annotation.PostConstruct)

Aggregations

URISyntaxException (java.net.URISyntaxException)4043 URI (java.net.URI)2496 IOException (java.io.IOException)1273 File (java.io.File)716 URL (java.net.URL)702 ArrayList (java.util.ArrayList)407 Test (org.junit.Test)274 MalformedURLException (java.net.MalformedURLException)270 InputStream (java.io.InputStream)224 HashMap (java.util.HashMap)212 Response (javax.ws.rs.core.Response)194 Test (org.testng.annotations.Test)175 Parameters (org.testng.annotations.Parameters)166 Builder (javax.ws.rs.client.Invocation.Builder)165 ResteasyClientBuilder (org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder)165 Map (java.util.Map)162 StorageException (com.microsoft.azure.storage.StorageException)142 Path (java.nio.file.Path)141 URIBuilder (org.apache.http.client.utils.URIBuilder)140 List (java.util.List)125