Example usage for java.net HttpURLConnection HTTP_CREATED

List of usage examples for java.net HttpURLConnection HTTP_CREATED

Introduction

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

Prototype

int HTTP_CREATED

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

Click Source Link

Document

HTTP Status-Code 201: Created.

Usage

From source file:com.hotmart.dragonfly.check.ui.CheckListActivity.java

private void saveCheckList(List<Long> ids) {
    VerificationRequestVO request = new VerificationRequestVO(idAddress, ids);
    VerificationService service = ApiServiceFactory.createService(VerificationService.class, this);
    call = service.post(request);//from  w  w w . jav a2 s  . com
    call.enqueue(new Callback<CheckLastVO>() {
        @Override
        public void onResponse(Call<CheckLastVO> call, Response<CheckLastVO> response) {
            if (response.code() == HttpURLConnection.HTTP_CREATED) {
                startActivity(ShareChecklistActivity.createIntent(CheckListActivity.this, data));
                finish();
            } else {
                Snackbar.make(findViewById(R.id.sign_up_next),
                        "Detectamos um erro, tente novamente mais tarde.", Snackbar.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onFailure(Call<CheckLastVO> call, Throwable t) {
            Snackbar.make(findViewById(R.id.sign_up_next), "Detectamos um erro, tente novamente mais tarde.",
                    Snackbar.LENGTH_SHORT).show();
        }
    });
}

From source file:com.contactlab.clabpush_android_sample.RegistrationIntentService.java

@Override
public void onTaskResult(ConnectionTask task, int requestCode, Response response) {

    if (requestCode == REQUEST_REGISTRATION) {

        if (response.responseCode == HttpURLConnection.HTTP_CREATED) {

            // The server returned 201 - Created as response code, we can flag the PREF_TOKENSENT flag in the SharedPreferences as true.

            SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
            preferences.edit().putBoolean(MainActivity.PREF_TOKENSENT, true).apply();

            Intent registrationCompleted = new Intent(MainActivity.MSG_REGISTRATION_COMPLETED);
            LocalBroadcastManager.getInstance(this).sendBroadcast(registrationCompleted);
        }//from w ww .j a  va 2s.  c o  m

    } else if (requestCode == REQUEST_UNREGISTRATION) {

        if (response.responseCode == HttpURLConnection.HTTP_OK) {

            // The server returned 200 - OK, we can set the PREF_TOKENSENT flag as false.

            SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
            preferences.edit().putBoolean(MainActivity.PREF_TOKENSENT, false).apply();

            Intent registrationCompleted = new Intent(MainActivity.MSG_REGISTRATION_COMPLETED);
            LocalBroadcastManager.getInstance(this).sendBroadcast(registrationCompleted);
        }
    }
}

From source file:io.joynr.messaging.bounceproxy.controller.RemoteBounceProxyFacade.java

private URI sendCreateChannelHttpRequest(ControlledBounceProxyInformation bpInfo, String ccid,
        String trackingId) throws IOException, JoynrProtocolException {

    // TODO jsessionid handling
    final String url = bpInfo.getLocationForBpc().toString() + "channels/?ccid=" + ccid;

    logger.debug("Using bounce proxy channel service URL: {}", url);

    HttpPost postCreateChannel = new HttpPost(url.trim());
    postCreateChannel.addHeader(ChannelServiceConstants.X_ATMOSPHERE_TRACKING_ID, trackingId);

    CloseableHttpResponse response = null;
    try {/*  w  w w.  j  ava2 s.  co m*/
        response = httpclient.execute(postCreateChannel);
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();

        if (statusCode == HttpURLConnection.HTTP_CREATED) {
            // the channel was created successfully

            // check if bounce proxy ID header was sent correctly
            if (response.containsHeader("bp")) {
                String bounceProxyId = response.getFirstHeader("bp").getValue();
                if (bounceProxyId == null || !bounceProxyId.equals(bpInfo.getId())) {
                    throw new JoynrProtocolException("Bounce proxy ID '" + bounceProxyId
                            + "' returned by bounce proxy '" + bpInfo.getId() + "' does not match.");
                }
            } else {
                throw new JoynrProtocolException(
                        "No bounce proxy ID returned by bounce proxy '" + bpInfo.getId() + "'");
            }

            // get URI of newly created channel
            if (!response.containsHeader("Location")) {
                throw new JoynrProtocolException(
                        "No channel location returned by bounce proxy '" + bpInfo.getId() + "'");
            }

            String locationValue = response.getFirstHeader("Location").getValue();

            if (locationValue == null || locationValue.isEmpty()) {
                throw new JoynrProtocolException(
                        "Bounce proxy '" + bpInfo.getId() + "' didn't return a channel location.");
            }
            try {
                URI channelLocation = new URI(locationValue);

                logger.info("Successfully created channel '{}' on bounce proxy '{}'", ccid, bpInfo.getId());
                return channelLocation;
            } catch (Exception e) {
                throw new JoynrProtocolException("Cannot parse channel location '" + locationValue
                        + "' returned by bounce proxy '" + bpInfo.getId() + "'", e);
            }
        }

        // the bounce proxy is not excepted to reject this call as it was
        // chosen based on performance measurements sent by it
        logger.error("Failed to create channel on bounce proxy '{}'. Response: {}", bpInfo.getId(), response);
        throw new JoynrProtocolException(
                "Bounce Proxy " + bpInfo.getId() + " rejected channel creation (Response: " + response + ")");

    } finally {
        if (response != null) {
            response.close();
        }
    }
}

From source file:org.eclipse.orion.server.tests.servlets.site.HostingTest.java

@Test
/**//from   w w w . j  a  v a  2 s  .  com
 * Tests accessing a workspace file <del>and remote URL</del> that are part of a running site.
 */
public void testSiteAccess() throws SAXException, IOException, JSONException, URISyntaxException {
    // Create file in workspace
    final String filename = "foo.html";
    final String fileContent = "<html><body>This is a test file</body></html>";
    createFileOnServer("", filename, fileContent);

    // Create a site that exposes the workspace file
    final String siteName = "My hosted site";
    //make absolute by adding test project path
    IPath path = new Path(URI.create(makeResourceURIAbsolute(filename)).getPath());
    while (path.segmentCount() != 0 && !path.segment(0).equals("file")) {
        if (path.segment(0).equals("file")) {
            break;
        }
        path = path.removeFirstSegments(1);
    }
    String filePath = path.toString();
    if (filePath.startsWith("/")) {
        filePath = filePath.substring(1);
    }
    //remove file segment to get the servlet-relative path
    Assert.assertTrue(filePath.startsWith("file/"));
    filePath = filePath.substring(5);
    final String mountAt = "/file.html";

    final JSONArray mappings = makeMappings(new String[][] { { mountAt, filePath } });
    WebRequest createSiteReq = getCreateSiteRequest(siteName, workspaceId, mappings, null);
    WebResponse createSiteResp = webConversation.getResponse(createSiteReq);
    assertEquals(HttpURLConnection.HTTP_CREATED, createSiteResp.getResponseCode());
    JSONObject siteObject = new JSONObject(createSiteResp.getText());

    // Start the site
    String location = siteObject.getString(ProtocolConstants.HEADER_LOCATION);
    siteObject = startSite(location);

    final JSONObject hostingStatus = siteObject.getJSONObject(SiteConfigurationConstants.KEY_HOSTING_STATUS);
    final String hostedURL = hostingStatus.getString(SiteConfigurationConstants.KEY_HOSTING_STATUS_URL);

    // Access the workspace file through the site
    WebRequest getFileReq = new GetMethodWebRequest(hostedURL + mountAt);
    WebResponse getFileResp = webConversation.getResponse(getFileReq);
    assertEquals(fileContent, getFileResp.getText());

    // Stop the site
    stopSite(location);

    // Check that the workspace file can't be accessed anymore
    WebRequest getFile404Req = new GetMethodWebRequest(hostedURL + mountAt);
    WebResponse getFile404Resp = webConversation.getResponse(getFile404Req);
    assertEquals(HttpURLConnection.HTTP_NOT_FOUND, getFile404Resp.getResponseCode());
    assertEquals("no-cache", getFile404Resp.getHeaderField("Cache-Control").toLowerCase());
}

From source file:play.modules.resteasy.crud.RESTResource.java

/**
 * Returns a CREATED response
 */
protected Response created() {
    return status(HttpURLConnection.HTTP_CREATED);
}

From source file:i5.las2peer.services.gamificationAchievementService.GamificationAchievementService.java

/**
 * Post a new achievement/*from  w w  w . ja  va 2  s .  c  om*/
 * @param appId applicationId
 * @param formData form data
 * @param contentType content type
 * @return HttpResponse returned as JSON object
 */
@POST
@Path("/{appId}")
@Produces(MediaType.APPLICATION_JSON)
@ApiResponses(value = {
        @ApiResponse(code = HttpURLConnection.HTTP_CREATED, message = "{\"status\": 3, \"message\": \"Achievement upload success ( (achievementid) )\"}"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "{\"status\": 3, \"message\": \"Failed to upload (achievementid)\"}"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "{\"status\": 1, \"message\": \"Failed to add the achievement. Achievement ID already exist!\"}"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "{\"status\": =, \"message\": \"Achievement ID cannot be null!\"}"),
        @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "{\"status\": 2, \"message\": \"File content null. Failed to upload (achievementid)\"}"),
        @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "{\"status\": 2, \"message\": \"Failed to upload (achievementid)\"}"),
        @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "{\"status\": 3, \"message\": \"Achievement upload success ( (achievementid) )}") })
@ApiOperation(value = "createNewAchievement", notes = "A method to store a new achievement with details (achievement ID, achievement name, achievement description, achievement point value, achievement point id, achievement badge id")
public HttpResponse createNewAchievement(
        @ApiParam(value = "Application ID to store a new achievement", required = true) @PathParam("appId") String appId,
        @ApiParam(value = "Content-type in header", required = true) @HeaderParam(value = HttpHeaders.CONTENT_TYPE) String contentType,
        @ApiParam(value = "Achievement detail in multiple/form-data type", required = true) @ContentParam byte[] formData) {

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

    // parse given multipart form data
    JSONObject objResponse = new JSONObject();
    String achievementid = null;
    String achievementname = null;
    String achievementdesc = null;
    int achievementpointvalue = 0;
    String achievementbadgeid = null;

    boolean achievementnotifcheck = false;
    String achievementnotifmessage = null;
    Connection conn = null;

    UserAgent userAgent = (UserAgent) getContext().getMainAgent();
    String name = userAgent.getLoginName();
    if (name.equals("anonymous")) {
        return unauthorizedMessage();
    }
    try {
        conn = dbm.getConnection();

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

        try {
            if (!achievementAccess.isAppIdExist(conn, appId)) {
                logger.info("App not found >> ");
                objResponse.put("message", "Cannot create achievement. App not found");
                L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));

                return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);
            }
        } catch (SQLException e1) {
            e1.printStackTrace();
            objResponse.put("message",
                    "Cannot create achievement. Cannot check whether application ID exist or not. Database error. "
                            + e1.getMessage());
            L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
            return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
        }
        Map<String, FormDataPart> parts = MultipartHelper.getParts(formData, contentType);
        FormDataPart partAchievementID = parts.get("achievementid");
        if (partAchievementID != null) {
            achievementid = partAchievementID.getContent();

            if (achievementAccess.isAchievementIdExist(conn, appId, achievementid)) {
                // Achievement id already exist
                objResponse.put("message",
                        "Cannot create achievement. Failed to add the achievement. achievement ID already exist!");
                L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
                return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);

            }
            FormDataPart partAchievementName = parts.get("achievementname");
            if (partAchievementName != null) {
                achievementname = partAchievementName.getContent();
            }
            FormDataPart partAchievementDesc = parts.get("achievementdesc");
            if (partAchievementDesc != null) {
                // optional description text input form element
                achievementdesc = partAchievementDesc.getContent();
            }
            FormDataPart partAchievementPV = parts.get("achievementpointvalue");
            if (partAchievementPV != null) {
                // optional description text input form element
                achievementpointvalue = Integer.parseInt(partAchievementPV.getContent());
            }

            FormDataPart partAchievementBID = parts.get("achievementbadgeid");
            System.out.println("BADGE In Ach : " + partAchievementBID);
            System.out.println("BADGE In Ach : " + partAchievementBID.getContent());
            if (partAchievementBID != null) {
                // optional description text input form element
                achievementbadgeid = partAchievementBID.getContent();
            }
            if (achievementbadgeid.equals("")) {
                achievementbadgeid = null;
            }

            FormDataPart partNotificationCheck = parts.get("achievementnotificationcheck");
            if (partNotificationCheck != null) {
                // checkbox is checked
                achievementnotifcheck = true;

            } else {
                achievementnotifcheck = false;
            }

            FormDataPart partNotificationMsg = parts.get("achievementnotificationmessage");
            if (partNotificationMsg != null) {
                achievementnotifmessage = partNotificationMsg.getContent();
            } else {
                achievementnotifmessage = "";
            }
            AchievementModel achievement = new AchievementModel(achievementid, achievementname, achievementdesc,
                    achievementpointvalue, achievementbadgeid, achievementnotifcheck, achievementnotifmessage);

            try {
                achievementAccess.addNewAchievement(conn, appId, achievement);
                objResponse.put("message", "Achievement upload success (" + achievementid + ")");
                L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_15, "" + randomLong);
                L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_24, "" + name);
                L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_25, "" + appId);

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

            } catch (SQLException e) {
                e.printStackTrace();
                objResponse.put("message",
                        "Cannot create achievement. Failed to upload " + achievementid + ". " + e.getMessage());
                L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
                return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
            }
        } else {
            objResponse.put("message", "Cannot create achievement. Achievement ID cannot be null!");
            L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
            return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
        }

    } catch (MalformedStreamException e) {
        // the stream failed to follow required syntax
        objResponse.put("message",
                "Cannot create achievement. Failed to upload " + achievementid + ". " + e.getMessage());
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);

    } catch (IOException e) {
        // a read or write error occurred
        objResponse.put("message",
                "Cannot create achievement. Failed to upload " + achievementid + ". " + 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 create achievement. Failed to upload " + achievementid + ". " + e.getMessage());
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);

    } catch (NullPointerException e) {
        e.printStackTrace();
        objResponse.put("message",
                "Cannot create achievement. Failed to upload " + achievementid + ". " + e.getMessage());
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
    }
    // always close connections
    finally {
        try {
            conn.close();
        } catch (SQLException e) {
            logger.printStackTrace(e);
        }
    }
}

From source file:i5.las2peer.services.gamificationActionService.GamificationActionService.java

/**
 * Post a new action// w  w w .  j a v a2s .c om
 * @param appId applicationId
 * @param formData form data
 * @param contentType content type
 * @return HttpResponse returned as JSON object
 */
@POST
@Path("/{appId}")
@Produces(MediaType.APPLICATION_JSON)
@ApiResponses(value = {
        @ApiResponse(code = HttpURLConnection.HTTP_CREATED, message = "{\"status\": 3, \"message\": \"Action upload success ( (actionid) )\"}"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "{\"status\": 3, \"message\": \"Failed to upload (actionid)\"}"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "{\"status\": 1, \"message\": \"Failed to add the action. Action ID already exist!\"}"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "{\"status\": =, \"message\": \"Action ID cannot be null!\"}"),
        @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "{\"status\": 2, \"message\": \"File content null. Failed to upload (actionid)\"}"),
        @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "{\"status\": 2, \"message\": \"Failed to upload (actionid)\"}"),
        @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "{\"status\": 3, \"message\": \"Action upload success ( (actionid) )}") })
@ApiOperation(value = "createNewAction", notes = "A method to store a new action with details (action ID, action name, action description,action point value")
public HttpResponse createNewAction(
        @ApiParam(value = "Application ID to store a new action", required = true) @PathParam("appId") String appId,
        @ApiParam(value = "Content-type in header", required = true) @HeaderParam(value = HttpHeaders.CONTENT_TYPE) String contentType,
        @ApiParam(value = "Action detail in multiple/form-data type", required = true) @ContentParam byte[] formData) {

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

    // parse given multipart form data
    JSONObject objResponse = new JSONObject();

    String actionid = null;
    String actionname = null;
    String actiondesc = null;
    int actionpointvalue = 0;

    boolean actionnotifcheck = false;
    String actionnotifmessage = null;
    Connection conn = null;

    UserAgent userAgent = (UserAgent) getContext().getMainAgent();
    String name = userAgent.getLoginName();
    if (name.equals("anonymous")) {
        return unauthorizedMessage();
    }
    try {
        conn = dbm.getConnection();
        L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_14, "" + randomLong);

        try {
            if (!actionAccess.isAppIdExist(conn, appId)) {
                objResponse.put("message", "Cannot create action. App not found");
                L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
                return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);
            }
        } catch (SQLException e1) {
            e1.printStackTrace();
            objResponse.put("message",
                    "Cannot create action. Cannot check whether application ID exist or not. Database error. "
                            + e1.getMessage());
            L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
            return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
        }
        Map<String, FormDataPart> parts = MultipartHelper.getParts(formData, contentType);
        FormDataPart partID = parts.get("actionid");
        if (partID != null) {
            actionid = partID.getContent();

            if (actionAccess.isActionIdExist(conn, appId, actionid)) {
                objResponse.put("message",
                        "Cannot create action. Failed to add the action. action ID already exist!");
                L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
                return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
            }
            FormDataPart partName = parts.get("actionname");
            if (partName != null) {
                actionname = partName.getContent();
            }
            FormDataPart partDesc = parts.get("actiondesc");
            if (partDesc != null) {
                // optional description text input form element
                actiondesc = partDesc.getContent();
            }
            FormDataPart partPV = parts.get("actionpointvalue");
            if (partPV != null) {
                // optional description text input form element
                actionpointvalue = Integer.parseInt(partPV.getContent());
            }
            FormDataPart partNotificationCheck = parts.get("actionnotificationcheck");
            if (partNotificationCheck != null) {
                // checkbox is checked
                actionnotifcheck = true;
            } else {
                actionnotifcheck = false;
            }
            FormDataPart partNotificationMsg = parts.get("actionnotificationmessage");
            if (partNotificationMsg != null) {
                actionnotifmessage = partNotificationMsg.getContent();
            } else {
                actionnotifmessage = "";
            }
            ActionModel action = new ActionModel(actionid, actionname, actiondesc, actionpointvalue,
                    actionnotifcheck, actionnotifmessage);

            try {
                actionAccess.addNewAction(conn, appId, action);
                objResponse.put("message", "Action upload success (" + actionid + ")");
                L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_15, "" + randomLong);
                L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_24, "" + name);
                L2pLogger.logEvent(Event.SERVICE_CUSTOM_MESSAGE_25, "" + appId);

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

            } catch (SQLException e) {
                e.printStackTrace();
                objResponse.put("message",
                        "Cannot create action. Failed to upload " + actionid + ". " + e.getMessage());
                L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
                return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
            }
        } else {
            objResponse.put("message", "Cannot create action. Action ID cannot be null!");
            L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
            return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);

        }

    } catch (MalformedStreamException e) {
        // the stream failed to follow required syntax
        objResponse.put("message",
                "Cannot create action. Failed to upload " + actionid + ". " + e.getMessage());
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);

    } catch (IOException e) {
        // a read or write error occurred
        objResponse.put("message",
                "Cannot create action. Failed to upload " + actionid + ". " + 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 create action. Failed to upload " + actionid + ". " + e.getMessage());
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);

    } catch (NullPointerException e) {
        e.printStackTrace();
        objResponse.put("message",
                "Cannot create action. Failed to upload " + actionid + ". " + e.getMessage());
        L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
        return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
    }
    // always close connections
    finally {
        try {
            conn.close();
        } catch (SQLException e) {
            logger.printStackTrace(e);
        }
    }
}

From source file:org.openbaton.sdk.api.util.RestRequest.java

/**
 * Does the POST Request//w ww  . ja  va  2  s  .com
 *
 * @param id
 * @return String
 * @throws SDKException
 */
public String requestPost(final String id) throws SDKException {
    CloseableHttpResponse response = null;
    HttpPost httpPost = null;
    try {
        log.debug("baseUrl: " + baseUrl);
        log.debug("id: " + baseUrl + "/" + id);

        try {
            checkToken();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            throw new SDKException("Could not get token", e);
        }

        // call the api here
        log.debug("Executing post on: " + this.baseUrl + "/" + id);
        httpPost = new HttpPost(this.baseUrl + "/" + id);
        httpPost.setHeader(new BasicHeader("accept", "application/json"));
        httpPost.setHeader(new BasicHeader("Content-Type", "application/json"));
        httpPost.setHeader(new BasicHeader("project-id", projectId));
        if (token != null)
            httpPost.setHeader(new BasicHeader("authorization", bearerToken.replaceAll("\"", "")));

        response = httpClient.execute(httpPost);

        // check response status
        checkStatus(response, HttpURLConnection.HTTP_CREATED);
        // return the response of the request
        String result = "";
        if (response.getEntity() != null)
            result = EntityUtils.toString(response.getEntity());
        response.close();
        log.trace("received: " + result);

        httpPost.releaseConnection();
        return result;
    } catch (IOException e) {
        // catch request exceptions here
        log.error(e.getMessage(), e);
        if (httpPost != null)
            httpPost.releaseConnection();
        throw new SDKException("Could not http-post or open the object properly", e);
    } catch (SDKException e) {
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
            token = null;
            if (httpPost != null)
                httpPost.releaseConnection();
            return requestPost(id);
        } else {
            if (httpPost != null)
                httpPost.releaseConnection();
            throw new SDKException("Status is " + response.getStatusLine().getStatusCode());
        }
    }
}

From source file:lu.list.itis.dkd.aig.util.FusekiHttpHelper.java

/**
 * Upload ontology content on specified dataset. Graph used is the default
 * one except if specified/*from w  w w .  j  a v a2  s.  co  m*/
 * 
 * @param ontology
 * @param datasetName
 * @param graphName
 * @throws IOException
 * @throws HttpException
 */
public static void uploadOntology(InputStream ontology, String datasetName, @Nullable String graphName)
        throws IOException, HttpException {
    graphName = Strings.emptyToNull(graphName);

    logger.info("upload ontology in dataset: " + datasetName + " graph:" + Strings.nullToEmpty(graphName));

    boolean createGraph = (graphName != null) ? true : false;
    String dataSetEncoded = URLEncoder.encode(datasetName, "UTF-8");
    String graphEncoded = createGraph ? URLEncoder.encode(graphName, "UTF-8") : null;

    URL url = new URL(HOST + '/' + dataSetEncoded + "/data" + (createGraph ? "?graph=" + graphEncoded : ""));

    final HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();

    String boundary = "------------------" + System.currentTimeMillis()
            + Long.toString(Math.round(Math.random() * 1000));

    httpConnection.setUseCaches(false);
    httpConnection.setRequestMethod("POST");
    httpConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
    httpConnection.setRequestProperty("Connection", "keep-alive");
    httpConnection.setRequestProperty("Cache-Control", "no-cache");

    // set content
    httpConnection.setDoOutput(true);
    final OutputStreamWriter out = new OutputStreamWriter(httpConnection.getOutputStream());
    out.write(BOUNDARY_DECORATOR + boundary + EOL);
    out.write("Content-Disposition: form-data; name=\"files[]\"; filename=\"ontology.owl\"" + EOL);
    out.write("Content-Type: application/octet-stream" + EOL + EOL);
    out.write(CharStreams.toString(new InputStreamReader(ontology)));
    out.write(EOL + BOUNDARY_DECORATOR + boundary + BOUNDARY_DECORATOR + EOL);
    out.close();

    // handle HTTP/HTTPS strange behaviour
    httpConnection.connect();
    httpConnection.disconnect();

    // handle response
    switch (httpConnection.getResponseCode()) {
    case HttpURLConnection.HTTP_CREATED:
        checkState(createGraph, "bad state - code:" + httpConnection.getResponseCode() + " message: "
                + httpConnection.getResponseMessage());
        break;
    case HttpURLConnection.HTTP_OK:
        checkState(!createGraph, "bad state - code:" + httpConnection.getResponseCode() + " message: "
                + httpConnection.getResponseMessage());
        break;
    default:
        throw new HttpException(
                httpConnection.getResponseCode() + " message: " + httpConnection.getResponseMessage());
    }

}

From source file:play.modules.resteasy.crud.RESTResource.java

/**
 * Returns a CREATED response with a Location header
 */
protected Response created(URI location) {
    return status(HttpURLConnection.HTTP_CREATED, location);
}