Example usage for java.lang Enum valueOf

List of usage examples for java.lang Enum valueOf

Introduction

In this page you can find the example usage for java.lang Enum valueOf.

Prototype

public static <T extends Enum<T>> T valueOf(Class<T> enumType, String name) 

Source Link

Document

Returns the enum constant of the specified enum type with the specified name.

Usage

From source file:org.rhq.enterprise.gui.alert.ListAlertHistoryUIBean.java

private AlertPriority getAlertPriority() {
    String alertPriorityName = getAlertPriorityFilter();
    if (alertPriorityName != null) {
        return Enum.valueOf(AlertPriority.class, alertPriorityName);
    }/*w  w w .  j av a 2s.  c  om*/
    return null;
}

From source file:info.pancancer.arch3.persistence.PostgreSQL.java

public List<Job> getJobs(JobState status) {

    List<Job> jobs = new ArrayList<>();
    Map<Object, Map<String, Object>> map;
    if (status != null) {
        map = this.runSelectStatement("select * from job where status = ?", new KeyedHandler<>("job_uuid"),
                status.toString());// w  ww  .  j  a  v a2 s .  c  o  m
    } else {
        map = this.runSelectStatement("select * from job", new KeyedHandler<>("job_uuid"));
    }

    for (Entry<Object, Map<String, Object>> entry : map.entrySet()) {

        Job j = new Job();
        j.setState(Enum.valueOf(JobState.class, (String) entry.getValue().get("status")));
        j.setUuid((String) entry.getValue().get("job_uuid"));
        j.setWorkflow((String) entry.getValue().get("workflow"));
        j.setWorkflowVersion((String) entry.getValue().get("workflow_version"));
        j.setJobHash((String) entry.getValue().get("job_hash"));
        j.setStdout((String) entry.getValue().get("stdout"));
        j.setStderr((String) entry.getValue().get("stderr"));
        JSONObject iniJson = Utilities.parseJSONStr((String) entry.getValue().get("ini"));
        HashMap<String, String> ini = new HashMap<>();
        for (Object key : iniJson.keySet()) {
            ini.put((String) key, (String) iniJson.get(key));
        }
        j.setIni(ini);

        // timestamp
        Timestamp createTs = (Timestamp) entry.getValue().get("create_timestamp");
        Timestamp updateTs = (Timestamp) entry.getValue().get("update_timestamp");
        j.setCreateTs(createTs);
        j.setUpdateTs(updateTs);

        jobs.add(j);

    }

    return jobs;
}

From source file:com.dumontierlab.pdb2rdf.Pdb2Rdf.java

private static void load(CommandLine cmd, final Map<String, Double> stats) {
    String username = "dba";
    String password = "dba";
    String host = "localhost";
    int port = 1111;
    DetailLevel detailLevel = null;//  w  ww  .ja v  a 2 s  . c  om
    if (cmd.hasOption("detailLevel")) {
        try {
            detailLevel = Enum.valueOf(DetailLevel.class, cmd.getOptionValue("detailLevel"));
        } catch (IllegalArgumentException e) {
            LOG.fatal("Invalid argument value for detailLevel option", e);
            System.exit(1);
        }
    }
    final DetailLevel f_detailLevel = detailLevel;

    if (cmd.hasOption("username")) {
        username = cmd.getOptionValue("username");
    }
    if (cmd.hasOption("password")) {
        password = cmd.getOptionValue("password");
    }
    if (cmd.hasOption("host")) {
        host = cmd.getOptionValue("host");
    }
    if (cmd.hasOption("port")) {
        try {
            port = Integer.parseInt(cmd.getOptionValue("port"));
        } catch (NumberFormatException e) {
            LOG.fatal("Invalid port number: " + cmd.getOptionValue("port"));
            System.exit(1);
        }
    }

    final VirtuosoDaoFactory factory = new VirtuosoDaoFactory(host, port, username, password);
    ExecutorService pool = getThreadPool(cmd);

    final ProgressMonitor monitor = getProgressMonitor();
    final Pdb2RdfInputIterator i = processInput(cmd);
    final int inputSize = i.size();
    final AtomicInteger progressCount = new AtomicInteger();

    if (monitor != null) {
        monitor.setProgress(0, inputSize);
    }

    while (i.hasNext()) {
        final InputSource input = i.next();
        pool.execute(new Runnable() {
            public void run() {
                PdbXmlParser parser = new PdbXmlParser();
                UriBuilder uriBuilder = new UriBuilder();
                PdbRdfModel model = null;
                try {
                    model = new VirtPdbRdfModel(factory, Bio2RdfPdbUriPattern.PDB_GRAPH, uriBuilder,
                            factory.getTripleStoreDao());
                    if (f_detailLevel != null) {
                        parser.parse(input, model, f_detailLevel);
                    } else {
                        parser.parse(input, model);
                    }
                    if (stats != null) {
                        updateStats(stats, model);
                    }
                    if (monitor != null) {
                        monitor.setProgress(progressCount.incrementAndGet(), inputSize);
                    }

                } catch (Exception e) {
                    LOG.error("Uanble to parse input for pdb=" + (model != null ? model.getPdbId() : "null"),
                            e);
                }
            }
        });
    }
    pool.shutdown();
    while (!pool.isTerminated()) {
        try {
            pool.awaitTermination(1, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            break;
        }
    }
}

From source file:com.sf.ddao.orm.RSMapperFactoryRegistry.java

public static RowMapperFactory getScalarRowMapperFactory(final Type itemType, final String name, boolean req) {
    if (itemType == String.class) {
        return new ScalarRMF() {
            public Object map(ResultSet rs) throws SQLException {
                return rs.getString(name);
            }//w ww  . ja  va  2s.  c o  m
        };
    }
    if (itemType == Integer.class || itemType == Integer.TYPE) {
        return new ScalarRMF() {
            public Object map(ResultSet rs) throws SQLException {
                return rs.getInt(name);
            }
        };
    }
    if (itemType == URL.class) {
        return new ScalarRMF() {
            public Object map(ResultSet rs) throws SQLException {
                return rs.getURL(name);
            }
        };
    }
    if (itemType == BigInteger.class) {
        return new ScalarRMF() {
            public Object map(ResultSet rs) throws SQLException {
                final BigDecimal res = rs.getBigDecimal(name);
                return res == null ? null : res.toBigInteger();
            }
        };
    }
    if (itemType == BigDecimal.class) {
        return new ScalarRMF() {
            public Object map(ResultSet rs) throws SQLException {
                return rs.getBigDecimal(name);
            }
        };
    }
    if (itemType == InputStream.class) {
        return new ScalarRMF() {
            public Object map(ResultSet rs) throws SQLException {
                return rs.getBinaryStream(name);
            }
        };
    }
    if (itemType == Boolean.class || itemType == Boolean.TYPE) {
        return new ScalarRMF() {
            public Object map(ResultSet rs) throws SQLException {
                return rs.getBoolean(name);
            }
        };
    }
    if (itemType == Blob.class) {
        return new ScalarRMF() {
            public Object map(ResultSet rs) throws SQLException {
                return rs.getBlob(name);
            }
        };
    }
    if (itemType == java.sql.Date.class || itemType == java.util.Date.class) {
        return new ScalarRMF() {
            public Object map(ResultSet rs) throws SQLException {
                return rs.getTimestamp(name);
            }
        };
    }
    if (itemType instanceof Class) {
        final Class itemClass = (Class) itemType;
        final ColumnMapper columnMapper = ColumnMapperRegistry.lookup(itemClass);
        if (columnMapper != null) {
            return new ScalarRMF() {
                public Object map(ResultSet rs) throws SQLException {
                    return columnMapper.map(rs, name);
                }
            };
        }
        final Converter converter = ConvertUtils.lookup(itemClass);
        if (converter != null) {
            return new ScalarRMF() {
                public Object map(ResultSet rs) throws SQLException {
                    String s = rs.getString(name);
                    if (s == null) {
                        return null;
                    }
                    return converter.convert(itemClass, s);
                }
            };
        }
        if (Enum.class.isAssignableFrom((Class<?>) itemType)) {
            return new ScalarRMF() {
                public Object map(ResultSet rs) throws SQLException {
                    String s = rs.getString(name);
                    if (s == null) {
                        return null;
                    }
                    //noinspection unchecked
                    return Enum.valueOf((Class<Enum>) itemType, s);
                }
            };
        }
    }
    if (req) {
        throw new IllegalArgumentException("no mapping defined for " + itemType);
    }
    return null;
}

From source file:gov.nih.nci.system.web.struts.action.CreateAction.java

public Object convertValue(Class klass, Object value) throws NumberFormatException, Exception {

    String fieldType = klass.getName();
    if (value == null)
        return null;

    Object convertedValue = null;
    try {/*w  w w  .j  a va  2  s  .  c  o  m*/
        if (fieldType.equals("java.lang.Long")) {
            convertedValue = new Long((String) value);
        } else if (fieldType.equals("java.lang.Integer")) {
            convertedValue = new Integer((String) value);
        } else if (fieldType.equals("java.lang.String")) {
            convertedValue = value;
        } else if (fieldType.equals("java.lang.Float")) {
            convertedValue = new Float((String) value);
        } else if (fieldType.equals("java.lang.Double")) {
            convertedValue = new Double((String) value);
        } else if (fieldType.equals("java.lang.Boolean")) {
            convertedValue = new Boolean((String) value);
        } else if (fieldType.equals("java.util.Date")) {
            SimpleDateFormat format = new SimpleDateFormat("MM-dd-yyyy");
            convertedValue = format.parse((String) value);
        } else if (fieldType.equals("java.net.URI")) {
            convertedValue = new URI((String) value);
        } else if (fieldType.equals("java.lang.Character")) {
            convertedValue = new Character(((String) value).charAt(0));
        } else if (klass.isEnum()) {
            Class enumKlass = Class.forName(fieldType);
            convertedValue = Enum.valueOf(enumKlass, (String) value);
        } else {
            throw new Exception("type mismatch - " + fieldType);
        }

    } catch (NumberFormatException e) {
        e.printStackTrace();
        log.error("ERROR : " + e.getMessage());
        throw e;
    } catch (Exception ex) {
        ex.printStackTrace();
        log.error("ERROR : " + ex.getMessage());
        throw ex;
    }
    return convertedValue;
}

From source file:com.fujitsu.dc.core.odata.DcExpressionParser.java

/**
 * processParentheses.//from   ww w.  j a v a2 s . c  o  m
 * @param tokens token
 * @return token
 */
public static List<Token> processParentheses(List<Token> tokens) {

    List<Token> rt = new ArrayList<Token>();

    for (int i = 0; i < tokens.size(); i++) {
        Token openToken = tokens.get(i);
        if (openToken.type == TokenType.OPENPAREN) {
            int afterParenIdx = i + 1;
            // is this a method call or any/all aggregate function?
            String methodName = null;
            String aggregateSource = null;
            String aggregateVariable = null;
            AggregateFunction aggregateFunction = AggregateFunction.none;
            int k = i - 1;
            while (k > 0 && tokens.get(k).type == TokenType.WHITESPACE) {
                k--;
            }
            if (k >= 0) {
                Token methodNameToken = tokens.get(k);
                if (methodNameToken.type == TokenType.WORD) {
                    if (methods.contains(methodNameToken.value)) {
                        methodName = methodNameToken.value;
                        // this isn't strictly correct. I think the parser has issues
                        // with sequences of WORD, WHITESPACE, WORD, etc. I'm not sure I've
                        // ever seen a token type of WHITESPACE producer by a lexer..
                    } else if (methodNameToken.value.endsWith("/any")
                            || methodNameToken.value.endsWith("/all")) {
                        aggregateSource = methodNameToken.value.substring(0,
                                methodNameToken.value.length() - TOKEN_SIZE_3);
                        aggregateFunction = Enum.valueOf(AggregateFunction.class,
                                methodNameToken.value.substring(methodNameToken.value.length() - TOKEN_SIZE_3));
                        // to get things rolling I'm going to lookahead and require a very strict
                        // sequence of tokens:
                        // i + 1 must be a WORD
                        // i + 2 must be a SYMBOL ':'
                        // or, for any, i + 1 can be CLOSEPAREN
                        int ni = i + 1;
                        Token ntoken = null;
                        if (ni < tokens.size()) {
                            ntoken = tokens.get(ni);
                        }
                        processParenthesesCheckToken(aggregateFunction, ntoken);
                        if (ntoken != null) {
                            if (ntoken.type == TokenType.WORD) {
                                aggregateVariable = ntoken.value;
                                ni += 1;
                                ntoken = null;
                                if (ni < tokens.size()) {
                                    ntoken = tokens.get(ni);
                                }
                                if (ntoken == null || ntoken.type != TokenType.SYMBOL
                                        || !ntoken.value.equals(":")) {
                                    String reason;
                                    if (ntoken == null) {
                                        reason = "eof";
                                    } else {
                                        reason = ntoken.toString();
                                    }
                                    throw new RuntimeException("expected ':', found: " + reason);
                                }
                                // now we can parse the predicate, starting after the ':'
                                afterParenIdx = ni + 1;
                            } else {
                                // any(), easiest to early out here
                                List<Token> tokensIncludingParens = tokens.subList(k, ni + 1);
                                CommonExpression any = Expression
                                        .any(Expression.simpleProperty(aggregateSource));

                                ExpressionToken et = new ExpressionToken(any, tokensIncludingParens);
                                rt.subList(rt.size() - (i - k), rt.size()).clear();
                                rt.add(et);
                                return rt;
                            }
                        }
                    }
                }
            }

            // find matching close paren
            int stack = 0;
            int start = i;
            List<CommonExpression> methodArguments = new ArrayList<CommonExpression>();
            for (int j = afterParenIdx; j < tokens.size(); j++) {
                Token closeToken = tokens.get(j);
                if (closeToken.type == TokenType.OPENPAREN) {
                    stack++;
                } else if (methodName != null && stack == 0 && closeToken.type == TokenType.SYMBOL
                        && closeToken.value.equals(",")) {
                    List<Token> tokensInsideComma = tokens.subList(start + 1, j);
                    CommonExpression expressionInsideComma = readExpression(tokensInsideComma);
                    methodArguments.add(expressionInsideComma);
                    start = j;
                } else if (closeToken.type == TokenType.CLOSEPAREN) {
                    if (stack > 0) {
                        stack--;
                        continue;
                    }
                    if (methodName != null) {
                        methodCall(tokens, rt, i, methodName, k, start, methodArguments, j);

                    } else if (aggregateVariable != null) {
                        List<Token> tokensIncludingParens = tokens.subList(k, j + 1);
                        List<Token> tokensInsideParens = tokens.subList(afterParenIdx, j);
                        CommonExpression expressionInsideParens = readExpression(tokensInsideParens);
                        if (!(expressionInsideParens instanceof BoolCommonExpression)) {
                            throw new RuntimeException("illegal any predicate");
                        }
                        CommonExpression any = Expression.aggregate(aggregateFunction,
                                Expression.simpleProperty(aggregateSource), aggregateVariable,
                                (BoolCommonExpression) expressionInsideParens);

                        ExpressionToken et = new ExpressionToken(any, tokensIncludingParens);
                        rt.subList(rt.size() - (i - k), rt.size()).clear();
                        rt.add(et);
                    } else {

                        List<Token> tokensIncludingParens = tokens.subList(i, j + 1);
                        List<Token> tokensInsideParens = tokens.subList(i + 1, j);
                        // paren expression: replace t ( t t t ) t with t et t
                        CommonExpression expressionInsideParens = readExpression(tokensInsideParens);
                        CommonExpression exp = null;
                        if (expressionInsideParens instanceof BoolCommonExpression) {
                            exp = Expression.boolParen(expressionInsideParens);
                        } else {
                            exp = Expression.paren(expressionInsideParens);
                        }

                        ExpressionToken et = new ExpressionToken(exp, tokensIncludingParens);
                        rt.add(et);
                    }

                    i = j;
                }
            }
        } else {
            rt.add(openToken);
        }
    }

    return rt;

}

From source file:com.hunchee.twist.gae.GaeUnmarshaller.java

private void doUnmarshall(Object destination, Transaction transaction, Entity entity) {
    //        Preconditions.checkNotNull(destination, "Destination object cannot be null");
    //        Preconditions.checkNotNull(entity, "Source entity cannot be null");
    assert validator.validate(destination) == true;

    Map<String, Object> props = entity.getProperties();
    Key key = entity.getKey();/*  www  . ja  va2  s .  co m*/
    String name = entity.getKey().getName();

    if (destination instanceof PrimitiveWrapper) {
        PrimitiveWrapper wrapper = (PrimitiveWrapper) destination;
        Object wrapped = wrapper.getValue();
        if (wrapped.getClass().isPrimitive() || wrapped.getClass().equals(String.class)
                || wrapped.getClass().equals(Integer.class) || wrapped.getClass().equals(Long.class)
                || wrapped.getClass().equals(Double.class) || wrapped.getClass().equals(Float.class)
                || wrapped.getClass().equals(Boolean.class)) {
            if (entity.getProperties().size() > 1) {
                LOG.warn(
                        "Unmarshalling entity with multiple properties into primitive type will be serialized");
                // TODO: Implement XStream serializer
                throw new RuntimeException(
                        "Serializing multiple properties into primitives not yet implemented");
            } else if (entity.getProperties().size() == 1) {
                String entityKey = entity.getProperties().keySet().iterator().next();
                wrapper.setValue(entity.getProperty(entityKey));
            }
        }
        return;
    } else if (destination instanceof Map) {
        Iterator<Map.Entry<String, Object>> it = entity.getProperties().entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, Object> entry = it.next();
            String entryKey = entry.getKey();
            Object entryVal = entry.getValue();
            if (entryVal instanceof EmbeddedEntity) {
                EmbeddedEntity ee = (EmbeddedEntity) entryVal;
                Object mapOrList = GaeMarshaller.getMapOrList(ee);
                ((Map) destination).put(entryKey, mapOrList);
            } else {
                ((Map) destination).put(entryKey, entryVal);
            }
        }
        ((Map) destination).put(Entity.KEY_RESERVED_PROPERTY, key.getName());
        return;
    }

    AnnotatedField parentKeyField = AnnotationUtil.getFieldWithAnnotation(GaeObjectStore.parent(), destination);
    if (parentKeyField != null) {
        if (parentKeyField.getFieldType().equals(Key.class)) {
            parentKeyField.setFieldValue(entity.getParent());
        } else {
            //                throw new RuntimeException("Only GAE Key can be used as @Ancestor");
        }
    }

    AnnotatedField ancestorKeyField = AnnotationUtil.getFieldWithAnnotation(GaeObjectStore.ancestor(),
            destination);
    if (ancestorKeyField != null) {
        if (ancestorKeyField.getFieldType().equals(Key.class)) {
            ancestorKeyField.setFieldValue(getAncestor(entity));
        } else {
            throw new RuntimeException("Only GAE Key can be used as @Ancestor");
        }
    }

    AnnotatedField idField = AnnotationUtil.getFieldWithAnnotation(GaeObjectStore.key(), destination);
    if (idField != null) {
        if (idField.getFieldType().equals(String.class)) {
            idField.setFieldValue(key.getName());
        } else if (idField.getFieldType().equals(Long.class)) {
            idField.setFieldValue(key.getId());
        } else if (idField.getFieldType().equals(long.class)) {
            idField.setFieldValue(key.getId());
        } else {
            throw new RuntimeException("Invalid key was retrieved with type " + idField.getFieldType());
        }
    }

    AnnotatedField kindField = AnnotationUtil.getFieldWithAnnotation(GaeObjectStore.kind(), destination);
    if (kindField != null) {
        if (kindField.getFieldType().equals(String.class)) {
            kindField.setFieldValue(entity.getKind());
        } else {
            throw new RuntimeException("Invalid @Kind field is found for " + destination.getClass().getName());
        }
    }

    AnnotatedField flatField = AnnotationUtil.getFieldWithAnnotation(Flat.class, destination);
    if (flatField != null) {
        if (flatField.getFieldType().equals(Map.class)) {
            Iterator<Map.Entry<String, Object>> it = props.entrySet().iterator();
            Map map = new LinkedHashMap();
            while (it.hasNext()) {
                Map.Entry<String, Object> entry = it.next();
                String fieldName = entry.getKey();
                Object fieldValue = entry.getValue();
                // TODO: How about when by change a Map key would be the same with the POJO field name
                // TODO: Fix this or do not allow that to happen!
                boolean ok = true;
                Field[] fields = destination.getClass().getDeclaredFields();
                for (Field field : list(fields)) {
                    if (field.getName().equals(fieldName)) {
                        ok = false;
                    }
                }
                if (ok) {
                    map.put(fieldName, fieldValue);
                }
            }
            Field field = flatField.getField();
            setFieldValue(field, destination, map);
        } else {
            throw new RuntimeException("Only java.util.Map should be used for @Flat fields");
        }

    }

    Iterator<Map.Entry<String, Object>> it = props.entrySet().iterator();
    Class<?> clazz = destination.getClass();
    List<Field> fields = list(clazz.getDeclaredFields());

    while (it.hasNext()) {
        Map.Entry<String, Object> entry = it.next();
        String fieldName = entry.getKey();
        Object fieldValue = entry.getValue();
        try {
            for (Field field : fields) {
                if (field.getName().equals(fieldName)) {
                    if (fieldValue == null) {
                        setFieldValue(field, destination, fieldValue);
                    } else if (fieldValue instanceof Key) { // child
                        try {
                            Entity e = store.getDatastoreService()
                                    .get((com.google.appengine.api.datastore.Key) fieldValue);
                            AnnotatedField annotatedField = AnnotationUtil
                                    .getFieldWithAnnotation(GaeObjectStore.child(), destination);
                            Object childInstance = store.createInstance(annotatedField.getFieldType());
                            unmarshall(childInstance, e);
                            setFieldValue(field, destination, childInstance);
                        } catch (EntityNotFoundException e) {
                            fieldValue = null;
                        }
                    } else if (fieldValue instanceof String || fieldValue instanceof Boolean
                            || fieldValue instanceof Number || fieldValue instanceof Blob) {
                        if (field.getName().equals(fieldName)) {
                            if (field.getType().isEnum()) {
                                setFieldValue(field, destination,
                                        Enum.valueOf((Class<Enum>) field.getType(), (String) fieldValue));
                            }
                            if (field.getType().equals(String.class)) {
                                setFieldValue(field, destination, String.valueOf(fieldValue));
                            } else if (field.getType().equals(Boolean.class)) {
                                setFieldValue(field, destination, (Boolean) fieldValue);
                            } else if (field.getType().equals(Long.class)) {
                                setFieldValue(field, destination, (Long) fieldValue);
                            } else if (field.getType().equals(Integer.class)) {
                                if (fieldValue.getClass().equals(Long.class)) {
                                    Long value = (Long) fieldValue;
                                    setFieldValue(field, destination, value.intValue());
                                } else {
                                    setFieldValue(field, destination, (Integer) fieldValue);
                                }
                            } else if (field.getType().equals(int.class)) {
                                if (fieldValue.getClass().equals(Long.class)
                                        || fieldValue.getClass().equals(long.class)) {
                                    Long value = (Long) fieldValue;
                                    setFieldValue(field, destination, value.intValue());
                                } else {
                                    setFieldValue(field, destination, ((Integer) fieldValue).intValue());
                                }
                            } else if (field.getType().equals(long.class)) {
                                if (fieldValue.getClass().equals(Integer.class)
                                        || fieldValue.getClass().equals(int.class)) {
                                    Integer value = (Integer) fieldValue;
                                    setFieldValue(field, destination, value.longValue());
                                } else {
                                    setFieldValue(field, destination, ((Long) fieldValue).longValue());
                                }
                            } else if (field.getType().equals(boolean.class)) {
                                setFieldValue(field, destination, ((Boolean) fieldValue).booleanValue());
                            } else if (field.getType().equals(byte.class)) {
                                if (fieldValue.getClass().equals(Blob.class)) {
                                    // TODO: Need to have a second look with this code
                                    Blob blob = (Blob) fieldValue;
                                    setFieldValue(field, destination, blob.getBytes()[0]);
                                }
                            } else if (field.getType().equals(byte[].class)) {
                                if (fieldValue.getClass().equals(Blob.class)) {
                                    Blob blob = (Blob) fieldValue;
                                    setFieldValue(field, destination, blob.getBytes());
                                }
                            } else if (field.getType().equals(Date.class)) {
                                if (fieldValue.getClass().equals(String.class)) {
                                    Date date = DateUtil.parseDate((String) fieldValue);
                                    setFieldValue(field, destination, date);
                                } else if (fieldValue.getClass().equals(Long.class)) {
                                    Date date = new Date((Long) fieldValue);
                                    setFieldValue(field, destination, date);
                                } else if (fieldValue.getClass().equals(Date.class)) {
                                    setFieldValue(field, destination, fieldValue);
                                } else {
                                    throw new RuntimeException(
                                            "Unable to unmarshall " + fieldValue.getClass().getName() + " to "
                                                    + field.getType().getName());
                                }
                            } else if (field.getType().equals(Blob.class)) {
                                if (fieldValue.getClass().equals(Blob.class)) {
                                    Blob blob = (Blob) fieldValue;
                                    setFieldValue(field, destination, blob);
                                }
                            }
                        }
                    } else if (fieldValue instanceof Blob) {
                        setFieldValue(field, destination, fieldValue);
                    } else if (fieldValue instanceof Text) {
                        Text textField = (Text) fieldValue;
                        setFieldValue(field, destination, textField.getValue());
                    } else if (fieldValue instanceof Date) {
                        setFieldValue(field, destination, fieldValue);
                    } else if (fieldValue instanceof User) {
                        setFieldValue(field, destination, fieldValue);
                    } else if (fieldValue instanceof EmbeddedEntity) { // List or Java  primitive types and standard types, Map or  POJO's
                        Class<?> fieldValueType = fieldValue.getClass();
                        EmbeddedEntity ee = (EmbeddedEntity) fieldValue;
                        Map<String, Object> map = ee.getProperties();
                        store.createInstance(fieldValueType);
                        if (field.getType().equals(List.class) || field.getType().equals(Map.class)) {
                            Object mapOrList = getMapOrList((EmbeddedEntity) fieldValue);
                            setFieldValue(field, destination, mapOrList);
                        } else { // Must be a POJO
                            Map<String, Object> getMap = getMapFromEmbeddedEntity((EmbeddedEntity) fieldValue);
                            Object pojo = Maps.fromMap(getMap, field.getType());
                            setFieldValue(field, destination, pojo);
                        }
                    } else if (fieldValue instanceof GeoPt) {
                        setFieldValue(field, destination, fieldValue);
                    } else if (fieldValue instanceof List) {
                        setFieldValue(field, destination, fieldValue);
                    } else if (fieldValue.getClass().isPrimitive()) {
                        throw new RuntimeException("Not yet implemented");
                    }
                }
            }
        } catch (ClassCastException e) {
            if (fieldName != null && fieldValue != null) {
                LOG.error("Exception while unmarshalling GAE Entity field name=" + fieldName + " type="
                        + fieldValue.getClass().getName() + " value=" + fieldValue);
            }
            throw e;
        }
    }
    AnnotatedField aliasField = AnnotationUtil.getFieldWithAnnotation(Alias.class, destination);
    if (aliasField != null) {
        Alias alias = aliasField.getField().getAnnotation(Alias.class);
        String fieldName = alias.field();
        Object value = props.get(fieldName);

        String actualField = aliasField.getFieldName();
        Object actualValue = props.get(actualField);

        if (value != null) {
            setFieldValue(aliasField.getField(), destination, value);
        } else {
            setFieldValue(aliasField.getField(), destination, actualValue);
        }
    }
}

From source file:org.chililog.server.workbench.workers.RepositoryRuntimeWorker.java

/**
 * Read/*from   w ww .j  a v a  2  s  .com*/
 * 
 * @throws Exception
 */
@SuppressWarnings("rawtypes")
@Override
public ApiResult processGet() throws Exception {
    try {
        UserBO user = this.getAuthenticatedUser();
        List<String> allowedRepositories = Arrays.asList(this.getAuthenticatedUserAllowedRepository());

        DB db = MongoConnection.getInstance().getConnection();
        Object responseContent = null;

        // Get info on all repositories
        // HTTP GET /api/repositories
        if (this.getUriPathParameters() == null || this.getUriPathParameters().length == 0) {
            Repository[] list = RepositoryService.getInstance().getRepositories();
            if (list != null && list.length > 0) {
                ArrayList<RepositoryStatusAO> aoList = new ArrayList<RepositoryStatusAO>();
                for (Repository repo : list) {
                    if (user.isSystemAdministrator()
                            || allowedRepositories.contains(repo.getRepoConfig().getName())) {
                        aoList.add(new RepositoryStatusAO(repo));
                    }
                }

                if (!aoList.isEmpty()) {
                    responseContent = aoList.toArray(new RepositoryStatusAO[] {});
                }
            }
        } else if (this.getUriPathParameters().length == 1) {
            // Get info on specified repository
            // HTTP GET /api/repositories/{id}
            String id = this.getUriPathParameters()[ID_URI_PATH_PARAMETER_INDEX];
            ObjectId objectId = parseDocumentObjectID(id);
            Repository repo = RepositoryService.getInstance().getRepository(objectId);
            if (user.isSystemAdministrator() || allowedRepositories.contains(repo.getRepoConfig().getName())) {
                responseContent = new RepositoryStatusAO(repo);
            } else {
                // Assume not found
                throw new ChiliLogException(Strings.REPOSITORY_NOT_FOUND_ERROR, id);
            }
        } else if (this.getUriPathParameters().length == 2) {
            // HTTP GET /api/repositories/{id}/entries?query_type=find
            // Get entries for a specific repository
            String id = this.getUriPathParameters()[ID_URI_PATH_PARAMETER_INDEX];
            ObjectId objectId = parseDocumentObjectID(id);
            Repository repo = RepositoryService.getInstance().getRepository(objectId);
            if (!user.isSystemAdministrator()
                    && !allowedRepositories.contains(repo.getRepoConfig().getName())) {
                // Assume not found
                throw new ChiliLogException(Strings.REPOSITORY_NOT_FOUND_ERROR, id);
            } else if (repo.getStatus() == Status.OFFLINE) {
                // Cannot search if repository is offline
                throw new ChiliLogException(Strings.REPOSITORY_OFFLINE_ERROR, id);
            }

            // Load criteria
            QueryType queryType = Enum.valueOf(QueryType.class,
                    this.getQueryStringOrHeaderValue(ENTRY_QUERY_TYPE_QUERYSTRING_PARAMETER_NAME,
                            ENTRY_QUERY_TYPE_HEADER_NAME, false).toUpperCase());
            RepositoryEntryListCriteria criteria = loadCriteria();

            // Convert to JSON ourselves because this is not a simple AO object.
            // mongoDB object JSON serialization required
            StringBuilder json = new StringBuilder();

            // Get controller and execute query
            RepositoryEntryController controller = RepositoryEntryController.getInstance(repo.getRepoConfig());
            if (queryType == QueryType.FIND) {
                ArrayList<DBObject> list = controller.executeFindQuery(db, criteria);

                if (list != null && !list.isEmpty()) {
                    MongoJsonSerializer.serialize(new BasicDBObject("find", list), json);
                }
            } else if (queryType == QueryType.COUNT) {
                int count = controller.executeCountQuery(db, criteria);
                MongoJsonSerializer.serialize(new BasicDBObject("count", count), json);
            } else if (queryType == QueryType.DISTINCT) {
                List l = controller.executeDistinctQuery(db, criteria);
                MongoJsonSerializer.serialize(new BasicDBObject("distinct", l), json);
            } else if (queryType == QueryType.GROUP) {
                DBObject groupObject = controller.executeGroupQuery(db, criteria);
                MongoJsonSerializer.serialize(new BasicDBObject("group", groupObject), json);
            } else {
                throw new OperationNotSupportedException("Unsupported query type: " + queryType.toString());
            }

            // If there is no json, skip this and a 204 No Content will be returned
            if (json.length() > 0) {
                responseContent = json.toString().getBytes(Worker.JSON_CHARSET);
                ApiResult result = new ApiResult(this.getAuthenticationToken(), JSON_CONTENT_TYPE,
                        responseContent);

                if (criteria.getDoPageCount()) {
                    result.getHeaders().put(PAGE_COUNT_HEADER, new Integer(criteria.getPageCount()).toString());
                }
                return result;
            }
        }

        // Return response
        return new ApiResult(this.getAuthenticationToken(), JSON_CONTENT_TYPE, responseContent);
    } catch (Exception ex) {
        return new ApiResult(HttpResponseStatus.BAD_REQUEST, ex);
    }
}

From source file:com.alliander.osgp.acceptancetests.configurationmanagement.GetConfigurationDataSteps.java

@DomainStep("the get configuration oslp message from the device contains (.*), (.*), (.*), (.*), (.*), (.*), (.*), (.*), (.*) and (.*)")
public void givenTheOslpResponse(final String lightType, final String dcLights, final String dcMap,
        final String rcType, final String rcMap, final String shortInterval, final String preferredLinkType,
        final String meterType, final String longInterval, final String longIntervalType) {

    LOGGER.info(/*from   w  w  w . j a  v a2  s  .  c  o  m*/
            "GIVEN: the get configuration oslp message from the device contains {}, {}, {}, {}, {}, {}, {}, {}, {} and {}.",
            new Object[] { lightType, dcLights, dcMap, rcType, rcMap, shortInterval, preferredLinkType,
                    meterType, longInterval, longIntervalType });

    Oslp.GetConfigurationResponse.Builder builder = Oslp.GetConfigurationResponse.newBuilder()
            .setStatus(Status.OK);

    if (StringUtils.isNotBlank(lightType)) {
        builder = builder.setLightType(StringUtils.isBlank(lightType) ? Oslp.LightType.LT_NOT_SET
                : Enum.valueOf(Oslp.LightType.class, lightType));
    }

    // Dali Configuration
    if (lightType.equals("DALI") && (StringUtils.isNotBlank(dcLights) || StringUtils.isNotBlank(dcMap))) {
        Oslp.DaliConfiguration.Builder dcBuilder = Oslp.DaliConfiguration.newBuilder();
        if (StringUtils.isNotBlank(dcLights)) {
            dcBuilder = dcBuilder.setNumberOfLights(OslpUtils.integerToByteString(Integer.parseInt(dcLights)));
        }
        if (StringUtils.isNotBlank(dcMap)) {
            for (final String i : dcMap.split(";")) {
                final String[] j = i.split(",");
                dcBuilder = dcBuilder.addAddressMap(Oslp.IndexAddressMap.newBuilder()
                        .setIndex(OslpUtils.integerToByteString(Integer.parseInt(j[0])))
                        .setAddress(OslpUtils.integerToByteString(Integer.parseInt(j[1])))
                        .setRelayType(Oslp.RelayType.LIGHT));
            }
        }
        builder = builder.setDaliConfiguration(dcBuilder);
    }

    // Relay Configuration
    if (lightType.equals("RELAY") && (StringUtils.isNotBlank(rcType) && StringUtils.isNotBlank(rcMap))) {
        Oslp.RelayConfiguration.Builder rcBuilder = Oslp.RelayConfiguration.newBuilder();
        for (final String i : rcMap.split(";")) {
            final String[] j = i.split(",");
            rcBuilder = rcBuilder.addAddressMap(Oslp.IndexAddressMap.newBuilder()
                    .setIndex(OslpUtils.integerToByteString(Integer.parseInt(j[0])))
                    .setAddress(OslpUtils.integerToByteString(Integer.parseInt(j[1])))
                    .setRelayType(Enum.valueOf(Oslp.RelayType.class, rcType)));
        }
        builder = builder.setRelayConfiguration(rcBuilder);
    } else {
        Oslp.RelayConfiguration.Builder rcBuilder = Oslp.RelayConfiguration.newBuilder();
        rcBuilder = rcBuilder
                .addAddressMap(Oslp.IndexAddressMap.newBuilder().setIndex(OslpUtils.integerToByteString(1))
                        .setAddress(OslpUtils.integerToByteString(1)).setRelayType(Oslp.RelayType.LIGHT));
        builder = builder.setRelayConfiguration(rcBuilder);
    }

    if (StringUtils.isNotBlank(shortInterval)) {
        builder = builder.setShortTermHistoryIntervalMinutes(Integer.parseInt(shortInterval.trim()));
    }

    if (StringUtils.isNotBlank(preferredLinkType)) {
        builder = builder.setPreferredLinkType(Enum.valueOf(Oslp.LinkType.class, preferredLinkType.trim()));
    }

    if (StringUtils.isNotBlank(meterType)) {
        builder = builder.setMeterType(Enum.valueOf(Oslp.MeterType.class, meterType.trim()));
    }

    if (StringUtils.isNotBlank(longInterval)) {
        builder = builder.setLongTermHistoryInterval(Integer.parseInt(longInterval.trim()));
    }

    if (StringUtils.isNotBlank(longIntervalType)) {
        builder = builder.setLongTermHistoryIntervalType(
                Enum.valueOf(Oslp.LongTermIntervalType.class, longIntervalType.trim()));
    }

    this.oslpResponse = OslpTestUtils.createOslpEnvelopeBuilder().withDeviceId(Base64.decodeBase64(DEVICE_UID))
            .withPayloadMessage(Message.newBuilder().setGetConfigurationResponse(builder).build()).build();

    this.oslpChannelHandler = OslpTestUtils.createOslpChannelHandlerWithResponse(this.oslpResponse,
            this.channelMock, this.device.getNetworkAddress());
    this.oslpChannelHandler.setDeviceRegistrationService(this.deviceRegistrationService);
    this.oslpDeviceService.setOslpChannelHandler(this.oslpChannelHandler);
}

From source file:org.seedstack.mqtt.internal.MqttPlugin.java

private void configureMqttClients() {
    String[] clients = mqttConfiguration.getStringArray(CONNECTION_CLIENTS);

    for (String clientName : clients) {
        LOGGER.debug("Configure new MqttClient [{}]", clientName);
        Configuration clientConfiguration = mqttConfiguration.subset(CONNECTION_CLIENT + "." + clientName);
        String uri = clientConfiguration.getString(BROKER_URI);
        String clientId = clientConfiguration.getString(MQTTCLIENT_ID);
        if (uri == null) {
            throw SeedException.createNew(MqttErrorCodes.MISCONFIGURED_MQTT_CLIENT).put("clients", clientName);
        }/*  w w  w  .j  a v a2 s.  com*/
        if (clientId == null) {
            clientId = MqttClient.generateClientId();
            LOGGER.debug("Generate new client id [{}] for client name [{}]", clientId, clientName);
        }

        MqttClientDefinition def = new MqttClientDefinition(uri, clientId);
        Configuration reconnectConfiguration = clientConfiguration.subset(RECONNECTION_PROPS);
        if (!reconnectConfiguration.isEmpty()) {
            try {
                String reconnection = reconnectConfiguration.getString(RECONNECTION_MODE);
                if (reconnection != null) {
                    MqttReconnectionMode mode = Enum.valueOf(MqttReconnectionMode.class, reconnection);
                    def.setReconnectionMode(mode);
                }
                String inter = reconnectConfiguration.getString(RECONNECTION_INTERVAL);
                if (inter != null) {
                    def.setReconnectionInterval(Integer.parseInt(inter));
                }
            } catch (Exception e) {
                throw SeedException.createNew(MqttErrorCodes.MISCONFIGURED_MQTT_RECONNECTION).put("values",
                        EnumSet.allOf(MqttReconnectionMode.class));
            }
        }
        MqttConnectOptionsDefinition connectOptionsDefinition = new MqttConnectOptionsDefinition(
                clientConfiguration.subset(MQTT_OPTIONS));
        def.setConnectOptionsDefinition(connectOptionsDefinition);

        // Check ThreadPool Configuration
        def.setPoolDefinition(new MqttPoolDefinition(clientConfiguration.subset(POOL_PROPS)));

        mqttClientDefinitions.put(clientName, def);
    }
}