Example usage for org.apache.commons.lang3 ArrayUtils toPrimitive

List of usage examples for org.apache.commons.lang3 ArrayUtils toPrimitive

Introduction

In this page you can find the example usage for org.apache.commons.lang3 ArrayUtils toPrimitive.

Prototype

public static boolean[] toPrimitive(final Boolean[] array) 

Source Link

Document

Converts an array of object Booleans to primitives.

This method returns null for a null input array.

Usage

From source file:org.kalypsodeegree.model.typeHandler.XsdBaseTypeHandlerByteArray.java

/**
 * @see org.kalypsodeegree.model.XsdBaseTypeHandler#convertToXMLString(java.lang.Object)
 *//*from  www  .  j av  a  2s . c  o m*/
@Override
public String convertToXMLString(final Byte[] value) {
    final byte[] base64Data = ArrayUtils.toPrimitive(value);
    final byte[] bytes = Base64.decodeBase64(base64Data);
    return new String(bytes);
}

From source file:org.kalypsodeegree.model.typeHandler.XsdBaseTypeHandlerHexArray.java

/**
 * @see org.kalypsodeegree.model.XsdBaseTypeHandler#convertToXMLString(java.lang.Object)
 *//*from w w  w  . j ava  2 s .  c o m*/
@Override
public String convertToXMLString(final Byte[] value) {
    final byte[] bytes = ArrayUtils.toPrimitive(value);
    return HexBin.bytesToString(bytes);
}

From source file:org.kalypsodeegree_impl.io.sax.parser.EnvelopeContentHandler.java

protected void addCoordinate(final List<Double[]> positions) throws SAXParseException {
    for (final Double[] position : positions) {
        final GM_Position pos = GeometryFactory.createGM_Position(ArrayUtils.toPrimitive(position));
        addPosition(new PositionsWithSrs(pos, m_srs));
    }/* w w w .  j ava  2 s .  c om*/
}

From source file:org.kalypsodeegree_impl.model.feature.FeatureHelper.java

public static int[] getPositionOfAllAssociations(final Feature feature) {
    final ArrayList<Integer> res = new ArrayList<>();
    final IFeatureType featureType = feature.getFeatureType();
    final IPropertyType[] properties = featureType.getProperties();
    for (int i = 0; i < properties.length; i++) {
        final IPropertyType property = properties[i];
        if (property instanceof IRelationType) {
            res.add(new Integer(i));
        }//from   w  w  w .  j a  va2  s .c  om
    }
    final Integer[] positions = res.toArray(new Integer[res.size()]);
    return ArrayUtils.toPrimitive(positions);
}

From source file:org.linqs.psl.model.rule.arithmetic.AbstractGroundArithmeticRule.java

protected AbstractGroundArithmeticRule(AbstractArithmeticRule rule, List<Double> coeffs, List<GroundAtom> atoms,
        FunctionComparator comparator, double constant) {
    this(rule, ArrayUtils.toPrimitive(coeffs.toArray(new Double[0])), atoms.toArray(new GroundAtom[0]),
            comparator, constant, false);
}

From source file:org.lmn.fc.frameworks.starbase.plugins.observatory.ui.instruments.commands.configuration.UploadControllerOS.java

/***********************************************************************************************
 * Upload the specified data to the AVR Controller's Bootloader.
 * Optionally fill the unused code memory with 0xff.
 * Capture the version number of the bootloader.
 *
 * @param target/*from w  w  w  .j a  va 2  s . c  om*/
 * @param broadcastaddress
 * @param data
 * @param fillunused
 * @param logentries
 * @param errors
 *
 * @return ResponseMessageStatus
 */

private static ResponseMessageStatus uploadToAVRBootloader(final TargetCPU target,
        final String broadcastaddress, final List<Byte> data, final boolean fillunused,
        final List<String> logentries, final List<String> errors) {
    final String SOURCE = "UploadControllerOS.uploadToAVRBootloader() ";
    final int RETRY_COUNT = 5;
    final byte COMMAND_IDENTIFY = 0x49; // ASCII 'I'
    final byte COMMAND_PROGRAM = 0x50; // ASCII 'P'
    final byte COMMAND_ACK = 0x41; // ASCII 'A'
    final byte COMMAND_NACK = 0x4e; // ASCII 'N'
    UDPClient clientUDP;
    ResponseMessageStatus responseMessageStatus;

    clientUDP = null;
    responseMessageStatus = ResponseMessageStatus.SUCCESS;

    try {
        final String strHostname;
        final InetAddress inetAddress;
        List<Byte> listPayload;
        byte[] arrayResponse;

        // Set up the UDPClient
        // Note that UDP requests are often restricted to the current subnet
        strHostname = broadcastaddress;
        inetAddress = InetAddress.getByName(strHostname);

        // SocketException
        clientUDP = new UDPClient(inetAddress, target.getLocalPort(), target.getRemotePort(),
                target.getTimeoutMillis());
        clientUDP.getSocket().setBroadcast(true);

        // The host program transmits an 'identify' packet to kick off communication with any devices in bootloader mode
        // The MAC address in this packet is all zeroes meaning any bootloader should respond
        // I <0x00> <0x00> <0x00> <0x00> <0x00> <0x00>
        listPayload = new ArrayList<Byte>(7);
        listPayload.add(COMMAND_IDENTIFY);
        listPayload.add((byte) 0x00);
        listPayload.add((byte) 0x00);
        listPayload.add((byte) 0x00);
        listPayload.add((byte) 0x00);
        listPayload.add((byte) 0x00);
        listPayload.add((byte) 0x00);

        // Prepare to get the Bootloader Version
        logentries.clear();

        // Send the packet, do NOT call UDPClient.connect() !
        // If the payload is longer than the maximum reliable length of a UDP Datagram
        // (8192) bytes then an IOException is thrown
        clientUDP.send(ArrayUtils.toPrimitive(listPayload.toArray(new Byte[listPayload.size()])));

        // The host then waits for timeout for any/all devices in bootloader mode to respond
        // This method blocks until a UDP Datagram is received
        // This Command is being executed on its own SwingWorker, so this doesn't matter...
        // IOException
        arrayResponse = clientUDP.receive();

        // The devices respond with an 'acknowledge' packet and its MAC address
        // There are additional data giving more details about the target processor
        // A <6 bytes Target MAC> <ChipFlashPageSize> <ProcessorID> <VersionNumber>
        // Ideally the host should capture all responses and allow the user to select which device to program,
        // at the moment this host simply uses the first (and normally only) response.

        if ((arrayResponse != null) && (arrayResponse.length > 0)) {
            final int INDEX_ACK = 0;
            final int INDEX_MAC_ADDRESS = 1;
            final int INDEX_PAGE_SIZE = 7;
            final int INDEX_PACKET_NUMBER = 7;
            final int INDEX_ID = 8;
            final int INDEX_VERSION = 9;
            final byte[] arrayMAC;
            final List<Byte> listMAC;
            final int intChipFlashPageSize;
            final byte byteProcessorID;
            final byte byteVersion;

            LOGGER.debug(LOADER_PROPERTIES.isStarinetDebug(),
                    "[identify_response=" + Utilities.byteArrayToSpacedHex(arrayResponse) + "]");

            // Read the MAC address of the responder, and convert to a List
            arrayMAC = ArrayUtils.subarray(arrayResponse, INDEX_MAC_ADDRESS, INDEX_MAC_ADDRESS + 6);
            listMAC = new ArrayList<Byte>(6);

            for (int intMACIndex = 0; intMACIndex < 6; intMACIndex++) {
                listMAC.add(arrayMAC[intMACIndex]);
            }

            // ChipFlashPageSize
            intChipFlashPageSize = arrayResponse[INDEX_PAGE_SIZE] << 4;

            // ProcessorID
            byteProcessorID = arrayResponse[INDEX_ID];

            // Version Number (did not exist prior to v1.1)
            if (arrayResponse.length > INDEX_VERSION) {
                byteVersion = arrayResponse[INDEX_VERSION];
            } else {
                byteVersion = 0x00;
            }
            logentries.add(Utilities.byteToTwoHexString(byteVersion));

            // Check that we have exactly the right target
            if ((byteProcessorID == target.getID()) && (intChipFlashPageSize == target.getPagesize())) {
                // Now program the data in PageSize packets
                if ((data != null) && (!data.isEmpty())) {
                    final int intSizeOfLastPacket;
                    final int intPacketCount;
                    boolean boolSuccessfulPacket;

                    // Record the Codesize (before padding) as the second entry
                    logentries.add(Integer.toString(data.size()));

                    // Fill the unused bytes in the code memory if requested
                    if (fillunused) {
                        while (data.size() < target.getCodesize()) {
                            data.add(target.getFill());
                        }
                    }

                    // Only now do we know the page size required for this processor
                    // Pad the data List to be multiple of PageSize bytes
                    intSizeOfLastPacket = data.size() % intChipFlashPageSize;

                    if ((intSizeOfLastPacket != intChipFlashPageSize) && (data.size() < target.getCodesize())) {
                        for (int intPadding = 0; ((intPadding < (intChipFlashPageSize - intSizeOfLastPacket))
                                && (data.size() < target.getCodesize())); intPadding++) {
                            data.add(target.getFill());
                        }
                    }

                    // Calculate the number of packets to send
                    intPacketCount = data.size() / intChipFlashPageSize;
                    boolSuccessfulPacket = true;

                    for (int intPacketIndex = 0; ((intPacketIndex < intPacketCount)
                            && (boolSuccessfulPacket)); intPacketIndex++) {
                        final int intPacketAddress;
                        boolean boolKeepRetrying;

                        intPacketAddress = intPacketIndex * intChipFlashPageSize;

                        // The program packet is made up as follows:
                        // P
                        // <6 bytes Dest MAC>
                        // <PacketNumber>
                        // <TargetAddressMSB>
                        // <TargetAddressLSB>
                        // <DataBytesLengthMSB>
                        // <DataBytesLengthLSB>
                        // <DataBytes>
                        // Code words in DataBytes are sent little-endian, i.e. LSB first
                        // but that order will have been set during compilation to create the HEX file

                        listPayload = new ArrayList<Byte>(12 + intChipFlashPageSize);

                        // Program Command 'P'
                        listPayload.add(COMMAND_PROGRAM);

                        // MAC Address
                        listPayload.addAll(listMAC);

                        // PacketNumber
                        listPayload.add((byte) intPacketIndex);

                        // Target Address MSB, LSB
                        listPayload.add((byte) ((intPacketAddress & 0xff00) >> 8));
                        listPayload.add((byte) ((intPacketAddress & 0x00ff)));

                        // DataBytesLength MSB, LSB
                        listPayload.add((byte) ((intChipFlashPageSize & 0xff00) >> 8));
                        listPayload.add((byte) ((intChipFlashPageSize & 0x00ff)));

                        // DataBytes
                        listPayload.addAll(
                                data.subList(intPacketAddress, intPacketAddress + intChipFlashPageSize));

                        LOGGER.debug(LOADER_PROPERTIES.isStarinetDebug(),
                                "[send] [packet_index=" + intPacketIndex + "] [packet_address="
                                        + intPacketAddress + "] [pagesize=" + intChipFlashPageSize + "]");
                        LOGGER.debug(LOADER_PROPERTIES.isStarinetDebug(), HexFileHelper.dumpHex(listPayload,
                                intPacketAddress, HexFileHelper.DUMP_BYTES_PER_LINE));
                        boolKeepRetrying = true;

                        // Start the retry loop
                        for (int intRetryIndex = 0; ((intRetryIndex < RETRY_COUNT)
                                && (boolKeepRetrying)); intRetryIndex++) {
                            // Send the packet to the remote Port
                            clientUDP.send(
                                    ArrayUtils.toPrimitive(listPayload.toArray(new Byte[listPayload.size()])));

                            // Wait here for Ack or Nack
                            arrayResponse = clientUDP.receive();

                            if ((arrayResponse != null) && (arrayResponse.length > 0)) {
                                // Was it an Ack or Nack from the correct MAC address?
                                // A
                                // <6 bytes Source MAC>
                                // <PacketNumber>

                                LOGGER.debug(LOADER_PROPERTIES.isStarinetDebug(), "[program_response="
                                        + Utilities.byteArrayToSpacedHex(arrayResponse) + "]");

                                // See if it was an Ack
                                if ((arrayResponse.length >= 8) && (COMMAND_ACK == arrayResponse[INDEX_ACK])) {
                                    final byte[] arrayAckMAC;
                                    final List<Byte> listAckMAC;

                                    // Read the MAC address in the Ack
                                    arrayAckMAC = ArrayUtils.subarray(arrayResponse, INDEX_MAC_ADDRESS,
                                            INDEX_MAC_ADDRESS + 6);
                                    listAckMAC = new ArrayList<Byte>(6);

                                    for (int intMACIndex = 0; intMACIndex < 6; intMACIndex++) {
                                        listAckMAC.add(arrayAckMAC[intMACIndex]);
                                    }

                                    // Check the the MAC address is correct
                                    if (listMAC.equals(listAckMAC)) {
                                        // Check the packet number
                                        if (arrayResponse[INDEX_PACKET_NUMBER] == (byte) intPacketIndex) {
                                            // Success, so stop the retry loop and carry on
                                            boolKeepRetrying = false;
                                            boolSuccessfulPacket = true;
                                        } else {
                                            // Faulty packet index, so retry?
                                            boolKeepRetrying = true;
                                            boolSuccessfulPacket = false;
                                            errors.add(METADATA_TARGET_STARINET + METADATA_ACTION_REQUEST_UDP
                                                    + METADATA_RESULT + "Faulty Packet Index, Retry [index="
                                                    + arrayResponse[7] + TERMINATOR);
                                        }
                                    } else {
                                        // Faulty MAC address, so retry
                                        boolKeepRetrying = true;
                                        boolSuccessfulPacket = false;
                                        errors.add(METADATA_TARGET_STARINET + METADATA_ACTION_REQUEST_UDP
                                                + METADATA_RESULT + "Faulty MAC Address, Retry [index="
                                                + intRetryIndex + TERMINATOR);
                                    }
                                } else if (COMMAND_NACK == arrayResponse[INDEX_ACK]) {
                                    // A Nack must always cause a retry
                                    boolKeepRetrying = true;
                                    boolSuccessfulPacket = false;
                                    errors.add(METADATA_TARGET_STARINET + METADATA_ACTION_REQUEST_UDP
                                            + METADATA_RESULT + "NACK Packet, Retry [index=" + intRetryIndex
                                            + TERMINATOR);
                                } else {
                                    // An unknown packet type, so give up
                                    boolKeepRetrying = false;
                                    boolSuccessfulPacket = false;
                                    responseMessageStatus = ResponseMessageStatus.PREMATURE_TERMINATION;
                                    errors.add(METADATA_TARGET_STARINET + METADATA_ACTION_REQUEST_UDP
                                            + METADATA_RESULT + "Unknown packet type ("
                                            + arrayResponse[INDEX_ACK] + ")" + TERMINATOR);
                                }
                            } else {
                                // A fatal error, since no Ack or Nack packet, so no sense in retrying again
                                boolKeepRetrying = false;
                                boolSuccessfulPacket = false;
                                responseMessageStatus = ResponseMessageStatus.PREMATURE_TERMINATION;
                                errors.add(
                                        METADATA_TARGET_STARINET + METADATA_ACTION_REQUEST_UDP + METADATA_RESULT
                                                + "Program Acknowledge was empty or NULL" + TERMINATOR);
                            }
                        }
                    }
                } else {
                    // Record the Codesize (before padding) as the second entry
                    logentries.add("0");

                    responseMessageStatus = ResponseMessageStatus.PREMATURE_TERMINATION;
                    errors.add(METADATA_TARGET_STARINET + METADATA_ACTION_REQUEST_UDP + METADATA_RESULT
                            + "No data to transmit" + TERMINATOR);
                }
            } else {
                responseMessageStatus = ResponseMessageStatus.PREMATURE_TERMINATION;
                errors.add(METADATA_TARGET_STARINET + METADATA_ACTION_REQUEST_UDP + METADATA_RESULT
                        + "Invalid AVR ProcessorID or PageSize [id=" + byteProcessorID + "] [pagesize="
                        + intChipFlashPageSize + TERMINATOR);
            }
        } else {
            responseMessageStatus = ResponseMessageStatus.PREMATURE_TERMINATION;
            errors.add(METADATA_TARGET_STARINET + METADATA_ACTION_REQUEST_UDP + METADATA_RESULT
                    + "Identify Acknowledge was empty or NULL" + TERMINATOR);
        }
    }

    catch (IndexOutOfBoundsException exception) {
        responseMessageStatus = ResponseMessageStatus.PREMATURE_TERMINATION;
        errors.add(METADATA_TARGET_STARINET + METADATA_ACTION_REQUEST_UDP + METADATA_EXCEPTION
                + ObservatoryInstrumentDAOInterface.ERROR_ARRAY_INDEX + TERMINATOR + SPACE + METADATA_MESSAGE
                + exception.getMessage() + TERMINATOR);
    }

    catch (PortUnreachableException exception) {
        responseMessageStatus = ResponseMessageStatus.PREMATURE_TERMINATION;
        errors.add(METADATA_TARGET_STARINET + METADATA_ACTION_REQUEST_UDP + METADATA_EXCEPTION
                + ObservatoryInstrumentDAOInterface.ERROR_PORT + TERMINATOR + SPACE + METADATA_MESSAGE
                + exception.getMessage() + TERMINATOR);
    }

    catch (SocketException exception) {
        responseMessageStatus = ResponseMessageStatus.PREMATURE_TERMINATION;
        errors.add(METADATA_TARGET_STARINET + METADATA_ACTION_REQUEST_UDP + METADATA_EXCEPTION
                + ObservatoryInstrumentDAOInterface.ERROR_SOCKET + TERMINATOR + SPACE + METADATA_MESSAGE
                + exception.getMessage() + TERMINATOR);
    }

    catch (IllegalArgumentException exception) {
        responseMessageStatus = ResponseMessageStatus.PREMATURE_TERMINATION;
        errors.add(METADATA_TARGET_STARINET + METADATA_ACTION_REQUEST_UDP + METADATA_EXCEPTION
                + ObservatoryInstrumentDAOInterface.ERROR_PARSE_INPUT + TERMINATOR + SPACE + METADATA_MESSAGE
                + exception.getMessage() + TERMINATOR);
    }

    catch (SecurityException exception) {
        responseMessageStatus = ResponseMessageStatus.PREMATURE_TERMINATION;
        errors.add(METADATA_TARGET_STARINET + METADATA_ACTION_REQUEST_UDP + METADATA_EXCEPTION
                + ObservatoryInstrumentDAOInterface.ERROR_SECURITY + TERMINATOR + SPACE + METADATA_MESSAGE
                + exception.getMessage() + TERMINATOR);
    }

    catch (UnknownHostException exception) {
        responseMessageStatus = ResponseMessageStatus.PREMATURE_TERMINATION;
        errors.add(METADATA_TARGET_STARINET + METADATA_ACTION_REQUEST_UDP + METADATA_EXCEPTION
                + ObservatoryInstrumentDAOInterface.ERROR_UNKNOWN_HOST + TERMINATOR + SPACE + METADATA_MESSAGE
                + exception.getMessage() + TERMINATOR);
    }

    catch (SocketTimeoutException exception) {
        responseMessageStatus = ResponseMessageStatus.PREMATURE_TERMINATION;
        errors.add(METADATA_TARGET_STARINET + METADATA_ACTION_REQUEST_UDP + METADATA_EXCEPTION
                + ObservatoryInstrumentDAOInterface.ERROR_TIMEOUT + TERMINATOR + SPACE + METADATA_MESSAGE
                + exception.getMessage() + TERMINATOR);
    }

    catch (IllegalBlockingModeException exception) {
        responseMessageStatus = ResponseMessageStatus.PREMATURE_TERMINATION;
        errors.add(METADATA_TARGET_STARINET + METADATA_ACTION_REQUEST_UDP + METADATA_EXCEPTION
                + ObservatoryInstrumentDAOInterface.ERROR_ILLEGAL_MODE + TERMINATOR + SPACE + METADATA_MESSAGE
                + exception.getMessage() + TERMINATOR);
    }

    catch (IOException exception) {
        responseMessageStatus = ResponseMessageStatus.PREMATURE_TERMINATION;
        errors.add(METADATA_TARGET_STARINET + METADATA_ACTION_REQUEST_UDP + METADATA_EXCEPTION
                + ObservatoryInstrumentDAOInterface.ERROR_IO + TERMINATOR + SPACE + METADATA_MESSAGE
                + exception.getMessage() + TERMINATOR);
    }

    finally {
        // Make sure that the Socket is released
        if (clientUDP != null) {
            clientUDP.close();
        }
    }

    return (responseMessageStatus);
}

From source file:org.lockss.exporter.counter.CounterReportsJournalReport5.java

/**
 * Populates the report publication year groupings.
 *///ww w  . j  av  a2s  .  c o  m
private void populatePublicationYears() {
    final String DEBUG_HEADER = "populatePublicationYears(): ";
    int year = currentYear;

    // The publication year groups.
    List<Integer> yops = new ArrayList<Integer>();

    // The first group is for the articles in press (YOP in the future).
    yops.add(new Integer(0));

    // Loop through all the years after the first one in this decade.
    while (year % 10 != 0) {
        yops.add(new Integer(year--));
    }

    // Loop through the first year in this decade and all the years in the
    // previous decade.
    for (int i = 0; i < 11; i++) {
        yops.add(new Integer(year--));
    }

    // The group for the prior years.
    yops.add(new Integer(0));

    // The group for the unknown publication years.
    yops.add(new Integer(0));

    pubYears = ArrayUtils.toPrimitive(yops.toArray(new Integer[yops.size()]));

    if (log.isDebug2()) {
        for (int pubYear : pubYears) {
            log.debug2(DEBUG_HEADER + "pubYear = " + pubYear + ".");
        }
    }
}

From source file:org.mrgeo.cmd.export.Export.java

@Override
public int run(final String[] args, Configuration conf, ProviderProperties providerProperties) {
    log.info("Export");

    try {//w  ww.  j  a v  a  2s. c om
        final Options options = createOptions();
        CommandLine line;
        try {
            final CommandLineParser parser = new PosixParser();
            line = parser.parse(options, args);

            if (line == null || line.hasOption("h")) {
                new HelpFormatter().printHelp("Export", options);
                return 1;
            }

            if (line.hasOption("b") && (line.hasOption("t") || line.hasOption("c") || line.hasOption("r"))) {
                log.debug("Option -b is currently incompatible with -t, -c, and -r");
                throw new ParseException("Incorrect combination of arguments");
            }

            if (line.hasOption("s") && line.hasOption("m")) {
                log.debug("Cannot use both -s and -m");
                throw new ParseException("Incorrect combination of arguments");
            }
            if (line.hasOption("v")) {
                LoggingUtils.setDefaultLogLevel(LoggingUtils.INFO);
            }
            if (line.hasOption("d")) {
                LoggingUtils.setDefaultLogLevel(LoggingUtils.DEBUG);
            }

            if (line.hasOption("l")) {
                System.out.println("Using local runner");
                HadoopUtils.setupLocalRunner(conf);
            }

            String outputbase = line.getOptionValue("o");

            if (line.hasOption("c")) {
                maxTiles = Integer.valueOf(line.getOptionValue("c"));
            }

            useRand = line.hasOption("r");
            all = line.hasOption("a");

            singleImage = line.hasOption("s");
            mosaicTiles = line.hasOption("m");
            if (mosaicTiles) {
                mosaicTileCount = Integer.valueOf(line.getOptionValue("m"));
            }

            useBounds = line.hasOption("b");
            if (useBounds) {
                final String boundsOption = line.getOptionValue("b");
                bounds = parseBounds(boundsOption);
            }

            if (line.hasOption("cs")) {
                colorscale = ColorScaleManager.fromName(line.getOptionValue("cs"));
            }

            useTileSet = line.hasOption("t");
            if (useTileSet) {
                final String tileIdOption = line.getOptionValue("t");
                final String[] tileIds = tileIdOption.split(",");
                for (final String tileId : tileIds) {
                    tileset.add(Long.valueOf(tileId));
                }
            }

            int zoomlevel = -1;
            if (line.hasOption("z")) {
                zoomlevel = Integer.valueOf(line.getOptionValue("z"));
            }

            String format = "tif";
            if (line.hasOption("f")) {
                format = line.getOptionValue("f");
            }

            useTMS = line.hasOption("tms");

            //      if (!singleImage)
            //      {
            //        FileUtils.createDir(new File(outputbase));
            //      }

            for (final String arg : line.getArgs()) {
                // The input can be either an image or a vector.
                MrsPyramid imagePyramid;
                MrsPyramid pyramid = null;
                try {
                    imagePyramid = MrsPyramid.open(arg, providerProperties);
                    pyramid = imagePyramid;
                } catch (IOException e) {
                    imagePyramid = null;
                }

                if (imagePyramid == null) {
                    throw new IOException("Specified input must be either an image or a vector");
                }
                if (zoomlevel <= 0) {
                    zoomlevel = pyramid.getMaximumLevel();
                }

                int end = zoomlevel;
                if (all) {
                    end = 1;
                }

                while (zoomlevel >= end) {
                    //final String output = outputbase + (all ? "_" + Integer.toString(zoomlevel) : "");

                    MrsImage image = null;
                    if (imagePyramid != null) {
                        image = imagePyramid.getImage(zoomlevel);
                    }
                    try {
                        final Set<Long> tiles = calculateTiles(pyramid, zoomlevel);

                        int tilesize = imagePyramid.getTileSize();

                        if (singleImage) {
                            if (imagePyramid != null) {
                                saveMultipleTiles(outputbase, format, image,
                                        ArrayUtils.toPrimitive(tiles.toArray(new Long[tiles.size()])));
                            }
                        } else if (mosaicTiles && mosaicTileCount > 0) {

                            if (!outputbase.contains(X) || !outputbase.contains(Y) || !outputbase.contains(LAT)
                                    || !outputbase.contains(LON)) {
                                outputbase = outputbase + "/$Y-$X";
                            }
                            for (final Long tileid : tiles) {
                                final Tile t = TMSUtils.tileid(tileid, zoomlevel);
                                final Set<Long> tilesToMosaic = new HashSet<>();
                                final LongRectangle tileBounds = pyramid.getTileBounds(zoomlevel);
                                for (long ty1 = t.ty; ((ty1 < (t.ty + mosaicTileCount))
                                        && (ty1 <= tileBounds.getMaxY())); ty1++) {
                                    for (long tx1 = t.tx; ((tx1 < (t.tx + mosaicTileCount))
                                            && (tx1 <= tileBounds.getMaxX())); tx1++) {
                                        tilesToMosaic.add(TMSUtils.tileid(tx1, ty1, zoomlevel));
                                    }
                                }
                                //                final String mosaicOutput = output + "/" + t.ty + "-" + t.tx + "-" +
                                //                    TMSUtils.tileid(t.tx, t.ty, zoomlevel);
                                if (imagePyramid != null) {
                                    saveMultipleTiles(outputbase, format, image, ArrayUtils.toPrimitive(
                                            tilesToMosaic.toArray(new Long[tilesToMosaic.size()])));
                                }
                            }
                        } else {
                            for (final Long tileid : tiles) {
                                if (imagePyramid != null) {
                                    saveSingleTile(outputbase, image, format, tileid, zoomlevel, tilesize);
                                }
                            }
                        }
                    } finally {
                        if (image != null) {
                            image.close();
                        }
                    }

                    zoomlevel--;
                }
            }
        } catch (final ParseException e) {
            new HelpFormatter().printHelp("Export", options);
            return 1;
        }

        return 0;
    } catch (Exception e) {
        e.printStackTrace();
    }

    return -1;
}

From source file:org.mrgeo.resources.tms.TileMapServiceResource.java

protected Response returnEmptyTile(final int width, final int height, final String format) throws Exception {
    //return an empty image
    ImageResponseWriter writer = (ImageResponseWriter) ImageHandlerFactory.getHandler(format,
            ImageResponseWriter.class);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    int bands;//  w w  w  .  j a v  a  2s .  c  o  m
    Double[] nodatas;
    if (format.equalsIgnoreCase("jpg") || format.equalsIgnoreCase("jpeg")) {
        bands = 3;
        nodatas = new Double[] { 0.0, 0.0, 0.0 };
    } else {
        bands = 4;
        nodatas = new Double[] { 0.0, 0.0, 0.0, 0.0 };
    }

    Raster raster = RasterUtils.createEmptyRaster(width, height, bands, DataBuffer.TYPE_BYTE, nodatas);
    writer.writeToStream(raster, ArrayUtils.toPrimitive(nodatas), baos);
    byte[] imageData = baos.toByteArray();
    IOUtils.closeQuietly(baos);

    final String type = mimeTypeMap.getContentType("output." + format);
    return Response.ok(imageData).header("Content-Type", type).build();

    // A 404 - Not Found response may be the most appropriate, but results in pink tiles,
    // maybe change that behavior on the OpenLayers client?
    // return Response.status( Response.Status.NOT_FOUND).build();

}

From source file:org.mrgeo.services.mrspyramid.MrsPyramidService.java

public byte[] getEmptyTile(int width, int height, String format) throws Exception {
    //return an empty image

    ImageResponseWriter writer = getImageResponseWriter(format);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    int bands;//from w  w w. j  av a2 s .c  o  m
    Double[] nodatas;
    if (format.equalsIgnoreCase("jpg") || format.equalsIgnoreCase("jpeg")) {
        bands = 3;
        nodatas = new Double[] { 0.0, 0.0, 0.0 };
    } else {
        bands = 4;
        nodatas = new Double[] { 0.0, 0.0, 0.0, 0.0 };
    }

    Raster raster = RasterUtils.createEmptyRaster(width, height, bands, DataBuffer.TYPE_BYTE, nodatas);
    writer.writeToStream(raster, ArrayUtils.toPrimitive(nodatas), baos);
    byte[] imageData = baos.toByteArray();
    IOUtils.closeQuietly(baos);
    return imageData;

}