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:org.eclipse.orion.server.tests.servlets.git.GitCheckoutTest.java

@Test
public void testCheckoutPathInUri() 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. java2 s.c  o  m

    // 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 testTxt = getChild(project, "test.txt");
    modifyFile(testTxt, "change");

    JSONObject gitSection = project.getJSONObject(GitConstants.KEY_GIT);
    String gitStatusUri = gitSection.getString(GitConstants.KEY_STATUS);
    String gitCloneUri = getCloneUri(gitStatusUri);

    // TODO: don't create URIs out of thin air
    request = getCheckoutRequest(gitCloneUri + "test.txt", new String[] {});
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, response.getResponseCode());
}

From source file:rapture.kernel.StructuredApiImpl.java

@Override
public List<String> getTables(CallingContext context, String repoURI) {
    RaptureURI uri = new RaptureURI(repoURI, Scheme.STRUCTURED);
    if (uri.hasDocPath()) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST,
                apiMessageCatalog.getMessage("NoDocPath", repoURI)); //$NON-NLS-1$
    }//from w  w  w . j a v a 2  s .c o  m
    return getRepoOrFail(uri.getAuthority()).getTables();
}

From source file:com.jaspersoft.jasperserver.api.engine.jasperreports.util.AwsEc2MetadataClient.java

private String readResource(String resourcePath) {
    HttpURLConnection connection = null;
    URL url = null;// www .  java  2 s  .c o  m
    try {
        url = getEc2MetadataServiceUrlForResource(resourcePath);
        log.debug("Connecting to EC2 instance metadata service at URL: " + url.toString());
        connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(SECOND * 2);
        connection.setReadTimeout(SECOND * 7);
        connection.setRequestMethod("GET");
        connection.setDoOutput(true);
        connection.connect();

        if (connection.getResponseCode() >= HttpURLConnection.HTTP_OK
                && connection.getResponseCode() < HttpURLConnection.HTTP_BAD_REQUEST) {
            return readResponse(connection);
        } else {
            return null;
        }
    } catch (Exception e) {
        return null;
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

From source file:org.eclipse.orion.server.tests.servlets.users.BasicUsersTest.java

@Test
public void testCreateDuplicateUser() throws IOException, SAXException, JSONException {
    WebConversation webConversation = new WebConversation();
    webConversation.setExceptionsThrownOnErrorStatus(false);

    // create user
    Map<String, String> params = new HashMap<String, String>();
    params.put("login", "testDupUser");
    params.put("Name", "username_testCreateDuplicateUser");

    params.put("password", "pass_" + System.currentTimeMillis());
    WebRequest request = getPostUsersRequest("", params, true);
    WebResponse response = webConversation.getResponse(request);
    assertEquals(response.getText(), HttpURLConnection.HTTP_OK, response.getResponseCode());

    //try creating same user again
    response = webConversation.getResponse(request);
    assertEquals(response.getText(), HttpURLConnection.HTTP_BAD_REQUEST, response.getResponseCode());
}

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

private Response saveTopicByIdOrName(String topicNameOrId, String requestContent, String httpMethod) {

    //Import from xml or json. Topic will not be saved
    ImportConfiguration configuration = ImportConfiguration.topic().persist(PersistMode.DO_NOT_PERSIST).build();

    Topic topicToBeSaved = astroboaClient.getImportService().importTopic(requestContent, configuration);

    Topic existingTopic = astroboaClient.getTopicService().getTopic(topicNameOrId,
            ResourceRepresentationType.TOPIC_INSTANCE, FetchLevel.ENTITY, false);

    boolean entityIsNew = existingTopic == null;

    if (CmsConstants.UUIDPattern.matcher(topicNameOrId).matches()) {
        //Save topic by Id
        if (topicToBeSaved.getId() == null) {
            topicToBeSaved.setId(topicNameOrId);
        } else {//from   w w  w  .  j a va2s .co  m
            //Payload contains id. Check if they are the same
            if (!StringUtils.equals(topicNameOrId, topicToBeSaved.getId())) {
                logger.warn("Try to " + httpMethod + " topic with ID " + topicNameOrId
                        + " but payload contains id " + topicToBeSaved.getId());
                throw new WebApplicationException(HttpURLConnection.HTTP_BAD_REQUEST);
            }
        }
    } else {
        //Save content object by SystemName

        //Check that payload contains id
        if (topicToBeSaved.getId() == null) {
            if (existingTopic != null) {
                //A topic with name 'topicIdOrName' exists, but in payload no id was provided
                //Set this id to Topic representing the payload
                topicToBeSaved.setId(existingTopic.getId());
            }
        } else {

            //Payload contains an id. 
            if (existingTopic != null) {
                //if this is not the same with the id returned from repository raise an exception
                if (!StringUtils.equals(existingTopic.getId(), topicToBeSaved.getId())) {
                    logger.warn("Try to " + httpMethod + " topic with name " + topicNameOrId
                            + " which corresponds to an existed topic in repository with id "
                            + existingTopic.getId() + " but payload contains a different id "
                            + topicToBeSaved.getId());
                    throw new WebApplicationException(HttpURLConnection.HTTP_BAD_REQUEST);
                }
            }
        }
    }

    //Save content object
    return saveTopic(topicToBeSaved, httpMethod, requestContent, entityIsNew);
}

From source file:i5.las2peer.services.gamificationApplicationService.GamificationApplicationService.java

/**
 * Create a new app//from  w w  w.j  a va2 s  .co m
 * 
 * @param contentType form content type
 * @param formData form data
 * @return Application data in JSON
 */
@POST
@Path("/data")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(value = "createApplication", notes = "Method to create a new application")
@ApiResponses(value = {
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Cannot connect to database"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Database Error"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Error in parsing form data"),
        @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "App ID already exist"),
        @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "App ID cannot be empty"),
        @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "Error checking app ID exist"),
        @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"),
        @ApiResponse(code = HttpURLConnection.HTTP_CREATED, message = "New application created") })
public HttpResponse createApplication(
        @ApiParam(value = "Application detail in multiple/form-data type", required = true) @HeaderParam(value = HttpHeaders.CONTENT_TYPE) String contentType,
        @ApiParam(value = "Content of form data", required = true) @ContentParam byte[] formData) {

    // Request log
    L2pLogger.logEvent(this, Event.SERVICE_CUSTOM_MESSAGE_99, "POST " + "gamification/applications/data");
    long randomLong = new Random().nextLong(); //To be able to match 

    JSONObject objResponse = new JSONObject();
    UserAgent userAgent = (UserAgent) getContext().getMainAgent();
    String name = userAgent.getLoginName();
    String appid = null;
    String appdesc = null;
    String commtype = null;
    Connection conn = null;

    if (name.equals("anonymous")) {
        return unauthorizedMessage();
    }

    Map<String, FormDataPart> parts;
    try {
        conn = dbm.getConnection();

        parts = MultipartHelper.getParts(formData, contentType);
        FormDataPart partAppID = parts.get("appid");
        if (partAppID != null) {
            // these data belong to the (optional) file id text input form element
            appid = partAppID.getContent();
            // appid must be unique
            System.out.println(appid);
            if (applicationAccess.isAppIdExist(conn, appid)) {
                // app id already exist
                objResponse.put("message", "App ID already exist");
                L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
                return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);
            }

            FormDataPart partAppDesc = parts.get("appdesc");
            if (partAppDesc != null) {
                appdesc = partAppDesc.getContent();
            } else {
                appdesc = "";
            }
            FormDataPart partCommType = parts.get("commtype");
            if (partAppDesc != null) {
                commtype = partCommType.getContent();
            } else {
                commtype = "def_type";
            }

            ApplicationModel newApp = new ApplicationModel(appid, appdesc, commtype);

            try {
                L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_1, "" + randomLong);
                applicationAccess.addNewApplication(conn, newApp);
                applicationAccess.addMemberToApp(conn, newApp.getId(), name);
                L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_2, "" + randomLong);
                L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_3, "" + name);
                L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_4, "" + newApp.getId());

                objResponse.put("message", "New application created");
                return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_CREATED);

            } catch (SQLException e) {
                e.printStackTrace();
                objResponse.put("message", "Cannot Add New Application. Database Error. " + e.getMessage());
                L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
                return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
            }
        } else {
            // app id cannot be empty
            objResponse.put("message", "Cannot Add New Application. App ID cannot be empty.");
            L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
            return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);
        }
    } catch (IOException e) {
        e.printStackTrace();
        objResponse.put("message", "Cannot Add New Application. Error in parsing form data. " + e.getMessage());
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
    } catch (SQLException e) {
        e.printStackTrace();
        objResponse.put("message",
                "Cannot Add New Application. Error checking app ID exist. " + e.getMessage());
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);
    }
    // always close connections
    finally {
        try {
            conn.close();
        } catch (SQLException e) {
            logger.printStackTrace(e);
        }
    }
}

From source file:rapture.kernel.DecisionApiImpl.java

@Override
public void addTransition(CallingContext context, String workflowURI, String stepName, Transition transition) {
    Workflow workflow = getWorkflowNotNull(context, workflowURI);
    Step step = getStep(workflow, stepName);
    if (step != null) {
        step.getTransitions().add(transition);
    } else {/*from ww  w  .jav a 2  s .  c  o  m*/
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST,
                String.format("Attempting to add a transition from non-existent step: '%s'", stepName));
    }

    WorkflowStorage.add(new RaptureURI(workflow.getWorkflowURI(), Scheme.WORKFLOW), workflow, context.getUser(),
            "Add transition");
}

From source file:org.opendaylight.plugin2oc.neutron.SubnetHandler.java

/**
 * Invoked when a subnet update is requested to indicate if the specified
 * subnet can be changed using the specified delta.
 *
 * @param delta//w  ww  .  ja  v a 2s  . co  m
 *            Updates to the subnet object using patch semantics.
 * @param original
 *            An instance of the Neutron Subnet object to be updated.
 * @return A HTTP status code to the update request.
 */
@Override
public int canUpdateSubnet(NeutronSubnet deltaSubnet, NeutronSubnet subnet) {
    if (deltaSubnet == null || subnet == null) {
        LOGGER.error("Neutron Subnets can't be null..");
        return HttpURLConnection.HTTP_BAD_REQUEST;
    }
    // if (deltaSubnet.getGatewayIP() == null ||
    // ("").equals(deltaSubnet.getGatewayIP().toString())) {
    // LOGGER.error("Gateway IP can't be empty/null`..");
    // return HttpURLConnection.HTTP_BAD_REQUEST;
    // }
    // boolean isvalidGateway = validGatewayIP(subnet,
    // deltaSubnet.getGatewayIP());
    // if (!isvalidGateway) {
    // LOGGER.error("Incorrect gateway IP....");
    // return HttpURLConnection.HTTP_BAD_REQUEST;
    // }
    apiConnector = Activator.apiConnector;
    try {
        boolean ifSubnetExist = false;
        VirtualNetwork virtualnetwork = (VirtualNetwork) apiConnector.findById(VirtualNetwork.class,
                subnet.getNetworkUUID());
        List<ObjectReference<VnSubnetsType>> ipamRefs = virtualnetwork.getNetworkIpam();
        if (ipamRefs != null) {
            for (ObjectReference<VnSubnetsType> ref : ipamRefs) {
                VnSubnetsType vnSubnetsType = ref.getAttr();
                if (vnSubnetsType != null) {
                    List<VnSubnetsType.IpamSubnetType> subnets = vnSubnetsType.getIpamSubnets();
                    for (VnSubnetsType.IpamSubnetType subnetValue : subnets) {
                        boolean doesSubnetExist = subnetValue.getSubnetUuid().matches(subnet.getSubnetUUID());
                        if (doesSubnetExist) {
                            // subnetValue.setDefaultGateway(deltaSubnet.getGatewayIP());
                            ifSubnetExist = true;
                        }
                    }
                }
            }
        }
        if (ifSubnetExist) {
            originalSubnet = subnet;
            return HttpURLConnection.HTTP_OK;
        } else {
            LOGGER.warn("Subnet upadtion failed..");
            return HttpURLConnection.HTTP_INTERNAL_ERROR;
        }
    } catch (IOException e) {
        e.printStackTrace();
        LOGGER.error("Exception :     " + e);
        return HttpURLConnection.HTTP_INTERNAL_ERROR;
    }
}

From source file:rapture.series.file.FileSeriesStore.java

@Override
public void addStructureToSeries(String key, String column, String jsonValue) {
    try {//  w ww.j ava 2 s.c o m
        addPointToSeries(key, StructureSeriesValueImpl.unmarshal(jsonValue, column));
    } catch (IOException e) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST,
                "Error parsing json value " + jsonValue, e);
    }
}

From source file:eu.codeplumbers.cosi.services.CosiFileService.java

private void getAllRemoteFolders() {
    //File.deleteAllFolders();

    URL urlO = null;//from ww w  .ja v a2 s  . c o m
    try {
        urlO = new URL(folderUrl);
        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();

        JSONArray jsonArray = new JSONArray(result);

        if (jsonArray != null) {
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject folderJson = jsonArray.getJSONObject(i).getJSONObject("value");
                File file = File.getByRemoteId(folderJson.get("_id").toString());

                if (file == null) {
                    file = new File(folderJson, true);
                } else {
                    file.setName(folderJson.getString("name"));
                    file.setPath(folderJson.getString("path"));
                    file.setCreationDate(folderJson.getString("creationDate"));
                    file.setLastModification(folderJson.getString("lastModification"));
                    file.setTags(folderJson.getString("tags"));
                }

                mBuilder.setProgress(jsonArray.length(), i, false);
                mBuilder.setContentText("Indexing remote folder : " + file.getName());
                mNotifyManager.notify(notification_id, mBuilder.build());

                EventBus.getDefault()
                        .post(new FileSyncEvent(SYNC_MESSAGE, "Indexing remote folder : " + file.getName()));

                file.save();
                createFolder(file.getPath(), file.getName());

                allFiles.add(file);
            }
        } else {
            EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, "Failed to parse API response"));
            stopSelf();
        }

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

    } catch (MalformedURLException e) {
        e.printStackTrace();
        EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (ProtocolException e) {
        e.printStackTrace();
        EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (IOException e) {
        e.printStackTrace();
        EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (JSONException e) {
        e.printStackTrace();
        EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    }
}