Example usage for java.lang.ref SoftReference get

List of usage examples for java.lang.ref SoftReference get

Introduction

In this page you can find the example usage for java.lang.ref SoftReference get.

Prototype

public T get() 

Source Link

Document

Returns this reference object's referent.

Usage

From source file:net.sf.jasperreports.engine.util.JRStyledTextParser.java

/**
 * Return a cached instance./*from w  w w  .  j a  va2 s.  c o m*/
 * 
 * @return a cached instance
 */
public static JRStyledTextParser getInstance() {
    JRStyledTextParser instance = null;
    SoftReference<JRStyledTextParser> instanceRef = threadInstances.get();
    if (instanceRef != null) {
        instance = instanceRef.get();
    }
    if (instance == null) {
        instance = new JRStyledTextParser();
        threadInstances.set(new SoftReference<JRStyledTextParser>(instance));
    }
    return instance;
}

From source file:ch.rasc.extclassgenerator.ModelGenerator.java

public static ModelBean createModel(final Class<?> clazz, final OutputConfig outputConfig) {

    Assert.notNull(clazz, "clazz must not be null");
    Assert.notNull(outputConfig.getIncludeValidation(), "includeValidation must not be null");

    ModelCacheKey key = new ModelCacheKey(clazz.getName(), outputConfig);
    SoftReference<ModelBean> modelReference = modelCache.get(key);
    if (modelReference != null && modelReference.get() != null) {
        return modelReference.get();
    }//from w w w  .  j a  va  2 s. c o  m

    Model modelAnnotation = clazz.getAnnotation(Model.class);

    final ModelBean model = new ModelBean();

    if (modelAnnotation != null && StringUtils.hasText(modelAnnotation.value())) {
        model.setName(modelAnnotation.value());
    } else {
        model.setName(clazz.getName());
    }

    if (modelAnnotation != null) {
        model.setAutodetectTypes(modelAnnotation.autodetectTypes());
    }

    if (modelAnnotation != null) {
        model.setExtend(modelAnnotation.extend());
        model.setIdProperty(modelAnnotation.idProperty());
        model.setVersionProperty(trimToNull(modelAnnotation.versionProperty()));
        model.setPaging(modelAnnotation.paging());
        model.setDisablePagingParameters(modelAnnotation.disablePagingParameters());
        model.setCreateMethod(trimToNull(modelAnnotation.createMethod()));
        model.setReadMethod(trimToNull(modelAnnotation.readMethod()));
        model.setUpdateMethod(trimToNull(modelAnnotation.updateMethod()));
        model.setDestroyMethod(trimToNull(modelAnnotation.destroyMethod()));
        model.setMessageProperty(trimToNull(modelAnnotation.messageProperty()));
        model.setWriter(trimToNull(modelAnnotation.writer()));
        model.setReader(trimToNull(modelAnnotation.reader()));
        model.setSuccessProperty(trimToNull(modelAnnotation.successProperty()));
        model.setTotalProperty(trimToNull(modelAnnotation.totalProperty()));
        model.setRootProperty(trimToNull(modelAnnotation.rootProperty()));
        model.setWriteAllFields(modelAnnotation.writeAllFields());
        model.setIdentifier(trimToNull(modelAnnotation.identifier()));
        String clientIdProperty = trimToNull(modelAnnotation.clientIdProperty());
        if (StringUtils.hasText(clientIdProperty)) {
            model.setClientIdProperty(clientIdProperty);
            model.setClientIdPropertyAddToWriter(true);
        } else {
            model.setClientIdProperty(null);
            model.setClientIdPropertyAddToWriter(false);
        }
    }

    final Set<String> hasReadMethod = new HashSet<String>();

    BeanInfo bi;
    try {
        bi = Introspector.getBeanInfo(clazz);
    } catch (IntrospectionException e) {
        throw new RuntimeException(e);
    }

    for (PropertyDescriptor pd : bi.getPropertyDescriptors()) {
        if (pd.getReadMethod() != null && pd.getReadMethod().getAnnotation(JsonIgnore.class) == null) {
            hasReadMethod.add(pd.getName());
        }
    }

    if (clazz.isInterface()) {
        final List<Method> methods = new ArrayList<Method>();

        ReflectionUtils.doWithMethods(clazz, new MethodCallback() {
            @Override
            public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
                methods.add(method);
            }
        });

        Collections.sort(methods, new Comparator<Method>() {
            @Override
            public int compare(Method o1, Method o2) {
                return o1.getName().compareTo(o2.getName());
            }
        });

        for (Method method : methods) {
            createModelBean(model, method, outputConfig);
        }
    } else {

        final Set<String> fields = new HashSet<String>();

        Set<ModelField> modelFieldsOnType = AnnotationUtils.getRepeatableAnnotation(clazz, ModelFields.class,
                ModelField.class);
        for (ModelField modelField : modelFieldsOnType) {
            if (StringUtils.hasText(modelField.value())) {
                ModelFieldBean modelFieldBean;

                if (StringUtils.hasText(modelField.customType())) {
                    modelFieldBean = new ModelFieldBean(modelField.value(), modelField.customType());
                } else {
                    modelFieldBean = new ModelFieldBean(modelField.value(), modelField.type());
                }

                updateModelFieldBean(modelFieldBean, modelField);
                model.addField(modelFieldBean);
            }
        }

        Set<ModelAssociation> modelAssociationsOnType = AnnotationUtils.getRepeatableAnnotation(clazz,
                ModelAssociations.class, ModelAssociation.class);
        for (ModelAssociation modelAssociationAnnotation : modelAssociationsOnType) {
            AbstractAssociation modelAssociation = AbstractAssociation
                    .createAssociation(modelAssociationAnnotation);
            if (modelAssociation != null) {
                model.addAssociation(modelAssociation);
            }
        }

        Set<ModelValidation> modelValidationsOnType = AnnotationUtils.getRepeatableAnnotation(clazz,
                ModelValidations.class, ModelValidation.class);
        for (ModelValidation modelValidationAnnotation : modelValidationsOnType) {
            AbstractValidation modelValidation = AbstractValidation.createValidation(
                    modelValidationAnnotation.propertyName(), modelValidationAnnotation,
                    outputConfig.getIncludeValidation());
            if (modelValidation != null) {
                model.addValidation(modelValidation);
            }
        }

        ReflectionUtils.doWithFields(clazz, new FieldCallback() {

            @Override
            public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
                if (!fields.contains(field.getName()) && (field.getAnnotation(ModelField.class) != null
                        || field.getAnnotation(ModelAssociation.class) != null
                        || (Modifier.isPublic(field.getModifiers()) || hasReadMethod.contains(field.getName()))
                                && field.getAnnotation(JsonIgnore.class) == null)) {

                    // ignore superclass declarations of fields already
                    // found in a subclass
                    fields.add(field.getName());
                    createModelBean(model, field, outputConfig);

                }
            }

        });
    }

    modelCache.put(key, new SoftReference<ModelBean>(model));
    return model;
}

From source file:ch.ralscha.extdirectspring.util.ApiCache.java

public String get(ApiCacheKey key) {
    if (key != null) {
        SoftReference<String> apiStringReference = cache.get(key);
        if (apiStringReference != null && apiStringReference.get() != null) {
            return apiStringReference.get();
        }//from  w  w  w  .java2 s  .c  o m
    }
    return null;
}

From source file:ch.rasc.extclassgenerator.ModelGenerator.java

public static String generateJavascript(ModelBean model, OutputConfig outputConfig) {

    if (!outputConfig.isDebug()) {
        JsCacheKey key = new JsCacheKey(model, outputConfig);

        SoftReference<String> jsReference = jsCache.get(key);
        if (jsReference != null && jsReference.get() != null) {
            return jsReference.get();
        }/*from w  w  w . ja  va2  s .c  o m*/
    }

    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(JsonGenerator.Feature.QUOTE_FIELD_NAMES, false);

    if (!outputConfig.isSurroundApiWithQuotes()) {
        if (outputConfig.getOutputFormat() == OutputFormat.EXTJS5) {
            mapper.addMixInAnnotations(ProxyObject.class, ProxyObjectWithoutApiQuotesExtJs5Mixin.class);
        } else {
            mapper.addMixInAnnotations(ProxyObject.class, ProxyObjectWithoutApiQuotesMixin.class);
        }
        mapper.addMixInAnnotations(ApiObject.class, ApiObjectMixin.class);
    } else {
        if (outputConfig.getOutputFormat() != OutputFormat.EXTJS5) {
            mapper.addMixInAnnotations(ProxyObject.class, ProxyObjectWithApiQuotesMixin.class);
        }
    }

    Map<String, Object> modelObject = new LinkedHashMap<String, Object>();
    modelObject.put("extend", model.getExtend());

    if (!model.getAssociations().isEmpty()) {
        Set<String> usesClasses = new HashSet<String>();
        for (AbstractAssociation association : model.getAssociations()) {
            usesClasses.add(association.getModel());
        }

        usesClasses.remove(model.getName());

        if (!usesClasses.isEmpty()) {
            modelObject.put("uses", usesClasses);
        }
    }

    Map<String, Object> configObject = new LinkedHashMap<String, Object>();
    ProxyObject proxyObject = new ProxyObject(model, outputConfig);

    Map<String, ModelFieldBean> fields = model.getFields();
    Set<String> requires = new HashSet<String>();

    if (!model.getValidations().isEmpty() && outputConfig.getOutputFormat() == OutputFormat.EXTJS5) {
        requires = addValidatorsToField(fields, model.getValidations());
    }

    if (proxyObject.hasContent() && outputConfig.getOutputFormat() == OutputFormat.EXTJS5) {
        requires.add("Ext.data.proxy.Direct");
    }

    if (StringUtils.hasText(model.getIdentifier()) && outputConfig.getOutputFormat() == OutputFormat.EXTJS5) {
        if ("sequential".equals(model.getIdentifier())) {
            requires.add("Ext.data.identifier.Sequential");
        } else if ("uuid".equals(model.getIdentifier())) {
            requires.add("Ext.data.identifier.Uuid");
        } else if ("negative".equals(model.getIdentifier())) {
            requires.add("Ext.data.identifier.Negative");
        }
    }

    if (requires != null && !requires.isEmpty()) {
        configObject.put("requires", requires);
    }

    if (StringUtils.hasText(model.getIdentifier())) {
        if (outputConfig.getOutputFormat() == OutputFormat.EXTJS5
                || outputConfig.getOutputFormat() == OutputFormat.TOUCH2) {
            configObject.put("identifier", model.getIdentifier());
        } else {
            configObject.put("idgen", model.getIdentifier());
        }
    }

    if (StringUtils.hasText(model.getIdProperty()) && !model.getIdProperty().equals("id")) {
        configObject.put("idProperty", model.getIdProperty());
    }

    if (outputConfig.getOutputFormat() == OutputFormat.EXTJS5
            && StringUtils.hasText(model.getVersionProperty())) {
        configObject.put("versionProperty", model.getVersionProperty());
    }

    if (StringUtils.hasText(model.getClientIdProperty())) {

        if (outputConfig.getOutputFormat() == OutputFormat.EXTJS5
                || outputConfig.getOutputFormat() == OutputFormat.EXTJS4) {
            configObject.put("clientIdProperty", model.getClientIdProperty());
        } else if (outputConfig.getOutputFormat() == OutputFormat.TOUCH2
                && !"clientId".equals(model.getClientIdProperty())) {
            configObject.put("clientIdProperty", model.getClientIdProperty());
        }
    }

    for (ModelFieldBean field : fields.values()) {
        field.updateTypes(outputConfig);
    }

    List<Object> fieldConfigObjects = new ArrayList<Object>();
    for (ModelFieldBean field : fields.values()) {
        if (field.hasOnlyName(outputConfig)) {
            fieldConfigObjects.add(field.getName());
        } else {
            fieldConfigObjects.add(field);
        }
    }
    configObject.put("fields", fieldConfigObjects);

    if (!model.getAssociations().isEmpty()) {
        configObject.put("associations", model.getAssociations());
    }

    if (!model.getValidations().isEmpty() && !(outputConfig.getOutputFormat() == OutputFormat.EXTJS5)) {
        configObject.put("validations", model.getValidations());
    }

    if (proxyObject.hasContent()) {
        configObject.put("proxy", proxyObject);
    }

    if (outputConfig.getOutputFormat() == OutputFormat.EXTJS4
            || outputConfig.getOutputFormat() == OutputFormat.EXTJS5) {
        modelObject.putAll(configObject);
    } else {
        modelObject.put("config", configObject);
    }

    StringBuilder sb = new StringBuilder();
    sb.append("Ext.define(\"").append(model.getName()).append("\",");
    if (outputConfig.isDebug()) {
        sb.append("\n");
    }

    String configObjectString;
    Class<?> jsonView = JsonViews.ExtJS4.class;
    if (outputConfig.getOutputFormat() == OutputFormat.TOUCH2) {
        jsonView = JsonViews.Touch2.class;
    } else if (outputConfig.getOutputFormat() == OutputFormat.EXTJS5) {
        jsonView = JsonViews.ExtJS5.class;
    }

    try {
        if (outputConfig.isDebug()) {
            configObjectString = mapper.writerWithDefaultPrettyPrinter().withView(jsonView)
                    .writeValueAsString(modelObject);
        } else {
            configObjectString = mapper.writerWithView(jsonView).writeValueAsString(modelObject);
        }

    } catch (JsonGenerationException e) {
        throw new RuntimeException(e);
    } catch (JsonMappingException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    sb.append(configObjectString);
    sb.append(");");

    String result = sb.toString();

    if (outputConfig.isUseSingleQuotes()) {
        result = result.replace('"', '\'');
    }

    if (!outputConfig.isDebug()) {
        jsCache.put(new JsCacheKey(model, outputConfig), new SoftReference<String>(result));
    }
    return result;
}

From source file:SoftHashMap.java

/**
 * Remove an object.//from  w  w w  .  j  av a2  s.c o m
 *
 * @param key the key
 * @return null or the old object
 */
public V remove(Object key) {
    processQueue();
    SoftReference<V> ref = map.remove(key);
    return ref == null ? null : ref.get();
}

From source file:SoftCache.java

public Object get(Object key) {
    SoftReference softRef = (SoftReference) map.get(key);

    if (softRef == null)
        return null;

    return softRef.get();
}

From source file:org.topazproject.xml.transform.MemoryCacheURLRetriever.java

/**
 * Lookup the <code>id</code> in the cache. If found, return results. Otherwise, call
 * delegate to fetch content.//  w w  w  .j  a  v  a  2s  .c o  m
 * 
 * @param url the url of the resource to retrieve
 * @param id  the id of the resource to retrieve
 * @return the contents, or null if not found
 * @throws IOException if an error occurred retrieving the contents (other than not-found)
 */
public synchronized byte[] retrieve(String url, String id) throws IOException {
    SoftReference ref = (SoftReference) cache.get(id);
    byte[] res = (ref != null) ? (byte[]) ref.get() : null;

    if (log.isDebugEnabled())
        log.debug("Memory cache('" + id + "'): "
                + (res != null ? "found" : ref != null ? "expired" : "not found"));

    if (res != null || delegate == null)
        return res;

    res = delegate.retrieve(url, id);
    if (res == null)
        return null;

    if (log.isDebugEnabled())
        log.debug("Caching '" + id + "'");

    cache.put(id, new SoftReference(res));
    return res;
}

From source file:SoftHashMap.java

public Object get(Object key) {
    Object res = null;/*from  w w  w.j a  v a2  s  . co m*/
    SoftReference sr = (SoftReference) hash.get(key);
    if (sr != null) {
        res = sr.get();
        if (res == null)
            hash.remove(key);
    }
    return res;
}

From source file:SoftCache.java

public Object remove(Object key) {
    SoftReference softRef = (SoftReference) map.remove(key);

    if (softRef == null)
        return null;

    Object oldValue = softRef.get();
    softRef.clear();/*from   w w  w  .  ja va 2 s  . co  m*/

    return oldValue;
}

From source file:com.eviware.soapui.security.log.FunctionalTestLogModel.java

public synchronized TestStepResult getTestStepResultAt(int index) {
    if (index >= results.size())
        return null;

    SoftReference<TestStepResult> result = results.get(index);
    return result == null ? null : result.get();
}