Example usage for javax.servlet.http HttpServletRequest setCharacterEncoding

List of usage examples for javax.servlet.http HttpServletRequest setCharacterEncoding

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest setCharacterEncoding.

Prototype

public void setCharacterEncoding(String env) throws UnsupportedEncodingException;

Source Link

Document

Overrides the name of the character encoding used in the body of this request.

Usage

From source file:jp.or.openid.eiwg.scim.servlet.Users.java

/**
 * PUT?/*from   w  ww  .  j  ava2s  .c om*/
 *
 * @param request 
 * @param response ?
 * @throws ServletException
 * @throws IOException
 */
protected void doPut(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // ?
    ServletContext context = getServletContext();

    // ??
    Operation op = new Operation();
    boolean result = op.Authentication(context, request);

    if (!result) {
        // 
        errorResponse(response, op.getErrorCode(), op.getErrorType(), op.getErrorMessage());
    } else {
        // ?
        String targetId = request.getPathInfo();
        String attributes = request.getParameter("attributes");

        if (targetId != null && !targetId.isEmpty()) {
            // ?'/'???
            targetId = targetId.substring(1);
        }

        if (targetId != null && !targetId.isEmpty()) {
            // PUT(JSON)?
            request.setCharacterEncoding("UTF-8");
            String body = IOUtils.toString(request.getReader());

            // 
            LinkedHashMap<String, Object> resultObject = op.updateUserInfo(context, request, targetId,
                    attributes, body);
            if (resultObject != null) {
                // javaJSON??
                ObjectMapper mapper = new ObjectMapper();
                StringWriter writer = new StringWriter();
                mapper.writeValue(writer, resultObject);

                // Location?URL?
                String location = request.getScheme() + "://" + request.getServerName();
                int serverPort = request.getServerPort();
                if (serverPort != 80 && serverPort != 443) {
                    location += ":" + Integer.toString(serverPort);
                }
                location += request.getContextPath();
                location += "/scim/Users/";
                if (resultObject.get("id") != null) {
                    location += resultObject.get("id").toString();
                }

                // ??
                response.setStatus(HttpServletResponse.SC_OK);
                response.setContentType("application/scim+json;charset=UTF-8");
                response.setHeader("Location", location);

                PrintWriter out = response.getWriter();
                out.println(writer.toString());
            } else {
                // 
                errorResponse(response, op.getErrorCode(), op.getErrorType(), op.getErrorMessage());
            }
        } else {
            errorResponse(response, HttpServletResponse.SC_BAD_REQUEST, null,
                    MessageConstants.ERROR_NOT_SUPPORT_OPERATION);
        }
    }
}

From source file:com.megaeyes.web.controller.VISController.java

@ControllerDescription(description = "?", isLog = true, isCheckSession = true)
@RequestMapping("/batchCreateVIS.json")
public void createVIS(HttpServletRequest request, HttpServletResponse response)
        throws UnsupportedEncodingException {
    // System.out.println("In CreateVISJsonServlet ...");
    request.setCharacterEncoding("UTF-8");
    BaseResponse resp = new BaseResponse();
    resp.setCode(ErrorCode.SUCCESS);//w  w  w.  j ava2 s . c  om
    String name = (String) request.getAttribute("name");
    String deviceNumber = (String) request.getAttribute("deviceNumber");
    String installLocation = (String) request.getAttribute("location");
    String ip = (String) request.getAttribute("ip");
    String linkType = (String) request.getAttribute("linkType");
    String hc = (String) request.getAttribute("heartCycle");
    String password = (String) request.getAttribute("password");
    Long heartCycle = null;
    if (StringUtils.isNotBlank(hc)) {
        try {
            heartCycle = Long.parseLong(hc);
        } catch (NumberFormatException e) {
            resp.setCode(ErrorCode.PARAMETER_VALUE_INVALIDED);
            resp.setMessage("heartCycle");
        }
    }
    String rebootTime = (String) request.getAttribute("rebootTime");

    String rc = (String) request.getAttribute("rebootCycle");
    Long rebootCycle = null;
    if (StringUtils.isNotBlank(rc)) {
        try {
            rebootCycle = Long.parseLong(rc);
        } catch (NumberFormatException e) {
            resp.setCode(ErrorCode.PARAMETER_VALUE_INVALIDED);
            resp.setMessage("rebootCycle");
        }
    }
    String mca = (String) request.getAttribute("maxConnectAmount");
    Long maxConnectAmount = null;
    if (StringUtils.isNotBlank(mca)) {
        try {
            maxConnectAmount = Long.parseLong(mca);
        } catch (NumberFormatException e) {
            resp.setCode(ErrorCode.PARAMETER_VALUE_INVALIDED);
            resp.setMessage("maxConnectAmount");
        }
    }
    String videoInputServerModelId = request.getParameter("videoInputServerModelId");
    String organId = (String) request.getAttribute("organId");
    String iss = (String) request.getAttribute("isSupportScheme");
    Short isSupportScheme = null;
    if (StringUtils.isNotBlank(iss)) {
        try {
            isSupportScheme = Short.parseShort(iss);
        } catch (NumberFormatException e) {
            resp.setCode(ErrorCode.PARAMETER_VALUE_INVALIDED);
            resp.setMessage("isSupportScheme");
        }
    }
    String note = (String) request.getAttribute("note");
    String type = (String) request.getAttribute("type");
    String sipCode = (String) request.getAttribute("sipCode");
    String longitude = (String) request.getAttribute("longitude");
    String latitude = (String) request.getAttribute("latitude");
    if (resp.getCode().equals(ErrorCode.SUCCESS)) {
        try {
            String id = vISManager.createVIS(name, deviceNumber, installLocation, ip, linkType, heartCycle,
                    rebootTime, rebootCycle, maxConnectAmount, videoInputServerModelId, organId,
                    isSupportScheme, note, type, sipCode, longitude, latitude, password);
            resp.setMessage(id);
        } catch (BusinessException be) {
            resp.setCode(be.getCode());
            resp.setMessage(be.getMessage());
        }
    }
    // 
    writePageNoZip(response, resp);
}

From source file:com.hp.action.ProductsAction.java

public String editProduct() throws UnsupportedEncodingException {
    HttpServletRequest request = (HttpServletRequest) ActionContext.getContext()
            .get(ServletActionContext.HTTP_REQUEST);
    HttpSession session = request.getSession();

    //Authorize/*from ww w .  ja  v a  2s.  c  o m*/
    if (!userDAO.authorize((String) session.getAttribute("user_name"),
            (String) session.getAttribute("user_password"))) {
        return LOGIN;
    }

    //request.setCharacterEncoding("UTF-8");
    providerIDList = providerDAO.getProvidersIDList();

    request.setCharacterEncoding("UTF8");

    String stt = request.getParameter("id_product");
    int st;
    if (stt == null) {
        return INPUT;
    }
    st = Integer.parseInt(stt);

    productsList = productDAO.getProductList();
    product = productDAO.loadProduct(st);

    return SUCCESS;
}

From source file:kbSRU.kbSRU.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType(XML_RESPONSE_HEADER); // Talkback happens in XML form.
    response.setCharacterEncoding("UTF-8"); // Unicode++
    request.setCharacterEncoding("UTF-8");

    PrintWriter out = null; // The talkback buffer.

    // handle startrecord 
    Integer startRecord = 0;/*from  w  ww.  j ava  2  s . com*/

    if (!(request.getParameter("startRecord") == null)) {
        try {
            startRecord = Integer.parseInt(request.getParameter("startRecord")) - 1;
        } catch (NumberFormatException e) {
            startRecord = 0;
        }
    }

    // maximumrecords
    Integer maximumRecords = Integer.parseInt(this.config.getProperty("default_maximumRecords"));
    if (!(request.getParameter("maximumRecords") == null)) {
        maximumRecords = Integer.parseInt(request.getParameter("maximumRecords"));
    }

    // operation 
    String operation = request.getParameter("operation");

    // x_collection
    String x_collection = request.getParameter("x-collection");
    if (x_collection == null)
        x_collection = this.config.getProperty("default_x_collection");
    if (x_collection == null)
        operation = null;

    // sortkeys
    String sortKeys = request.getParameter("sortKeys");

    // sortorder
    String sortOrder = request.getParameter("sortOrder");

    // recordschema 
    String recordSchema = request.getParameter("recordSchema");
    if (recordSchema == null)
        recordSchema = "dc";

    if (recordSchema.equalsIgnoreCase("dcx")) {
        recordSchema = "dcx";
    }

    if (recordSchema.equalsIgnoreCase("solr")) {
        recordSchema = "solr";
    }

    // query request 
    String query = request.getParameter("query");
    String q = request.getParameter("q");

    // who is requestor ?
    String remote_ip = request.getHeader("X-FORWARDED-FOR");

    if (remote_ip == null) {
        remote_ip = request.getRemoteAddr().trim();
    } else {
        remote_ip = request.getHeader("X-FORWARDED-FOR");
    }

    // handle debug 
    Boolean debug = Boolean.parseBoolean(request.getParameter("debug"));
    if (!debug) {
        out = new PrintWriter(new OutputStreamWriter(response.getOutputStream(), "UTF8"), true);
    }

    // handle query
    if ((query == null) && (q != null)) {
        query = q;
    } else {
        if ((query != null) && (q == null)) {
            q = query;
        } else {
            operation = null;
        }
    }

    // handle operation
    if (operation == null) {
        if (query != null) {
            operation = "searchRetrieve";
        } else {
            operation = "explain";
        }
    }

    //  searchRetrieve 
    if (operation.equalsIgnoreCase("searchRetrieve")) {
        if (query == null) {
            operation = "explain";
            log.debug(operation + ":" + query);
        }
    }

    // start talking back.
    String[] sq = { "" };
    String solrquery = "";

    // facet

    String facet = null;
    List<FacetField> fct = null;

    if (request.getParameter("facet") != null) {
        facet = request.getParameter("facet");
        log.debug("facet : " + facet);
    }

    if (operation == null) {
        operation = "searchretrieve";
    } else { // explain response
        if (operation.equalsIgnoreCase("explain")) {
            log.debug("operation = explain");
            out.write("<srw:explainResponse xmlns:srw=\"http://www.loc.gov/zing/srw/\">");
            out.write("</srw:explainResponse>");
        } else { // DEBUG routine
            operation = "searchretrieve";

            String triplequery = null;

            if (query.matches(".*?\\[.+?\\].*?")) { // New symantic syntax
                triplequery = symantic_query(query);
                query = query.split("\\[")[0] + " " + triplequery;
                log.fatal(triplequery);

                solrquery = CQLtoLucene.translate(query, log, config);
            } else {
                solrquery = CQLtoLucene.translate(query, log, config);
            }
            log.debug(solrquery);

            if (debug == true) {
                response.setContentType(HTML_RESPONSE_HEADER);
                out = new PrintWriter(new OutputStreamWriter(response.getOutputStream(), "UTF8"), true);
                out.write("<html><body>\n\n");
                out.write("'" + remote_ip + "'<br>\n");
                out.write("<form action='http://www.kbresearch.nl/kbSRU'>");
                out.write("<input type=text name=q value='" + query + "' size=120>");
                out.write("<input type=hidden name=debug value=True>");
                out.write("<input type=submit>");
                out.write("<table border=1><tr><td>");
                out.write("q</td><td>" + query + "</td></tr><tr>");
                out.write("<td>query out</td><td>" + URLDecoder.decode(solrquery) + "</td></tr>");
                out.write("<tr><td>SOLR_URL</td><td> <a href='"
                        + this.config.getProperty("collection." + x_collection.toLowerCase() + ".solr_baseurl")
                        + "/?q=" + solrquery + "'>"
                        + this.config.getProperty("collection." + x_collection.toLowerCase() + ".solr_baseurl")
                        + "/select/?q=" + solrquery + "</a><br>" + this.config.getProperty("solr_url")
                        + solrquery + "</td></tr>");
                out.write("<b>SOLR_QUERY</b> : <BR> <iframe width=900 height=400 src='"
                        + this.config.getProperty("collection." + x_collection.toLowerCase() + ".solr_baseurl")
                        + "/../?q=" + solrquery + "'></iframe><BR>");
                out.write("<b>SRU_QUERY</b> : <BR> <a href=" + this.config.getProperty("baseurl") + "?q="
                        + query + "'>" + this.config.getProperty("baseurl") + "?q=" + query
                        + "</a><br><iframe width=901 height=400 src='http://www.kbresearch.nl/kbSRU/?q=" + query
                        + "'></iframe><BR>");
                out.write("<br><b>JSRU_QUERY</b> : <BR><a href='http://jsru.kb.nl/sru/?query=" + query
                        + "&x-collection=" + x_collection + "'>http://jsru.kb.nl/sru/?query=" + query
                        + "&x-collection=GGC</a><br><iframe width=900 height=400 src='http://jsru.kb.nl/sru/?query="
                        + query + "&x-collection=GGC'></iframe>");

            } else { // XML SearchRetrieve response
                String url = this.config
                        .getProperty("collection." + x_collection.toLowerCase() + ".solr_baseurl");
                String buffer = "";
                CommonsHttpSolrServer server = null;
                server = new CommonsHttpSolrServer(url);
                log.fatal("URSING " + url);
                server.setParser(new XMLResponseParser());
                int numfound = 0;
                try {
                    SolrQuery do_query = new SolrQuery();
                    do_query.setQuery(solrquery);
                    do_query.setRows(maximumRecords);
                    do_query.setStart(startRecord);

                    if ((sortKeys != null) && (sortKeys.length() > 1)) {
                        if (sortOrder != null) {
                            if (sortOrder.equals("asc")) {
                                do_query.setSortField(sortKeys, SolrQuery.ORDER.asc);
                            }
                            if (sortOrder.equals("desc")) {
                                do_query.setSortField(sortKeys, SolrQuery.ORDER.desc);
                            }
                        } else {
                            for (String str : sortKeys.trim().split(",")) {
                                str = str.trim();
                                if (str.length() > 1) {
                                    if (str.equals("date")) {
                                        do_query.setSortField("date_date", SolrQuery.ORDER.desc);
                                        log.debug("SORTORDERDEBUG | DATE! " + str + " | ");
                                        break;
                                    } else {
                                        do_query.setSortField(str + "_str", SolrQuery.ORDER.asc);
                                        log.debug("SORTORDERDEBUG | " + str + " | ");
                                        break;
                                    }
                                }
                            }
                        }
                    }

                    if (facet != null) {
                        if (facet.indexOf(",") > 1) {
                            for (String str : facet.split(",")) {
                                if (str.indexOf("date") > 1) {
                                    do_query.addFacetField(str);
                                } else {
                                    do_query.addFacetField(str);
                                }
                                //do_query.setParam("facet.method", "enum");
                            }
                            //q.setFacetSort(false); 
                        } else {
                            do_query.addFacetField(facet);
                        }
                        do_query.setFacet(true);
                        do_query.setFacetMinCount(1);
                        do_query.setFacetLimit(-1);
                    }

                    log.fatal(solrquery);

                    QueryResponse rsp = null;
                    boolean do_err = false;
                    boolean do_sugg = false;
                    SolrDocumentList sdl = null;
                    String diag = "";
                    StringBuffer suggest = new StringBuffer("");

                    String content = "1";

                    SolrQuery spellq = do_query;
                    try {
                        rsp = server.query(do_query);
                    } catch (SolrServerException e) {
                        String header = this.SRW_HEADER.replaceAll("\\$numberOfRecords", "0");
                        out.write(header);
                        diag = this.SRW_DIAG.replaceAll("\\$error", e.getMessage());
                        do_err = true;
                        rsp = null;
                    }

                    log.fatal("query done..");
                    if (!(do_err)) { // XML dc response

                        SolrDocumentList docs = rsp.getResults();
                        numfound = (int) docs.getNumFound();
                        int count = startRecord;
                        String header = this.SRW_HEADER.replaceAll("\\$numberOfRecords",
                                Integer.toString(numfound));
                        out.write(header);
                        out.write("<srw:records>");

                        Iterator<SolrDocument> iter = rsp.getResults().iterator();

                        while (iter.hasNext()) {
                            count += 1;
                            if (recordSchema.equalsIgnoreCase("dc")) {
                                SolrDocument resultDoc = iter.next();
                                content = (String) resultDoc.getFieldValue("id");
                                out.write("<srw:record>");
                                out.write("<srw:recordPacking>xml</srw:recordPacking>");
                                out.write("<srw:recordSchema>info:srw/schema/1/dc-v1.1</srw:recordSchema>");
                                out.write(
                                        "<srw:recordData xmlns:srw_dc=\"info:srw/schema/1/dc-v1.1\" xmlns:mods=\"http://www.loc.gov/mods\" xmlns:dcterms=\"http://purl.org/dc/terms/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:dcx=\"http://krait.kb.nl/coop/tel/handbook/telterms.html\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:marcrel=\"http://www.loc.gov/loc.terms/relators/OTH\" xmlns:facets=\"info:srw/extension/4/facets\" >");
                                StringBuffer result = new StringBuffer("");

                                construct_lucene_dc(result, resultDoc);

                                out.write(result.toString());
                                out.write("</srw:recordData>");
                                out.write("<srw:recordPosition>" + Integer.toString(count)
                                        + "</srw:recordPosition>");
                                out.write("</srw:record>");
                            }

                            if (recordSchema.equalsIgnoreCase("solr")) {
                                SolrDocument resultDoc = iter.next();
                                content = (String) resultDoc.getFieldValue("id");
                                out.write("<srw:record>");
                                out.write("<srw:recordPacking>xml</srw:recordPacking>");
                                out.write("<srw:recordSchema>info:srw/schema/1/solr</srw:recordSchema>");
                                out.write("<srw:recordData xmlns:expand=\"http://www.kbresearch.nl/expand\">");
                                StringBuffer result = new StringBuffer("");
                                construct_lucene_solr(result, resultDoc);
                                out.write(result.toString());

                                out.write("</srw:recordData>");
                                out.write("<srw:recordPosition>" + Integer.toString(count)
                                        + "</srw:recordPosition>");
                                out.write("</srw:record>");
                            }

                            if (recordSchema.equalsIgnoreCase("dcx")) { // XML dcx response
                                out.write("<srw:record>");
                                out.write("<srw:recordPacking>xml</srw:recordPacking>");
                                out.write("<srw:recordSchema>info:srw/schema/1/dc-v1.1</srw:recordSchema>");
                                out.write(
                                        "<srw:recordData><srw_dc:dc xmlns:srw_dc=\"info:srw/schema/1/dc-v1.1\" xmlns:mods=\"http://www.loc.gov/mods\" xmlns:dcterms=\"http://purl.org/dc/terms/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:dcx=\"http://krait.kb.nl/coop/tel/handbook/telterms.html\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:marcrel=\"http://www.loc.gov/marc.relators/\" xmlns:expand=\"http://www.kbresearch.nl/expand\" xmlns:skos=\"http://www.w3.org/2004/02/skos/core#\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" >");
                                SolrDocument resultDoc = iter.next();
                                content = (String) resultDoc.getFieldValue("id");

                                String dcx_data = helpers.getOAIdcx(
                                        "http://services.kb.nl/mdo/oai?verb=GetRecord&identifier=" + content,
                                        log);
                                if (x_collection.equalsIgnoreCase("ggc-thes")) {
                                    dcx_data = helpers.getOAIdcx(
                                            "http://serviceso.kb.nl/mdo/oai?verb=GetRecord&identifier="
                                                    + content,
                                            log);
                                }

                                if (!(dcx_data.length() == 0)) {
                                    out.write(dcx_data);
                                } else {
                                    // Should not do this!!

                                    out.write("<srw:record>");
                                    out.write("<srw:recordPacking>xml</srw:recordPacking>");
                                    out.write("<srw:recordSchema>info:srw/schema/1/dc-v1.1</srw:recordSchema>");
                                    out.write(
                                            "<srw:recordData xmlns:srw_dc=\"info:srw/schema/1/dc-v1.1\" xmlns:mods=\"http://www.loc.gov/mods\" xmlns:dcterms=\"http://purl.org/dc/terms/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:dcx=\"http://krait.kb.nl/coop/tel/handbook/telterms.html\" xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:marcrel=\"http://www.loc.gov/loc.terms/relators/OTH\" >");
                                    StringBuffer result = new StringBuffer("");

                                    construct_lucene_dc(result, resultDoc);

                                    out.write(result.toString());
                                    out.write("</srw:recordData>");
                                    out.write("<srw:recordPosition>" + Integer.toString(count)
                                            + "</srw:recordPosition>");
                                    out.write("</srw:record>");

                                }

                                out.write("</srw_dc:dc>");

                                StringBuffer expand_data;
                                boolean expand = false;

                                if (content.startsWith("GGC-THES:AC:")) {
                                    String tmp_content = "";
                                    tmp_content = content.replaceFirst("GGC-THES:AC:", "");
                                    log.fatal("calling get");
                                    expand_data = new StringBuffer(
                                            helpers.getExpand("http://www.kbresearch.nl/general/lod_new/get/"
                                                    + tmp_content + "?format=rdf", log));
                                    log.fatal("get finini");

                                    if (expand_data.toString().length() > 4) {

                                        out.write(
                                                "<srw_dc:expand xmlns:srw_dc=\"info:srw/schema/1/dc-v1.1\" xmlns:expand=\"http://www.kbresearch.nl/expand\" xmlns:skos=\"http://www.w3.org/2004/02/skos/core#\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" >");
                                        out.write(expand_data.toString());
                                        expand = true;
                                    }
                                } else {
                                    expand_data = new StringBuffer(helpers
                                            .getExpand("http://www.kbresearch.nl/ANP.cgi?q=" + content, log));
                                    if (expand_data.toString().length() > 0) {
                                        if (!expand) {
                                            out.write(
                                                    "<srw_dc:expand xmlns:srw_dc=\"info:srw/schema/1/dc-v1.1\" xmlns:expand=\"http://www.kbresearch.nl/expand\" xmlns:skos=\"http://www.w3.org/2004/02/skos/core#\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" >");
                                            expand = true;
                                        }
                                        out.write(expand_data.toString());
                                    }
                                }
                                if (expand) {
                                    out.write("</srw_dc:expand>");
                                }

                                out.write("</srw:recordData>");
                                out.write("<srw:recordPosition>" + Integer.toString(count)
                                        + "</srw:recordPosition>");
                                out.write("</srw:record>");
                            }
                        }
                    }

                    if ((do_err) || (numfound == 0)) {
                        log.fatal("I haz suggestions");

                        try {
                            spellq.setParam("spellcheck", true);
                            spellq.setQueryType("/spell");
                            server = new CommonsHttpSolrServer(url);
                            rsp = server.query(spellq);
                            sdl = rsp.getResults();
                            SpellCheckResponse spell;
                            spell = rsp.getSpellCheckResponse();
                            List<SpellCheckResponse.Suggestion> suggestions = spell.getSuggestions();
                            if (suggestions.isEmpty() == false) {
                                suggest.append("<srw:extraResponseData>");
                                suggest.append("<suggestions>");

                                for (SpellCheckResponse.Suggestion sugg : suggestions) {
                                    suggest.append("<suggestionfor>" + sugg.getToken() + "</suggestionfor>");
                                    for (String item : sugg.getSuggestions()) {
                                        suggest.append("<suggestion>" + item + "</suggestion>");
                                    }
                                    suggest.append("</suggestions>");
                                    suggest.append("</srw:extraResponseData>");
                                }
                                do_sugg = true;
                            }
                        } catch (Exception e) {
                            rsp = null;
                            //log.fatal(e.toString());
                        }
                        ;
                    }
                    ;

                    if (!do_err) {
                        if (facet != null) {

                            try {
                                fct = rsp.getFacetFields();
                                out.write("<srw:facets>");

                                for (String str : facet.split(",")) {
                                    out.write("<srw:facet>");
                                    out.write("<srw:facetType>");
                                    out.write(str);
                                    out.write("</srw:facetType>");

                                    for (FacetField f : fct) {
                                        log.debug(f.getName());
                                        //if (f.getName().equals(str+"_str") || (f.getName().equals(str+"_date")) ) {
                                        List<FacetField.Count> facetEnties = f.getValues();
                                        for (FacetField.Count fcount : facetEnties) {
                                            out.write("<srw:facetValue>");
                                            out.write("<srw:valueString>");
                                            out.write(helpers.xmlEncode(fcount.getName()));
                                            out.write("</srw:valueString>");
                                            out.write("<srw:count>");
                                            out.write(Double.toString(fcount.getCount()));
                                            out.write("</srw:count>");
                                            out.write("</srw:facetValue>");
                                            //   }
                                        }

                                    }
                                    out.write("</srw:facet>");
                                }
                                out.write("</srw:facets>");
                                startRecord += 1;
                            } catch (Exception e) {
                            }

                            //log.fatal(e.toString()); }
                        }
                    } else {
                        out.write(diag);
                    }
                    out.write("</srw:records>"); // SearchRetrieve response footer
                    String footer = this.SRW_FOOTER.replaceAll("\\$query", helpers.xmlEncode(query));
                    footer = footer.replaceAll("\\$startRecord", (startRecord).toString());
                    footer = footer.replaceAll("\\$maximumRecords", maximumRecords.toString());
                    footer = footer.replaceAll("\\$recordSchema", recordSchema);
                    if (do_sugg) {
                        out.write(suggest.toString());
                    }
                    out.write(footer);
                } catch (MalformedURLException e) {
                    out.write(e.getMessage());
                } catch (IOException e) {
                    out.write("TO ERR is Human");
                }
            }
        }
    }
    out.close();
}

From source file:org.compiere.mobile.WWindow.java

/**
 *    Update Field Values from Parameter
 *   @param request request//  w  ww. ja  va 2  s .  c  om
 *   @param wsc session context
 *   @param ws window status
 *   @return true if error
 */
private boolean updateFields(HttpServletRequest request, MobileSessionCtx wsc, WWindowStatus ws) {
    boolean error = false;
    try {
        String enc = request.getCharacterEncoding();
        if (enc == null)
            request.setCharacterEncoding(MobileEnv.ENCODING);
    } catch (Exception e) {
        log.log(Level.SEVERE, "Set CharacterEncoding=" + MobileEnv.ENCODING, e);
    }
    //  loop through parameters
    Enumeration en = request.getParameterNames();
    while (en.hasMoreElements()) {
        String key = (String) en.nextElement();
        //  ignore hidden commands
        if (key.equals(P_Command) || key.equals(P_ChangedColumn) || key.equals(P_MR_RowNo) || key.equals(P_Tab))
            continue;
        GridField mField = ws.curTab.getField(key);
        //   log.fine("executeSave - Key=" + key + " - " + mField);
        //  we found a writable field
        if (mField != null && mField.isEditable(true)) {
            String oldValue = MobileUtil.getParameter(request, key);
            String newValue = MobileUtil.getParameter(request, key + "F");
            String value = null;
            if (newValue != null) {
                Object val = lookupValue(newValue, mField.getLookup());
                if (val != null)
                    value = val.toString();
            }
            if (value == null)
                value = oldValue;

            Object dbValue = mField.getValue();
            boolean fieldError = false;
            String columnName = mField.getColumnName();
            log.finest(columnName + ": " + (dbValue == null ? "null" : dbValue.toString()) + " -> "
                    + (value == null ? "null" : value.toString()));
            //  same = both null
            if (dbValue == null && value == null)
                continue;
            //   new value null
            else if (dbValue != null && value == null)
                ws.curTab.setValue(mField, null);
            //  from null to new value
            else if (dbValue == null && value != null)
                fieldError = !setFieldValue(wsc, ws, mField, value);
            //  same
            else if (dbValue.equals(value))
                continue;
            else
                fieldError = !setFieldValue(wsc, ws, mField, value);
            //
            if (!error && fieldError) {
                log.info("Error: " + mField.getColumnName());
                error = true;
            }
        }
    } //  for all parameters

    //   Re-Do Changed Column to overwrite
    /*String columnName = WebUtil.getParameter (request, P_ChangedColumn);
    if (columnName != null && columnName.length() > 0)
    {
       GridField mField = ws.curTab.getField(columnName);
       if (mField != null)
       {
    String value = WebUtil.getParameter(request, columnName);
    Object newValue = getFieldValue (wsc, mField, value);
    if (!ERROR.equals(newValue))
    {
       //   De-Selected Check Boxes are null 
       if (newValue == null && mField.getDisplayType() == DisplayType.YesNo)
          newValue = "N";
       log.fine("ChangedColumn: " + columnName + "=" + newValue);
       ws.curTab.setValue(mField, newValue);
    }
       }
    }*/
    return error;
}

From source file:org.apache.nutch.searcher.OpenSearchServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    //if (NutchBean.LOG.isInfoEnabled()) {
    LOG.debug("query request from " + request.getRemoteAddr());
    //}/* w ww.ja  va 2  s .c o  m*/

    Calendar DATE_END = new GregorianCalendar();
    DATE_END.set(Calendar.YEAR, DATE_END.get(Calendar.YEAR));
    DATE_END.set(Calendar.MONTH, 12 - 1);
    DATE_END.set(Calendar.DAY_OF_MONTH, 31);
    DATE_END.set(Calendar.HOUR_OF_DAY, 23);
    DATE_END.set(Calendar.MINUTE, 59);
    DATE_END.set(Calendar.SECOND, 59);
    String dateEndString = FORMAT.format(DATE_END.getTime());

    // get parameters from request
    request.setCharacterEncoding("UTF-8");

    String queryString = request.getParameter("query");

    if (queryString == null)
        queryString = "";

    String urlQuery = URLEncoder.encode(queryString, "UTF-8");
    urlQuery = URLEncoder.encode(queryString, "UTF-8");
    // the query language
    String queryLang = request.getParameter("lang");

    // first hit to display
    int start = 0;
    String startString = request.getParameter("start");
    if (startString != null)
        start = Integer.parseInt(startString);

    // number of hits to display
    int hitsPerPage = 10;
    String hitsString = request.getParameter("hitsPerPage");
    if (hitsString != null)
        hitsPerPage = Integer.parseInt(hitsString);

    String sort = request.getParameter("sort");
    boolean reverse = sort != null && "true".equals(request.getParameter("reverse"));

    // De-Duplicate handling.  Look for duplicates field and for how many
    // duplicates per results to return. Default duplicates field is 'site'
    // and duplicates per results default is '2'.
    String dedupField = request.getParameter("dedupField");
    if (dedupField == null || dedupField.length() == 0) {
        dedupField = "site";
    }
    int hitsPerDup = 2;
    String hitsPerDupString = request.getParameter("hitsPerDup");
    if (hitsPerDupString != null && hitsPerDupString.length() > 0) {
        hitsPerDup = Integer.parseInt(hitsPerDupString);
    } else {
        // If 'hitsPerSite' present, use that value.
        String hitsPerSiteString = request.getParameter("hitsPerSite");
        if (hitsPerSiteString != null && hitsPerSiteString.length() > 0) {
            hitsPerDup = Integer.parseInt(hitsPerSiteString);
        }
    }

    // date restriction   
    String dateStart = request.getParameter("dtstart");
    if (dateStart == null || dateStart.length() == 0) {
        dateStart = null;
    }
    String dateEnd = request.getParameter("dtend");
    if (dateEnd == null || dateEnd.length() == 0) {
        dateEnd = null;
    }
    if (dateStart != null && dateEnd != null) {
        try {
            Date dStart = RFC3339Date.parseRFC3339Date(dateStart);
            Date dEnd = RFC3339Date.parseRFC3339Date(dateEnd);

            DateFormat dOutputFormat = new SimpleDateFormat("yyyyMMddHHmmss");
            queryString += " date:" + dOutputFormat.format(dStart.getTime()) + "-"
                    + dOutputFormat.format(dEnd.getTime());
        } catch (ParseException e) {
            // ignore
        } catch (IndexOutOfBoundsException e) {
            // ignore
        }
    }

    // wayback parameters
    boolean multipleDetails = request.getParameter("multDet") != null
            && request.getParameter("multDet").equals("true"); // indicates that it requests multiple details instead of one at the time
    String sId = request.getParameter("id");
    String sIndex = request.getParameter("index");
    boolean waybackQuery = request.getParameter("waybackQuery") != null
            && request.getParameter("waybackQuery").equals("true"); // indicates that is a wayback request

    // To support querying opensearch by  url
    // Lucene index format
    String queryStringOpensearchWayback = null;
    boolean isOpensearhWayback = false;
    int urlLength = queryString.length();
    boolean urlMatch = false;
    urlMatch = URL_PATTERN.matcher(queryString.toString()).matches();
    String urlQueryParam = null;

    if (!waybackQuery && urlMatch && !queryString.contains("site:")) {
        if (!queryString.startsWith("http://") && !queryString.startsWith("https://")) {
            urlQueryParam = "http://" + queryString;
        } else
            urlQueryParam = queryString;

        String s = "date:19960101000000-" + dateEndString + " exacturlexpand:" + urlQueryParam;
        queryStringOpensearchWayback = request.getParameter(s);
        isOpensearhWayback = true;
    } else if (queryString.contains("site:")) {// if it contains site: is also a full-text search
        hitsPerDup = 0;
        queryString = queryString.replaceAll("site:http://", "site:");
        queryString = queryString.replaceAll("site:https://", "site:");
    }
    // Make up query string for use later drawing the 'rss' logo.
    String params = "&hitsPerPage=" + hitsPerPage + (queryLang == null ? "" : "&lang=" + queryLang)
            + (sort == null ? ""
                    : "&sort=" + sort + (reverse ? "&reverse=true" : "")
                            + (dedupField == null ? "" : "&dedupField=" + dedupField))
            + (multipleDetails == false ? "" : "&multDet=true") + (sId == null ? "" : "&id=" + sId)
            + (sIndex == null ? "" : "&index=" + sIndex) + (waybackQuery == false ? "" : "&waybackQuery=true");

    Hits hits;
    if (sId != null && sIndex != null) { // only want the details of this document with this id in this index
        Hit[] oneHit = new Hit[1];
        oneHit[0] = new Hit(Integer.parseInt(sIndex), Integer.parseInt(sId));
        hits = new Hits(1, oneHit);
    } else { // search hits
        Query query = null;
        if (isOpensearhWayback) {
            query = Query.parse(queryStringOpensearchWayback, queryLang, this.conf);
            LOG.debug("query: " + queryStringOpensearchWayback);
            sort = "relevance";
        } else {
            query = Query.parse(queryString, queryLang, this.conf);
            LOG.debug("query: " + queryString);
        }

        // execute the query    
        try {
            if (waybackQuery) { // wayback (URL) query

                hits = bean.search(query, start + hitsPerPage, hitsPerDup, dedupField, sort, reverse, true);
            } else { // nutchwax (full-text) query                          
                int hitsPerVersion = 1;
                hits = bean.search(query, start + hitsPerPage, nQueryMatches, hitsPerDup, dedupField, sort,
                        reverse, functions, hitsPerVersion);

            }
        } catch (IOException e) {
            LOG.warn("Search Error", e);
            hits = new Hits(0, new Hit[0]);
        }

        LOG.debug("total hits: " + hits.getTotal());
    }

    // generate xml results
    int end = (int) Math.min(hits.getLength(), start + hitsPerPage);
    int length = end - start;

    Hit[] show = hits.getHits(start, end - start);
    HitDetails[] details = null;

    if (!multipleDetails) { // normal case
        details = bean.getDetails(show);
    } else { // BUG wayback 0000155 - send only the fields necessary to presentation
        PwaRequestDetailsWritable detailsWritable = new PwaRequestDetailsWritable();
        //detailsWritable.setFields(null);
        detailsWritable.setFields(new String[] { "digestDiff", "tstamp" });
        detailsWritable.setHits(show);
        details = bean.getDetails(detailsWritable);
    }

    String requestUrl = request.getRequestURL().toString();
    String base = requestUrl.substring(0, requestUrl.lastIndexOf('/'));

    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        Document doc = factory.newDocumentBuilder().newDocument();

        Element rss = addNode(doc, doc, "rss");
        addAttribute(doc, rss, "version", "2.0");
        addAttribute(doc, rss, "xmlns:opensearch", (String) NS_MAP.get("opensearch"));
        addAttribute(doc, rss, "xmlns:time", (String) NS_MAP.get("time"));
        addAttribute(doc, rss, "xmlns:pwa", (String) NS_MAP.get("pwa"));

        /*
        addAttribute(doc, rss, "xmlns:nutch", (String)NS_MAP.get("nutch"));
        */

        Element channel = addNode(doc, rss, "channel");

        addNode(doc, channel, "title", "PWA Search Engine");
        addNode(doc, channel, "description", "PWA search results for query: " + queryString);
        addNode(doc, channel, "link", "http://archive.pt");

        /*
        addNode(doc, channel, "link",
                base+"/search.jsp"
                +"?query="+urlQuery
                +"&start="+start
                +"&hitsPerDup="+hitsPerDup
                +params);
        */
        addNode(doc, channel, "opensearch", "totalResults", "" + hits.getTotal());
        addNode(doc, channel, "opensearch", "startIndex", "" + start);
        addNode(doc, channel, "opensearch", "itemsPerPage", "" + hitsPerPage);
        Element queryElem = addNode(doc, channel, "opensearch", "Query", "");
        addAttribute(doc, queryElem, "role", "request");
        addAttribute(doc, queryElem, "searchTerms", queryString);
        addAttribute(doc, queryElem, "startPage", "1");

        /*
        if ((hits.totalIsExact() && end < hits.getTotal()) // more hits to show
            || (!hits.totalIsExact() && (hits.getLength() > start+hitsPerPage))){
          addNode(doc, channel, "nutch", "nextPage", requestUrl
        +"?query="+urlQuery
        +"&start="+end
        +"&hitsPerDup="+hitsPerDup
        +params);
        }
        */

        /*
        if ((!hits.totalIsExact() && (hits.getLength() <= start+hitsPerPage))) {
          addNode(doc, channel, "nutch", "showAllHits", requestUrl
        +"?query="+urlQuery
        +"&hitsPerDup="+0
        +params);
        }
        */

        for (int i = 0; i < length; i++) {
            Hit hit = show[i];
            HitDetails detail = details[i];
            String title = detail.getValue("title");

            String url = detail.getValue("url");
            String arcname = detail.getValue("arcname");
            String arcoffset = detail.getValue("arcoffset");
            Element item = addNode(doc, channel, "item");

            if (title == null || title.equals("")) { // use url for docs w/o title
                title = url;
            }
            addNode(doc, item, "title", title);

            //addNode(doc, item, "description", /*summaries[i].toHtml(false)*/""); // BUG wayback 0000155 - this is unnecessary
            String date = detail.getValue("tstamp");
            Date datet = null;
            try {
                datet = FORMAT.parse(date);

            } catch (ParseException e) {
                LOG.error(e);
            }
            if (url != null) {
                // Lucene index format
                String infoIndex = "http://" + collectionsHost + "/id" + hit.getIndexDocNo() + "index"
                        + hit.getIndexNo();

                LOG.info("Index Information " + infoIndex);
                queryElem = addNode(doc, item, "source", "Original URL of " + title);
                addAttribute(doc, queryElem, "url", url);
                String target = "http://" + collectionsHost + "/" + FORMAT.format(datet).toString() + "/" + url;
                if (isOpensearhWayback)
                    addNode(doc, item, "title", FORMATVIEW.format(datet).toString());
                addNode(doc, item, "link", target);
            }

            /*
            addNode(doc, item, "nutch", "site", hit.getDedupValue());        
            addNode(doc, item, "nutch", "cache", base+"/cached.jsp?"+id);
            addNode(doc, item, "nutch", "explain", base+"/explain.jsp?"+id
                    +"&query="+urlQuery+"&lang="+queryLang);
            */

            // BUG wayback 0000155 - add docId and index id to use in wayback search to see a page
            addNode(doc, item, "pwa", "id", "" + hit.getIndexDocNo());
            addNode(doc, item, "pwa", "index", "" + hit.getIndexNo());
            addNode(doc, item, "pwa", "arcname", "" + arcname);
            addNode(doc, item, "pwa", "arcoffset", "" + arcoffset);
            /*
            if (hit.moreFromDupExcluded()) {
              addNode(doc, item, "nutch", "moreFromSite", requestUrl
                      +"?query="
                      +URLEncoder.encode("site:"+hit.getDedupValue()
                             +" "+queryString, "UTF-8")
                      +"&hitsPerSite="+0
                      +params);
            }
            */

            for (int j = 0; j < detail.getLength(); j++) { // add all from detail
                String field = detail.getField(j);
                if ((waybackQuery && !SKIP_DETAILS.contains(field)) || (!waybackQuery
                        && !SKIP_DETAILS_USER.contains(field) && !SKIP_DETAILS.contains(field))) {
                    addNode(doc, item, "pwa", field, detail.getValue(j));
                }
            }
        }

        // dump DOM tree

        DOMSource source = new DOMSource(doc);
        TransformerFactory transFactory = TransformerFactory.newInstance();
        Transformer transformer = transFactory.newTransformer();
        transformer.setOutputProperty("indent", "yes");
        StreamResult result = new StreamResult(response.getOutputStream());
        response.setContentType("application/rss+xml; charset=UTF-8");
        transformer.transform(source, result);

    } catch (javax.xml.parsers.ParserConfigurationException e) {
        throw new ServletException(e);
    } catch (javax.xml.transform.TransformerException e) {
        throw new ServletException(e);
    }

}

From source file:edu.uoc.videochat.LTIAuthenticator.java

/**
 * @param request/*from w w  w .  j av  a  2  s .c o m*/
 * @param response
 * @throws javax.servlet.ServletException
 * @throws java.io.IOException
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 * response) This is a template of LTI Provider
 * @author
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    String nextPage = "error";
    String params = "";
    HttpSession session = request.getSession();
    //ModelAndView model = new ModelAndView();
    session.setAttribute(Constants.USER_SESSION, null);
    session.setAttribute(Constants.COURSE_SESSION, null);
    session.setAttribute(Constants.MEETING_SESSION, null);
    session.setAttribute(Constants.USER_METTING_SESSION, null);
    session.setAttribute(Constants.USER_LANGUAGE, null);

    try {
        ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
        //ApplicationContext context = ContextLoader.getCurrentWebApplicationContext();
        UserDao userDao = (UserDao) context.getBean("UserDao");
        CourseDao courseDao = context.getBean(CourseDao.class);
        UserCourseDao userCourseDao = context.getBean(UserCourseDao.class);
        RoomDao roomDao = context.getBean(RoomDao.class);

        request.setCharacterEncoding("UTF-8");
        //1. Check if LTI call is valid
        LTIEnvironment LTIEnvironment;
        LTIEnvironment = new LTIEnvironment();
        if (LTIEnvironment.is_lti_request(request)) {

            LTIEnvironment.parseRequest(request);
            if (LTIEnvironment.isAuthenticated()) {

                //2. Get the values of user and course      
                String username = Util.sanitizeString(LTIEnvironment.getUserName());
                //TODO mirar si cal posar
                /*if (username.startsWith(LTIEnvironment.getResourcekey()+":")) {
                         username = username.substring((LTIEnvironment.getResourcekey()+":").length());
                         }*/
                String full_name = LTIEnvironment.getFullName();

                String first_name = LTIEnvironment.getParameter(Constants.FIRST_NAME_LTI_PARAMETER);
                String last_name = LTIEnvironment.getParameter(Constants.LAST_NAME_LTI_PARAMETER);

                String email = LTIEnvironment.getEmail();
                String user_image = LTIEnvironment.getUser_image();

                //3. Get the role
                boolean is_instructor = LTIEnvironment.isInstructor();
                boolean is_course_autz = LTIEnvironment.isCourseAuthorized();

                //4. Get course data
                String course_key = Util.sanitizeString(LTIEnvironment.getCourseKey());
                String course_label = LTIEnvironment.getCourseName();
                String resource_key = Util.sanitizeString(LTIEnvironment.getResourceKey());
                String resource_label = LTIEnvironment.getResourceTitle();

                //LTIEnvironment.getParameter(lis_person_name_given);
                //5. Get the locale
                String locale = LTIEnvironment.getLocale();

                java.util.Date date = new java.util.Date();

                //Steps to integrate with your applicationa
                boolean redirectToPlayer = LTIEnvironment
                        .getCustomParameter(Constants.PLAYER_CUSTOM_LTI_PARAMETER, request) != null;
                boolean is_debug = LTIEnvironment.getCustomParameter(Constants.DEBUG_CUSTOM_LTI_PARAMETER,
                        request) != null;

                // System.out.println("ID:" + userDao.findByUserCode(1));
                User user = userDao.findByUserName(username);
                user.setUsername(username);
                user.setFirstname(first_name);
                user.setSurname(last_name);
                user.setFullname(full_name);
                user.setEmail(email);
                user.setImage(user_image);
                userDao.save(user);

                Course course = courseDao.findByCourseKey(course_key);
                course.setTitle(course_label);
                course.setLang(locale);

                if (course.getId() <= 0) {
                    course.setCreated(new Timestamp(date.getTime()));
                    course.setCoursekey(course_key);
                }
                courseDao.save(course);

                UserCourse userCourse = userCourseDao.findByCourseCode(course.getId(), user.getId());
                userCourse.setIs_instructor(is_instructor);
                //TODO change it
                userCourse.setRole("admin");

                UserCourseId userCourseId = new UserCourseId(user, course);
                userCourse.setPk(userCourseId);

                userCourseDao.save(userCourse);

                Course courseRoom = courseDao.findByCourseKey(course_key);

                Room room = roomDao.findByRoomKey(resource_key);
                if (room == null) {
                    room = new Room();
                }
                room.setId_course(courseRoom);
                room.setLabel(resource_label);
                if (room.getId() <= 0) {
                    //if there is no room, create a new room and meeting room
                    room.setIs_blocked(false);
                    room.setKey(resource_key);
                    room.setReason_blocked(null);
                    roomDao.save(room);
                }

                session.setAttribute(Constants.ROOM_SESSION, room);
                //Steps to integrate with your applicationa
                //6. Check if username exists in system
                //6.1 If doesn't exist you have to create user using Tool Api
                //TODO create_user
                //6.2 If exists you can update the values of user (if you want)
                //TODO update_user
                //7. Check if course exists in system (you can set the locale of course)
                //7.1 If doesn't exist you have to create course using Tool Api
                //TODO create_course
                //7.2 If exists you can update the values of course (if you want)
                //TODO update_course
                //8. Register user in course 
                session.setAttribute(Constants.USER_SESSION, user);
                session.setAttribute(Constants.COURSE_SESSION, course);
                locale = locale.substring(0, 2);
                session.setAttribute(Constants.USER_LANGUAGE, locale);
                params = "?" + Constants.PARAM_SPRING_LANG + "=" + locale;
                nextPage = redirectToPlayer ? "searchMeeting" : "videochat";

            } else {

                Exception lastException = LTIEnvironment.getLastException();
                logger.error("Error authenticating user LTI Exception " + lastException);
                //Retornar excepcio
                nextPage = "errorLTI";
            }
        } else {
            logger.warn("Error authenticating user LTI is not LTI Request ");
            nextPage = "errorNoLTIRequest";
        }
    } catch (Exception e) {
        logger.error("Error authenticating user ", e);

    }
    response.sendRedirect(request.getContextPath() + "/" + nextPage + ".htm" + params);
}

From source file:com.stratelia.silverpeas.versioningPeas.servlets.VersioningRequestRouter.java

/**
 * Process request form/*from  w  ww.j  a v  a 2  s  .  co  m*/
 * @param request
 * @param versioningSC
 * @return
 * @throws Exception
 * @throws IOException
 */
private void saveNewDocument(HttpServletRequest request, VersioningSessionController versioningSC)
        throws Exception {
    SilverTrace.debug("versioningPeas", "VersioningRequestRooter.saveNewDocument()",
            "root.MSG_GEN_ENTER_METHOD");
    int majorNumber = 0;
    int minorNumber = 1;
    String type = "dummy";
    String physicalName = "dummy";
    String logicalName = "dummy";
    String mimeType = "dummy";
    File dir = null;
    int size = 0;
    DocumentPK docPK = new DocumentPK(-1, versioningSC.getComponentId());
    if (!StringUtil.isDefined(request.getCharacterEncoding())) {
        request.setCharacterEncoding("UTF-8");
    }
    String encoding = request.getCharacterEncoding();

    List<FileItem> items = FileUploadUtil.parseRequest(request);
    String comments = FileUploadUtil.getParameter(items, "comments", "", encoding);
    int versionType = Integer.parseInt(FileUploadUtil.getParameter(items, "versionType", "0", encoding));

    FileItem fileItem = FileUploadUtil.getFile(items, "file_upload");
    boolean runOnUnix = !FileUtil.isWindows();
    logicalName = fileItem.getName();
    if (logicalName != null) {

        if (runOnUnix) {
            logicalName = logicalName.replace('\\', File.separatorChar);
        }

        logicalName = logicalName.substring(logicalName.lastIndexOf(File.separator) + 1, logicalName.length());
        type = logicalName.substring(logicalName.lastIndexOf(".") + 1, logicalName.length());
        physicalName = new Long(new Date().getTime()).toString() + "." + type;
        mimeType = FileUtil.getMimeType(logicalName);
        if (!StringUtil.isDefined(mimeType)) {
            mimeType = "unknown";
        }
        dir = new File(versioningSC.createPath(versioningSC.getComponentId(), null) + physicalName);
        size = new Long(fileItem.getSize()).intValue();
        fileItem.write(dir);
    }

    if (versionType == VersioningSessionController.PUBLIC_VERSION) {
        majorNumber = 1;
        minorNumber = 0;
    }
    if (size == 0) {
        majorNumber = 0;
        minorNumber = 0;
    }
    DocumentVersion documentVersion = new DocumentVersion(null, docPK, majorNumber, minorNumber,
            Integer.parseInt(versioningSC.getUserId()), new Date(), comments, versionType,
            DocumentVersion.STATUS_VALIDATION_NOT_REQ, physicalName, logicalName, mimeType, size,
            versioningSC.getComponentId());

    boolean addXmlForm = !isXMLFormEmpty(versioningSC, items);
    if (addXmlForm) {
        documentVersion.setXmlForm(versioningSC.getXmlForm());
    }

    // Document
    docPK = new DocumentPK(-1, versioningSC.getComponentId());

    String name = FileUploadUtil.getParameter(items, "name", "", encoding);
    String publicationId = FileUploadUtil.getParameter(items, "publicationId", "-1", encoding);
    String description = FileUploadUtil.getParameter(items, "description", "", encoding);

    PublicationPK pubPK = new PublicationPK(publicationId, versioningSC.getComponentId());
    Document document = new Document(docPK, pubPK, name, description, Document.STATUS_CHECKINED, -1, new Date(),
            null, versioningSC.getComponentId(), null, null, 0,
            Integer.parseInt(VersioningSessionController.WRITERS_LIST_SIMPLE));

    String docId = versioningSC.createDocument(document, documentVersion).getId();

    if (addXmlForm) {
        // Save additional informations
        saveXMLData(versioningSC, documentVersion.getPk(), items);
    }

    versioningSC.setEditingDocument(document);
    versioningSC.setFileRights();
    versioningSC.updateWorkList(document);
    versioningSC.updateDocument(document);

    // Specific case: 3d file to convert by Actify Publisher
    ResourceLocator attachmentSettings = new ResourceLocator(
            "com.stratelia.webactiv.util.attachment.Attachment", "");
    boolean actifyPublisherEnable = attachmentSettings.getBoolean("ActifyPublisherEnable", false);
    if (actifyPublisherEnable) {
        versioningSC.saveFileForActify(docId, documentVersion, attachmentSettings);
    }

    SilverTrace.debug("versioningPeas", "VersioningRequestRooter.saveNewDocument()",
            "root.MSG_GEN_EXIT_METHOD");
}

From source file:Admin_Thesaurus.ImportData.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    if (SystemIsLockedForAdministrativeJobs(request, response)) {
        return;//from  w w w .j a  v a  2  s.  c o m
    }
    String basePath = request.getSession().getServletContext().getRealPath("");

    // ---------------------- LOCK SYSTEM ----------------------
    ConfigDBadmin config = new ConfigDBadmin(basePath);
    DBAdminUtilities dbAdminUtils = new DBAdminUtilities();
    dbAdminUtils.LockSystemForAdministrativeJobs(config);

    response.setContentType("text/html;charset=UTF-8");
    request.setCharacterEncoding("UTF-8");

    HttpSession session = request.getSession();
    ServletContext context = session.getServletContext();
    SessionWrapperClass sessionInstance = new SessionWrapperClass();
    init(request, response, sessionInstance);

    PrintWriter out = response.getWriter();

    OutputStreamWriter logFileWriter = null;

    try {

        // check for previous logon but because of ajax usage respond with Session Invalidate str
        UserInfoClass SessionUserInfo = (UserInfoClass) sessionInstance.getAttribute("SessionUser");

        if (SessionUserInfo == null || !SessionUserInfo.servletAccessControl(this.getClass().getName())) {
            out.println("Session Invalidate");
            response.sendRedirect("Index");
            return;
        }

        //tools
        Utilities u = new Utilities();
        DBGeneral dbGen = new DBGeneral();
        DBImportData dbImport = new DBImportData();
        DBMergeThesauri dbMerge = new DBMergeThesauri();
        StringObject translatedMsgObj = new StringObject("");

        Vector<String> thesauriNames = new Vector<String>();

        CommonUtilsDBadmin common_utils = new CommonUtilsDBadmin(config);
        StringObject resultObj = new StringObject("");

        String initiallySelectedThesaurus = SessionUserInfo.selectedThesaurus;

        //Parameters
        String xmlFilePath = request.getParameter("importXMLfilename");

        //String importSchemaName    = request.getParameter("schematype");
        String importSchemaName = ConstantParameters.xmlschematype_THEMAS;
        String importThesaurusName = request.getParameter("Import_Thesaurus_NewName_NAME");
        String importMethodChoice = request.getParameter("ImportThesaurusMode");//thesaurusImport or bulkImport
        String importHierarchyName = u
                .getDecodedParameterValue(request.getParameter("Import_Thesaurus_HierarchyName"));
        String pathToErrorsXML = context.getRealPath("/translations/Consistencies_Error_Codes.xml");
        String language = context.getInitParameter("LocaleLanguage");
        String country = context.getInitParameter("LocaleCountry");
        String WebAppUsersFileName = request.getSession().getServletContext()
                .getRealPath("/" + UsersClass.WebAppUsersXMLFilePath);

        String logPath = context.getRealPath("/" + ConstantParameters.LogFilesFolderName);
        String logFileNamePath = logPath;
        String webAppSaveResults_Folder = Parameters.Save_Results_Folder;
        String pathToSaveScriptingAndLocale = context
                .getRealPath("/translations/SaveAll_Locale_And_Scripting.xml");
        Locale targetLocale = new Locale(language, country);

        if ((importMethodChoice.equals("thesaurusImport") && (importThesaurusName != null))
                || (importMethodChoice.equals("bulkImport") && importHierarchyName != null)) {
            UpDownFiles fup = new UpDownFiles();
            String[] formData = new String[10];
            FileItem[] dom = fup.prepareToUpBinary(request, formData);
            //Hashtable initParams = UpDownFiles.uploadParams;

            if (dom[0] != null) {

                String filename = xmlFilePath;
                ///String caption = (String) initParams.get("caption");

                filename = filename.substring(filename.lastIndexOf(File.separator) + 1);

                String fileType = filename.substring(filename.lastIndexOf(".") + 1);
                String userFileName = filename.substring(0, filename.lastIndexOf("."));

                filename = userFileName + "(" + getDate() + " " + getTime() + ")." + fileType;

                String fullPath = getServletContext().getRealPath("/Uploads") + "/" + filename;
                xmlFilePath = fullPath;
                if (fup.writeBinary(dom[0], fullPath)) {
                    //mode = 1;
                } else {
                    //mode = -1;
                }
            } else {
                //mode = -1;
            }
        }

        QClass Q = new QClass();
        TMSAPIClass TA = new TMSAPIClass();
        IntegerObject sis_session = new IntegerObject();
        IntegerObject tms_session = new IntegerObject();

        //open connection and start transaction
        if (dbGen.openConnectionAndStartQueryOrTransaction(Q, TA, sis_session, null, null,
                true) == QClass.APIFail) {
            Utils.StaticClass
                    .webAppSystemOutPrintln("OPEN CONNECTION ERROR @ servlet " + this.getServletName());
            return;
        }

        dbGen.GetExistingThesaurus(false, thesauriNames, Q, sis_session);

        if (importMethodChoice.equals("thesaurusImport")) {

            //Format Name Of import Thesaurus
            importThesaurusName = importThesaurusName.trim();
            importThesaurusName = importThesaurusName.replaceAll(" ", "_");
            importThesaurusName = importThesaurusName.toUpperCase();

            if (thesauriNames.contains(importThesaurusName)) {

                resultObj.setValue(u.translateFromMessagesXML("root/ImportData/importThesaurusNameFailure",
                        new String[] { importThesaurusName }));
                //resultObj.setValue("Thesaurus '" + importThesaurusName + "' already exists in database. Please choose a different name for the Thesaurus.");

                Vector<String> allHierarchies = new Vector<String>();
                Vector<String> allGuideTerms = new Vector<String>();
                dbGen.getDBAdminHierarchiesStatusesAndGuideTermsXML(SessionUserInfo, Q, sis_session,
                        allHierarchies, allGuideTerms);

                //end query and close connection
                Q.free_all_sets();
                Q.TEST_end_query();
                //Q.TEST_abort_transaction();
                dbGen.CloseDBConnection(Q, null, sis_session, null, false);

                StringBuffer xml = new StringBuffer();
                xml.append(u.getXMLStart(ConstantParameters.LMENU_THESAURI));
                xml.append(u.getDBAdminHierarchiesStatusesAndGuideTermsXML(allHierarchies, allGuideTerms,
                        targetLocale));

                xml.append(getXMLMiddle(thesauriNames,
                        u.translateFromMessagesXML("root/ImportData/ImportFunctionFailure", null)
                                + resultObj.getValue(),
                        importMethodChoice));
                xml.append(u.getXMLUserInfo(SessionUserInfo));
                xml.append(u.getXMLEnd());
                u.XmlPrintWriterTransform(out, xml, sessionInstance.path + "/xml-xsl/page_contents.xsl");

                // ---------------------- UNLOCK SYSTEM ----------------------
                dbAdminUtils.UnlockSystemForAdministrativeJobs();
                return;
            }
        } else if (importMethodChoice.equals("bulkImport")) {
            importThesaurusName = SessionUserInfo.selectedThesaurus;
            if (thesauriNames.contains(importThesaurusName) == false) {

                //String pathToMessagesXML = context.getRealPath("/translations/Messages.xml");
                //StringObject resultMessageObj = new StringObject();
                StringObject resultMessageObj_2 = new StringObject();
                //Vector<String> errorArgs = new Vector<String>();

                resultObj.setValue(u.translateFromMessagesXML("root/ImportData/ThesaurusDoesNotExist",
                        new String[] { importThesaurusName }));

                //resultObj.setValue("Thesaurus '" + importThesaurusName + "' does not exist in database. Please choose a different thesaurus if this one still exists.");
                Vector<String> allHierarchies = new Vector<String>();
                Vector<String> allGuideTerms = new Vector<String>();
                dbGen.getDBAdminHierarchiesStatusesAndGuideTermsXML(SessionUserInfo, Q, sis_session,
                        allHierarchies, allGuideTerms);

                //end query and close connection
                Q.free_all_sets();
                Q.TEST_end_query();
                //Q.TEST_abort_transaction();
                dbGen.CloseDBConnection(Q, null, sis_session, null, false);

                StringBuffer xml = new StringBuffer();
                xml.append(u.getXMLStart(ConstantParameters.LMENU_THESAURI));
                xml.append(u.getDBAdminHierarchiesStatusesAndGuideTermsXML(allHierarchies, allGuideTerms,
                        targetLocale));

                resultMessageObj_2
                        .setValue(u.translateFromMessagesXML("root/ImportData/InsertionFailure", null));
                xml.append(getXMLMiddle(thesauriNames, resultMessageObj_2.getValue() + resultObj.getValue(),
                        importMethodChoice));
                //xml.append(getXMLMiddle(thesauriNames, "Data insertion failure. " + resultObj.getValue(),importMethodChoice));
                xml.append(u.getXMLUserInfo(SessionUserInfo));
                xml.append(u.getXMLEnd());
                u.XmlPrintWriterTransform(out, xml, sessionInstance.path + "/xml-xsl/page_contents.xsl");

                // ---------------------- UNLOCK SYSTEM ----------------------
                dbAdminUtils.UnlockSystemForAdministrativeJobs();
                return;
            }
        }

        //end query and close connection
        Q.free_all_sets();
        Q.TEST_end_query();
        dbGen.CloseDBConnection(Q, null, sis_session, null, false);
        Utils.StaticClass.closeDb();

        StringObject DBbackupFileNameCreated = new StringObject("");

        long startTime = Utilities.startTimer();
        String time = Utilities.GetNow();
        String Filename = "Import_Thesaurus_" + importThesaurusName + "_" + time;
        logFileNamePath += "/" + Filename + ".xml";

        try {
            OutputStream fout = new FileOutputStream(logFileNamePath);
            OutputStream bout = new BufferedOutputStream(fout);
            logFileWriter = new OutputStreamWriter(bout, "UTF-8");
            logFileWriter.append(ConstantParameters.xmlHeader);//+ "\r\n"

            //logFileWriter.append("<?xml-stylesheet type=\"text/xsl\" href=\"../" + webAppSaveResults_Folder + "/ImportCopyMergeThesaurus_Report.xsl" + "\"?>\r\n");
            logFileWriter.append("<page language=\"" + Parameters.UILang + "\" primarylanguage=\""
                    + Parameters.PrimaryLang.toLowerCase() + "\">\r\n");
            logFileWriter.append("<title>"
                    + u.translateFromMessagesXML("root/ImportData/ReportTitle",
                            new String[] { importThesaurusName, time })
                    + "</title>\r\n" + "<pathToSaveScriptingAndLocale>" + pathToSaveScriptingAndLocale
                    + "</pathToSaveScriptingAndLocale>\r\n");
            //logFileWriter.append("<!--"+time + " LogFile for data import in thesaurus: " + importThesaurusName +".-->\r\n");
            Utils.StaticClass.webAppSystemOutPrintln(Parameters.LogFilePrefix + time
                    + " LogFile for data import in thesaurus: " + importThesaurusName + ".");

        } catch (Exception exc) {
            Utils.StaticClass.webAppSystemOutPrintln(
                    Parameters.LogFilePrefix + "Error in opening file: " + exc.getMessage());
            Utils.StaticClass.handleException(exc);
        }

        if (importMethodChoice.equals("thesaurusImport")) {

            if (dbImport.thesaurusImportActions(SessionUserInfo, common_utils, config, targetLocale,
                    pathToErrorsXML, xmlFilePath, importSchemaName, importThesaurusName,
                    "backup_before_import_data_to_thes_" + importThesaurusName, DBbackupFileNameCreated,
                    resultObj, logFileWriter) == false) {
                abortActions(request, sessionInstance, context, targetLocale, common_utils,
                        initiallySelectedThesaurus, importThesaurusName, DBbackupFileNameCreated, resultObj,
                        out);
                return;
            }
        } else if (importMethodChoice.equals("bulkImport")) {
            /*
             //open connection and start Transaction
             if(dbGen.openConnectionAndStartQueryOrTransaction(Q, TA, sis_session, tms_session, SessionUserInfo.selectedThesaurus, false)==QClass.APIFail)
             {
             Utils.StaticClass.webAppSystemOutPrintln("OPEN CONNECTION ERROR @ servlet " + this.getServletName());
             return;
             }
             */
            if (dbImport.bulkImportActions(sessionInstance, context, common_utils, config, targetLocale,
                    pathToErrorsXML, xmlFilePath, importThesaurusName, importHierarchyName,
                    "backup_before_import_data_to_thes_" + importThesaurusName, DBbackupFileNameCreated,
                    resultObj, logFileWriter) == false) {
                abortActions(request, sessionInstance, context, targetLocale, common_utils,
                        initiallySelectedThesaurus, importThesaurusName, DBbackupFileNameCreated, resultObj,
                        out);
                return;
            }

        }

        commitActions(request, WebAppUsersFileName, sessionInstance, context, targetLocale, importThesaurusName,
                out, Filename.concat(".html"));

        //ReportSuccessMessage            
        logFileWriter
                .append("\r\n<creationInfo>"
                        + u.translateFromMessagesXML("root/ImportData/ReportSuccessMessage",
                                new String[] { importThesaurusName, xmlFilePath,
                                        ((Utilities.stopTimer(startTime)) / 60) + "" })
                        + "</creationInfo>\r\n");

        if (logFileWriter != null) {
            logFileWriter.append("</page>");
            logFileWriter.flush();
            logFileWriter.close();
        }

        //Now XSL should be found and java xsl transformation should be performed
        String XSL = context.getRealPath("/" + webAppSaveResults_Folder)
                + "/ImportCopyMergeThesaurus_Report.xsl";

        u.XmlFileTransform(logFileNamePath, XSL, logPath + "/" + Filename.concat(".html"));

    } catch (Exception e) {

        Utils.StaticClass.webAppSystemOutPrintln(Parameters.LogFilePrefix + ".Exception catched in servlet "
                + getServletName() + ". Message:" + e.getMessage());
        Utils.StaticClass.handleException(e);
        if (logFileWriter != null) {
            logFileWriter.append("</page>");
            logFileWriter.flush();
            logFileWriter.close();
        }
    } finally {
        out.flush();
        out.close();
        sessionInstance.writeBackToSession(session);
    }
}

From source file:com.softwarementors.extjs.djn.servlet.DirectJNgineServlet.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
    assert request != null;
    assert response != null;

    NDC.push("rid=" + Long.toString(getUniqueRequestId()));
    try {//w w w. j  a  v  a2  s  .  co  m
        Timer timer = new Timer();
        try {
            attachThreadLocalData(request, response);
            try {
                if (logger.isTraceEnabled()) {
                    String requestInfo = ServletUtils.getDetailedRequestInformation(request);
                    logger.trace("Request info: " + requestInfo);
                }

                String requestEncoding = request.getCharacterEncoding();
                // If we don't know what the request encoding is, assume it to be UTF-8
                if (StringUtils.isEmpty(requestEncoding)) {
                    request.setCharacterEncoding(EncodingUtils.UTF8);
                }
                response.setCharacterEncoding(EncodingUtils.UTF8);

                RequestType type = getFromRequestContentType(request);
                processRequest(request, response, type);
            } finally {
                detachThreadLocalData();
            }
        } finally {
            timer.stop();
            timer.logDebugTimeInMilliseconds("Total servlet processing time");
        }

    } finally {
        NDC.pop();
    }
}