Example usage for org.apache.commons.httpclient.methods PutMethod setRequestEntity

List of usage examples for org.apache.commons.httpclient.methods PutMethod setRequestEntity

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.methods PutMethod setRequestEntity.

Prototype

public void setRequestEntity(RequestEntity paramRequestEntity) 

Source Link

Usage

From source file:de.mpg.escidoc.pubman.easySubmission.EasySubmission.java

/**
 * Uploads a file to the staging servlet and returns the corresponding URL.
 * /*from  w  w w .  j ava 2s  .c o  m*/
 * @param InputStream to upload
 * @param mimetype The mimetype of the file
 * @param userHandle The userhandle to use for upload
 * @return The URL of the uploaded file.
 * @throws Exception If anything goes wrong...
 */
protected URL uploadFile(InputStream in, String mimetype, String userHandle) throws Exception {
    // Prepare the HttpMethod.
    String fwUrl = de.mpg.escidoc.services.framework.ServiceLocator.getFrameworkUrl();
    PutMethod method = new PutMethod(fwUrl + "/st/staging-file");
    method.setRequestEntity(new InputStreamRequestEntity(in));
    method.setRequestHeader("Content-Type", mimetype);
    method.setRequestHeader("Cookie", "escidocCookie=" + userHandle);
    // Execute the method with HttpClient.
    HttpClient client = new HttpClient();
    client.executeMethod(method);
    String response = method.getResponseBodyAsString();
    return xmlTransforming.transformUploadResponseToFileURL(response);
}

From source file:de.mpg.mpdl.inge.pubman.web.easySubmission.EasySubmission.java

/**
 * Uploads a file to the staging servlet and returns the corresponding URL.
 * /*ww w. j av a2s.  c o m*/
 * @param uploadedFile The file to upload
 * @param mimetype The mimetype of the file
 * @param userHandle The userhandle to use for upload
 * @return The URL of the uploaded file.
 * @throws Exception If anything goes wrong...
 */
protected URL uploadFile(UploadedFile uploadedFile, String mimetype, String userHandle) throws Exception {
    // Prepare the HttpMethod.
    String fwUrl = PropertyReader.getFrameworkUrl();
    PutMethod method = new PutMethod(fwUrl + "/st/staging-file");
    /*
     * if(uploadedFile.isTempFile()) {
     */
    InputStream fis = uploadedFile.getInputstream();
    method.setRequestEntity(new InputStreamRequestEntity(fis));

    /*
     * } else { method.setRequestEntity(new InputStreamRequestEntity(new
     * ByteArrayInputStream(uploadedFile.getData()))); }
     */
    method.setRequestHeader("Content-Type", mimetype);
    method.setRequestHeader("Cookie", "escidocCookie=" + userHandle);
    // Execute the method with HttpClient.
    HttpClient client = new HttpClient();
    ProxyHelper.setProxy(client, fwUrl);
    client.executeMethod(method);
    String response = method.getResponseBodyAsString();
    fis.close();
    return xmlTransforming.transformUploadResponseToFileURL(response);
}

From source file:de.mpg.escidoc.pubman.easySubmission.EasySubmission.java

/**
 * Uploads a file to the staging servlet and returns the corresponding URL.
 * // w ww  .  j  a  v a2s  . c o m
 * @param uploadedFile The file to upload
 * @param mimetype The mimetype of the file
 * @param userHandle The userhandle to use for upload
 * @return The URL of the uploaded file.
 * @throws Exception If anything goes wrong...
 */
protected URL uploadFile(UploadedFile uploadedFile, String mimetype, String userHandle) throws Exception {
    // Prepare the HttpMethod.
    String fwUrl = de.mpg.escidoc.services.framework.ServiceLocator.getFrameworkUrl();
    PutMethod method = new PutMethod(fwUrl + "/st/staging-file");
    /*
     if(uploadedFile.isTempFile())
     {
     */
    InputStream fis = uploadedFile.getInputstream();
    method.setRequestEntity(new InputStreamRequestEntity(fis));

    /*    
    }
        else
        {
    method.setRequestEntity(new InputStreamRequestEntity(new ByteArrayInputStream(uploadedFile.getData())));
        }
        */
    method.setRequestHeader("Content-Type", mimetype);
    method.setRequestHeader("Cookie", "escidocCookie=" + userHandle);
    // Execute the method with HttpClient.
    HttpClient client = new HttpClient();
    ProxyHelper.setProxy(client, fwUrl);
    client.executeMethod(method);
    String response = method.getResponseBodyAsString();
    fis.close();
    return xmlTransforming.transformUploadResponseToFileURL(response);
}

From source file:edu.stanford.epad.epadws.processing.pipeline.task.EpadStatisticsTask.java

@Override
public void run() {
    try {/*from   ww w. j a  va  2 s.c  o m*/
        log.info("Getting epad statistics");
        EpadStatistics es = new EpadStatistics();
        int users = new User().getCount("");
        int projects = new Project().getCount("");
        int patients = new Subject().getCount("");
        int studies = new Study().getCount("");
        int files = new EpadFile().getCount("");
        int templates = new EpadFile().getCount("filetype = '" + FileType.TEMPLATE.getName() + "'");
        int plugins = new Plugin().getCount("");
        int series = epadDatabaseOperations.getNumberOfSeries();
        int npacs = RemotePACService.getInstance().getRemotePACs().size();
        int aims = epadDatabaseOperations.getNumberOfAIMs("1 = 1");
        int dsos = epadDatabaseOperations.getNumberOfAIMs("DSOSeriesUID is not null or DSOSeriesUID != ''");
        int pacQueries = new RemotePACQuery().getCount("");
        int wls = 0;
        try {
            wls = new WorkList().getCount("");
        } catch (Exception x) {
        }
        String host = EPADConfig.xnatServer;
        if (host == null || host.equalsIgnoreCase("localhost") || host.equalsIgnoreCase("127.0.0.1")
                || host.equalsIgnoreCase("epad-vm"))
            host = System.getenv("DOCKER_HOST");
        ;
        if (host == null || host.equalsIgnoreCase("localhost") || host.equalsIgnoreCase("127.0.0.1")
                || host.equalsIgnoreCase("epad-vm"))
            host = System.getenv("HOSTNAME");
        ;
        if (host == null || host.equalsIgnoreCase("localhost") || host.equalsIgnoreCase("127.0.0.1")
                || host.equalsIgnoreCase("epad-vm"))
            host = InetAddress.getLocalHost().getHostName();
        if (host == null || host.equalsIgnoreCase("localhost") || host.equalsIgnoreCase("127.0.0.1")
                || host.equalsIgnoreCase("epad-vm"))
            host = getIPAddress();
        es.setHost(host);
        es.setNumOfUsers(users);
        es.setNumOfProjects(projects);
        es.setNumOfPatients(patients);
        es.setNumOfStudies(studies);
        es.setNumOfSeries(series);
        es.setNumOfAims(aims);
        es.setNumOfDSOs(dsos);
        es.setNumOfWorkLists(wls);
        es.setNumOfPacs(npacs);
        es.setNumOfAutoQueries(pacQueries);
        es.setNumOfFiles(files);
        es.setNumOfPlugins(plugins);
        es.setNumOfTemplates(templates);
        es.setCreator("admin");
        es.save();

        //get the template statistics
        List<EpadStatisticsTemplate> templateStats = epadDatabaseOperations.getTemplateStats();

        Calendar now = Calendar.getInstance();
        boolean daily = true;
        if ("Weekly".equalsIgnoreCase(EPADConfig.getParamValue("StatisticsPeriod", "Daily")))
            daily = false;
        if (!"true".equalsIgnoreCase(EPADConfig.getParamValue("DISABLE_STATISTICS_TRANSMIT"))) {
            if (daily || now.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
                long delay = new Random().nextInt(1800 + 1);
                if (EPADConfig.xnatServer.indexOf("stanford") == -1)
                    Thread.sleep(1000 * delay); // So that all don't do this at the same time
                //send the number statistics
                String epadUrl = EPADConfig.getParamValue("EpadStatisticsURL",
                        "https://epad-public.stanford.edu/epad/statistics/");
                epadUrl = epadUrl + "?numOfUsers=" + users;
                epadUrl = epadUrl + "&numOfProjects=" + projects;
                epadUrl = epadUrl + "&numOfPatients=" + patients;
                epadUrl = epadUrl + "&numOfStudies=" + studies;
                epadUrl = epadUrl + "&numOfSeries=" + series;
                epadUrl = epadUrl + "&numOfAims=" + aims;
                epadUrl = epadUrl + "&numOfDSOs=" + dsos;
                epadUrl = epadUrl + "&numOfWorkLists=" + wls;
                epadUrl = epadUrl + "&numOfFiles=" + files;
                epadUrl = epadUrl + "&numOfPlugins=" + plugins;
                epadUrl = epadUrl + "&numOfTemplates=" + templates;
                epadUrl = epadUrl + "&host=" + host;
                HttpClient client = new HttpClient();
                PutMethod putMethod = new PutMethod(epadUrl);

                try {
                    log.info("Sending statistics to Central Epad, url:" + epadUrl);
                    int status = client.executeMethod(putMethod);
                    log.info("Done Sending, status:" + putMethod.getStatusLine());
                } catch (IOException e) {
                    log.warning("Error calling Central Epad with URL " + epadUrl, e);
                } finally {
                    putMethod.releaseConnection();
                }

                //send statistics for templates
                for (EpadStatisticsTemplate st : templateStats) {
                    //get the xml first
                    String filePath = st.getFilePath() + st.getFileId() + ".xml";
                    log.info("path " + filePath);
                    File f = null;
                    if (filePath != null && (f = new File(filePath)).exists()) {
                        st.setTemplateText(EPADFileUtils.readFileAsString(f));
                    }
                    st.setCreator("admin");
                    //persist to db
                    st.save();

                    epadUrl = EPADConfig.getParamValue("EpadTemplateStatisticsURL",
                            "https://epad-public.stanford.edu/epad/statistics/templates/");
                    epadUrl = epadUrl + "?templateCode=" + encode(st.getTemplateCode());
                    epadUrl = epadUrl + "&templateName=" + encode(st.getTemplateName());
                    epadUrl = epadUrl + "&authors=" + encode(st.getAuthors());
                    epadUrl = epadUrl + "&version=" + encode(st.getVersion());
                    epadUrl = epadUrl + "&templateLevelType=" + encode(st.getTemplateLevelType());
                    epadUrl = epadUrl + "&templateDescription=" + encode(st.getTemplateDescription());
                    epadUrl = epadUrl + "&numOfAims=" + st.getNumOfAims();
                    epadUrl = epadUrl + "&host=" + host;
                    putMethod = new PutMethod(epadUrl);
                    putMethod.setRequestEntity(
                            new StringRequestEntity(st.getTemplateText(), "text/xml", "UTF-8"));

                    try {
                        log.info("Sending template statistics to Central Epad, url:" + epadUrl);
                        int status = client.executeMethod(putMethod);
                        log.info("Done Sending, status:" + putMethod.getStatusLine());
                    } catch (IOException e) {
                        log.warning("Error calling Central Epad with URL " + epadUrl, e);
                    } finally {
                        putMethod.releaseConnection();
                    }
                }
            }
        }

    } catch (Exception e) {
        log.warning("Error is saving/sending statistics", e);
    }
    GetMethod getMethod = null;
    try {
        String epadUrl = EPADConfig.getParamValue("EpadStatusURL",
                "https://epad-public.stanford.edu/epad/status/");
        HttpClient client = new HttpClient();
        getMethod = new GetMethod(epadUrl);
        int status = client.executeMethod(getMethod);
        if (status == HttpServletResponse.SC_OK) {
            String response = getMethod.getResponseBodyAsString();
            int versInd = response.indexOf("Version:");
            if (versInd != -1) {
                String version = response.substring(versInd + "Version:".length() + 1);
                if (version.indexOf("\n") != -1)
                    version = version.substring(0, version.indexOf("\n"));
                if (version.indexOf(" ") != -1)
                    version = version.substring(0, version.indexOf(" "));
                log.info("Current ePAD version:" + version + " Our Version:"
                        + new EPadWebServerVersion().getVersion());
                if (!version.equals(new EPadWebServerVersion().getVersion())) {
                    newEPADVersion = version;
                    newEPADVersionAvailable = true;
                    String msg = "A new version of ePAD: " + version
                            + " is available, please go to ftp://epad-distribution.stanford.edu/ to download";
                    log.info(msg);
                    List<User> admins = new User().getObjects("admin = 1 and enabled = 1");
                    for (User admin : admins) {
                        List<Map<String, String>> userEvents = epadDatabaseOperations
                                .getEpadEventsForSessionID(admin.getUsername(), false);
                        boolean skip = false;
                        for (Map<String, String> event : userEvents) {
                            if (event.get("aim_name").equals("Upgrade")) {
                                skip = true;
                                break;
                            }
                        }
                        if (skip)
                            continue;
                        if (EPADConfig.xnatServer.indexOf("stanford") == -1)
                            epadDatabaseOperations.insertEpadEvent(admin.getUsername(), msg, // Message
                                    "", "", // aimUID, aimName
                                    "", // patient ID
                                    "", // patient Name
                                    "", // templateID
                                    "", // templateName
                                    "Please update ePAD"); // PluginName
                    }
                }
            }
        } else
            log.warning("Error is getting epad version");

    } catch (Exception x) {
        log.warning("Error is getting epad version", x);
    } finally {
        getMethod.releaseConnection();
    }

    //done with calculating and sending the statistics
    //calculate a monthly cumulative if it is there is no record for the month
    boolean isAlreadyCalced = false;
    Calendar now = Calendar.getInstance();
    try {
        EPADUsageList monthly = epadOperations.getMonthlyUsageSummaryForMonth(now.get(Calendar.MONTH) + 1);
        if (monthly != null && monthly.ResultSet.totalRecords > 0)
            isAlreadyCalced = true;
    } catch (Exception e) {
        log.warning("Couldn't get if the monthly cumulative statistics already calculated, assuming no", e);
    }
    if (isAlreadyCalced == false) {
        epadDatabaseOperations.calcMonthlyCumulatives();
    }

}

From source file:itslearning.platform.restapi.sdk.learningtoolapp.LearningObjectServicetRestClient.java

public void updateLearningObjectInstance(LearningObjectInstance instance, int instanceId, int learningObjectId)
        throws Exception {
    String uri = String.format(_baseUri + "/LearningObjectService.svc/learningObjects/%s/instances/%s",
            learningObjectId, instanceId);
    PutMethod method = (PutMethod) getInitializedHttpMethod(_httpClient, uri, HttpMethodType.PUT);
    String loiAsXml = serializeLearningObjectInstanceToXML(instance);
    InputStream is = new ByteArrayInputStream(loiAsXml.getBytes("UTF-8"));
    method.setRequestEntity(new InputStreamRequestEntity(is));
    try {//from   w  ww. jav a2s .  com
        int statusCode = _httpClient.executeMethod(method);
        // Put methods, may return 200, 201, 204
        if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED
                && statusCode != HttpStatus.SC_NOT_MODIFIED) {
            throw new HTTPException(statusCode);
        }

    } catch (Exception ex) {
        ExceptionHandler.handle(ex);
    } finally {
        method.releaseConnection();
    }
}

From source file:itslearning.platform.restapi.sdk.learningtoolapp.LearningObjectServicetRestClient.java

public void updateLearningObjectInstanceUserReport(LearningObjectInstanceUserReport userReport, int instanceId,
        int learningObjectId, int userId) throws Exception {
    String uri = String.format(
            _baseUri + "/LearningObjectService.svc/learningObjects/%s/instances/%s/Reports/%s",
            learningObjectId, instanceId, userId);
    PutMethod method = (PutMethod) getInitializedHttpMethod(_httpClient, uri, HttpMethodType.PUT);
    String reportAsXml = serializeLearningObjectInstanceUserReportToXML(userReport);
    InputStream is = new ByteArrayInputStream(reportAsXml.getBytes("UTF-8"));
    method.setRequestEntity(new InputStreamRequestEntity(is));
    try {/*from w  ww . j  a  v  a  2  s . c  o m*/
        int statusCode = _httpClient.executeMethod(method);
        // Put methods, may return 200, 201, 204
        if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED
                && statusCode != HttpStatus.SC_NOT_MODIFIED) {
            throw new HTTPException(statusCode);
        }

    } catch (Exception ex) {
        ExceptionHandler.handle(ex);
    } finally {
        method.releaseConnection();
    }
}

From source file:itslearning.platform.restapi.sdk.learningtoolapp.LearningObjectServicetRestClient.java

public void updateLearningObjectInstanceUserReportForCollaboration(LearningObjectInstanceUserReport userReport,
        int learningObjectId, int instanceId, int collaborationId) throws Exception {
    String uri = String.format(
            _baseUri + "/LearningObjectService.svc/learningObjects/%s/instances/%s/Collaborations/%s/Report",
            learningObjectId, instanceId, collaborationId);
    PutMethod method = (PutMethod) getInitializedHttpMethod(_httpClient, uri, HttpMethodType.PUT);
    String userReportAsXml = serializeLearningObjectInstanceUserReportToXML(userReport);
    InputStream is = new ByteArrayInputStream(userReportAsXml.getBytes("UTF-8"));
    method.setRequestEntity(new InputStreamRequestEntity(is));
    try {/*ww w .  j  a  v  a 2 s .com*/
        int statusCode = _httpClient.executeMethod(method);
        // Put methods, may return 200, 201, 204
        if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED
                && statusCode != HttpStatus.SC_NOT_MODIFIED) {
            throw new HTTPException(statusCode);
        }

    } catch (Exception ex) {
        ExceptionHandler.handle(ex);
    } finally {
        method.releaseConnection();
    }
}

From source file:itslearning.platform.restapi.sdk.learningtoolapp.LearningObjectServicetRestClient.java

public void updateLearningObjectiveCollaborationAssessments(int learningObjectId, int instanceId,
        int collaborationId, List<LearningObjectiveAssessment> assessments) throws Exception {
    String uri = String.format(_baseUri
            + "/LearningObjectService.svc/learningObjects/%s/instances/%s/LearningObjectiveCollaborationAssessments/%s",
            learningObjectId, instanceId, collaborationId);
    PutMethod method = (PutMethod) getInitializedHttpMethod(_httpClient, uri, HttpMethodType.PUT);

    String assessmentsAsXml = serializeLearningObjectiveAssessmentsToXml(assessments);
    InputStream is = new ByteArrayInputStream(assessmentsAsXml.getBytes("UTF-8"));
    method.setRequestEntity(new InputStreamRequestEntity(is));
    try {// w w  w.j  a  va  2s.c om
        int statusCode = _httpClient.executeMethod(method);
        // Put methods, may return 200, 201, 204
        if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED
                && statusCode != HttpStatus.SC_NOT_MODIFIED) {
            throw new HTTPException(statusCode);
        }
    } catch (Exception ex) {
        ExceptionHandler.handle(ex);
    } finally {
        method.releaseConnection();
    }
}

From source file:itslearning.platform.restapi.sdk.learningtoolapp.LearningObjectServicetRestClient.java

public void updateLearningObjectInstanceUserReportComment(
        LearningObjectInstanceUserReportCommentOnComment reportComment, int instanceId, int learningObjectId,
        int userId) throws Exception {
    String uri = String.format(
            _baseUri + "/LearningObjectService.svc/learningObjects/%s/instances/%s/Reports/%s/comments",
            learningObjectId, instanceId, userId);
    PutMethod method = (PutMethod) getInitializedHttpMethod(_httpClient, uri, HttpMethodType.PUT);
    String commentAsXml = serializeLearningObjectInstanceUserReportCommentOnCommentToXML(reportComment);
    InputStream is = new ByteArrayInputStream(commentAsXml.getBytes("UTF-8"));
    method.setRequestEntity(new InputStreamRequestEntity(is));
    try {//w  w w .java 2  s .  c o  m
        int statusCode = _httpClient.executeMethod(method);
        // Put methods, may return 200, 201, 204
        if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED
                && statusCode != HttpStatus.SC_NOT_MODIFIED) {
            throw new HTTPException(statusCode);
        }

    } catch (Exception ex) {
        ExceptionHandler.handle(ex);
    } finally {
        method.releaseConnection();
    }
}

From source file:itslearning.platform.restapi.sdk.learningtoolapp.LearningObjectServicetRestClient.java

public void updateLearningObjectInstanceUserReportCommentForCollaboration(
        LearningObjectInstanceUserReportCommentOnComment reportComment, int instanceId, int learningObjectId,
        int collaborationId) throws Exception {
    String uri = String.format(_baseUri
            + "/LearningObjectService.svc/learningObjects/%s/instances/%s/Collaborations/%s/Report/comments",
            learningObjectId, instanceId, collaborationId);
    PutMethod method = (PutMethod) getInitializedHttpMethod(_httpClient, uri, HttpMethodType.PUT);
    String commentAsXml = serializeLearningObjectInstanceUserReportCommentOnCommentToXML(reportComment);
    InputStream is = new ByteArrayInputStream(commentAsXml.getBytes("UTF-8"));
    method.setRequestEntity(new InputStreamRequestEntity(is));
    try {//w  w  w. jav a  2s . c  om
        int statusCode = _httpClient.executeMethod(method);
        // Put methods, may return 200, 201, 204
        if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED
                && statusCode != HttpStatus.SC_NOT_MODIFIED) {
            throw new HTTPException(statusCode);
        }

    } catch (Exception ex) {
        ExceptionHandler.handle(ex);
    } finally {
        method.releaseConnection();
    }
}