Example usage for java.lang StringBuffer setLength

List of usage examples for java.lang StringBuffer setLength

Introduction

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

Prototype

@Override
public synchronized void setLength(int newLength) 

Source Link

Usage

From source file:org.apache.fop.render.ps.PSPainter.java

private void writeText(String text, int start, int len, int letterSpacing, int wordSpacing, int[][] dp,
        Font font, Typeface tf, boolean multiByte) throws IOException {
    PSGenerator generator = getGenerator();
    int end = start + len;
    int initialSize = len;
    initialSize += initialSize / 2;//from ww  w . j a v  a2s  .c o m

    boolean hasLetterSpacing = (letterSpacing != 0);
    boolean needTJ = false;

    int lineStart = 0;
    StringBuffer accText = new StringBuffer(initialSize);
    StringBuffer sb = new StringBuffer(initialSize);
    int[] dx = IFUtil.convertDPToDX(dp);
    int dxl = (dx != null ? dx.length : 0);
    for (int i = start; i < end; i++) {
        char orgChar = text.charAt(i);
        char ch;
        int cw;
        int glyphAdjust = 0;
        if (CharUtilities.isFixedWidthSpace(orgChar)) {
            //Fixed width space are rendered as spaces so copy/paste works in a reader
            ch = font.mapChar(CharUtilities.SPACE);
            cw = font.getCharWidth(orgChar);
            glyphAdjust = font.getCharWidth(ch) - cw;
        } else {
            if ((wordSpacing != 0) && CharUtilities.isAdjustableSpace(orgChar)) {
                glyphAdjust -= wordSpacing;
            }
            ch = font.mapChar(orgChar);
            cw = font.getCharWidth(orgChar);
        }

        if (dx != null && i < dxl - 1) {
            glyphAdjust -= dx[i + 1];
        }
        if (multiByte) {
            accText.append(HexEncoder.encode(ch));
        } else {
            char codepoint = (char) (ch % 256);
            PSGenerator.escapeChar(codepoint, accText); //add character to accumulated text
        }
        if (glyphAdjust != 0) {
            needTJ = true;
            if (sb.length() == 0) {
                sb.append('['); //Need to start TJ
            }
            if (accText.length() > 0) {
                if ((sb.length() - lineStart + accText.length()) > 200) {
                    sb.append(PSGenerator.LF);
                    lineStart = sb.length();
                }
                lineStart = writePostScriptString(sb, accText, multiByte, lineStart);
                sb.append(' ');
                accText.setLength(0); //reset accumulated text
            }
            sb.append(Integer.toString(glyphAdjust)).append(' ');
        }
    }
    if (needTJ) {
        if (accText.length() > 0) {
            if ((sb.length() - lineStart + accText.length()) > 200) {
                sb.append(PSGenerator.LF);
            }
            writePostScriptString(sb, accText, multiByte);
        }
        if (hasLetterSpacing) {
            sb.append("] " + formatMptAsPt(generator, letterSpacing) + " ATJ");
        } else {
            sb.append("] TJ");
        }
    } else {
        writePostScriptString(sb, accText, multiByte);
        if (hasLetterSpacing) {
            StringBuffer spb = new StringBuffer();
            spb.append(formatMptAsPt(generator, letterSpacing)).append(" 0 ");
            sb.insert(0, spb.toString());
            sb.append(" " + generator.mapCommand("ashow"));
        } else {
            sb.append(" " + generator.mapCommand("show"));
        }
    }
    generator.writeln(sb.toString());
}

From source file:com.tremolosecurity.provisioning.core.providers.BasicDB.java

@Override

public void deleteUser(User user, Map<String, Object> request) throws ProvisioningException {
    Connection con = null;//from  www .  j  a v a2  s .  c  o m

    int approvalID = 0;

    Workflow workflow = (Workflow) request.get("WORKFLOW");

    if (request.containsKey("APPROVAL_ID")) {
        approvalID = (Integer) request.get("APPROVAL_ID");
    }

    try {
        con = this.ds.getConnection();
        StringBuffer select = new StringBuffer();

        if (this.userSQL != null) {
            select.append(this.userSQL.replaceAll("\\%S", this.userPrimaryKey).replaceAll("\\%L", "?"));
        } else {
            select.append("SELECT ");
            this.getFieldName(this.userPrimaryKey, select).append(" FROM ").append(this.userTable)
                    .append(" WHERE ");
            this.getFieldName(this.userName, select).append("=?");
        }

        PreparedStatement ps = con.prepareStatement(select.toString());
        ps.setString(1, user.getUserID());
        ResultSet rs = ps.executeQuery();

        if (!rs.next()) {
            throw new ProvisioningException("User not found " + user.getUserID());
        }

        int id = rs.getInt(this.userPrimaryKey);

        rs.close();
        ps.close();

        con.setAutoCommit(false);

        if (this.customDBProvider != null) {
            this.customDBProvider.deleteUser(con, id);
        } else {
            select.setLength(0);
            select.append("DELETE FROM ").append(this.userTable).append(" WHERE ");
            this.getFieldName(this.userPrimaryKey, select).append("=?");
            ps = con.prepareStatement(select.toString());
            ps.setInt(1, id);
            ps.executeUpdate();

            switch (this.groupMode) {
            case None:
                break;
            case One2Many:
                select.setLength(0);
                select.append("DELETE FROM ").append(this.groupTable).append(" WHERE ");
                this.getFieldName(this.groupUserKey, select).append("=?");
                ps = con.prepareStatement(select.toString());
                ps.setInt(1, id);
                ps.executeUpdate();
                break;
            case Many2Many:
                many2manyDeleteGroups(con, select, id);
                break;
            }
        }

        con.commit();

        this.cfgMgr.getProvisioningEngine().logAction(this.name, true, ActionType.Delete, approvalID, workflow,
                "userName", user.getUserID());
    } catch (Exception e) {
        try {
            con.rollback();
        } catch (SQLException e1) {

        }

        throw new ProvisioningException("Could not delete user " + user.getUserID(), e);
    } finally {
        if (con != null) {

            try {
                con.close();
            } catch (SQLException e) {

            }
        }
    }

}

From source file:com.tremolosecurity.proxy.filter.PostProcess.java

protected void postProcess(HttpFilterRequest req, HttpFilterResponse resp, UrlHolder holder,
        HttpResponse response, String finalURL, HttpFilterChain curChain, HttpRequestBase httpRequest)
        throws IOException, Exception {
    boolean isText;
    HttpEntity entity = null;//from   w ww.  j  a va 2s.com

    try {
        entity = response.getEntity();
        /*if (entity != null) {
            entity = new BufferedHttpEntity(entity);
        }*/
    } catch (Throwable t) {
        throw new Exception(t);
    }

    InputStream ins = null;
    boolean entExists = false;

    if (entity == null) {
        resp.setStatus(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase());
        ins = new StringBufferInputStream("");
    } else {
        try {
            ins = entity.getContent();
            resp.setStatus(response.getStatusLine().getStatusCode(),
                    response.getStatusLine().getReasonPhrase());
            entExists = true;
        } catch (IllegalStateException e) {
            //do nothing
        }
    }

    if (entExists) {
        org.apache.http.Header hdr = response.getFirstHeader("Content-Type");
        org.apache.http.Header encoding = response.getFirstHeader("Content-Encoding");

        /*if (hdr == null) {
           isText = false;
        } else {
           isText = response.getFirstHeader("Content-Type").getValue().startsWith("text");
                   
           if (encoding != null ) {
              isText = (! encoding.getValue().startsWith("gzip")) && (! encoding.getValue().startsWith("deflate"));
           }
                   
           if (isText) {
              resp.setContentType(response.getFirstHeader("Content-Type").getValue());
              resp.setLocale(response.getLocale());
           }
        }*/
        isText = false;

        try {
            resp.setCharacterEncoding(null);
        } catch (Throwable t) {
            //we're not doing anything
        }

        StringBuffer stmp = new StringBuffer();
        if (response.getFirstHeader("Content-Type") != null) {
            resp.setContentType(response.getFirstHeader("Content-Type").getValue());
        }

        if (response.getLocale() != null) {
            resp.setLocale(response.getLocale());
        }

        org.apache.http.Header[] headers = response.getAllHeaders();
        for (int i = 0; i < headers.length; i++) {
            org.apache.http.Header header = headers[i];
            if (header.getName().equals("Content-Type")) {

                continue;
            } else if (header.getName().equals("Content-Type")) {

                continue;
            } else if (header.getName().equals("Content-Length")) {
                if (!header.getValue().equals("0")) {
                    continue;
                }
            } else if (header.getName().equals("Transfer-Encoding")) {
                continue;
            } else if (header.getName().equalsIgnoreCase("set-cookie")
                    || header.getName().equalsIgnoreCase("set-cookie2")) {
                //System.out.println(header.getValue());
                String cookieVal = header.getValue();
                /*if (cookieVal.endsWith("HttpOnly")) {
                   cookieVal = cookieVal.substring(0,cookieVal.indexOf("HttpOnly"));
                }
                        
                //System.out.println(cookieVal);*/

                List<HttpCookie> cookies = HttpCookie.parse(cookieVal);
                Iterator<HttpCookie> it = cookies.iterator();
                while (it.hasNext()) {
                    HttpCookie cookie = it.next();
                    String cookieFinalName = cookie.getName();
                    if (cookieFinalName.equalsIgnoreCase("JSESSIONID")) {
                        stmp.setLength(0);
                        stmp.append("JSESSIONID").append('-')
                                .append(holder.getApp().getName().replaceAll(" ", "|"));
                        cookieFinalName = stmp.toString();
                    }
                    Cookie respcookie = new Cookie(cookieFinalName, cookie.getValue());
                    respcookie.setComment(cookie.getComment());
                    if (cookie.getDomain() != null) {
                        respcookie.setDomain(cookie.getDomain());
                    }

                    if (cookie.hasExpired()) {
                        respcookie.setMaxAge(0);
                    } else {
                        respcookie.setMaxAge((int) cookie.getMaxAge());
                    }
                    respcookie.setPath(cookie.getPath());

                    respcookie.setSecure(cookie.getSecure());
                    respcookie.setVersion(cookie.getVersion());
                    resp.addCookie(respcookie);
                }
            } else if (header.getName().equals("Location")) {

                if (holder.isOverrideHost()) {
                    fixRedirect(req, resp, finalURL, header);
                } else {
                    resp.addHeader("Location", header.getValue());
                }
            } else {
                resp.addHeader(header.getName(), header.getValue());
            }

        }

        curChain.setIns(ins);
        curChain.setText(isText);
        curChain.setEntity(entity);
        curChain.setHttpRequestBase(httpRequest);

        //procData(req, resp, holder, isText, entity, ins);

    } else {
        isText = false;
    }
}

From source file:edu.isi.pfindr.learn.util.PairsFileIO.java

public void generatePairsFromTwoDifferentFilesWithClass(String inputFilePath1, String inputFilePath2,
        String outputFilePath) {/*from  ww w . ja va 2 s  . c  o  m*/

    List<String> phenotypeList1 = new ArrayList<String>();
    List<String> phenotypeList2 = new ArrayList<String>();
    try {
        phenotypeList1 = FileUtils.readLines(new File(inputFilePath1));
        phenotypeList2 = FileUtils.readLines(new File(inputFilePath2));
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
    String[] phenotype1, phenotype2;
    StringBuffer outputBuffer = new StringBuffer();

    //List<String> resultList = new ArrayList<String>();
    BufferedWriter bw = null;
    try {
        bw = new BufferedWriter(new FileWriter(outputFilePath));
        int count = 0;

        for (int i = 0; i < phenotypeList1.size(); i++) {
            phenotype1 = phenotypeList1.get(i).split("\t");
            for (int j = 0; j < phenotypeList2.size(); j++) {
                count++;
                phenotype2 = phenotypeList2.get(j).split("\t");
                System.out.println("i " + i + "j " + j + "  " + phenotype1[0] + " " + phenotype2[0]);
                if (phenotype1[1].equals(phenotype2[1])) { //if the classes are the same
                    //if (phenotype1[1].equals(phenotype2[0])) { //if the classes are the same

                    //resultList.add(String.format("%s\t%s\t%d", phenotype1[3], phenotype2[3], 1));
                    //resultList.add(String.format("%s\t%s\t%d", phenotype1[0], phenotype2[1], 1));
                    outputBuffer.append(String.format("%s\t%s\t%d", phenotype1[0], phenotype2[0], 1))
                            .append("\n");
                    //bw.write(String.format("%s\t%s\t%d", phenotype1[0], phenotype2[0], 1) + "\n");
                } else {
                    //resultList.add(String.format("%s\t%s\t%d", phenotype1[3], phenotype2[3], 0));
                    //resultList.add(String.format("%s\t%s\t%d", phenotype1[0], phenotype2[1], 0));
                    //bw.write(String.format("%s\t%s\t%d", phenotype1[0], phenotype2[0], 0) + "\n");
                    outputBuffer.append(String.format("%s\t%s\t%d", phenotype1[0], phenotype2[0], 0))
                            .append("\n");
                }
                bw.append(outputBuffer.toString());
                outputBuffer.setLength(0);
            }
        }
        bw.flush();
        System.out.println("The count is: " + count);
    } catch (IOException io) {
        try {
            if (bw != null)
                bw.close();
            io.printStackTrace();
        } catch (IOException e) {
            System.out.println("Problem occured while closing output stream  " + bw);
            e.printStackTrace();
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (bw != null)
                bw.close();
        } catch (IOException e) {
            System.out.println("Problem occured while closing output stream  " + bw);
            e.printStackTrace();
        }
    }
}

From source file:com.ikanow.infinit.e.data_model.driver.InfiniteDriver.java

private ObjectId createCustomPluginTask(CustomMapReduceJobPojo taskConfig, Collection<String> dependencies,
        Collection<ObjectId> communities, ResponseObject response, boolean bUpdate) {
    ObjectId retVal = null;//w  w w  .ja  v a  2 s  .  c om
    try {
        StringBuffer url = new StringBuffer(apiRoot).append("custom/mapreduce/");
        if (bUpdate) {
            if (taskConfig._id != null) {
                url.append("updatejob/").append(taskConfig._id.toString()).append("/");
            } else {
                url.append("updatejob/").append(taskConfig.jobtitle).append("/");
                taskConfig.jobtitle = null;
            } //TESTED
        } else {
            url.append("schedulejob/");
        }
        if (null != communities) {
            for (ObjectId communityId : communities) {
                url.append(communityId.toString()).append(',');
            }
            url.setLength(url.length() - 1);
        } else {
            url.append("null");
        }
        url.append('/');

        if ((null != taskConfig.jobDependencies) && !taskConfig.jobDependencies.isEmpty()) {
            for (ObjectId jobId : taskConfig.jobDependencies) {
                url.append(jobId.toString()).append(',');
            }
            url.setLength(url.length() - 1);
        } else if ((null != dependencies) && !dependencies.isEmpty()) {
            for (String jobTitle : dependencies) {
                url.append(jobTitle).append(',');
            }
            url.setLength(url.length() - 1);
        } else {
            url.append("null");
        }
        url.append("/");

        // "nextRunTime"==first Schedule (date)
        if (null != taskConfig.firstSchedule) {
            taskConfig.nextRunTime = taskConfig.firstSchedule.getTime();
        }

        String json = sendRequest(url.toString(), ApiManager.mapToApi(taskConfig, null));
        ResponsePojo internal_responsePojo = ResponsePojo.fromApi(json, ResponsePojo.class);
        ResponseObject internal_ro = internal_responsePojo.getResponse();
        response = shallowCopy(response, internal_ro);

        if (response.isSuccess()) {
            JsonPrimitive retValObj = (JsonPrimitive) internal_responsePojo.getData();
            retVal = new ObjectId(retValObj.getAsString());
        }
    } catch (Exception e) {
        response.setSuccess(false);
        response.setMessage(e.getMessage());
    }
    return retVal;
}

From source file:org.sakaiproject.genericdao.springjdbc.JdbcGenericDao.java

private void executeDDLforType(InputStream sqlDDL, Class<?> type) {
    // Now run the DDL commands if possible
    try {//from  ww w . jav a  2s .  c  om
        if (isAutoCommitDDL()) {
            commitTransaction(); // start the transaction
        }
        BufferedReader r = new BufferedReader(new InputStreamReader(sqlDDL));
        try {
            // read the first line, skipping any '--' comment lines
            boolean firstLine = true;
            StringBuffer buf = new StringBuffer();
            for (String line = r.readLine(); line != null; line = r.readLine()) {
                line = line.trim();
                if (line.startsWith("--"))
                    continue;
                if (line.length() == 0)
                    continue;

                // add the line to the buffer
                buf.append(' ');
                buf.append(line);

                // process if the line ends with a ';'
                boolean process = line.endsWith(";");

                if (!process)
                    continue;

                // remove trailing ';'
                buf.setLength(buf.length() - 1);

                String ddl = buf.toString().trim();
                // FIXME do replacements even if we do not know the type
                if (type != null) {
                    // handle ddl replacements
                    ddl = handleTypeReplacements(type, ddl);
                }

                // run the first line as the test - if it fails, we are done
                if (firstLine) {
                    firstLine = false;
                    try {
                        if (showSQL) {
                            logInfo("DDL=" + ddl);
                        }
                        getSpringJdbcTemplate().execute(ddl);
                    } catch (DataAccessException e) {
                        //log.info("Could not to execute first DDL ("+ddl+"), skipping the rest");
                        logInfo("Could not execute first DDL line, skipping the rest: " + e.getMessage() + ":"
                                + e.getCause());
                        //e.printStackTrace();
                        return;
                    }
                } else {
                    // run other lines, until done - any one can fail (we will report it)
                    try {
                        if (showSQL) {
                            logInfo("DDL=" + ddl);
                        }
                        getSpringJdbcTemplate().execute(ddl);
                    } catch (DataAccessException e) {
                        throw new IllegalArgumentException("Failed while executing ddl: " + e.getMessage(), e);
                    }
                }
                if (isAutoCommitDDL()) {
                    commitTransaction();
                }

                // clear the buffer for next
                buf.setLength(0);
            }
        } catch (IOException any) {
            throw new RuntimeException("Failure while processing DDL", any);
        } finally {
            try {
                r.close();
            } catch (IOException any) {
                //log.warn("Failure while closing DDL inputstream reader", any);
            }
            // close the connection used for this DDL
            if (isAutoCommitDDL()) {
                closeConnection();
            }
        }
    } finally {
        try {
            sqlDDL.close();
        } catch (IOException any) {
            //log.warn("Failure while closing inputstream", any);
        }
    }
}

From source file:com.tremolosecurity.unison.openstack.KeystoneProvisioningTarget.java

public UserAndID lookupUser(String userID, Set<String> attributes, Map<String, Object> request, KSToken token,
        HttpCon con) throws Exception {

    KSUser fromKS = null;/* w  ww.  j  a va 2s.  co m*/

    List<NameValuePair> qparams = new ArrayList<NameValuePair>();
    qparams.add(new BasicNameValuePair("domain_id", this.usersDomain));
    qparams.add(new BasicNameValuePair("name", userID));

    StringBuffer b = new StringBuffer();
    b.append(this.url).append("/users?").append(URLEncodedUtils.format(qparams, "UTF-8"));
    String fullURL = b.toString();
    String json = this.callWS(token.getAuthToken(), con, fullURL);

    Gson gson = new Gson();
    UserLookupResponse resp = gson.fromJson(json, UserLookupResponse.class);

    if (resp.getUsers().isEmpty()) {
        return null;
    } else {
        fromKS = resp.getUsers().get(0);

        User user = new User(fromKS.getName());

        if (attributes.contains("name")) {
            user.getAttribs().put("name", new Attribute("name", fromKS.getName()));
        }

        if (attributes.contains("id")) {
            user.getAttribs().put("id", new Attribute("id", fromKS.getId()));
        }

        if (attributes.contains("email") && fromKS.getEmail() != null) {
            user.getAttribs().put("email", new Attribute("email", fromKS.getEmail()));
        }

        if (attributes.contains("description") && fromKS.getDescription() != null) {
            user.getAttribs().put("description", new Attribute("description", fromKS.getEmail()));
        }

        if (attributes.contains("enabled")) {
            user.getAttribs().put("enabled", new Attribute("enabled", Boolean.toString(fromKS.getEnabled())));
        }

        if (!rolesOnly) {
            b.setLength(0);
            b.append(this.url).append("/users/").append(fromKS.getId()).append("/groups");
            json = this.callWS(token.getAuthToken(), con, b.toString());

            GroupLookupResponse gresp = gson.fromJson(json, GroupLookupResponse.class);

            for (KSGroup group : gresp.getGroups()) {
                user.getGroups().add(group.getName());
            }
        }

        if (attributes.contains("roles")) {
            b.setLength(0);
            b.append(this.url).append("/role_assignments?user.id=").append(fromKS.getId())
                    .append("&include_names=true");
            json = this.callWS(token.getAuthToken(), con, b.toString());

            RoleAssignmentResponse rar = gson.fromJson(json, RoleAssignmentResponse.class);
            Attribute attr = new Attribute("roles");
            for (KSRoleAssignment role : rar.getRole_assignments()) {
                if (role.getScope().getProject() != null) {
                    attr.getValues()
                            .add(gson.toJson(new Role(role.getRole().getName(), "project",
                                    role.getScope().getProject().getDomain().getName(),
                                    role.getScope().getProject().getName())));
                } else {
                    attr.getValues().add(gson.toJson(new Role(role.getRole().getName(), "domain",
                            role.getScope().getDomain().getName())));
                }
            }

            if (!attr.getValues().isEmpty()) {
                user.getAttribs().put("roles", attr);
            }

        }

        UserAndID userAndId = new UserAndID();
        userAndId.setUser(user);
        userAndId.setId(fromKS.getId());

        return userAndId;
    }

}

From source file:org.codehaus.mojo.dbupgrade.sqlexec.DefaultSQLExec.java

/**
 * read in lines and execute them//  w ww .jav a2 s  . c o  m
 */
private void runStatements(Reader reader, PrintStream out) throws SQLException, IOException {
    String line;

    StringBuffer sql = new StringBuffer();

    BufferedReader in = new BufferedReader(reader);

    while ((line = in.readLine()) != null) {
        if (!config.isKeepFormat()) {
            line = line.trim();
        }

        if (!config.isKeepFormat()) {
            if (line.startsWith("#")) {
                continue;
            }
            if (line.startsWith("//")) {
                continue;
            }
            if (line.startsWith("--")) {
                continue;
            }
            StringTokenizer st = new StringTokenizer(line);
            if (st.hasMoreTokens()) {
                String token = st.nextToken();
                if ("REM".equalsIgnoreCase(token)) {
                    continue;
                }
            }
        }

        if (!config.isKeepFormat()) {
            sql.append(" ").append(line);
        } else {
            sql.append("\n").append(line);
        }

        // SQL defines "--" as a comment to EOL
        // and in Oracle it may contain a hint
        // so we cannot just remove it, instead we must end it
        if (!config.isKeepFormat()) {
            if (SqlSplitter.containsSqlEnd(line, config.getDelimiter()) == SqlSplitter.NO_END) {
                sql.append("\n");
            }
        }

        DelimiterType delimiterType = this.config.getDelimiterType();
        String delimiter = this.config.getDelimiter();

        if ((delimiterType.equals(DelimiterType.NORMAL) && SqlSplitter.containsSqlEnd(line, delimiter) > 0)
                || (delimiterType.equals(DelimiterType.ROW) && line.trim().equals(delimiter))) {
            execSQL(sql.substring(0, sql.length() - delimiter.length()), out);
            sql.setLength(0); // clean buffer
        }
    }

    // Catch any statements not followed by ;
    if (!sql.toString().equals("")) {
        execSQL(sql.toString(), out);
    }
}

From source file:com.dragonflow.StandardMonitor.URLOriginalMonitor.java

static long[] fillBufferParse(String s, SocketSession socketsession, SocketStream socketstream, Socket socket,
        long l, StringBuffer stringbuffer, long l1, long l2) throws IOException {
    if ((debugURL & kDebugIO) != 0) {
        LogManager.log("RunMonitor", "reading HTTP 1.1 reply");
    }/* w w w .  j a  v a 2 s .co  m*/
    socketstream.receivedReply = false;
    long l3 = 0L;
    long l4 = 0L;
    long l5 = -1L;
    try {
        if (stringbuffer != null) {
            stringbuffer.setLength(0);
        }
        int i = (int) (l - System.currentTimeMillis());
        if ((long) i <= kTimedOutValue) {
            if ((debugURL & kDebugIO) != 0) {
                LogManager.log("RunMonitor", "1.1 reply timeout, " + i);
            }
            throw new InterruptedIOException();
        }
        Platform.setSocketTimeout(socket, i);
        long al1[] = readHeader(socketstream, stringbuffer, l2, l);
        l5 = al1[2];
        if (!s.equals("HEAD")) {
            long l6 = al1[0];
            l4 = al1[1];
            if (l6 == kReadChunked) {
                do {
                    String s1 = socketstream.HTTPReadLine();
                    if ((debugURL & kDebugIO) != 0) {
                        LogManager.log("RunMonitor", "read chunk header=" + s1);
                    }
                    if (s1 == null) {
                        socketstream.receivedEndOfStream = true;
                        break;
                    }
                    socketstream.receivedReply = true;
                    long l7 = TextUtils.readHex(s1);
                    if (l7 == 0L) {
                        break;
                    }
                    l3 += readData(socketsession, socketstream, socket, stringbuffer, l1, l, l7);
                    socketstream.HTTPReadLine();
                } while (true);
                String s2;
                do {
                    s2 = socketstream.HTTPReadLine();
                    if ((debugURL & kDebugIO) != 0) {
                        LogManager.log("RunMonitor", "read chunk footer=" + s2);
                    }
                    if (s2 == null) {
                        socketstream.receivedEndOfStream = true;
                        break;
                    }
                    socketstream.receivedReply = true;
                } while (s2.length() != 0);
            } else {
                l3 = readData(socketsession, socketstream, socket, stringbuffer, l1, l, l6);
            }
        }
    } catch (SocketException socketexception) {
        if (l3 != 0L) {
            throw socketexception;
        }
    }
    if (l - System.currentTimeMillis() <= kTimedOutValue) {
        throw new InterruptedIOException();
    } else {
        long al[] = new long[3];
        al[0] = l3;
        al[1] = l4;
        al[2] = l5;
        return al;
    }
}

From source file:com.bstek.dorado.config.text.DispatchableTextParser.java

/**
 * ????Map?Map??? ????//from   w w  w. java  2  s.  c o m
 * {@link #HEADER_ATTRIBUTE}??
 */
protected Map<String, Object> parseToAttributes(char[] charArray, TextParseContext context) throws Exception {
    Map<String, Object> attributes = new HashMap<String, Object>();
    int status;

    if (supportsHeader()) {
        String header = parseHeader(charArray, context);
        if (header != null)
            attributes.put(HEADER_ATTRIBUTE, header);
    }

    status = BEFORE_ATTRIBUTE_NAME;
    StringBuffer nameStack = new StringBuffer();
    for (int currentIndex = context.getCurrentIndex(); currentIndex < charArray.length; currentIndex++) {
        char c = charArray[currentIndex];
        context.setCurrentIndex(currentIndex);

        switch (status) {
        case BEFORE_ATTRIBUTE_NAME:
            if (isValidPropertyNameChar(c)) {
                status = IN_ATTRIBUTE_NAME;
                nameStack.append(c);
            } else if (isIgnoredChar(c)) {
                continue;
            } else if (c == ':') {
                throw new TextParseException(charArray, context);
            }
            break;
        case IN_ATTRIBUTE_NAME:
            if (isValidPropertyNameChar(c)) {
                nameStack.append(c);
            } else if (isIgnoredChar(c)) {
                status = AFTER_ATTRIBUTE_NAME;
                continue;
            } else if (c == ':') {
                status = BEFORE_ATTRIBUTE_VALUE;
                continue;
            } else if (c == ';') {
                throw new TextParseException(charArray, context);
            }
            break;
        case AFTER_ATTRIBUTE_NAME:
            if (isValidPropertyNameChar(c)) {
                throw new TextParseException(charArray, context);
            } else if (isIgnoredChar(c)) {
                continue;
            } else if (c == ':') {
                status = BEFORE_ATTRIBUTE_VALUE;
                continue;
            } else if (c == ';') {
                throw new TextParseException(charArray, context);
            }
            break;
        case BEFORE_ATTRIBUTE_VALUE:
            if (nameStack.length() == 0) {
                throw new TextParseException("Attribute name can not be empty.", charArray, context);
            } else {
                String name = nameStack.toString();
                char firstC = name.charAt(0);
                if (firstC >= '0' && firstC <= '9') {
                    throw new TextParseException("Attribute name [" + name + "] can not start with number.");
                }

                Object value = dispatchAttribute(name, charArray, context);
                attributes.put(name, value);

                currentIndex = context.getCurrentIndex();
                status = BEFORE_ATTRIBUTE_NAME;
                nameStack.setLength(0);
            }
            break;
        }
    }

    if (nameStack.length() > 0) {
        throw new TextParseException(charArray, context);
    }
    return attributes;
}