Example usage for java.lang ClassCastException getMessage

List of usage examples for java.lang ClassCastException getMessage

Introduction

In this page you can find the example usage for java.lang ClassCastException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:tuit.java

@SuppressWarnings("ConstantConditions")
public static void main(String[] args) {
    System.out.println(licence);//from   w  w  w .  j  a v  a2  s.  com
    //Declare variables
    File inputFile;
    File outputFile;
    File tmpDir;
    File blastnExecutable;
    File properties;
    File blastOutputFile = null;
    //
    TUITPropertiesLoader tuitPropertiesLoader;
    TUITProperties tuitProperties;
    //
    String[] parameters = null;
    //
    Connection connection = null;
    MySQL_Connector mySQL_connector;
    //
    Map<Ranks, TUITCutoffSet> cutoffMap;
    //
    BLASTIdentifier blastIdentifier = null;
    //
    RamDb ramDb = null;

    CommandLineParser parser = new GnuParser();
    Options options = new Options();

    options.addOption(tuit.IN, "input<file>", true, "Input file (currently fasta-formatted only)");
    options.addOption(tuit.OUT, "output<file>", true, "Output file (in " + tuit.TUIT_EXT + " format)");
    options.addOption(tuit.P, "prop<file>", true, "Properties file (XML formatted)");
    options.addOption(tuit.V, "verbose", false, "Enable verbose output");
    options.addOption(tuit.B, "blast_output<file>", true, "Perform on a pre-BLASTed output");
    options.addOption(tuit.DEPLOY, "deploy", false, "Deploy the taxonomic databases");
    options.addOption(tuit.UPDATE, "update", false, "Update the taxonomic databases");
    options.addOption(tuit.USE_DB, "usedb", false, "Use RDBMS instead of RAM-based taxonomy");

    Option option = new Option(tuit.REDUCE, "reduce", true,
            "Pack identical (100% similar sequences) records in the given sample file");
    option.setArgs(Option.UNLIMITED_VALUES);
    options.addOption(option);
    option = new Option(tuit.COMBINE, "combine", true,
            "Combine a set of given reduction files into an HMP Tree-compatible taxonomy");
    option.setArgs(Option.UNLIMITED_VALUES);
    options.addOption(option);
    options.addOption(tuit.NORMALIZE, "normalize", false,
            "If used in combination with -combine ensures that the values are normalized by the root value");

    HelpFormatter formatter = new HelpFormatter();

    try {

        //Get TUIT directory
        final File tuitDir = new File(
                new File(tuit.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath())
                        .getParent());
        final File ramDbFile = new File(tuitDir, tuit.RAM_DB);

        //Setup logger
        Log.getInstance().setLogName("tuit.log");

        //Read command line
        final CommandLine commandLine = parser.parse(options, args, true);

        //Check if the REDUCE option is on
        if (commandLine.hasOption(tuit.REDUCE)) {

            final String[] fileList = commandLine.getOptionValues(tuit.REDUCE);
            for (String s : fileList) {
                final Path path = Paths.get(s);
                Log.getInstance().log(Level.INFO, "Processing " + path.toString() + "...");
                final NucleotideFastaSequenceReductor nucleotideFastaSequenceReductor = NucleotideFastaSequenceReductor
                        .fromPath(path);
                ReductorFileOperator.save(nucleotideFastaSequenceReductor,
                        path.resolveSibling(path.getFileName().toString() + ".rdc"));
            }

            Log.getInstance().log(Level.FINE, "Task done, exiting...");
            return;
        }

        //Check if COMBINE is on
        if (commandLine.hasOption(tuit.COMBINE)) {
            final boolean normalize = commandLine.hasOption(tuit.NORMALIZE);
            final String[] fileList = commandLine.getOptionValues(tuit.COMBINE);
            //TODO: implement a test for format here

            final List<TreeFormatter.TreeFormatterFormat.HMPTreesOutput> hmpTreesOutputs = new ArrayList<>();
            final TreeFormatter treeFormatter = TreeFormatter
                    .newInstance(new TreeFormatter.TuitLineTreeFormatterFormat());
            for (String s : fileList) {
                final Path path = Paths.get(s);
                Log.getInstance().log(Level.INFO, "Merging " + path.toString() + "...");
                treeFormatter.loadFromPath(path);
                final TreeFormatter.TreeFormatterFormat.HMPTreesOutput output = TreeFormatter.TreeFormatterFormat.HMPTreesOutput
                        .newInstance(treeFormatter.toHMPTree(normalize), s.substring(0, s.indexOf(".")));
                hmpTreesOutputs.add(output);
                treeFormatter.erase();
            }
            final Path destination;
            if (commandLine.hasOption(OUT)) {
                destination = Paths.get(commandLine.getOptionValue(tuit.OUT));
            } else {
                destination = Paths.get("merge.tcf");
            }
            CombinatorFileOperator.save(hmpTreesOutputs, treeFormatter, destination);
            Log.getInstance().log(Level.FINE, "Task done, exiting...");
            return;
        }

        if (!commandLine.hasOption(tuit.P)) {
            throw new ParseException("No properties file option found, exiting.");
        } else {
            properties = new File(commandLine.getOptionValue(tuit.P));
        }

        //Load properties
        tuitPropertiesLoader = TUITPropertiesLoader.newInstanceFromFile(properties);
        tuitProperties = tuitPropertiesLoader.getTuitProperties();

        //Create tmp directory and blastn executable
        tmpDir = new File(tuitProperties.getTMPDir().getPath());
        blastnExecutable = new File(tuitProperties.getBLASTNPath().getPath());

        //Check for deploy
        if (commandLine.hasOption(tuit.DEPLOY)) {
            if (commandLine.hasOption(tuit.USE_DB)) {
                NCBITablesDeployer.fastDeployNCBIDatabasesFromNCBI(connection, tmpDir);
            } else {
                NCBITablesDeployer.fastDeployNCBIRamDatabaseFromNCBI(tmpDir, ramDbFile);
            }

            Log.getInstance().log(Level.FINE, "Task done, exiting...");
            return;
        }
        //Check for update
        if (commandLine.hasOption(tuit.UPDATE)) {
            if (commandLine.hasOption(tuit.USE_DB)) {
                NCBITablesDeployer.updateDatabasesFromNCBI(connection, tmpDir);
            } else {
                //No need to specify a different way to update the database other than just deploy in case of the RAM database
                NCBITablesDeployer.fastDeployNCBIRamDatabaseFromNCBI(tmpDir, ramDbFile);
            }
            Log.getInstance().log(Level.FINE, "Task done, exiting...");
            return;
        }

        //Connect to the database
        if (commandLine.hasOption(tuit.USE_DB)) {
            mySQL_connector = MySQL_Connector.newDefaultInstance(
                    "jdbc:mysql://" + tuitProperties.getDBConnection().getUrl().trim() + "/",
                    tuitProperties.getDBConnection().getLogin().trim(),
                    tuitProperties.getDBConnection().getPassword().trim());
            mySQL_connector.connectToDatabase();
            connection = mySQL_connector.getConnection();
        } else {
            //Probe for ram database

            if (ramDbFile.exists() && ramDbFile.canRead()) {
                Log.getInstance().log(Level.INFO, "Loading RAM taxonomic map...");
                try {
                    ramDb = RamDb.loadSelfFromFile(ramDbFile);
                } catch (IOException ie) {
                    if (ie instanceof java.io.InvalidClassException)
                        throw new IOException("The RAM-based taxonomic database needs to be updated.");
                }

            } else {
                Log.getInstance().log(Level.SEVERE,
                        "The RAM database either has not been deployed, or is not accessible."
                                + "Please use the --deploy option and check permissions on the TUIT directory. "
                                + "If you were looking to use the RDBMS as a taxonomic reference, plese use the -usedb option.");
                return;
            }
        }

        if (commandLine.hasOption(tuit.B)) {
            blastOutputFile = new File(commandLine.getOptionValue(tuit.B));
            if (!blastOutputFile.exists() || !blastOutputFile.canRead()) {
                throw new Exception("BLAST output file either does not exist, or is not readable.");
            } else if (blastOutputFile.isDirectory()) {
                throw new Exception("BLAST output file points to a directory.");
            }
        }
        //Check vital parameters
        if (!commandLine.hasOption(tuit.IN)) {
            throw new ParseException("No input file option found, exiting.");
        } else {
            inputFile = new File(commandLine.getOptionValue(tuit.IN));
            Log.getInstance().setLogName(inputFile.getName().split("\\.")[0] + ".tuit.log");
        }
        //Correct the output file option if needed
        if (!commandLine.hasOption(tuit.OUT)) {
            outputFile = new File((inputFile.getPath()).split("\\.")[0] + tuit.TUIT_EXT);
        } else {
            outputFile = new File(commandLine.getOptionValue(tuit.OUT));
        }

        //Adjust the output level
        if (commandLine.hasOption(tuit.V)) {
            Log.getInstance().setLevel(Level.FINE);
            Log.getInstance().log(Level.INFO, "Using verbose output for the log");
        } else {
            Log.getInstance().setLevel(Level.INFO);
        }
        //Try all files
        if (inputFile != null) {
            if (!inputFile.exists() || !inputFile.canRead()) {
                throw new Exception("Input file either does not exist, or is not readable.");
            } else if (inputFile.isDirectory()) {
                throw new Exception("Input file points to a directory.");
            }
        }

        if (!properties.exists() || !properties.canRead()) {
            throw new Exception("Properties file either does not exist, or is not readable.");
        } else if (properties.isDirectory()) {
            throw new Exception("Properties file points to a directory.");
        }

        //Create blast parameters
        final StringBuilder stringBuilder = new StringBuilder();
        for (Database database : tuitProperties.getBLASTNParameters().getDatabase()) {
            stringBuilder.append(database.getUse());
            stringBuilder.append(" ");//Gonna insert an extra space for the last database
        }
        String remote;
        String entrez_query;
        if (tuitProperties.getBLASTNParameters().getRemote().getDelegate().equals("yes")) {
            remote = "-remote";
            entrez_query = "-entrez_query";
            parameters = new String[] { "-db", stringBuilder.toString(), remote, entrez_query,
                    tuitProperties.getBLASTNParameters().getEntrezQuery().getValue(), "-evalue",
                    tuitProperties.getBLASTNParameters().getExpect().getValue() };
        } else {
            if (!commandLine.hasOption(tuit.B)) {
                if (tuitProperties.getBLASTNParameters().getEntrezQuery().getValue().toUpperCase()
                        .startsWith("NOT")
                        || tuitProperties.getBLASTNParameters().getEntrezQuery().getValue().toUpperCase()
                                .startsWith("ALL")) {
                    parameters = new String[] { "-db", stringBuilder.toString(), "-evalue",
                            tuitProperties.getBLASTNParameters().getExpect().getValue(), "-negative_gilist",
                            TUITFileOperatorHelper.restrictToEntrez(tmpDir,
                                    tuitProperties.getBLASTNParameters().getEntrezQuery().getValue()
                                            .toUpperCase().replace("NOT", "OR"))
                                    .getAbsolutePath(),
                            "-num_threads", tuitProperties.getBLASTNParameters().getNumThreads().getValue() };
                } else if (tuitProperties.getBLASTNParameters().getEntrezQuery().getValue().toUpperCase()
                        .equals("")) {
                    parameters = new String[] { "-db", stringBuilder.toString(), "-evalue",
                            tuitProperties.getBLASTNParameters().getExpect().getValue(), "-num_threads",
                            tuitProperties.getBLASTNParameters().getNumThreads().getValue() };
                } else {
                    parameters = new String[] { "-db", stringBuilder.toString(), "-evalue",
                            tuitProperties.getBLASTNParameters().getExpect().getValue(),
                            /*"-gilist", TUITFileOperatorHelper.restrictToEntrez(
                            tmpDir, tuitProperties.getBLASTNParameters().getEntrezQuery().getValue()).getAbsolutePath(),*/ //TODO remove comment!!!!!
                            "-num_threads", tuitProperties.getBLASTNParameters().getNumThreads().getValue() };
                }
            }
        }
        //Prepare a cutoff Map
        if (tuitProperties.getSpecificationParameters() != null
                && tuitProperties.getSpecificationParameters().size() > 0) {
            cutoffMap = new HashMap<Ranks, TUITCutoffSet>(tuitProperties.getSpecificationParameters().size());
            for (SpecificationParameters specificationParameters : tuitProperties
                    .getSpecificationParameters()) {
                cutoffMap.put(Ranks.valueOf(specificationParameters.getCutoffSet().getRank()),
                        TUITCutoffSet.newDefaultInstance(
                                Double.parseDouble(
                                        specificationParameters.getCutoffSet().getPIdentCutoff().getValue()),
                                Double.parseDouble(specificationParameters.getCutoffSet()
                                        .getQueryCoverageCutoff().getValue()),
                                Double.parseDouble(
                                        specificationParameters.getCutoffSet().getAlpha().getValue())));
            }
        } else {
            cutoffMap = new HashMap<Ranks, TUITCutoffSet>();
        }
        final TUITFileOperatorHelper.OutputFormat format;
        if (tuitProperties.getBLASTNParameters().getOutputFormat().getFormat().equals("rdp")) {
            format = TUITFileOperatorHelper.OutputFormat.RDP_FIXRANK;
        } else {
            format = TUITFileOperatorHelper.OutputFormat.TUIT;
        }

        try (TUITFileOperator<NucleotideFasta> nucleotideFastaTUITFileOperator = NucleotideFastaTUITFileOperator
                .newInstance(format, cutoffMap);) {
            nucleotideFastaTUITFileOperator.setInputFile(inputFile);
            nucleotideFastaTUITFileOperator.setOutputFile(outputFile);
            final String cleanupString = tuitProperties.getBLASTNParameters().getKeepBLASTOuts().getKeep();
            final boolean cleanup;
            if (cleanupString.equals("no")) {
                Log.getInstance().log(Level.INFO, "Temporary BLAST files will be deleted.");
                cleanup = true;
            } else {
                Log.getInstance().log(Level.INFO, "Temporary BLAST files will be kept.");
                cleanup = false;
            }
            //Create blast identifier
            ExecutorService executorService = Executors.newSingleThreadExecutor();
            if (commandLine.hasOption(tuit.USE_DB)) {

                if (blastOutputFile == null) {
                    blastIdentifier = TUITBLASTIdentifierDB.newInstanceFromFileOperator(tmpDir,
                            blastnExecutable, parameters, nucleotideFastaTUITFileOperator, connection,
                            cutoffMap,
                            Integer.parseInt(
                                    tuitProperties.getBLASTNParameters().getMaxFilesInBatch().getValue()),
                            cleanup);

                } else {
                    try {
                        blastIdentifier = TUITBLASTIdentifierDB.newInstanceFromBLASTOutput(
                                nucleotideFastaTUITFileOperator, connection, cutoffMap, blastOutputFile,
                                Integer.parseInt(
                                        tuitProperties.getBLASTNParameters().getMaxFilesInBatch().getValue()),
                                cleanup);

                    } catch (JAXBException e) {
                        Log.getInstance().log(Level.SEVERE, "Error reading " + blastOutputFile.getName()
                                + ", please check input. The file must be XML formatted.");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            } else {
                if (blastOutputFile == null) {
                    blastIdentifier = TUITBLASTIdentifierRAM.newInstanceFromFileOperator(tmpDir,
                            blastnExecutable, parameters, nucleotideFastaTUITFileOperator, cutoffMap,
                            Integer.parseInt(
                                    tuitProperties.getBLASTNParameters().getMaxFilesInBatch().getValue()),
                            cleanup, ramDb);

                } else {
                    try {
                        blastIdentifier = TUITBLASTIdentifierRAM.newInstanceFromBLASTOutput(
                                nucleotideFastaTUITFileOperator, cutoffMap, blastOutputFile,
                                Integer.parseInt(
                                        tuitProperties.getBLASTNParameters().getMaxFilesInBatch().getValue()),
                                cleanup, ramDb);

                    } catch (JAXBException e) {
                        Log.getInstance().log(Level.SEVERE, "Error reading " + blastOutputFile.getName()
                                + ", please check input. The file must be XML formatted.");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            Future<?> runnableFuture = executorService.submit(blastIdentifier);
            runnableFuture.get();
            executorService.shutdown();
        }
    } catch (ParseException pe) {
        Log.getInstance().log(Level.SEVERE, (pe.getMessage()));
        formatter.printHelp("tuit", options);
    } catch (SAXException saxe) {
        Log.getInstance().log(Level.SEVERE, saxe.getMessage());
    } catch (FileNotFoundException fnfe) {
        Log.getInstance().log(Level.SEVERE, fnfe.getMessage());
    } catch (TUITPropertyBadFormatException tpbfe) {
        Log.getInstance().log(Level.SEVERE, tpbfe.getMessage());
    } catch (ClassCastException cce) {
        Log.getInstance().log(Level.SEVERE, cce.getMessage());
    } catch (JAXBException jaxbee) {
        Log.getInstance().log(Level.SEVERE,
                "The properties file is not well formatted. Please ensure that the XML is consistent with the io.properties.dtd schema.");
    } catch (ClassNotFoundException cnfe) {
        //Probably won't happen unless the library deleted from the .jar
        Log.getInstance().log(Level.SEVERE, cnfe.getMessage());
        //cnfe.printStackTrace();
    } catch (SQLException sqle) {
        Log.getInstance().log(Level.SEVERE,
                "A database communication error occurred with the following message:\n" + sqle.getMessage());
        //sqle.printStackTrace();
        if (sqle.getMessage().contains("Access denied for user")) {
            Log.getInstance().log(Level.SEVERE, "Please use standard database login: "
                    + NCBITablesDeployer.login + " and password: " + NCBITablesDeployer.password);
        }
    } catch (Exception e) {
        Log.getInstance().log(Level.SEVERE, e.getMessage());
        e.printStackTrace();
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException sqle) {
                Log.getInstance().log(Level.SEVERE, "Problem closing the database connection: " + sqle);
            }
        }
        Log.getInstance().log(Level.FINE, "Task done, exiting...");
    }
}

From source file:Main.java

@SuppressWarnings("unchecked")
public static final <E extends View> E getView(View parent, int id) {
    try {/*from   w w  w.ja va 2  s . co m*/
        return (E) parent.findViewById(id);
    } catch (ClassCastException ex) {
        Log.e("ImagPageUtil", "Could not cast View to concrete class \n" + ex.getMessage());
        throw ex;
    }
}

From source file:com.comcast.cats.service.util.YAMLUtils.java

@SuppressWarnings("unchecked")
public static synchronized <T> T loadFromYAML(String filePath, T resultObject, Constructor constructor)
        throws IllegalClassException, IOException {
    Yaml yaml;//from  www. j a  v  a 2  s .c o m
    FileInputStream fileIS = null;

    if (constructor != null) {
        yaml = new Yaml(constructor);
    } else {
        yaml = new Yaml();
    }
    try {
        fileIS = new FileInputStream(filePath);
        resultObject = (T) yaml.load(fileIS);
    } catch (FileNotFoundException exception) {
        File file = new File(filePath);
        file.createNewFile(); // create file if one does not exist.
        fileIS = new FileInputStream(filePath);
        resultObject = (T) yaml.load(fileIS);
    } catch (ClassCastException e) {
        logger.warn(
                "YAML content found at " + filePath + " does not conform to passed object " + e.getMessage());
        throw new IllegalClassException(
                "YAML content found at " + filePath + " does not conform to passed object " + e.getMessage());
    } finally {
        if (fileIS != null) {
            fileIS.close();
        }
    }

    return resultObject;
}

From source file:com.feilong.core.lang.ObjectUtilTemp.java

/**
 * ?? {@link java.util.Iterator}.//from ww w .  ja va2s. com
 * <p>
 * ??,,???with no copying<br>
 * ?, ClassCastException  ,Rats -- ,arrayList ?arrayList.iterator()
 * </p>
 * <p>
 * <b>:</b>{@link Arrays#asList(Object...)} list {@link Array}  ArrayList,
 * {@link java.util.AbstractList#add(int, Object)} ,<br>
 * listadd?, {@link java.lang.UnsupportedOperationException}
 * </p>
 * 
 * @param <T>
 *            the generic type
 * @param arrays
 *            ,? , 
 * @return  (null == arrays)  null;<br>
 *         ?arrays?Object[], {@link Arrays#asList(Object...)}?list,? {@link List#iterator()
 *         t}<br>
 *         ,? Object[],?, {@link Array#getLength(Object)}?, {@link Array#get(Object, int)} list
 * @see Arrays#asList(Object...)
 * @see Array#getLength(Object)
 * @see Array#get(Object, int)
 * @see List#iterator()
 * @deprecated
 */
@Deprecated
@SuppressWarnings({ "unchecked" })
public static <T> Iterator<T> toIterator(Object arrays) {
    if (null == arrays) {
        return null;
    }
    List<T> list = null;
    try {
        // ??,,???with no copying
        Object[] objArrays = (Object[]) arrays;
        list = (List<T>) toList(objArrays);
    } catch (ClassCastException e) {
        LOGGER.debug("arrays can not cast to Object[],maybe primitive type,values is:{},{}", arrays,
                e.getMessage());
        // Rats -- 
        int length = Array.getLength(arrays);
        list = new ArrayList<T>(length);
        for (int i = 0; i < length; ++i) {
            Object object = Array.get(arrays, i);
            list.add((T) object);
        }
    }
    return list.iterator();
}

From source file:org.apache.synapse.util.PayloadHelper.java

public static DataHandler getBinaryPayload(SOAPEnvelope envelope) {
    OMElement el = getXMLPayload(envelope);
    if (el == null)
        return null;
    if (!el.getQName().equals(BINARYELT)) {
        log.error("Wrong QName" + el.getQName());
        return null;
    }// w w  w .j  av  a  2  s.c  o m
    OMNode textNode = el.getFirstOMChild();
    if (textNode.getType() != OMNode.TEXT_NODE) {
        log.error("Text Node not found");
        return null;
    }
    OMText text = (OMText) textNode;
    try {
        return (DataHandler) text.getDataHandler();
    } catch (ClassCastException ce) {
        log.error("cannot get DataHandler" + ce.getMessage());
        return null;
    }
}

From source file:com.netflix.astyanax.thrift.ThriftUtils.java

@SuppressWarnings({ "rawtypes", "unchecked" })
private static Object populateObject(Object obj, Map<String, Object> map) throws Exception {
    org.apache.thrift.TBase entity = (org.apache.thrift.TBase) obj;
    Field field = entity.getClass().getDeclaredField("metaDataMap");
    Map<org.apache.thrift.TFieldIdEnum, org.apache.thrift.meta_data.FieldMetaData> fields = (Map<org.apache.thrift.TFieldIdEnum, FieldMetaData>) field
            .get(entity);//from   w w w .j av a  2s . c  om

    for (Entry<TFieldIdEnum, FieldMetaData> f : fields.entrySet()) {
        Object value = map.get(f.getKey().getFieldName());
        if (value != null) {
            ThriftTypes type = ThriftTypes.values()[f.getValue().valueMetaData.type];

            switch (type) {
            case VOID:
                break;
            case BYTE:
            case BOOL:
            case DOUBLE:
            case I16:
            case I32:
            case I64:
            case STRING:
                try {
                    entity.setFieldValue(f.getKey(), valueForBasicType(value, f.getValue().valueMetaData.type));
                } catch (ClassCastException e) {
                    if (e.getMessage().contains(ByteBuffer.class.getCanonicalName())) {
                        entity.setFieldValue(f.getKey(), ByteBuffer.wrap(Base64.decodeBase64((String) value)));
                    } else {
                        throw e;
                    }
                }
                break;
            case ENUM: {
                org.apache.thrift.meta_data.EnumMetaData meta = (org.apache.thrift.meta_data.EnumMetaData) f
                        .getValue().valueMetaData;
                Object e = meta.enumClass;
                entity.setFieldValue(f.getKey(), Enum.valueOf((Class<Enum>) e, (String) value));
                break;
            }
            case MAP: {
                org.apache.thrift.meta_data.MapMetaData meta = (org.apache.thrift.meta_data.MapMetaData) f
                        .getValue().valueMetaData;
                if (!meta.keyMetaData.isStruct() && !meta.keyMetaData.isContainer()) {
                    Map<Object, Object> childMap = (Map<Object, Object>) value;
                    Map<Object, Object> childEntityMap = Maps.newHashMap();
                    entity.setFieldValue(f.getKey(), childEntityMap);

                    if (!meta.keyMetaData.isStruct() && !meta.keyMetaData.isContainer()) {
                        for (Entry<Object, Object> entry : childMap.entrySet()) {
                            Object childKey = valueForBasicType(entry.getKey(), meta.keyMetaData.type);
                            Object childValue = valueForBasicType(entry.getValue(), meta.valueMetaData.type);
                            childEntityMap.put(childKey, childValue);
                        }
                    }
                } else {
                    LOG.error(String.format("Unable to serializer field '%s' key type '%s' not supported",
                            f.getKey().getFieldName(), meta.keyMetaData.getTypedefName()));
                }
                break;
            }
            case LIST: {
                Map<String, Object> childMap = (Map<String, Object>) value;
                org.apache.thrift.meta_data.ListMetaData listMeta = (org.apache.thrift.meta_data.ListMetaData) f
                        .getValue().valueMetaData;

                // Create an empty list and attach to the parent entity
                List<Object> childList = Lists.newArrayList();
                entity.setFieldValue(f.getKey(), childList);

                if (listMeta.elemMetaData instanceof org.apache.thrift.meta_data.StructMetaData) {
                    org.apache.thrift.meta_data.StructMetaData structMeta = (org.apache.thrift.meta_data.StructMetaData) listMeta.elemMetaData;
                    for (Entry<String, Object> childElement : childMap.entrySet()) {
                        org.apache.thrift.TBase childEntity = structMeta.structClass.newInstance();
                        populateObject(childEntity, (Map<String, Object>) childElement.getValue());
                        childList.add(childEntity);
                    }
                }
                break;
            }
            case STRUCT: {
                break;
            }
            case SET:
            default:
                LOG.error("Unhandled value : " + f.getKey().getFieldName() + " " + type);
                break;
            }
        }
    }
    return entity;
}

From source file:com.cinchapi.concourse.lang.Parser.java

/**
 * Go through a list of symbols and group the expressions together in a
 * {@link Expression} object./*from www  .  j av  a 2 s  .c o m*/
 * 
 * @param symbols
 * @return the expression
 */
protected static List<Symbol> groupExpressions(List<Symbol> symbols) { // visible
                                                                       // for
                                                                       // testing
    try {
        List<Symbol> grouped = Lists.newArrayList();
        ListIterator<Symbol> it = symbols.listIterator();
        while (it.hasNext()) {
            Symbol symbol = it.next();
            if (symbol instanceof KeySymbol) {
                // NOTE: We are assuming that the list of symbols is well
                // formed, and, as such, the next elements will be an
                // operator and one or more symbols. If this is not the
                // case, this method will throw a ClassCastException
                OperatorSymbol operator = (OperatorSymbol) it.next();
                ValueSymbol value = (ValueSymbol) it.next();
                Expression expression;
                if (operator.getOperator() == Operator.BETWEEN) {
                    ValueSymbol value2 = (ValueSymbol) it.next();
                    expression = Expression.create((KeySymbol) symbol, operator, value, value2);
                } else {
                    expression = Expression.create((KeySymbol) symbol, operator, value);
                }
                grouped.add(expression);
            } else if (symbol instanceof TimestampSymbol) { // Add the
                                                            // timestamp to the
                                                            // previously
                                                            // generated
                                                            // Expression
                ((Expression) Iterables.getLast(grouped)).setTimestamp((TimestampSymbol) symbol);
            } else {
                grouped.add(symbol);
            }
        }
        return grouped;
    } catch (ClassCastException e) {
        throw new SyntaxException(e.getMessage());
    }
}

From source file:org.filteredpush.qc.sciname.services.GBIFService.java

public static NameUsage parseNameUsageFromJSON(String targetName, String json) {
    JSONParser parser = new JSONParser();

    try {//  w w w . j a  v a 2  s .  co  m
        JSONArray array = new JSONArray();
        try {
            JSONObject o = (JSONObject) parser.parse(json);
            if (o.get("results") != null) {
                array = (JSONArray) o.get("results");
            } else {
                // array = (JSONArray)parser.parse(json);
            }
        } catch (ClassCastException e) {
            logger.debug(e.getMessage(), e);
            array = (JSONArray) parser.parse(json);
        }

        Iterator<JSONObject> i = array.iterator();
        while (i.hasNext()) {
            JSONObject obj = i.next();
            // System.out.println(obj.toJSONString());
            NameUsage name = new NameUsage(obj);
            if (name.getCanonicalName().equals(targetName)) {
                return name;
            }
        }

    } catch (ParseException e) {
        logger.debug(e.getMessage(), e);
    }
    return null;
}

From source file:org.exoplatform.commons.notification.template.TemplateUtils.java

/**
 * Generate the Groovy Template//from   www .  j a va  2 s  .  c o m
 * @param context The template context
 * @param element The GroovyElemt
 * @param out The Writer to writer template
 * @return
 */
public static void loadGroovy(TemplateContext context, Element element, Writer out) {

    try {
        String groovyTemplate = element.getTemplate();
        if (groovyTemplate == null) {
            groovyTemplate = loadGroovyTemplate(element.getTemplateConfig().getTemplatePath());
            element.template(groovyTemplate);
        }
        if (groovyTemplate != null && groovyTemplate.length() > 0) {
            GroovyTemplate gTemplate = new GroovyTemplate(groovyTemplate);
            gTemplate.render(out, context);
        }
    } catch (ClassCastException e) {
        throw new IllegalArgumentException("The function only load groovy with GroovyElement type.");
    } catch (Exception e) {
        LOG.warn("Failed to load groovy template of plugin " + context.getPluginId() + "\n" + e.getMessage());
    }
}

From source file:com.discovery.darchrow.lang.ArrayUtil.java

/**
 * ?? {@link java.util.Iterator}.//w  w w.  j  a v  a2 s.com
 * <p>
 * ??,???with no copying<br>
 * ?, ClassCastException  ,Rats -- ,arrayList ?arrayList.iterator()
 * </p>
 * <p>
 * <b>:</b>{@link Arrays#asList(Object...)} list {@link Array}  ArrayList,
 * {@link java.util.AbstractList#add(int, Object)} ,<br>
 * listadd?, {@link java.lang.UnsupportedOperationException}
 * </p>
 * 
 * @param <T>
 *            the generic type
 * @param arrays
 *            ,? , 
 * @return if (null == arrays) return null;<br>
 *         ?arrays?Object[], {@link Arrays#asList(Object...)}?list,? {@link List#iterator()
 *         t}<br>
 *         ,? Object[],?, {@link Array#getLength(Object)}?, {@link Array#get(Object, int)} list
 * @see Arrays#asList(Object...)
 * @see Array#getLength(Object)
 * @see Array#get(Object, int)
 * @see List#iterator()
 */
@SuppressWarnings({ "unchecked" })
public static <T> Iterator<T> toIterator(Object arrays) {
    if (null == arrays) {
        return null;
    }
    List<T> list = null;
    try {
        // ??,???with no copying
        Object[] objArrays = (Object[]) arrays;
        list = (List<T>) toList(objArrays);
    } catch (ClassCastException e) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("arrays can not cast to Object[],maybe primitive type,values is:{},{}", arrays,
                    e.getMessage());
        }
        // Rats -- 
        int length = Array.getLength(arrays);
        list = new ArrayList<T>(length);
        for (int i = 0; i < length; ++i) {
            Object object = Array.get(arrays, i);
            list.add((T) object);
        }
    }
    return list.iterator();
}