Example usage for java.util Queue size

List of usage examples for java.util Queue size

Introduction

In this page you can find the example usage for java.util Queue size.

Prototype

int size();

Source Link

Document

Returns the number of elements in this collection.

Usage

From source file:com.mirth.connect.plugins.datapruner.DataPruner.java

@Override
public void run() {
    try {//from www  .j  a v a 2 s . c om
        logger.debug("Executing pruner, started at "
                + new SimpleDateFormat("MM/dd/yyyy hh:mm aa").format(Calendar.getInstance().getTime()));

        if (pruneEvents) {
            pruneEvents();
        }

        String date = new SimpleDateFormat(MessageWriterFactory.ARCHIVE_DATE_PATTERN)
                .format(Calendar.getInstance().getTime());
        String archiveFolder = (archiveEnabled) ? archiverOptions.getRootFolder() + IOUtils.DIR_SEPARATOR + date
                : null;
        Queue<PrunerTask> taskQueue;

        try {
            taskQueue = buildTaskQueue();
        } catch (Exception e) {
            // the error should already be logged
            return;
        }

        logger.debug("Pruner task queue built, " + taskQueue.size() + " channels will be processed");

        Map<String, String> attributes = new HashMap<String, String>();
        if (taskQueue.isEmpty()) {
            attributes.put("No messages to prune.", "");
            eventController.dispatchEvent(new ServerEvent(serverId, DataPrunerService.PLUGINPOINT,
                    Level.INFORMATION, Outcome.SUCCESS, attributes));
        }

        while (!taskQueue.isEmpty()) {
            ThreadUtils.checkInterruptedStatus();
            PrunerTask task = taskQueue.poll();

            try {
                status.setCurrentChannelId(task.getChannelId());
                status.setCurrentChannelName(task.getChannelName());
                status.setTaskStartTime(Calendar.getInstance());

                PruneResult result = pruneChannel(task.getChannelId(), task.getChannelName(),
                        task.getMessageDateThreshold(), task.getContentDateThreshold(), archiveFolder,
                        task.isArchiveEnabled());

                status.getProcessedChannelIds().add(task.getChannelId());

                attributes.put("Channel ID", task.getChannelId());
                attributes.put("Channel Name", task.getChannelName());

                if (archiveEnabled && task.isArchiveEnabled()) {
                    attributes.put("Messages Archived", Long.toString(result.numMessagesArchived));
                }

                attributes.put("Messages Pruned", Long.toString(result.numMessagesPruned));
                attributes.put("Content Rows Pruned", Long.toString(result.numContentPruned));
                attributes.put("Time Elapsed", getTimeElapsed());
                eventController.dispatchEvent(new ServerEvent(serverId, DataPrunerService.PLUGINPOINT,
                        Level.INFORMATION, Outcome.SUCCESS, attributes));
            } catch (InterruptedException e) {
                throw e;
            } catch (Exception e) {
                status.getFailedChannelIds().add(task.getChannelId());

                attributes.put("channel", task.getChannelName());
                attributes.put("error", e.getMessage());
                attributes.put("trace", ExceptionUtils.getStackTrace(e));
                eventController.dispatchEvent(new ServerEvent(serverId, DataPrunerService.PLUGINPOINT,
                        Level.ERROR, Outcome.FAILURE, attributes));
                Throwable t = e;
                if (e instanceof DataPrunerException) {
                    t = e.getCause();
                }
                logger.error("Failed to prune messages for channel " + task.getChannelName() + " ("
                        + task.getChannelId() + ").", t);
            } finally {
                status.getPendingChannelIds().remove(task.getChannelId());
                status.setCurrentChannelId(null);
                status.setCurrentChannelName(null);
            }
        }

        logger.debug("Pruner job finished executing");
    } catch (InterruptedException e) {
        // We need to clear this thread's interrupted status, or else the EventController will fail to dispatch the event
        Thread.interrupted();
        ServerEvent event = new ServerEvent(serverId, DataPrunerService.PLUGINPOINT + " Halted");
        event.setLevel(Level.INFORMATION);
        event.setOutcome(Outcome.SUCCESS);
        eventController.dispatchEvent(event);
        logger.debug("Data Pruner halted");
    } catch (Throwable t) {
        logger.error("An error occurred while executing the data pruner", t);
    } finally {
        status.setEndTime(Calendar.getInstance());
        lastStatus = SerializationUtils.clone(status);
        running.set(false);
    }
}

From source file:it.geosolutions.geobatch.imagemosaic.ImageMosaicAction.java

/**
 * Public or update an ImageMosaic layer on the specified GeoServer
 *///from   w  ww  .  j a v  a  2s.co m
public Queue<EventObject> execute(Queue<EventObject> events) throws ActionException {

    if (LOGGER.isInfoEnabled())
        LOGGER.info("Start processing...");

    listenerForwarder.started();

    try {
        // looking for file
        if (events == null)
            throw new IllegalArgumentException("Unable to execute action with incoming null parameter");
        if (events.size() == 0)
            throw new IllegalArgumentException("Wrong number of elements for this action: " + events.size());

        /*
         * If here: we can execute the action
         */
        Queue<EventObject> ret = new LinkedList<EventObject>();

        /**
         * For each event into the queue
         */
        while (events.size() > 0) {
            final Object evObj = events.remove();

            /**
             * If the input file exists and it is a file: Check if it is: -
             * A Directory - An XML -> Serialized ImageMosaicCommand
             * 
             * Building accordingly the ImageMosaicCommand command.
             */
            final ImageMosaicCommand cmd;

            if (evObj == null) {
                ActionExceptionHandler.handleError(getConfiguration(), this, "Input null object.");
                continue;
            }

            if (evObj instanceof FileSystemEvent) {
                /*
                 * Checking input files.
                 */
                final File input = ((FileSystemEvent) evObj).getSource();
                if (!input.exists()) {
                    // no file is found for this event try with the next one
                    ActionExceptionHandler.handleError(getConfiguration(), this,
                            "The input file does not exists at url: " + input.getAbsolutePath());
                    continue;
                }

                /**
                 * the file event points to an XML file...
                 * 
                 * @see ImageMosaicCommand
                 */
                if (input.isFile() && FilenameUtils.getExtension(input.getName()).equalsIgnoreCase("xml")) {
                    if (LOGGER.isInfoEnabled()) {
                        LOGGER.info("Working on an XML command file: " + input.getAbsolutePath());
                    }

                    // try to deserialize
                    cmd = ImageMosaicCommand.deserialize(input.getAbsoluteFile());
                    if (cmd == null) {
                        ActionExceptionHandler.handleError(getConfiguration(), this,
                                "Unable to deserialize the passed file: " + input.getAbsolutePath());
                        continue;
                    }

                } else if (input.isDirectory()) {
                    if (LOGGER.isInfoEnabled()) {
                        LOGGER.info("Input file event points to a directory: " + input.getAbsolutePath());
                    }
                    String format = ((ImageMosaicConfiguration) super.getConfiguration()).getGranuleFormat();
                    if (format == null || format.isEmpty()) {
                        LOGGER.warn(
                                "No granule format specified in flow configuration... try force it to .tif");
                        format = "tif";
                    }
                    StringBuilder builder = new StringBuilder();
                    builder.append("*.");
                    builder.append(format);
                    final Collector coll = new Collector(
                            new WildcardFileFilter(builder.toString(), IOCase.INSENSITIVE));
                    // try to deserialize
                    cmd = new ImageMosaicCommand(input, coll.collect(input), null);
                } else {
                    // the file event does not point to a directory nor to an xml file
                    ActionExceptionHandler.handleError(getConfiguration(), this,
                            "The file event does not point to a directory nor to an xml file: "
                                    + input.getAbsolutePath());
                    continue;
                }
            } else if (evObj instanceof EventObject) {
                Object innerObject = ((EventObject) evObj).getSource();
                if (innerObject instanceof ImageMosaicCommand) {
                    cmd = (ImageMosaicCommand) innerObject;
                } else {
                    // the file event does not point to a directory nor to an xml file
                    ActionExceptionHandler.handleError(getConfiguration(), this,
                            "The file event does not point to a valid object: " + evObj);
                    continue;
                }
            } else {
                // the file event does not point to a directory nor to an xml file
                ActionExceptionHandler.handleError(getConfiguration(), this,
                        "The file event does not point to a valid object: " + evObj);
                continue;
            }

            /**
             * the file pointing to the directory which the layer will refer
             * to.
             */
            final File baseDir = cmd.getBaseDir();
            /**
             * a descriptor for the mosaic to handle
             */
            final ImageMosaicGranulesDescriptor mosaicDescriptor = ImageMosaicGranulesDescriptor
                    .buildDescriptor(baseDir, getConfiguration());

            if (mosaicDescriptor == null) {
                ActionExceptionHandler.handleError(getConfiguration(), this,
                        "Unable to build the imageMosaic descriptor" + cmd.getBaseDir());
                continue;
            }

            // Perform tests on the base dir file
            if (!baseDir.exists() || !baseDir.isDirectory()) {
                // no base dir exists try to build a new one using
                // addList()
                if (cmd.getAddFiles() != null) {
                    if (cmd.getAddFiles().size() > 0) {
                        // try build the baseDir
                        if (!baseDir.mkdirs()) {
                            ActionExceptionHandler.handleError(getConfiguration(), this,
                                    "Unable to create the base directory named \'" + baseDir.getAbsolutePath()
                                            + "\'.");
                            continue;
                        }
                    } else {
                        final StringBuilder msg = new StringBuilder();
                        msg.append("Unexpected not existent baseDir for this layer '")
                                .append(baseDir.getAbsolutePath())
                                .append("'.\n If you want to build a new layer try using an ")
                                .append("existent or writeable baseDir and append a list of file to use to the addFile list.");
                        ActionExceptionHandler.handleError(getConfiguration(), this, msg.toString());
                        continue;
                    }
                } else {
                    final StringBuilder msg = new StringBuilder();
                    msg.append("Unexpected not existent baseDir for this layer '")
                            .append(baseDir.getAbsolutePath())
                            .append("'.\n If you want to build a new layer try using an ")
                            .append("existent or writeable baseDir and append a list of file to use to the addFile list.");
                    ActionExceptionHandler.handleError(getConfiguration(), this, msg.toString());
                    continue;
                }
            }

            // override local cmd null params with the getConfiguration()
            cmd.copyConfigurationIntoCommand(getConfiguration());

            // prepare configuration for layername and storename
            final String layerName;
            if (cmd.getLayerName() == null) {
                layerName = baseDir.getName();
                cmd.setLayerName(layerName);
            } else {
                layerName = cmd.getLayerName();
            }
            final String storeName;
            if (cmd.getStoreName() == null) {
                storeName = layerName;
                cmd.setStoreName(storeName);
            } else {
                storeName = cmd.getStoreName();
            }

            /**
             * HERE WE HAVE A 'cmd' COMMAND FILE WHICH MAY HAVE GETADDFILE
             * OR GETDELFILE !=NULL USING THOSE LIST WE MAY:<br>
             * DEL ->DELETE FROM THE DATASTORE AN IMAGE USING THE ABSOLUTE
             * PATH.<br>
             * ADD ->INSERT INTO THE DATASTORE AN IMAGE USING THE ABSOLUTE
             * PATH.<br>
             */
            // REST library read
            GeoServerRESTReader gsReader = new GeoServerRESTReader(cmd.getGeoserverURL(), cmd.getGeoserverUID(),
                    cmd.getGeoserverPWD());
            // REST library write
            final GeoServerRESTPublisher gsPublisher = new GeoServerRESTPublisher(cmd.getGeoserverURL(),
                    cmd.getGeoserverUID(), cmd.getGeoserverPWD());

            final String workspace = cmd.getDefaultNamespace() != null ? cmd.getDefaultNamespace() : "";

            /*
             * Check if ImageMosaic layer already exists...
             */
            final boolean layerExists;

            if (cmd.getIgnoreGeoServer()) {
                if (LOGGER.isInfoEnabled()) {
                    LOGGER.info(
                            "GeoServer will be ignored by configuration. Assuming that an updated is required. ");
                }
                layerExists = true;
            } else {
                final RESTLayer layer = gsReader.getLayer(layerName);
                layerExists = layer != null;
            }

            if (layerExists) {
                if (!updateMosaicLayer(cmd, baseDir, layerName, mosaicDescriptor, gsPublisher)) {
                    ActionExceptionHandler.handleError(getConfiguration(), this, "Mosaic not Updated...");
                    continue;
                }

            } else {
                if (!createMosaicLayer(cmd, baseDir, workspace, mosaicDescriptor, layerName, gsPublisher,
                        storeName)) {
                    ActionExceptionHandler.handleError(getConfiguration(), this, "Mosaic not Created...");
                    continue;
                }
            }

            /**
             * The returned file: - one for each event - .layer file - will
             * be added to the output queue
             */
            final File layerDescriptor;

            // generate a RETURN file and append it to the return queue
            // TODO get info about store and workspace name...
            layerDescriptor = ImageMosaicOutput.writeReturn(baseDir, baseDir, cmd);
            if (layerDescriptor != null) {
                LOGGER.info("Created layer descriptor file " + layerDescriptor);
                ret.add(new FileSystemEvent(layerDescriptor, FileSystemEventType.FILE_ADDED));
            }

        } // while

        listenerForwarder.completed();

        // ... setting up the appropriate event for the next action
        return ret;

    } catch (Exception t) {
        if (LOGGER.isErrorEnabled())
            LOGGER.error(t.getLocalizedMessage(), t);
        listenerForwarder.failed(t);
        throw new ActionException(this, t.getMessage(), t);
    }
}

From source file:voldemort.tools.KeyVersionFetcherCLI.java

public boolean sampleStore(StoreDefinition storeDefinition) {
    String storeName = storeDefinition.getName();

    String keysFileName = inDir + System.getProperty("file.separator") + storeName + ".keys";
    File keysFile = new File(keysFileName);
    if (!keysFile.exists()) {
        logger.error("Keys file " + keysFileName + " does not exist!");
        return false;
    }/*from ww  w  .  j a  v a2 s.c o  m*/

    String kvFileName = outDir + System.getProperty("file.separator") + storeName + ".kvs";
    File kvFile = new File(kvFileName);
    if (kvFile.exists()) {
        logger.info("Key-Version file " + kvFileName + " exists, so will not sample keys from file "
                + keysFileName + ".");
        return true;
    }

    BaseStoreRoutingPlan storeRoutingPlan = new BaseStoreRoutingPlan(cluster, storeDefinition);
    BufferedReader keyReader = null;
    BufferedWriter kvWriter = null;
    try {
        keyReader = new BufferedReader(new FileReader(keysFileName));
        kvWriter = new BufferedWriter(new FileWriter(kvFileName));

        boolean readAllKeys = false;
        while (!readAllKeys) {
            Queue<Future<String>> futureKVs = new LinkedList<Future<String>>();
            for (int numFetchTasks = 0; numFetchTasks < this.outputBatchSize; numFetchTasks++) {
                String keyLine = keyReader.readLine();
                if (keyLine == null) {
                    readAllKeys = true;
                    break;
                }
                byte[] keyInBytes = ByteUtils.fromHexString(keyLine.trim());
                FetchKeyVersionsTask kvFetcher = new FetchKeyVersionsTask(storeRoutingPlan, keyInBytes);
                Future<String> future = kvFetcherService.submit(kvFetcher);
                futureKVs.add(future);
            }

            if (futureKVs.size() > 0) {
                while (!futureKVs.isEmpty()) {
                    Future<String> future = futureKVs.poll();
                    String keyVersions = future.get();
                    kvWriter.append(keyVersions);
                }
            }
        }
        return true;
    } catch (DecoderException de) {
        logger.error("Could not decode key to sample for store " + storeName, de);
        return false;
    } catch (IOException ioe) {
        logger.error("IOException caught while sampling store " + storeName, ioe);
        return false;
    } catch (InterruptedException ie) {
        logger.error("InterruptedException caught while sampling store " + storeName, ie);
        return false;
    } catch (ExecutionException ee) {
        logger.error("Encountered an execution exception while sampling " + storeName, ee);
        ee.printStackTrace();
        return false;
    } finally {
        if (keyReader != null) {
            try {
                keyReader.close();
            } catch (IOException e) {
                logger.error("IOException caught while trying to close keyReader for store " + storeName, e);
                e.printStackTrace();
            }
        }
        if (kvWriter != null) {
            try {
                kvWriter.close();
            } catch (IOException e) {
                logger.error("IOException caught while trying to close kvWriter for store " + storeName, e);
                e.printStackTrace();
            }
        }
    }
}

From source file:org.hyperic.hq.product.JDBCMeasurementPlugin.java

protected Connection getCachedConnection(String url, String user, String pass) throws SQLException {
    String cacheKey = calculateKey(url, user, pass);
    Connection conn;//from   w w  w .  j  a  v a2s  .  c om
    Queue<Connection> pool;

    synchronized (connectionPools) {
        pool = connectionPools.get(cacheKey);
        if (pool == null) {
            pool = new ConcurrentLinkedQueue<Connection>();
            connectionPools.put(cacheKey, pool);
            log.debug("[getCC] Pool for '" + cacheKey + "' created");
        }
    }

    int count = 0;
    while (((conn = pool.poll()) == null) && (count++ < 5)) {
        try {
            Thread.sleep(100);
        } catch (InterruptedException ex) {
            log.error(ex, ex);
        }
    }

    if (conn == null) {
        conn = getConnection(url, user, pass);
        log.debug("[getCC] Connection for '" + cacheKey + "' created (pool.size=" + pool.size() + ")");
    }
    log.debug("[getCC] Connection for '" + cacheKey + "' used (pool.size=" + pool.size() + ")");
    return conn;
}

From source file:it.geosolutions.geobatch.geoserver.shapefile.ShapeFileAction.java

/**
 *
 *//*from   w w w  .ja  v a  2s .  com*/
public Queue<EventObject> execute(Queue<EventObject> events) throws ActionException {

    listenerForwarder.setTask("config");
    listenerForwarder.started();

    try {
        //
        // Initializing input variables
        //
        GeoServerActionConfiguration configuration = getConfiguration();
        if (configuration == null) {
            throw new IllegalStateException("ActionConfig is null.");
        }

        // how many files do we have?
        final int inputSize = events.size();

        // Fetch the first event in the queue.
        // We may have one in these 2 cases:
        // 1) a single event for a .zip file
        // 2) a list of events for a (.shp+.dbf+.shx) collection, plus some other optional files
        final EventObject event = events.peek();

        // the name of the shapefile
        String[] shapeNames;

        // the output (to send to the geoserver) file
        File zippedFile = null;

        // upload method to use
        it.geosolutions.geobatch.geoserver.UploadMethod transferMethod = it.geosolutions.geobatch.geoserver.UploadMethod
                .valueOf(configuration.getDataTransferMethod());
        if (transferMethod == null) {
            transferMethod = it.geosolutions.geobatch.geoserver.UploadMethod.getDefault(); // default one
        }

        // list of file to send to the GeoServer
        File[] files = null;
        File tmpDirFile = null;
        Integer epsgCode = null;
        GeometryDescriptor descriptor = null;
        CoordinateReferenceSystem crs = null;

        if (inputSize == 1) {
            //
            // SINGLE FILE, is a zip or throw error
            //
            zippedFile = toFile(event);
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("Testing for compressed file: " + zippedFile);

            // try to extract
            tmpDirFile = Extract.extract(zippedFile, getTempDir(), false);
            listenerForwarder.progressing(5, "File extracted");

            //if the output (Extract) file is not a dir the event was a not compressed file so
            //we have to throw and error
            if (tmpDirFile == null) {
                throw new IllegalStateException("Not valid input: we need a zip file ");
            }

            if (!tmpDirFile.isDirectory()) {
                if (!tmpDirFile.isFile()) {
                    throw new IllegalStateException("Not valid input: we need a zip file ");
                } else {
                    tmpDirFile = tmpDirFile.getParentFile();
                }
            }

            // collect extracted files
            final Collector c = new Collector(
                    FileFilterUtils.notFileFilter(FileFilterUtils.nameFileFilter(tmpDirFile.getName()))); // no filter
            final List<File> fileList = c.collect(tmpDirFile);
            files = fileList.toArray(new File[1]);

            // Check if there is at least one shp there
            shapeNames = acceptable(files);

        } else {
            //
            // Multiple separated files, let's look for the right one
            //
            if (LOGGER.isTraceEnabled())
                LOGGER.trace("Checking input collection...");

            listenerForwarder.progressing(5, "Checking input collection...");

            // collect files
            files = new File[events.size()];
            int i = 0;
            for (EventObject ev : events) {
                files[i++] = toFile(ev);
            }

            // Get tmp dir from the absolute path of the first captured file
            tmpDirFile = new File(FilenameUtils.getFullPath(files[0].getAbsolutePath()));

            // Check for shapefile names
            shapeNames = acceptable(files);

            // zip to a single file if method is not external.
            // Will use the first shapeName as the zip name.
            if (transferMethod != it.geosolutions.geobatch.geoserver.UploadMethod.EXTERNAL) {
                zippedFile = Compressor.deflate(getTempDir(), shapeNames[0], files);
                if (zippedFile == null) {
                    throw new IllegalStateException("Unable to create the zip file");
                }
            }

        }

        // check that we actually found some shapefiles
        if (shapeNames == null) {
            final String message = "Input is not a zipped file nor a valid collection of files";
            if (LOGGER.isErrorEnabled())
                LOGGER.error(message);
            throw new IllegalStateException(message);
        }

        // do some additional checks and look for some ausillary information
        for (String shape : shapeNames) {
            FileDataStore store = null;

            try {
                // create a shapefile datastore
                store = Utils.SHP_FACTORY.createDataStore(new File(tmpDirFile, shape + ".shp").toURI().toURL());

                // get the CRS
                crs = store.getSchema().getCoordinateReferenceSystem();
                epsgCode = crs != null ? CRS.lookupEpsgCode(crs, false) : null;

                // get the geometry
                descriptor = store.getSchema().getGeometryDescriptor();
            } finally {
                if (store != null) {
                    try {
                        store.dispose();
                    } catch (Exception e) {
                        if (LOGGER.isTraceEnabled()) {
                            LOGGER.trace(e.getLocalizedMessage(), e);
                        }
                    }
                }
            }
        }
        listenerForwarder.progressing(10, "In progress");

        GeoServerRESTReader reader = new GeoServerRESTReader(configuration.getGeoserverURL(),
                configuration.getGeoserverUID(), configuration.getGeoserverPWD());
        GeoServerRESTPublisher publisher = new GeoServerRESTPublisher(configuration.getGeoserverURL(),
                configuration.getGeoserverUID(), configuration.getGeoserverPWD());

        WorkspaceUtils.createWorkspace(reader, publisher, configuration.getDefaultNamespace(),
                configuration.getDefaultNamespaceUri());

        // TODO: check if a layer with the same name already exists in GS
        // TODO: Handle CRSs for multiple files
        // TODO: Handle styles for multiple files (see comment on #16)

        // decide CRS
        String nativeCRS = null;
        ProjectionPolicy projectionPolicy = ProjectionPolicy.NONE; // by default we do nothing
        final String defaultCRS = configuration.getCrs(); //do we have a default crs in the config
        String finalEPSGCode = defaultCRS; // this is the SRS for this shape

        // retain original CRS if the code is there
        if (epsgCode == null) {
            // we do not have a valid EPSG code in the input file, we do need one as per default
            if (finalEPSGCode == null) {
                final String message = "Input file has no CRS neither the configuration provides a default one";
                final ActionException ae = new ActionException(this, message);
                if (LOGGER.isErrorEnabled())
                    LOGGER.error(message, ae);
                listenerForwarder.failed(ae);
                throw ae;
            }

            // we do have a default, let's choose the proper CRS management
            if (crs != null) {
                // we have a WKT native crs, let's use it
                nativeCRS = crs.toWKT();
                projectionPolicy = ProjectionPolicy.REPROJECT_TO_DECLARED;
            } else {
                projectionPolicy = ProjectionPolicy.FORCE_DECLARED;
            }

        } else {
            // we do have an EPSG code for the original CRS, do nothing
            finalEPSGCode = "EPSG:" + epsgCode;
            nativeCRS = finalEPSGCode;
        }

        // check style for this geometry
        String defaultStyle = configuration.getDefaultStyle();
        if (defaultStyle == null || defaultStyle.isEmpty()) {
            final GeometryType geometryType = descriptor.getType();
            Class clazz = geometryType.getBinding();
            if (clazz.isAssignableFrom(Point.class) || clazz.isAssignableFrom(MultiPoint.class)) {
                defaultStyle = Utils.DEFAULT_POINT_STYLE;
            } else if (clazz.isAssignableFrom(LineString.class)
                    || clazz.isAssignableFrom(MultiLineString.class)) {
                defaultStyle = Utils.DEFAULT_LINE_STYLE;
            } else if (clazz.isAssignableFrom(Polygon.class) || clazz.isAssignableFrom(MultiPolygon.class)) {
                defaultStyle = Utils.DEFAULT_POLYGON_STYLE;
            }
        }

        UploadMethod uMethod = null;
        switch (transferMethod) {
        case DIRECT:
            uMethod = UploadMethod.FILE;
            break;
        case EXTERNAL:
            uMethod = UploadMethod.EXTERNAL;
            break;
        default:
            throw new IllegalArgumentException(
                    "Unsupported transfer method: " + configuration.getDataTransferMethod());
        }

        // Get some common parameters
        String wsName = configuration.getDefaultNamespace();
        String dsName = configuration.getStoreName() == null ? shapeNames[0] : configuration.getStoreName();
        String lyrName = configuration.getLayerName() == null ? shapeNames[0] : configuration.getLayerName();
        String styleName = defaultStyle;

        //
        // SENDING data to GeoServer via REST protocol.
        //
        boolean success = false;

        // Either publish a single shapefile, or a collection of shapefiles
        if (shapeNames.length == 1) {
            success = publisher.publishShp(wsName, dsName, null, lyrName, uMethod, zippedFile.toURI(),
                    finalEPSGCode, nativeCRS, projectionPolicy, styleName);
        } else {
            success = publisher.publishShpCollection(wsName, dsName, zippedFile.toURI());
        }

        if (success) {
            final String message = "Shape file SUCCESFULLY sent";
            if (LOGGER.isInfoEnabled())
                LOGGER.info(message);
            listenerForwarder.progressing(90, message);
        } else {
            final String message = "Shape file FAILED to be sent";
            final ActionException ae = new ActionException(this, message);
            if (LOGGER.isErrorEnabled())
                LOGGER.error(message, ae);
            listenerForwarder.failed(ae);
            throw ae;
        }

        // If we have shape specific config, apply now
        if (configuration instanceof GeoServerShapeActionConfiguration) {
            // Log
            if (LOGGER.isInfoEnabled())
                LOGGER.info("Configuring shape datastore connection parameters");

            // Get config
            GeoServerShapeActionConfiguration shpConfig = (GeoServerShapeActionConfiguration) configuration;

            // Get managers from geoserver-manager
            GeoServerRESTManager manager = new GeoServerRESTManager(new URL(shpConfig.getGeoserverURL()),
                    shpConfig.getGeoserverUID(), shpConfig.getGeoserverPWD());
            GeoServerRESTStoreManager dsManager = manager.getStoreManager();

            // Read config from GS
            RESTDataStore dsRead = manager.getReader().getDatastore(wsName, dsName);
            GSShapefileDatastoreEncoder dsWrite = new GSShapefileDatastoreEncoder(dsRead);

            // Update store params
            if (shpConfig.getUrl() != null)
                dsWrite.setUrl(shpConfig.getUrl());
            if (shpConfig.getCharset() != null)
                dsWrite.setCharset(shpConfig.getCharset());
            if (shpConfig.getCreateSpatialIndex() != null)
                dsWrite.setCreateSpatialIndex(shpConfig.getCreateSpatialIndex());
            if (shpConfig.getMemoryMappedBuffer() != null)
                dsWrite.setMemoryMappedBuffer(shpConfig.getMemoryMappedBuffer());
            if (shpConfig.getCacheAndReuseMemoryMaps() != null)
                dsWrite.setCacheAndReuseMemoryMaps(shpConfig.getCacheAndReuseMemoryMaps());

            // Push changes to GS
            success = dsManager.update(wsName, dsWrite);

            // Success or die
            if (success) {
                String message = "Shape datastore SUCCESFULLY configured";
                if (LOGGER.isInfoEnabled())
                    LOGGER.info(message);
                listenerForwarder.progressing(100, message);
            } else {
                String message = "Shape datastore FAILED to be configured";
                final ActionException ae = new ActionException(this, message);
                if (LOGGER.isErrorEnabled())
                    LOGGER.error(message, ae);
                listenerForwarder.failed(ae);
                throw ae;
            }
        }

        return events;

    } catch (Throwable t) {
        final ActionException ae = new ActionException(this, t.getMessage(), t);
        if (LOGGER.isErrorEnabled())
            LOGGER.error(ae.getLocalizedMessage(), ae);
        listenerForwarder.failed(ae); // fails the Action
        throw ae;
    }
}

From source file:org.geoserver.wms.legendgraphic.ColorMapLegendCreator.java

private BufferedImage mergeRows(Queue<BufferedImage> legendsQueue) {
    // I am doing a straight cast since I know that I built this
    // dimension object by using the widths and heights of the various
    // bufferedimages for the various bkgColor map entries.
    final Dimension finalDimension = new Dimension();
    final int numRows = legendsQueue.size();
    finalDimension.setSize(Math.max(footerW, colorW + ruleW + labelW) + 2 * dx + 2 * margin,
            rowH * numRows + 2 * margin + (numRows - 1) * dy);

    final int totalWidth = (int) finalDimension.getWidth();
    final int totalHeight = (int) finalDimension.getHeight();
    BufferedImage finalLegend = ImageUtils.createImage(totalWidth, totalHeight, (IndexColorModel) null,
            transparent);/*w  ww .  j ava 2 s  .c om*/

    /*
     * For RAMP type, only HORIZONTAL or VERTICAL condition is valid
     */
    if (colorMapType == ColorMapType.RAMP) {

        final Map<Key, Object> hintsMap = new HashMap<Key, Object>();
        Graphics2D finalGraphics = ImageUtils.prepareTransparency(transparent, backgroundColor, finalLegend,
                hintsMap);
        hintsMap.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        finalGraphics.setRenderingHints(hintsMap);

        int topOfRow = (int) (margin + 0.5);
        for (int i = 0; i < numRows; i++) {
            final BufferedImage img = legendsQueue.remove();

            // draw the image
            finalGraphics.drawImage(img, (int) (margin + 0.5), topOfRow, null);
            topOfRow += img.getHeight() + dy;

        }

        if (this.layout == LegendLayout.HORIZONTAL) {
            BufferedImage newImage = new BufferedImage(totalHeight, totalWidth, finalLegend.getType());
            Graphics2D g2 = newImage.createGraphics();
            g2.rotate(-Math.PI / 2, 0, 0);
            g2.drawImage(finalLegend, null, -totalWidth, 0);
            finalLegend = newImage;
            g2.dispose();
            finalGraphics.dispose();
        }
    } else {
        List<RenderedImage> imgs = new ArrayList<RenderedImage>(legendsQueue);

        LegendMerger.MergeOptions options = new LegendMerger.MergeOptions(imgs, (int) dx, (int) dy,
                (int) margin, 0, backgroundColor, transparent, true, layout, rowWidth, rows, columnHeight,
                columns, null, false, false);
        finalLegend = LegendMerger.mergeRasterLegends(options);
    }

    return finalLegend;

}

From source file:cosmos.sql.TestSql.java

@Test
public void testNoLimit() throws SQLException {
    loadDriverClass();//from ww  w  . j av a 2s. co m
    Connection connection = null;
    Statement statement = null;
    try {
        Properties info = new Properties();
        info.put("url", JDBC_URL);
        info.put("user", USER);
        info.put("password", PASSWORD);
        connection = DriverManager.getConnection("jdbc:accumulo:cosmos//localhost", info);
        statement = connection.createStatement();
        final ResultSet resultSet = statement.executeQuery(
                "select \"PAGE_ID\" from \"" + CosmosDriver.COSMOS + "\".\"" + meataData.uuid() + "\"");

        final ResultSetMetaData metaData = resultSet.getMetaData();
        final int columnCount = metaData.getColumnCount();

        assertEquals(columnCount, 1);

        int resultsFound = 0;
        SortedSet<String> sets = Sets.newTreeSet();
        for (int i = 0; i < 10; i++) {
            sets.add(Integer.valueOf(i).toString());
        }
        Queue<String> values = Lists.newLinkedList(sets);

        while (resultSet.next()) {
            assertEquals(metaData.getColumnName(1), "PAGE_ID");
            @SuppressWarnings("unchecked")
            List<Entry<Column, RecordValue<?>>> sValues = (List<Entry<Column, RecordValue<?>>>) resultSet
                    .getObject("PAGE_ID");
            assertEquals(sValues.size(), 1);
            RecordValue<?> onlyValue = sValues.iterator().next().getValue();
            assertEquals(onlyValue.visibility().toString(), "[en]");
            values.remove(onlyValue.value());
            resultsFound++;

        }

        assertEquals(resultsFound, 10);
        assertEquals(values.size(), 0);
    } finally {
        close(connection, statement);
    }
}

From source file:candr.yoclip.ParserTest.java

@Test
public void getParsedOptionProperty() {
    final ParserOption<ParserTest> mockOptionProperty = createMockOptionProperty("T");
    final List<ParserOption<ParserTest>> parserOptions = Arrays.asList(mockOptionProperty);

    final ParserOptions<ParserTest> mockParserOptions = createMockParserParameters("++");
    when(mockParserOptions.get()).thenReturn(parserOptions);
    when(mockParserOptions.get("T")).thenReturn(mockOptionProperty);

    final Queue<String> parameters = new LinkedList<String>();

    final Parser<ParserTest> testCase = new Parser<ParserTest>(mockParserOptions,
            createMockParserHelpFactory());
    assertThat("empty queue", testCase.getParsedOptionProperty(parameters), nullValue());

    final String expectedArgument = "argument";
    parameters.add(expectedArgument);/* w  ww . j  av  a 2s  .c o m*/
    assertThat("parsed parameter with argument", testCase.getParsedOptionProperty(parameters), nullValue());
    assertThat("queue size after parsed parameter error", parameters.size(), is(1));

    parameters.clear();
    parameters.add("++Tfoo=bar");
    final ParsedOption<ParserTest> parsedOption = testCase.getParsedOptionProperty(parameters);
    assertThat("ParsedOption error", parsedOption.isError(), is(false));
    assertThat("parser option", parsedOption.getParserOption(), is(mockOptionProperty));
    assertThat("value", parsedOption.getValue(), is("foo=bar"));
    assertThat("queue size after parsed parameter", parameters.size(), is(0));

    parameters.add("++Dfoo=bar");
    assertThat("property not matched", testCase.getParsedOptionProperty(parameters), nullValue());
}

From source file:candr.yoclip.ParserTest.java

@Test
public void getParsedArgument() {
    final ParserOptions<ParserTest> mockParserOptions = createMockParserParameters();

    final Queue<String> parameters = new LinkedList<String>();

    final Parser<ParserTest> testCase = new Parser<ParserTest>(mockParserOptions,
            createMockParserHelpFactory());
    assertThat("empty queue", testCase.getParsedArgument(parameters), nullValue());

    final String expectedParameter = "argument parameter";
    parameters.add(expectedParameter);/*from  w  w  w  . j a v a2 s.  c  om*/
    ParsedOption<ParserTest> parsedOption = testCase.getParsedArgument(parameters);
    assertThat("parsed parameter error", parsedOption.isError(), is(true));
    assertThat("queue size after parsed parameter error", parameters.size(), is(0));

    final ParserOption<ParserTest> mockArguments = createMockArguments();
    when(mockParserOptions.getArguments()).thenReturn(mockArguments);

    final String remainingParameter = "remaining parameter";
    parameters.add(expectedParameter);
    parameters.add(remainingParameter);
    parsedOption = testCase.getParsedArgument(parameters);
    assertThat("parsed parameter not error", parsedOption.isError(), is(false));
    assertThat("parser parameter", parsedOption.getParserOption(), is(mockArguments));
    assertThat("value", parsedOption.getValue(), is(expectedParameter));
    assertThat("queue size", parameters.size(), is(1));
    assertThat("remaining parameter", parameters.remove(), is(remainingParameter));
}

From source file:org.geotools.gce.imagemosaic.Utils.java

/**
 * Creates a mosaic for the provided input parameters.
 * //from  w w  w  . j  a v a 2  s.  com
 * @param location
 *            path to the directory where to gather the elements for the
 *            mosaic.
 * @param indexName
 *            name to give to this mosaic
 * @param wildcard
 *            wildcard to use for walking through files. We are using
 *            commonsIO for this task
 * @param absolutePath
 *            tells the catalogue builder to use absolute paths.
 * @param hints hints to control reader instantiations
 * @return <code>true</code> if everything is right, <code>false</code>if
 *         something bad happens, in which case the reason should be logged
 *         to the logger.
 */
static boolean createMosaic(final String location, final String indexName, final String wildcard,
        final boolean absolutePath, final Hints hints) {

    // create a mosaic index builder and set the relevant elements
    final CatalogBuilderConfiguration configuration = new CatalogBuilderConfiguration();
    configuration.setAbsolute(absolutePath);
    configuration.setHints(hints);
    configuration.setRootMosaicDirectory(location);
    configuration.setIndexingDirectories(Arrays.asList(location));
    configuration.setIndexName(indexName);

    // create the builder
    final CatalogBuilder catalogBuilder = new CatalogBuilder(configuration);
    // this is going to help us with catching exceptions and logging them
    final Queue<Throwable> exceptions = new LinkedList<Throwable>();
    try {

        final CatalogBuilder.ProcessingEventListener listener = new CatalogBuilder.ProcessingEventListener() {

            @Override
            public void exceptionOccurred(ExceptionEvent event) {
                final Throwable t = event.getException();
                exceptions.add(t);
                if (LOGGER.isLoggable(Level.SEVERE))
                    LOGGER.log(Level.SEVERE, t.getLocalizedMessage(), t);

            }

            @Override
            public void getNotification(ProcessingEvent event) {
                if (LOGGER.isLoggable(Level.FINE))
                    LOGGER.fine(event.getMessage());

            }

        };
        catalogBuilder.addProcessingEventListener(listener);
        catalogBuilder.run();
    } catch (Throwable e) {
        LOGGER.log(Level.SEVERE, "Unable to build mosaic", e);
        return false;
    } finally {
        catalogBuilder.dispose();
    }

    // check that nothing bad happened
    if (exceptions.size() > 0)
        return false;
    return true;
}