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:rapture.kernel.ScriptApiImpl.java

@SuppressWarnings("unchecked")
private <T> T runScriptStrategy(CallingContext context, final String scriptURI, Map<String, String> params,
        T retVal) {//from  w ww  .  jav  a2s .c  o m

    RaptureScript script = getScript(context, scriptURI);
    if (script == null) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST,
                String.format("Script %s does not exists in repository", scriptURI));
    }
    final RaptureURI internalURI = new RaptureURI(scriptURI, Scheme.SCRIPT);
    Kernel.getStackContainer().pushStack(context, internalURI.toString());

    IRaptureScript scriptContext = ScriptFactory.getScript(script);
    Map<String, Object> extraVals = new HashMap<String, Object>();
    if (params != null) {
        for (Map.Entry<String, String> entry : params.entrySet()) {
            extraVals.put(entry.getKey(), entry.getValue());
        }
    }
    Kernel.writeComment(String.format(Messages.getString("Script.running"), scriptURI)); //$NON-NLS-1$
    final String activityId = Kernel.getActivity().createActivity(ContextFactory.getKernelUser(),
            internalURI.toString(), "Running script", 1L, 100L);

    IActivityInfo activityInfo = new IActivityInfo() {
        @Override
        public String getActivityId() {
            return activityId;
        }

        @Override
        public String getOtherId() {
            return internalURI.toString();
        }
    };

    if (retVal instanceof String) {
        retVal = (T) scriptContext.runProgram(context, activityInfo, script, extraVals);
    } else if (retVal instanceof ScriptResult) {
        retVal = (T) scriptContext.runProgramExtended(context, activityInfo, script, extraVals);
    }

    Kernel.getActivity().finishActivity(ContextFactory.getKernelUser(), activityId, "Ran script");
    Kernel.getKernel().getStat().registerRunScript();
    Kernel.getStackContainer().popStack(context);

    return retVal;
}

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

@Override
public void addStructuresToSeries(String key, List<String> columns, List<String> jsonValues) {
    try {//w w  w .j a  v  a 2  s.com
        addPointsToSeries(key, StructureSeriesValueImpl.zip(columns, jsonValues));
    } catch (IOException e) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST, "Error parsing json values",
                e);
    }
}

From source file:i5.las2peer.services.gamificationGamifierService.GamificationGamifierService.java

@POST
@Path("/repo")
@Produces(MediaType.APPLICATION_JSON)//from ww w. j a  v a 2s . c  om
@ApiOperation(value = "memberLoginValidation", notes = "Simple function to validate a member login.")
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_OK, message = "Member is registered"),
        @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "Unauthorized"),
        @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "User data error to be retrieved"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Cannot connect to database"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "User data error to be retrieved. Not JSON object") })
public HttpResponse updateRepository(
        @ApiParam(value = "Data in JSON", required = true) @ContentParam byte[] contentB) {
    // Request log
    L2pLogger.logEvent(this, Event.SERVICE_CUSTOM_MESSAGE_99, "POST " + "gamification/gamifier/repo");
    long randomLong = new Random().nextLong(); //To be able to match
    UserAgent userAgent = (UserAgent) getContext().getMainAgent();
    // take username as default name
    String name = userAgent.getLoginName();
    System.out.println("User name : " + name);
    if (name.equals("anonymous")) {
        return unauthorizedMessage();
    }

    L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_9, "" + randomLong);

    JSONObject objResponse = new JSONObject();
    String content = new String(contentB);
    if (content.equals(null)) {
        objResponse.put("message", "Cannot update repository. Cannot parse json data into string");
        //L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        L2pLogger.logEvent(this, Event.AGENT_UPLOAD_FAILED, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
    }

    //      if(!initializeDBConnection()){
    //         objResponse.put("message", "Cannot connect to database");
    //         L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
    //         return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
    //      }

    JSONObject obj;
    String originRepositoryName;
    String newRepositoryName;
    String fileContent;
    String appId;
    String epURL;
    String aopScript;

    try {
        obj = (JSONObject) JSONValue.parseWithException(content);
        originRepositoryName = stringfromJSON(obj, "originRepositoryName");
        newRepositoryName = stringfromJSON(obj, "newRepositoryName");
        //fileContent = stringfromJSON(obj,"fileContent");
        appId = stringfromJSON(obj, "appId");
        epURL = stringfromJSON(obj, "epURL");
        aopScript = stringfromJSON(obj, "aopScript");
    } catch (ParseException e) {
        e.printStackTrace();
        objResponse.put("message",
                "Cannot update repository. Cannot parse json data into string. " + e.getMessage());
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
    } catch (IOException e) {
        e.printStackTrace();
        objResponse.put("message",
                "Cannot update repository. Cannot parse json data into string. " + e.getMessage());
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
    }
    // check if repo exist
    TreeWalk treeWalk = null;
    Repository newRepository = null;
    Repository originRepository = null;

    // helper variables
    // variables holding content to be modified and added to repository later
    String widget = null;
    try {
        RepositoryHelper.deleteRemoteRepository(newRepositoryName, gitHubOrganizationNewRepo, gitHubUserNewRepo,
                gitHubPasswordNewRepo);
    } catch (GitHubException e) {
        //e.printStackTrace();      
    }

    try {

        PersonIdent caeUser = new PersonIdent(gitHubUserNewRepo, gitHubUserMailNewRepo);

        originRepository = RepositoryHelper.getRemoteRepository(originRepositoryName, gitHubOrganizationOrigin);
        newRepository = RepositoryHelper.generateNewRepository(newRepositoryName, gitHubOrganizationNewRepo,
                gitHubUserNewRepo, gitHubPasswordNewRepo);
        File originDir = originRepository.getDirectory();
        // now load the TreeWalk containing the origin repository content
        treeWalk = RepositoryHelper.getRepositoryContent(originRepositoryName, gitHubOrganizationOrigin);

        //System.out.println("PATH " + treeWalk.getPathString());
        System.out.println("PATH2 " + originDir.getParent());
        System.out.println("PATH3 " + newRepository.getDirectory().getParent());
        // treeWalk.setFilter(PathFilter.create("frontend/"));
        ObjectReader reader = treeWalk.getObjectReader();
        // walk through the tree and retrieve the needed templates
        while (treeWalk.next()) {
            ObjectId objectId = treeWalk.getObjectId(0);
            ObjectLoader loader = reader.open(objectId);
            switch (treeWalk.getNameString()) {
            case "widget.xml":
                widget = new String(loader.getBytes(), "UTF-8");
                break;
            }
        }

        // replace widget.xml 
        //widget = createWidgetCode(widget, htmlElementTemplate, yjsImports, gitHubOrganization, repositoryName, frontendComponent);
        widget = RepositoryHelper.appendWidget(widget, gitHubOrganizationNewRepo, newRepositoryName);

        RepositoryHelper.copyFolder(originRepository.getDirectory().getParentFile(),
                newRepository.getDirectory().getParentFile());

        String aopfilestring = RepositoryHelper.readFile("../GamificationGamifierService/jsfiles/aop.pack.js",
                Charset.forName("UTF-8"));
        String oidcwidgetfilestring = RepositoryHelper
                .readFile("../GamificationGamifierService/jsfiles/oidc-widget.js", Charset.forName("UTF-8"));
        String gamifierstring = RepositoryHelper.readFile("../GamificationGamifierService/jsfiles/gamifier.js",
                Charset.forName("UTF-8"));

        gamifierstring = gamifierstring.replace("$Application_Id$", appId);
        gamifierstring = gamifierstring.replace("$Endpoint_URL$", epURL);
        gamifierstring = gamifierstring.replace("$AOP_Script$", aopScript);

        // add files to new repository
        newRepository = RepositoryHelper.createTextFileInRepository(newRepository, "", "widget.xml", widget);
        newRepository = RepositoryHelper.createTextFileInRepository(newRepository, "gamification/",
                "aop.pack.js", aopfilestring);
        newRepository = RepositoryHelper.createTextFileInRepository(newRepository, "gamification/",
                "oidc-widget.js", oidcwidgetfilestring);
        newRepository = RepositoryHelper.createTextFileInRepository(newRepository, "gamification/",
                "gamifier.js", gamifierstring);

        // stage file
        Git.wrap(newRepository).add().addFilepattern(".").call();

        // commit files
        Git.wrap(newRepository).commit().setMessage("Generated new repo  ").setCommitter(caeUser).call();

        // push (local) repository content to GitHub repository "gh-pages" branch
        RepositoryHelper.pushToRemoteRepository(newRepository, gitHubUserNewRepo, gitHubPasswordNewRepo,
                "master", "gh-pages");

        // close all open resources
    } catch (GitHubException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
        objResponse.put("message", "Cannot update repository. Github exception. " + e1.getMessage());
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
    } catch (IOException e1) {
        e1.printStackTrace();
        objResponse.put("message", "Cannot update repository. Github exception. " + e1.getMessage());
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
    } catch (Exception e) {
        objResponse.put("message", "Cannot update repository. Github exception. " + e.getMessage());
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
    } finally {
        newRepository.close();
        originRepository.close();
        treeWalk.close();
    }

    objResponse.put("message", "Updated");
    L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_10, "" + randomLong);
    L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_22, "" + appId);
    L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_23, "" + name);

    return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_OK);

}

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

/**
 * Processes a request for a non-standard operation.
 * <p>/*from  w  w  w  .ja v  a  2s  . c  om*/
 * Subclasses should override this method in order to support additional, custom
 * operations that are not defined by Hono's Device Registration API.
 * <p>
 * This default implementation simply returns a future that is failed with a
 * {@link ClientErrorException} with an error code <em>400 Bad Request</em>.
 *
 * @param request The request to process.
 * @return A future indicating the outcome of the service invocation.
 */
protected Future<EventBusMessage> processCustomRegistrationMessage(final EventBusMessage request) {
    log.debug("invalid operation in request message [{}]", request.getOperation());
    return Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST));
}

From source file:rapture.kernel.DocApiImpl.java

@Override
public void deleteDocRepo(CallingContext context, String docRepoUri) {
    RaptureURI internalUri = new RaptureURI(docRepoUri, Scheme.DOCUMENT);
    if (internalUri.hasDocPath()) {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST,
                apiMessageCatalog.getMessage("NoDocPath", docRepoUri)); //$NON-NLS-1$
    }// ww w .j a v a 2  s .  c o  m
    checkParameter(NAME, internalUri.getAuthority());

    // First drop the data, then drop the repo config

    try {
        Repository repository = getRepoFromCache(internalUri.getAuthority());
        log.info(Messages.getString("Admin.DropRepo") + internalUri.getAuthority()); //$NON-NLS-1$
        if (repository != null) {
            repository.drop();
        }
    } catch (IllegalArgumentException e) {
        // Will happen if the config wasn't valid - but we are trying to delete it anyway
    }

    // Remove jobs associated with this authority.
    for (String jobUri : Kernel.getSchedule().getTrusted().getJobs(context)) {
        RaptureURI uri = new RaptureURI(
                Kernel.getSchedule().getTrusted().retrieveJob(context, jobUri).getJobURI());
        if (uri.getAuthority().equals(internalUri.getAuthority())) {
            Kernel.getSchedule().getTrusted().deleteJob(context, jobUri);
        }
    }
    // Yeah this is like "delete everything that is prefixed by //docRepoUri
    SearchPublisher.publishDropMessage(context, internalUri.toString());
    // We can't just delete the repo. If we do then
    // DocRepoCache.reloadConfig will just create it.
    // So mark the config as having been deleted.
    // DocumentRepoConfigStorage.deleteByAddress(internalUri,
    // context.getUser(), "Drop document repo");
    DocumentRepoConfig drc = DocumentRepoConfigStorage.readByAddress(internalUri);
    drc.setDeleted(true);
    DocumentRepoConfigStorage.add(internalUri, drc, context.getUser(), "Mark config as deleted");
    log.info("Config for " + internalUri.toString() + " marked as deleted ");
    removeRepoFromCache(internalUri.getAuthority());

    String idGenUri = getDocRepoIdGenUri(context, docRepoUri);
    if (Kernel.getIdGen().idGenExists(context, idGenUri)) {
        Kernel.getIdGen().deleteIdGen(context, idGenUri);
    }
}

From source file:rapture.kernel.BlobApiImpl.java

private void lowerStoreBlob(CallingContext context, String blobUri, byte[] content, String contentType,
        boolean append) {
    RaptureURI interimUri = new RaptureURI(blobUri, BLOB);
    Preconditions.checkNotNull(interimUri);
    Map<String, String> newMeta = createMetaData(context);

    if (interimUri.hasAttribute()) {
        logger.debug("interim uri has attribute");
        // This does not work. See RAP-2797
        // Here is the old code:
        // retVal = Kernel.getRepo().getTrusted().putContent(context, interimUri.toString(), content, "Updated Attribute");
        // That was replaced by this:

        putContent(context, interimUri, content, "Updated Attribute");

        // but in testing it gets a UnsupportedOperationException
        // I think we need something more like this:
        // Kernel.getDoc().getTrusted().putContent(context, {document URI based on interimUri} , {something - possibly the attribute} );
    } else {/*  ww w .java2s  .  co  m*/
        BlobRepo blobRepo = getRepoFromCache(interimUri.getAuthority());
        if (blobRepo == null)
            throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST,
                    apiMessageCatalog.getMessage("NoSuchRepo", interimUri.toAuthString())); //$NON-NLS-1$
        // if file store, pass on docPathWithElement
        // since element contains local file path, which could be used to create sym link
        // A cleaner solution should be in place after RAP-3587
        Map<String, String> attributes = getBlobMetaData(context, blobUri);
        if (attributes.isEmpty()) {
            attributes.put(CREATED_TIMESTAMP, newMeta.get(CREATED_TIMESTAMP));
        }
        boolean isStored = blobRepo.storeBlob(context, interimUri, append, new ByteArrayInputStream(content));

        if (isStored) {
            if (contentType != null) {
                attributes.put(ContentEnvelope.CONTENT_TYPE_HEADER, contentType);
            }
            attributes.put(WRITE_TIME, newMeta.get(WRITE_TIME));
            attributes.put(MODIFIED_TIMESTAMP, newMeta.get(MODIFIED_TIMESTAMP));
            attributes.put(USER, newMeta.get(USER));
            attributes.put(ContentEnvelope.CONTENT_SIZE, Integer.toString(content.length));
            putBlobMetaData(context, interimUri.toString(), attributes);
        }
    }
}

From source file:net.mceoin.cominghome.api.NestUtil.java

private static String getNestAwayStatusCall(String access_token) {

    String away_status = "";

    String urlString = "https://developer-api.nest.com/structures?auth=" + access_token;
    log.info("url=" + urlString);

    StringBuilder builder = new StringBuilder();
    boolean error = false;
    String errorResult = "";

    HttpURLConnection urlConnection = null;
    try {//  w ww .j  a  v  a  2 s .c o m
        URL url = new URL(urlString);
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestProperty("User-Agent", "ComingHomeBackend/1.0");
        urlConnection.setRequestMethod("GET");
        urlConnection.setDoOutput(true);
        urlConnection.setDoInput(true);
        urlConnection.setConnectTimeout(15000);
        urlConnection.setReadTimeout(15000);
        //            urlConnection.setChunkedStreamingMode(0);

        //            urlConnection.setRequestProperty("Content-Type", "application/json; charset=utf8");

        boolean redirect = false;

        // normally, 3xx is redirect
        int status = urlConnection.getResponseCode();
        if (status != HttpURLConnection.HTTP_OK) {
            if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM
                    || status == 307 // Temporary redirect
                    || status == HttpURLConnection.HTTP_SEE_OTHER)
                redirect = true;
        }

        //            System.out.println("Response Code ... " + status);

        if (redirect) {

            // get redirect url from "location" header field
            String newUrl = urlConnection.getHeaderField("Location");

            // open the new connnection again
            urlConnection = (HttpURLConnection) new URL(newUrl).openConnection();
            urlConnection.setRequestMethod("PUT");
            urlConnection.setDoOutput(true);
            urlConnection.setDoInput(true);
            //                urlConnection.setChunkedStreamingMode(0);

            //                System.out.println("Redirect to URL : " + newUrl);

        }

        int statusCode = urlConnection.getResponseCode();

        log.info("statusCode=" + statusCode);
        if ((statusCode == HttpURLConnection.HTTP_OK)) {
            error = false;

            InputStream response;
            response = urlConnection.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(response));
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
            log.info("response=" + builder.toString());
            JSONObject object = new JSONObject(builder.toString());

            Iterator keys = object.keys();
            while (keys.hasNext()) {
                String key = (String) keys.next();
                JSONObject structure = object.getJSONObject(key);

                if (structure.has("away")) {
                    away_status = structure.getString("away");
                } else {
                    log.info("missing away");
                }
            }

        } else if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
            // bad auth
            error = true;
            errorResult = "Unauthorized";
        } else if (statusCode == HttpURLConnection.HTTP_BAD_REQUEST) {
            error = true;
            InputStream response;
            response = urlConnection.getErrorStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(response));
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
            log.info("response=" + builder.toString());
            JSONObject object = new JSONObject(builder.toString());

            Iterator keys = object.keys();
            while (keys.hasNext()) {
                String key = (String) keys.next();
                if (key.equals("error")) {
                    // error = Internal Error on bad structure_id
                    errorResult = object.getString("error");
                    log.info("errorResult=" + errorResult);
                }
            }
        } else {
            error = true;
            errorResult = Integer.toString(statusCode);
        }

    } catch (IOException e) {
        error = true;
        errorResult = e.getLocalizedMessage();
        log.warning("IOException: " + errorResult);
    } catch (Exception e) {
        error = true;
        errorResult = e.getLocalizedMessage();
        log.warning("Exception: " + errorResult);
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }

    if (error)
        away_status = "Error: " + errorResult;
    return away_status;
}

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

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

    // create user
    Map<String, String> params = new HashMap<String, String>();
    params.put("login", "testDupEmail");
    params.put("Name", "username_testCreateUserDuplicateEmail");
    params.put("password", "pass_" + System.currentTimeMillis());
    params.put("email", "username@example.com");
    WebRequest request = getPostUsersRequest("", params, true);
    WebResponse response = webConversation.getResponse(request);
    assertEquals(response.getText(), HttpURLConnection.HTTP_OK, response.getResponseCode());

    //try creating another user with same email address
    params.put("login", "usertestCreateUserDuplicateEmail2");
    request = getPostUsersRequest("", params, true);
    response = webConversation.getResponse(request);
    assertEquals(response.getText(), HttpURLConnection.HTTP_BAD_REQUEST, response.getResponseCode());
}

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

@Override
public void addPointsToSeries(String key, List<SeriesValue> values) {
    boolean nullKey = false;
    for (SeriesValue value : values) {
        if (value.getColumn() == null)
            nullKey = true;/*from   w w  w  .java 2s.  co  m*/
        else
            addPointToSeries(key, value);
    }
    if (nullKey)
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST,
                "Column Key may not be null, other values added");
}

From source file:com.ibm.pi.beacon.PIBeaconSensorService.java

private void sendBeaconNotification(Collection<Beacon> beacons) {
    PILogger.d(TAG, "sending beacon notification message");

    JSONObject payload = buildBeaconPayload(beacons);
    mPiApiAdapter.sendBeaconNotificationMessage(payload, new PIAPICompletionHandler() {
        @Override/*from  w ww . j a v  a2s.c o  m*/
        public void onComplete(PIAPIResult result) {
            if (result.getResponseCode() >= HttpURLConnection.HTTP_BAD_REQUEST) {
                PILogger.e(TAG, result.toString());
            }
        }
    });

    // send beacons in range event to listener callback
    Intent intent = new Intent(PIBeaconSensor.INTENT_RECEIVER_BEACON_COLLECTION);
    intent.putParcelableArrayListExtra(PIBeaconSensor.INTENT_EXTRA_BEACONS_IN_RANGE,
            new ArrayList<Beacon>(beacons));

    LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}