Example usage for java.lang Character toString

List of usage examples for java.lang Character toString

Introduction

In this page you can find the example usage for java.lang Character toString.

Prototype

public static String toString(int codePoint) 

Source Link

Document

Returns a String object representing the specified character (Unicode code point).

Usage

From source file:edu.harvard.iq.dataverse.ingest.tabulardata.impl.plugins.por.PORFileReader.java

private void decodeData(BufferedReader reader) throws IOException {
    dbgLog.fine("decodeData(): start");
    // TODO: get rid of this "variableTypeFinal"; -- L.A. 4.0 beta
    int[] variableTypeFinal = new int[varQnty];
    dateFormatList = new String[varQnty];

    // create a File object to save the tab-delimited data file
    File tabDelimitedDataFile = File.createTempFile("tempTabfile.", ".tab");
    ingesteddata.setTabDelimitedFile(tabDelimitedDataFile);

    FileOutputStream fileOutTab = null;
    PrintWriter pwout = null;/*from  ww  w.j  av  a2 s  .  c  o  m*/

    try {
        fileOutTab = new FileOutputStream(tabDelimitedDataFile);
        pwout = new PrintWriter(new OutputStreamWriter(fileOutTab, "utf8"), true);

        variableFormatTypeList = new String[varQnty];
        for (int i = 0; i < varQnty; i++) {
            variableFormatTypeList[i] = SPSSConstants.FORMAT_CATEGORY_TABLE
                    .get(printFormatTable.get(variableNameList.get(i)));
            formatCategoryTable.put(variableNameList.get(i), variableFormatTypeList[i]);
        }

        // contents (variable) checker concering decimals
        Arrays.fill(variableTypeFinal, 0);

        // raw-case counter
        int j = 0; // case

        // use while instead for because the number of cases (observations) is usually unknown
        FBLOCK: while (true) {
            j++;

            // case(row)-wise storage object; to be updated after each row-reading

            String[] casewiseRecordForTabFile = new String[varQnty];
            // warning: the above object is later shallow-copied to the
            // data object for calculating a UNF value/summary statistics
            //

            for (int i = 0; i < varQnty; i++) {
                // check the type of this variable
                boolean isStringType = variableTypeTable.get(variableNameList.get(i)) > 0;

                if (isStringType) {
                    // String case
                    variableTypeFinal[i] = -1;

                    StringBuilder sb_StringLengthBase30 = new StringBuilder("");
                    int stringLengthBase10 = 0;
                    String buffer = "";
                    char[] tmp = new char[1];

                    int nint;
                    while ((nint = reader.read(tmp)) > 0) {
                        buffer = Character.toString(tmp[0]);
                        if (buffer.equals("/")) {
                            break;
                        } else if (buffer.equals("Z")) {
                            if (i == 0) {
                                // the reader has passed the last case; subtract 1 from the j counter
                                caseQnty = j - 1;
                                break FBLOCK;
                            }
                        } else {
                            sb_StringLengthBase30.append(buffer);
                        }

                    }

                    if (nint == 0) {
                        // no more data to be read (reached the eof)
                        caseQnty = j - 1;
                        break FBLOCK;
                    }

                    dbgLog.finer(
                            j + "-th case " + i + "=th var:datum length=" + sb_StringLengthBase30.toString());

                    // this length value should be a positive integer
                    Matcher mtr = pattern4positiveInteger.matcher(sb_StringLengthBase30.toString());
                    if (mtr.matches()) {
                        stringLengthBase10 = Integer.valueOf(sb_StringLengthBase30.toString(), 30);
                    } else {
                        // reading error case
                        throw new IOException("reading F(data) section: string: length is not integer");
                    }

                    // read this string-variable's contents after "/"
                    char[] char_datumString = new char[stringLengthBase10];
                    reader.read(char_datumString);

                    String datum = new String(char_datumString);
                    casewiseRecordForTabFile[i] = "\""
                            + datum.replaceAll("\"", Matcher.quoteReplacement("\\\"")) + "\"";
                    // end of string case
                } else {

                    // numeric case
                    StringBuilder sb_datumNumericBase30 = new StringBuilder("");
                    boolean isMissingValue = false;
                    String datum = null;
                    String datumForTabFile = null;
                    String datumDateFormat = null;

                    String buffer = "";
                    char[] tmp = new char[1];
                    int nint;
                    while ((nint = reader.read(tmp)) > 0) {
                        sb_datumNumericBase30.append(buffer);
                        buffer = Character.toString(tmp[0]);

                        if (buffer.equals("/")) {
                            break;
                        } else if (buffer.equals("Z")) {
                            if (i == 0) {
                                // the reader has passed the last case
                                // subtract 1 from the j counter
                                dbgLog.fine("Z-mark was detected");
                                caseQnty = j - 1;
                                break FBLOCK;
                            }
                        } else if (buffer.equals("*")) {
                            // '*' is the first character of the system missing value
                            datumForTabFile = MissingValueForTextDataFile;
                            datum = null;
                            isMissingValue = true;

                            // read next char '.' as part of the missing value
                            reader.read(tmp);
                            buffer = Character.toString(tmp[0]);
                            break;
                        }

                    }
                    if (nint == 0) {
                        // no more data to be read; reached the eof
                        caseQnty = j - 1;
                        break FBLOCK;
                    }

                    // follow-up process for non-missing-values
                    if (!isMissingValue) {
                        // decode a numeric datum as String
                        String datumNumericBase30 = sb_datumNumericBase30.toString();
                        Matcher matcher = pattern4Integer.matcher(datumNumericBase30);

                        if (matcher.matches()) {
                            // integer case
                            datum = Long.valueOf(datumNumericBase30, 30).toString();
                        } else {
                            // double case
                            datum = doubleNumberFormatter.format(base30Tobase10Conversion(datumNumericBase30));
                        }

                        // now check format (if date or time)
                        String variableFormatType = variableFormatTypeList[i];

                        if (variableFormatType.equals("date")) {
                            variableTypeFinal[i] = -1;
                            long dateDatum = Long.parseLong(datum) * 1000L - SPSS_DATE_OFFSET;
                            datum = sdf_ymd.format(new Date(dateDatum));
                            datumDateFormat = sdf_ymd.toPattern();

                        } else if (variableFormatType.equals("time")) {
                            variableTypeFinal[i] = -1;
                            int formatDecimalPointPosition = formatDecimalPointPositionList.get(i);

                            if (printFormatTable.get(variableNameList.get(i)).equals("DTIME")) {

                                if (datum.indexOf(".") < 0) {
                                    long dateDatum = Long.parseLong(datum) * 1000L - SPSS_DATE_BIAS;
                                    datum = sdf_dhms.format(new Date(dateDatum));
                                    // don't save date format for dtime
                                } else {
                                    // decimal point included
                                    String[] timeData = datum.split("\\.");
                                    long dateDatum = Long.parseLong(timeData[0]) * 1000L - SPSS_DATE_BIAS;
                                    StringBuilder sb_time = new StringBuilder(
                                            sdf_dhms.format(new Date(dateDatum)));

                                    if (formatDecimalPointPosition > 0) {
                                        sb_time.append(
                                                "." + timeData[1].substring(0, formatDecimalPointPosition));
                                    }

                                    datum = sb_time.toString();
                                    // DTIME is weird date/time format that no one uses outside of 
                                    // SPSS; so we are not even going to bother trying to save
                                    // this variable as a datetime. 
                                }

                            } else if (printFormatTable.get(variableNameList.get(i)).equals("DATETIME")) {
                                // TODO: 
                                // (for both datetime and "dateless" time)
                                // keep the longest of the matching formats - i.e., if there are *some*
                                // values in the vector that have thousands of a second, that should be 
                                // part of the saved format!
                                //  -- L.A. Aug. 12 2014 

                                if (!datum.contains(".")) {
                                    long dateDatum = Long.parseLong(datum) * 1000L - SPSS_DATE_OFFSET;
                                    datum = sdf_ymdhms.format(new Date(dateDatum));
                                    datumDateFormat = sdf_ymdhms.toPattern();
                                } else {
                                    // decimal point included
                                    String[] timeData = datum.split("\\.");
                                    long dateDatum = Long.parseLong(timeData[0]) * 1000L - SPSS_DATE_OFFSET;
                                    StringBuilder sb_time = new StringBuilder(
                                            sdf_ymdhms.format(new Date(dateDatum)));

                                    if (formatDecimalPointPosition > 0) {
                                        sb_time.append(
                                                "." + timeData[1].substring(0, formatDecimalPointPosition));
                                    }

                                    datum = sb_time.toString();
                                    datumDateFormat = sdf_ymdhms.toPattern()
                                            + (formatDecimalPointPosition > 0 ? ".S" : "");
                                }

                            } else if (printFormatTable.get(variableNameList.get(i)).equals("TIME")) {

                                if (!datum.contains(".")) {
                                    long dateDatum = Long.parseLong(datum) * 1000L;
                                    datum = sdf_hms.format(new Date(dateDatum));
                                    datumDateFormat = sdf_hms.toPattern();
                                } else {
                                    // decimal point included
                                    String[] timeData = datum.split("\\.");
                                    long dateDatum = Long.parseLong(timeData[0]) * 1000L;
                                    StringBuilder sb_time = new StringBuilder(
                                            sdf_hms.format(new Date(dateDatum)));

                                    if (formatDecimalPointPosition > 0) {
                                        sb_time.append(
                                                "." + timeData[1].substring(0, formatDecimalPointPosition));
                                    }

                                    datum = sb_time.toString();
                                    datumDateFormat = sdf_hms.toPattern()
                                            + (formatDecimalPointPosition > 0 ? ".S" : "");
                                }
                            }

                        } else if (variableFormatType.equals("other")) {

                            if (printFormatTable.get(variableNameList.get(i)).equals("WKDAY")) {
                                // day of week
                                variableTypeFinal[i] = -1;
                                datum = SPSSConstants.WEEKDAY_LIST.get(Integer.valueOf(datum) - 1);

                            } else if (printFormatTable.get(variableNameList.get(i)).equals("MONTH")) {
                                // month
                                variableTypeFinal[i] = -1;
                                datum = SPSSConstants.MONTH_LIST.get(Integer.valueOf(datum) - 1);
                            }
                        }

                        // since value is not missing, set both values to be the same
                        datumForTabFile = datum;

                        // decimal-point check (variable is integer or not)
                        if (variableTypeFinal[i] == 0) {
                            if (datum.contains(".")) {
                                variableTypeFinal[i] = 1;
                                decimalVariableSet.add(i);
                            }
                        }
                    }

                    if (datumDateFormat != null) {
                        dateFormatList[i] = datumDateFormat;
                    }
                    casewiseRecordForTabFile[i] = datumForTabFile;

                } // end: if: string vs numeric variable

            } // end:for-loop-i (variable-wise loop)

            // print the i-th case; use casewiseRecord to dump the current case to the tab-delimited file
            pwout.println(StringUtils.join(casewiseRecordForTabFile, "\t"));

        } // end: while-block
    } finally {
        // close the print writer
        if (pwout != null) {
            pwout.close();
        }
    }

    ///smd.setDecimalVariables(decimalVariableSet);
    dataTable.setCaseQuantity(new Long(caseQnty));

    dbgLog.fine("decodeData(): end");
}

From source file:org.globus.gsi.gssapi.GlobusGSSContextImpl.java

/**
 * This function drives the initiating side of the context establishment
 * process. It is expected to be called in tandem with the
 * {@link #acceptSecContext(byte[], int, int) acceptSecContext} function.
 * <BR>/*ww  w .  j a  v a  2  s  .  c  om*/
 * The behavior of context establishment process can be modified by
 * {@link GSSConstants#GSS_MODE GSSConstants.GSS_MODE},
 * {@link GSSConstants#DELEGATION_TYPE GSSConstants.DELEGATION_TYPE}, and
 * {@link GSSConstants#REJECT_LIMITED_PROXY GSSConstants.REJECT_LIMITED_PROXY}
 * context options. If the {@link GSSConstants#GSS_MODE GSSConstants.GSS_MODE}
 * option is set to {@link GSIConstants#MODE_SSL GSIConstants.MODE_SSL}
 * the context establishment process will be compatible with regular SSL
 * (no credential delegation support). If the option is set to
 * {@link GSIConstants#MODE_GSI GSIConstants.GSS_MODE_GSI}
 * credential delegation during context establishment process will performed.
 * The delegation type to be performed can be set using the
 * {@link GSSConstants#DELEGATION_TYPE GSSConstants.DELEGATION_TYPE}
 * context option. If the {@link GSSConstants#REJECT_LIMITED_PROXY
 * GSSConstants.REJECT_LIMITED_PROXY} option is enabled,
 * a peer presenting limited proxy credential will be automatically
 * rejected and the context establishment process will be aborted.
 *
 * @return a byte[] containing the token to be sent to the peer.
 *         null indicates that no token is generated (needs more data).
 */
public byte[] initSecContext(byte[] inBuff, int off, int len) throws GSSException {
    logger.debug("enter initSecContext");

    if (!this.conn) {
        this.role = INITIATE;

        logger.debug("enter initializing in initSecContext");

        if (this.anonymity || this.ctxCred.getName().isAnonymous()) {
            this.anonymity = true;
        } else {
            this.anonymity = false;

            setCredential();

            if (this.ctxCred.getUsage() != GSSCredential.INITIATE_ONLY
                    && this.ctxCred.getUsage() != GSSCredential.INITIATE_AND_ACCEPT) {
                throw new GlobusGSSException(GSSException.DEFECTIVE_CREDENTIAL, GlobusGSSException.UNKNOWN,
                        "badCredUsage");
            }
        }

        if (getCredDelegState()) {
            if (this.gssMode == GSIConstants.MODE_SSL) {
                throw new GlobusGSSException(GSSException.FAILURE, GlobusGSSException.BAD_ARGUMENT,
                        "initCtx00");
            }
            if (this.anonymity) {
                throw new GlobusGSSException(GSSException.FAILURE, GlobusGSSException.BAD_ARGUMENT,
                        "initCtx01");
            }
        }

        try {
            init(this.role);
        } catch (SSLException e) {
            throw new GlobusGSSException(GSSException.FAILURE, e);
        }

        this.conn = true;
        logger.debug("done initializing in initSecContext");
    }

    // Unless explicitly disabled, check if delegation is
    // requested and expected target is null
    logger.debug("Require authz with delegation: " + this.requireAuthzWithDelegation);
    if (!Boolean.FALSE.equals(this.requireAuthzWithDelegation)) {

        if (this.expectedTargetName == null && getCredDelegState()) {
            throw new GlobusGSSException(GSSException.FAILURE, GlobusGSSException.BAD_ARGUMENT, "initCtx02");
        }
    }

    /*DEL
            this.out.reset();
            this.in.putToken(inBuff, off, len);
    */

    this.outByteBuff.clear();
    ByteBuffer inByteBuff;
    if (savedInBytes != null) {
        if (len > 0) {
            byte[] allInBytes = new byte[savedInBytes.length + len];
            logger.debug("ALLOCATED for allInBytes " + savedInBytes.length + " + " + len + " bytes\n");
            System.arraycopy(savedInBytes, 0, allInBytes, 0, savedInBytes.length);
            System.arraycopy(inBuff, off, allInBytes, savedInBytes.length, len);
            inByteBuff = ByteBuffer.wrap(allInBytes, 0, allInBytes.length);
        } else {
            inByteBuff = ByteBuffer.wrap(savedInBytes, 0, savedInBytes.length);
        }
        savedInBytes = null;
    } else {
        inByteBuff = ByteBuffer.wrap(inBuff, off, len);
    }

    switch (state) {

    case HANDSHAKE:
        try {

            logger.debug("STATUS BEFORE: " + this.sslEngine.getHandshakeStatus().toString());
            SSLEngineResult.HandshakeStatus handshake_status = sslEngine.getHandshakeStatus();

            if (handshake_status == SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING) {
                // return null;
                throw new Exception("GSSAPI in HANDSHAKE state but " + "SSLEngine in NOT_HANDSHAKING state!");
            } else {
                outByteBuff = this.sslProcessHandshake(inByteBuff, outByteBuff);
            }

            logger.debug("STATUS AFTER: " + this.sslEngine.getHandshakeStatus().toString());

            outByteBuff.flip();
            /*DEL
                            this.conn.getHandshake().processHandshake();
                            if (this.conn.getHandshake().finishedP()) {
            */
            if (this.sslEngine.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING) {
                // the wrap/unwrap above has resulted in handshaking
                // being complete on our end.
                logger.debug("initSecContext handshake finished");
                handshakeFinished();

                /*DEL
                                    Vector chain = this.conn.getCertificateChain();
                                    X509Cert crt = (X509Cert)chain.elementAt(chain.size()-1);
                                    setGoodUntil(crt.getValidityNotAfter());
                */
                Certificate[] chain = this.sslEngine.getSession().getPeerCertificates();
                if (!(chain instanceof X509Certificate[])) {
                    throw new Exception("Certificate chain not of type X509Certificate");
                }

                for (X509Certificate cert : (X509Certificate[]) chain) {
                    setGoodUntil(cert.getNotAfter());
                }

                // acceptor - peer

                /*DEL
                                    String identity = verifyChain(chain);
                */
                // chain verification would have already been done by
                // JSSE

                String identity = BouncyCastleUtil.getIdentity(
                        bcConvert(BouncyCastleUtil.getIdentityCertificate((X509Certificate[]) chain)));
                this.targetName = new GlobusGSSName(CertificateUtil.toGlobusID(identity, false));

                this.peerLimited = Boolean.valueOf(ProxyCertificateUtil
                        .isLimitedProxy(BouncyCastleUtil.getCertificateType((X509Certificate) chain[0])));

                logger.debug("Peer Identity is: " + identity + " Target name is: " + this.targetName
                        + " Limited Proxy: " + this.peerLimited.toString());

                // initiator
                if (this.anonymity) {
                    this.sourceName = new GlobusGSSName();
                } else {
                    for (X509Certificate cert : this.ctxCred.getCertificateChain()) {
                        setGoodUntil(cert.getNotAfter());
                    }
                    this.sourceName = this.ctxCred.getName();
                }

                // mutual authentication test
                if (this.expectedTargetName != null && !this.expectedTargetName.equals(this.targetName)) {
                    throw new GlobusGSSException(GSSException.UNAUTHORIZED, GlobusGSSException.BAD_NAME,
                            "authFailed00", new Object[] { this.expectedTargetName, this.targetName });
                }

                if (this.gssMode == GSIConstants.MODE_GSI) {
                    this.state = CLIENT_START_DEL;
                    // if there is data to return then
                    // break. otherwise we fall through!!!
                    if (this.outByteBuff.remaining() > 0) {
                        break;
                    }
                } else {
                    setDone();
                    break;
                }

            } else {
                break;
            }
        } catch (IOException e) {
            throw new GlobusGSSException(GSSException.FAILURE, e);
        } catch (Exception e) {
            throw new GlobusGSSException(GSSException.FAILURE, e);
        }

    case CLIENT_START_DEL:

        logger.debug("CLIENT_START_DEL");
        // sanity check - might be invalid state
        if (this.state != CLIENT_START_DEL || this.outByteBuff.remaining() > 0) {
            throw new GSSException(GSSException.FAILURE);
        }
        if (inByteBuff.hasRemaining()) {
            throw new GlobusGSSException(GSSException.FAILURE,
                    new Exception(
                            "Not all data processed; Original: " + len + " Remaining: " + inByteBuff.remaining()
                                    + " Handshaking status: " + sslEngine.getHandshakeStatus()));
        }
        this.outByteBuff.clear();

        try {
            String deleg;

            if (getCredDelegState()) {
                deleg = Character.toString(GSIConstants.DELEGATION_CHAR);
                this.state = CLIENT_END_DEL;
            } else {
                deleg = Character.toString('0');
                setDone();
            }

            byte[] a = deleg.getBytes("US-ASCII");
            inByteBuff = ByteBuffer.wrap(a, 0, a.length);
            outByteBuff = sslDataWrap(inByteBuff, outByteBuff);
            outByteBuff.flip();

        } catch (Exception e) {
            throw new GlobusGSSException(GSSException.FAILURE, e);
        }

        break;

    case CLIENT_END_DEL:

        logger.debug("CLIENT_END_DEL");
        if (!inByteBuff.hasRemaining()) {
            throw new GSSException(GSSException.DEFECTIVE_TOKEN);
        }

        ByteArrayInputStream byteArrayInputStream = null;
        try {
            /*DEL
                            if (this.in.available() <= 0) {
            return null;
                            }
            */
            outByteBuff = sslDataUnwrap(inByteBuff, outByteBuff);
            outByteBuff.flip();
            if (!outByteBuff.hasRemaining())
                break;

            byte[] certReq = new byte[outByteBuff.remaining()];
            outByteBuff.get(certReq, 0, certReq.length);

            X509Certificate[] chain = this.ctxCred.getCertificateChain();

            byteArrayInputStream = new ByteArrayInputStream(certReq);
            X509Certificate cert = this.certFactory.createCertificate(byteArrayInputStream, chain[0],
                    this.ctxCred.getPrivateKey(), -1,
                    /*DEL
                                                       getDelegationType(chain[0]));
                    */
                    BouncyCastleCertProcessingFactory.decideProxyType(chain[0], this.delegationType));

            byte[] enc = cert.getEncoded();
            /*DEL
                            this.conn.getOutStream().write(enc, 0, enc.length);
            */
            inByteBuff = ByteBuffer.wrap(enc, 0, enc.length);
            outByteBuff.clear();
            outByteBuff = sslDataWrap(inByteBuff, outByteBuff);
            outByteBuff.flip();

            setDone();
        } catch (GeneralSecurityException e) {
            throw new GlobusGSSException(GSSException.FAILURE, e);
        } catch (IOException e) {
            throw new GlobusGSSException(GSSException.FAILURE, e);
        } finally {
            if (byteArrayInputStream != null) {
                try {
                    byteArrayInputStream.close();
                } catch (Exception e) {
                    logger.warn("Unable to close stream.");
                }
            }
        }

        break;

    default:
        throw new GSSException(GSSException.FAILURE);
    }

    if (inByteBuff.hasRemaining()) {
        // Likely BUFFER_UNDERFLOW; save the
        // inByteBuff bytes here like in the unwrap() case
        logger.debug("Not all data processed; Original: " + len + " Remaining: " + inByteBuff.remaining()
                + " Handshaking status: " + sslEngine.getHandshakeStatus());
        logger.debug("SAVING unprocessed " + inByteBuff.remaining() + "BYTES\n");
        savedInBytes = new byte[inByteBuff.remaining()];
        inByteBuff.get(savedInBytes, 0, savedInBytes.length);
    }

    logger.debug("exit initSecContext");
    //XXX: Why is here a check for CLIENT_START_DEL?
    // if (this.outByteBuff.hasRemaining() || this.state == CLIENT_START_DEL) {
    if (this.outByteBuff.hasRemaining()) {
        // TODO can we avoid this copy if the ByteBuffer is array based
        // and we return that array, each time allocating a new array
        // for outByteBuff?
        byte[] out = new byte[this.outByteBuff.remaining()];
        this.outByteBuff.get(out, 0, out.length);
        return out;
    } else
        return null;
}

From source file:com.screenslicer.common.HtmlCoder.java

public static String encode(String string) {
    try {/*from ww  w.  ja v  a2s . c om*/
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < string.length();) {
            int codePoint = string.codePointAt(i);
            String symbol = codePointToSymbol(codePoint);
            char[] chars = symbol.toCharArray();
            if (chars.length == 1 && CharUtils.isAscii(chars[0])) {
                builder.append(StringEscapeUtils.escapeHtml4(Character.toString(chars[0])));
            } else {
                builder.append(symbol);
            }
            i += chars.length;
        }
        return builder.toString();
    } catch (Throwable t) {
        Log.exception(t);
        return string;
    }
}

From source file:edu.emory.cci.aiw.i2b2etl.ksb.I2b2KnowledgeSourceBackend.java

public String getReligionPropertyValueSetDelimiter() {
    return Character.toString(religionPropertyValueSetDelimiter);
}

From source file:com.yek.keyboard.keyboards.views.AnyKeyboardViewBase.java

@CallSuper
protected void onBufferDraw(Canvas canvas, final Paint paint) {
    if (mKeyboardChanged) {
        invalidateAllKeys();/* www  .  j a va 2 s .c  o m*/
        mKeyboardChanged = false;
    }

    canvas.getClipBounds(mDirtyRect);

    if (mKeyboard == null)
        return;

    final boolean drawKeyboardNameText = (mKeyboardNameTextSize > 1f)
            && AnyApplication.getConfig().getShowKeyboardNameText();

    final boolean drawHintText = (mHintTextSize > 1) && AnyApplication.getConfig().getShowHintTextOnKeys();

    final boolean useCustomKeyTextColor = false;
    // TODO: final boolean useCustomKeyTextColor =
    // AnyApplication.getConfig().getUseCustomTextColorOnKeys();
    final ColorStateList keyTextColor = useCustomKeyTextColor
            ? new ColorStateList(new int[][] { { 0 } }, new int[] { 0xFF6666FF })
            : mKeyTextColor;

    final boolean useCustomHintColor = drawHintText && false;
    // TODO: final boolean useCustomHintColor = drawHintText &&
    final ColorStateList hintColor = useCustomHintColor
            ? new ColorStateList(new int[][] { { 0 } }, new int[] { 0xFFFF6666 })
            : mHintTextColor;

    // allow preferences to override theme settings for hint text position
    final boolean useCustomHintAlign = drawHintText && AnyApplication.getConfig().getUseCustomHintAlign();
    final int hintAlign = useCustomHintAlign ? AnyApplication.getConfig().getCustomHintAlign()
            : mHintLabelAlign;
    final int hintVAlign = useCustomHintAlign ? AnyApplication.getConfig().getCustomHintVAlign()
            : mHintLabelVAlign;

    final Drawable keyBackground = mKeyBackground;
    final Rect clipRegion = mClipRegion;
    final int kbdPaddingLeft = getPaddingLeft();
    final int kbdPaddingTop = getPaddingTop();
    final Keyboard.Key[] keys = mKeys;
    final Keyboard.Key invalidKey = mInvalidatedKey;

    boolean drawSingleKey = false;
    if (invalidKey != null && canvas.getClipBounds(clipRegion)) {
        // TODO we should use Rect.inset and Rect.contains here.
        // Is clipRegion completely contained within the invalidated key?
        if (invalidKey.x + kbdPaddingLeft - 1 <= clipRegion.left
                && invalidKey.y + kbdPaddingTop - 1 <= clipRegion.top
                && invalidKey.x + invalidKey.width + kbdPaddingLeft + 1 >= clipRegion.right
                && invalidKey.y + invalidKey.height + kbdPaddingTop + 1 >= clipRegion.bottom) {
            drawSingleKey = true;
        }
    }

    for (Keyboard.Key keyBase : keys) {
        final AnyKeyboard.AnyKey key = (AnyKeyboard.AnyKey) keyBase;
        final boolean keyIsSpace = isSpaceKey(key);

        if (drawSingleKey && (invalidKey != key)) {
            continue;
        }
        if (!mDirtyRect.intersects(key.x + kbdPaddingLeft, key.y + kbdPaddingTop,
                key.x + key.width + kbdPaddingLeft, key.y + key.height + kbdPaddingTop)) {
            continue;
        }
        int[] drawableState = key.getCurrentDrawableState(mDrawableStatesProvider);

        if (keyIsSpace)
            paint.setColor(mKeyboardNameTextColor);
        else
            paint.setColor(keyTextColor.getColorForState(drawableState, 0xFF000000));
        keyBackground.setState(drawableState);

        // Switch the character to uppercase if shift is pressed
        CharSequence label = key.label == null ? null : adjustLabelToShiftState(key);

        final Rect bounds = keyBackground.getBounds();
        if ((key.width != bounds.right) || (key.height != bounds.bottom)) {
            keyBackground.setBounds(0, 0, key.width, key.height);
        }
        canvas.translate(key.x + kbdPaddingLeft, key.y + kbdPaddingTop);
        keyBackground.draw(canvas);

        if (TextUtils.isEmpty(label)) {
            Drawable iconToDraw = getIconToDrawForKey(key, false);
            if (iconToDraw != null/* && shouldDrawIcon */) {
                //http://developer.android.com/reference/android/graphics/drawable/Drawable.html#getCurrent()
                //http://stackoverflow.com/a/103600/1324235
                final boolean is9Patch = iconToDraw.getCurrent() instanceof NinePatchDrawable;

                // Special handing for the upper-right number hint icons
                final int drawableWidth;
                final int drawableHeight;
                final int drawableX;
                final int drawableY;

                drawableWidth = is9Patch ? key.width : iconToDraw.getIntrinsicWidth();
                drawableHeight = is9Patch ? key.height : iconToDraw.getIntrinsicHeight();
                drawableX = (key.width + mKeyBackgroundPadding.left - mKeyBackgroundPadding.right
                        - drawableWidth) / 2;
                drawableY = (key.height + mKeyBackgroundPadding.top - mKeyBackgroundPadding.bottom
                        - drawableHeight) / 2;

                canvas.translate(drawableX, drawableY);
                iconToDraw.setBounds(0, 0, drawableWidth, drawableHeight);
                iconToDraw.draw(canvas);
                canvas.translate(-drawableX, -drawableY);
                if (keyIsSpace && drawKeyboardNameText) {
                    // now a little hack, I'll set the label now, so it get
                    // drawn.
                    label = mKeyboardName;
                }
            } else {
                // ho... no icon.
                // I'll try to guess the text
                label = guessLabelForKey(key.getPrimaryCode());
            }
        }

        if (label != null) {
            // For characters, use large font. For labels like "Done", use
            // small font.
            final FontMetrics fm;
            if (keyIsSpace) {
                paint.setTextSize(mKeyboardNameTextSize);
                paint.setTypeface(Typeface.DEFAULT_BOLD);
                if (mKeyboardNameFM == null)
                    mKeyboardNameFM = paint.getFontMetrics();
                fm = mKeyboardNameFM;
            } else if (label.length() > 1 && key.getCodesCount() < 2) {
                setPaintForLabelText(paint);
                if (mLabelFM == null)
                    mLabelFM = paint.getFontMetrics();
                fm = mLabelFM;
            } else {
                setPaintToKeyText(paint);
                if (mTextFM == null)
                    mTextFM = paint.getFontMetrics();
                fm = mTextFM;
            }

            if (isLabelOfPictographic(label)) {
                paint.setTextSize(2f * paint.getTextSize());
            }

            final float labelHeight = -fm.top;
            // Draw a drop shadow for the text
            paint.setShadowLayer(mShadowRadius, mShadowOffsetX, mShadowOffsetY, mShadowColor);

            final float textWidth = adjustTextSizeForLabel(paint, label, key.width);

            // the center of the drawable space, which is value used
            // previously for vertically
            // positioning the key label
            final float centerY = mKeyBackgroundPadding.top
                    + ((key.height - mKeyBackgroundPadding.top - mKeyBackgroundPadding.bottom)
                            / (keyIsSpace ? 3 : 2));// the label on the space is a bit higher

            // the X coordinate for the center of the main label text is
            // unaffected by the hints
            final float textX = mKeyBackgroundPadding.left
                    + (key.width - mKeyBackgroundPadding.left - mKeyBackgroundPadding.right) / 2;
            final float textY;
            // Some devices (mostly pre-Honeycomb, have issues with RTL text
            // drawing.
            // Of course, there is no issue with a single character :)
            // so, we'll use the RTL secured drawing (via StaticLayout) for
            // labels.
            if (label.length() > 1 && !AnyApplication.getConfig().workaround_alwaysUseDrawText()) {
                // calculate Y coordinate of top of text based on center
                // location
                textY = centerY - ((labelHeight - paint.descent()) / 2);
                canvas.translate(textX, textY);
                // RTL fix. But it costs, let do it when in need (more than
                // 1 character)
                StaticLayout labelText = new StaticLayout(label, new TextPaint(paint), (int) textWidth,
                        Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
                labelText.draw(canvas);
            } else {
                // to get Y coordinate of baseline from center of text,
                // first add half the height (to get to
                // bottom of text), then subtract the part below the
                // baseline. Note that fm.top is negative.
                textY = centerY + ((labelHeight - paint.descent()) / 2);
                canvas.translate(textX, textY);
                canvas.drawText(label, 0, label.length(), 0, 0, paint);
            }
            canvas.translate(-textX, -textY);
            // (-)

            // Turn off drop shadow
            paint.setShadowLayer(0, 0, 0, 0);
        }

        if (drawHintText) {
            if ((key.popupCharacters != null && key.popupCharacters.length() > 0) || (key.popupResId != 0)
                    || (key.longPressCode != 0)) {
                Align oldAlign = paint.getTextAlign();

                String hintText = null;

                if (key.hintLabel != null && key.hintLabel.length() > 0) {
                    hintText = key.hintLabel.toString();
                    // it is the responsibility of the keyboard layout
                    // designer to ensure that they do
                    // not put too many characters in the hint label...
                } else if (key.longPressCode != 0) {
                    if (Character.isLetterOrDigit(key.longPressCode))
                        hintText = Character.toString((char) key.longPressCode);
                } else if (key.popupCharacters != null) {
                    final String hintString = key.popupCharacters.toString();
                    final int hintLength = hintString.length();
                    if (hintLength <= 3)
                        hintText = hintString;
                }

                // if hintText is still null, it means it didn't fit one of
                // the above
                // cases, so we should provide the hint using the default
                if (hintText == null) {
                    if (mHintOverflowLabel != null)
                        hintText = mHintOverflowLabel;
                    else {
                        // theme does not provide a defaultHintLabel
                        // use  if hints are above, ... if hints are
                        // below
                        // (to avoid being too close to main label/icon)
                        if (hintVAlign == Gravity.TOP)
                            hintText = "";
                        else
                            hintText = "...";
                    }
                }

                if (mKeyboard.isShifted())
                    hintText = hintText.toUpperCase(getKeyboard().getLocale());

                // now draw hint
                paint.setTypeface(Typeface.DEFAULT);
                paint.setColor(hintColor.getColorForState(drawableState, 0xFF000000));
                paint.setTextSize(mHintTextSize);
                // get the hint text font metrics so that we know the size
                // of the hint when
                // we try to position the main label (to try to make sure
                // they don't overlap)
                if (mHintTextFM == null) {
                    mHintTextFM = paint.getFontMetrics();
                }

                final float hintX;
                final float hintY;

                // the (float) 0.5 value is added or subtracted to just give
                // a little more room
                // in case the theme designer didn't account for the hint
                // label location
                if (hintAlign == Gravity.START) {
                    // left
                    paint.setTextAlign(Align.LEFT);
                    hintX = mKeyBackgroundPadding.left + 0.5f;
                } else if (hintAlign == Gravity.CENTER) {
                    // center
                    paint.setTextAlign(Align.CENTER);
                    hintX = mKeyBackgroundPadding.left
                            + (key.width - mKeyBackgroundPadding.left - mKeyBackgroundPadding.right) / 2;
                } else {
                    // right
                    paint.setTextAlign(Align.RIGHT);
                    hintX = key.width - mKeyBackgroundPadding.right - 0.5f;
                }

                if (hintVAlign == Gravity.TOP) {
                    // above
                    hintY = mKeyBackgroundPadding.top - mHintTextFM.top + 0.5f;
                } else {
                    // below
                    hintY = key.height - mKeyBackgroundPadding.bottom - mHintTextFM.bottom - 0.5f;
                }

                canvas.drawText(hintText, hintX, hintY, paint);
                paint.setTextAlign(oldAlign);
            }
        }

        canvas.translate(-key.x - kbdPaddingLeft, -key.y - kbdPaddingTop);
    }
    mInvalidatedKey = null;

    mDirtyRect.setEmpty();
}

From source file:com.anysoftkeyboard.keyboards.views.AnyKeyboardViewBase.java

@CallSuper
protected void onBufferDraw(Canvas canvas, final Paint paint) {
    if (mKeyboardChanged) {
        invalidateAllKeys();//from  www  . j  ava  2  s .c o m
        mKeyboardChanged = false;
    }

    canvas.getClipBounds(mDirtyRect);

    if (mKeyboard == null)
        return;

    final boolean drawKeyboardNameText = (mKeyboardNameTextSize > 1f)
            && AnyApplication.getConfig().getShowKeyboardNameText();

    final boolean drawHintText = (mHintTextSize > 1) && AnyApplication.getConfig().getShowHintTextOnKeys();

    final boolean useCustomKeyTextColor = false;
    // TODO: final boolean useCustomKeyTextColor =
    // AnyApplication.getConfig().getUseCustomTextColorOnKeys();
    final ColorStateList keyTextColor = useCustomKeyTextColor
            ? new ColorStateList(new int[][] { { 0 } }, new int[] { 0xFF6666FF })
            : mKeyTextColor;

    final boolean useCustomHintColor = drawHintText && false;
    // TODO: final boolean useCustomHintColor = drawHintText &&
    final ColorStateList hintColor = useCustomHintColor
            ? new ColorStateList(new int[][] { { 0 } }, new int[] { 0xFFFF6666 })
            : mHintTextColor;

    // allow preferences to override theme settings for hint text position
    final boolean useCustomHintAlign = drawHintText && AnyApplication.getConfig().getUseCustomHintAlign();
    final int hintAlign = useCustomHintAlign ? AnyApplication.getConfig().getCustomHintAlign()
            : mHintLabelAlign;
    final int hintVAlign = useCustomHintAlign ? AnyApplication.getConfig().getCustomHintVAlign()
            : mHintLabelVAlign;

    final Drawable keyBackground = mKeyBackground;
    final Rect clipRegion = mClipRegion;
    final int kbdPaddingLeft = getPaddingLeft();
    final int kbdPaddingTop = getPaddingTop();
    final Key[] keys = mKeys;
    final Key invalidKey = mInvalidatedKey;

    boolean drawSingleKey = false;
    if (invalidKey != null && canvas.getClipBounds(clipRegion)) {
        // TODO we should use Rect.inset and Rect.contains here.
        // Is clipRegion completely contained within the invalidated key?
        if (invalidKey.x + kbdPaddingLeft - 1 <= clipRegion.left
                && invalidKey.y + kbdPaddingTop - 1 <= clipRegion.top
                && invalidKey.x + invalidKey.width + kbdPaddingLeft + 1 >= clipRegion.right
                && invalidKey.y + invalidKey.height + kbdPaddingTop + 1 >= clipRegion.bottom) {
            drawSingleKey = true;
        }
    }

    for (Key keyBase : keys) {
        final AnyKey key = (AnyKey) keyBase;
        final boolean keyIsSpace = isSpaceKey(key);

        if (drawSingleKey && (invalidKey != key)) {
            continue;
        }
        if (!mDirtyRect.intersects(key.x + kbdPaddingLeft, key.y + kbdPaddingTop,
                key.x + key.width + kbdPaddingLeft, key.y + key.height + kbdPaddingTop)) {
            continue;
        }
        int[] drawableState = key.getCurrentDrawableState(mDrawableStatesProvider);

        if (keyIsSpace)
            paint.setColor(mKeyboardNameTextColor);
        else
            paint.setColor(keyTextColor.getColorForState(drawableState, 0xFF000000));
        keyBackground.setState(drawableState);

        // Switch the character to uppercase if shift is pressed
        CharSequence label = key.label == null ? null : adjustLabelToShiftState(key);

        final Rect bounds = keyBackground.getBounds();
        if ((key.width != bounds.right) || (key.height != bounds.bottom)) {
            keyBackground.setBounds(0, 0, key.width, key.height);
        }
        canvas.translate(key.x + kbdPaddingLeft, key.y + kbdPaddingTop);
        keyBackground.draw(canvas);

        if (TextUtils.isEmpty(label)) {
            Drawable iconToDraw = getIconToDrawForKey(key, false);
            if (iconToDraw != null/* && shouldDrawIcon */) {
                //http://developer.android.com/reference/android/graphics/drawable/Drawable.html#getCurrent()
                //http://stackoverflow.com/a/103600/1324235
                final boolean is9Patch = iconToDraw.getCurrent() instanceof NinePatchDrawable;

                // Special handing for the upper-right number hint icons
                final int drawableWidth;
                final int drawableHeight;
                final int drawableX;
                final int drawableY;

                drawableWidth = is9Patch ? key.width : iconToDraw.getIntrinsicWidth();
                drawableHeight = is9Patch ? key.height : iconToDraw.getIntrinsicHeight();
                drawableX = (key.width + mKeyBackgroundPadding.left - mKeyBackgroundPadding.right
                        - drawableWidth) / 2;
                drawableY = (key.height + mKeyBackgroundPadding.top - mKeyBackgroundPadding.bottom
                        - drawableHeight) / 2;

                canvas.translate(drawableX, drawableY);
                iconToDraw.setBounds(0, 0, drawableWidth, drawableHeight);
                iconToDraw.draw(canvas);
                canvas.translate(-drawableX, -drawableY);
                if (keyIsSpace && drawKeyboardNameText) {
                    // now a little hack, I'll set the label now, so it get
                    // drawn.
                    label = mKeyboardName;
                }
            } else {
                // ho... no icon.
                // I'll try to guess the text
                label = guessLabelForKey(key.getPrimaryCode());
            }
        }

        if (label != null) {
            // For characters, use large font. For labels like "Done", use
            // small font.
            final FontMetrics fm;
            if (keyIsSpace) {
                paint.setTextSize(mKeyboardNameTextSize);
                paint.setTypeface(Typeface.DEFAULT_BOLD);
                if (mKeyboardNameFontMetrics == null)
                    mKeyboardNameFontMetrics = paint.getFontMetrics();
                fm = mKeyboardNameFontMetrics;
            } else if (label.length() > 1 && key.getCodesCount() < 2) {
                setPaintForLabelText(paint);
                if (mLabelFontMetrics == null)
                    mLabelFontMetrics = paint.getFontMetrics();
                fm = mLabelFontMetrics;
            } else {
                setPaintToKeyText(paint);
                if (mTextFontMetrics == null)
                    mTextFontMetrics = paint.getFontMetrics();
                fm = mTextFontMetrics;
            }

            if (isLabelOfPictographic(label)) {
                paint.setTextSize(2f * paint.getTextSize());
            }

            final float labelHeight = -fm.top;
            // Draw a drop shadow for the text
            paint.setShadowLayer(mShadowRadius, mShadowOffsetX, mShadowOffsetY, mShadowColor);

            final float textWidth = adjustTextSizeForLabel(paint, label, key.width);

            // the center of the drawable space, which is value used
            // previously for vertically
            // positioning the key label
            final float centerY = mKeyBackgroundPadding.top
                    + ((key.height - mKeyBackgroundPadding.top - mKeyBackgroundPadding.bottom)
                            / (keyIsSpace ? 3 : 2));// the label on the space is a bit higher

            // the X coordinate for the center of the main label text is
            // unaffected by the hints
            final float textX = mKeyBackgroundPadding.left
                    + (key.width - mKeyBackgroundPadding.left - mKeyBackgroundPadding.right) / 2;
            final float textY;
            // Some devices (mostly pre-Honeycomb, have issues with RTL text
            // drawing.
            // Of course, there is no issue with a single character :)
            // so, we'll use the RTL secured drawing (via StaticLayout) for
            // labels.
            if (label.length() > 1 && !AnyApplication.getConfig().workaround_alwaysUseDrawText()) {
                // calculate Y coordinate of top of text based on center
                // location
                textY = centerY - ((labelHeight - paint.descent()) / 2);
                canvas.translate(textX, textY);
                // RTL fix. But it costs, let do it when in need (more than
                // 1 character)
                StaticLayout labelText = new StaticLayout(label, new TextPaint(paint), (int) textWidth,
                        Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
                labelText.draw(canvas);
            } else {
                // to get Y coordinate of baseline from center of text,
                // first add half the height (to get to
                // bottom of text), then subtract the part below the
                // baseline. Note that fm.top is negative.
                textY = centerY + ((labelHeight - paint.descent()) / 2);
                canvas.translate(textX, textY);
                canvas.drawText(label, 0, label.length(), 0, 0, paint);
            }
            canvas.translate(-textX, -textY);
            // (-)

            // Turn off drop shadow
            paint.setShadowLayer(0, 0, 0, 0);
        }

        if (drawHintText) {
            if ((key.popupCharacters != null && key.popupCharacters.length() > 0) || (key.popupResId != 0)
                    || (key.longPressCode != 0)) {
                Align oldAlign = paint.getTextAlign();

                String hintText = null;

                if (key.hintLabel != null && key.hintLabel.length() > 0) {
                    hintText = key.hintLabel.toString();
                    // it is the responsibility of the keyboard layout
                    // designer to ensure that they do
                    // not put too many characters in the hint label...
                } else if (key.longPressCode != 0) {
                    if (Character.isLetterOrDigit(key.longPressCode))
                        hintText = Character.toString((char) key.longPressCode);
                } else if (key.popupCharacters != null) {
                    final String hintString = key.popupCharacters.toString();
                    final int hintLength = hintString.length();
                    if (hintLength <= 3)
                        hintText = hintString;
                }

                // if hintText is still null, it means it didn't fit one of
                // the above
                // cases, so we should provide the hint using the default
                if (hintText == null) {
                    if (mHintOverflowLabel != null)
                        hintText = mHintOverflowLabel;
                    else {
                        // theme does not provide a defaultHintLabel
                        // use  if hints are above, ... if hints are
                        // below
                        // (to avoid being too close to main label/icon)
                        if (hintVAlign == Gravity.TOP)
                            hintText = "";
                        else
                            hintText = "...";
                    }
                }

                if (mKeyboard.isShifted())
                    hintText = hintText.toUpperCase(getKeyboard().getLocale());

                // now draw hint
                paint.setTypeface(Typeface.DEFAULT);
                paint.setColor(hintColor.getColorForState(drawableState, 0xFF000000));
                paint.setTextSize(mHintTextSize);
                // get the hint text font metrics so that we know the size
                // of the hint when
                // we try to position the main label (to try to make sure
                // they don't overlap)
                if (mHintTextFontMetrics == null) {
                    mHintTextFontMetrics = paint.getFontMetrics();
                }

                final float hintX;
                final float hintY;

                // the (float) 0.5 value is added or subtracted to just give
                // a little more room
                // in case the theme designer didn't account for the hint
                // label location
                if (hintAlign == Gravity.START) {
                    // left
                    paint.setTextAlign(Align.LEFT);
                    hintX = mKeyBackgroundPadding.left + 0.5f;
                } else if (hintAlign == Gravity.CENTER) {
                    // center
                    paint.setTextAlign(Align.CENTER);
                    hintX = mKeyBackgroundPadding.left
                            + (key.width - mKeyBackgroundPadding.left - mKeyBackgroundPadding.right) / 2;
                } else {
                    // right
                    paint.setTextAlign(Align.RIGHT);
                    hintX = key.width - mKeyBackgroundPadding.right - 0.5f;
                }

                if (hintVAlign == Gravity.TOP) {
                    // above
                    hintY = mKeyBackgroundPadding.top - mHintTextFontMetrics.top + 0.5f;
                } else {
                    // below
                    hintY = key.height - mKeyBackgroundPadding.bottom - mHintTextFontMetrics.bottom - 0.5f;
                }

                canvas.drawText(hintText, hintX, hintY, paint);
                paint.setTextAlign(oldAlign);
            }
        }

        canvas.translate(-key.x - kbdPaddingLeft, -key.y - kbdPaddingTop);
    }
    mInvalidatedKey = null;

    mDirtyRect.setEmpty();
}

From source file:org.exoplatform.social.core.storage.impl.SpaceStorageImpl.java

private void _applyUnifiedSearchFilter(WhereExpression whereExpression, SpaceFilter spaceFilter) {

    String spaceNameSearchCondition = spaceFilter.getSpaceNameSearchCondition();
    char firstCharacterOfName = spaceFilter.getFirstCharacterOfSpaceName();

    if (spaceNameSearchCondition != null && spaceNameSearchCondition.length() != 0) {
        if (this.isValidInput(spaceNameSearchCondition)) {

            List<String> unifiedSearchConditions = this.processUnifiedSearchCondition(spaceNameSearchCondition);

            boolean first = true;
            for (String condition : unifiedSearchConditions) {
                //
                if (first == false) {
                    whereExpression.and();
                } else {
                    whereExpression.startGroup();
                    first = false;/*from  ww  w.ja  v a  2  s. c  o m*/
                }

                //
                if (condition.contains(StorageUtils.PERCENT_STR)) {
                    whereExpression.startGroup();
                    whereExpression
                            .like(whereExpression.callFunction(QueryFunction.LOWER, SpaceEntity.name),
                                    condition.toLowerCase())
                            .or()
                            .like(whereExpression.callFunction(QueryFunction.LOWER, SpaceEntity.description),
                                    StringEscapeUtils.escapeHtml(condition).toLowerCase());
                    whereExpression.endGroup();
                } else {
                    whereExpression.startGroup();
                    whereExpression
                            .contains(whereExpression.callFunction(QueryFunction.LOWER, SpaceEntity.name),
                                    condition.toLowerCase())
                            .or().contains(
                                    whereExpression.callFunction(QueryFunction.LOWER, SpaceEntity.description),
                                    StringEscapeUtils.escapeHtml(condition).toLowerCase());
                    whereExpression.endGroup();
                }
            } //end for
            whereExpression.endGroup();
        }
    } else if (!Character.isDigit(firstCharacterOfName)) {
        String firstCharacterOfNameString = Character.toString(firstCharacterOfName);
        String firstCharacterOfNameLowerCase = firstCharacterOfNameString.toLowerCase()
                + StorageUtils.PERCENT_STR;
        whereExpression.like(whereExpression.callFunction(QueryFunction.LOWER, SpaceEntity.name),
                firstCharacterOfNameLowerCase);
    }
}

From source file:edu.stanford.muse.util.Util.java

/** will parse Vila Dinar\u00E9s, Pau to map the \u00E9 to the right unicode char. Useful when parsing FAST Index */
public static String convertSlashUToUnicode(String s) {
    if (s == null)
        return s;
    if (s.indexOf("\\u") < 0)
        return s;

    List<Character> out = new ArrayList<>();
    for (int i = 0; i < s.length(); i++) {
        char ch = s.charAt(i);
        if (ch == '\\' && (i + 5 < s.length()) && s.charAt(i + 1) == 'u') {
            String seq = Character.toString(s.charAt(i + 2)) + Character.toString(s.charAt(i + 3))
                    + Character.toString(s.charAt(i + 4)) + Character.toString(s.charAt(i + 5));
            ch = (char) Integer.parseInt(seq, 16);
            i += 5;//from w w w .  j av a 2  s .c  om
        }

        out.add(ch);
    }

    StringBuilder sb = new StringBuilder();
    for (char c : out)
        sb.append(c);
    return sb.toString();
}

From source file:com.krawler.spring.exportFunctionality.exportDAOImpl.java

public void createPrinPriviewFile(HttpServletRequest request, HttpServletResponse response, JSONObject obj)
        throws ServiceException {

    try {/*  www .ja va  2  s. c  o m*/
        String headers[] = null;
        String titles[] = null;
        String xtypes[] = null;
        String[] str = null;
        StringBuilder newtitle = new StringBuilder();
        JSONArray repArr = new JSONArray();
        String searchjson = request.getParameter("searchJson");
        JSONObject json = null;
        JSONArray advSearch = null;
        String htmlCode = "";
        String advStr = "<ol>";
        //            User userid = (User) session.load(User.class, AuthHandler.getUserid(request));
        //            String  startdate = remoteapi.getUserDateFormatter1(userid, session, KWLDateFormat.DATE_PART).format(new Date());
        String startdate = formatDate(System.currentTimeMillis(), true, false);
        if (!StringUtil.isNullOrEmpty(searchjson) && !StringUtil.equal(searchjson, "undefined")) {
            json = new JSONObject(request.getParameter("searchJson"));
            advSearch = json.getJSONArray("root");
            for (int i = 0; i < advSearch.length(); i++) {
                JSONObject key = advSearch.getJSONObject(i);
                String value = "";
                String name = key.getString("columnheader");
                name = URLDecoder.decode(name);
                name.trim();
                if (name.contains("*"))
                    name = name.substring(0, name.indexOf("*") - 1);
                if (name.contains("(") && name.charAt(name.indexOf("(") + 1) == '&') {
                    htmlCode = name.substring(name.indexOf("(") + 3, name.length() - 2);
                    char temp = (char) Integer.parseInt(htmlCode, 10);
                    htmlCode = Character.toString(temp);
                    if (htmlCode.equals("$")) {
                        String currencyid = sessionHandlerImpl.getCurrencyID(request);
                        String currency = currencyRender(key.getString("combosearch"), currencyid);
                        name = name.substring(0, name.indexOf("(") - 1);
                        name = name + "(" + htmlCode + ")";
                        value = currency;
                    } else {
                        name = name.substring(0, name.indexOf("(") - 1);
                        value = name + " " + htmlCode;
                    }
                } else
                    value = key.getString("combosearch");
                advStr += "<li><font size=\"2\">" + name + " : " + value + "</font></li>";
            }
            advStr += "</ol>";
        }

        //To modify the Heading of document to be printed ..String 'newtitle' is manipulated.
        String name = request.getParameter("name");
        String heading = request.getParameter("heading");
        if (!StringUtil.isNullOrEmpty(heading)) {
            name = heading + name;
        }
        String maintitle = name;
        String title = request.getParameter("titlename");
        str = maintitle.split("(?=\\p{Upper})");
        if (!StringUtil.isNullOrEmpty(title)) {
            newtitle.append(title);
        } else {
            for (int i = 0; i < str.length; i++) {
                newtitle.append(str[i] + " ");
            }
        }
        newtitle.trimToSize();
        String ashtmlString = "<html> " + "<head>"
                + "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"/>" + "<title>"
                + request.getParameter("name") + "</title>"
                + "<style type=\"text/css\">@media print {button#print {display: none;}}</style>" + "</head>"
                + "<body style = \"font-family: Tahoma, Verdana, Arial, Helvetica, sans-sarif;\">" +

                "<center><div style='padding-bottom: 5px; padding-right: 5px;'>" + "<h3> " + newtitle + " </h3>"
                + "</div></center>";

        ashtmlString += "<div>" + "<b><font size=\"2\">Generated On : </b>" + startdate + "</font>"
                + "</div></br>";
        if (!StringUtil.isNullOrEmpty(searchjson) && !StringUtil.equal(searchjson, "undefined")) {
            ashtmlString += "<div>" + "<b><font size=\"2\">Selection Criteria : </b></font>" + advStr
                    + "</div>";
        }

        String atempstr = "<DIV style='page-break-after:always'></DIV>";

        if (request.getParameter("header") != null) {
            String head = request.getParameter("header").replace("$$", "#");
            String xtype = request.getParameter("xtype");
            String tit = request.getParameter("title");
            tit = URLDecoder.decode(tit, "utf-8");
            headers = (String[]) head.split(",");
            titles = (String[]) tit.split(",");
            xtypes = xtype.split(",");
        } else {
            headers = (String[]) obj.get("header");
            titles = (String[]) obj.get("title");
            xtypes = (String[]) obj.get("xtype");
        }
        StringBuilder reportSB = new StringBuilder();

        if (obj.isNull("coldata")) {
            if (obj.has("data"))
                repArr = obj.getJSONArray("data");
        } else {
            repArr = obj.getJSONArray("coldata");
        }

        for (int t = 0; t < repArr.length(); t++) {
            if (t != 0) {
                ashtmlString += "</br></br>";
            }
            ashtmlString += "<center>";
            ashtmlString += "<table cellspacing=0 border=1 cellpadding=2 width='100%' style='font-size:9pt'>";
            ashtmlString += "<tr>";
            for (int hCnt = -1; hCnt < titles.length; hCnt++) {
                if (hCnt == -1)
                    ashtmlString += "<th>S No.</th>";
                else
                    ashtmlString += "<th>" + titles[hCnt] + "</th>";
            }
            ashtmlString += "</tr>";
            for (int h = 0; h < 15; h++) {
                if (repArr.length() - t != 0) {
                    String recordData = "<tr><td align=\"center\">" + (t + 1) + "</td>";
                    JSONObject temp = repArr.getJSONObject(t);
                    for (int hCnt = 0; hCnt < headers.length; hCnt++) {
                        String str1 = temp.optString(headers[hCnt], "");
                        try {
                            if (xtypes.length > 0) {
                                str1 = formatValue(temp.optString(headers[hCnt], ""), xtypes[hCnt]);
                            }
                        } catch (Exception e) {

                        }
                        if (temp.has(headers[hCnt].toString()))
                            recordData += "<td>" + str1 + "&nbsp;</td>";
                        else
                            recordData += "<td>&nbsp;</td>";
                    }
                    ashtmlString += recordData + "</tr>";
                    t++;
                } else {
                    atempstr = "";
                }
            }
            ashtmlString += "</table>";
            ashtmlString += "</center>";
            if (t != repArr.length() - 1) {
                ashtmlString += atempstr;
            }
            t--;
        }
        ashtmlString += "<div style='float: left; padding-top: 3px; padding-right: 5px;'>"
                + "<button id = 'print' title='Print Invoice' onclick='window.print();' style='color: rgb(8, 55, 114);' href='#'>Print</button>"
                + "</div>";
        ashtmlString += "</body>" + "</html>";
        String fname = request.getParameter("name");
        response.getOutputStream().write(ashtmlString.getBytes());
        response.getOutputStream().flush();
    } catch (SessionExpiredException ex) {
        errorMsg = ex.getMessage();
        throw ServiceException.FAILURE("exportDAOImpl.createPrinPriviewFile : " + ex.getMessage(), ex);
    } catch (IOException ex) {
        errorMsg = ex.getMessage();
        throw ServiceException.FAILURE("exportDAOImpl.createPrinPriviewFile : " + ex.getMessage(), ex);
    } catch (JSONException ex) {
        errorMsg = ex.getMessage();
        throw ServiceException.FAILURE("exportDAOImpl.createPrinPriviewFile : " + ex.getMessage(), ex);
    } catch (Exception ex) {
        errorMsg = ex.getMessage();
        throw ServiceException.FAILURE("exportDAOImpl.createPrinPriviewFile : " + ex.getMessage(), ex);
    }
}

From source file:edu.harvard.iq.dataverse.ingest.tabulardata.impl.plugins.por.PORFileReader.java

private int parseNumericField(BufferedReader reader) throws IOException {
    String temp = null;/*from  w  w  w .j a  v a 2  s. c o m*/
    char[] tmp = new char[1];
    StringBuilder sb = new StringBuilder();
    while (reader.read(tmp) > 0) {
        temp = Character.toString(tmp[0]);//new String(tmp);
        if (temp.equals("/")) {
            break;
        } else {
            sb.append(temp);
        }
        //temp = sb.toString();//new String(tmp);
    }
    String base30numberString = sb.toString();
    dbgLog.finer("base30numberString=" + base30numberString);
    int base10equivalent = Integer.valueOf(base30numberString, 30);
    dbgLog.finer("base10equivalent=" + base10equivalent);
    return base10equivalent;
}