Example usage for org.apache.commons.httpclient.methods StringRequestEntity StringRequestEntity

List of usage examples for org.apache.commons.httpclient.methods StringRequestEntity StringRequestEntity

Introduction

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

Prototype

public StringRequestEntity(String paramString1, String paramString2, String paramString3)
  throws UnsupportedEncodingException

Source Link

Usage

From source file:com.salesmanager.core.module.impl.integration.payment.PsigateTransactionImpl.java

public GatewayTransactionVO refundTransaction(IntegrationKeys keys, IntegrationProperties props,
        MerchantStore store, Order order, GatewayTransactionVO trx, Customer customer, CoreModuleService cis,
        BigDecimal amount) throws TransactionException {

    // Get refundable transaction

    PostMethod httppost = null;// w  ww. ja va  2 s . c  o m

    try {

        String host = cis.getCoreModuleServiceProdDomain();
        String protocol = cis.getCoreModuleServiceProdProtocol();
        String port = cis.getCoreModuleServiceProdPort();
        String url = cis.getCoreModuleServiceProdEnv();
        if (props.getProperties2().equals(String.valueOf(PaymentConstants.TEST_ENVIRONMENT))) {
            host = cis.getCoreModuleServiceDevDomain();
            protocol = cis.getCoreModuleServiceDevProtocol();
            port = cis.getCoreModuleServiceDevPort();
            url = cis.getCoreModuleServiceDevEnv();
        }

        // String total = CurrencyUtil.getAmount(order.getTotal(),
        // order.getCurrency());
        String total = CurrencyUtil.getAmount(amount, order.getCurrency());

        HttpClient client = new HttpClient();

        String xml = "<?xml version=\"1.0\"?><AddressValidationRequest xml:lang=\"en-US\"><Request><TransactionReference><CustomerContext>SalesManager Data</CustomerContext><XpciVersion>1.0001</XpciVersion></TransactionReference><RequestAction>AV</RequestAction></Request>";
        StringBuffer xmldatabuffer = new StringBuffer();
        xmldatabuffer.append("<Order>");
        xmldatabuffer.append("<StoreID>").append(keys.getUserid()).append("</StoreID>");
        xmldatabuffer.append("<Passphrase>").append(keys.getTransactionKey()).append("</Passphrase>");
        xmldatabuffer.append("<PaymentType>").append("CC").append("</PaymentType>");

        // 0=Sale, 1=PreAuth, 2=PostAuth, 3=Credit, 4=Forced PostAuth

        xmldatabuffer.append("<CardAction>").append("3").append("</CardAction>");
        // For postauth only
        xmldatabuffer.append("<OrderID>").append(trx.getInternalGatewayOrderId()).append("</OrderID>");
        xmldatabuffer.append("<SubTotal>").append(total).append("</SubTotal>");
        xmldatabuffer.append("</Order>");
        /**
         * xmldatabuffer.append("<CardNumber>").append("").append(
         * "</CardNumber>");
         * xmldatabuffer.append("<CardExpMonth>").append(""
         * ).append("</CardExpMonth>");
         * xmldatabuffer.append("<CardExpYear>")
         * .append("").append("</CardExpYear>"); //CVV
         * xmldatabuffer.append("<CustomerIP>"
         * ).append("").append("</CustomerIP>");
         * xmldatabuffer.append("<CardIDNumber>"
         * ).append("").append("</CardIDNumber>");
         * xmldatabuffer.append("</Order>");
         **/

        log.debug("Psigate request " + xmldatabuffer.toString());

        httppost = new PostMethod(protocol + "://" + host + ":" + port + url);
        RequestEntity entity = new StringRequestEntity(xmldatabuffer.toString(), "text/plain", "UTF-8");
        httppost.setRequestEntity(entity);

        PsigateParsedElements pe = null;
        String stringresult = null;

        int result = client.executeMethod(httppost);
        if (result != 200) {
            log.error("Communication Error with psigate " + protocol + "://" + host + ":" + port + url);
            // throw new Exception("Psigate Gateway error ");
            TransactionException te = new TransactionException(
                    "Communication Error with psigate " + protocol + "://" + host + ":" + port + url);
            te.setErrorcode("01");
            throw te;
        }
        stringresult = httppost.getResponseBodyAsString();
        log.debug("Psigate response " + stringresult);

        pe = new PsigateParsedElements();
        Digester digester = new Digester();
        digester.push(pe);

        digester.addCallMethod("Result/OrderID", "setOrderID", 0);
        digester.addCallMethod("Result/Approved", "setApproved", 0);
        digester.addCallMethod("Result/ErrMsg", "setErrMsg", 0);
        digester.addCallMethod("Result/ReturnCode", "setReturnCode", 0);
        digester.addCallMethod("Result/TransRefNumber", "setTransRefNumber", 0);
        digester.addCallMethod("Result/CardType", "setCardType", 0);

        Reader reader = new StringReader(stringresult);

        digester.parse(reader);

        return this.parseResponse(PaymentConstants.REFUND, xmldatabuffer.toString(), stringresult, pe, order,
                amount);

    } catch (Exception e) {
        if (e instanceof TransactionException) {
            throw (TransactionException) e;
        }
        log.error(e);
        // throw new
        // Exception("Exception occured while calling Psigate gateway " +
        // e);
        TransactionException te = new TransactionException("Communication Error with psigate ", e);
        te.setErrorcode("01");
        throw te;
    } finally {
        if (httppost != null)
            httppost.releaseConnection();
    }

}

From source file:hoot.services.controllers.ogr.TranslatorResource.java

/**
 * <NAME>OGR-LTDS Translation Service Translate TDS to OSM</NAME>
 * <DESCRIPTION>//from www .jav a  2 s.  c om
 * WARNING: THIS END POINT WILL BE DEPRECATED SOON
 * Translate TDS to OSM
 *  http://localhost:8080/hoot-services/ogr/ltds/translate/tds/{OSM element id}?translation={translation script}
 * </DESCRIPTION>
 * <PARAMETERS>
 * <translation>
 *    relative path of translation script
 * </translation>
 * </PARAMETERS>
 * <OUTPUT>
 *    TDS output
 * </OUTPUT>
 * <EXAMPLE>
 *    <URL>http://localhost:8080/hoot-services/ogr/ltds/translate/-1669795?translation=MGCP.js</URL>
 *    <REQUEST_TYPE>POST</REQUEST_TYPE>
 *    <INPUT>
 * {"attrs":{"FCODE":"AP030","HCT":"0","UID":"d9c4b1df-066c-4ece-a583-76fec0056b58"},"tableName":"LAP030"}
 *   </INPUT>
 * <OUTPUT>OSM XML output</OUTPUT>
 * </EXAMPLE>
* @param id
* @param translation
* @param osmXml
* @return
*/
@POST
@Path("/ltds/translate/tds/{id}")
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.APPLICATION_JSON)
public Response translateTdsToOsm(@PathParam("id") String id,
        @QueryParam("translation") final String translation, String osmXml) {
    String outStr = "unknown";
    PostMethod mpost = new PostMethod("http://localhost:" + currentPort + "/tdstoosm");
    try {

        try {

            String ogrxml = osmXml.replace('"', '\'');

            JSONObject requestParams = new JSONObject();
            requestParams.put("command", "translate");
            requestParams.put("uid", id);
            requestParams.put("input", ogrxml);
            requestParams.put("script", homeFolder + "/translations" + translation);
            requestParams.put("direction", "toogr");
            String postData = requestParams.toJSONString();
            StringEntity se = new StringEntity(requestParams.toJSONString());
            StringRequestEntity requestEntity = new StringRequestEntity(requestParams.toJSONString(),
                    "text/plain", "UTF-8");
            mpost.setRequestEntity(requestEntity);

            mclient.executeMethod(mpost);
            String response = mpost.getResponseBodyAsString();

            JSONParser par = new JSONParser();
            JSONObject transRes = (JSONObject) par.parse(response);
            String tdsOSM = transRes.get("output").toString();
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            StringReader strReader = new StringReader(tdsOSM);
            InputSource is = new InputSource(strReader);

            Document document = builder.parse(is);
            strReader.close();

            JSONObject attrib = new JSONObject();
            NodeList nodeList = document.getDocumentElement().getChildNodes();
            for (int i = 0; i < nodeList.getLength(); i++) {
                Node node = nodeList.item(i);
                if (node instanceof Element) {
                    NodeList childNodes = node.getChildNodes();
                    for (int j = 0; j < childNodes.getLength(); j++) {
                        Node cNode = childNodes.item(j);
                        if (cNode instanceof Element) {
                            String k = ((Element) cNode).getAttribute("k");
                            String v = ((Element) cNode).getAttribute("v");
                            attrib.put(k, v);

                        }
                    }
                }
            }

            JSONObject ret = new JSONObject();
            ret.put("tablenName", "");
            ret.put("attrs", attrib);
            outStr = ret.toJSONString();

        } catch (Exception ee) {
            ResourceErrorHandler.handleError("Failed upload: " + ee.toString(), Status.INTERNAL_SERVER_ERROR,
                    log);
        } finally {
            log.debug("postJobRequest Closing");
            mpost.releaseConnection();
        }

    } catch (Exception e) {
        ResourceErrorHandler.handleError("Translation error: " + e.toString(), Status.INTERNAL_SERVER_ERROR,
                log);
    }

    return Response.ok(outStr, MediaType.APPLICATION_JSON).build();
}

From source file:flex.messaging.services.http.proxy.RequestFilter.java

/**
 * Send the request.//from  w  ww . ja  va2 s .c  o  m
 *
 * @param context the context
 */
protected void sendRequest(ProxyContext context) {
    Target target = context.getTarget();
    String method = context.getMethod();
    HttpMethod httpMethod = context.getHttpMethod();
    final String BEGIN = "-- Begin ";
    final String END = "-- End ";
    final String REQUEST = " request --";

    if (httpMethod instanceof EntityEnclosingMethod) {
        Object data = processBody(context);
        Class dataClass = data.getClass();
        if (data instanceof String) {
            String requestString = (String) data;
            if (Log.isInfo()) {
                Logger logger = Log.getLogger(HTTPProxyService.LOG_CATEGORY);
                logger.debug(BEGIN + method + REQUEST);
                logger.debug(StringUtils.prettifyString(requestString));
                logger.debug(END + method + REQUEST);
            }

            try {
                StringRequestEntity requestEntity = new StringRequestEntity(requestString, null, "UTF-8");
                ((EntityEnclosingMethod) httpMethod).setRequestEntity(requestEntity);
            } catch (UnsupportedEncodingException ex) {
                ProxyException pe = new ProxyException(CAUGHT_ERROR);
                pe.setDetails(CAUGHT_ERROR, "1", new Object[] { ex });
                throw pe;
            }
        } else if (dataClass.isArray() && Byte.TYPE.equals(dataClass.getComponentType())) {
            byte[] dataBytes = (byte[]) data;
            ByteArrayRequestEntity requestEntity = new ByteArrayRequestEntity(dataBytes,
                    context.getContentType());
            ((EntityEnclosingMethod) httpMethod).setRequestEntity(requestEntity);
        } else if (data instanceof InputStream) {
            InputStreamRequestEntity requestEntity = new InputStreamRequestEntity((InputStream) data,
                    context.getContentType());
            ((EntityEnclosingMethod) httpMethod).setRequestEntity(requestEntity);
        }
        //TODO: Support multipart post
        //else
        //{
        //FIXME: Throw exception if unhandled data type
        //}
    } else if (httpMethod instanceof GetMethod) {
        Object req = processBody(context);

        if (req instanceof String) {
            String requestString = (String) req;
            if (Log.isInfo()) {
                Logger logger = Log.getLogger(HTTPProxyService.LOG_CATEGORY);
                logger.debug(BEGIN + method + REQUEST);
                logger.debug(StringUtils.prettifyString(requestString));
                logger.debug(END + method + REQUEST);
            }

            if (!"".equals(requestString)) {
                String query = context.getHttpMethod().getQueryString();
                if (query != null) {
                    query += "&" + requestString;
                } else {
                    query = requestString;
                }
                context.getHttpMethod().setQueryString(query);
            }
        }
    }

    context.getHttpClient().setHostConfiguration(target.getHostConfig());

    try {
        context.getHttpClient().executeMethod(context.getHttpMethod());
    } catch (UnknownHostException uhex) {
        ProxyException pe = new ProxyException();
        pe.setMessage(UNKNOWN_HOST, new Object[] { uhex.getMessage() });
        pe.setCode(ProxyException.CODE_SERVER_PROXY_REQUEST_FAILED);
        throw pe;
    } catch (Exception ex) {
        // FIXME: JRB - could be more specific by looking for timeout and sending 504 in that case.
        // rfc2616 10.5.5 504 - could get more specific if we parse the HttpException
        ProxyException pe = new ProxyException(CAUGHT_ERROR);
        pe.setDetails(CAUGHT_ERROR, "1", new Object[] { ex.getMessage() });
        pe.setCode(ProxyException.CODE_SERVER_PROXY_REQUEST_FAILED);
        throw pe;
    }
}

From source file:com.ikanow.infinit.e.harvest.enrichment.legacy.opencalais.ExtractorOpenCalais.java

private PostMethod createPostMethod(String text) throws UnsupportedEncodingException {

    if (text.length() > MAX_LENGTH) {
        text = text.substring(0, MAX_LENGTH);
    }//w ww . j  a  va 2s. c  o  m
    PostMethod method = new PostMethod(CALAIS_URL);

    // Set mandatory parameters
    method.setRequestHeader("x-calais-licenseID", CALAIS_LICENSE.trim());

    // Set input content type
    method.setRequestHeader("Content-Type", "text/raw; charset=UTF-8");

    // Set response/output format
    method.setRequestHeader("Accept", "application/json");

    method.setRequestHeader("enableMetadataType", "GenericRelations");
    // Enable Social Tags processing
    method.setRequestEntity(new StringRequestEntity(text, "text/plain", "UTF-8"));
    return method;
}

From source file:com.evolveum.midpoint.model.impl.bulkmodify.PostXML.java

public int createUserForSelfRegistration(ModifyUserBean user) throws Exception {
    String returnString = "";
    int result = 0;
    // Get target URL
    String strURLBase = "http://localhost:8080/midpoint/ws/rest/users";
    String strURL = strURLBase;//from   w  w w  . ja  v  a 2s  .c o  m

    // Prepare HTTP post
    PostMethod post = new PostMethod(strURL);

    //AUTHENTICATION
    String userPass = this.getUsername() + ":" + this.getPassword();
    String basicAuth = "Basic "
            + javax.xml.bind.DatatypeConverter.printBase64Binary(userPass.getBytes("UTF-8"));
    post.addRequestHeader("Authorization", basicAuth);

    //construct searching string.
    String sendingXml = XML_TEMPLATE_CREATE_USER_SELFREGISTRATION;

    sendingXml = sendingXml.replace("<name></name>", "<name>" + user.getUserName() + "</name>");
    sendingXml = sendingXml.replace("<givenName></givenName>",
            "<givenName>" + user.getFirstname() + "</givenName>");
    sendingXml = sendingXml.replace("<familyName></familyName>",
            "<familyName>" + user.getSurname() + "</familyName>");
    sendingXml = sendingXml.replace("<emailAddress></emailAddress>",
            "<emailAddress>" + user.getEmail() + "</emailAddress>");
    sendingXml = sendingXml.replace("<telephoneNumber></telephoneNumber>",
            "<telephoneNumber>" + user.getPhoneNumber() + "</telephoneNumber>");
    sendingXml = sendingXml.replace("<administrativeStatus></administrativeStatus>",
            "<administrativeStatus>" + user.getStatus() + "</administrativeStatus>");

    RequestEntity userSearchEntity = new StringRequestEntity(sendingXml, "application/xml", "UTF-8");
    post.setRequestEntity(userSearchEntity);
    // Get HTTP client
    HttpClient httpclient = new HttpClient();
    // Execute request
    try {
        result = httpclient.executeMethod(post);
        // Display status code
        //System.out.println("Response status code: " + result);
        // Display response
        //System.out.println("Response body: ");
        // System.out.println(post.getResponseBodyAsString());
        //String sbf = new String(post.getResponseBodyAsString());
        //System.out.println(sbf);

    } finally {
        // Release current connection to the connection pool once you are done
        post.releaseConnection();
    }

    return result;
}

From source file:com.cubeia.backoffice.wallet.client.WalletServiceClientHTTP.java

@Override
public void addCurrency(Currency currency) {
    String uri = baseUrl + CURRENCIES;
    PostMethod method = createPostMethod(uri);

    try {/* w w w  .ja  va  2s .  co  m*/
        String data = serialize(currency);
        method.setRequestEntity(new StringRequestEntity(data, MIME_TYPE_JSON, DEFAULT_CHAR_ENCODING));

        // Execute the method.
        int statusCode = getClient().executeMethod(method);
        if (statusCode == HttpStatus.SC_NOT_FOUND) {
            return;
        }
        assertResponseCodeOK(method, statusCode);
    } catch (Exception e) {
        throw new RuntimeException("Failed adding currency via url " + uri, e);
    } finally {
        method.releaseConnection();
    }
}

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

@Override
public void run() {
    try {//w  ww .  j ava2 s . com
        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:edu.indiana.d2i.htrc.portal.HTRCPersistenceAPIClient.java

/**
 * Create workset//from ww  w  .j ava  2s . c o  m
 *
 * @param worksetContent , Give workset content as a String
 * @param isPublic
 */

public void createWorkset(String worksetContent, boolean isPublic) throws IOException {
    String url;

    if (isPublic) {
        url = PlayConfWrapper.registryEPR() + "/worksets" + "?public=true";
    } else {
        url = PlayConfWrapper.registryEPR() + "/worksets";
    }
    PostMethod post = new PostMethod(url);
    post.addRequestHeader("Authorization", "Bearer " + accessToken);
    post.setRequestEntity(new StringRequestEntity(worksetContent, "application/vnd.htrc-workset+xml", "UTF-8"));

    int response = client.executeMethod(post);
    if (response == 201) {
        // nothing
    } else {
        this.responseCode = response;
        throw new IOException(
                "Response code " + response + " for " + url + " message: \n " + post.getResponseBodyAsString());
    }
}

From source file:com.cubeia.backoffice.users.client.UserServiceClientHTTP.java

@Override
public void setUserAttribute(Long userId, String key, String value) {
    String resource = String.format(baseUrl + USER_ATTRIBUTES + "/" + key, userId);
    PutMethod method = new PutMethod(resource);
    try {//from w ww.ja v  a2 s . co m
        method.setRequestEntity(new StringRequestEntity(value, "text/plain", "UTF-8"));

        // Execute the HTTP Call
        int statusCode = getClient().executeMethod(method);
        if (statusCode == HttpStatus.SC_NOT_FOUND) {
            return;
        }
        assertResponseCodeOK(method, statusCode);

    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        method.releaseConnection();
    }
}

From source file:com.apifest.oauth20.tests.OAuth20BasicTest.java

public String updateScope(String scope, String description, Integer ccExpiresIn, Integer passExpiresIn) {
    PutMethod put = new PutMethod(baseOAuth20Uri + SCOPE_ENDPOINT + "/" + scope);
    String response = null;//from w w  w. j  a va  2s .  co  m
    try {
        JSONObject json = new JSONObject();
        json.put("description", description);
        json.put("cc_expires_in", ccExpiresIn);
        json.put("pass_expires_in", passExpiresIn);
        String requestBody = json.toString();
        RequestEntity requestEntity = new StringRequestEntity(requestBody, "application/json", "UTF-8");
        put.setRequestHeader(HttpHeaders.CONTENT_TYPE, "application/json");
        put.setRequestEntity(requestEntity);
        response = readResponse(put);
        log.info(response);
    } catch (IOException e) {
        log.error("cannot update scope", e);
    } catch (JSONException e) {
        log.error("cannot update scope", e);
    }
    return response;
}