Example usage for java.util Properties isEmpty

List of usage examples for java.util Properties isEmpty

Introduction

In this page you can find the example usage for java.util Properties isEmpty.

Prototype

@Override
    public boolean isEmpty() 

Source Link

Usage

From source file:org.apache.stratos.rest.endpoint.util.converter.ObjectConverter.java

private static List<org.apache.stratos.common.beans.PropertyBean> convertJavaUtilPropertiesToPropertyBeans(
        java.util.Properties properties) {

    List<org.apache.stratos.common.beans.PropertyBean> propertyBeans = null;
    if (properties != null && !properties.isEmpty()) {
        Enumeration<?> e = properties.propertyNames();
        propertyBeans = new ArrayList<org.apache.stratos.common.beans.PropertyBean>();

        while (e.hasMoreElements()) {
            String key = (String) e.nextElement();
            String value = properties.getProperty(key);
            org.apache.stratos.common.beans.PropertyBean propertyBean = new org.apache.stratos.common.beans.PropertyBean();
            propertyBean.setName(key);/*from   w ww  .  jav  a  2s.c  om*/
            propertyBean.setValue(value);
            propertyBeans.add(propertyBean);
        }
    }
    return propertyBeans;
}

From source file:org.jboss.dashboard.ui.resources.GraphicElement.java

/**
 * Process the element descriptor inside the zip file, and set properties for given graphic element.
 *
 * @throws java.io.IOException//from w  ww.  j  a va 2s . c  o m
 */
protected void deploy() throws Exception {
    Properties prop = new Properties();
    resources = new HashMap<String, Map<String, String>>();
    InputStream in = new BufferedInputStream(new FileInputStream(tmpZipFile));
    ZipInputStream zin = null;
    try {
        zin = new ZipInputStream(in);
        ZipEntry e;
        while ((e = zin.getNextEntry()) != null) {
            if (getDescriptorFileName().equals(e.getName())) {
                prop.load(zin);
            }
        }
    } finally {
        if (zin != null)
            zin.close();
    }
    if (prop.isEmpty()) {
        log.error("No properties inside descriptor " + getDescriptorFileName() + " for item with id " + id);
    }
    Enumeration properties = prop.propertyNames();
    String[] languages = getLocaleManager().getAllLanguages();
    while (properties.hasMoreElements()) {
        String propName = (String) properties.nextElement();
        if (propName.startsWith("name.")) {
            String lang = propName.substring(propName.lastIndexOf(".") + 1);
            setDescription(prop.getProperty(propName), lang);
            log.debug("Look-and-feel name (" + lang + "): " + prop.getProperty(propName));
        } else if (propName.startsWith("resource.")) {
            String resourceName = propName.substring("resource.".length());
            String langId = null;
            for (int i = 0; i < languages.length; i++) {
                String lngId = languages[i];
                if (resourceName.startsWith(lngId + ".")) {
                    langId = lngId;
                    resourceName = resourceName.substring(langId.length() + 1);
                    break;
                }
            }
            String resourcePath = prop.getProperty(propName);
            Map<String, String> existingResource = resources.get(resourceName);
            if (existingResource == null)
                resources.put(resourceName, existingResource = new HashMap<String, String>());
            existingResource.put(langId, resourcePath);
        } else {
            log.error("Unknown property in descriptor " + propName);
        }
    }
    log.debug("Loaded Graphic element description" + getDescription());
    log.debug("Loaded Graphic element resources: " + resources);
}

From source file:org.efaps.admin.common.SystemConfiguration.java

/**
 * Returns for given <code>_key</code> the related value as Properties. If
 * no attribute is found an empty Properties is returned.
 * Can concatenates Properties for Keys.<br/>
 * e.b. Key, Key01, Key02, Key03//from   w w  w  .j av  a  2  s  .co m
 *
 * @param _key key of searched attribute
 * @param _concatenate  concatenate or not
 * @return map with properties
 * @throws EFapsException on error
 */
public Properties getAttributeValueAsProperties(final String _key, final boolean _concatenate)
        throws EFapsException {
    final Properties ret = new Properties();
    final String value = getAttributeValue(_key);
    if (value != null) {
        try {
            ret.load(new StringReader(value));
        } catch (final IOException e) {
            throw new EFapsException(SystemConfiguration.class, "getAttributeValueAsProperties", e);
        }
    }
    if (_concatenate) {
        for (int i = 1; i < 100; i++) {
            final String keyTmp = _key + String.format("%02d", i);
            final String valueTmp = getAttributeValue(keyTmp);
            final Properties propsTmp = new Properties();
            if (valueTmp != null) {
                try {
                    propsTmp.load(new StringReader(valueTmp));
                } catch (final IOException e) {
                    throw new EFapsException(SystemConfiguration.class, "getAttributeValueAsPropertiesConcat",
                            e);
                }
            } else {
                break;
            }
            if (propsTmp.isEmpty()) {
                break;
            } else {
                ret.putAll(propsTmp);
            }
        }
    }
    return ret;
}

From source file:com.mirth.connect.client.ui.NotificationDialog.java

private void doSave() {
    final Properties personPreferences = new Properties();

    if (!StringUtils.equals(checkForNotifications, Boolean.toString(checkForNotificationsSetting))) {
        personPreferences.put("checkForNotifications", Boolean.toString(checkForNotificationsSetting));
    }/*from  w  w  w .jav a2 s  .  c  o  m*/
    if (!StringUtils.equals(showNotificationPopup, Boolean.toString(notificationCheckBox.isSelected()))) {
        personPreferences.put("showNotificationPopup", Boolean.toString(notificationCheckBox.isSelected()));
    }

    Set<Integer> currentArchivedNotifications = notificationModel.getArchivedNotifications();
    if (!archivedNotifications.equals(currentArchivedNotifications)) {
        personPreferences.put("archivedNotifications",
                ObjectXMLSerializer.getInstance().serialize(currentArchivedNotifications));
    }

    if (!personPreferences.isEmpty()) {
        final String workingId = parent.startWorking("Saving notifications settings...");

        SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
            public Void doInBackground() {
                try {
                    parent.mirthClient.setUserPreferences(parent.getCurrentUser(parent).getId(),
                            personPreferences);
                } catch (ClientException e) {
                    parent.alertThrowable(parent, e);
                }
                return null;
            }

            @Override
            public void done() {
                parent.stopWorking(workingId);
            }
        };

        worker.execute();
    }

    parent.updateNotificationTaskName(unarchivedCount);

    this.dispose();
}

From source file:solidbase.config.Configuration.java

/**
 * Create a new configuration object. This constructor is used by the command line version of SolidBase.
 *
 * @param progress The listener that listens to config events.
 * @param pass Are we in pass 1 or pass 2 of booting?
 * @param options The options from the command line.
 *///from w w  w. jav a  2s  .c  om
public Configuration(ConfigListener progress, int pass, Options options) {
    try {
        // Load the default properties

        URL url = Configuration.class.getResource(SOLIDBASE_DEFAULT_PROPERTIES);
        if (url == null)
            throw new SystemException(SOLIDBASE_DEFAULT_PROPERTIES + " not found in classpath");

        progress.readingConfigFile(url.toString());

        this.properties = new Properties();
        InputStream input = url.openStream();
        try {
            this.properties.load(input);
        } finally {
            input.close();
        }

        // Load the solidbase.properties

        File file;
        if (options.config != null)
            file = new File(options.config);
        else
            file = getPropertiesFile();

        if (file.exists()) {
            progress.readingConfigFile(file.getAbsolutePath());

            this.properties = new Properties(this.properties);
            input = new FileInputStream(file);
            try {
                this.properties.load(input);
            } finally {
                input.close();
            }

            // Read the config version

            String s = this.properties.getProperty("properties-version");
            if (!"1.0".equals(s))
                throw new FatalException("Expecting properties-version 1.0 in the properties file");
        }

        // Load the commandline properties

        Properties commandLineProperties = new Properties(this.properties);
        if (options.driver != null)
            commandLineProperties.put("connection.driver", options.driver);
        if (options.url != null)
            commandLineProperties.put("connection.url", options.url);
        if (options.username != null)
            commandLineProperties.put("connection.username", options.username);
        if (options.password != null)
            commandLineProperties.put("connection.password", options.password);
        if (options.target != null)
            commandLineProperties.put("upgrade.target", options.target);
        if (options.upgradefile != null)
            commandLineProperties.put("upgrade.file", options.upgradefile);
        if (options.sqlfile != null)
            commandLineProperties.put("sql.file", options.sqlfile);
        if (!commandLineProperties.isEmpty())
            this.properties = commandLineProperties;
        this.parameters = options.parameters;

        // Read the classpath extension

        this.driverJars = new ArrayList<String>();
        String driversProperty = this.properties.getProperty("classpath.ext");
        if (driversProperty != null)
            for (String driverJar : driversProperty.split(";")) {
                driverJar = driverJar.trim();
                if (driverJar.length() > 0)
                    this.driverJars.add(driverJar);
            }

        if (pass > 1) {
            String driver = this.properties.getProperty("connection.driver");
            String dbUrl = this.properties.getProperty("connection.url");
            String userName = this.properties.getProperty("connection.username");
            String password = this.properties.getProperty("connection.password");
            String upgradeFile = this.properties.getProperty("upgrade.file");
            String target = this.properties.getProperty("upgrade.target");
            String sqlFile = this.properties.getProperty("sql.file");

            if (driver != null || dbUrl != null || userName != null || password != null)
                this.defaultDatabase = new Database("default", driver, dbUrl, userName, password);
            this.upgradeFile = upgradeFile;
            this.target = target;
            this.sqlFile = sqlFile;

            for (Entry<Object, Object> entry : this.properties.entrySet()) {
                String key = (String) entry.getKey();
                Matcher matcher = propertyPattern.matcher(key);
                if (matcher.matches()) {
                    String name = matcher.group(1);
                    String prop = matcher.group(2);
                    String value = (String) entry.getValue();
                    Database database = this.secondaryDatabases.get(name);
                    if (database == null) {
                        database = new Database(name);
                        this.secondaryDatabases.put(name, database);
                    }
                    if (prop.equals("driver"))
                        database.setDriver(value);
                    else if (prop.equals("url"))
                        database.setUrl(value);
                    else if (prop.equals("username"))
                        database.setUserName(value);
                    else if (prop.equals("password"))
                        database.setPassword(value);
                    else
                        Assert.fail();
                } else if (key.startsWith("parameter.")) {
                    key = key.substring(10);
                    if (!this.parameters.containsKey(key))
                        this.parameters.put(key, entry.getValue());
                }
            }

            // Validate them

            for (Database database : this.secondaryDatabases.values()) {
                if (database.getName().equals("default"))
                    throw new FatalException("The secondary connection name 'default' is not allowed");
                if (StringUtils.isBlank(database.getUserName()))
                    throw new FatalException("Property 'connection." + database.getName()
                            + ".username' must be specified in " + SOLIDBASE_PROPERTIES);
            }
        }
    } catch (IOException e) {
        throw new SystemException(e);
    }
}

From source file:org.apache.tomee.embedded.TomEEEmbeddedApplicationRunner.java

public synchronized void start(final Class<?> marker, final Properties config, final String... args)
        throws Exception {
    if (started) {
        return;// w ww.j  ava2s  .c  om
    }

    ensureAppInit(marker);
    started = true;

    final Class<?> appClass = app.getClass();
    final AnnotationFinder finder = new AnnotationFinder(new ClassesArchive(ancestors(appClass)));

    // setup the container config reading class annotation, using a randome http port and deploying the classpath
    final Configuration configuration = new Configuration();
    final ContainerProperties props = appClass.getAnnotation(ContainerProperties.class);
    if (props != null) {
        final Properties runnerProperties = new Properties();
        for (final ContainerProperties.Property p : props.value()) {
            final String name = p.name();
            if (name.startsWith("tomee.embedded.application.runner.")) { // allow to tune the Configuration
                // no need to filter there since it is done in loadFromProperties()
                runnerProperties.setProperty(name.substring("tomee.embedded.application.runner.".length()),
                        p.value());
            } else {
                configuration.property(name, StrSubstitutor.replaceSystemProperties(p.value()));
            }
        }
        if (!runnerProperties.isEmpty()) {
            configuration.loadFromProperties(runnerProperties);
        }
    }
    configuration.loadFromProperties(System.getProperties()); // overrides, note that some config are additive by design

    final List<Method> annotatedMethods = finder
            .findAnnotatedMethods(org.apache.openejb.testing.Configuration.class);
    if (annotatedMethods.size() > 1) {
        throw new IllegalArgumentException("Only one @Configuration is supported: " + annotatedMethods);
    }
    for (final Method m : annotatedMethods) {
        final Object o = m.invoke(app);
        if (Properties.class.isInstance(o)) {
            final Properties properties = Properties.class.cast(o);
            if (configuration.getProperties() == null) {
                configuration.setProperties(new Properties());
            }
            configuration.getProperties().putAll(properties);
        } else {
            throw new IllegalArgumentException("Unsupported " + o + " for @Configuration");
        }
    }

    final Collection<org.apache.tomee.embedded.LifecycleTask> lifecycleTasks = new ArrayList<>();
    final Collection<Closeable> postTasks = new ArrayList<>();
    final LifecycleTasks tasks = appClass.getAnnotation(LifecycleTasks.class);
    if (tasks != null) {
        for (final Class<? extends org.apache.tomee.embedded.LifecycleTask> type : tasks.value()) {
            final org.apache.tomee.embedded.LifecycleTask lifecycleTask = type.newInstance();
            lifecycleTasks.add(lifecycleTask);
            postTasks.add(lifecycleTask.beforeContainerStartup());
        }
    }

    final Map<String, Field> ports = new HashMap<>();
    {
        Class<?> type = appClass;
        while (type != null && type != Object.class) {
            for (final Field f : type.getDeclaredFields()) {
                final RandomPort annotation = f.getAnnotation(RandomPort.class);
                final String value = annotation == null ? null : annotation.value();
                if (value != null && value.startsWith("http")) {
                    f.setAccessible(true);
                    ports.put(value, f);
                }
            }
            type = type.getSuperclass();
        }
    }

    if (ports.containsKey("http")) {
        configuration.randomHttpPort();
    }

    // at least after LifecycleTasks to inherit from potential states (system properties to get a port etc...)
    final Configurers configurers = appClass.getAnnotation(Configurers.class);
    if (configurers != null) {
        for (final Class<? extends Configurer> type : configurers.value()) {
            type.newInstance().configure(configuration);
        }
    }

    final Classes classes = appClass.getAnnotation(Classes.class);
    String context = classes != null ? classes.context() : "";
    context = !context.isEmpty() && context.startsWith("/") ? context.substring(1) : context;

    Archive archive = null;
    if (classes != null && classes.value().length > 0) {
        archive = new ClassesArchive(classes.value());
    }

    final Jars jars = appClass.getAnnotation(Jars.class);
    final List<URL> urls;
    if (jars != null) {
        final Collection<File> files = ApplicationComposers.findFiles(jars);
        urls = new ArrayList<>(files.size());
        for (final File f : files) {
            urls.add(f.toURI().toURL());
        }
    } else {
        urls = null;
    }

    final WebResource resources = appClass.getAnnotation(WebResource.class);
    if (resources != null && resources.value().length > 1) {
        throw new IllegalArgumentException("Only one docBase is supported for now using @WebResource");
    }

    String webResource = null;
    if (resources != null && resources.value().length > 0) {
        webResource = resources.value()[0];
    } else {
        final File webapp = new File("src/main/webapp");
        if (webapp.isDirectory()) {
            webResource = "src/main/webapp";
        }
    }

    if (config != null) { // override other config from annotations
        configuration.loadFromProperties(config);
    }

    final Container container = new Container(configuration);
    SystemInstance.get().setComponent(TomEEEmbeddedArgs.class, new TomEEEmbeddedArgs(args, null));
    SystemInstance.get().setComponent(LifecycleTaskAccessor.class, new LifecycleTaskAccessor(lifecycleTasks));
    container.deploy(new Container.DeploymentRequest(context,
            // call ClasspathSearcher that lazily since container needs to be started to not preload logging
            urls == null
                    ? new DeploymentsResolver.ClasspathSearcher()
                            .loadUrls(Thread.currentThread().getContextClassLoader()).getUrls()
                    : urls,
            webResource != null ? new File(webResource) : null, true, null, archive));

    for (final Map.Entry<String, Field> f : ports.entrySet()) {
        switch (f.getKey()) {
        case "http":
            setPortField(f.getKey(), f.getValue(), configuration, context, app);
            break;
        case "https":
            break;
        default:
            throw new IllegalArgumentException("port " + f.getKey() + " not yet supported");
        }
    }

    SystemInstance.get().addObserver(app);
    composerInject(app);

    final AnnotationFinder appFinder = new AnnotationFinder(new ClassesArchive(appClass));
    for (final Method mtd : appFinder.findAnnotatedMethods(PostConstruct.class)) {
        if (mtd.getParameterTypes().length == 0) {
            if (!mtd.isAccessible()) {
                mtd.setAccessible(true);
            }
            mtd.invoke(app);
        }
    }

    hook = new Thread() {
        @Override
        public void run() { // ensure to log errors but not fail there
            for (final Method mtd : appFinder.findAnnotatedMethods(PreDestroy.class)) {
                if (mtd.getParameterTypes().length == 0) {
                    if (!mtd.isAccessible()) {
                        mtd.setAccessible(true);
                    }
                    try {
                        mtd.invoke(app);
                    } catch (final IllegalAccessException e) {
                        throw new IllegalStateException(e);
                    } catch (final InvocationTargetException e) {
                        throw new IllegalStateException(e.getCause());
                    }
                }
            }

            try {
                container.close();
            } catch (final Exception e) {
                e.printStackTrace();
            }
            for (final Closeable c : postTasks) {
                try {
                    c.close();
                } catch (final IOException e) {
                    e.printStackTrace();
                }
            }
            postTasks.clear();
            app = null;
            try {
                SHUTDOWN_TASKS.remove(this);
            } catch (final Exception e) {
                // no-op: that's ok at that moment if not called manually
            }
        }
    };
    SHUTDOWN_TASKS.put(hook, hook);
}

From source file:edu.kit.dama.staging.services.impl.StagingService.java

/**
 * This method finalizes the download for the provided download entity. This
 * method is intended to be used internally only.
 *
 * @param pDownloadInfo The download information.
 *
 * @return TRUE if the download could be finalized.
 *//*from   w w w  .  ja  v a  2 s.c o  m*/
private boolean finalizeDownload(DownloadInformation pDownloadInfo) {
    if (!pDownloadInfo.getStatusEnum().isFinalizationPossible()) {
        LOGGER.error(
                "Finalization of download impossible. Status of download #{} is {}, but has to be DOWNLOAD_STATUS.SCHEDULED",
                pDownloadInfo.getTransferId(), pDownloadInfo.getStatusEnum());
        return false;
    }

    LOGGER.debug("Setting download status to PREPARING");
    pDownloadInfo.setStatusEnum(DOWNLOAD_STATUS.PREPARING);
    if (!updateTransferStatus(pDownloadInfo)) {
        LOGGER.error("Failed to update download status to {}. Finalizing impossible.",
                DOWNLOAD_STATUS.PREPARING);
        return false;
    }

    LOGGER.debug("Performing download finalization for download with id {}", pDownloadInfo.getTransferId());
    boolean result = true;

    try {
        URL stagingUrl = new URL(pDownloadInfo.getStagingUrl());
        LOGGER.debug("Obtaining AccessPoint with id  '{}'", pDownloadInfo.getAccessPointId());
        AbstractStagingAccessPoint accessPoint = StagingConfigurationManager.getSingleton()
                .getAccessPointById(pDownloadInfo.getAccessPointId());

        LOGGER.debug("Obtaining user paths for staging URL '{}'", stagingUrl.toString());
        File localStagingPath = accessPoint.getLocalPathForUrl(stagingUrl, getContext(pDownloadInfo));
        //obtain settings path as the file tree to download is stored there
        File localSettingsPath = new File(localStagingPath, Constants.STAGING_SETTINGS_FOLDER_NAME);

        //try to perform staging
        StagingFile destinationForStaging = new StagingFile(new AbstractFile(localStagingPath));
        LOGGER.debug("Perform staging into folder '{}'", destinationForStaging);

        String treeFile = FilenameUtils.concat(localSettingsPath.getPath(),
                DownloadPreparationHandler.DATA_FILENAME);
        LOGGER.debug(" - Loading file tree from {}", treeFile);
        IFileTree downloadTree = DataOrganizationUtils.readTreeFromFile(new File(treeFile));

        //get filetree and restore
        LOGGER.debug("Restoring data organization tree using storage virtualization");
        if (!StagingConfigurationManager.getSingleton().getStorageVirtualizationAdapter().restore(pDownloadInfo,
                downloadTree, destinationForStaging)) {
            LOGGER.error("Failed to restore data organization tree from file {}", treeFile);
            pDownloadInfo.setStatus(DOWNLOAD_STATUS.PREPARATION_FAILED.getId());
            pDownloadInfo.setErrorMessage("Failed to reconstruct file tree.");
            result = false;
        } else {
            LOGGER.debug("Creating file tree and transfer container.");
            IFileTree tree = DataOrganizationUtils.createTreeFromFile(pDownloadInfo.getDigitalObjectId(),
                    destinationForStaging.getAbstractFile(), destinationForStaging.getAbstractFile().getUrl(),
                    false);
            TransferTaskContainer container = TransferTaskContainer.factoryDownloadContainer(pDownloadInfo,
                    tree, StagingConfigurationManager.getSingleton().getRestServiceUrl());
            container.setDestination(localStagingPath.toURI().toURL());
            LOGGER.debug("Transfer container successfully created.");
            boolean postProcessingSucceeded = true;

            StagingProcessor[] processors = pDownloadInfo.getStagingProcessors()
                    .toArray(new StagingProcessor[] {});
            Arrays.sort(processors, StagingProcessor.DEFAULT_PRIORITY_COMPARATOR);

            LOGGER.debug("Executing {} staging processors", processors.length);
            for (StagingProcessor processor : processors) {
                if (processor.isDisabled()) {
                    LOGGER.info("StagingProcessor with id {} is disabled. Skipping execution.",
                            processor.getUniqueIdentifier());
                    continue;
                }

                try {
                    LOGGER.debug(" - Try to execute processor {} ({})",
                            new Object[] { processor.getName(), processor.getUniqueIdentifier() });
                    AbstractStagingProcessor sProcessor = processor.createInstance();
                    LOGGER.debug(" - Executing processor");
                    sProcessor.performPostTransferProcessing(container);
                    LOGGER.debug(" - Finishing processor execution");
                    sProcessor.finalizePostTransferProcessing(container);
                    LOGGER.debug(" - Processor successfully executed");
                } catch (ConfigurationException ex) {
                    LOGGER.error("Failed to configure StagingProcessor " + processor.getName() + " ("
                            + processor.getUniqueIdentifier() + ")", ex);
                    pDownloadInfo.setStatus(DOWNLOAD_STATUS.PREPARATION_FAILED.getId());
                    pDownloadInfo.setErrorMessage("Internal error. Failed to configure StagingProcessor '"
                            + processor.getName() + "'.");
                    postProcessingSucceeded = false;
                    result = false;
                } catch (StagingProcessorException ex) {
                    LOGGER.error("Failed to perform StagingProcessor " + processor.getName() + " ("
                            + processor.getUniqueIdentifier() + ")", ex);
                    pDownloadInfo.setStatus(DOWNLOAD_STATUS.PREPARATION_FAILED.getId());
                    pDownloadInfo.setErrorMessage("Internal error. Failed to execute StagingProcessor '"
                            + processor.getName() + "'.");
                    postProcessingSucceeded = false;
                    result = false;
                }
            }

            if (postProcessingSucceeded) {
                //preparation successfully...transfer can be performed
                LOGGER.debug("Download preparation finished. Download #{} for object {} is now ready.",
                        pDownloadInfo.getTransferId(), pDownloadInfo.getDigitalObjectId());
                pDownloadInfo.setStatus(DOWNLOAD_STATUS.DOWNLOAD_READY.getId());
                pDownloadInfo.setErrorMessage(null);

                //handle notification
                Properties notificationProperties = MailNotificationHelper.restoreProperties(localSettingsPath);
                if (!notificationProperties.isEmpty()) {
                    if (result) {
                        LOGGER.debug("Try to notify user about finalized download");
                        MailNotificationHelper.sendDownloadNotification(notificationProperties, pDownloadInfo);
                    } else {
                        LOGGER.warn("Download not finalized successfully. Notification skipped.");
                    }
                }
            } else {
                LOGGER.error("Postprocessing failed, skipping user notification.");
                //status to download should be already set
            }
        }
    } catch (MalformedURLException mue) {
        LOGGER.error("Failed to convert staging URL '" + pDownloadInfo.getStagingUrl() + "' of transfer '"
                + pDownloadInfo.getTransferId() + "' to local path", mue);
        pDownloadInfo.setStatus(DOWNLOAD_STATUS.PREPARATION_FAILED.getId());
        pDownloadInfo
                .setErrorMessage("Staging URL '" + pDownloadInfo.getStagingUrl() + "' seems to be invalid.");
        result = false;
    } catch (AdalapiException ex) {
        //failed to handle file tree stuff
        LOGGER.error("Failed finalize download for object ID " + pDownloadInfo.getId(), ex);
        pDownloadInfo.setStatus(DOWNLOAD_STATUS.PREPARATION_FAILED.getId());
        pDownloadInfo.setErrorMessage("Failed to finalize download. Cause: " + ex.getMessage());
        result = false;
    } catch (RuntimeException t) {
        //failed to handle file tree stuff
        LOGGER.error("An unexpected error occured while downloading object " + pDownloadInfo.getTransferId()
                + ". Download cannot be continued.", t);
        pDownloadInfo.setStatus(DOWNLOAD_STATUS.PREPARATION_FAILED.getId());
        pDownloadInfo.setErrorMessage("Unhandled error during download. Cause: " + t.getMessage());
        result = false;
    }

    LOGGER.debug("Updating download information to status {}", pDownloadInfo.getStatusEnum());
    if (updateTransferStatus(pDownloadInfo)) {
        LOGGER.debug("Download status successfully updated.");
    } else {
        LOGGER.error("Failed to update status or download #{} for digital object {} to {}",
                pDownloadInfo.getTransferId(), pDownloadInfo.getDigitalObjectId(),
                pDownloadInfo.getStatusEnum());
        result = false;
    }
    return result;
}

From source file:com.mnxfst.testing.client.TSClient.java

/**
 * Executes the referenced test plan for all given host names. The result contains a mapping from a host name to the returned result identifier
 * of that ptest-server instance //from w  ww . j  a  v  a 2s.  c  o m
 * @param hostNames
 * @param port
 * @param threads
 * @param recurrences
 * @param recurrenceType
 * @param testplan
 * @param additionalParameters
 * @param urlEncoding
 * @return
 * @throws TSClientConfigurationException
 * @throws TSClientExecutionException
 */
protected Map<String, String> executeTestPlan(String[] hostNames, int port, long threads, long recurrences,
        TSPlanRecurrenceType recurrenceType, byte[] testplan, Properties additionalParameters,
        String urlEncoding) throws TSClientConfigurationException, TSClientExecutionException {

    // the ptest-server understands http get, thus we use it TODO refactor to post and send testplan as well and do not reference it anymore!
    StringBuffer buffer = new StringBuffer("/?");
    buffer.append(REQUEST_PARAMETER_EXECUTE).append("=1");
    buffer.append("&").append(REQUEST_PARAMETER_RECURRENCES).append("=").append(recurrences);
    buffer.append("&").append(REQUEST_PARAMETER_RECURRENCE_TYPE).append("=").append(recurrenceType.toString());
    buffer.append("&").append(REQUEST_PARAMETER_THREADS).append("=").append(threads);

    try {
        if (additionalParameters != null && !additionalParameters.isEmpty()) {
            for (Object key : additionalParameters.keySet()) {
                String value = (String) additionalParameters.get(key);
                buffer.append("&").append(key).append("=").append(URLEncoder.encode(value, urlEncoding));
            }
        }
    } catch (UnsupportedEncodingException e) {
        throw new TSClientConfigurationException(
                "Unsupported encoding type: " + urlEncoding + ". Error: " + e.getMessage());
    }

    StringBuffer hn = new StringBuffer();
    for (int i = 0; i < hostNames.length; i++) {
        hn.append(hostNames[i]);
        if (i < hostNames.length - 1)
            hn.append(", ");
    }

    System.out.println("Execute testplan:");
    System.out.println("\thostNames: " + hn.toString());
    System.out.println("\tport: " + port);
    System.out.println("\tthreads: " + threads);
    System.out.println("\trecurrences: " + recurrences);
    System.out.println("\trecurrenceType: " + recurrenceType);
    System.out.println("\turl enc: " + urlEncoding);
    System.out.println("\n\turi: " + buffer.toString());

    TSClientPlanExecCallable[] testplanCallables = new TSClientPlanExecCallable[hostNames.length];
    for (int i = 0; i < hostNames.length; i++) {
        testplanCallables[i] = new TSClientPlanExecCallable(hostNames[i], port, buffer.toString(), testplan);
    }

    ExecutorService executorService = Executors.newFixedThreadPool(hostNames.length);
    List<Future<NameValuePair>> executionResults = new ArrayList<Future<NameValuePair>>();
    try {
        executionResults = executorService.invokeAll(Arrays.asList(testplanCallables));
    } catch (InterruptedException e) {
        System.out.println("Test execution interrupted: " + e.getMessage());
    }

    // collect results from callables
    Map<String, String> result = new HashMap<String, String>();
    for (Future<NameValuePair> r : executionResults) {
        try {
            NameValuePair nvp = r.get();
            result.put(nvp.getName(), nvp.getValue());
        } catch (InterruptedException e) {
            System.out.println("Interrupted while waiting for results. Error: " + e.getMessage());
        } catch (ExecutionException e) {
            System.out.println("Interrupted while waiting for results. Error: " + e.getMessage());
        }
    }

    return result;
}

From source file:net.jetrix.config.ServerConfig.java

/**
 * Save the configuration.//from w  w  w  . j  av  a 2  s . c  o  m
 */
public void save() throws IOException {
    // todo make a backup copy of the previous configuration files

    // save the server.xml file
    PrintWriter out = null;

    try {
        File file = new File(serverConfigURL.toURI());
        out = new PrintWriter(file, ENCODING);
    } catch (URISyntaxException e) {
        log.log(Level.SEVERE, e.getMessage(), e);
    }

    out.println("<?xml version=\"1.0\"?>");
    out.println(
            "<!DOCTYPE tetrinet-server PUBLIC \"-//LFJR//Jetrix TetriNET Server//EN\" \"http://jetrix.sourceforge.net/dtd/tetrinet-server.dtd\">");
    out.println();
    out.println("<tetrinet-server host=\"" + (host == null ? "[ALL]" : host.getHostAddress()) + "\">");
    out.println();
    out.println("  <!-- Server name -->");
    out.println("  <name>" + getName() + "</name>");
    out.println();
    out.println("  <!-- Server default language (using an ISO-639 two-letter language code) -->");
    out.println("  <language>" + getLocale().getLanguage() + "</language>");
    out.println();
    out.println("  <!-- How many seconds of inactivity before timeout occurs -->");
    out.println("  <timeout>" + getTimeout() + "</timeout>");
    out.println();
    out.println("  <!-- How many channels should be available on the server -->");
    out.println("  <max-channels>" + getMaxChannels() + "</max-channels>");
    out.println();
    out.println("  <!-- Maximum number of players on the server -->");
    out.println("  <max-players>" + getMaxPlayers() + "</max-players>");
    out.println();
    out.println("  <!-- Maximum number of simultaneous connections allowed from the same IP -->");
    out.println("  <max-connections>" + getMaxConnections() + "</max-connections>");
    out.println();
    out.println("  <!-- Typing /op <thispassword> will give player operator status -->");
    out.println("  <op-password>" + getOpPassword() + "</op-password>");
    out.println();
    out.println("  <!-- Use this password to log on the administration console -->");
    out.println("  <admin-password>" + getAdminPassword() + "</admin-password>");
    out.println();
    out.println("  <!-- Access Log, where requests are logged to -->");
    out.println("  <access-log path=\"" + getAccessLogPath() + "\" />");
    out.println();
    out.println("  <!-- Error Log, where errors are logged to -->");
    out.println("  <error-log  path=\"" + getErrorLogPath() + "\" />");
    out.println();
    out.println("  <!-- Path to the channels descriptor file (relative to the current configuration file) -->");
    out.println("  <channels path=\"" + getChannelsFile() + "\"/>");
    out.println();
    out.println("  <!-- Client listeners -->");
    out.println("  <listeners>");
    for (Listener listener : getListeners()) {
        String autostart = !listener.isAutoStart() ? " auto-start=\"false\"" : "";
        out.println("    <listener class=\"" + listener.getClass().getName() + "\" port=\"" + listener.getPort()
                + "\"" + autostart + "/>");
    }
    out.println("  </listeners>");
    out.println();

    out.println("  <!-- Services -->");
    out.println("  <services>");
    for (Service service : getServices()) {
        try {
            // get the parameters
            Map<String, Object> params = PropertyUtils.describe(service);

            String autostart = !service.isAutoStart() ? "auto-start=\"false\"" : "";
            String classname = "class=\"" + service.getClass().getName() + "\"";

            if (params.size() <= 4) {
                out.println("    <service " + classname + " " + autostart + "/>");
            } else {
                out.println("    <service " + classname + " " + autostart + ">");
                for (String param : params.keySet()) {
                    PropertyDescriptor desc = PropertyUtils.getPropertyDescriptor(service, param);
                    if (!"autoStart".equals(param) && desc.getWriteMethod() != null) {
                        out.println(
                                "      <param name=\"" + param + "\" value=\"" + params.get(param) + "\"/>");
                    }
                }
                out.println("    </service>");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    out.println("  </services>");
    out.println();

    out.println("  <!-- Server commands -->");
    out.println("  <commands>");
    Iterator<Command> commands = CommandManager.getInstance().getCommands(AccessLevel.ADMINISTRATOR);
    while (commands.hasNext()) {
        try {
            Command command = commands.next();
            String hidden = command.isHidden() ? " hidden=\"true\"" : "";
            Command command2 = command.getClass().newInstance();
            String level = command2.getAccessLevel() != command.getAccessLevel()
                    ? " access-level=\"" + command.getAccessLevel() + "\""
                    : "";
            out.println("    <command class=\"" + command.getClass().getName() + "\"" + hidden + level + "/>");
        } catch (Exception e) {
            log.log(Level.WARNING, e.getMessage(), e);
        }
    }
    out.println("  </commands>");
    out.println();

    out.println("  <ban>");
    Iterator<Banlist.Entry> entries = Banlist.getInstance().getBanlist();
    while (entries.hasNext()) {
        Banlist.Entry entry = entries.next();
        out.println("    <host>" + entry.pattern + "</host>");
    }
    out.println("  </ban>");
    out.println();

    if (!datasources.isEmpty()) {
        out.println("  <!-- Database connection parameters -->");
        out.println("  <datasources>");
        out.println();

        for (DataSourceConfig datasource : datasources.values()) {
            out.println("    <datasource name=\"" + datasource.getName() + "\">");
            out.println("      <!-- The class of the JDBC driver used -->");
            out.println("      <driver>" + datasource.getDriver() + "</driver>");
            out.println();
            out.println("      <!-- The URL of the database (jdbc:<type>://<hostname>:<port>/<database>) -->");
            out.println("      <url>" + datasource.getUrl() + "</url>");
            out.println();
            out.println("      <!-- The username connecting to the database -->");
            out.println("      <username>" + datasource.getUsername() + "</username>");
            out.println();
            out.println("      <!-- The password of the user -->");
            if (datasource.getPassword() != null) {
                out.println("      <password>" + datasource.getPassword() + "</password>");
            } else {
                out.println("      <password/>");
            }
            if (datasource.getMinIdle() != DataSourceManager.DEFAULT_MIN_IDLE) {
                out.println();
                out.println("      <!-- The minimum number of idle connections -->");
                out.println("      <min-idle>" + datasource.getMinIdle() + "</min-idle>");
            }
            if (datasource.getMaxActive() != DataSourceManager.DEFAULT_MAX_ACTIVE) {
                out.println();
                out.println("      <!-- The maximum number of active connections -->");
                out.println("      <max-active>" + datasource.getMaxActive() + "</max-active>");
            }
            out.println("    </datasource>");
            out.println();
        }
        out.println("  </datasources>");
        out.println();
    }

    if (mailSessionConfig != null) {
        StringBuilder buffer = new StringBuilder();
        buffer.append("  <mailserver host=\"").append(mailSessionConfig.getHostname()).append("\"");
        buffer.append(" port=\"").append(mailSessionConfig.getPort()).append("\"");
        if (mailSessionConfig.isAuth()) {
            buffer.append(" auth=\"true\"");
            buffer.append(" username=\"").append(mailSessionConfig.getUsername()).append("\"");
            buffer.append(" password=\"").append(mailSessionConfig.getPassword()).append("\"");
        }
        if (mailSessionConfig.isDebug()) {
            buffer.append(" debug=\"true\"");
        }
        buffer.append("/>");

        out.println("  <!-- Mail server parameters -->");
        out.println(buffer.toString());
        out.println();
    }

    if (properties != null && !properties.isEmpty()) {
        out.println("  <!-- Extended properties -->");
        out.println("  <properties>");
        for (String key : properties.stringPropertyNames()) {
            out.println("    <property name=\"" + key + "\" value=\"" + properties.getProperty(key) + "\">");
        }
        out.println("  </properties>");
        out.println();
    }

    out.println("</tetrinet-server>");

    out.flush();
    out.close();

    // save the channels.xml file
    try {
        File file = new File(channelsConfigURL.toURI());
        out = new PrintWriter(file, ENCODING);
    } catch (URISyntaxException e) {
        log.log(Level.SEVERE, e.getMessage(), e);
    }

    out.println("<?xml version=\"1.0\"?>");
    out.println(
            "<!DOCTYPE tetrinet-channels PUBLIC \"-//LFJR//Jetrix Channels//EN\" \"http://jetrix.sourceforge.net/dtd/tetrinet-channels.dtd\">");
    out.println();
    out.println("<tetrinet-channels>");
    out.println();
    out.println("  <!-- Message Of The Day -->");
    out.println("  <motd><![CDATA[");
    out.println(getMessageOfTheDay());
    out.println("  ]]></motd>");
    out.println();

    // filter definitions
    Map<String, String> aliases = FilterManager.getInstance().getFilterAliases();
    out.println("  <!-- Channel filters -->");
    out.println("  <filter-definitions>");
    for (String alias : aliases.keySet()) {
        out.println("    <alias name=\"" + alias + "\" class=\"" + aliases.get(alias) + "\"/>");
    }
    out.println("  </filter-definitions>");
    out.println();

    // global filters
    out.println("  <!-- Global filters -->");
    out.println("  <default-filters>");
    for (FilterConfig filter : globalFilters) {
        saveFilter(filter, out, "    ");
    }
    out.println("  </default-filters>");
    out.println();

    // winlists
    out.println("  <!-- Winlists -->");
    out.println("  <winlists>");
    for (Winlist winlist : WinlistManager.getInstance().getWinlists()) {
        WinlistConfig config = winlist.getConfig();
        Properties props = config.getProperties();
        if (props == null || props.isEmpty()) {
            out.println("    <winlist name=\"" + winlist.getId() + "\" class=\"" + winlist.getClass().getName()
                    + "\"/>");
        } else {
            out.println("    <winlist name=\"" + winlist.getId() + "\" class=\"" + winlist.getClass().getName()
                    + "\">");
            for (Object name : props.keySet()) {
                out.println("      <param name=\"" + name + "\" value=\"" + props.get(name) + "\"/>");
            }
            out.println("    </winlist>");
        }
    }
    out.println("  </winlists>");
    out.println();

    // default settings
    Settings settings = Settings.getDefaultSettings();

    out.println("  <!-- Default game settings -->");
    out.println("  <default-settings>");
    out.println("    <!-- What level each player starts at -->");
    out.println("    <starting-level>" + settings.getStartingLevel() + "</starting-level>");
    out.println();
    out.println("    <!-- How many lines to make before player level increases -->");
    out.println("    <lines-per-level>" + settings.getLinesPerLevel() + "</lines-per-level>");
    out.println();
    out.println("    <!-- Number of levels to increase each time -->");
    out.println("    <level-increase>" + settings.getLevelIncrease() + "</level-increase>");
    out.println();
    out.println("    <!-- Lines to make to get a special block -->");
    out.println("    <lines-per-special>" + settings.getLinesPerSpecial() + "</lines-per-special>");
    out.println();
    out.println("    <!-- Number of special blocks added each time -->");
    out.println("    <special-added>" + settings.getSpecialAdded() + "</special-added>");
    out.println();
    out.println("    <!-- Capacity of Special block inventory -->");
    out.println("    <special-capacity>" + settings.getSpecialCapacity() + "</special-capacity>");
    out.println();
    out.println("    <!-- Play by classic rules? -->");
    out.println("    <classic-rules>" + (settings.getClassicRules() ? "true" : "false") + "</classic-rules>");
    out.println();
    out.println("    <!-- Average together all player's game level? -->");
    out.println(
            "    <average-levels>" + (settings.getAverageLevels() ? "true" : "false") + "</average-levels>");
    out.println();
    out.println("    <!-- Same sequence of blocks for all players? (tetrinet 1.14 clients only) -->");
    out.println("    <same-blocks>" + (settings.getSameBlocks() ? "true" : "false") + "</same-blocks>");
    out.println();
    out.println("    <block-occurancy>");
    for (Block block : Block.values()) {
        out.println("      <" + block.getCode() + ">" + settings.getOccurancy(block) + "</" + block.getCode()
                + ">");
    }
    out.println("    </block-occurancy>");
    out.println();
    out.println("    <special-occurancy>");
    for (Special special : Special.values()) {
        out.println("      <" + special.getCode() + ">" + settings.getOccurancy(special) + "</"
                + special.getCode() + ">");
    }
    out.println("    </special-occurancy>");
    out.println();
    out.println("    <!-- Sudden death parameters -->");
    out.println("    <sudden-death>");
    out.println("      <!-- Time in seconds before the sudden death begins, 0 to disable the sudden death -->");
    out.println("      <time>" + settings.getSuddenDeathTime() + "</time>");
    out.println();
    out.println(
            "      <!-- The message displayed when the sudden death begins. Use \"key:\" prefix to display an internationalized message -->");
    out.println("      <message>" + settings.getSuddenDeathMessage() + "</message>");
    out.println();
    out.println("      <!-- The delay in seconds between lines additions -->");
    out.println("      <delay>" + settings.getSuddenDeathDelay() + "</delay>");
    out.println();
    out.println("      <!-- The number of lines added -->");
    out.println("      <lines-added>" + settings.getSuddenDeathLinesAdded() + "</lines-added>");
    out.println("    </sudden-death>");
    out.println();
    out.println("  </default-settings>");
    out.println();
    out.println();

    out.println("  <channels>");
    for (Channel channel : ChannelManager.getInstance().channels()) {
        ChannelConfig config = channel.getConfig();

        if (config.isPersistent()) {
            out.println("    <channel name=\"" + config.getName() + "\">");
            if (config.getDescription() != null) {
                String description = config.getDescription();
                description = description.contains("<") ? "<![CDATA[" + description + "]]>" : description;
                out.println("      <description>" + description + "</description>");
            }

            if (config.getTopic() != null && config.getTopic().trim().length() > 0) {
                out.println("      <topic>");
                out.println("<![CDATA[");
                out.println(config.getTopic());
                out.println("]]>");
                out.println("      </topic>");
            }

            if (config.getSpeed() != Speed.MIXED) {
                out.println("      <speed>" + config.getSpeed().name().toLowerCase() + "</speed>");
            }

            if (config.isPasswordProtected()) {
                out.println("      <password>" + config.getPassword() + "</password>");
            }

            if (config.getAccessLevel() != AccessLevel.PLAYER) {
                out.println("      <access-level>" + config.getAccessLevel() + "</access-level>");
            }

            if (config.isIdleAllowed()) {
                out.println("      <idle>true</idle>");
            }

            if (!config.isVisible()) {
                out.println("      <visible>false</visible>");
            }

            if (config.getMaxPlayers() != ChannelConfig.PLAYER_CAPACITY) {
                out.println("      <max-players>" + config.getMaxPlayers() + "</max-players>");
            }

            if (config.getMaxSpectators() != ChannelConfig.SPECTATOR_CAPACITY) {
                out.println("      <max-spectators>" + config.getMaxSpectators() + "</max-spectators>");
            }

            if (config.getWinlistId() != null) {
                out.println("      <winlist name=\"" + config.getWinlistId() + "\"/>");
            }

            // channel settings
            settings = config.getSettings();
            if (!settings.useDefaultSettings()) {
                out.println("      <settings>");
                if (!settings.isDefaultStartingLevel()) {
                    out.println("        <starting-level>" + settings.getStartingLevel() + "</starting-level>");
                }
                if (!settings.isDefaultLinesPerLevel()) {
                    out.println(
                            "        <lines-per-level>" + settings.getLinesPerLevel() + "</lines-per-level>");
                }
                if (!settings.isDefaultLevelIncrease()) {
                    out.println("        <level-increase>" + settings.getLevelIncrease() + "</level-increase>");
                }
                if (!settings.isDefaultLinesPerSpecial()) {
                    out.println("        <lines-per-special>" + settings.getLinesPerSpecial()
                            + "</lines-per-special>");
                }
                if (!settings.isDefaultSpecialAdded()) {
                    out.println("        <special-added>" + settings.getSpecialAdded() + "</special-added>");
                }
                if (!settings.isDefaultSpecialCapacity()) {
                    out.println("        <special-capacity>" + settings.getSpecialCapacity()
                            + "</special-capacity>");
                }
                if (!settings.isDefaultClassicRules()) {
                    out.println("        <classic-rules>" + (settings.getClassicRules() ? "true" : "false")
                            + "</classic-rules>");
                }
                if (!settings.isDefaultAverageLevels()) {
                    out.println("        <average-levels>" + (settings.getAverageLevels() ? "true" : "false")
                            + "</average-levels>");
                }
                if (!settings.isDefaultSameBlocks()) {
                    out.println("        <same-blocks>" + (settings.getSameBlocks() ? "true" : "false")
                            + "</same-blocks>");
                }

                if (!settings.isDefaultBlockOccurancy()) {
                    out.println("        <block-occurancy>");
                    for (Block block : Block.values()) {
                        if (settings.getOccurancy(block) != 0) {
                            out.println("          <" + block.getCode() + ">" + settings.getOccurancy(block)
                                    + "</" + block.getCode() + ">");
                        }

                    }
                    out.println("        </block-occurancy>");
                }

                if (!settings.isDefaultSpecialOccurancy()) {
                    out.println("        <special-occurancy>");
                    for (Special special : Special.values()) {
                        if (settings.getOccurancy(special) != 0) {
                            out.println("          <" + special.getCode() + ">" + settings.getOccurancy(special)
                                    + "</" + special.getCode() + ">");
                        }
                    }
                    out.println("        </special-occurancy>");
                }

                // sudden death settings
                if (!settings.isDefaultSuddenDeath()) {
                    out.println("        <sudden-death>");
                    if (!settings.isDefaultSuddenDeathTime()) {
                        out.println("          <time>" + settings.getSuddenDeathTime() + "</time>");
                    }
                    if (!settings.isDefaultSuddenDeathMessage()) {
                        out.println("          <message>" + settings.getSuddenDeathMessage() + "</message>");
                    }
                    if (!settings.isDefaultSuddenDeathDelay()) {
                        out.println("          <delay>" + settings.getSuddenDeathDelay() + "</delay>");
                    }
                    if (!settings.isDefaultSuddenDeathLinesAdded()) {
                        out.println("          <lines-added>" + settings.getSuddenDeathLinesAdded()
                                + "</lines-added>");
                    }
                    out.println("        </sudden-death>");
                }

                out.println("      </settings>");
            }

            // local filters
            Collection<MessageFilter> filters = channel.getLocalFilters();
            if (!filters.isEmpty()) {
                out.println("      <filters>");
                for (MessageFilter filter : filters) {
                    saveFilter(filter.getConfig(), out, "        ");
                }
                out.println("      </filters>");
            }

            out.println("    </channel>");
            out.println();
        }
    }

    out.println("  </channels>");
    out.println();
    out.println("</tetrinet-channels>");

    out.close();
}

From source file:org.jahia.services.usermanager.ldap.LDAPUserGroupProvider.java

private ContainerCriteria getGroupQuery(Properties searchCriteria, boolean isDynamic) {
    ContainerCriteria query = null;//from w w  w.j ava 2s .  co m
    if (searchCriteria.isEmpty()) {
        // we once build and reuse the queries in case of empty search criteria
        if (isDynamic) {
            if (searchGroupDynamicCriteria == null) {
                searchGroupDynamicCriteria = buildGroupQuery(searchCriteria, isDynamic);
            }
            query = searchGroupDynamicCriteria;
        } else {
            if (searchGroupCriteria == null) {
                searchGroupCriteria = buildGroupQuery(searchCriteria, isDynamic);
            }
            query = searchGroupCriteria;
        }
    } else {
        query = buildGroupQuery(searchCriteria, isDynamic);
    }

    return query;
}