Example usage for java.lang StringBuffer replace

List of usage examples for java.lang StringBuffer replace

Introduction

In this page you can find the example usage for java.lang StringBuffer replace.

Prototype

@Override
public synchronized StringBuffer replace(int start, int end, String str) 

Source Link

Usage

From source file:com.topsec.tsm.sim.report.util.ReportUiUtil.java

/**
 * ?/*from  w  w  w  . j a  v  a  2 s .  c o  m*/
 * @param subMap ?
 * @param width 
 * @param url url
 * @param talCategory ?
 * @param top top
 * @return
 */
public static String createSubTitle(Map subMap, String width, String url, String[] talCategory, int top) {
    String repeatid = "";
    int subRepeat = url.indexOf("subREPEAT_");
    if (subRepeat != -1) {
        repeatid = url.split("subREPEAT_")[1];
        url = url.substring(0, subRepeat);
        url = url + "&chartTableId=" + subMap.get("subId") + repeatid;
    }
    String Rn = "\r\n";
    String s4 = "    ";
    String[] tableLables = subMap.get("tableLable").toString().split(",");
    StringBuffer sb = new StringBuffer();
    String subType = subMap.get("subType").toString();
    boolean isExistTable = StringUtil.toInt(subType, 0) == 1 ? false : true;
    if (isExistTable) {
        for (int i = 0, len = tableLables.length; i < len; i++) {
            sb.append("<td>").append(tableLables[i]).append("</td>");
        }
    }
    Object reTab = subMap.get("InformReportOnlyTable");
    boolean InformReportOnlyTable = reTab == null ? false : Boolean.valueOf(reTab.toString());
    String tds = sb.toString();
    String title = subMap.get("subName").toString();
    title = ReportUiUtil.viewRptName(title, subType);
    if (talCategory != null) {
        boolean flag = ReportUiUtil.isSystemLog(subMap);
        if (title.indexOf("(") > 0) {
            String[] cats = title.substring(title.indexOf("(") + 1, title.indexOf(")")).split(",");
            sb.replace(0, tds.length(), title.substring(0, title.indexOf("(") + 1));
            for (int i = 0, len = cats.length; i < len; i++) {
                String str = "";
                if (!GlobalUtil.isNullOrEmpty(talCategory[i]) && talCategory[i].contains("***")) {
                    str = talCategory[i].substring(talCategory[i].indexOf("***") + 3);
                    if (str.indexOf("%") > -1) {
                        try {
                            str = new String(str.getBytes("iso-8859-1"), "UTF-8");
                            str = URLDecoder.decode(str, "UTF-8");
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                    }
                }
                if (flag) {
                    str = DeviceTypeNameUtil.getDeviceTypeName(str, Locale.getDefault());
                }
                sb.append(cats[i]).append(" ").append(str);
                if (i < len - 1) {
                    sb.append(" -> ");
                }
            }
            sb.append(")");
            title = sb.toString();
        }
    }

    sb.replace(0, sb.length(),
            "<div id='div_" + subMap.get("subId") + repeatid + "' class='easyui-panel' data-options='");
    if (!InformReportOnlyTable) {
        sb.append("headerCls:\"sim-panel-header\",");
    } else {
        sb.append("headerCls:\"dymicReport-panel-header\",height:175,");
    }
    sb.append("width:" + width + ",onOpen:highcharts.loadReportData(\"" + url + "\"," + top + "," + isExistTable
            + ")' title='" + title + "'>").append(Rn).append(s4).append("<div>").append(Rn);
    if (!InformReportOnlyTable) {
        sb.append(s4).append(s4).append("<div id='chart_" + subMap.get("subId") + repeatid + "'/>").append(Rn);
    }
    if (isExistTable) {
        if (!InformReportOnlyTable) {
            sb.append(s4).append(s4).append("<a href='#' onClick=\"report.viewCmd(this,'table_"
                    + subMap.get("subId") + repeatid + "')\" style='margin-left:6px;'>??</a>").append(Rn);
        }
        sb.append(s4).append(s4)
                .append("<table id='table_" + subMap.get("subId") + repeatid
                        + "' class='report-table' align='center' cellpadding='0' cellspacing='0'>")
                .append(Rn).append(s4).append(s4).append(s4).append("<thead");
        if (!InformReportOnlyTable) {
            sb.append(" class='fixedHeader'");
        } else {
            sb.append(" class='onlyfixedHeader'");
        }
        sb.append(">").append(Rn).append(s4).append(s4).append(s4).append("<tr align='center'");
        if (!InformReportOnlyTable) {
            sb.append(" class='tableHead'");
        } else {
            sb.append(" class='onlytableHead'");
        }
        sb.append(">").append(Rn).append(s4).append(s4).append(s4).append(s4).append(tds).append(Rn).append(s4)
                .append(s4).append(s4).append("</tr>").append(Rn).append(s4).append(s4).append(s4)
                .append("</thead>").append(Rn).append(s4).append(s4).append("</table>").append(Rn);
    }
    sb.append(s4).append("</div>").append(Rn).append("</div>");
    return sb.toString();
}

From source file:info.magnolia.cms.beans.config.PropertiesInitializer.java

/**
 * Parse the given String value recursively, to be able to resolve nested placeholders. Partly borrowed from
 * org.springframework.beans.factory.config.PropertyPlaceholderConfigurer (original author: Juergen Hoeller)
 *
 * @deprecated since 4.5 this is now done by {@link info.magnolia.init.AbstractMagnoliaConfigurationProperties#parseStringValue}.
 *///from  ww w .  java  2 s  . c o  m
protected String parseStringValue(String strVal, Set<String> visitedPlaceholders) {

    StringBuffer buf = new StringBuffer(strVal);

    int startIndex = strVal.indexOf(PLACEHOLDER_PREFIX);
    while (startIndex != -1) {
        int endIndex = -1;

        int index = startIndex + PLACEHOLDER_PREFIX.length();
        int withinNestedPlaceholder = 0;
        while (index < buf.length()) {
            if (PLACEHOLDER_SUFFIX.equals(buf.subSequence(index, index + PLACEHOLDER_SUFFIX.length()))) {
                if (withinNestedPlaceholder > 0) {
                    withinNestedPlaceholder--;
                    index = index + PLACEHOLDER_SUFFIX.length();
                } else {
                    endIndex = index;
                    break;
                }
            } else if (PLACEHOLDER_PREFIX.equals(buf.subSequence(index, index + PLACEHOLDER_PREFIX.length()))) {
                withinNestedPlaceholder++;
                index = index + PLACEHOLDER_PREFIX.length();
            } else {
                index++;
            }
        }

        if (endIndex != -1) {
            String placeholder = buf.substring(startIndex + PLACEHOLDER_PREFIX.length(), endIndex);
            if (!visitedPlaceholders.add(placeholder)) {

                log.warn("Circular reference detected in properties, \"{}\" is not resolvable", strVal);
                return strVal;
            }
            // Recursive invocation, parsing placeholders contained in the placeholder key.
            placeholder = parseStringValue(placeholder, visitedPlaceholders);
            // Now obtain the value for the fully resolved key...
            String propVal = SystemProperty.getProperty(placeholder);
            if (propVal != null) {
                // Recursive invocation, parsing placeholders contained in the
                // previously resolved placeholder value.
                propVal = parseStringValue(propVal, visitedPlaceholders);
                buf.replace(startIndex, endIndex + PLACEHOLDER_SUFFIX.length(), propVal);
                startIndex = buf.indexOf(PLACEHOLDER_PREFIX, startIndex + propVal.length());
            } else {
                // Proceed with unprocessed value.
                startIndex = buf.indexOf(PLACEHOLDER_PREFIX, endIndex + PLACEHOLDER_SUFFIX.length());
            }
            visitedPlaceholders.remove(placeholder);
        } else {
            startIndex = -1;
        }
    }

    return buf.toString();
}

From source file:com.topsec.tsm.sim.report.web.TopoReportController.java

private void setImfo(List<Map<String, Object>> subResult, Map<String, Object> params, ReportBean bean,
        StringBuffer layout, StringBuffer subUrl, Map layoutValue, String scanNodeId,
        Map<Integer, Integer> rowColumns, String sUrl, int screenWidth) {

    for (int i = 0, len = subResult.size(); i < len; i++) {
        params.remove("sTime");
        Map subMap = subResult.get(i);
        if (i == 0) {
            bean.setViewItem(StringUtil.toString(subMap.get("viewItem"), ""));
        }/*from  ww  w .ja va 2 s  .c om*/
        Integer row = (Integer) subMap.get("subRow");
        layout.append(row + ":" + subMap.get("subColumn") + ",");
        if (GlobalUtil.isNullOrEmpty(subMap)) {
            continue;
        }
        params.put("sTime", bean.getTalStartTime());
        params.put("dvcType", subMap.get("subject"));
        sUrl = getComprehensiveUrl(ReportUiConfig.subEvtUrl, scanNodeId, params, bean.getTalCategory())
                .toString();
        params.remove("dvcType");
        subUrl.replace(0, subUrl.length(), sUrl);
        subUrl.append("&").append(ReportUiConfig.subrptid).append("=").append(subMap.get("subId"));
        subUrl.substring(0, subUrl.length());
        int column = rowColumns.get(row);
        String width = String.valueOf((screenWidth - 10 * column) / column);
        String _column = subMap.get("subColumn").toString();
        layoutValue.put(row + _column, ReportUiUtil.createSubTitle(subMap, width, subUrl.toString(),
                bean.getTalCategory(), StringUtil.toInt(bean.getTalTop(), 5)));
    }
}

From source file:net.java.sip.communicator.impl.gui.main.chat.ChatWritePanel.java

/**
 * When CTRL+Z is pressed invokes the <code>ChatWritePanel.undo()</code>
 * method, when CTRL+R is pressed invokes the
 * <code>ChatWritePanel.redo()</code> method.
 *
 * @param e the <tt>KeyEvent</tt> that notified us
 *//*from   w  w w .j a  v  a 2 s  .  c  om*/
public void keyPressed(KeyEvent e) {
    if ((e.getModifiers() & KeyEvent.CTRL_MASK) == KeyEvent.CTRL_MASK && (e.getKeyCode() == KeyEvent.VK_Z)
    // And not ALT(right ALT gives CTRL + ALT).
            && (e.getModifiers() & KeyEvent.ALT_MASK) != KeyEvent.ALT_MASK) {
        if (undo.canUndo())
            undo();
    } else if ((e.getModifiers() & KeyEvent.CTRL_MASK) == KeyEvent.CTRL_MASK
            && (e.getKeyCode() == KeyEvent.VK_R)
            // And not ALT(right ALT gives CTRL + ALT).
            && (e.getModifiers() & KeyEvent.ALT_MASK) != KeyEvent.ALT_MASK) {
        if (undo.canRedo())
            redo();
    } else if (e.getKeyCode() == KeyEvent.VK_TAB) {
        if (!(chatPanel.getChatSession() instanceof ConferenceChatSession))
            return;

        e.consume();
        int index = ((JEditorPane) e.getSource()).getCaretPosition();

        StringBuffer message = new StringBuffer(chatPanel.getMessage());

        int position = index - 1;

        while (position > 0 && (message.charAt(position) != ' ')) {
            position--;
        }

        if (position != 0)
            position++;

        String sequence = message.substring(position, index);

        if (sequence.length() <= 0) {
            // Do not look for matching contacts if the matching pattern is
            // 0 chars long, since all contacts will match.
            return;
        }

        Iterator<ChatContact<?>> iter = chatPanel.getChatSession().getParticipants();
        ArrayList<String> contacts = new ArrayList<String>();
        while (iter.hasNext()) {
            ChatContact<?> c = iter.next();
            if (c.getName().length() >= (index - position)
                    && c.getName().substring(0, index - position).equals(sequence)) {
                message.replace(position, index, c.getName().substring(0, index - position));
                contacts.add(c.getName());
            }
        }

        if (contacts.size() > 1) {
            char key = contacts.get(0).charAt(index - position - 1);
            int pos = index - position - 1;
            boolean flag = true;

            while (flag) {
                try {
                    for (String name : contacts) {
                        if (key != name.charAt(pos)) {
                            flag = false;
                        }
                    }

                    if (flag) {
                        pos++;
                        key = contacts.get(0).charAt(pos);
                    }
                } catch (IndexOutOfBoundsException exp) {
                    flag = false;
                }
            }

            message.replace(position, index, contacts.get(0).substring(0, pos));

            Iterator<String> contactIter = contacts.iterator();
            String contactList = "<DIV align='left'><h5>";
            while (contactIter.hasNext()) {
                contactList += contactIter.next() + " ";
            }
            contactList += "</h5></DIV>";

            chatPanel.getChatConversationPanel().appendMessageToEnd(contactList,
                    ChatHtmlUtils.HTML_CONTENT_TYPE);
        } else if (contacts.size() == 1) {
            String limiter = (position == 0) ? ": " : "";
            message.replace(position, index, contacts.get(0) + limiter);
        }

        try {
            ((JEditorPane) e.getSource()).getDocument().remove(0,
                    ((JEditorPane) e.getSource()).getDocument().getLength());
            ((JEditorPane) e.getSource()).getDocument().insertString(0, message.toString(), null);
        } catch (BadLocationException ex) {
            ex.printStackTrace();
        }
    } else if (e.getKeyCode() == KeyEvent.VK_UP) {
        // Only enters editing mode if the write panel is empty in
        // order not to lose the current message contents, if any.
        if (this.chatPanel.getLastSentMessageUID() != null && this.chatPanel.isWriteAreaEmpty()) {
            this.chatPanel.startLastMessageCorrection();
            e.consume();
        }
    } else if (e.getKeyCode() == KeyEvent.VK_DOWN) {
        if (chatPanel.isMessageCorrectionActive()) {
            Document doc = editorPane.getDocument();
            if (editorPane.getCaretPosition() == doc.getLength()) {
                chatPanel.stopMessageCorrection();
            }
        }
    }
}

From source file:com.topsec.tsm.sim.report.web.TopoReportController.java

public String reportQuery(SID sid, HttpServletRequest request, HttpServletResponse response) throws Exception {

    JSONObject json = new JSONObject();
    ReportBean bean = new ReportBean();
    bean = ReportUiUtil.tidyFormBean(bean, request);
    String[] talCategory = bean.getTalCategory();
    ReportModel.setBeanPropery(bean);/*from   w ww. j  a v  a  2 s .  c o m*/
    RptMasterTbService rptMasterTbImp = (RptMasterTbService) SpringContextServlet.springCtx
            .getBean(ReportUiConfig.MstBean);
    List<Map> subResult = new ArrayList<Map>();
    Map<Integer, Integer> rowColumns = new HashMap<Integer, Integer>();

    List<Map<String, Object>> subResultTemp = rptMasterTbImp.queryTmpList(ReportUiConfig.MstSubSql,
            new Object[] { StringUtil.toInt(bean.getMstrptid(), StringUtil.toInt(bean.getTalTop(), 5)) });
    Map<Integer, Integer> rowColumnsTeMap = ReportModel.getRowColumns(subResultTemp);
    int evtRptsize = subResultTemp.size();
    if (!GlobalUtil.isNullOrEmpty(subResultTemp)) {
        subResult.addAll(subResultTemp);
        rowColumns.putAll(rowColumnsTeMap);
    }
    String nodeType = bean.getNodeType();
    String dvcaddress = bean.getDvcaddress();
    if (!GlobalUtil.isNullOrEmpty(bean.getDvctype()) && bean.getDvctype().startsWith("Profession/Group")
            && !GlobalUtil.isNullOrEmpty(nodeType) && !GlobalUtil.isNullOrEmpty(dvcaddress)) {
        Map map = TopoUtil.getAssetEvtMstMap();
        String mstIds = null;
        List<SimDatasource> simDatasources = dataSourceService.getByIp(dvcaddress);
        if (!GlobalUtil.isNullOrEmpty(simDatasources)) {
            mstIds = "";
            for (SimDatasource simDatasource : simDatasources) {
                if (map.containsKey(simDatasource.getSecurityObjectType())) {
                    mstIds += map.get(simDatasource.getSecurityObjectType()).toString() + ":::";
                } else {
                    String keyString = getStartStringKey(map, simDatasource.getSecurityObjectType());
                    if (!GlobalUtil.isNullOrEmpty(keyString)) {
                        mstIds += map.get(keyString).toString() + ":::";
                    }
                }
            }
            if (mstIds.length() > 3) {
                mstIds = mstIds.substring(0, mstIds.length() - 3);
            }
        } else {
            if (map.containsKey(nodeType)) {
                mstIds = map.get(nodeType).toString();
            } else {
                String keyString = getStartStringKey(map, nodeType);
                if (!GlobalUtil.isNullOrEmpty(keyString)) {
                    mstIds = map.get(keyString).toString();
                }
            }
        }
        /**/
        if (!GlobalUtil.isNullOrEmpty(mstIds)) {
            String[] mstIdArr = mstIds.split(":::");
            for (String string : mstIdArr) {
                List<Map<String, Object>> subTemp = rptMasterTbImp.queryTmpList(ReportUiConfig.MstSubSql,
                        new Object[] { StringUtil.toInt(string, StringUtil.toInt(bean.getTalTop(), 5)) });
                if (!GlobalUtil.isNullOrEmpty(subTemp)) {
                    int maxCol = 0;
                    if (!GlobalUtil.isNullOrEmpty(rowColumns)) {
                        maxCol = getMaxOrMinKey(rowColumns, 1);
                    }
                    for (Map map2 : subTemp) {
                        Integer row = (Integer) map2.get("subRow") + maxCol;
                        map2.put("subRow", row);
                    }
                    subResult.addAll(subTemp);
                    Map<Integer, Integer> rowColTemp = ReportModel.getRowColumns(subTemp);
                    rowColumns.putAll(rowColTemp);
                    //                  rowColumns=newLocationMap(rowColumns, rowColTemp);
                }
            }
        }
    }
    StringBuffer layout = new StringBuffer();
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("dvcType", bean.getDvctype());
    params.put("talTop", bean.getTalTop());
    params.put("mstId", bean.getMstrptid());
    params.put("eTime", bean.getTalEndTime());
    params.put("rootId", bean.getRootId());
    params.put("assGroupNodeId", bean.getAssGroupNodeId());
    params.put("topoId", bean.getTopoId());
    params.put("nodeLevel", bean.getNodeLevel());
    params.put("nodeType", bean.getNodeType());
    String sUrl = null;
    int screenWidth = StringUtil.toInt(request.getParameter("screenWidth"), 1280) - 25 - 200;

    StringBuffer subUrl = new StringBuffer();
    Map layoutValue = new HashMap();
    for (int i = 0, len = subResult.size(); i < len; i++) {
        params.remove("sTime");
        Map subMap = subResult.get(i);
        if (i == 0) {
            bean.setViewItem(StringUtil.toString(subMap.get("viewItem"), ""));
        }
        Integer row = (Integer) subMap.get("subRow");
        layout.append(row + ":" + subMap.get("subColumn") + ",");
        if (GlobalUtil.isNullOrEmpty(subMap)) {
            continue;
        }
        params.put("sTime", bean.getTalStartTime());

        if (i < evtRptsize) {
            sUrl = getUrl(ReportUiConfig.subEvtUrl, request, params, bean.getTalCategory(), true).toString();
        } else {
            sUrl = getUrl(ReportUiConfig.subEvtUrl, request, params, bean.getTalCategory(), false).toString();
        }
        subUrl.replace(0, subUrl.length(), sUrl);
        subUrl.append("&").append(ReportUiConfig.subrptid).append("=").append(subMap.get("subId"));
        subUrl.substring(0, subUrl.length());
        int column = rowColumns.get(row);
        String width = String.valueOf((screenWidth - 10 * column) / column);
        String _column = subMap.get("subColumn").toString();
        layoutValue.put(row + _column, ReportUiUtil.createSubTitle(subMap, width, subUrl.toString(),
                bean.getTalCategory(), StringUtil.toInt(bean.getTalTop(), 5)));
    }

    if (!GlobalUtil.isNullOrEmpty(subResult) && subResult.size() > 0) {
        if (!GlobalUtil.isNullOrEmpty(subResult.get(0).get("mstName"))) {
            request.setAttribute("title", subResult.get(0).get("mstName"));
        }
    }
    String htmlLayout = ReportModel.createMstTable(layout.toString(), layoutValue);
    StringBuffer sb = getExportUrl(request, params, talCategory, true);
    request.setAttribute("expUrl", sb.toString());
    request.setAttribute("layout", htmlLayout);
    request.setAttribute("bean", bean);

    return "/page/report/assetStatusEvtReport";
}

From source file:org.oscm.identityservice.bean.IdentityServiceBean.java

private void removeTrailingSlashes(StringBuffer url) {
    while (url.length() > 0 && url.charAt(url.length() - 1) == '/') {
        url.replace(url.length() - 1, url.length(), "");
    }/*  w  w  w. j  a v a 2 s.  c o  m*/
}

From source file:com.india.arunava.network.httpProxy.HTTPProxyThreadBrowser.java

@Override
public void run() {

    ByteArrayOutputStream mainBuffer = new ByteArrayOutputStream();

    long count1 = 0;
    long count2 = 0;

    if (ProxyConstants.logLevel >= 1) {
        System.out.println(new Date() + " HTTPProxyThreadBrowser ::Started  " + currentThread());
    }//from  ww w  .  j av a  2 s.  c  o  m

    final byte[] buffer = new byte[ProxyConstants.MAX_BUFFER];
    int numberRead = 0;
    OutputStream server;
    InputStream client;

    try {

        client = incoming.getInputStream();
        server = outgoing.getOutputStream();
        String proxyAuth = "";
        // If Organization proxy required Authentication
        if (!ProxyConstants.ORGANIZATION_HTTP_PROXY_USER_NAME.equals("")) {
            final String authString = ProxyConstants.ORGANIZATION_HTTP_PROXY_USER_NAME + ":"
                    + ProxyConstants.ORGANIZATION_HTTP_PROXY_USER_PASS;
            proxyAuth = "Basic " + Base64.encodeBase64String(authString.getBytes());
        }

        int rdL;
        final StringBuffer header = new StringBuffer(9999);
        while (true) {
            rdL = client.read();
            if (rdL == -1) {
                break;
            }
            header.append((char) rdL);
            if (header.indexOf("\r\n\r\n") != -1) {
                break;
            }
        }

        if (ProxyConstants.logLevel >= 2) {
            System.out.println(new Date() + " HTTPProxyThreadBrowser :: Request header   = " + currentThread()
                    + " \n" + header);
        }

        final String allInpRequest = header.toString();

        // modify: if it is https request, resend to sslproxy
        if (ProxyConstants.HTTPS_ENABLED && allInpRequest.startsWith("CONNECT ")) {
            new SSLProxy(incoming, incoming.getInputStream(), incoming.getOutputStream(), allInpRequest)
                    .start();
            return;
        }
        // modify end

        String host = "";
        String port = "";
        String tmpHost = "";
        final int indexOf = allInpRequest.toLowerCase().indexOf("host:");
        if (indexOf != -1) {
            final int immediateNeLineChar = allInpRequest.toLowerCase().indexOf("\r\n",
                    allInpRequest.toLowerCase().indexOf("host:"));
            tmpHost = allInpRequest
                    .substring(allInpRequest.toLowerCase().indexOf("host:") + 5, immediateNeLineChar).trim();
            final int isPortThere = tmpHost.indexOf(":");
            if (isPortThere != -1) {
                host = tmpHost.substring(0, tmpHost.indexOf(":"));
                port = tmpHost.substring(tmpHost.indexOf(":") + 1);

            } else {
                port = "80";
                host = tmpHost;
            }
        }

        // ////////////////// Added since rapidshare not opening
        // Making it relative request.

        String modifyGet = header.toString().toLowerCase();

        if (modifyGet.startsWith("get http://")) {
            int i2 = modifyGet.indexOf("/", 11);
            header.replace(4, i2, "");
        }
        if (modifyGet.startsWith("post http://")) {
            int i2 = modifyGet.indexOf("/", 12);
            header.replace(5, i2, "");
        }

        // ///////////////////////////////////////////////

        final String proxyServerURL = ProxyConstants.webPHP_URL_HTTP;
        String isSecure = "";
        final String HeaderHost = ProxyConstants.webPHP_HOST_HTTP;

        if (header.indexOf("X-IS-SSL-RECURSIVE:") == -1) {
            isSecure = "N";
        } else {
            isSecure = "Y";
            // Now detect which Port 443 or 8443 ?
            // Like : abcd X-IS-SSL-RECURSIVE: 8443
            final int p1 = header.indexOf("X-IS-SSL-RECURSIVE: ");
            port = header.substring(p1 + 20, p1 + 20 + 4);
            port = "" + Integer.valueOf(port).intValue();
        }

        if (ProxyConstants.logLevel >= 1) {
            System.out.println(new Date() + " HTTPProxyThreadBrowser ::Started  " + currentThread()
                    + "URL Information :\n" + "Host=" + host + " Port=" + port + " ProxyServerURL="
                    + proxyServerURL + " HeaderHost=" + HeaderHost);
        }

        // Get Content length
        String contentLenght = "";
        final int contIndx = header.toString().toLowerCase().indexOf("content-length: ");
        if (contIndx != -1) {
            final int endI = header.indexOf("\r\n", contIndx + 17);
            contentLenght = header.substring(contIndx + 16, endI);
        }

        String data = header + "";
        data = data.replaceFirst("\r\n\r\n", "\r\nConnection: Close\r\n\r\n");

        // remove the proxy header to become high-anonymous proxy
        data = data.replaceFirst("Proxy-Connection: keep-alive\r\n", "");

        // Replace culprit KeepAlive
        // Should have used Regex
        data = data.replaceFirst("Keep-Alive: ", "X-Dummy-1: ");
        data = data.replaceFirst("keep-alive: ", "X-Dummy-1: ");
        data = data.replaceFirst("Keep-alive: ", "X-Dummy-1: ");
        data = data.replaceFirst("keep-Alive: ", "X-Dummy-1: ");

        data = data.replaceFirst("keep-alive", "Close");
        data = data.replaceFirst("Keep-Alive", "Close");
        data = data.replaceFirst("keep-Alive", "Close");
        data = data.replaceFirst("Keep-alive", "Close");

        int totallength = 0;
        if (!contentLenght.equals("")) {
            totallength = Integer.parseInt(contentLenght.trim()) + (data.length() + 61 + 1);
        } else {
            totallength = (data.length() + 61 + 1);
        }

        String header1 = "";
        header1 = header1 + "POST " + proxyServerURL + " HTTP/1.1\r\n";
        header1 = header1 + "Host: " + HeaderHost + "\r\n";
        header1 = header1 + "Connection: Close\r\n";
        header1 = header1 + "Content-Length: " + totallength + "\r\n";
        header1 = header1 + "Cache-Control: no-cache\r\n";

        if (!ProxyConstants.ORGANIZATION_HTTP_PROXY_USER_NAME.equals("")) {
            header1 = header1 + "Proxy-Authorization: " + proxyAuth + "\r\n";
        }

        count1 = totallength;

        header1 = header1 + "\r\n";
        server.write(header1.getBytes());
        server.flush();

        if (ProxyConstants.ENCRYPTION_ENABLED) {
            // Let know PHP waht are we using
            server.write(("Y".getBytes()));

            server.write(SimpleEncryptDecrypt.enc(host.getBytes()));
            // Padding with space
            for (int i = 0; i < 50 - host.length(); i++) {
                server.write(SimpleEncryptDecrypt.enc(" ".getBytes()));
            }
            server.write(SimpleEncryptDecrypt.enc(port.getBytes()));
            // Padding with space
            for (int i = 0; i < 10 - port.length(); i++) {
                server.write(SimpleEncryptDecrypt.enc(" ".getBytes()));
            }
            // Write fsockopen info
            server.write(SimpleEncryptDecrypt.enc(isSecure.getBytes()));

            // It is destination header
            server.write(SimpleEncryptDecrypt.enc(data.getBytes()));

        } else {
            // Let know PHP waht are we using
            server.write(("N".getBytes()));

            server.write(host.getBytes());
            // Padding with space
            for (int i = 0; i < 50 - host.length(); i++) {
                server.write(" ".getBytes());
            }
            server.write(port.getBytes());
            // Padding with space
            for (int i = 0; i < 10 - port.length(); i++) {
                server.write(" ".getBytes());
            }
            // Write fsockopen info
            server.write(isSecure.getBytes());

            // It is destination header
            server.write(data.getBytes());

        }
        server.flush();

        if (ProxyConstants.logLevel >= 2) {
            System.out.println(new Date() + " HTTPProxyThreadBrowser :: destination header   = "
                    + currentThread() + " \n" + data);
        }

        while (true) {
            numberRead = client.read(buffer);
            count2 = count2 + numberRead;
            if (numberRead == -1) {
                outgoing.close();
                incoming.close();
                break;
            }

            if (ProxyConstants.ENCRYPTION_ENABLED) {
                server.write(SimpleEncryptDecrypt.enc(buffer, numberRead), 0, numberRead);
            } else {
                server.write(buffer, 0, numberRead);
            }
            if (ProxyConstants.logLevel >= 3) {
                final ByteArrayOutputStream bo = new ByteArrayOutputStream();
                bo.write(buffer, 0, numberRead);
                System.out.println("::Readingbody::" + bo + "::Readingbody::");
            }
        }

        if (ProxyConstants.logLevel >= 1) {
            System.out.println(new Date() + " HTTPProxyThreadBrowser :: Finish " + currentThread());
        }
    } catch (final Exception e) {
    }
    synchronized (ProxyConstants.MUTEX) {
        ProxyConstants.TOTAL_TRANSFER = ProxyConstants.TOTAL_TRANSFER + count1 + count2;
    }
}

From source file:org.etudes.mneme.impl.ImportTextServiceImpl.java

/**
 * Process if it is recognized as an fill-in question.
 * /*w  w  w.  j av  a  2s.  co m*/
 * @param pool
 *         The pool to hold the question.
 * @param lines
 *         The lines to process.
 * @return true if successfully recognized and processed, false if not.
 * 
 * @throws AssessmentPermissionException
 */
protected boolean processTextFillIn(Pool pool, String[] lines) throws AssessmentPermissionException {
    // if there are only answers then that may be a fill-in question. Another case is if the question has braces that may be a fill-in question
    if (lines.length == 0)
        return false;

    boolean braces = false;
    boolean first = true;
    boolean foundAnswer = false;
    List<String> answers = new ArrayList<String>();
    String feedback = null;
    String hints = null;
    boolean explainReason = false;
    boolean isSurvey = false;
    boolean foundQuestionAttributes = false;
    boolean bracesNoAnswer = false;
    boolean isResponseTextual = false;

    boolean numberFormatEstablished = false;

    NumberingType numberingType = null;

    String clean = null;

    // question with braces may be a fill in question
    if ((lines[0].indexOf("{") != -1) && (lines[0].indexOf("}") != -1)
            && (lines[0].indexOf("{") < lines[0].indexOf("}"))) {
        String validateBraces = lines[0];
        while (validateBraces.indexOf("{") != -1) {
            validateBraces = validateBraces.substring(validateBraces.indexOf("{") + 1);
            int startBraceIndex = validateBraces.indexOf("{");
            int endBraceIndex = validateBraces.indexOf("}");
            String answer;

            if (startBraceIndex != -1 && endBraceIndex != -1) {
                if (endBraceIndex > startBraceIndex)
                    return false;
            }
            if (endBraceIndex != -1) {
                answer = validateBraces.substring(0, endBraceIndex);
                if (StringUtil.trimToNull(answer) == null) {
                    if (lines.length < 1)
                        return false;

                    bracesNoAnswer = true;
                } else {
                    if (!isResponseTextual) {
                        String[] multiAnswers = answer.split("\\|");
                        if (multiAnswers.length > 1) {
                            for (String multiAnswer : multiAnswers) {
                                try {
                                    Float.parseFloat(multiAnswer.trim());

                                } catch (NumberFormatException e) {
                                    isResponseTextual = true;
                                }
                            }
                        } else {
                            try {
                                Float.parseFloat(answer);

                            } catch (NumberFormatException e) {
                                isResponseTextual = true;
                            }
                        }
                    }
                }
            } else
                return false;

            validateBraces = validateBraces.substring(validateBraces.indexOf("}") + 1);
        }

        braces = true;
    }

    if (braces) {
        // hints and feedback
        for (String line : lines) {
            // ignore first line as first line is question text
            if (first) {
                first = false;
                continue;
            }

            if (line.startsWith("*") || line.matches("^\\[\\w.*\\].*"))
                return false;

            // hints and feedback
            String lower = line.toLowerCase();
            if (lower.startsWith(feedbackKey1) || lower.startsWith(feedbackKey2)) {
                String[] parts = StringUtil.splitFirst(line, ":");
                if (parts.length > 1)
                    feedback = parts[1].trim();
            } else if (lower.startsWith(hintKey)) {
                String[] parts = StringUtil.splitFirst(line, ":");
                if (parts.length > 1)
                    hints = parts[1].trim();
            } else if (lower.equalsIgnoreCase(reasonKey)) {
                explainReason = true;
            } else if (lower.equalsIgnoreCase(surveyKey)) {
                isSurvey = true;
            }
        }
    } else {
        for (String line : lines) {
            // ignore first line as first line is question text
            if (first) {
                first = false;
                continue;
            }

            if (line.startsWith("*") || line.matches("^\\[\\w.*\\].*"))
                return false;

            // hints and feedback
            String lower = line.toLowerCase();
            if (foundAnswer) {
                if (lower.startsWith(feedbackKey1) || lower.startsWith(feedbackKey2)) {
                    String[] parts = StringUtil.splitFirst(line, ":");
                    if (parts.length > 1)
                        feedback = parts[1].trim();
                    foundQuestionAttributes = true;
                } else if (lower.startsWith(hintKey)) {
                    String[] parts = StringUtil.splitFirst(line, ":");
                    if (parts.length > 1)
                        hints = parts[1].trim();
                    foundQuestionAttributes = true;
                } else if (lower.equalsIgnoreCase(reasonKey)) {
                    explainReason = true;
                    foundQuestionAttributes = true;
                } else if (lower.equalsIgnoreCase(surveyKey)) {
                    isSurvey = true;
                    foundQuestionAttributes = true;
                }

                // ignore the answer choices after hints or feedback found
                if (foundQuestionAttributes)
                    continue;
            }

            String[] answer = line.trim().split("\\s+");
            if (answer.length < 2)
                return false;

            if (!numberFormatEstablished) {
                numberingType = establishNumberingType(answer[0]);

                if (numberingType == NumberingType.none)
                    continue;

                numberFormatEstablished = true;
            }

            if (validateNumberingType(answer[0], numberingType)) {
                String answerChoice = line.substring(answer[0].length()).trim();
                answers.add(answerChoice);
                if (!foundAnswer)
                    foundAnswer = true;
            } else
                continue;
        }

        if (!foundAnswer)
            return false;
    }

    // create the question
    Question question = this.questionService.newQuestion(pool, "mneme:FillBlanks");
    FillBlanksQuestionImpl f = (FillBlanksQuestionImpl) (question.getTypeSpecificQuestion());

    // case sensitive
    f.setCaseSensitive(Boolean.FALSE.toString());

    //mutually exclusive
    f.setAnyOrder(Boolean.FALSE.toString());

    //if found answers append them at the end of question
    String questionText = lines[0].trim();
    if (!braces && foundAnswer) {
        StringBuffer buildAnswers = new StringBuffer();
        buildAnswers.append("{");
        for (String answer : answers) {
            if (!isResponseTextual) {
                String[] multiAnswers = answer.split("\\|");
                if (multiAnswers.length > 1) {
                    for (String multiAnswer : multiAnswers) {
                        try {
                            Float.parseFloat(multiAnswer.trim());

                        } catch (NumberFormatException e) {
                            isResponseTextual = true;
                        }
                    }
                } else {
                    try {
                        Float.parseFloat(answer);

                    } catch (NumberFormatException e) {
                        isResponseTextual = true;
                    }
                }
            }
            buildAnswers.append(answer);
            buildAnswers.append("|");
        }
        buildAnswers.replace(buildAnswers.length() - 1, buildAnswers.length(), "}");
        questionText = questionText.concat(buildAnswers.toString());
    }

    // set the text
    if (questionText.matches("^\\d+\\.\\s.*")) {
        String[] parts = StringUtil.splitFirst(questionText, ".");
        if (parts.length > 1) {
            questionText = parts[1].trim();
            clean = Validator.escapeHtml(questionText);
        } else
            return false;
    } else
        clean = Validator.escapeHtml(questionText);

    f.setText(clean);

    // text or numeric
    f.setResponseTextual(Boolean.toString(isResponseTextual));

    // add feedback
    if (StringUtil.trimToNull(feedback) != null) {
        question.setFeedback(Validator.escapeHtml(feedback));
    }

    // add hints
    if (StringUtil.trimToNull(hints) != null) {
        question.setHints(Validator.escapeHtml(hints));
    }

    // explain reason
    question.setExplainReason(explainReason);

    if (bracesNoAnswer && !isSurvey)
        return false;

    // survey
    question.setIsSurvey(isSurvey);

    // save
    question.getTypeSpecificQuestion().consolidate("");
    this.questionService.saveQuestion(question);

    return true;
}

From source file:org.etudes.mneme.impl.ImportQtiServiceImpl.java

/**
 * Process this item if it is recognized as a Respondous Fill in the blank.
 * //w ww  .  j av  a 2  s.c o  m
 * @param item
 *        The QTI item from the QTI file DOM.
 * @param pool
 *        The pool to add the question to.
 * @param pointsAverage
 *        A running average to contribute the question's point value to for the pool.
 * @return true if successfully recognized and processed, false if not.
 */
protected boolean processRespondousFillIn(Element item, Pool pool, Average pointsAverage)
        throws AssessmentPermissionException {
    // the attributes of a Fill In the Blank question
    boolean caseSensitive = false;
    boolean mutuallyExclusive = false;
    String presentation = null;
    float points = 0.0f;
    String feedback = null;
    boolean isResponseTextual = false;

    String externalId = null;
    List<String> answers = new ArrayList<String>();

    try {
        // identifier
        externalId = StringUtil.trimToNull(item.getAttribute("ident"));

        // presentation text
        // Respondous is using the format - presentation/material/mattext
        XPath presentationTextPath = new DOMXPath("presentation/material/mattext");
        List presentationMaterialTexts = presentationTextPath.selectNodes(item);
        StringBuilder presentationTextBuilder = new StringBuilder();
        for (Object presentationMaterialText : presentationMaterialTexts) {
            Element presentationTextElement = (Element) presentationMaterialText;
            XPath matTextPath = new DOMXPath(".");
            String matText = StringUtil.trimToNull(matTextPath.stringValueOf(presentationTextElement));

            if (matText != null)
                presentationTextBuilder.append(matText);
        }
        presentation = presentationTextBuilder.toString();

        if (presentation == null) {
            // QTI format - presentation/flow/material/mattext
            presentationTextPath = new DOMXPath("presentation/flow/material/mattext");
            presentation = StringUtil.trimToNull(presentationTextPath.stringValueOf(item));
        }

        if (presentation == null)
            return false;

        // reponse_str/response_fib
        XPath renderFibPath = new DOMXPath("presentation/response_str/render_fib");
        Element responseFib = (Element) renderFibPath.selectSingleNode(item);

        if (responseFib == null)
            return false;

        Attr promptAttr = responseFib.getAttributeNode("prompt");
        Attr rowsAttr = responseFib.getAttributeNode("rows");
        Attr columnsAttr = responseFib.getAttributeNode("columns");

        if (promptAttr == null || rowsAttr != null || columnsAttr != null)
            return false;

        if (!"Box".equalsIgnoreCase(promptAttr.getValue().trim()))
            return false;

        // score declaration - decvar
        XPath scoreDecVarPath = new DOMXPath("resprocessing/outcomes/decvar");
        Element scoreDecVarElement = (Element) scoreDecVarPath.selectSingleNode(item);

        if (scoreDecVarElement == null)
            return false;

        String vartype = StringUtil.trimToNull(scoreDecVarElement.getAttribute("vartype"));

        if ((vartype != null) && !("Integer".equalsIgnoreCase(vartype) || "Decimal".equalsIgnoreCase(vartype)))
            return false;

        String maxValue = StringUtil.trimToNull(scoreDecVarElement.getAttribute("maxvalue"));
        String minValue = StringUtil.trimToNull(scoreDecVarElement.getAttribute("minvalue"));

        try {
            points = Float.valueOf(maxValue);
        } catch (NumberFormatException e) {
            points = Float.valueOf("1.0");
        }

        // correct answer
        XPath respConditionPath = new DOMXPath("resprocessing/respcondition");
        List responses = respConditionPath.selectNodes(item);

        if (responses == null || responses.size() == 0)
            return false;

        for (Object oResponse : responses) {
            Element responseElement = (Element) oResponse;

            XPath responsePath = new DOMXPath("conditionvar/varequal");
            String responseText = StringUtil.trimToNull(responsePath.stringValueOf(responseElement));

            if (responseText != null) {
                // score
                XPath setVarPath = new DOMXPath("setvar");
                Element setVarElement = (Element) setVarPath.selectSingleNode(responseElement);

                if (setVarElement == null)
                    continue;

                if ("Add".equalsIgnoreCase(setVarElement.getAttribute("action"))) {
                    String pointsValue = StringUtil.trimToNull(setVarElement.getTextContent());

                    if (pointsValue == null)
                        pointsValue = "1.0";

                    answers.add(responseText.trim());

                    // feedback optional and can be Response, Solution, Hint
                    XPath displayFeedbackPath = new DOMXPath("displayfeedback");
                    Element displayFeedbackElement = (Element) displayFeedbackPath
                            .selectSingleNode(responseElement);

                    if (displayFeedbackElement == null)
                        continue;

                    String feedbackType = StringUtil
                            .trimToNull(displayFeedbackElement.getAttribute("feedbacktype"));

                    if (feedbackType == null || "Response".equalsIgnoreCase(feedbackType)) {
                        String linkRefId = StringUtil
                                .trimToNull(displayFeedbackElement.getAttribute("linkrefid"));

                        if (linkRefId == null)
                            continue;

                        XPath itemfeedbackPath = new DOMXPath(".//itemfeedback[@ident='" + linkRefId + "']");
                        Element feedbackElement = (Element) itemfeedbackPath.selectSingleNode(item);

                        if (feedbackElement == null)
                            continue;

                        XPath feedbackTextPath = new DOMXPath("material/mattext");
                        String feedbackText = StringUtil
                                .trimToNull(feedbackTextPath.stringValueOf(feedbackElement));

                        feedback = feedbackText;
                    }
                }
            }
        }

        if (answers.size() == 0)
            return false;

        // create the question
        Question question = this.questionService.newQuestion(pool, "mneme:FillBlanks");
        FillBlanksQuestionImpl f = (FillBlanksQuestionImpl) (question.getTypeSpecificQuestion());

        // case sensitive
        f.setCaseSensitive(Boolean.FALSE.toString());

        // mutually exclusive
        f.setAnyOrder(Boolean.FALSE.toString());

        StringBuffer buildAnswers = new StringBuffer();
        buildAnswers.append("{");
        for (String answer : answers) {
            if (!isResponseTextual) {
                try {
                    Float.parseFloat(answer);
                } catch (NumberFormatException e) {
                    isResponseTextual = true;
                }
            }
            buildAnswers.append(answer);
            buildAnswers.append("|");
        }
        buildAnswers.replace(buildAnswers.length() - 1, buildAnswers.length(), "}");
        String questionText = presentation.concat(buildAnswers.toString());

        String clean = HtmlHelper.cleanAndAssureAnchorTarget(questionText, true);

        f.setText(clean);

        // text or numeric
        f.setResponseTextual(Boolean.toString(isResponseTextual));

        // add feedback
        if (StringUtil.trimToNull(feedback) != null) {
            question.setFeedback(HtmlHelper.cleanAndAssureAnchorTarget(feedback, true));
        }

        // save
        question.getTypeSpecificQuestion().consolidate("");
        this.questionService.saveQuestion(question);

        // add to the points average
        pointsAverage.add(points);

        return true;
    } catch (JaxenException e) {
        return false;
    }
}

From source file:org.pentaho.di.core.Const.java

/**
 * Replaces environment variables in a string. For example if you set KETTLE_HOME as an environment variable, you can
 * use %%KETTLE_HOME%% in dialogs etc. to refer to this value. This procedures looks for %%...%% pairs and replaces
 * them including the name of the environment variable with the actual value. In case the variable was not set,
 * nothing is replaced!// w w w  . ja va2  s  .  c  o m
 *
 * @param string
 *          The source string where text is going to be replaced.
 *
 * @return The expanded string.
 * @deprecated use StringUtil.environmentSubstitute(): handles both Windows and unix conventions
 */
@Deprecated
public static final String replEnv(String string) {
    if (string == null) {
        return null;
    }
    StringBuffer str = new StringBuffer(string);

    int idx = str.indexOf("%%");
    while (idx >= 0) {
        // OK, so we found a marker, look for the next one...
        int to = str.indexOf("%%", idx + 2);
        if (to >= 0) {
            // OK, we found the other marker also...
            String marker = str.substring(idx, to + 2);
            String var = str.substring(idx + 2, to);

            if (var != null && var.length() > 0) {
                // Get the environment variable
                String newval = getEnvironmentVariable(var, null);

                if (newval != null) {
                    // Replace the whole bunch
                    str.replace(idx, to + 2, newval);
                    // System.out.println("Replaced ["+marker+"] with ["+newval+"]");

                    // The last position has changed...
                    to += newval.length() - marker.length();
                }
            }

        } else {
            // We found the start, but NOT the ending %% without closing %%
            to = idx;
        }

        // Look for the next variable to replace...
        idx = str.indexOf("%%", to + 1);
    }

    return str.toString();
}