Example usage for java.lang String getClass

List of usage examples for java.lang String getClass

Introduction

In this page you can find the example usage for java.lang String getClass.

Prototype

@HotSpotIntrinsicCandidate
public final native Class<?> getClass();

Source Link

Document

Returns the runtime class of this Object .

Usage

From source file:org.apache.torque.criteria.Criteria.java

/**
 * Returns the database table name associated with an alias.
 *
 * @param alias a <code>String</code> value.
 *
 * @return a <code>String</code> value, or null if the alias is not defined.
 *
 * @throws IllegalArgumentException if the alias with the name
 *         <code>alias</code> is defined but is no alias for a table name
 *         (e.g. it is an alias for a subselect).
 *//* ww  w. j a v a 2s.c o m*/
public String getTableForAlias(String alias) {
    Object aliasResolved = aliases.get(alias);
    if (aliasResolved == null) {
        return null;
    }
    if (aliasResolved instanceof String) {
        return (String) aliasResolved;
    }
    throw new IllegalArgumentException("The alias " + alias
            + " is not associated to a table but to an object of type " + alias.getClass().getName());
}

From source file:org.apache.torque.criteria.Criteria.java

/**
 * Returns the subselect associated with an alias.
 *
 * @param alias a <code>String</code> value.
 *
 * @return a <code>String</code> value, or null if the alias is not defined.
 *
 * @throws IllegalArgumentException if the alias with the name
 *         <code>alias</code> is defined but is not an alias for a subselect
 *         (e.g. it is an alias for a table).
 *//*from   w  w  w  .j  a  v  a2  s. c o  m*/
public Criteria getSubselectForAlias(String alias) {
    Object aliasResolved = aliases.get(alias);
    if (aliasResolved == null) {
        return null;
    }
    if (aliasResolved instanceof Criteria) {
        return (Criteria) aliasResolved;
    }
    throw new IllegalArgumentException("The alias " + alias
            + " is not associated to a subselect but to an object of type " + alias.getClass().getName());
}

From source file:org.openmrs.module.sync.api.db.hibernate.HibernateSyncInterceptor.java

/**
 * Processes changes to persistent collection that contains instances of OpenmrsObject objects.
 * <p>//from   ww  w . j  a  v a2  s  . c  om
 * Remarks:
 * <p>
 * Xml 'schema' for the sync item content for the persisted collection follows. Note that for persisted
 * collections syncItemKey is a composite of owner object uuid and the property name that contains the
 * collection. <br/>
 * &lt;persistent-collection&gt; element: wrapper element <br/>
 * &lt;owner uuid='' propertyName='' type='' action='recreate|update' &gt; element: this
 * captures the information about the object that holds reference to the collection being
 * processed <br/>
 * -uuid: owner object uuid <br/>
 * -properyName: names of the property on owner object that holds this collection <br/>
 * -type: owner class name <br/>
 * -action: recreate, update -- these are collection events defined by hibernate interceptor <br/>
 * &lt;entry action='update|delete' uuid='' type='' &gt; element: this captures info about
 * individual collection entries: <br/>
 * -action: what is being done to this item of the collection: delete (item was removed from the
 * collection) or update (item was added to the collection) <br/>
 * -uuid: entry's uuid <br/>
 * -type: class name
 *
 * @param collection Instance of Hibernate AbstractPersistentCollection to process.
 * @param key key of owner for the collection.
 * @param action action being performed on the collection: update, recreate
 */
private void processPersistentCollection(AbstractPersistentCollection collection, Serializable key,
        String action, String originalRecordUuid, OpenmrsObject owner, String ownerPropertyName) {

    LinkedHashMap<String, OpenmrsObject> entriesHolder = null;

    // Setup the serialization data structures to hold the state
    Package pkg = new Package();
    entriesHolder = new LinkedHashMap<String, OpenmrsObject>();
    try {

        CollectionMetadata collMD = getCollectionMetadata(owner.getClass(), ownerPropertyName,
                getSessionFactory());
        if (collMD == null) {
            throw new SyncException(
                    "Can't find a collection with " + ownerPropertyName + " in class " + owner.getClass());
        }

        Class<?> elementClass = collMD.getElementType().getReturnedClass();
        //If this is a simple type like Integer, serialization of the collection will be as below:
        //<org.openmrs.Cohort>
        //   <memberIds type="java.util.Set(org.openmrs.Cohort)">[2, 3]</memberIds>
        //  ............. and more
        //This should work just fine as long as there is a Normalizer registered for it
        if (!OpenmrsObject.class.isAssignableFrom(elementClass)
                && SyncUtil.getNormalizer(elementClass) != null) {

            //Check if there is already a NEW/UPDATE sync item for the owner
            SyncItem syncItem = new SyncItem();
            syncItem.setKey(new SyncItemKey<String>(owner.getUuid(), String.class));
            syncItem.setContainedType(owner.getClass());
            syncItem.setState(SyncItemState.UPDATED);

            boolean ownerHasSyncItem = getSyncRecord().hasSyncItem(syncItem);
            syncItem.setState(SyncItemState.NEW);
            if (!ownerHasSyncItem)
                ownerHasSyncItem = getSyncRecord().hasSyncItem(syncItem);

            if (!ownerHasSyncItem) {
                ClassMetadata cmd = getSessionFactory().getClassMetadata(owner.getClass());
                //create an UPDATE sync item for the owner so that the collection changes get recorded along
                Serializable primaryKeyValue = cmd.getIdentifier(owner,
                        (SessionImplementor) getSessionFactory().getCurrentSession());
                packageObject(owner, cmd.getPropertyValues(owner, EntityMode.POJO), cmd.getPropertyNames(),
                        cmd.getPropertyTypes(), primaryKeyValue, SyncItemState.UPDATED);
            } else {
                //There is already an UPDATE OR NEW SyncItem for the owner containing the above updates
            }

            return;
        }
        // find out what entries need to be serialized
        for (Object entry : (Iterable) collection) {
            if (entry instanceof OpenmrsObject) {
                OpenmrsObject obj = (OpenmrsObject) entry;

                // attempt to retrieve entry uuid
                String entryUuid = obj.getUuid();
                if (entryUuid == null) {
                    entryUuid = fetchUuid(obj);
                    if (log.isDebugEnabled()) {
                        log.debug("Entry uuid was null, attempted to fetch uuid with the following results");
                        log.debug("Entry type:" + obj.getClass().getName() + ",uuid:" + entryUuid);
                    }
                }
                // well, this is messed up: have an instance of
                // OpenmrsObject but has no uuid
                if (entryUuid == null) {
                    log.error("Cannot handle collection entries where uuid is null.");
                    throw new CallbackException("Cannot handle collection entries where uuid is null.");
                }

                // add it to the holder to avoid possible duplicates: key =
                // uuid + action
                entriesHolder.put(entryUuid + "|update", obj);
            } else {
                log.warn(
                        "Cannot handle collections where entries are not OpenmrsObject and have no Normalizers. Type was "
                                + entry.getClass() + " in property " + ownerPropertyName + " in class "
                                + owner.getClass());
                // skip out early because we don't want to write any xml for it
                // it was handled by the normal property writer hopefully
                return;
            }
        }

        // add on deletes
        if (!"recreate".equals(action) && collection.getRole() != null) {
            org.hibernate.persister.collection.CollectionPersister persister = ((org.hibernate.engine.SessionFactoryImplementor) getSessionFactory())
                    .getCollectionPersister(collection.getRole());
            Iterator it = collection.getDeletes(persister, false);
            if (it != null) {
                while (it.hasNext()) {
                    Object entryDelete = it.next();
                    if (entryDelete instanceof OpenmrsObject) {
                        OpenmrsObject objDelete = (OpenmrsObject) entryDelete;
                        // attempt to retrieve entry uuid
                        String entryDeleteUuid = objDelete.getUuid();
                        if (entryDeleteUuid == null) {
                            entryDeleteUuid = fetchUuid(objDelete);
                            if (log.isDebugEnabled()) {
                                log.debug(
                                        "Entry uuid was null, attempted to fetch uuid with the following results");
                                log.debug("Entry type:" + entryDeleteUuid.getClass().getName() + ",uuid:"
                                        + entryDeleteUuid);
                            }
                        }
                        // well, this is messed up: have an instance of
                        // OpenmrsObject but has no uuid
                        if (entryDeleteUuid == null) {
                            log.error("Cannot handle collection delete entries where uuid is null.");
                            throw new CallbackException(
                                    "Cannot handle collection delete entries where uuid is null.");
                        }

                        // add it to the holder to avoid possible
                        // duplicates: key = uuid + action
                        // also, only add if there is no update action for the same object: see SYNC-280
                        if (!entriesHolder.containsKey(entryDeleteUuid + "|update")) {
                            entriesHolder.put(entryDeleteUuid + "|delete", objDelete);
                        }

                    } else {
                        // TODO: more debug info
                        log.warn(
                                "Cannot handle collections where entries are not OpenmrsObject and have no Normalizers!");
                        // skip out early because we don't want to write any
                        // xml for it. it
                        // was handled by the normal property writer
                        // hopefully
                        return;
                    }
                }
            }
        }

        /*
         * Create SyncItem and store change in SyncRecord kept in
         * ThreadLocal. note: when making SyncItemKey, make it a composite
         * string of uuid + prop. name to avoid collisions with updates to
         * parent object or updates to more than one collection on same
         * owner
         */

        // Setup the serialization data structures to hold the state
        Record xml = pkg.createRecordForWrite(collection.getClass().getName());
        Item entityItem = xml.getRootItem();

        // serialize owner info: we will need type, prop name where collection
        // goes, and owner uuid
        Item item = xml.createItem(entityItem, "owner");
        item.setAttribute("type", this.getType(owner));
        item.setAttribute("properyName", ownerPropertyName);
        item.setAttribute("action", action);
        item.setAttribute("uuid", owner.getUuid());

        // build out the xml for the item content
        Boolean hasNoAutomaticPrimaryKey = null;
        String type = null;
        for (String entryKey : entriesHolder.keySet()) {
            OpenmrsObject entryObject = entriesHolder.get(entryKey);
            if (type == null) {
                type = this.getType(entryObject);
                hasNoAutomaticPrimaryKey = SyncUtil.hasNoAutomaticPrimaryKey(type);
            }

            Item temp = xml.createItem(entityItem, "entry");
            temp.setAttribute("type", type);
            temp.setAttribute("action", entryKey.substring(entryKey.indexOf('|') + 1));
            temp.setAttribute("uuid", entryObject.getUuid());
            if (hasNoAutomaticPrimaryKey) {
                temp.setAttribute("primaryKey", getSyncService().getPrimaryKey(entryObject));
            }
        }

        SyncItem syncItem = new SyncItem();
        syncItem.setKey(new SyncItemKey<String>(owner.getUuid() + "|" + ownerPropertyName, String.class));
        syncItem.setState(SyncItemState.UPDATED);
        syncItem.setContainedType(collection.getClass());
        syncItem.setContent(xml.toStringAsDocumentFragment());

        getSyncRecord().addOrRemoveAndAddItem(syncItem);
        getSyncRecord().addContainedClass(owner.getClass().getName());

        // do the original uuid dance, same as in packageObject
        if (getSyncRecord().getOriginalUuid() == null || "".equals(getSyncRecord().getOriginalUuid())) {
            getSyncRecord().setOriginalUuid(originalRecordUuid);
        }
    } catch (Exception ex) {
        log.error("Error processing Persistent collection, see callstack and inner expection", ex);
        throw new CallbackException(
                "Error processing Persistent collection, see callstack and inner expection.", ex);
    }
}

From source file:org.sakaiproject.search.elasticsearch.ElasticSearchIndexBuilder.java

/**
 * Extract properties from the {@link EntityContentProducer}
 * <p>//from w  ww .ja  va2 s .c om
 * The {@link EntityContentProducer#getCustomProperties(String)} method returns a map of different kind of elements.
 * To avoid casting and calls to {@code instanceof}, extractCustomProperties does all the work and returns a formated
 * map containing only {@link Collection<String>}.
 * </p>
 *
 * @param resourceName    affected resource
 * @param contentProducer producer providing properties for the given resource
 * @return a formated map of {@link Collection<String>}
 */
private Map<String, Collection<String>> extractCustomProperties(String resourceName,
        EntityContentProducer contentProducer) {
    Map<String, ?> m = contentProducer.getCustomProperties(resourceName);

    if (m == null)
        return Collections.emptyMap();

    Map<String, Collection<String>> properties = new HashMap<String, Collection<String>>(m.size());
    for (Map.Entry<String, ?> propertyEntry : m.entrySet()) {
        String propertyName = propertyEntry.getKey();
        Object propertyValue = propertyEntry.getValue();
        Collection<String> values;

        //Check for basic data type that could be provided by the EntityContentProducer
        //If the data type can't be defined, nothing is stored. The toString method could be called, but some values
        //could be not meant to be indexed.
        if (propertyValue instanceof String)
            values = Collections.singleton((String) propertyValue);
        else if (propertyValue instanceof String[])
            values = Arrays.asList((String[]) propertyValue);
        else if (propertyValue instanceof Collection)
            values = (Collection<String>) propertyValue;
        else {
            if (propertyValue != null)
                log.warn("Couldn't find what the value for '" + propertyName + "' was. It has been ignored. "
                        + propertyName.getClass());
            values = Collections.emptyList();
        }

        //If this property was already present there (this shouldn't happen, but if it does everything must be stored
        if (properties.containsKey(propertyName)) {
            log.warn("Two properties had a really similar name and were merged. This shouldn't happen! "
                    + propertyName);
            log.debug("Merged values '" + properties.get(propertyName) + "' with '" + values);
            values = new ArrayList<String>(values);
            values.addAll(properties.get(propertyName));
        }

        properties.put(propertyName, values);
    }

    return properties;
}

From source file:org.soybeanMilk.core.bean.DefaultGenericConverter.java

@SuppressWarnings("unchecked")
protected Object convertStringToType(String str, Type type) throws ConvertException {
    Object result = null;//  w  w  w.j ava2 s.c  o  m

    if (str == null || str.length() == 0) {
        if (SbmUtils.isPrimitive(type))
            throw new GenericConvertException("can not convert " + SbmUtils.toString(str)
                    + " to primitive type " + SbmUtils.toString(type));
        else
            return null;
    } else if (SbmUtils.isClassType(type)) {
        @SuppressWarnings("rawtypes")
        Class clazz = SbmUtils.narrowToClass(type);

        if (clazz.isEnum())
            result = Enum.valueOf(clazz, str);
        else
            result = converterNotFoundThrow(str.getClass(), type);
    } else if (type instanceof TypeVariable<?>) {
        result = convertObjectToType(str, reify(type));
    } else if (type instanceof WildcardType) {
        result = convertObjectToType(str, reify(type));
    } else if (type instanceof ParameterizedType) {
        result = converterNotFoundThrow(str.getClass(), type);
    } else if (type instanceof GenericArrayType) {
        result = converterNotFoundThrow(str.getClass(), type);
    } else
        result = converterNotFoundThrow(str.getClass(), type);

    return result;
}

From source file:org.enerj.apache.commons.beanutils.ConvertUtilsBean.java

/**
 * Remove all registered {@link Converter}s, and re-establish the
 * standard Converters.//w  w  w  .  ja  va 2s  . co  m
 */
public void deregister() {

    boolean booleanArray[] = new boolean[0];
    byte byteArray[] = new byte[0];
    char charArray[] = new char[0];
    double doubleArray[] = new double[0];
    float floatArray[] = new float[0];
    int intArray[] = new int[0];
    long longArray[] = new long[0];
    short shortArray[] = new short[0];
    String stringArray[] = new String[0];

    converters.clear();
    register(BigDecimal.class, new BigDecimalConverter());
    register(BigInteger.class, new BigIntegerConverter());
    register(Boolean.TYPE, new BooleanConverter(defaultBoolean));
    register(Boolean.class, new BooleanConverter(defaultBoolean));
    register(booleanArray.getClass(), new BooleanArrayConverter(booleanArray));
    register(Byte.TYPE, new ByteConverter(defaultByte));
    register(Byte.class, new ByteConverter(defaultByte));
    register(byteArray.getClass(), new ByteArrayConverter(byteArray));
    register(Character.TYPE, new CharacterConverter(defaultCharacter));
    register(Character.class, new CharacterConverter(defaultCharacter));
    register(charArray.getClass(), new CharacterArrayConverter(charArray));
    register(Class.class, new ClassConverter());
    register(Double.TYPE, new DoubleConverter(defaultDouble));
    register(Double.class, new DoubleConverter(defaultDouble));
    register(doubleArray.getClass(), new DoubleArrayConverter(doubleArray));
    register(Float.TYPE, new FloatConverter(defaultFloat));
    register(Float.class, new FloatConverter(defaultFloat));
    register(floatArray.getClass(), new FloatArrayConverter(floatArray));
    register(Integer.TYPE, new IntegerConverter(defaultInteger));
    register(Integer.class, new IntegerConverter(defaultInteger));
    register(intArray.getClass(), new IntegerArrayConverter(intArray));
    register(Long.TYPE, new LongConverter(defaultLong));
    register(Long.class, new LongConverter(defaultLong));
    register(longArray.getClass(), new LongArrayConverter(longArray));
    register(Short.TYPE, new ShortConverter(defaultShort));
    register(Short.class, new ShortConverter(defaultShort));
    register(shortArray.getClass(), new ShortArrayConverter(shortArray));
    register(String.class, new StringConverter());
    register(stringArray.getClass(), new StringArrayConverter(stringArray));
    register(Date.class, new SqlDateConverter());
    register(Time.class, new SqlTimeConverter());
    register(Timestamp.class, new SqlTimestampConverter());
    register(File.class, new FileConverter());
    register(URL.class, new URLConverter());

}

From source file:controllers.ModuleController.java

private static List<ModuleModel> getNextModules(String input) {
    // get all the supplied view models.
    List<ViewModel> suppliedViewModels = Lists.newArrayList();
    JsonNode inputJson = Json.parse(input);

    // convert json nodes to view models.
    if (inputJson != null && inputJson.isArray()) {
        suppliedViewModels = Lists/*from w w  w  .ja v  a  2 s  . c o  m*/
                .newArrayList(Iterators.transform(inputJson.getElements(), new Function<JsonNode, ViewModel>() {
                    @Override
                    @Nullable
                    public ViewModel apply(@Nullable JsonNode input) {
                        if (!input.isTextual()) {
                            return null;
                        }
                        return createViewModelQuietly(
                                fetchResource(UuidUtils.create(input.asText()), PersistentObject.class), null);

                    }
                }));
    } else if (inputJson != null && inputJson.isObject()) {
        suppliedViewModels.add(createViewModelQuietly(inputJson, null));
    }

    suppliedViewModels = Lists.newArrayList(Iterables.filter(suppliedViewModels, Predicates.notNull()));

    // get all the modules that can use these inputs.
    Map<Module, Double> nullModulesMap = Maps.newHashMap();
    Map<Module, Double> modulesMap = Maps.newHashMap();
    Reflections reflections = new Reflections("controllers.modules", Play.application().classloader());
    for (Class<? extends Module> moduleClass : reflections.getSubTypesOf(Module.class)) {
        // we're not interested in abstract classes.
        if (Modifier.isAbstract(moduleClass.getModifiers())) {
            continue;
        }

        // get the Module.Requires/Requireses annotation for each module class.
        // the requirements within each Module.Require are ANDed.
        // the requirements across multiple Module.Require annotations are ORed.
        List<Module.Requires> requireds = Lists.newArrayList();
        if (moduleClass.isAnnotationPresent(Module.Requires.class)) {
            requireds.add(moduleClass.getAnnotation(Module.Requires.class));
        }
        if (moduleClass.isAnnotationPresent(Module.Requireses.class)) {
            Collections.addAll(requireds, moduleClass.getAnnotation(Module.Requireses.class).value());
        }

        if (requireds.size() == 0) {
            requireds.add(null);
        }

        for (Module.Requires required : requireds) {
            final Set<Class<? extends ViewModel>> requiredViewModelClasses = Sets.newHashSet();
            if (required != null) {
                Collections.addAll(requiredViewModelClasses, required.value());
            }

            // get all the supplied view modules that are relevant to this module.
            List<ViewModel> usefulViewModels = Lists
                    .newArrayList(Iterables.filter(suppliedViewModels, new Predicate<ViewModel>() {
                        @Override
                        public boolean apply(@Nullable ViewModel input) {
                            // if this class is required, then return true.
                            if (requiredViewModelClasses.contains(input.getClass())) {
                                return true;
                            }

                            // if any of its super classes are required, that also works.
                            for (Class<?> superClass : ClassUtils.getAllSuperclasses(input.getClass())) {
                                if (requiredViewModelClasses.contains(superClass)) {
                                    return true;
                                }
                            }

                            return false;
                        }
                    }));

            // if all the requirements were satisfied.
            if (usefulViewModels.size() >= requiredViewModelClasses.size()) {
                // try to create an instance of the module.
                Module module = null;
                try {
                    module = moduleClass.newInstance();
                    module.setViewModels(usefulViewModels);
                } catch (InstantiationException | IllegalAccessException | IllegalArgumentException e) {
                    module = null;
                } finally {
                    // if no module was created, just ignore.
                    if (module == null) {
                        continue;
                    }
                }

                // let's not divide by zero!
                double relevancyScore = suppliedViewModels.size() != 0
                        ? usefulViewModels.size() / (double) suppliedViewModels.size()
                        : 1.0;

                // keep null modules separate.
                Map<Module, Double> targetModulesMap = null;
                if (requiredViewModelClasses.size() > 0) {
                    // if a module of this type does not exist, add it.
                    if (Maps.filterKeys(modulesMap, Predicates.instanceOf(moduleClass)).size() == 0) {
                        targetModulesMap = modulesMap;
                    }
                } else {
                    targetModulesMap = nullModulesMap;
                }
                if (targetModulesMap != null) {
                    targetModulesMap.put(module, relevancyScore);
                }
            }
        }
    }

    // use null modules only if there are no regular ones.
    if (modulesMap.size() == 0) {
        modulesMap = nullModulesMap;
    }

    // convert to view models.
    Set<ModuleModel> moduleViewModels = Sets.newHashSet(
            Iterables.transform(modulesMap.entrySet(), new Function<Entry<Module, Double>, ModuleModel>() {
                @Override
                @Nullable
                public ModuleModel apply(@Nullable Entry<Module, Double> input) {
                    return new ModuleModel(input.getKey()).setRelevancyScore(input.getValue());
                }
            }));

    // order first by relevance and then by name.
    return Ordering.from(new Comparator<ModuleModel>() {
        @Override
        public int compare(ModuleModel o1, ModuleModel o2) {
            int relDiff = (int) Math.round((o2.relevancyScore - o1.relevancyScore) * 1000);
            if (relDiff == 0) {
                return o1.name.compareTo(o2.name);
            }

            return relDiff;
        }
    }).sortedCopy(moduleViewModels);
}

From source file:org.sakaiproject.search.elasticsearch.BaseElasticSearchIndexBuilder.java

/**
 * Extract properties from the given {@link EntityContentProducer}
 * <p>//from   ww  w  .  ja  v a2 s  .c om
 * The {@link EntityContentProducer#getCustomProperties(String)} method returns a map of different kind of elements.
 * To avoid casting and calls to {@code instanceof}, extractCustomProperties does all the work and returns a formated
 * map containing only {@link Collection<String>}.
 * </p>
 *
 * @param resourceName    affected resource
 * @param contentProducer producer providing properties for the given resource
 * @return a formated map of {@link Collection<String>}
 */
protected Map<String, Collection<String>> extractCustomProperties(String resourceName,
        EntityContentProducer contentProducer) {
    Map<String, ?> m = contentProducer.getCustomProperties(resourceName);

    if (m == null)
        return Collections.emptyMap();

    Map<String, Collection<String>> properties = new HashMap<String, Collection<String>>(m.size());
    for (Map.Entry<String, ?> propertyEntry : m.entrySet()) {
        String propertyName = propertyEntry.getKey();
        Object propertyValue = propertyEntry.getValue();
        Collection<String> values;

        //Check for basic data type that could be provided by the EntityContentProducer
        //If the data type can't be defined, nothing is stored. The toString method could be called, but some values
        //could be not meant to be indexed.
        if (propertyValue instanceof String)
            values = Collections.singleton((String) propertyValue);
        else if (propertyValue instanceof String[])
            values = Arrays.asList((String[]) propertyValue);
        else if (propertyValue instanceof Collection)
            values = (Collection<String>) propertyValue;
        else {
            if (propertyValue != null)
                getLog().warn("Couldn't find what the value for '" + propertyName
                        + "' was. It has been ignored. " + propertyName.getClass());
            values = Collections.emptyList();
        }

        //If this property was already present there (this shouldn't happen, but if it does everything must be stored
        if (properties.containsKey(propertyName)) {
            getLog().warn("Two properties had a really similar name and were merged. This shouldn't happen! "
                    + propertyName);
            getLog().debug("Merged values '" + properties.get(propertyName) + "' with '" + values);
            values = new ArrayList<String>(values);
            values.addAll(properties.get(propertyName));
        }

        properties.put(propertyName, values);
    }

    return properties;
}

From source file:org.appverse.web.framework.backend.frontfacade.rest.authentication.filter.JWSAuthenticationProcessFilterTest.java

@Test
public void testJWSAuthenticationFilterHeaderWithContent() throws Exception {
    //some content and specific url
    final String content = "{\n" + "\t\"id\": \"0001\",\n" + "\t\"type\": \"donut\",\n"
            + "\t\"name\": \"Cake\",\n" + "\t\"image\":\n" + "\t\t{\n" + "\t\t\t\"url\": \"images/0001.jpg\",\n"
            + "\t\t\t\"width\": 200,\n" + "\t\t\t\"height\": 200\n" + "\t\t},\n" + "\t\"thumbnail\":\n"
            + "\t\t{\n" + "\t\t\t\"url\": \"images/thumbnails/0001.jpg\",\n" + "\t\t\t\"width\": 32,\n"
            + "\t\t\t\"height\": 32\n" + "\t\t}\n" + "}";
    String requestURL = "http://localhost:8080";

    //prepare client
    ServletInputStream someContent = new DelegatingServletInputStream(
            new ByteArrayInputStream(content.getBytes()));
    KeyStore keyStore = getKeyStoreClient();
    Key key = keyStore.getKey(clientCertAlias, clientCertPassword.toCharArray());
    JWSJerseyFilter jwsJerseyFilter = new JWSJerseyFilter();

    //environment
    ArgumentCaptor<String> argumentHeader = ArgumentCaptor.forClass(String.class);
    ArgumentCaptor<String> argumentHeaderValue = ArgumentCaptor.forClass(String.class);
    when(context.getConfiguration()).thenReturn(config);
    when(config.getRuntimeType()).thenReturn(RuntimeType.CLIENT);
    when(context.getProperty(JWSJerseyFilter.JWS_FILTER_KEY)).thenReturn(key);
    when(context.getUri()).thenReturn(new URI(requestURL));
    when(context.getHeaders()).thenReturn(headers);
    when(context.getEntity()).thenReturn(content);
    doAnswer(new Answer<Void>() {
        @Override//  www.  j a  v a2s .c  o  m
        public Void answer(InvocationOnMock invocation) throws Throwable {
            Object[] arguments = invocation.getArguments();

            ((OutputStream) arguments[6]).write(content.getBytes());
            ((OutputStream) arguments[6]).flush();
            return null;
        }
    }).when(messageBodyWriter).writeTo(any(Object.class), any(Class.class), any(Type.class),
            any(Annotation[].class), any(MediaType.class), any(MultivaluedMap.class), any(OutputStream.class));

    /* TODO: Next sentence is not working because of jax.ws.rs version change, it needs to be reviewed 
    when(messageBodyWorkers.getMessageBodyWriter(any(Class.class), any(Type.class), any(Annotation[].class), any(MediaType.class))).thenReturn(messageBodyWriter);
    */
    jwsJerseyFilter.setWorkers(messageBodyWorkers);

    Type entity = content.getClass();
    when(context.getEntityClass()).thenReturn((Class) entity);

    //test client
    jwsJerseyFilter.filter(context);
    //validation client
    verify(headers, times(1)).add(argumentHeader.capture(), argumentHeaderValue.capture());
    String headerKey = argumentHeader.getValue();
    String headerValue = argumentHeaderValue.getValue();
    Assert.assertTrue("Response from client should contain token",
            headerValue.contains(JWSJerseyFilter.JWS_AUTHORIZATION_START_TOKEN));
    logger.info("Client Header Content: {}={}", headerKey, headerValue);

    //prepare server
    when(request.getHeader(headerKey)).thenReturn(headerValue);
    when(request.getInputStream()).thenReturn(someContent);
    when(request.getRequestURL()).thenReturn(new StringBuffer(requestURL));
    //test server
    myJWSFilter.doFilter(request, response, chain);

    //validation
    verify(chain, times(1)).doFilter(any(ServletRequest.class), any(ServletResponse.class));
    verify(response, times(0)).sendError(anyInt());//check sendError is not set

}

From source file:com.supremainc.biostar2.push.GcmBroadcastReceiver.java

@Override
public void onReceive(Context context, Intent intent) {
    if (BuildConfig.DEBUG) {
        Log.i(TAG, "========push receiver start =========");
    }/*from www .jav  a 2  s.  c  o m*/

    Bundle bundle = intent.getExtras();
    if (bundle == null) {
        setResultCode(Activity.RESULT_OK);
        return;
    }

    if (REGISTER_RESPONSE_ACTION.equals(intent.getAction())) {
        String registrationId = intent.getStringExtra("registration_id");
        Log.e(TAG, "registered:" + registrationId);
        if ((registrationId != null) && (registrationId.length() > 0)) {
            PreferenceUtil.putSharedPreference(context, "registrationId", registrationId);
        }
        PackageInfo packageInfo;
        try {
            packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            PreferenceUtil.putSharedPreference(context, "version", packageInfo.versionCode);
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }

        PushDataProvider pushDataProvider = PushDataProvider.getInstance(context);
        pushDataProvider.setNeedUpdateNotificationToken(registrationId);
        ComponentName comp = new ComponentName(context.getPackageName(), GcmIntentService.class.getName());
        startWakefulService(context, intent.setComponent(comp));
        setResultCode(Activity.RESULT_OK);
        if (BuildConfig.DEBUG) {
            Log.i(TAG, "========push receiver end =========");
        }
        return;
    }
    PushNotification noti = null;
    for (String key : bundle.keySet()) {
        String value;
        try {
            value = (String) bundle.get(key);
        } catch (Exception e) {
            Log.e(TAG, " " + e.getMessage());
            continue;
        }
        if (value == null) {
            continue;
        }
        if (key.equals("CMD") && value.equals("RST_FULL")) {
            if (BuildConfig.DEBUG) {
                Log.e(TAG, "RST_FULL");
            }
            int registeredVersion = PreferenceUtil.getIntSharedPreference(context, "version");
            if (registeredVersion > 0) {
                registeredVersion--;
            }
            PreferenceUtil.putSharedPreference(context, "version", registeredVersion);
            Intent intentBoradCast = new Intent(Setting.BROADCAST_PUSH_TOKEN_UPDATE);
            LocalBroadcastManager.getInstance(context).sendBroadcast(intentBoradCast);
            return;
        }
        String code = null;
        if (key.equals(NotificationType.DEVICE_REBOOT.mName)) {
            code = NotificationType.DEVICE_REBOOT.mName;
        } else if (key.equals(NotificationType.DEVICE_RS485_DISCONNECT.mName)) {
            code = NotificationType.DEVICE_RS485_DISCONNECT.mName;
        } else if (key.equals(NotificationType.DEVICE_TAMPERING.mName)) {
            code = NotificationType.DEVICE_TAMPERING.mName;
        } else if (key.equals(NotificationType.DOOR_FORCED_OPEN.mName)) {
            code = NotificationType.DOOR_FORCED_OPEN.mName;
        } else if (key.equals(NotificationType.DOOR_HELD_OPEN.mName)) {
            code = NotificationType.DOOR_HELD_OPEN.mName;
        } else if (key.equals(NotificationType.DOOR_OPEN_REQUEST.mName)) {
            code = NotificationType.DOOR_OPEN_REQUEST.mName;
        } else if (key.equals(NotificationType.ZONE_APB.mName)) {
            code = NotificationType.ZONE_APB.mName;
        } else if (key.equals(NotificationType.ZONE_FIRE.mName)) {
            code = NotificationType.ZONE_FIRE.mName;
        }
        if (code != null) {
            PushNotification tempNoti = NotificationBuild(value, code, context);
            if (tempNoti != null) {
                noti = tempNoti;
            }
        }

        if (BuildConfig.DEBUG) {
            Log.i(TAG, "|" + String.format("%s : %s (%s)", key, value.toString(), value.getClass().getName())
                    + "|");
        }
    }

    if (noti != null) {
        Notification(noti, context);
    }

    ComponentName comp = new ComponentName(context.getPackageName(), GcmIntentService.class.getName());
    startWakefulService(context, intent.setComponent(comp));
    setResultCode(Activity.RESULT_OK);
    if (BuildConfig.DEBUG) {
        Log.i(TAG, "========push receiver end =========");
    }
}