Example usage for java.lang Class toString

List of usage examples for java.lang Class toString

Introduction

In this page you can find the example usage for java.lang Class toString.

Prototype

public String toString() 

Source Link

Document

Converts the object to a string.

Usage

From source file:com.dngames.mobilewebcam.PhotoSettings.java

public static void GETSettings(Context context, String configtext, SharedPreferences prefs) {
    String[] settings = configtext.split("\n");

    Editor edit = prefs.edit();/*from  w w  w. j  av  a 2  s  . co  m*/
    Map<String, Object> all = new HashMap<String, Object>();

    for (Field f : PhotoSettings.class.getFields()) {
        {
            BooleanPref bp = f.getAnnotation(BooleanPref.class);
            if (bp != null) {
                all.put(bp.key(), bp.val());
                if (bp.night())
                    all.put(bp.key() + PhotoSettings.NIGHTPOSTFIX, bp.val());
            }
        }
        {
            StringPref sp = f.getAnnotation(StringPref.class);
            if (sp != null) {
                all.put(sp.key(), getDefaultString(context, sp));
                if (sp.night())
                    all.put(sp.key() + PhotoSettings.NIGHTPOSTFIX, getDefaultString(context, sp));
            }
        }
        {
            EditIntPref ip = f.getAnnotation(EditIntPref.class);
            if (ip != null) {
                all.put(ip.key(), ip.val() + "");
                if (ip.night())
                    all.put(ip.key() + PhotoSettings.NIGHTPOSTFIX, ip.val() + "");
            }
        }
        {
            IntPref ip = f.getAnnotation(IntPref.class);
            if (ip != null) {
                all.put(ip.key(), ip.val());
                if (ip.night())
                    all.put(ip.key() + PhotoSettings.NIGHTPOSTFIX, ip.val());
            }
        }
        {
            EditFloatPref fp = f.getAnnotation(EditFloatPref.class);
            if (fp != null) {
                all.put(fp.key(), fp.val() + "");
                if (fp.night())
                    all.put(fp.key() + PhotoSettings.NIGHTPOSTFIX, fp.val() + "");
            }
        }
    }

    for (String s : settings) {
        try {
            String[] setting = s.split(":", 2);
            String param = setting[0];
            if (all.containsKey(param)) {
                String value = setting[1];
                if (value.length() > 0) {
                    Class<? extends Object> c = all.get(param).getClass();
                    Object val = parseObjectFromString(value, c);

                    if (c == String.class)
                        edit.putString(param, (String) val);
                    else if (c == Boolean.class)
                        edit.putBoolean(param, (Boolean) val);
                    else if (c == Integer.class)
                        edit.putInt(param, (Integer) val);
                    else
                        throw new UnsupportedOperationException(c.toString());
                } else {
                    MobileWebCam.LogE("Warning: config.txt entry '" + param + "' value is empty!");
                }
            }
        } catch (Exception e) {
            if (e.getMessage() != null)
                MobileWebCam.LogE(e.getMessage());
            e.printStackTrace();
        }
    }
    edit.commit();
}

From source file:org.eclipse.winery.repository.export.ZipExporter.java

/**
 * Writes a complete CSAR containing all necessary things reachable from the given service
 * template/*from   w ww.  j a  v a  2s. c om*/
 * 
 * @param id the id of the service template to export
 * @param out the outputstream to write to
 * @throws JAXBException
 */
public void writeZip(TOSCAComponentId entryId, OutputStream out)
        throws ArchiveException, IOException, XMLStreamException, JAXBException {
    ZipExporter.logger.trace("Starting CSAR export with {}", entryId.toString());

    Map<RepositoryFileReference, String> refMap = new HashMap<RepositoryFileReference, String>();
    Collection<String> definitionNames = new ArrayList<>();

    final ArchiveOutputStream zos = new ArchiveStreamFactory().createArchiveOutputStream("zip", out);

    TOSCAExportUtil exporter = new TOSCAExportUtil();
    Map<String, Object> conf = new HashMap<>();

    ExportedState exportedState = new ExportedState();

    TOSCAComponentId currentId = entryId;
    do {
        logger.info("begin to scan class:" + System.currentTimeMillis());
        Reflections reflections = new Reflections("org.eclipse.winery.repository.ext");
        Set<Class<? extends ExportFileGenerator>> implenmetions = reflections
                .getSubTypesOf(org.eclipse.winery.repository.ext.export.custom.ExportFileGenerator.class);
        logger.info("end to scan class:" + System.currentTimeMillis());
        Iterator<Class<? extends ExportFileGenerator>> it = implenmetions.iterator();
        Collection<TOSCAComponentId> referencedIds = null;

        String defName = ZipExporter.getDefinitionsPathInsideCSAR(currentId);
        definitionNames.add(defName);

        zos.putArchiveEntry(new ZipArchiveEntry(defName));

        try {
            referencedIds = exporter.exportTOSCA(currentId, zos, refMap, conf, null);
        } catch (IllegalStateException e) {
            // thrown if something went wrong inside the repo
            out.close();
            // we just rethrow as there currently is no error stream.
            throw e;
        }
        zos.closeArchiveEntry();

        while (it.hasNext()) {
            Class<? extends ExportFileGenerator> exportClass = it.next();
            logger.trace("the " + exportClass.toString() + "begin to write file");
            try {
                if (!Modifier.isAbstract(exportClass.getModifiers())) {
                    ExportFileGenerator fileGenerator = exportClass.newInstance();
                    referencedIds = exporter.exportTOSCA(currentId, zos, refMap, conf, fileGenerator);
                }
            } catch (InstantiationException e) {
                logger.error("export error occur while instancing " + exportClass.toString(), e);
                out.close();
            } catch (IllegalAccessException e) {
                logger.error("export error occur", e);
                out.close();
            }
        }

        exportedState.flagAsExported(currentId);
        exportedState.flagAsExportRequired(referencedIds);

        currentId = exportedState.pop();
    } while (currentId != null);

    // if we export a ServiceTemplate, data for the self-service portal might exist
    if (entryId instanceof ServiceTemplateId) {
        this.addSelfServiceMetaData((ServiceTemplateId) entryId, refMap);
        addCsarMeta((ServiceTemplateId) entryId, zos);
    }

    // write custom file
    CustomizedFileInfos customizedResult = null;
    if (entryId instanceof ServiceTemplateId) {
        customizedResult = this.exportCustomFiles((ServiceTemplateId) entryId, zos);
    }

    // write manifest directly after the definitions to have it more at the beginning of the ZIP
    // rather than having it at the very end
    this.addManifest(entryId, definitionNames, refMap, zos);
    this.addManiYamlfest(entryId, exporter.getYamlExportDefResultList(), refMap, zos, exporter);
    this.addCheckSumFest(
            getCheckSums(exporter.getYamlExportDefResultList(), customizedResult.getCustomizedFileResults()),
            zos);
    // used for generated XSD schemas
    TransformerFactory tFactory = TransformerFactory.newInstance();
    Transformer transformer;
    try {
        transformer = tFactory.newTransformer();
    } catch (TransformerConfigurationException e1) {
        ZipExporter.logger.debug(e1.getMessage(), e1);
        throw new IllegalStateException("Could not instantiate transformer", e1);
    }

    // write all referenced files
    for (RepositoryFileReference ref : refMap.keySet()) {
        String archivePath = refMap.get(ref);
        ZipExporter.logger.trace("Creating {}", archivePath);
        ArchiveEntry archiveEntry = new ZipArchiveEntry("xml/" + archivePath);
        zos.putArchiveEntry(archiveEntry);
        if (ref instanceof DummyRepositoryFileReferenceForGeneratedXSD) {
            ZipExporter.logger.trace("Special treatment for generated XSDs");
            Document document = ((DummyRepositoryFileReferenceForGeneratedXSD) ref).getDocument();
            DOMSource source = new DOMSource(document);
            StreamResult result = new StreamResult(zos);
            try {
                transformer.transform(source, result);
            } catch (TransformerException e) {
                ZipExporter.logger.debug("Could not serialize generated xsd", e);
            }
        } else {
            try (InputStream is = Repository.INSTANCE.newInputStream(ref)) {
                IOUtils.copy(is, zos);
            } catch (Exception e) {
                ZipExporter.logger.error("Could not copy file content to ZIP outputstream", e);
            }
        }

        // add plan files/artifact templantes to yaml folder
        updatePlanDef(archivePath, ref, zos, customizedResult.getPlanInfos());

        zos.closeArchiveEntry();
    }

    addPlan2Zip(customizedResult.getPlanInfos(), zos);
    this.addNamespacePrefixes(zos);

    zos.finish();
    zos.close();
}

From source file:com.amazon.kinesis.streaming.agent.config.Configuration.java

@SuppressWarnings("unchecked")
private <T> ValueReader<T> getReader(Class<T> clazz) {
    if (this.readers.containsKey(clazz))
        return (ValueReader<T>) this.readers.get(clazz);
    else// w  ww .jav  a2 s  .c om
        throw new ConfigurationException("Don't know how to read value of type: " + clazz.toString());
}

From source file:org.opt4j.config.ModuleAutoFinder.java

/**
 * Returns all not abstract classes that implement {@link PropertyModule}.
 * //from  w  w w .  j  av  a  2 s  .  c  o m
 * @return all property modules
 */
protected Collection<Class<? extends Module>> getAll() {

    Starter starter = new Starter();
    Collection<File> files = starter.addPlugins();

    classLoader = ClassLoader.getSystemClassLoader();

    String paths = System.getProperty("java.class.path");
    StringTokenizer st = new StringTokenizer(paths, ";\n:");

    while (st.hasMoreTokens()) {
        String path = st.nextToken();
        File f = new File(path);

        if (f.exists()) {
            try {
                f = f.getCanonicalFile();
                files.add(f);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    List<Class<?>> classes = new ArrayList<Class<?>>();

    for (File file : files) {

        if (isJar(file)) {

            try {
                classes.addAll(getAllClasses(new ZipFile(file)));
            } catch (ZipException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (UnsupportedClassVersionError e) {
                System.err.println(file + " not supported: bad version number");
            }
        } else {
            classes.addAll(getAllClasses(file));
        }
    }

    List<Class<? extends Module>> modules = new ArrayList<Class<? extends Module>>();

    for (Class<?> clazz : classes) {
        if (Opt4JModule.class.isAssignableFrom(clazz) && !Modifier.isAbstract(clazz.getModifiers())) {
            Class<? extends Module> module = clazz.asSubclass(Module.class);
            Ignore i = module.getAnnotation(Ignore.class);

            if (i == null && !module.isAnonymousClass() && accept.transform(module)
                    && !ignore.transform(module)) {
                modules.add(module);
                invokeOut("Add module: " + module.toString());
            }
        }
    }

    return modules;

}

From source file:com.dssmp.agent.config.Configuration.java

/**
 * @param enumType//from  w w w .  j ava 2 s.  co  m
 * @param key
 * @return the enum constant at given key, or <code>fallback</code> if the
 * key does not exist in the configuration.
 * @throws ConfigurationException if the enum constant failed to be returned.
 */
public <E extends Enum<E>> E readEnum(Class<E> enumType, String key) {
    try {
        return Enum.valueOf(enumType, readString(key));
    } catch (Exception e) {
        throw new ConfigurationException(String.format(
                "Failed to return the enum constant of the enum type(%s): %s", enumType.toString(), key), e);
    }
}

From source file:com.amazon.kinesis.streaming.agent.config.Configuration.java

@SuppressWarnings("unchecked")
private <T> Function<Object, T> getConverter(Class<T> clazz) {
    if (this.converters.containsKey(clazz))
        return (Function<Object, T>) this.converters.get(clazz);
    else/* w  w  w.  j  av a 2  s . co m*/
        throw new ConfigurationException("There's no converter for type: " + clazz.toString());
}

From source file:org.datacleaner.descriptors.SimpleComponentDescriptor.java

@Override
public int compareTo(ComponentDescriptor<?> o) {
    if (o == null) {
        return 1;
    }//from ww w.ja  v a  2s  .  co m
    Class<?> otherComponentClass = o.getComponentClass();
    if (otherComponentClass == null) {
        return 1;
    }

    int diff = this.getDisplayName().compareTo(o.getDisplayName());
    if (diff == 0) {
        String thisBeanClassName = this.getComponentClass().toString();
        String thatBeanClassName = otherComponentClass.toString();
        diff = thisBeanClassName.compareTo(thatBeanClassName);
    }

    return diff;
}

From source file:org.energyos.espi.common.repositories.jpa.ResourceRepositoryImpl.java

@Override
public <T extends IdentifiedObject> void deleteById(Long id, Class<T> clazz) {

    try {//from ww w . j  av a2 s  .  c o m
        T temp = findById(id, clazz);

        em.merge(temp);
        temp.unlink();
        em.remove(temp);

    } catch (Exception e) {
        System.out.printf("**** deleteById(Long id) Exception: %s - %s\n", clazz.toString(), e.toString());
        throw new RuntimeException(e);
    }

}

From source file:org.grouplens.lenskit.eval.script.ConfigMethodInvoker.java

/**
 * Find an external method (a builder or task) and return a closure that, when invoked,
 * constructs and configures it.  It does <strong>not</strong> invoke the builder or task, that
 * is left up to the caller.//w  w  w. j a  v  a 2s  .co  m
 *
 * @param name   The method name.
 * @return The constructed and configured object corresponding to this method.
 */
public Object callExternalMethod(String name, Object... args) throws NoSuchMethodException {
    final Class<?> mtype = engine.lookupMethod(name);
    if (mtype != null) {
        try {
            return constructAndConfigure(mtype, args);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException("cannot find suitable for " + mtype.toString(), e);
        }
    } else {
        throw new NoSuchMethodException(name);
    }
}

From source file:net.fenyo.gnetwatch.targets.Target.java

/**
 * Returns the last event./*from  www . java2  s.c  o  m*/
 * @param clazz type of events.
 * @return EventGeneric last event.
 */
public EventGeneric getLastEvent(Class clazz) {
    EventGeneric result = null;

    final Synchro synchro = getGUI().getSynchro();
    synchronized (synchro) {
        final Session session = synchro.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        try {
            session.update(this);

            // get events inside the range
            final EventList el = eventLists.get(clazz.toString());
            java.util.List results = session.createQuery(
                    "from EventGeneric as ev where ev.eventList = :event_list " + "order by ev.date desc")
                    .setString("event_list", el.getId().toString()).list();
            if (results.size() > 0)
                result = (EventGeneric) results.get(0);

            session.getTransaction().commit();
        } catch (final Exception ex) {
            log.error("Exception", ex);
            session.getTransaction().rollback();
        }
    }

    return result;
}