Example usage for java.net HttpURLConnection HTTP_BAD_REQUEST

List of usage examples for java.net HttpURLConnection HTTP_BAD_REQUEST

Introduction

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

Prototype

int HTTP_BAD_REQUEST

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

Click Source Link

Document

HTTP Status-Code 400: Bad Request.

Usage

From source file:com.hotmart.dragonfly.profile.ui.ChangePasswordActivity.java

@OnClick(R.id.redefinir_senha_enviar)
public void redefinirSenha(View view) {
    final EditText email = (EditText) findViewById(R.id.accountName);
    String textoEmail = email.getText().toString();

    ForgotPasswordRequestVO forgotPasswordRequestVO = new ForgotPasswordRequestVO();
    forgotPasswordRequestVO.setEmail(textoEmail);

    mUserService.forgotPassword(forgotPasswordRequestVO).enqueue(new Callback<Void>() {
        @Override//  w w w  .  j  a va2  s.  c  om
        public void onResponse(Call<Void> call, Response<Void> response) {
            switch (response.code()) {
            case HttpURLConnection.HTTP_OK:
                Bundle bundle = new Bundle();
                bundle.putString(AuthenticatorActivity.PARAM_USER_NAME, email.getText().toString());
                Intent intent = new Intent();
                intent.putExtras(bundle);
                setResult(RESULT_OK, intent);
                Intent redefinirSenhaSucesso = new Intent(thisActivity, ResetPasswordSuccessActivity.class);
                thisActivity.startActivity(redefinirSenhaSucesso);
                finish();
                break;
            case HttpURLConnection.HTTP_BAD_REQUEST:
                Snackbar.make(email, R.string.status_400, Snackbar.LENGTH_LONG).show();
            default:
                Snackbar.make(email, R.string.status_500, Snackbar.LENGTH_LONG).show();
            }
        }

        @Override
        public void onFailure(Call<Void> call, Throwable t) {
            Snackbar.make(email, R.string.status_500, Snackbar.LENGTH_LONG).show();
            Log.e("dragonfly", t.getMessage(), t);
        }
    });

}

From source file:eu.codeplumbers.cosi.api.tasks.CheckDesignDocumentsTask.java

@Override
protected String doInBackground(String... docTypes) {
    errorMessage = "";
    for (int i = 0; i < docTypes.length; i++) {
        String docType = docTypes[i].toLowerCase();
        publishProgress("Checking design: " + docType);

        URL urlO = null;/*ww w . j  a v  a2 s.  c o m*/
        try {

            // using all view can break notes, files app in cozy
            urlO = getCosiUrl(docType);

            HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
            conn.setConnectTimeout(5000);
            conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            conn.setRequestProperty("Authorization", authHeader);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");

            // read the response
            int status = conn.getResponseCode();
            InputStream in = null;

            if (status >= HttpURLConnection.HTTP_BAD_REQUEST) {
                in = conn.getErrorStream();
            } else {
                in = conn.getInputStream();
            }

            StringWriter writer = new StringWriter();
            IOUtils.copy(in, writer, "UTF-8");
            String result = writer.toString();

            if (result != "") {
                errorMessage = createDesignDocument(docType);
                if (errorMessage != "") {
                    return errorMessage;
                } else {
                    errorMessage = "";
                }
            } else {
                errorMessage = "Failed to parse API response";
                return errorMessage;
            }

            in.close();
            conn.disconnect();

        } catch (MalformedURLException e) {
            e.printStackTrace();
            errorMessage = e.getLocalizedMessage();
        } catch (ProtocolException e) {
            errorMessage = e.getLocalizedMessage();
            e.printStackTrace();
        } catch (IOException e) {
            errorMessage = e.getLocalizedMessage();
            e.printStackTrace();
        }
    }

    return errorMessage;
}

From source file:org.betaconceptframework.astroboa.resourceapi.resource.SecurityResource.java

private Response encryptInternal(String requestContent, Output output, String callback) {

    try {//from w w w.ja v  a2 s .c o  m

        if (StringUtils.isBlank(requestContent)) {
            throw new WebApplicationException(HttpURLConnection.HTTP_BAD_REQUEST);
        }

        checkUserIsAuthorizedToUseEncryptionUtility();

        Map<String, Object> userData = ContentApiUtils.parse(requestContent);

        String propertyPath = (String) userData.get("fullPropertyPath");

        if (StringUtils.isBlank(propertyPath)) {
            logger.error(
                    "No property path found. Request {} does not contain field {} or its value is blank. User info {}",
                    new Object[] { requestContent, "fullPropertyPath", astroboaClient.getInfo() });

            throw new WebApplicationException(HttpURLConnection.HTTP_BAD_REQUEST);
        }

        String password = (String) userData.get("password");

        if (StringUtils.isBlank(password)) {
            logger.error(
                    "No value for password found. Request {} does not contain field {} or its value is blank. User info {}",
                    new Object[] { requestContent, "password", astroboaClient.getInfo() });

            throw new WebApplicationException(HttpURLConnection.HTTP_BAD_REQUEST);
        }

        DefinitionService definitionService = astroboaClient.getDefinitionService();

        CmsDefinition definition = definitionService.getCmsDefinition(propertyPath,
                ResourceRepresentationType.DEFINITION_INSTANCE, false);

        if (definition == null) {
            logger.error("No definition found for property {}. Request {} - User info {}",
                    new Object[] { propertyPath, requestContent, astroboaClient.getInfo() });

            throw new WebApplicationException(HttpURLConnection.HTTP_BAD_REQUEST);
        }

        if (!(definition instanceof StringPropertyDefinition)
                || !((StringPropertyDefinition) definition).isPasswordType()) {
            logger.error("Property {}'s type  is not password type. Request {} - User info {}",
                    new Object[] { propertyPath, requestContent, astroboaClient.getInfo() });

            throw new WebApplicationException(HttpURLConnection.HTTP_BAD_REQUEST);
        }

        String encryptedPassword = StringEscapeUtils
                .escapeJava(((StringPropertyDefinition) definition).getPasswordEncryptor().encrypt(password));

        StringBuilder encryptedPasswordBuidler = new StringBuilder();

        switch (output) {
        case XML: {

            encryptedPassword = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><encryptedPassword>"
                    + encryptedPassword + "</encryptedPassword>";

            if (StringUtils.isBlank(callback)) {
                encryptedPasswordBuidler.append(encryptedPassword);
            } else {
                ContentApiUtils.generateXMLP(encryptedPasswordBuidler, encryptedPassword, callback);
            }
            break;
        }
        case JSON:

            encryptedPassword = "{\"encryptedPassword\" : \"" + encryptedPassword + "\"}";
            if (StringUtils.isBlank(callback)) {
                encryptedPasswordBuidler.append(encryptedPassword);
            } else {
                ContentApiUtils.generateJSONP(encryptedPasswordBuidler, encryptedPassword, callback);
            }
            break;
        }

        return ContentApiUtils.createResponse(encryptedPasswordBuidler, output, callback, null);

    } catch (WebApplicationException wae) {
        throw wae;
    } catch (Exception e) {
        logger.error(
                "Encrytpion failed. Request " + requestContent + " - User info " + astroboaClient.getInfo(), e);
        throw new WebApplicationException(HttpURLConnection.HTTP_INTERNAL_ERROR);
    }
}

From source file:com.hotmart.dragonfly.profile.ui.ResetPasswordActivity.java

@OnClick(R.id.redefinirSalvar)
public void salvarNovaSenha(View view) {

    ResetPasswordRequestVO resetPasswordRequestVO = new ResetPasswordRequestVO();
    final String code = codeEditText.getText().toString();
    resetPasswordRequestVO.setPassword(passwordEditText.getText().toString());
    resetPasswordRequestVO.setRepeatPassword(repeatPasswordEditText.getText().toString());

    mUserService.resetPassword(resetPasswordRequestVO, code).enqueue(new Callback<Void>() {
        @Override//w  w  w .  j a v a  2 s .c  o m
        public void onResponse(Call<Void> call, Response<Void> response) {
            switch (response.code()) {
            case HttpURLConnection.HTTP_OK:

                Intent intent = new Intent();
                setResult(RESULT_OK, intent);

                Intent homeIntent = new Intent(thisActivity, AuthenticatorActivity.class);
                thisActivity.startActivity(homeIntent);

                finish();
                break;
            case HttpURLConnection.HTTP_BAD_REQUEST:
                Snackbar.make(codeEditText, response.message(), Snackbar.LENGTH_LONG).show();
            case HttpURLConnection.HTTP_NOT_FOUND:
                Snackbar.make(codeEditText, response.message(), Snackbar.LENGTH_LONG).show();
            default:
                Snackbar.make(codeEditText, response.message(), Snackbar.LENGTH_LONG).show();
            }
        }

        @Override
        public void onFailure(Call<Void> call, Throwable t) {
            Snackbar.make(codeEditText, R.string.status_500, Snackbar.LENGTH_LONG).show();
            Log.e("dragonfly", t.getMessage(), t);
        }
    });

}

From source file:rapture.blob.mongodb.MongoDBBlobStore.java

@Override
public void setConfig(Map<String, String> config) {
    String bucket;// www.  ja v  a2 s.  c  o m
    if (config.containsKey(PRIMARY_CONFIG)) {
        bucket = config.get(PRIMARY_CONFIG);
    } else if (config.containsKey(SECONDARY_CONFIG)) {
        bucket = config.get(SECONDARY_CONFIG);
    } else {
        bucket = null;
    }
    if (StringUtils.isEmpty(bucket)) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST,
                mongoMsgCatalog.getMessage("PrefixOrGrid"));
    }

    if (Boolean.valueOf(config.get(MULTIPART))) {
        blobHandler = new DocHandler(INSTANCE_NAME, bucket);
    } else {
        blobHandler = new GridFSBlobHandler(INSTANCE_NAME, bucket);
    }
}

From source file:org.eclipse.orion.server.tests.servlets.git.GitPushTest.java

@Test
public void testPushNoBody() throws Exception {
    // clone a repo
    URI workspaceLocation = createWorkspace(getMethodName());
    String workspaceId = workspaceIdFromLocation(workspaceLocation);
    JSONObject project = createProjectOrLink(workspaceLocation, getMethodName(), null);
    IPath clonePath = getClonePath(workspaceId, project);
    clone(clonePath);/*from  w w w. j a  v a  2  s. com*/

    // get project metadata
    WebRequest request = getGetRequest(project.getString(ProtocolConstants.KEY_CONTENT_LOCATION));
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    project = new JSONObject(response.getText());

    JSONObject gitSection = project.getJSONObject(GitConstants.KEY_GIT);
    String gitRemoteUri = gitSection.getString(GitConstants.KEY_REMOTE);

    // get remote branch location
    JSONObject remoteBranch = getRemoteBranch(gitRemoteUri, 1, 0, Constants.MASTER);
    String remoteBranchLocation = remoteBranch.getString(ProtocolConstants.KEY_LOCATION);

    // push with no body
    request = getPostGitRemoteRequest(remoteBranchLocation, null, false, false);
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, response.getResponseCode());
}

From source file:rapture.kernel.UserApiImpl.java

@Override
public RaptureUser changeMyEmail(CallingContext context, String newAddress) {
    RaptureUser usr = Kernel.getAdmin().getTrusted().getUser(context, context.getUser());
    if (usr != null) {
        usr.setEmailAddress(newAddress);
        RaptureUserStorage.add(usr, context.getUser(), "Updated my email");
        return usr;
    } else {/* w ww . j a  v a  2 s  . com*/
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST, "Could not find this user");
    }
}

From source file:rapture.repo.google.IdGenGoogleDatastore.java

@Override
public Long getNextIdGen(Long interval) {
    if (!isValid())
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST,
                googleMsgCatalog.getMessage("GeneratorInvalid"));

    Key entityKey = datastore.newKeyFactory().setKind(kind).newKey(kind);
    Entity entity = datastore.get(entityKey);
    Long next = interval;//from  w w w  .java2s. co m

    if (entity != null) {
        Set<String> names = entity.getNames();
        if ((names == null) || (names.size() != 1))
            throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST,
                    googleMsgCatalog.getMessage("IdGenerator"));

        Value<?> value = entity.getValue(names.iterator().next());
        if (!(value instanceof LongValue))
            throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST,
                    googleMsgCatalog.getMessage("IdGenerator"));
        next = ((LongValue) value).get() + interval;
    }
    try {
        Entity.Builder builder = Entity.newBuilder(entityKey);
        builder.set(kind, new LongValue(next));
        entity = builder.build();
        datastore.put(entity);
    } catch (Exception e) {
        throw new RuntimeException("Cannot initialise idgen ", e);
    }
    return next;
}

From source file:org.eclipse.hono.service.tenant.TenantHttpEndpoint.java

/**
 * Check if the payload (that was put to the RoutingContext ctx with the
 * key {@link #KEY_REQUEST_BODY}) contains a value for the key {@link TenantConstants#FIELD_PAYLOAD_TENANT_ID} that is not null.
 *
 * @param ctx The routing context to retrieve the JSON request body from.
 *//*from  w  ww.j  av  a2s.  c o m*/
protected void checkPayloadForTenantId(final RoutingContext ctx) {

    final JsonObject payload = ctx.get(KEY_REQUEST_BODY);

    final Object tenantId = payload.getValue(TenantConstants.FIELD_PAYLOAD_TENANT_ID);

    if (tenantId == null) {
        ctx.response().setStatusMessage(
                String.format("'%s' param is required", TenantConstants.FIELD_PAYLOAD_TENANT_ID));
        ctx.fail(HttpURLConnection.HTTP_BAD_REQUEST);
    } else if (!(tenantId instanceof String)) {
        ctx.response().setStatusMessage(
                String.format("'%s' must be a string", TenantConstants.FIELD_PAYLOAD_TENANT_ID));
        ctx.fail(HttpURLConnection.HTTP_BAD_REQUEST);
    }
    ctx.next();
}

From source file:eu.codeplumbers.cosi.api.tasks.DeleteFileTask.java

@Override
protected String doInBackground(File... files) {
    for (int i = 0; i < files.length; i++) {
        File file = files[i];/*  w ww .j  a v  a 2 s . c om*/
        String binaryRemoteId = file.getRemoteId();

        if (!binaryRemoteId.isEmpty()) {
            publishProgress("Deleting file: " + file.getName(), "0", "100");
            URL urlO = null;
            try {
                urlO = new URL(url + binaryRemoteId + "/binaries/file");
                HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
                conn.setConnectTimeout(5000);
                conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
                conn.setRequestProperty("Authorization", authHeader);
                conn.setDoInput(true);
                conn.setRequestMethod("DELETE");
                InputStream in = null;

                // read the response
                int status = conn.getResponseCode();

                if (status >= HttpURLConnection.HTTP_BAD_REQUEST) {
                    in = conn.getErrorStream();
                } else {
                    in = conn.getInputStream();
                }

                StringWriter writer = new StringWriter();
                IOUtils.copy(in, writer, "UTF-8");
                String result = writer.toString();

                if (status >= HttpURLConnection.HTTP_BAD_REQUEST) {
                    errorMessage = conn.getResponseMessage();
                } else {
                    errorMessage = deleteFileRequest(file);

                    if (errorMessage == "") {
                        java.io.File newFile = file.getLocalPath();

                        if (newFile.exists()) {
                            newFile.delete();
                        }
                        file.delete();
                    } else {
                        return errorMessage;
                    }

                }
            } catch (MalformedURLException e) {
                errorMessage = e.getLocalizedMessage();
            } catch (ProtocolException e) {
                errorMessage = e.getLocalizedMessage();
            } catch (IOException e) {
                errorMessage = e.getLocalizedMessage();
            }
        }
    }

    return errorMessage;
}