Example usage for java.util Locale toString

List of usage examples for java.util Locale toString

Introduction

In this page you can find the example usage for java.util Locale toString.

Prototype

@Override
public final String toString() 

Source Link

Document

Returns a string representation of this Locale object, consisting of language, country, variant, script, and extensions as below:
language + "_" + country + "_" + (variant + "_#" | "#") + script + "_" + extensions
Language is always lower case, country is always upper case, script is always title case, and extensions are always lower case.

Usage

From source file:org.eclipse.e4.tools.services.impl.ResourceBundleHelper.java

/**
 * Parses the specified contributor URI and loads the {@link ResourceBundle} for the specified {@link Locale}
 * out of an OSGi {@link Bundle}./*from www  . ja v a2 s . c o  m*/
 * <p>Following URIs are supported:
 * <ul>
 * <li>platform:/[plugin|fragment]/[Bundle-SymbolicName]<br>
 * Load the OSGi resource bundle out of the bundle/fragment named [Bundle-SymbolicName]</li>
 * <li>platform:/[plugin|fragment]/[Bundle-SymbolicName]/[Path]/[Basename]<br>
 * Load the resource bundle specified by [Path] and [Basename] out of the bundle/fragment named [Bundle-SymbolicName].</li>
 * <li>bundleclass://[plugin|fragment]/[Full-Qualified-Classname]<br>
 * Instantiate the class specified by [Full-Qualified-Classname] out of the bundle/fragment named [Bundle-SymbolicName].
 * Note that the class needs to be a subtype of {@link ResourceBundle}.</li>
 * </ul>
 * </p>
 * @param contributorURI The URI that points to a {@link ResourceBundle}
 * @param locale The {@link Locale} to use for loading the {@link ResourceBundle}
 * @param localization The service for retrieving a {@link ResourceBundle} for a given {@link Locale} out of
 *          the given {@link Bundle} which is specified by URI.
 * @return
 */
public static ResourceBundle getResourceBundleForUri(String contributorURI, Locale locale,
        BundleLocalization localization) {
    if (contributorURI == null)
        return null;

    LogService logService = ToolsServicesActivator.getDefault().getLogService();

    URI uri;
    try {
        uri = new URI(contributorURI);
    } catch (URISyntaxException e) {
        if (logService != null)
            logService.log(LogService.LOG_ERROR, "Invalid contributor URI: " + contributorURI); //$NON-NLS-1$
        return null;
    }

    String bundleName = null;
    Bundle bundle = null;
    String resourcePath = null;
    String classPath = null;

    //the uri follows the platform schema, so we search for .properties files in the bundle
    if (PLATFORM_SCHEMA.equals(uri.getScheme())) {
        bundleName = uri.getPath();
        if (bundleName.startsWith(PLUGIN_SEGMENT))
            bundleName = bundleName.substring(PLUGIN_SEGMENT.length());
        else if (bundleName.startsWith(FRAGMENT_SEGMENT))
            bundleName = bundleName.substring(FRAGMENT_SEGMENT.length());

        resourcePath = ""; //$NON-NLS-1$
        if (bundleName.contains(PATH_SEPARATOR)) {
            resourcePath = bundleName.substring(bundleName.indexOf(PATH_SEPARATOR) + 1);
            bundleName = bundleName.substring(0, bundleName.indexOf(PATH_SEPARATOR));
        }
    } else if (BUNDLECLASS_SCHEMA.equals(uri.getScheme())) {
        if (uri.getAuthority() == null) {
            if (logService != null)
                logService.log(LogService.LOG_ERROR, "Failed to get bundle for: " + contributorURI); //$NON-NLS-1$
        }
        bundleName = uri.getAuthority();
        //remove the leading /
        classPath = uri.getPath().substring(1);
    }

    ResourceBundle result = null;

    if (bundleName != null) {
        bundle = getBundleForName(bundleName);

        if (bundle != null) {
            if (resourcePath == null && classPath != null) {
                //the URI points to a class within the bundle classpath
                //therefore we are trying to instantiate the class
                try {
                    Class<?> resourceBundleClass = bundle.loadClass(classPath);
                    result = getEquinoxResourceBundle(classPath, locale, resourceBundleClass.getClassLoader());
                } catch (Exception e) {
                    if (logService != null)
                        logService.log(LogService.LOG_ERROR,
                                "Failed to load specified ResourceBundle: " + contributorURI, e); //$NON-NLS-1$
                }
            } else if (resourcePath.length() > 0) {
                //the specified URI points to a resource 
                //therefore we try to load the .properties files into a ResourceBundle
                result = getEquinoxResourceBundle(resourcePath.replace('.', '/'), locale, bundle);
            } else {
                //there is no class and no special resource specified within the URI 
                //therefore we load the OSGi resource bundle out of the specified Bundle
                //for the current Locale
                result = localization.getLocalization(bundle, locale.toString());
            }
        }
    }

    return result;
}

From source file:org.mifosplatform.infrastructure.core.serialization.JsonParserHelper.java

public BigDecimal convertFrom(final String numericalValueFormatted, final String parameterName,
        final Locale clientApplicationLocale) {

    if (clientApplicationLocale == null) {

        final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
        final String defaultMessage = new StringBuilder(
                "The parameter '" + parameterName + "' requires a 'locale' parameter to be passed with it.")
                        .toString();//from   w ww .j  ava 2s  .  c o  m
        final ApiParameterError error = ApiParameterError
                .parameterError("validation.msg.missing.locale.parameter", defaultMessage, parameterName);
        dataValidationErrors.add(error);

        throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist",
                "Validation errors exist.", dataValidationErrors);
    }

    try {
        BigDecimal number = null;

        if (StringUtils.isNotBlank(numericalValueFormatted)) {

            String source = numericalValueFormatted.trim();

            final NumberFormat format = NumberFormat.getNumberInstance(clientApplicationLocale);
            final DecimalFormat df = (DecimalFormat) format;
            final DecimalFormatSymbols symbols = df.getDecimalFormatSymbols();
            // http://bugs.sun.com/view_bug.do?bug_id=4510618
            final char groupingSeparator = symbols.getGroupingSeparator();
            if (groupingSeparator == '\u00a0') {
                source = source.replaceAll(" ", Character.toString('\u00a0'));
            }

            final NumberFormatter numberFormatter = new NumberFormatter();
            final Number parsedNumber = numberFormatter.parse(source, clientApplicationLocale);
            number = BigDecimal.valueOf(Double.valueOf(parsedNumber.doubleValue()));
        }

        return number;
    } catch (final ParseException e) {

        final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
        final ApiParameterError error = ApiParameterError.parameterError(
                "validation.msg.invalid.decimal.format",
                "The parameter " + parameterName + " has value: " + numericalValueFormatted
                        + " which is invalid decimal value for provided locale of ["
                        + clientApplicationLocale.toString() + "].",
                parameterName, numericalValueFormatted, clientApplicationLocale);
        error.setValue(numericalValueFormatted);
        dataValidationErrors.add(error);

        throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist",
                "Validation errors exist.", dataValidationErrors);
    }
}

From source file:org.alfresco.repo.search.impl.lucene.ADMLuceneIndexerImpl.java

/**
 * @param indexAtomicPropertiesOnly/* w w  w. ja  v  a2  s . c  o  m*/
 *            true to ignore all properties that must be indexed non-atomically
 * @return Returns true if the property was indexed atomically, or false if it should be done asynchronously
 */
protected boolean indexProperty(NodeRef nodeRef, QName propertyName, Serializable value, Document doc,
        boolean indexAtomicPropertiesOnly, boolean isContentIndexedForNode) {
    String attributeName = "@"
            + QName.createQName(propertyName.getNamespaceURI(), ISO9075.encode(propertyName.getLocalName()));

    boolean store = true;
    boolean index = true;
    IndexTokenisationMode tokenise = IndexTokenisationMode.TRUE;
    boolean atomic = true;
    boolean isContent = false;
    boolean isMultiLingual = false;
    boolean isText = false;
    boolean isDateTime = false;

    PropertyDefinition propertyDef = getDictionaryService().getProperty(propertyName);
    if (propertyDef != null) {
        index = propertyDef.isIndexed();
        store = propertyDef.isStoredInIndex();
        tokenise = propertyDef.getIndexTokenisationMode();
        atomic = propertyDef.isIndexedAtomically();
        isContent = propertyDef.getDataType().getName().equals(DataTypeDefinition.CONTENT);
        isMultiLingual = propertyDef.getDataType().getName().equals(DataTypeDefinition.MLTEXT);
        isText = propertyDef.getDataType().getName().equals(DataTypeDefinition.TEXT);
        if (propertyDef.getDataType().getName().equals(DataTypeDefinition.DATETIME)) {
            DataTypeDefinition dataType = propertyDef.getDataType();
            String analyserClassName = propertyDef.resolveAnalyserClassName();
            isDateTime = analyserClassName.equals(DateTimeAnalyser.class.getCanonicalName());
        }
    }
    if (value == null) {
        // the value is null
        return true;
    } else if (indexAtomicPropertiesOnly && !atomic) {
        // we are only doing atomic properties and the property is definitely non-atomic
        return false;
    }

    if (!indexAtomicPropertiesOnly) {
        doc.removeFields(propertyName.toString());
    }
    boolean wereAllAtomic = true;
    // convert value to String
    for (Serializable serializableValue : DefaultTypeConverter.INSTANCE.getCollection(Serializable.class,
            value)) {
        String strValue = null;
        try {
            strValue = DefaultTypeConverter.INSTANCE.convert(String.class, serializableValue);
        } catch (TypeConversionException e) {
            doc.add(new Field(attributeName, NOT_INDEXED_NO_TYPE_CONVERSION, Field.Store.NO,
                    Field.Index.UN_TOKENIZED, Field.TermVector.NO));
            continue;
        }
        if (strValue == null) {
            // nothing to index
            continue;
        }

        if (isContent) {
            // Content is always tokenised

            ContentData contentData = DefaultTypeConverter.INSTANCE.convert(ContentData.class,
                    serializableValue);
            if (!index || contentData == null || contentData.getMimetype() == null) {
                // no content, mimetype or property not indexed
                continue;
            }
            // store mimetype in index - even if content does not index it is useful
            // Added szie and locale - size needs to be tokenised correctly
            doc.add(new Field(attributeName + ".mimetype", contentData.getMimetype(), Field.Store.NO,
                    Field.Index.UN_TOKENIZED, Field.TermVector.NO));
            doc.add(new Field(attributeName + ".size", Long.toString(contentData.getSize()), Field.Store.NO,
                    Field.Index.TOKENIZED, Field.TermVector.NO));

            // TODO: Use the node locale in preferanced to the system locale
            Locale locale = contentData.getLocale();
            if (locale == null) {
                Serializable localeProperty = nodeService.getProperty(nodeRef, ContentModel.PROP_LOCALE);
                if (localeProperty != null) {
                    locale = DefaultTypeConverter.INSTANCE.convert(Locale.class, localeProperty);
                }
            }
            if (locale == null) {
                locale = I18NUtil.getLocale();
            }
            doc.add(new Field(attributeName + ".locale", locale.toString().toLowerCase(), Field.Store.NO,
                    Field.Index.UN_TOKENIZED, Field.TermVector.NO));

            if (getLuceneConfig().isContentIndexingEnabled() && isContentIndexedForNode) {
                // Avoid handling (or even getting) a reader if (maxAtomicTransformationTime <= 0)
                // ALF-5677: Extremely long launch of the Alfresco server with connector V1.2
                boolean avoidReader = maxAtomicTransformationTime <= 0 && indexAtomicPropertiesOnly;
                ContentReader reader = avoidReader ? null : contentService.getReader(nodeRef, propertyName);
                if (reader != null && reader.exists()) {
                    // We have a reader, so use it
                    boolean readerReady = true;
                    // transform if necessary (it is not a UTF-8 text document)
                    String sourceMimetype = reader.getMimetype();
                    if (!EqualsHelper.nullSafeEquals(sourceMimetype, MimetypeMap.MIMETYPE_TEXT_PLAIN)
                            || !EqualsHelper.nullSafeEquals(reader.getEncoding(), "UTF-8")) {
                        try {
                            // get the transformer
                            TransformationOptions options = new TransformationOptions();
                            options.setUse("index");
                            options.setSourceNodeRef(nodeRef);
                            transformerDebug.pushAvailable(reader.getContentUrl(), sourceMimetype,
                                    MimetypeMap.MIMETYPE_TEXT_PLAIN, options);
                            long sourceSize = reader.getSize();
                            List<ContentTransformer> transformers = contentService.getActiveTransformers(
                                    sourceMimetype, sourceSize, MimetypeMap.MIMETYPE_TEXT_PLAIN, options);
                            transformerDebug.availableTransformers(transformers, sourceSize, options,
                                    "ADMLuceneIndexer");

                            if (transformers.isEmpty()) {
                                // log it
                                if (s_logger.isInfoEnabled()) {
                                    s_logger.info("Not indexed: No transformation: \n" + "   source: " + reader
                                            + "\n" + "   target: " + MimetypeMap.MIMETYPE_TEXT_PLAIN + " at "
                                            + nodeService.getPath(nodeRef));
                                }
                                // don't index from the reader
                                readerReady = false;
                                // not indexed: no transformation
                                // doc.add(new Field("TEXT", NOT_INDEXED_NO_TRANSFORMATION, Field.Store.NO,
                                // Field.Index.TOKENIZED, Field.TermVector.NO));
                                doc.add(new Field(attributeName, NOT_INDEXED_NO_TRANSFORMATION, Field.Store.NO,
                                        Field.Index.TOKENIZED, Field.TermVector.NO));
                            }
                            // is this transformer good enough?
                            else if (indexAtomicPropertiesOnly
                                    && transformers.get(0).getTransformationTime(sourceMimetype,
                                            MimetypeMap.MIMETYPE_TEXT_PLAIN) > maxAtomicTransformationTime) {
                                // only indexing atomic properties
                                // indexing will take too long, so push it to the background
                                wereAllAtomic = false;
                                readerReady = false;

                                if (transformerDebug.isEnabled()) {
                                    transformerDebug.debug("Run later. Transformer average ("
                                            + transformers.get(0).getTransformationTime() + " ms) > "
                                            + maxAtomicTransformationTime + " ms");
                                }
                            } else {
                                // We have a transformer that is fast enough
                                ContentTransformer transformer = transformers.get(0);
                                ContentWriter writer = contentService.getTempWriter();
                                writer.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
                                // this is what the analyzers expect on the stream
                                writer.setEncoding("UTF-8");
                                try {
                                    transformer.transform(reader, writer, options);
                                    // point the reader to the new-written content
                                    reader = writer.getReader();
                                    // Check that the reader is a view onto something concrete
                                    if (!reader.exists()) {
                                        throw new ContentIOException(
                                                "The transformation did not write any content, yet: \n"
                                                        + "   transformer:     " + transformer + "\n"
                                                        + "   temp writer:     " + writer);
                                    }
                                } catch (ContentIOException | NoTransformerException
                                        | UnsupportedTransformationException e) {
                                    // log it
                                    if (s_logger.isInfoEnabled()) {
                                        s_logger.info("Not indexed: Transformation failed at "
                                                + nodeService.getPath(nodeRef), e);
                                    }
                                    // don't index from the reader
                                    readerReady = false;
                                    doc.add(new Field(attributeName, NOT_INDEXED_TRANSFORMATION_FAILED,
                                            Field.Store.NO, Field.Index.TOKENIZED, Field.TermVector.NO));
                                }
                            }
                        } finally {
                            transformerDebug.popAvailable();
                        }
                    }
                    // add the text field using the stream from the
                    // reader, but only if the reader is valid
                    if (readerReady) {
                        // ALF-15857: We want to avoid actually opening any streams until we're writing this document to the
                        // index. Then we can 'stream through'
                        final ContentReader contentReader = reader;
                        Reader lazyReader = new Reader() {
                            private Reader isr;

                            private Reader getReader() {
                                if (isr == null) {
                                    InputStream ris = contentReader.getReader().getContentInputStream();
                                    try {
                                        isr = new InputStreamReader(ris, "UTF-8");
                                    } catch (UnsupportedEncodingException e) {
                                        isr = new InputStreamReader(ris);
                                    }
                                }
                                return isr;
                            }

                            @Override
                            public int read(java.nio.CharBuffer target) throws IOException {
                                return getReader().read(target);
                            }

                            @Override
                            public int read() throws IOException {
                                return getReader().read();
                            }

                            @Override
                            public int read(char cbuf[], int off, int len) throws IOException {
                                return getReader().read(cbuf, off, len);
                            }

                            @Override
                            public long skip(long n) throws IOException {
                                return getReader().skip(n);
                            }

                            @Override
                            public void close() throws IOException {
                                if (isr != null) {
                                    getReader().close();
                                }
                            }
                        };
                        StringBuilder builder = new StringBuilder();
                        builder.append("\u0000").append(locale.toString()).append("\u0000");
                        StringReader prefix = new StringReader(builder.toString());
                        Reader multiReader = new MultiReader(prefix, lazyReader);
                        doc.add(new Field(attributeName, multiReader, Field.TermVector.NO));
                    }
                } else if (avoidReader) {
                    // Reader was deliberately not used; process in the background
                    wereAllAtomic = false;
                } else
                // URL not present (null reader) or no content at the URL (file missing)
                {
                    // log it
                    if (s_logger.isInfoEnabled()) {
                        s_logger.info("Not indexed: Content Missing \n" + "   node: " + nodeRef + " at "
                                + nodeService.getPath(nodeRef) + "\n" + "   reader: " + reader + "\n"
                                + "   content exists: "
                                + (reader == null ? " --- " : Boolean.toString(reader.exists())));
                    }
                    // not indexed: content missing
                    doc.add(new Field(attributeName, NOT_INDEXED_CONTENT_MISSING, Field.Store.NO,
                            Field.Index.TOKENIZED, Field.TermVector.NO));
                }
            } else {
                wereAllAtomic = false;
            }
        } else {
            Field.Store fieldStore = store ? Field.Store.YES : Field.Store.NO;
            Field.Index fieldIndex;

            if (index) {
                switch (tokenise) {
                case TRUE:
                case BOTH:
                default:
                    fieldIndex = Field.Index.TOKENIZED;
                    break;
                case FALSE:
                    fieldIndex = Field.Index.UN_TOKENIZED;
                    break;

                }
            } else {
                fieldIndex = Field.Index.NO;
            }

            if ((fieldIndex != Field.Index.NO) || (fieldStore != Field.Store.NO)) {
                if (isMultiLingual) {
                    MLText mlText = DefaultTypeConverter.INSTANCE.convert(MLText.class, serializableValue);
                    for (Locale locale : mlText.getLocales()) {
                        String localeString = mlText.getValue(locale);
                        if (localeString == null) {
                            // No text for that locale
                            continue;
                        }
                        StringBuilder builder;
                        MLAnalysisMode analysisMode;
                        VerbatimAnalyser vba;
                        MLTokenDuplicator duplicator;
                        Token t;
                        switch (tokenise) {
                        case TRUE:
                            builder = new StringBuilder();
                            builder.append("\u0000").append(locale.toString()).append("\u0000")
                                    .append(localeString);
                            doc.add(new Field(attributeName, builder.toString(), fieldStore, fieldIndex,
                                    Field.TermVector.NO));
                            break;
                        case FALSE:
                            // analyse ml text
                            analysisMode = getLuceneConfig().getDefaultMLIndexAnalysisMode();
                            // Do the analysis here
                            vba = new VerbatimAnalyser(false);
                            duplicator = new MLTokenDuplicator(
                                    vba.tokenStream(attributeName, new StringReader(localeString)), locale,
                                    null, analysisMode);
                            try {
                                while ((t = duplicator.next()) != null) {
                                    String localeText = "";
                                    if (t.termText().indexOf('{') == 0) {
                                        int end = t.termText().indexOf('}', 1);
                                        if (end != -1) {
                                            localeText = t.termText().substring(1, end);
                                        }
                                    }
                                    if (localeText.length() > 0) {
                                        doc.add(new Field(attributeName + "." + localeText + ".sort",
                                                t.termText(), Field.Store.NO, Field.Index.NO_NORMS,
                                                Field.TermVector.NO));
                                    }
                                    // locale free identifiers are in the default field

                                    doc.add(new Field(attributeName, t.termText(), fieldStore,
                                            Field.Index.NO_NORMS, Field.TermVector.NO));

                                }
                            } catch (IOException e) {
                                // TODO ??
                            }

                            break;
                        case BOTH:
                            builder = new StringBuilder();
                            builder.append("\u0000").append(locale.toString()).append("\u0000")
                                    .append(localeString);
                            doc.add(new Field(attributeName, builder.toString(), fieldStore, fieldIndex,
                                    Field.TermVector.NO));

                            // analyse ml text
                            analysisMode = getLuceneConfig().getDefaultMLIndexAnalysisMode();
                            // Do the analysis here
                            vba = new VerbatimAnalyser(false);
                            duplicator = new MLTokenDuplicator(
                                    vba.tokenStream(attributeName, new StringReader(localeString)), locale,
                                    null, analysisMode);
                            try {
                                while ((t = duplicator.next()) != null) {
                                    String localeText = "";
                                    if (t.termText().indexOf('{') == 0) {
                                        int end = t.termText().indexOf('}', 1);
                                        if (end != -1) {
                                            localeText = t.termText().substring(1, end);
                                        }
                                    }
                                    if (localeText.length() > 0) {
                                        doc.add(new Field(attributeName + "." + localeText + ".sort",
                                                t.termText(), Field.Store.NO, Field.Index.NO_NORMS,
                                                Field.TermVector.NO));
                                    } else {
                                        // no locale
                                        doc.add(new Field(attributeName + ".no_locale", t.termText(),
                                                Field.Store.NO, Field.Index.NO_NORMS, Field.TermVector.NO));
                                    }

                                }
                            } catch (IOException e) {
                                // TODO ??
                            }

                            break;
                        }
                    }
                } else if (isText) {
                    // Temporary special case for uids and gids
                    if (propertyName.equals(ContentModel.PROP_USER_USERNAME)
                            || propertyName.equals(ContentModel.PROP_USERNAME)
                            || propertyName.equals(ContentModel.PROP_AUTHORITY_NAME)) {
                        doc.add(new Field(attributeName, strValue, fieldStore, fieldIndex,
                                Field.TermVector.NO));
                    }

                    // TODO: Use the node locale in preferanced to the system locale
                    Locale locale = null;

                    Serializable localeProperty = nodeService.getProperty(nodeRef, ContentModel.PROP_LOCALE);
                    if (localeProperty != null) {
                        locale = DefaultTypeConverter.INSTANCE.convert(Locale.class, localeProperty);
                    }

                    if (locale == null) {
                        locale = I18NUtil.getLocale();
                    }

                    StringBuilder builder;
                    MLAnalysisMode analysisMode;
                    VerbatimAnalyser vba;
                    MLTokenDuplicator duplicator;
                    Token t;
                    switch (tokenise) {
                    default:
                    case TRUE:
                        builder = new StringBuilder();
                        builder.append("\u0000").append(locale.toString()).append("\u0000").append(strValue);
                        doc.add(new Field(attributeName, builder.toString(), fieldStore, fieldIndex,
                                Field.TermVector.NO));
                        break;
                    case FALSE:
                        analysisMode = getLuceneConfig().getDefaultMLIndexAnalysisMode();
                        // Do the analysis here
                        vba = new VerbatimAnalyser(false);
                        duplicator = new MLTokenDuplicator(
                                vba.tokenStream(attributeName, new StringReader(strValue)), locale, null,
                                analysisMode);
                        try {
                            while ((t = duplicator.next()) != null) {
                                String localeText = "";
                                if (t.termText().indexOf('{') == 0) {
                                    int end = t.termText().indexOf('}', 1);
                                    if (end != -1) {
                                        localeText = t.termText().substring(1, end);
                                    }
                                }
                                if (localeText.length() > 0) {
                                    doc.add(new Field(attributeName + "." + localeText + ".sort", t.termText(),
                                            Field.Store.NO, Field.Index.NO_NORMS, Field.TermVector.NO));
                                }
                                doc.add(new Field(attributeName, t.termText(), fieldStore, Field.Index.NO_NORMS,
                                        Field.TermVector.NO));
                            }
                        } catch (IOException e) {
                            // TODO ??
                        }

                        break;
                    case BOTH:
                        builder = new StringBuilder();
                        builder.append("\u0000").append(locale.toString()).append("\u0000").append(strValue);
                        doc.add(new Field(attributeName, builder.toString(), fieldStore, fieldIndex,
                                Field.TermVector.NO));

                        analysisMode = getLuceneConfig().getDefaultMLIndexAnalysisMode();
                        // Do the analysis here
                        vba = new VerbatimAnalyser(false);
                        duplicator = new MLTokenDuplicator(
                                vba.tokenStream(attributeName, new StringReader(strValue)), locale, null,
                                analysisMode);
                        try {
                            while ((t = duplicator.next()) != null) {
                                String localeText = "";
                                if (t.termText().indexOf('{') == 0) {
                                    int end = t.termText().indexOf('}', 1);
                                    if (end != -1) {
                                        localeText = t.termText().substring(1, end);
                                    } else {

                                    }
                                }

                                // localised sort support
                                if (localeText.length() > 0) {
                                    doc.add(new Field(attributeName + "." + localeText + ".sort", t.termText(),
                                            Field.Store.NO, Field.Index.NO_NORMS, Field.TermVector.NO));
                                } else {
                                    // All identifiers for cross language search as supported by false
                                    doc.add(new Field(attributeName + ".no_locale", t.termText(),
                                            Field.Store.NO, Field.Index.NO_NORMS, Field.TermVector.NO));
                                }
                            }
                        } catch (IOException e) {
                            // TODO ??
                        }
                        break;
                    }
                } else if (isDateTime) {
                    SimpleDateFormat df;
                    Date date;
                    switch (tokenise) {
                    default:
                    case TRUE:
                        doc.add(new Field(attributeName, strValue, fieldStore, fieldIndex,
                                Field.TermVector.NO));
                        break;
                    case FALSE:
                        df = CachingDateFormat.getDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", true);
                        try {
                            date = df.parse(strValue);
                            doc.add(new Field(attributeName, df.format(date), fieldStore, Field.Index.NO_NORMS,
                                    Field.TermVector.NO));
                        } catch (ParseException e) {
                            // ignore for ordering
                        }
                        break;
                    case BOTH:
                        doc.add(new Field(attributeName, strValue, fieldStore, fieldIndex,
                                Field.TermVector.NO));

                        df = CachingDateFormat.getDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", true);
                        try {
                            date = df.parse(strValue);
                            doc.add(new Field(attributeName + ".sort", df.format(date), Field.Store.NO,
                                    Field.Index.NO_NORMS, Field.TermVector.NO));
                        } catch (ParseException e) {
                            // ignore for ordering
                        }
                        break;
                    }
                } else {
                    doc.add(new Field(attributeName, strValue, fieldStore, fieldIndex, Field.TermVector.NO));
                }
            }
        }
    }

    return wereAllAtomic;
}

From source file:org.de.jmg.learn.SettingsActivity.java

private void initSpinners(boolean blnRestart) {
    libLearn.gStatus = "initSpinners";
    try {/*from  w w w.  j  av  a  2s.c  o m*/
        spnAbfragebereich = (Spinner) findViewById(R.id.spnAbfragebereich);
        spnASCII = (Spinner) findViewById(R.id.spnASCII);
        spnStep = (Spinner) findViewById(R.id.spnStep);
        spnDisplayDurationWord = (Spinner) findViewById(R.id.spnAnzeigedauerWord);
        spnDisplayDurationBed = (Spinner) findViewById(R.id.spnAnzeigedauerBed);
        spnPaukRepetitions = (Spinner) findViewById(R.id.spnRepetitions);
        spnProbabilityFactor = (Spinner) findViewById(R.id.spnProbabilityFactor);
        spnRestartInterval = (Spinner) findViewById(R.id.spnRestartInterval);
        spnLanguages = (Spinner) findViewById(R.id.spnLanguages);
        spnColors = (org.de.jmg.lib.NoClickSpinner) findViewById(R.id.spnColors);
        spnSounds = (org.de.jmg.lib.NoClickSpinner) findViewById(R.id.spnSounds);
        spnLangWord = (Spinner) findViewById(R.id.spnLangWord);
        spnLangMeaning = (Spinner) findViewById(R.id.spnLangMeaning);
        if (!blnRestart)
            langinitialized = 0;
        else
            langinitialized = 0;
        if (spnAbfragebereich.getAdapter() != null && spnAbfragebereich.getAdapter().getCount() > 0)
            return;
        if (Colors == null || Colors != null) {
            Colors = new ColorsArrayAdapter(_main, R.layout.spinnerrow);
            Colors.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

            Sounds = new SoundsArrayAdapter(_main, R.layout.soundsspinnerrow);
            Sounds.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        }

        spnASCII.getBackground().setColorFilter(Color.BLACK, PorterDuff.Mode.SRC_ATOP);
        spnStep.getBackground().setColorFilter(Color.BLACK, PorterDuff.Mode.SRC_ATOP);
        spnDisplayDurationBed.getBackground().setColorFilter(Color.BLACK, PorterDuff.Mode.SRC_ATOP);
        spnDisplayDurationWord.getBackground().setColorFilter(Color.BLACK, PorterDuff.Mode.SRC_ATOP);
        spnAbfragebereich.getBackground().setColorFilter(Color.BLACK, PorterDuff.Mode.SRC_ATOP);
        spnPaukRepetitions.getBackground().setColorFilter(Color.BLACK, PorterDuff.Mode.SRC_ATOP);
        spnProbabilityFactor.getBackground().setColorFilter(Color.BLACK, PorterDuff.Mode.SRC_ATOP);
        spnRestartInterval.getBackground().setColorFilter(Color.BLACK, PorterDuff.Mode.SRC_ATOP);
        spnLanguages.getBackground().setColorFilter(Color.BLACK, PorterDuff.Mode.SRC_ATOP);
        //spnColors.getBackground().setColorFilter(Color.BLACK,   PorterDuff.Mode.SRC_ATOP);
        //spnSounds.getBackground().setColorFilter(Color.BLACK,   PorterDuff.Mode.SRC_ATOP);

        // Create an ArrayAdapter using the string array and a default
        // spinner layout
        ScaledArrayAdapter<CharSequence> adapter = ScaledArrayAdapter.createFromResource(_main,
                R.array.spnAbfragebereichEntries, android.R.layout.simple_spinner_item);
        // Specify the layout to use when the list of choices appears
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        if (lib.NookSimpleTouch() && mScale == 1)
            adapter.Scale = 1.8f;
        // Apply the adapter to the spinner
        spnAbfragebereich.setAdapter(adapter);
        spnAbfragebereich.setSelection(getIntent().getShortExtra("Abfragebereich", (short) -1) + 1);

        spnAbfragebereich.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                intent.putExtra("Abfragebereich", (short) (position - 1));
                intent.putExtra("OK", "OK");
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }

        });
        ScaledArrayAdapter<CharSequence> adapterStep = ScaledArrayAdapter.createFromResource(_main,
                R.array.spnStepEntries, android.R.layout.simple_spinner_item);
        // Specify the layout to use when the list of choices appears
        adapterStep.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        // Apply the adapter to the spinner
        if (lib.NookSimpleTouch() && mScale == 1)
            adapterStep.Scale = 1.8f;
        spnStep.setAdapter(adapterStep);
        spnStep.setSelection(adapterStep.getPosition("" + getIntent().getShortExtra("Step", (short) 5)));
        spnStep.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                intent.putExtra("Step",
                        (short) (Integer.parseInt((String) parent.getItemAtPosition(position))));
                intent.putExtra("OK", "OK");
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }

        });

        ScaledArrayAdapter<String> adapterASCII = new ScaledArrayAdapter<String>(_main,
                android.R.layout.simple_spinner_item);
        // adapterASCII.addAll(Charset.availableCharsets().values());
        ArrayList<String> charsets = new ArrayList<String>();
        for (Charset c : Charset.availableCharsets().values()) {
            charsets.add(c.name());
        }
        adapterASCII.addAll(charsets);
        // Specify the layout to use when the list of choices appears
        adapterASCII.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        // Apply the adapter to the spinner
        if (lib.NookSimpleTouch() && mScale == 1)
            adapterASCII.Scale = 1.8f;
        spnASCII.setAdapter(adapterASCII);
        String CharsetASCII = getIntent().getStringExtra("CharsetASCII");
        if (!libString.IsNullOrEmpty(CharsetASCII)) {
            int i = 0;
            for (Charset c : Charset.availableCharsets().values()) {
                if (c.name().equalsIgnoreCase(CharsetASCII)) {
                    break;
                }
                i++;
            }
            if (i < adapterASCII.getCount()) {
                spnASCII.setSelection(i);
            }

        }
        spnASCII.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                intent.putExtra("CharsetASCII", ((String) (parent.getSelectedItem())));
                intent.putExtra("OK", "OK");
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }

        });

        final ScaledArrayAdapter<CharSequence> adapterDDWord = ScaledArrayAdapter.createFromResource(_main,
                R.array.spnDurations, android.R.layout.simple_spinner_item);
        // Specify the layout to use when the list of choices appears
        adapterDDWord.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        if (lib.NookSimpleTouch() && mScale == 1)
            adapterDDWord.Scale = 1.8f;
        // Apply the adapter to the spinner
        spnDisplayDurationWord.setAdapter(adapterDDWord);
        String strDD = "" + getIntent().getFloatExtra("DisplayDurationWord", 1.5f);
        strDD = strDD.replace(".0", "");
        int Pos = adapterDDWord.getPosition(strDD);
        spnDisplayDurationWord.setSelection(Pos);
        spnDisplayDurationWord.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                intent.putExtra("DisplayDurationWord",
                        (Float.parseFloat((String) parent.getItemAtPosition(position))));
                intent.putExtra("OK", "OK");
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }

        });

        ScaledArrayAdapter<CharSequence> adapterDDBed = ScaledArrayAdapter.createFromResource(_main,
                R.array.spnDurations, android.R.layout.simple_spinner_item);
        // Specify the layout to use when the list of choices appears
        adapterDDBed.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        if (lib.NookSimpleTouch() && mScale == 1)
            adapterDDBed.Scale = 1.8f;
        // Apply the adapter to the spinner
        spnDisplayDurationBed.setAdapter(adapterDDBed);
        strDD = "" + getIntent().getFloatExtra("DisplayDurationBed", 2.5f);
        strDD = strDD.replace(".0", "");
        Pos = adapterDDBed.getPosition(strDD);
        spnDisplayDurationBed.setSelection(Pos);
        spnDisplayDurationBed.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                intent.putExtra("DisplayDurationBed",
                        (Float.parseFloat((String) parent.getItemAtPosition(position))));
                intent.putExtra("OK", "OK");
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }

        });

        ScaledArrayAdapter<CharSequence> adapterPaukRepetitions = ScaledArrayAdapter.createFromResource(_main,
                R.array.spnRepetitions, android.R.layout.simple_spinner_item);
        // Specify the layout to use when the list of choices appears
        adapterPaukRepetitions.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        if (lib.NookSimpleTouch() && mScale == 1)
            adapterPaukRepetitions.Scale = 1.8f;
        spnPaukRepetitions.setAdapter(adapterPaukRepetitions);
        Pos = getIntent().getIntExtra("PaukRepetitions", 3) - 1;
        spnPaukRepetitions.setSelection(Pos);
        spnPaukRepetitions.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                intent.putExtra("PaukRepetitions",
                        (Integer.parseInt((String) parent.getItemAtPosition(position))));
                intent.putExtra("OK", "OK");
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }

        });

        ScaledArrayAdapter<CharSequence> adapterProbabilityFactor = ScaledArrayAdapter.createFromResource(_main,
                R.array.spnProbabilityFactors, android.R.layout.simple_spinner_item);
        // Specify the layout to use when the list of choices appears
        adapterProbabilityFactor.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        if (lib.NookSimpleTouch() && mScale == 1)
            adapterProbabilityFactor.Scale = 1.8f;
        spnProbabilityFactor.setAdapter(adapterProbabilityFactor);
        float ProbabilityFactor = getIntent().getFloatExtra("ProbabilityFactor", -1f);
        if (ProbabilityFactor == -1) {
            strDD = _main.getString((R.string.auto));
        } else {
            strDD = "" + ProbabilityFactor;
            strDD = strDD.replace(".0", "");
        }

        ArrayAdapter<CharSequence> a1 = adapterProbabilityFactor;
        if (a1 != null) {
            try {
                libLearn.gStatus = "get Spinneradapter ProbabilityFactor";
                Pos = (a1.getPosition(strDD));
                spnProbabilityFactor.setSelection(Pos);
            } catch (Exception ex) {
                lib.ShowException(_main, ex);
            }

        }

        spnProbabilityFactor.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                String strDD = (String) parent.getItemAtPosition(position);
                if (strDD.equalsIgnoreCase(_main.getString(R.string.auto)))
                    strDD = "-1";
                intent.putExtra("ProbabilityFactor", (Float.parseFloat(strDD)));
                intent.putExtra("OK", "OK");
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }

        });

        ScaledArrayAdapter<CharSequence> adapterRestartInterval = ScaledArrayAdapter.createFromResource(_main,
                R.array.spnRestartInterval, android.R.layout.simple_spinner_item);
        // Specify the layout to use when the list of choices appears
        adapterRestartInterval.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        if (lib.NookSimpleTouch() && mScale == 1)
            adapterRestartInterval.Scale = 1.8f;
        spnRestartInterval.setAdapter(adapterRestartInterval);
        int RestartInterval = getIntent().getIntExtra("RestartInterval", -1);
        if (RestartInterval == -1) {
            strDD = _main.getString(R.string.off);
        } else {
            strDD = "" + RestartInterval;
        }

        a1 = adapterRestartInterval;
        if (a1 != null) {
            try {
                libLearn.gStatus = "get Spinneradapter ProbabilityFactor";
                Pos = (a1.getPosition(strDD));
                spnRestartInterval.setSelection(Pos);
            } catch (Exception ex) {
                lib.ShowException(_main, ex);
            }

        }

        spnRestartInterval.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                String strDD = (String) parent.getItemAtPosition(position);
                if (strDD.equalsIgnoreCase(_main.getString(R.string.off)))
                    strDD = "-1";
                intent.putExtra("RestartInterval", (Integer.parseInt(strDD)));
                intent.putExtra("OK", "OK");
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }

        });

        ScaledArrayAdapter<CharSequence> adapterLanguages = ScaledArrayAdapter.createFromResource(_main,
                R.array.spnLanguages, android.R.layout.simple_spinner_item);
        // Specify the layout to use when the list of choices appears
        adapterLanguages.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        if (lib.NookSimpleTouch() && mScale == 1)
            adapterLanguages.Scale = 1.8f;
        spnLanguages.setAdapter(adapterLanguages);
        int Language = getIntent().getIntExtra("Language",
                org.de.jmg.learn.vok.Vokabel.EnumSprachen.undefiniert.ordinal());
        spnLanguages.setSelection(Language);
        spnLanguages.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                intent.putExtra("Language", position);
                intent.putExtra("OK", "OK");
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }

        });

        adapterLangWord = new ScaledArrayAdapter<>(_main, android.R.layout.simple_spinner_item);
        // Specify the layout to use when the list of choices appears
        adapterLangWord.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        if (lib.NookSimpleTouch() && mScale == 1)
            adapterLangWord.Scale = 1.8f;

        adapterLangWord.add(new DisplayLocale(new Locale("", "")));
        adapterLangWord.add(new DisplayLocale(new Locale("_off")));
        for (Locale l : Locale.getAvailableLocales()) {
            DisplayLocale dl = new DisplayLocale(l);
            adapterLangWord.add(dl);
        }
        sortLangWord();

        spnLangWord.setAdapter(adapterLangWord);
        /*
        if (selectedLocale != null)
        {
           int pos = adapterLangWord.getPosition(selectedLocale);
           spnLangWord.setSelection (-1);
           spnLangWord.setSelection(pos);
        }*/
        spnLangWord.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position <= 0 || langinitialized == 0) {
                    langinitialized += 1;
                    return;
                }
                Locale l = adapterLangWord.getItem(position).locale;
                int res = 0;
                if (_main.tts.isLanguageAvailable(Locale.US) >= 0) {
                    res = _main.tts.setLanguage(l);
                }
                if (!chkTextToSpeech.isChecked() || res >= 0 || l.toString().equalsIgnoreCase("_off")
                        || !_main.blnTextToSpeech
                        || lib.ShowMessageYesNo(_main,
                                String.format(_main.getString(R.string.msgLanguageNotavailable),
                                        l.getDisplayLanguage() + " " + l.getDisplayCountry()),
                                "") == yesnoundefined.yes) {
                    intent.putExtra("langword", lib.toLanguageTag(l));
                    intent.putExtra("OK", "OK");
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }

        });

        adapterLangMeaning = new ScaledArrayAdapter<>(_main, android.R.layout.simple_spinner_item);
        // Specify the layout to use when the list of choices appears
        adapterLangMeaning.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        if (lib.NookSimpleTouch() && mScale == 1)
            adapterLangMeaning.Scale = 1.8f;
        adapterLangMeaning.add(new DisplayLocale(new Locale("", "")));
        adapterLangMeaning.add(new DisplayLocale(new Locale("_off")));
        for (Locale l : Locale.getAvailableLocales()) {
            DisplayLocale dl = new DisplayLocale((l));
            adapterLangMeaning.add(dl);
        }
        sortLangMeaning();

        spnLangMeaning.setAdapter(adapterLangMeaning);
        /*
        if (selectedLocale != null)
        {
           int pos = adapterLangMeaning.getPosition(selectedLocale);
           spnLangMeaning.setSelection(-1);
           spnLangMeaning.setSelection(pos);
        }
        */
        spnLangMeaning.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position <= 0 || langinitialized < 2) {
                    langinitialized += 1;
                    return;
                }
                Locale l = adapterLangMeaning.getItem(position).locale;
                int res = 0;
                if (_main.tts.isLanguageAvailable(Locale.US) >= 0) {
                    res = _main.tts.setLanguage(l);
                }
                if (!chkTextToSpeech.isChecked() || res >= 0 || l.toString().equalsIgnoreCase("_off")
                        || !_main.blnTextToSpeech
                        || lib.ShowMessageYesNo(_main,
                                String.format(_main.getString(R.string.msgLanguageNotavailable),
                                        l.getDisplayLanguage() + " " + l.getDisplayCountry()),
                                "") == yesnoundefined.yes) {
                    intent.putExtra("langmeaning", lib.toLanguageTag(l));
                    intent.putExtra("OK", "OK");
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }

        });

        if (lib.NookSimpleTouch() && mScale == 1)
            Colors.Scale = 1.8f;
        spnColors.setAdapter(Colors);
        spnColors.setOnLongClickListener(new android.widget.AdapterView.OnLongClickListener() {

            @Override
            public boolean onLongClick(View v) {

                spnColors.blnDontCallOnClick = true;
                ShowColorDialog();
                return false;
            }
        });
        spnColors.setOnItemLongClickListener(new android.widget.AdapterView.OnItemLongClickListener() {

            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {

                spnColors.blnDontCallOnClick = true;
                ShowColorDialog();
                return false;
            }
        });

        if (lib.NookSimpleTouch() && mScale == 1)
            Sounds.Scale = 1.8f;
        spnSounds.setAdapter(Sounds);
        spnSounds.setOnLongClickListener(new android.widget.AdapterView.OnLongClickListener() {

            @Override
            public boolean onLongClick(View v) {

                spnSounds.blnDontCallOnClick = true;
                ShowSoundsDialog();
                return false;
            }
        });
        spnSounds.setOnItemLongClickListener(new android.widget.AdapterView.OnItemLongClickListener() {

            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {

                spnSounds.blnDontCallOnClick = true;
                ShowSoundsDialog();
                return false;
            }
        });

        spnSounds.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                SoundSetting item = (SoundSetting) parent.getItemAtPosition(position);
                File F = new File(item.SoundPath);
                try {
                    if (F.exists())
                        lib.playSound(F);
                    else
                        lib.playSound(_main.getAssets(), item.SoundPath);
                } catch (Exception e) {

                    e.printStackTrace();
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }

        });

    } catch (Exception ex) {
        lib.ShowException(_main, ex);
    }
}

From source file:de.vanita5.twittnuker.util.Utils.java

public static String getMapStaticImageUri(final double lat, final double lng, final int zoom, final int w,
        final int h, final Locale locale) {
    return String.format(Locale.US, MAPS_STATIC_IMAGE_URI_TEMPLATE, zoom, w, h, locale.toString(), lat, lng,
            lat, lng);/*from  ww  w . j a v a2  s. c om*/
}

From source file:facebook4j.FacebookImpl.java

public Map<String, JSONArray> executeMultiFQL(Map<String, String> queries, Locale locale)
        throws FacebookException {
    ensureAuthorizationEnabled();//from   www .ja va 2 s . c  om
    String url = conf.getRestBaseURL() + "fql?q=" + convertQueriesToJson(queries);
    if (locale != null) {
        url += "&locale=" + HttpParameter.encode(locale.toString());
    }
    JSONObject json = get(url).asJSONObject();
    Map<String, JSONArray> result = new HashMap<String, JSONArray>();
    try {
        JSONArray jsonArray = json.getJSONArray("data");
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            String name = jsonObject.getString("name");
            JSONArray resultSets = jsonObject.getJSONArray("fql_result_set");
            result.put(name, resultSets);
        }
    } catch (JSONException jsone) {
        throw new FacebookException(jsone.getMessage(), jsone);
    }
    return result;
}

From source file:com.gst.infrastructure.core.serialization.JsonParserHelper.java

public BigDecimal convertFrom(final String numericalValueFormatted, final String parameterName,
        final Locale clientApplicationLocale) {

    if (clientApplicationLocale == null) {

        final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
        final String defaultMessage = new StringBuilder(
                "The parameter '" + parameterName + "' requires a 'locale' parameter to be passed with it.")
                        .toString();// w  w w . jav a2  s . c o  m
        final ApiParameterError error = ApiParameterError
                .parameterError("validation.msg.missing.locale.parameter", defaultMessage, parameterName);
        dataValidationErrors.add(error);

        throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist",
                "Validation errors exist.", dataValidationErrors);
    }

    try {
        BigDecimal number = null;

        if (StringUtils.isNotBlank(numericalValueFormatted)) {

            String source = numericalValueFormatted.trim();

            final NumberFormat format = NumberFormat.getNumberInstance(clientApplicationLocale);
            final DecimalFormat df = (DecimalFormat) format;
            final DecimalFormatSymbols symbols = df.getDecimalFormatSymbols();
            // http://bugs.sun.com/view_bug.do?bug_id=4510618
            final char groupingSeparator = symbols.getGroupingSeparator();
            if (groupingSeparator == '\u00a0') {
                source = source.replaceAll(" ", Character.toString('\u00a0'));
            }

            final NumberFormatter numberFormatter = new NumberFormatter();
            final Number parsedNumber = numberFormatter.parse(source, clientApplicationLocale);
            if (parsedNumber instanceof BigDecimal) {
                number = (BigDecimal) parsedNumber;
            } else {
                number = BigDecimal.valueOf(Double.valueOf(parsedNumber.doubleValue()));
            }
        }

        return number;
    } catch (final ParseException e) {

        final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
        final ApiParameterError error = ApiParameterError.parameterError(
                "validation.msg.invalid.decimal.format",
                "The parameter " + parameterName + " has value: " + numericalValueFormatted
                        + " which is invalid decimal value for provided locale of ["
                        + clientApplicationLocale.toString() + "].",
                parameterName, numericalValueFormatted, clientApplicationLocale);
        error.setValue(numericalValueFormatted);
        dataValidationErrors.add(error);

        throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist",
                "Validation errors exist.", dataValidationErrors);
    }
}

From source file:facebook4j.FacebookImpl.java

public JSONArray executeFQL(String query, Locale locale) throws FacebookException {
    ensureAuthorizationEnabled();//  w  w  w  . j  av a  2  s. co  m
    String url = "";
    try {
        url = conf.getRestBaseURL() + "fql?q=" + URLEncoder.encode(query, "UTF-8");
    } catch (UnsupportedEncodingException ignore) {
    }
    if (locale != null) {
        url += "&locale=" + HttpParameter.encode(locale.toString());
    }

    JSONObject json = get(url).asJSONObject();
    try {
        return json.getJSONArray("data");
    } catch (JSONException jsone) {
        throw new FacebookException(jsone.getMessage(), jsone);
    }
}

From source file:org.jahia.services.sites.JahiaSitesService.java

public JahiaSite addSite(JahiaUser currentUser, String title, String serverName, String siteKey, String descr,
        Locale selectedLocale, String selectTmplSet, final String[] modulesToDeploy, String firstImport,
        Resource fileImport, String fileImportName, Boolean asAJob, Boolean doImportServerPermissions,
        String originatingJahiaRelease, Resource legacyMappingFilePath, Resource legacyDefinitionsFilePath,
        JCRSessionWrapper session) throws JahiaException, IOException {

    // check there is no site with same server name before adding
    boolean importingSystemSite = false;
    final JahiaTemplateManagerService templateService = ServicesRegistry.getInstance()
            .getJahiaTemplateManagerService();
    JCRSiteNode site = null;//w ww  . j  av a2s  .  c om

    try {

        if (!siteExists(siteKey, session)) {

            final JahiaTemplatesPackage templateSet = templateService
                    .getAnyDeployedTemplatePackage(selectTmplSet);
            final String templatePackage = templateSet.getId();

            JCRNodeWrapper sitesFolder = session.getNode("/sites");

            try {
                sitesFolder.getNode(siteKey);
                throw new IOException("site already exists");
            } catch (PathNotFoundException e) {

                JCRNodeWrapper siteNode = sitesFolder.addNode(siteKey, "jnt:virtualsite");

                if (sitesFolder.hasProperty("j:virtualsitesFolderSkeleton")) {
                    String skeletons = sitesFolder.getProperty("j:virtualsitesFolderSkeleton").getString();
                    try {
                        JCRContentUtils.importSkeletons(skeletons, sitesFolder.getPath() + "/" + siteKey,
                                session);
                    } catch (Exception importEx) {
                        logger.error("Unable to import data using site skeleton " + skeletons, importEx);
                    }
                }

                siteNode.setProperty("j:title", title);
                siteNode.setProperty("j:description", descr);
                siteNode.setProperty("j:serverName", serverName);
                siteNode.setProperty(SitesSettings.DEFAULT_LANGUAGE, selectedLocale.toString());
                siteNode.setProperty(SitesSettings.MIX_LANGUAGES_ACTIVE, false);
                siteNode.setProperty(SitesSettings.LANGUAGES, new String[] { selectedLocale.toString() });
                siteNode.setProperty(SitesSettings.INACTIVE_LIVE_LANGUAGES, new String[] {});
                siteNode.setProperty(SitesSettings.INACTIVE_LANGUAGES, new String[] {});
                siteNode.setProperty(SitesSettings.MANDATORY_LANGUAGES, new String[] {});
                siteNode.setProperty("j:templatesSet", templatePackage);

                siteNode.setProperty("j:installedModules", new Value[] { session.getValueFactory()
                        .createValue(templatePackage /*+ ":" + aPackage.getLastVersion()*/) });

                String target = getTargetString(siteKey);

                deployModules(target, modulesToDeploy, templateSet, session, templateService);

                //Auto deploy all modules that define this behavior on site creation
                final List<JahiaTemplatesPackage> availableTemplatePackages = templateService
                        .getAvailableTemplatePackages();
                for (JahiaTemplatesPackage availableTemplatePackage : availableTemplatePackages) {
                    String autoDeployOnSite = availableTemplatePackage.getAutoDeployOnSite();
                    if (autoDeployOnSite != null
                            && ("all".equals(autoDeployOnSite) || siteKey.equals(autoDeployOnSite)
                                    || (siteKey.equals("systemsite") && autoDeployOnSite.equals("system")))) {
                        String source = "/modules/" + availableTemplatePackage.getId();
                        try {
                            logger.info("Deploying module {} to {}", source, target);
                            templateService.installModule(availableTemplatePackage, target, session);
                        } catch (RepositoryException re) {
                            logger.error("Unable to deploy module " + source + " to " + target + ". Cause: "
                                    + re.getMessage(), re);
                        }
                    }
                }
                site = (JCRSiteNode) siteNode;
            }

            session.save();
        } else if (siteKey.equals(SYSTEM_SITE_KEY)) {
            site = (JCRSiteNode) getSiteByKey(SYSTEM_SITE_KEY);
            importingSystemSite = true;
        } else {
            throw new IOException("site already exists");
        }

        JCRSiteNode siteNode = (JCRSiteNode) session.getNode(site.getPath());

        // continue if the site is added correctly...
        if (!site.isDefault() && !site.getSiteKey().equals(SYSTEM_SITE_KEY) && getNbSites() == 2) {
            setDefaultSite(site, session);
        }

        if (!importingSystemSite) {

            JahiaGroupManagerService jgms = ServicesRegistry.getInstance().getJahiaGroupManagerService();

            siteNode.setMixLanguagesActive(false);
            session.save();

            JCRGroupNode privGroup = jgms.lookupGroup(null, JahiaGroupManagerService.PRIVILEGED_GROUPNAME,
                    session);
            if (privGroup == null) {
                privGroup = jgms.createGroup(null, JahiaGroupManagerService.PRIVILEGED_GROUPNAME, null, true,
                        session);
            }

            JCRGroupNode adminGroup = jgms.lookupGroup(site.getSiteKey(),
                    JahiaGroupManagerService.SITE_ADMINISTRATORS_GROUPNAME, session);
            if (adminGroup == null) {
                adminGroup = jgms.createGroup(site.getSiteKey(),
                        JahiaGroupManagerService.SITE_ADMINISTRATORS_GROUPNAME, null, false, session);
            }

            // attach superadmin user (current) to administrators group...
            if (currentUser != null) {
                adminGroup.addMember(session.getNode(currentUser.getLocalPath()));
            }

            JCRGroupNode sitePrivGroup = jgms.lookupGroup(site.getSiteKey(),
                    JahiaGroupManagerService.SITE_PRIVILEGED_GROUPNAME, session);
            if (sitePrivGroup == null) {
                sitePrivGroup = jgms.createGroup(site.getSiteKey(),
                        JahiaGroupManagerService.SITE_PRIVILEGED_GROUPNAME, null, false, session);
            }
            // atach site privileged group to server privileged
            privGroup.addMember(sitePrivGroup);

            if (!siteKey.equals(SYSTEM_SITE_KEY)) {
                siteNode.grantRoles("g:" + JahiaGroupManagerService.SITE_PRIVILEGED_GROUPNAME,
                        Collections.singleton("privileged"));
                siteNode.denyRoles("g:" + JahiaGroupManagerService.PRIVILEGED_GROUPNAME,
                        Collections.singleton("privileged"));
            }
            siteNode.grantRoles("g:" + JahiaGroupManagerService.SITE_ADMINISTRATORS_GROUPNAME,
                    Collections.singleton("site-administrator"));
            session.save();
        }

        Resource initialZip = null;
        if ("fileImport".equals(firstImport)) {
            initialZip = fileImport;
        }

        if ("importRepositoryFile".equals(firstImport)
                || (initialZip != null && initialZip.exists() && !"noImport".equals(firstImport))) {
            try {
                Map<Object, Object> importInfos = new HashMap<Object, Object>();
                importInfos.put("originatingJahiaRelease", originatingJahiaRelease);
                ServicesRegistry.getInstance().getImportExportService().importSiteZip(initialZip, site,
                        importInfos, legacyMappingFilePath, legacyDefinitionsFilePath, session);
            } catch (RepositoryException e) {
                logger.warn("Error importing site ZIP", e);
            }
        }

        logger.debug("Site updated with Home Page");
    } catch (RepositoryException e) {
        logger.warn("Error adding home node", e);
    }

    return site;
}

From source file:org.mifosplatform.infrastructure.core.serialization.JsonParserHelper.java

public Integer convertToInteger(final String numericalValueFormatted, final String parameterName,
        final Locale clientApplicationLocale) {

    if (clientApplicationLocale == null) {

        final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
        final String defaultMessage = new StringBuilder(
                "The parameter '" + parameterName + "' requires a 'locale' parameter to be passed with it.")
                        .toString();//from w  w  w .  ja  va 2 s  .c om
        final ApiParameterError error = ApiParameterError
                .parameterError("validation.msg.missing.locale.parameter", defaultMessage, parameterName);
        dataValidationErrors.add(error);

        throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist",
                "Validation errors exist.", dataValidationErrors);
    }

    try {
        Integer number = null;

        if (StringUtils.isNotBlank(numericalValueFormatted)) {

            String source = numericalValueFormatted.trim();

            final NumberFormat format = NumberFormat.getInstance(clientApplicationLocale);
            final DecimalFormat df = (DecimalFormat) format;
            final DecimalFormatSymbols symbols = df.getDecimalFormatSymbols();
            df.setParseBigDecimal(true);

            // http://bugs.sun.com/view_bug.do?bug_id=4510618
            final char groupingSeparator = symbols.getGroupingSeparator();
            if (groupingSeparator == '\u00a0') {
                source = source.replaceAll(" ", Character.toString('\u00a0'));
            }

            final Number parsedNumber = df.parse(source);

            final double parsedNumberDouble = parsedNumber.doubleValue();
            final int parsedNumberInteger = parsedNumber.intValue();

            if (source.contains(Character.toString(symbols.getDecimalSeparator()))) {
                throw new ParseException(source, 0);
            }

            if (!Double.valueOf(parsedNumberDouble)
                    .equals(Double.valueOf(Integer.valueOf(parsedNumberInteger)))) {
                throw new ParseException(source, 0);
            }

            number = parsedNumber.intValue();
        }

        return number;
    } catch (final ParseException e) {

        final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
        final ApiParameterError error = ApiParameterError.parameterError(
                "validation.msg.invalid.integer.format",
                "The parameter " + parameterName + " has value: " + numericalValueFormatted
                        + " which is invalid integer value for provided locale of ["
                        + clientApplicationLocale.toString() + "].",
                parameterName, numericalValueFormatted, clientApplicationLocale);
        error.setValue(numericalValueFormatted);
        dataValidationErrors.add(error);

        throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist",
                "Validation errors exist.", dataValidationErrors);
    }
}