Example usage for java.net HttpURLConnection HTTP_FORBIDDEN

List of usage examples for java.net HttpURLConnection HTTP_FORBIDDEN

Introduction

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

Prototype

int HTTP_FORBIDDEN

To view the source code for java.net HttpURLConnection HTTP_FORBIDDEN.

Click Source Link

Document

HTTP Status-Code 403: Forbidden.

Usage

From source file:org.apache.maven.wagon.providers.http.LightweightHttpWagon.java

public boolean resourceExists(String resourceName) throws TransferFailedException, AuthorizationException {
    HttpURLConnection headConnection;

    try {/*from w w  w. j  av a  2 s. c om*/
        URL url = new URL(buildUrl(new Resource(resourceName).getName()));
        headConnection = (HttpURLConnection) url.openConnection(this.proxy);

        addHeaders(headConnection);

        headConnection.setRequestMethod("HEAD");
        headConnection.setDoOutput(true);

        int statusCode = headConnection.getResponseCode();

        switch (statusCode) {
        case HttpURLConnection.HTTP_OK:
            return true;

        case HttpURLConnection.HTTP_FORBIDDEN:
            throw new AuthorizationException("Access denied to: " + url);

        case HttpURLConnection.HTTP_NOT_FOUND:
            return false;

        case HttpURLConnection.HTTP_UNAUTHORIZED:
            throw new AuthorizationException("Access denied to: " + url);

        default:
            throw new TransferFailedException(
                    "Failed to look for file: " + buildUrl(resourceName) + ". Return code is: " + statusCode);
        }
    } catch (IOException e) {
        throw new TransferFailedException("Error transferring file: " + e.getMessage(), e);
    }
}

From source file:org.openhab.binding.digitalstrom.internal.lib.manager.impl.ConnectionManagerImpl.java

private boolean codeIsAuthentificationFaild() {
    return this.code == HttpURLConnection.HTTP_FORBIDDEN;
}

From source file:net.dahanne.gallery3.client.business.G3Client.java

private HttpEntity requestToResponseEntity(String appendToGalleryUrl, List<NameValuePair> nameValuePairs,
        String requestMethod, File file)
        throws UnsupportedEncodingException, IOException, ClientProtocolException, G3GalleryException {
    HttpClient defaultHttpClient = new DefaultHttpClient();
    HttpRequestBase httpMethod;/*from  w w w .  j a  v  a 2 s  .  co m*/
    //are we using rewritten urls ?
    if (this.isUsingRewrittenUrls && appendToGalleryUrl.contains(INDEX_PHP_REST)) {
        appendToGalleryUrl = StringUtils.remove(appendToGalleryUrl, "index.php");
    }

    logger.debug("requestToResponseEntity , url requested : {}", galleryItemUrl + appendToGalleryUrl);
    if (POST.equals(requestMethod)) {
        httpMethod = new HttpPost(galleryItemUrl + appendToGalleryUrl);
        httpMethod.setHeader(X_GALLERY_REQUEST_METHOD, requestMethod);
        if (file != null) {
            MultipartEntity multipartEntity = new MultipartEntity();

            String string = nameValuePairs.toString();
            // dirty fix to remove the enclosing entity{}
            String substring = string.substring(string.indexOf("{"), string.lastIndexOf("}") + 1);

            StringBody contentBody = new StringBody(substring, Charset.forName("UTF-8"));
            multipartEntity.addPart("entity", contentBody);
            FileBody fileBody = new FileBody(file);
            multipartEntity.addPart("file", fileBody);
            ((HttpPost) httpMethod).setEntity(multipartEntity);
        } else {
            ((HttpPost) httpMethod).setEntity(new UrlEncodedFormEntity(nameValuePairs));
        }
    } else if (PUT.equals(requestMethod)) {
        httpMethod = new HttpPost(galleryItemUrl + appendToGalleryUrl);
        httpMethod.setHeader(X_GALLERY_REQUEST_METHOD, requestMethod);
        ((HttpPost) httpMethod).setEntity(new UrlEncodedFormEntity(nameValuePairs));
    } else if (DELETE.equals(requestMethod)) {
        httpMethod = new HttpGet(galleryItemUrl + appendToGalleryUrl);
        httpMethod.setHeader(X_GALLERY_REQUEST_METHOD, requestMethod);
        //this is to avoid the HTTP 414 (length too long) error
        //it should only happen when getting items, index.php/rest/items?urls=
        //      } else if(appendToGalleryUrl.length()>2000) {
        //         String resource = appendToGalleryUrl.substring(0,appendToGalleryUrl.indexOf("?"));
        //         String variable = appendToGalleryUrl.substring(appendToGalleryUrl.indexOf("?")+1,appendToGalleryUrl.indexOf("="));
        //         String value = appendToGalleryUrl.substring(appendToGalleryUrl.indexOf("=")+1);
        //         httpMethod = new HttpPost(galleryItemUrl + resource);
        //         httpMethod.setHeader(X_GALLERY_REQUEST_METHOD, requestMethod);
        //         nameValuePairs.add(new BasicNameValuePair(variable, value));
        //         ((HttpPost) httpMethod).setEntity(new UrlEncodedFormEntity(
        //               nameValuePairs));
    } else {
        httpMethod = new HttpGet(galleryItemUrl + appendToGalleryUrl);
    }
    if (existingApiKey != null) {
        httpMethod.setHeader(X_GALLERY_REQUEST_KEY, existingApiKey);
    }
    //adding the userAgent to the request
    httpMethod.setHeader(USER_AGENT, userAgent);
    HttpResponse response = null;

    String[] patternsArray = new String[3];
    patternsArray[0] = "EEE, dd MMM-yyyy-HH:mm:ss z";
    patternsArray[1] = "EEE, dd MMM yyyy HH:mm:ss z";
    patternsArray[2] = "EEE, dd-MMM-yyyy HH:mm:ss z";
    try {
        // be extremely careful here, android httpclient needs it to be
        // an
        // array of string, not an arraylist
        defaultHttpClient.getParams().setParameter(CookieSpecPNames.DATE_PATTERNS, patternsArray);
        response = defaultHttpClient.execute(httpMethod);
    } catch (ClassCastException e) {
        List<String> patternsList = Arrays.asList(patternsArray);
        defaultHttpClient.getParams().setParameter(CookieSpecPNames.DATE_PATTERNS, patternsList);
        response = defaultHttpClient.execute(httpMethod);
    }

    int responseStatusCode = response.getStatusLine().getStatusCode();
    HttpEntity responseEntity = null;
    if (response.getEntity() != null) {
        responseEntity = response.getEntity();
    }

    switch (responseStatusCode) {
    case HttpURLConnection.HTTP_CREATED:
        break;
    case HttpURLConnection.HTTP_OK:
        break;
    case HttpURLConnection.HTTP_MOVED_TEMP:
        //the gallery is using rewritten urls, let's remember it and re hit the server
        this.isUsingRewrittenUrls = true;
        responseEntity = requestToResponseEntity(appendToGalleryUrl, nameValuePairs, requestMethod, file);
        break;
    case HttpURLConnection.HTTP_BAD_REQUEST:
        throw new G3BadRequestException();
    case HttpURLConnection.HTTP_FORBIDDEN:
        //for some reasons, the gallery may respond with 403 when trying to log in with the wrong url
        if (appendToGalleryUrl.contains(INDEX_PHP_REST)) {
            this.isUsingRewrittenUrls = true;
            responseEntity = requestToResponseEntity(appendToGalleryUrl, nameValuePairs, requestMethod, file);
            break;
        }
        throw new G3ForbiddenException();
    case HttpURLConnection.HTTP_NOT_FOUND:
        throw new G3ItemNotFoundException();
    default:
        throw new G3GalleryException("HTTP code " + responseStatusCode);
    }

    return responseEntity;
}

From source file:org.eclipse.hono.deviceregistry.FileBasedTenantService.java

/**
 * Updates a tenant./*from ww  w  .j  ava2s.c  om*/
 *
 * @param tenantId The identifier of the tenant.
 * @param tenantSpec The information to update the tenant with.
 * @return The outcome of the operation indicating success or failure.
 * @throws NullPointerException if any of the parameters are {@code null}.
 */
public TenantResult<JsonObject> update(final String tenantId, final JsonObject tenantSpec) {

    Objects.requireNonNull(tenantId);
    Objects.requireNonNull(tenantSpec);

    if (getConfig().isModificationEnabled()) {
        if (tenants.containsKey(tenantId)) {
            try {
                final TenantObject tenant = tenantSpec.mapTo(TenantObject.class);
                tenant.setTenantId(tenantId);
                final TenantObject conflictingTenant = getByCa(tenant.getTrustedCaSubjectDn());
                if (conflictingTenant != null && !tenantId.equals(conflictingTenant.getTenantId())) {
                    // we are trying to use the same CA as another tenant
                    return TenantResult.from(HttpURLConnection.HTTP_CONFLICT);
                } else {
                    tenants.put(tenantId, tenant);
                    dirty = true;
                    return TenantResult.from(HttpURLConnection.HTTP_NO_CONTENT);
                }
            } catch (IllegalArgumentException e) {
                return TenantResult.from(HttpURLConnection.HTTP_BAD_REQUEST);
            }
        } else {
            return TenantResult.from(HttpURLConnection.HTTP_NOT_FOUND);
        }
    } else {
        return TenantResult.from(HttpURLConnection.HTTP_FORBIDDEN);
    }
}

From source file:org.openhab.binding.digitalstrom.internal.lib.manager.impl.ConnectionManagerImpl.java

@Override
public boolean checkConnection(int code) {
    switch (code) {
    case HttpURLConnection.HTTP_INTERNAL_ERROR:
    case HttpURLConnection.HTTP_OK:
        if (!connectionEstablished) {
            connectionEstablished = true;
            onConnectionResumed();/*from  ww  w.  j  a  v a 2s  . com*/
        }
        break;
    case HttpURLConnection.HTTP_UNAUTHORIZED:
        connectionEstablished = false;
        break;
    case HttpURLConnection.HTTP_FORBIDDEN:
        getNewSessionToken();
        if (sessionToken != null) {
            if (!connectionEstablished) {
                onConnectionResumed();
                connectionEstablished = true;
            }
        } else {
            if (this.genAppToken) {
                onNotAuthenticated();
            }
            connectionEstablished = false;
        }
        break;
    case ConnectionManager.MALFORMED_URL_EXCEPTION:
        onConnectionLost(ConnectionListener.INVALID_URL);
        connectionEstablished = false;
        break;
    case ConnectionManager.CONNECTION_EXCEPTION:
    case ConnectionManager.SOCKET_TIMEOUT_EXCEPTION:
        onConnectionLost(ConnectionListener.CONNECTON_TIMEOUT);
        connectionEstablished = false;
        break;
    case ConnectionManager.GENERAL_EXCEPTION:
        if (connListener != null) {
            connListener.onConnectionStateChange(ConnectionListener.CONNECTION_LOST);
        }
        break;
    case ConnectionManager.UNKNOWN_HOST_EXCEPTION:
        if (connListener != null) {
            onConnectionLost(ConnectionListener.UNKNOWN_HOST);
        }
        break;
    case ConnectionManager.AUTHENTIFICATION_PROBLEM:
        if (connListener != null) {
            if (config.getAppToken() != null) {
                connListener.onConnectionStateChange(ConnectionListener.NOT_AUTHENTICATED,
                        ConnectionListener.WRONG_APP_TOKEN);
            } else {
                connListener.onConnectionStateChange(ConnectionListener.NOT_AUTHENTICATED,
                        ConnectionListener.WRONG_USER_OR_PASSWORD);
            }
        }
        break;
    case HttpURLConnection.HTTP_NOT_FOUND:
        onConnectionLost(ConnectionListener.HOST_NOT_FOUND);
        connectionEstablished = false;
        break;
    }
    return connectionEstablished;
}

From source file:org.eclipse.mylyn.internal.gerrit.core.client.GerritHttpClient.java

public <T> T execute(Request<T> request, boolean authenticateIfNeeded, IProgressMonitor monitor)
        throws IOException, GerritException {
    String openIdProvider = getOpenIdProvider();

    hostConfiguration = WebUtil.createHostConfiguration(httpClient, location, monitor);

    for (int attempt = 0; attempt < 2; attempt++) {
        if (authenticateIfNeeded) {
            // force authentication
            if (needsAuthentication()) {
                AuthenticationCredentials credentials = location.getCredentials(AuthenticationType.REPOSITORY);
                if (openIdProvider != null || credentials != null) {
                    authenticate(openIdProvider, monitor);
                }//  w ww  .ja  v a 2  s  .  c  om
            }
            if (!obtainedXsrfKey) {
                updateXsrfKey(monitor);
            }
        }

        HttpMethodBase method = request.createMethod();
        if (obtainedXsrfKey) {
            // required to authenticate against Gerrit 2.6+ REST endpoints
            // harmless in previous versions
            method.setRequestHeader(X_GERRIT_AUTHORITY, xsrfKey);
        }
        try {
            // Execute the method.
            WebUtil.execute(httpClient, hostConfiguration, method, monitor);
        } catch (IOException e) {
            WebUtil.releaseConnection(method, monitor);
            throw e;
        } catch (RuntimeException e) {
            WebUtil.releaseConnection(method, monitor);
            throw e;
        }

        int code = method.getStatusCode();
        if (code == HttpURLConnection.HTTP_OK || code == HttpURLConnection.HTTP_ACCEPTED
                || code == HttpURLConnection.HTTP_CREATED) {
            try {
                return request.process(method);
            } finally {
                WebUtil.releaseConnection(method, monitor);
            }
        } else if (code == HttpURLConnection.HTTP_NO_CONTENT) {
            try {
                return null;
            } finally {
                WebUtil.releaseConnection(method, monitor);
            }

        } else {
            try {
                request.handleError(method);
            } finally {
                WebUtil.releaseConnection(method, monitor);
            }
            if (code == HttpURLConnection.HTTP_UNAUTHORIZED || code == HttpURLConnection.HTTP_FORBIDDEN) {
                // login or re-authenticate due to an expired session
                authenticate(openIdProvider, monitor);
            } else {
                throw new GerritHttpException(code);
            }
        }
    }

    throw new GerritLoginException();
}

From source file:org.eclipse.hono.service.registration.BaseRegistrationService.java

/**
 * {@inheritDoc}/*  w  ww .  j  a v  a 2s. c o  m*/
 * <p>
 * Subclasses may override this method in order to implement a more sophisticated approach for asserting registration status, e.g.
 * using cached information etc.
 */
@Override
public void assertRegistration(final String tenantId, final String deviceId, final String gatewayId,
        final Handler<AsyncResult<RegistrationResult>> resultHandler) {

    Objects.requireNonNull(tenantId);
    Objects.requireNonNull(deviceId);
    Objects.requireNonNull(gatewayId);
    Objects.requireNonNull(resultHandler);

    final Future<RegistrationResult> deviceInfoTracker = Future.future();
    final Future<RegistrationResult> gatewayInfoTracker = Future.future();

    getDevice(tenantId, deviceId, deviceInfoTracker.completer());
    getDevice(tenantId, gatewayId, gatewayInfoTracker.completer());

    CompositeFuture.all(deviceInfoTracker, gatewayInfoTracker).compose(ok -> {

        final RegistrationResult deviceResult = deviceInfoTracker.result();
        final RegistrationResult gatewayResult = gatewayInfoTracker.result();

        if (!isDeviceEnabled(deviceResult)) {
            return Future.succeededFuture(RegistrationResult.from(HttpURLConnection.HTTP_NOT_FOUND));
        } else if (!isDeviceEnabled(gatewayResult)) {
            return Future.succeededFuture(RegistrationResult.from(HttpURLConnection.HTTP_FORBIDDEN));
        } else {

            final JsonObject deviceData = deviceResult.getPayload()
                    .getJsonObject(RegistrationConstants.FIELD_DATA, new JsonObject());
            final JsonObject gatewayData = gatewayResult.getPayload()
                    .getJsonObject(RegistrationConstants.FIELD_DATA, new JsonObject());

            if (isGatewayAuthorized(gatewayId, gatewayData, deviceId, deviceData)) {
                return Future.succeededFuture(RegistrationResult.from(HttpURLConnection.HTTP_OK,
                        getAssertionPayload(tenantId, deviceId, deviceData),
                        CacheDirective.maxAgeDirective(assertionFactory.getAssertionLifetime())));
            } else {
                return Future.succeededFuture(RegistrationResult.from(HttpURLConnection.HTTP_FORBIDDEN));
            }
        }
    }).setHandler(resultHandler);
}

From source file:fr.mael.jiwigo.dao.impl.ImageDaoImpl.java

public void addSimple(File file, Integer category, String title, Integer level) throws JiwigoException {
    HttpPost httpMethod = new HttpPost(((SessionManagerImpl) sessionManager).getUrl());

    //   nameValuePairs.add(new BasicNameValuePair("method", "pwg.images.addSimple"));
    //   for (int i = 0; i < parametres.length; i += 2) {
    //       nameValuePairs.add(new BasicNameValuePair(parametres[i], parametres[i + 1]));
    //   }/*from  ww  w  .  ja  v  a 2  s.c o m*/
    //   method.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    if (file != null) {
        MultipartEntity multipartEntity = new MultipartEntity();

        //      String string = nameValuePairs.toString();
        // dirty fix to remove the enclosing entity{}
        //      String substring = string.substring(string.indexOf("{"),
        //            string.lastIndexOf("}") + 1);
        try {
            multipartEntity.addPart("method", new StringBody(MethodsEnum.ADD_SIMPLE.getLabel()));
            multipartEntity.addPart("category", new StringBody(category.toString()));
            multipartEntity.addPart("name", new StringBody(title));
            if (level != null) {
                multipartEntity.addPart("level", new StringBody(level.toString()));
            }
        } catch (UnsupportedEncodingException e) {
            throw new JiwigoException(e);
        }

        //      StringBody contentBody = new StringBody(substring,
        //            Charset.forName("UTF-8"));
        //      multipartEntity.addPart("entity", contentBody);
        FileBody fileBody = new FileBody(file);
        multipartEntity.addPart("image", fileBody);
        ((HttpPost) httpMethod).setEntity(multipartEntity);
    }

    HttpResponse response;
    StringBuilder sb = new StringBuilder();
    try {
        response = ((SessionManagerImpl) sessionManager).getClient().execute(httpMethod);

        int responseStatusCode = response.getStatusLine().getStatusCode();

        switch (responseStatusCode) {
        case HttpURLConnection.HTTP_CREATED:
            break;
        case HttpURLConnection.HTTP_OK:
            break;
        case HttpURLConnection.HTTP_BAD_REQUEST:
            throw new JiwigoException("status code was : " + responseStatusCode);
        case HttpURLConnection.HTTP_FORBIDDEN:
            throw new JiwigoException("status code was : " + responseStatusCode);
        case HttpURLConnection.HTTP_NOT_FOUND:
            throw new JiwigoException("status code was : " + responseStatusCode);
        default:
            throw new JiwigoException("status code was : " + responseStatusCode);
        }

        HttpEntity resultEntity = response.getEntity();
        BufferedHttpEntity responseEntity = new BufferedHttpEntity(resultEntity);

        BufferedReader reader = new BufferedReader(new InputStreamReader(responseEntity.getContent()));
        String line;

        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line);
                sb.append("\n");
            }
        } finally {
            reader.close();
        }
    } catch (ClientProtocolException e) {
        throw new JiwigoException(e);
    } catch (IOException e) {
        throw new JiwigoException(e);
    }
    String stringResult = sb.toString();

}

From source file:hudson.model.DirectoryBrowserSupportSEC904Test.java

@Test
@Issue("SECURITY-904")
public void junctionAndSymlink_outsideWorkspace_areNotAllowed_windowsJunction() throws Exception {
    Assume.assumeTrue(Functions.isWindows());

    FreeStyleProject p = j.createFreeStyleProject();

    File secretsFolder = new File(j.jenkins.getRootDir(), "secrets");
    File secretTarget = new File(secretsFolder, "goal.txt");
    String secretContent = "secret";
    FileUtils.write(secretTarget, secretContent);

    /*/*from   w w  w .ja  va 2  s .c  om*/
     *  secrets/
     *      goal.txt
     *  workspace/
     *      intermediateFolder/
     *          public2.key
     *          otherFolder/
     *              to_secret3s -> symlink ../../../../secrets/
     *              to_secret3j -> junction ../../../../secrets/
     *          to_secret2s -> symlink ../../../secrets/
     *          to_secret2j -> junction ../../../secrets/
     *          to_secret_goal2 -> symlink ../../../secrets/goal.txt
     *      public1.key
     *      to_secret1s -> symlink ../../secrets/
     *      to_secret1j -> junction ../../secrets/
     *      to_secret_goal1 -> symlink ../../secrets/goal.txt
     *
     */
    String script = loadContentFromResource("outsideWorkspaceStructureWithJunctions.bat");
    p.getBuildersList().add(new BatchFile(script));

    assertEquals(Result.SUCCESS, p.scheduleBuild2(0).get().getResult());

    JenkinsRule.WebClient wc = j.createWebClient();
    wc.getOptions().setThrowExceptionOnFailingStatusCode(false);
    { // workspace root must be reachable (regular case)
        Page page = wc.goTo(p.getUrl() + "ws/", null);
        assertThat(page.getWebResponse().getStatusCode(), equalTo(HttpURLConnection.HTTP_OK));
        String workspaceContent = page.getWebResponse().getContentAsString();
        assertThat(workspaceContent,
                allOf(containsString("public1.key"), containsString("intermediateFolder"),
                        containsString("to_secrets1j"), containsString("to_secrets1s"),
                        containsString("to_secrets_goal1"), not(containsString("to_secrets2")),
                        not(containsString("to_secrets_goal2"))));
    }
    { // to_secrets1s not reachable
        Page page = wc.goTo(p.getUrl() + "ws/to_secrets1s/", null);
        assertThat(page.getWebResponse().getStatusCode(), equalTo(HttpURLConnection.HTTP_FORBIDDEN));
    }
    { // to_secrets1j not reachable
        Page page = wc.goTo(p.getUrl() + "ws/to_secrets1j/", null);
        assertThat(page.getWebResponse().getStatusCode(), equalTo(HttpURLConnection.HTTP_FORBIDDEN));
    }
    { // to_secrets_goal1 not reachable
        Page page = wc.goTo(p.getUrl() + "ws/to_secrets_goal1/", null);
        assertThat(page.getWebResponse().getStatusCode(), equalTo(HttpURLConnection.HTTP_FORBIDDEN));
    }
    { // intermediateFolder must be reachable (regular case)
        Page page = wc.goTo(p.getUrl() + "ws/intermediateFolder/", null);
        assertThat(page.getWebResponse().getStatusCode(), equalTo(HttpURLConnection.HTTP_OK));
        String workspaceContent = page.getWebResponse().getContentAsString();
        assertThat(workspaceContent,
                allOf(not(containsString("to_secrets1")), not(containsString("to_secrets_goal1")),
                        containsString("to_secrets2s"), containsString("to_secrets2j"),
                        containsString("to_secrets_goal2")));
    }
    { // to_secrets2s not reachable
        Page page = wc.goTo(p.getUrl() + "ws/intermediateFolder/to_secrets2s/", null);
        assertThat(page.getWebResponse().getStatusCode(), equalTo(HttpURLConnection.HTTP_FORBIDDEN));
    }
    { // to_secrets2j not reachable
        Page page = wc.goTo(p.getUrl() + "ws/intermediateFolder/to_secrets2j/", null);
        assertThat(page.getWebResponse().getStatusCode(), equalTo(HttpURLConnection.HTTP_FORBIDDEN));
    }
    { // using symbolic in the intermediate path
        Page page = wc.goTo(p.getUrl() + "ws/intermediateFolder/to_secrets2s/master.key", null);
        assertThat(page.getWebResponse().getStatusCode(), equalTo(HttpURLConnection.HTTP_FORBIDDEN));
    }
    { // using symbolic in the intermediate path
        Page page = wc.goTo(p.getUrl() + "ws/intermediateFolder/to_secrets2j/master.key", null);
        assertThat(page.getWebResponse().getStatusCode(), equalTo(HttpURLConnection.HTTP_FORBIDDEN));
    }
    { // to_secrets_goal2 not reachable
        Page page = wc.goTo(p.getUrl() + "ws/intermediateFolder/to_secrets_goal2/", null);
        assertThat(page.getWebResponse().getStatusCode(), equalTo(HttpURLConnection.HTTP_FORBIDDEN));
    }

    // pattern search feature
    { // the pattern allow us to search inside the files / folders, 
      // without the patch the master.key from inside the outside symlinks would have been linked
        Page page = wc.goTo(p.getUrl() + "ws/**/*.key", null);
        assertThat(page.getWebResponse().getStatusCode(), equalTo(HttpURLConnection.HTTP_OK));
        String workspaceContent = page.getWebResponse().getContentAsString();
        assertThat(workspaceContent,
                allOf(not(containsString("master.key")), containsString("public1.key"),
                        containsString("public2.key"), containsString("intermediateFolder"),
                        not(containsString("otherFolder")), not(containsString("to_secrets3j")),
                        not(containsString("to_secrets3s")), not(containsString("to_secrets2j")),
                        not(containsString("to_secrets2s")), not(containsString("to_secrets1j")),
                        not(containsString("to_secrets1s"))));
    }

    // zip feature
    { // all the outside folders / files are not included in the zip
        Page zipPage = wc.goTo(p.getUrl() + "ws/*zip*/ws.zip", null);
        assertThat(zipPage.getWebResponse().getStatusCode(), equalTo(HttpURLConnection.HTTP_OK));

        List<String> entryNames = getListOfEntriesInDownloadedZip((UnexpectedPage) zipPage);
        assertThat(entryNames, containsInAnyOrder(p.getName() + "/intermediateFolder/public2.key",
                p.getName() + "/public1.key"));
    }
    { // all the outside folders / files are not included in the zip
        Page zipPage = wc.goTo(p.getUrl() + "ws/intermediateFolder/*zip*/intermediateFolder.zip", null);
        assertThat(zipPage.getWebResponse().getStatusCode(), equalTo(HttpURLConnection.HTTP_OK));

        List<String> entryNames = getListOfEntriesInDownloadedZip((UnexpectedPage) zipPage);
        assertThat(entryNames, contains("intermediateFolder/public2.key"));
    }
}

From source file:org.eclipse.hono.adapter.mqtt.AbstractVertxBasedMqttProtocolAdapter.java

private Future<Device> handleEndpointConnectionWithAuthentication(final MqttEndpoint endpoint) {

    if (endpoint.auth() == null) {

        LOG.debug("connection request from device [clientId: {}] rejected: {}", endpoint.clientIdentifier(),
                "device did not provide credentials in CONNECT packet");

        return rejected(MqttConnectReturnCode.CONNECTION_REFUSED_BAD_USER_NAME_OR_PASSWORD);

    } else {//from  ww  w  . ja  v  a  2  s.c o  m

        final DeviceCredentials credentials = getCredentials(endpoint.auth());

        if (credentials == null) {

            LOG.debug("connection request from device [clientId: {}] rejected: {}", endpoint.clientIdentifier(),
                    "device provided malformed credentials in CONNECT packet");
            return rejected(MqttConnectReturnCode.CONNECTION_REFUSED_BAD_USER_NAME_OR_PASSWORD);

        } else {

            return getTenantConfiguration(credentials.getTenantId()).compose(tenantConfig -> {
                if (tenantConfig.isAdapterEnabled(getTypeName())) {
                    LOG.debug("protocol adapter [{}] is enabled for tenant [{}]", getTypeName(),
                            credentials.getTenantId());
                    return Future.succeededFuture(tenantConfig);
                } else {
                    LOG.debug("protocol adapter [{}] is disabled for tenant [{}]", getTypeName(),
                            credentials.getTenantId());
                    return Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_FORBIDDEN,
                            "adapter disabled for tenant"));
                }
            }).compose(tenantConfig -> {
                final Future<Device> result = Future.future();
                usernamePasswordAuthProvider.authenticate(credentials, result.completer());
                return result;
            }).compose(authenticatedDevice -> {
                LOG.debug("successfully authenticated device [tenant-id: {}, auth-id: {}, device-id: {}]",
                        authenticatedDevice.getTenantId(), credentials.getAuthId(),
                        authenticatedDevice.getDeviceId());
                return triggerLinkCreation(authenticatedDevice.getTenantId()).map(done -> {
                    onAuthenticationSuccess(endpoint, authenticatedDevice);
                    return null;
                }).compose(ok -> accepted(authenticatedDevice));
            }).recover(t -> {
                LOG.debug("cannot establish connection with device [tenant-id: {}, auth-id: {}]",
                        credentials.getTenantId(), credentials.getAuthId(), t);
                if (t instanceof ServerErrorException) {
                    // one of the services we depend on might not be available (yet)
                    return rejected(MqttConnectReturnCode.CONNECTION_REFUSED_SERVER_UNAVAILABLE);
                } else {
                    // validation of credentials has failed
                    return rejected(MqttConnectReturnCode.CONNECTION_REFUSED_NOT_AUTHORIZED);
                }
            });

        }
    }
}