Example usage for java.net HttpURLConnection HTTP_INTERNAL_ERROR

List of usage examples for java.net HttpURLConnection HTTP_INTERNAL_ERROR

Introduction

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

Prototype

int HTTP_INTERNAL_ERROR

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

Click Source Link

Document

HTTP Status-Code 500: Internal Server Error.

Usage

From source file:com.netflix.genie.server.resources.CommandConfigResource.java

/**
 * Delete a command./*from  w  ww .j a v a 2 s  .com*/
 *
 * @param id unique id for configuration to delete
 * @return The deleted configuration
 * @throws GenieException For any error
 */
@DELETE
@Path("/{id}")
@ApiOperation(value = "Delete an comamnd", notes = "Delete an command with the supplied id.", response = Command.class)
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Command not found"),
        @ApiResponse(code = HttpURLConnection.HTTP_PRECON_FAILED, message = "Invalid required parameter supplied"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Genie Server Error due to Unknown Exception") })
public Command deleteCommand(
        @ApiParam(value = "Id of the command to delete.", required = true) @PathParam("id") final String id)
        throws GenieException {
    LOG.info("Called to delete command with id " + id);
    return this.commandConfigService.deleteCommand(id);
}

From source file:im.vector.util.BugReporter.java

/**
 * Send a bug report.//from  w w w . j  a  v  a2s.  c  o m
 *
 * @param context         the application context
 * @param withDevicesLogs true to include the device logs
 * @param withCrashLogs   true to include the crash logs
 */
private static void sendBugReport(final Context context, final boolean withDevicesLogs,
        final boolean withCrashLogs, final String bugDescription, final IMXBugReportListener listener) {
    new AsyncTask<Void, Integer, String>() {
        @Override
        protected String doInBackground(Void... voids) {
            File bugReportFile = new File(context.getApplicationContext().getFilesDir(), "bug_report");

            if (bugReportFile.exists()) {
                bugReportFile.delete();
            }

            String serverError = null;
            FileWriter fileWriter = null;

            try {
                fileWriter = new FileWriter(bugReportFile);
                JsonWriter jsonWriter = new JsonWriter(fileWriter);
                jsonWriter.beginObject();

                // android bug report
                jsonWriter.name("user_agent").value("Android");

                // logs list
                jsonWriter.name("logs");
                jsonWriter.beginArray();

                // the logs are optional
                if (withDevicesLogs) {
                    List<File> files = org.matrix.androidsdk.util.Log.addLogFiles(new ArrayList<File>());
                    for (File f : files) {
                        if (!mIsCancelled) {
                            jsonWriter.beginObject();
                            jsonWriter.name("lines").value(convertStreamToString(f));
                            jsonWriter.endObject();
                            jsonWriter.flush();
                        }
                    }
                }

                if (!mIsCancelled && (withCrashLogs || withDevicesLogs)) {
                    jsonWriter.beginObject();
                    jsonWriter.name("lines").value(getLogCatError());
                    jsonWriter.endObject();
                    jsonWriter.flush();
                }

                jsonWriter.endArray();

                jsonWriter.name("text").value(bugDescription);

                String version = "";

                if (null != Matrix.getInstance(context).getDefaultSession()) {
                    version += "User : " + Matrix.getInstance(context).getDefaultSession().getMyUserId() + "\n";
                }

                version += "Phone : " + Build.MODEL.trim() + " (" + Build.VERSION.INCREMENTAL + " "
                        + Build.VERSION.RELEASE + " " + Build.VERSION.CODENAME + ")\n";
                version += "Vector version: " + Matrix.getInstance(context).getVersion(true) + "\n";
                version += "SDK version:  " + Matrix.getInstance(context).getDefaultSession().getVersion(true)
                        + "\n";
                version += "Olm version:  "
                        + Matrix.getInstance(context).getDefaultSession().getCryptoVersion(context, true)
                        + "\n";

                jsonWriter.name("version").value(version);

                jsonWriter.endObject();
                jsonWriter.close();

            } catch (Exception e) {
                Log.e(LOG_TAG, "doInBackground ; failed to collect the bug report data " + e.getMessage());
                serverError = e.getLocalizedMessage();
            } catch (OutOfMemoryError oom) {
                Log.e(LOG_TAG, "doInBackground ; failed to collect the bug report data " + oom.getMessage());
                serverError = oom.getMessage();

                if (TextUtils.isEmpty(serverError)) {
                    serverError = "Out of memory";
                }
            }

            try {
                if (null != fileWriter) {
                    fileWriter.close();
                }
            } catch (Exception e) {
                Log.e(LOG_TAG, "doInBackground ; failed to close fileWriter " + e.getMessage());
            }

            if (TextUtils.isEmpty(serverError) && !mIsCancelled) {

                // the screenshot is defined here
                // File screenFile = new File(VectorApp.mLogsDirectoryFile, "screenshot.jpg");
                InputStream inputStream = null;
                HttpURLConnection conn = null;
                try {
                    inputStream = new FileInputStream(bugReportFile);
                    final int dataLen = inputStream.available();

                    // should never happen
                    if (0 == dataLen) {
                        return "No data";
                    }

                    URL url = new URL(context.getResources().getString(R.string.bug_report_url));
                    conn = (HttpURLConnection) url.openConnection();
                    conn.setDoInput(true);
                    conn.setDoOutput(true);
                    conn.setUseCaches(false);
                    conn.setRequestMethod("POST");
                    conn.setRequestProperty("Content-Type", "application/json");
                    conn.setRequestProperty("Content-Length", Integer.toString(dataLen));
                    // avoid caching data before really sending them.
                    conn.setFixedLengthStreamingMode(inputStream.available());

                    conn.connect();

                    DataOutputStream dos = new DataOutputStream(conn.getOutputStream());

                    byte[] buffer = new byte[8192];

                    // read file and write it into form...
                    int bytesRead;
                    int totalWritten = 0;

                    while (!mIsCancelled && (bytesRead = inputStream.read(buffer, 0, buffer.length)) > 0) {
                        dos.write(buffer, 0, bytesRead);
                        totalWritten += bytesRead;
                        publishProgress(totalWritten * 100 / dataLen);
                    }

                    dos.flush();
                    dos.close();

                    int mResponseCode;

                    try {
                        // Read the SERVER RESPONSE
                        mResponseCode = conn.getResponseCode();
                    } catch (EOFException eofEx) {
                        mResponseCode = HttpURLConnection.HTTP_INTERNAL_ERROR;
                    }

                    // if the upload failed, try to retrieve the reason
                    if (mResponseCode != HttpURLConnection.HTTP_OK) {
                        serverError = null;
                        InputStream is = conn.getErrorStream();

                        if (null != is) {
                            int ch;
                            StringBuilder b = new StringBuilder();
                            while ((ch = is.read()) != -1) {
                                b.append((char) ch);
                            }
                            serverError = b.toString();
                            is.close();

                            // check if the error message
                            try {
                                JSONObject responseJSON = new JSONObject(serverError);
                                serverError = responseJSON.getString("error");
                            } catch (JSONException e) {
                                Log.e(LOG_TAG, "doInBackground ; Json conversion failed " + e.getMessage());
                            }

                            // should never happen
                            if (null == serverError) {
                                serverError = "Failed with error " + mResponseCode;
                            }

                            is.close();
                        }
                    }
                } catch (Exception e) {
                    Log.e(LOG_TAG,
                            "doInBackground ; failed with error " + e.getClass() + " - " + e.getMessage());
                    serverError = e.getLocalizedMessage();

                    if (TextUtils.isEmpty(serverError)) {
                        serverError = "Failed to upload";
                    }
                } catch (OutOfMemoryError oom) {
                    Log.e(LOG_TAG, "doInBackground ; failed to send the bug report " + oom.getMessage());
                    serverError = oom.getLocalizedMessage();

                    if (TextUtils.isEmpty(serverError)) {
                        serverError = "Out ouf memory";
                    }

                } finally {
                    try {
                        if (null != conn) {
                            conn.disconnect();
                        }
                    } catch (Exception e2) {
                        Log.e(LOG_TAG, "doInBackground : conn.disconnect() failed " + e2.getMessage());
                    }
                }

                if (null != inputStream) {
                    try {
                        inputStream.close();
                    } catch (Exception e) {
                        Log.e(LOG_TAG, "doInBackground ; failed to close the inputStream " + e.getMessage());
                    }
                }
            }
            return serverError;
        }

        @Override
        protected void onProgressUpdate(Integer... progress) {
            super.onProgressUpdate(progress);

            if (null != listener) {
                try {
                    listener.onProgress((null == progress) ? 0 : progress[0]);
                } catch (Exception e) {
                    Log.e(LOG_TAG, "## onProgress() : failed " + e.getMessage());
                }
            }
        }

        @Override
        protected void onPostExecute(String reason) {
            if (null != listener) {
                try {
                    if (mIsCancelled) {
                        listener.onUploadCancelled();
                    } else if (null == reason) {
                        listener.onUploadSucceed();
                    } else {
                        listener.onUploadFailed(reason);
                    }
                } catch (Exception e) {
                    Log.e(LOG_TAG, "## onPostExecute() : failed " + e.getMessage());
                }
            }
        }
    }.execute();
}

From source file:i5.las2peer.services.gamificationBadgeService.GamificationBadgeService.java

/**
 * Post a new badge/*www  .j  a v a 2  s  .c  o  m*/
 * @param appId application id
 * @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\": \"Badge upload success ( (badgeid) )\"}"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "{\"status\": 3, \"message\": \"Failed to upload (badgeid)\"}"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "{\"status\": 1, \"message\": \"Failed to add the badge. Badge ID already exist!\"}"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "{\"status\": =, \"message\": \"Badge ID cannot be null!\"}"),
        @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "{\"status\": 2, \"message\": \"File content null. Failed to upload (badgeid)\"}"),
        @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "{\"status\": 2, \"message\": \"Failed to upload (badgeid)\"}"),
        @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "{\"status\": 3, \"message\": \"Badge upload success ( (badgeid) )}") })
@ApiOperation(value = "createNewBadge", notes = "A method to store a new badge with details (badge ID, badge name, badge description, and badge image")
public HttpResponse createNewBadge(
        @ApiParam(value = "Application ID to store a new badge", required = true) @PathParam("appId") String appId,
        @ApiParam(value = "Content-type in header", required = true) @HeaderParam(value = HttpHeaders.CONTENT_TYPE) String contentType,
        @ApiParam(value = "Badge detail in multiple/form-data type", required = true) @ContentParam byte[] formData) {

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

    // parse given multipart form data
    JSONObject objResponse = new JSONObject();
    String filename = null;
    byte[] filecontent = null;
    String mimeType = null;
    String badgeid = null;
    // Badge ID for the filesystem is appended with app id to make sure it is unique
    String badgename = null;
    String badgedescription = null;
    String badgeImageURI = null;
    boolean badgeusenotification = false;
    String badgenotificationmessage = 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 (!badgeAccess.isAppIdExist(conn, appId)) {
                logger.info("App not found >> ");
                objResponse.put("message", "Cannot create badge. 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();
            logger.info(
                    "Cannot check whether application ID exist or not. Database error. >> " + e1.getMessage());
            objResponse.put("message",
                    "Cannot create badge. 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 partBadgeID = parts.get("badgeid");
        if (partBadgeID != null) {
            // these data belong to the (optional) file id text input form element
            badgeid = partBadgeID.getContent();

            if (badgeAccess.isBadgeIdExist(conn, appId, badgeid)) {
                // Badge id already exist
                logger.info("Failed to add the badge. Badge ID already exist!");
                objResponse.put("message",
                        "Cannot create badge. Failed to add the badge. Badge ID already exist!.");
                L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
                return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);

            }
            FormDataPart partFilecontent = parts.get("badgeimageinput");
            if (partFilecontent != null) {
                System.out.println(partFilecontent.getContent());
                // these data belong to the file input form element
                filename = partFilecontent.getHeader(HEADER_CONTENT_DISPOSITION).getParameter("filename");
                byte[] filecontentbefore = partFilecontent.getContentRaw();
                //                         validate input
                if (filecontentbefore == null) {
                    logger.info("File content null");
                    objResponse.put("message",
                            "Cannot create badge. File content null. Failed to upload " + badgeid);
                    L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
                    return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_BAD_REQUEST);
                }

                // in unit test, resize image will turn the image into null BufferedImage
                // but, it works in web browser
                FormDataPart partDev = parts.get("dev");
                if (partDev != null) {
                    filecontent = filecontentbefore;
                } else {
                    filecontent = resizeImage(filecontentbefore);
                }
                mimeType = partFilecontent.getContentType();
                logger.info("upload request (" + filename + ") of mime type '" + mimeType
                        + "' with content length " + filecontent.length);
            }

            FormDataPart partBadgeName = parts.get("badgename");
            if (partBadgeName != null) {
                badgename = partBadgeName.getContent();
            }
            FormDataPart partDescription = parts.get("badgedesc");
            if (partDescription != null) {
                // optional description text input form element
                badgedescription = partDescription.getContent();
            }

            FormDataPart partNotificationCheck = parts.get("badgenotificationcheck");
            if (partNotificationCheck != null) {
                // checkbox is checked
                badgeusenotification = true;
            } else {
                badgeusenotification = false;
            }
            FormDataPart partNotificationMsg = parts.get("badgenotificationmessage");
            if (partNotificationMsg != null) {
                badgenotificationmessage = partNotificationMsg.getContent();
            } else {
                badgenotificationmessage = "";
            }

            try {

                storeBadgeDataToSystem(appId, badgeid, filename, filecontent, mimeType, badgedescription);
                BadgeModel badge = new BadgeModel(badgeid, badgename, badgedescription, badgeusenotification,
                        badgenotificationmessage);

                try {
                    badgeAccess.addNewBadge(conn, appId, badge);
                    objResponse.put("message", "Badge upload success (" + badgeid + ")");
                    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 badge. Failed to upload " + badgeid + ". " + e.getMessage());
                    L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
                    return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);
                }

            } catch (AgentNotKnownException | L2pServiceException | L2pSecurityException | InterruptedException
                    | TimeoutException e) {
                e.printStackTrace();
                objResponse.put("message",
                        "Cannot create badge. Failed to upload " + badgeid + ". " + e.getMessage());
                L2pLogger.logEvent(this, Event.SERVICE_ERROR, (String) objResponse.get("message"));
                return new HttpResponse(objResponse.toJSONString(), HttpURLConnection.HTTP_INTERNAL_ERROR);

            }
        } else {
            logger.info("Badge ID cannot be null");
            objResponse.put("message", "Cannot create badge. Badge 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 badge. Failed to upload " + badgeid + ". " + 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 badge. Failed to upload " + badgeid + ". " + 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 badge. Failed to upload " + badgeid + ". " + e.getMessage());
        //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);

    } catch (NullPointerException e) {
        e.printStackTrace();
        objResponse.put("message", "Cannot create badge. Failed to upload " + badgeid + ". " + 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.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/*from w w w  . j a  v  a2  s  . 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:fi.cosky.sdk.API.java

private <T extends BaseData> T sendRequest(Link l, Class<T> tClass, Object object) throws IOException {
    URL serverAddress;/*from  w  w w  . j av  a  2  s  .c o m*/
    BufferedReader br;
    String result = "";
    HttpURLConnection connection = null;
    String url = l.getUri().contains("://") ? l.getUri() : this.baseUrl + l.getUri();
    try {
        String method = l.getMethod();
        String type = l.getType();

        serverAddress = new URL(url);
        connection = (HttpURLConnection) serverAddress.openConnection();
        boolean doOutput = doOutput(method);
        connection.setDoOutput(doOutput);
        connection.setRequestMethod(method);
        connection.setInstanceFollowRedirects(false);

        if (method.equals("GET") && useMimeTypes)
            if (type == null || type.equals("")) {
                addMimeTypeAcceptToRequest(object, tClass, connection);
            } else {
                connection.addRequestProperty("Accept", helper.getSupportedType(type));
            }
        if (!useMimeTypes)
            connection.setRequestProperty("Accept", "application/json");

        if (doOutput && useMimeTypes) {
            //this handles the case if the link is self made and the type field has not been set.
            if (type == null || type.equals("")) {
                addMimeTypeContentTypeToRequest(l, tClass, connection);
                addMimeTypeAcceptToRequest(l, tClass, connection);
            } else {
                connection.addRequestProperty("Accept", helper.getSupportedType(type));
                connection.addRequestProperty("Content-Type", helper.getSupportedType(type));
            }
        }

        if (!useMimeTypes)
            connection.setRequestProperty("Content-Type", "application/json");

        if (tokenData != null) {
            connection.addRequestProperty("Authorization",
                    tokenData.getTokenType() + " " + tokenData.getAccessToken());
        }

        addVersionNumberToHeader(object, url, connection);

        if (method.equals("POST") || method.equals("PUT")) {
            String json = object != null ? gson.toJson(object) : ""; //should handle the case when POST without object.
            connection.addRequestProperty("Content-Length", json.getBytes("UTF-8").length + "");
            OutputStreamWriter osw = new OutputStreamWriter(connection.getOutputStream());
            osw.write(json);
            osw.flush();
            osw.close();
        }

        connection.connect();

        if (connection.getResponseCode() == HttpURLConnection.HTTP_CREATED
                || connection.getResponseCode() == HttpURLConnection.HTTP_SEE_OTHER) {
            ResponseData data = new ResponseData();
            Link link = parseLocationLinkFromString(connection.getHeaderField("Location"));
            link.setType(type);
            data.setLocation(link);
            connection.disconnect();
            return (T) data;
        }

        if (connection.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
            System.out.println(
                    "Authentication expired " + connection.getResponseMessage() + " trying to reauthenticate");
            if (retry && this.tokenData != null) {
                this.tokenData = null;
                retry = false;
                if (authenticate()) {
                    System.out.println("Reauthentication success, will continue with " + l.getMethod()
                            + " request on " + l.getRel());
                    return sendRequest(l, tClass, object);
                }
            } else
                throw new IOException(
                        "Tried to reauthenticate but failed, please check the credentials and status of NFleet-API");
        }

        if (connection.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) {
            return (T) objectCache.getObject(url);
        }

        if (connection.getResponseCode() == HttpURLConnection.HTTP_NO_CONTENT) {
            return (T) new ResponseData();
        }

        if (connection.getResponseCode() >= HttpURLConnection.HTTP_BAD_REQUEST
                && connection.getResponseCode() < HttpURLConnection.HTTP_INTERNAL_ERROR) {
            System.out.println("ErrorCode: " + connection.getResponseCode() + " "
                    + connection.getResponseMessage() + " " + url + ", verb: " + method);

            String errorString = readErrorStreamAndCloseConnection(connection);
            throw (NFleetRequestException) gson.fromJson(errorString, NFleetRequestException.class);
        } else if (connection.getResponseCode() >= HttpURLConnection.HTTP_INTERNAL_ERROR) {
            if (retry) {
                System.out.println("Request caused internal server error, waiting " + RETRY_WAIT_TIME
                        + " ms and trying again.");
                return waitAndRetry(connection, l, tClass, object);
            } else {
                System.out.println("Requst caused internal server error, please contact dev@nfleet.fi");
                String errorString = readErrorStreamAndCloseConnection(connection);
                throw new IOException(errorString);
            }
        }

        if (connection.getResponseCode() >= HttpURLConnection.HTTP_BAD_GATEWAY) {
            if (retry) {
                System.out.println("Could not connect to NFleet-API, waiting " + RETRY_WAIT_TIME
                        + " ms and trying again.");
                return waitAndRetry(connection, l, tClass, object);
            } else {
                System.out.println(
                        "Could not connect to NFleet-API, please check service status from http://status.nfleet.fi and try again later.");
                String errorString = readErrorStreamAndCloseConnection(connection);
                throw new IOException(errorString);
            }

        }

        result = readDataFromConnection(connection);

    } catch (MalformedURLException e) {
        throw e;
    } catch (ProtocolException e) {
        throw e;
    } catch (UnsupportedEncodingException e) {
        throw e;
    } catch (IOException e) {
        throw e;
    } catch (SecurityException e) {
        throw e;
    } catch (IllegalArgumentException e) {
        throw e;
    } finally {
        assert connection != null;
        connection.disconnect();
    }
    Object newEntity = gson.fromJson(result, tClass);
    objectCache.addUri(url, newEntity);
    return (T) newEntity;
}

From source file:com.netflix.genie.server.resources.ApplicationConfigResource.java

/**
 * Delete an application configuration from database.
 *
 * @param id unique id of configuration to delete
 * @return The deleted application configuration
 * @throws GenieException For any error//from ww w  .  j  a  va 2s.c om
 */
@DELETE
@Path("/{id}")
@ApiOperation(value = "Delete an application", notes = "Delete an application with the supplied id.", response = Application.class)
@ApiResponses(value = {
        @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Application not found"),
        @ApiResponse(code = HttpURLConnection.HTTP_PRECON_FAILED, message = "Invalid ID supplied"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Genie Server Error due to Unknown Exception") })
public Application deleteApplication(
        @ApiParam(value = "Id of the application to delete.", required = true) @PathParam("id") final String id)
        throws GenieException {
    LOG.info("Delete an application with id " + id);
    return this.applicationConfigService.deleteApplication(id);
}

From source file:rapture.repo.file.FileDataStore.java

@Override
public void visitKeysFromStart(String startPoint, StoreKeyVisitor iStoreKeyVisitor) {
    File dir = FileRepoUtils.makeGenericFile(parentDir, convertKeyToPath(""));
    if (!dir.exists()) {
        return;//from   ww  w . j  ava  2 s. c  o m
    }
    int authLen = dir.getPath().toString().length();
    boolean canStart = startPoint == null;
    Iterator<File> fIterator = FileUtils.iterateFiles(dir, null, true);
    while (fIterator.hasNext()) {
        File f = fIterator.next();
        if (f.isFile()) {
            try {
                if (!canStart) {
                    if (f.getName().equals(startPoint)) {
                        canStart = true; // On the next loop
                    }
                } else {
                    // Skip the prefix and authority
                    String fileName = f.getPath().toString();
                    String docPath = fileName.substring(authLen + 1);
                    if (docPath.endsWith(".txt"))
                        docPath = docPath.substring(0, docPath.length() - 4);
                    if (!iStoreKeyVisitor.visit(docPath, FileUtils.readFileToString(f)))
                        break;
                }
            } catch (IOException e) {
                throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_INTERNAL_ERROR,
                        "Could not read keys", e);
            }
        }
    }
}

From source file:org.cm.podd.report.service.DataSubmitService.java

private boolean submitReport(Report report) throws URISyntaxException, IOException, JSONException {

    HttpParams params = new BasicHttpParams();
    params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    HttpClient client = new DefaultHttpClient(params);
    boolean success = false;

    try {/*from   w ww . j  a  va2s  . co  m*/

        String serverUrl = settings.getString("serverUrl", BuildConfig.SERVER_URL);

        URI http = new URI(serverUrl + "/reports/");
        Log.i(TAG, "submit report url=" + http.toURL());

        HttpPost post = new HttpPost(http);
        post.setHeader("Content-type", "application/json");
        post.setHeader("Authorization", "Token " + sharedPrefUtil.getAccessToken());

        SimpleDateFormat sdfDateTime = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
        SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd");

        JSONObject data = new JSONObject();
        data.put("reportId", report.getId());
        data.put("guid", report.getGuid());
        data.put("reportTypeId", report.getType());
        if (report.getFollowFlag() == Report.TRUE) {
            data.put("date", sdfDateTime.format(report.getFollowDate()));
            data.put("followFlag", Report.TRUE);
            data.put("parentGuid", report.getParentGuid());
        } else {
            data.put("date", sdfDateTime.format(report.getDate()));
        }
        Date startDate = report.getStartDate();
        if (startDate == null) {
            startDate = new Date();
        }
        data.put("incidentDate", sdfDate.format(startDate));
        if (report.getRegionId() != 0) {
            data.put("administrationAreaId", report.getRegionId());
        }
        if (report.getLatitude() != 0.00 && report.getLongitude() != 0.00) {
            JSONObject loc = new JSONObject();
            loc.put("latitude", report.getLatitude());
            loc.put("longitude", report.getLongitude());

            data.put("reportLocation", loc);
        }

        data.put("remark", report.getRemark());
        data.put("negative", report.getNegative() == 1);

        JSONObject formObj = report.getNegative() == 1 ? report.getSubmitJSONFormData() : new JSONObject();
        formObj.put("programVersion", BuildConfig.VERSION_CODE);
        formObj.put("reportTypeVersion", report.getReportTypeVersion());
        data.put("formData", formObj);

        if (report.isTestReport()) {
            data.put("testFlag", true);
        } else {
            data.put("testFlag", false);
        }

        post.setEntity(new StringEntity(data.toString(), HTTP.UTF_8));
        Log.d(TAG, "request with " + EntityUtils.toString(post.getEntity()));

        HttpResponse response;
        response = client.execute(post);
        HttpEntity entity = response.getEntity();

        // Detect server complaints
        int statusCode = response.getStatusLine().getStatusCode();
        Log.d(TAG, "status code=" + statusCode);

        if (statusCode == HttpURLConnection.HTTP_INTERNAL_ERROR) {
            Log.e(TAG, "error " + EntityUtils.toString(response.getEntity()));
        }
        success = statusCode == 201;
        entity.consumeContent();

    } finally {
        client.getConnectionManager().shutdown();
    }
    return success;
}

From source file:org.jboss.test.web.test.WebIntegrationUnitTestCase.java

/** Access the http://{host}/jbosstest/UnsecureEJBAccess with method=echo
 * to test that an unsecured servlet cannot access a secured EJB method
 * that requires a valid permission. This should fail.
 *//*from w  w w  . j a v a 2s .  co  m*/
public void testUnsecureEJBAccess() throws Exception {
    URL url = new URL(baseURLNoAuth + "jbosstest/UnsecureEJBAccess?method=echo");
    HttpUtils.accessURL(url, REALM, HttpURLConnection.HTTP_INTERNAL_ERROR);
}

From source file:com.netflix.genie.server.resources.ClusterConfigResource.java

/**
 * Delete all clusters from database./* ww  w.  j a va2  s  .  c om*/
 *
 * @return All The deleted clusters
 * @throws GenieException For any error
 */
@DELETE
@ApiOperation(value = "Delete all clusters", notes = "Delete all available clusters and get them back.", response = Cluster.class, responseContainer = "List")
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_NOT_FOUND, message = "Cluster not found"),
        @ApiResponse(code = HttpURLConnection.HTTP_PRECON_FAILED, message = "Invalid required parameter supplied"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "Genie Server Error due to Unknown Exception") })
public List<Cluster> deleteAllClusters() throws GenieException {
    LOG.info("called");
    return this.clusterConfigService.deleteAllClusters();
}