Example usage for java.io DataOutputStream write

List of usage examples for java.io DataOutputStream write

Introduction

In this page you can find the example usage for java.io DataOutputStream write.

Prototype

public synchronized void write(int b) throws IOException 

Source Link

Document

Writes the specified byte (the low eight bits of the argument b) to the underlying output stream.

Usage

From source file:org.apache.jackrabbit.core.persistence.bundle.util.BundleBinding.java

/**
 * Serializes a <code>PropertyState</code> to the data output stream
 *
 * @param out the output stream//  w  ww  .jav  a  2  s  .  co m
 * @param state the property entry to store
 * @throws IOException if an I/O error occurs.
 */
public void writeState(DataOutputStream out, NodePropBundle.PropertyEntry state) throws IOException {
    // type & mod count
    out.writeInt(state.getType() | (state.getModCount() << 16));
    // multiValued
    out.writeBoolean(state.isMultiValued());
    // definitionId
    out.writeUTF("");
    // values
    InternalValue[] values = state.getValues();
    out.writeInt(values.length); // count
    for (int i = 0; i < values.length; i++) {
        InternalValue val = values[i];
        switch (state.getType()) {
        case PropertyType.BINARY:
            BLOBFileValue blobVal = val.getBLOBFileValue();
            long size = blobVal.getLength();
            if (InternalValue.USE_DATA_STORE && dataStore != null) {
                int maxMemorySize = dataStore.getMinRecordLength() - 1;
                if (size < maxMemorySize) {
                    writeSmallBinary(out, blobVal, state, i);
                } else {
                    out.writeInt(BINARY_IN_DATA_STORE);
                    try {
                        val.store(dataStore);
                    } catch (RepositoryException e) {
                        String msg = "Error while storing blob. id=" + state.getId() + " idx=" + i + " size="
                                + val.getBLOBFileValue().getLength();
                        log.error(msg, e);
                        throw new IOException(msg);
                    }
                    out.writeUTF(val.toString());
                }
                break;
            }
            // special handling required for binary value:
            // spool binary value to file in blob store
            if (size < 0) {
                log.warn("Blob has negative size. Potential loss of data. " + "id={} idx={}", state.getId(),
                        String.valueOf(i));
                out.writeInt(0);
                values[i] = InternalValue.create(new byte[0]);
                blobVal.discard();
            } else if (size > minBlobSize) {
                out.writeInt(BINARY_IN_BLOB_STORE);
                String blobId = state.getBlobId(i);
                if (blobId == null) {
                    try {
                        InputStream in = blobVal.getStream();
                        try {
                            blobId = blobStore.createId(state.getId(), i);
                            blobStore.put(blobId, in, size);
                            state.setBlobId(blobId, i);
                        } finally {
                            IOUtils.closeQuietly(in);
                        }
                    } catch (Exception e) {
                        String msg = "Error while storing blob. id=" + state.getId() + " idx=" + i + " size="
                                + size;
                        log.error(msg, e);
                        throw new IOException(msg);
                    }
                    try {
                        // replace value instance with value
                        // backed by resource in blob store and delete temp file
                        if (blobStore instanceof ResourceBasedBLOBStore) {
                            values[i] = InternalValue
                                    .create(((ResourceBasedBLOBStore) blobStore).getResource(blobId));
                        } else {
                            values[i] = InternalValue.create(blobStore.get(blobId));
                        }
                    } catch (Exception e) {
                        log.error("Error while reloading blob. truncating. id=" + state.getId() + " idx=" + i
                                + " size=" + size, e);
                        values[i] = InternalValue.create(new byte[0]);
                    }
                    blobVal.discard();
                }
                // store id of blob as property value
                out.writeUTF(blobId); // value
            } else {
                // delete evt. blob
                byte[] data = writeSmallBinary(out, blobVal, state, i);
                // replace value instance with value
                // backed by resource in blob store and delete temp file
                values[i] = InternalValue.create(data);
                blobVal.discard();
            }
            break;
        case PropertyType.DOUBLE:
            out.writeDouble(val.getDouble());
            break;
        case PropertyType.LONG:
            out.writeLong(val.getLong());
            break;
        case PropertyType.BOOLEAN:
            out.writeBoolean(val.getBoolean());
            break;
        case PropertyType.NAME:
            writeQName(out, val.getQName());
            break;
        case PropertyType.REFERENCE:
            writeUUID(out, val.getUUID());
            break;
        default:
            // because writeUTF(String) has a size limit of 64k,
            // we're using write(byte[]) instead
            byte[] bytes = val.toString().getBytes("UTF-8");
            out.writeInt(bytes.length); // length of byte[]
            out.write(bytes); // byte[]
        }
    }
}

From source file:org.apache.hadoop.hive.ql.exec.DDLTask.java

/**
 * Shows a description of a function.//w w w  . jav  a 2s.c  om
 * @param db
 *
 * @param descFunc
 *          is the function we are describing
 * @throws HiveException
 */
private int describeFunction(Hive db, DescFunctionDesc descFunc) throws HiveException, SQLException {
    String funcName = descFunc.getName();

    // write the results in the file
    DataOutputStream outStream = getOutputStream(descFunc.getResFile());
    try {
        // get the function documentation
        Description desc = null;
        Class<?> funcClass = null;
        FunctionInfo functionInfo = FunctionRegistry.getFunctionInfo(funcName);
        if (functionInfo != null) {
            funcClass = functionInfo.getFunctionClass();
        }
        if (funcClass != null) {
            desc = AnnotationUtils.getAnnotation(funcClass, Description.class);
        }
        if (desc != null) {
            outStream.writeBytes(desc.value().replace("_FUNC_", funcName));
            if (descFunc.isExtended()) {
                Set<String> synonyms = FunctionRegistry.getFunctionSynonyms(funcName);
                if (synonyms.size() > 0) {
                    outStream.writeBytes("\nSynonyms: " + join(synonyms, ", "));
                }
                if (desc.extended().length() > 0) {
                    outStream.writeBytes("\n" + desc.extended().replace("_FUNC_", funcName));
                }
            }
        } else {
            if (funcClass != null) {
                outStream.writeBytes("There is no documentation for function '" + funcName + "'");
            } else {
                outStream.writeBytes("Function '" + funcName + "' does not exist.");
            }
        }

        outStream.write(terminator);
        if (descFunc.isExtended()) {
            if (funcClass != null) {
                outStream.writeBytes("Function class:" + funcClass.getName() + "\n");
            }
            if (functionInfo != null) {
                outStream.writeBytes("Function type:" + functionInfo.getFunctionType() + "\n");
                FunctionResource[] resources = functionInfo.getResources();
                if (resources != null) {
                    for (FunctionResource resource : resources) {
                        outStream.writeBytes("Resource:" + resource.getResourceURI() + "\n");
                    }
                }
            }
        }
    } catch (FileNotFoundException e) {
        LOG.warn("describe function: " + stringifyException(e));
        return 1;
    } catch (IOException e) {
        LOG.warn("describe function: " + stringifyException(e));
        return 1;
    } catch (Exception e) {
        throw new HiveException(e);
    } finally {
        IOUtils.closeStream(outStream);
    }
    return 0;
}

From source file:org.apache.hadoop.hive.ql.exec.DDLTask.java

/**
 * Write a list of the current locks to a file.
 * @param db/*from w w  w . j  a  v  a 2  s.com*/
 *
 * @param showLocks
 *          the locks we're interested in.
 * @return Returns 0 when execution succeeds and above 0 if it fails.
 * @throws HiveException
 *           Throws this exception if an unexpected error occurs.
 */
private int showLocks(Hive db, ShowLocksDesc showLocks) throws HiveException {
    Context ctx = driverContext.getCtx();
    HiveTxnManager txnManager = ctx.getHiveTxnManager();
    HiveLockManager lockMgr = txnManager.getLockManager();

    if (txnManager.useNewShowLocksFormat())
        return showLocksNewFormat(showLocks, lockMgr);

    boolean isExt = showLocks.isExt();
    if (lockMgr == null) {
        throw new HiveException("show Locks LockManager not specified");
    }

    // write the results in the file
    DataOutputStream outStream = getOutputStream(showLocks.getResFile());
    try {
        List<HiveLock> locks = null;

        if (showLocks.getTableName() == null) {
            // TODO should be doing security check here.  Users should not be
            // able to see each other's locks.
            locks = lockMgr.getLocks(false, isExt);
        } else {
            locks = lockMgr.getLocks(
                    HiveLockObject.createFrom(db, showLocks.getTableName(), showLocks.getPartSpec()), true,
                    isExt);
        }

        Collections.sort(locks, new Comparator<HiveLock>() {

            @Override
            public int compare(HiveLock o1, HiveLock o2) {
                int cmp = o1.getHiveLockObject().getName().compareTo(o2.getHiveLockObject().getName());
                if (cmp == 0) {
                    if (o1.getHiveLockMode() == o2.getHiveLockMode()) {
                        return cmp;
                    }
                    // EXCLUSIVE locks occur before SHARED locks
                    if (o1.getHiveLockMode() == HiveLockMode.EXCLUSIVE) {
                        return -1;
                    }
                    return +1;
                }
                return cmp;
            }

        });

        Iterator<HiveLock> locksIter = locks.iterator();

        while (locksIter.hasNext()) {
            HiveLock lock = locksIter.next();
            outStream.writeBytes(lock.getHiveLockObject().getDisplayName());
            outStream.write(separator);
            outStream.writeBytes(lock.getHiveLockMode().toString());
            if (isExt) {
                HiveLockObjectData lockData = lock.getHiveLockObject().getData();
                if (lockData != null) {
                    outStream.write(terminator);
                    outStream.writeBytes("LOCK_QUERYID:" + lockData.getQueryId());
                    outStream.write(terminator);
                    outStream.writeBytes("LOCK_TIME:" + lockData.getLockTime());
                    outStream.write(terminator);
                    outStream.writeBytes("LOCK_MODE:" + lockData.getLockMode());
                    outStream.write(terminator);
                    outStream.writeBytes("LOCK_QUERYSTRING:" + lockData.getQueryStr());
                }
            }
            outStream.write(terminator);
        }
    } catch (FileNotFoundException e) {
        LOG.warn("show function: " + stringifyException(e));
        return 1;
    } catch (IOException e) {
        LOG.warn("show function: " + stringifyException(e));
        return 1;
    } catch (Exception e) {
        throw new HiveException(e.toString(), e);
    } finally {
        IOUtils.closeStream(outStream);
    }
    return 0;
}

From source file:carnero.cgeo.original.libs.Base.java

public boolean runExternalMap(int application, Activity activity, Resources res, Warning warning,
        GoogleAnalyticsTracker tracker, Cache cache, Waypoint waypoint, Double latitude, Double longitude) {
    if (cache == null && waypoint == null && latitude == null && longitude == null) {
        return false;
    }//www.ja va 2 s.  c o m

    if (application == mapAppLocus) {
        // locus
        try {
            final Intent intentTest = new Intent(Intent.ACTION_VIEW);
            intentTest.setData(Uri.parse("menion.points:x"));

            if (isIntentAvailable(activity, intentTest) == true) {
                final ArrayList<Waypoint> waypoints = new ArrayList<Waypoint>();
                // get only waypoints with coordinates
                if (cache != null && cache.waypoints != null && cache.waypoints.isEmpty() == false) {
                    for (Waypoint wp : cache.waypoints) {
                        if (wp.latitude != null && wp.longitude != null) {
                            waypoints.add(wp);
                        }
                    }
                }

                final ByteArrayOutputStream baos = new ByteArrayOutputStream();
                final DataOutputStream dos = new DataOutputStream(baos);

                dos.writeInt(1); // not used
                if (cache != null) {
                    if (waypoints == null || waypoints.isEmpty() == true) {
                        dos.writeInt(1); // cache only
                    } else {
                        dos.writeInt((1 + waypoints.size())); // cache and waypoints
                    }
                } else {
                    dos.writeInt(1); // one waypoint
                }

                int icon = -1;
                if (cache != null) {
                    icon = getIcon(true, cache.type, cache.own, cache.found, cache.disabled || cache.archived);
                } else if (waypoint != null) {
                    icon = getIcon(false, waypoint.type, false, false, false);
                } else {
                    icon = getIcon(false, "waypoint", false, false, false);
                }

                if (icon > 0) {
                    // load icon
                    Bitmap bitmap = BitmapFactory.decodeResource(res, icon);
                    ByteArrayOutputStream baos2 = new ByteArrayOutputStream();
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos2);
                    byte[] image = baos2.toByteArray();

                    dos.writeInt(image.length);
                    dos.write(image);
                } else {
                    // no icon
                    dos.writeInt(0); // no image
                }

                // name
                if (cache != null && cache.name != null && cache.name.length() > 0) {
                    dos.writeUTF(cache.name);
                } else if (waypoint != null && waypoint.name != null && waypoint.name.length() > 0) {
                    dos.writeUTF(waypoint.name);
                } else {
                    dos.writeUTF("");
                }

                // description
                if (cache != null && cache.geocode != null && cache.geocode.length() > 0) {
                    dos.writeUTF(cache.geocode.toUpperCase());
                } else if (waypoint != null && waypoint.lookup != null && waypoint.lookup.length() > 0) {
                    dos.writeUTF(waypoint.lookup.toUpperCase());
                } else {
                    dos.writeUTF("");
                }

                // additional data :: keyword, button title, package, activity, data name, data content
                if (cache != null && cache.geocode != null && cache.geocode.length() > 0) {
                    dos.writeUTF("intent;c:geo;carnero.cgeo;carnero.cgeo.cgeodetail;geocode;" + cache.geocode);
                } else if (waypoint != null && waypoint.id != null && waypoint.id > 0) {
                    dos.writeUTF("intent;c:geo;carnero.cgeo;carnero.cgeo.cgeowaypoint;id;" + waypoint.id);
                } else {
                    dos.writeUTF("");
                }

                if (cache != null && cache.latitude != null && cache.longitude != null) {
                    dos.writeDouble(cache.latitude); // latitude
                    dos.writeDouble(cache.longitude); // longitude
                } else if (waypoint != null && waypoint.latitude != null && waypoint.longitude != null) {
                    dos.writeDouble(waypoint.latitude); // latitude
                    dos.writeDouble(waypoint.longitude); // longitude
                } else {
                    dos.writeDouble(latitude); // latitude
                    dos.writeDouble(longitude); // longitude
                }

                // cache waypoints
                if (waypoints != null && waypoints.isEmpty() == false) {
                    for (Waypoint wp : waypoints) {
                        if (wp == null || wp.latitude == null || wp.longitude == null) {
                            continue;
                        }

                        final int wpIcon = getIcon(false, wp.type, false, false, false);

                        if (wpIcon > 0) {
                            // load icon
                            Bitmap bitmap = BitmapFactory.decodeResource(res, wpIcon);
                            ByteArrayOutputStream baos2 = new ByteArrayOutputStream();
                            bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos2);
                            byte[] image = baos2.toByteArray();

                            dos.writeInt(image.length);
                            dos.write(image);
                        } else {
                            // no icon
                            dos.writeInt(0); // no image
                        }

                        // name
                        if (wp.lookup != null && wp.lookup.length() > 0) {
                            dos.writeUTF(wp.lookup.toUpperCase());
                        } else {
                            dos.writeUTF("");
                        }

                        // description
                        if (wp.name != null && wp.name.length() > 0) {
                            dos.writeUTF(wp.name);
                        } else {
                            dos.writeUTF("");
                        }

                        // additional data :: keyword, button title, package, activity, data name, data content
                        if (wp.id != null && wp.id > 0) {
                            dos.writeUTF("intent;c:geo;carnero.cgeo;carnero.cgeo.cgeowaypoint;id;" + wp.id);
                        } else {
                            dos.writeUTF("");
                        }

                        dos.writeDouble(wp.latitude); // latitude
                        dos.writeDouble(wp.longitude); // longitude
                    }
                }

                final Intent intent = new Intent();
                intent.setAction(Intent.ACTION_VIEW);
                intent.setData(Uri.parse("menion.points:data"));
                intent.putExtra("data", baos.toByteArray());

                activity.startActivity(intent);

                sendAnal(activity, tracker, "/external/locus");

                return true;
            }
        } catch (Exception e) {
            // nothing
        }
    }

    if (application == mapAppRmaps) {
        // rmaps
        try {
            final Intent intent = new Intent("com.robert.maps.action.SHOW_POINTS");

            if (isIntentAvailable(activity, intent) == true) {
                final ArrayList<String> locations = new ArrayList<String>();
                if (cache != null && cache.latitude != null && cache.longitude != null) {
                    locations.add(String.format((Locale) null, "%.6f", cache.latitude) + ","
                            + String.format((Locale) null, "%.6f", cache.longitude) + ";" + cache.geocode + ";"
                            + cache.name);
                } else if (waypoint != null && waypoint.latitude != null && waypoint.longitude != null) {
                    locations.add(String.format((Locale) null, "%.6f", waypoint.latitude) + ","
                            + String.format((Locale) null, "%.6f", waypoint.longitude) + ";" + waypoint.lookup
                            + ";" + waypoint.name);
                }

                intent.putStringArrayListExtra("locations", locations);

                activity.startActivity(intent);

                sendAnal(activity, tracker, "/external/rmaps");

                return true;
            }
        } catch (Exception e) {
            // nothing
        }
    }

    if (application == mapAppAny) {
        // fallback
        try {
            if (cache != null && cache.latitude != null && cache.longitude != null) {
                activity.startActivity(new Intent(Intent.ACTION_VIEW,
                        Uri.parse("geo:" + cache.latitude + "," + cache.longitude)));
                // INFO: q parameter works with Google Maps, but breaks cooperation with all other apps
            } else if (waypoint != null && waypoint.latitude != null && waypoint.longitude != null) {
                activity.startActivity(new Intent(Intent.ACTION_VIEW,
                        Uri.parse("geo:" + waypoint.latitude + "," + waypoint.longitude)));
                // INFO: q parameter works with Google Maps, but breaks cooperation with all other apps
            }

            sendAnal(activity, tracker, "/external/native/maps");

            return true;
        } catch (Exception e) {
            // nothing
        }
    }

    Log.i(Settings.tag, "cgBase.runExternalMap: No maps application available.");

    if (warning != null && res != null) {
        warning.showToast(res.getString(R.string.err_application_no));
    }

    return false;
}

From source file:org.apache.jackrabbit.core.persistence.bundle.util.BundleBinding.java

/**
 * Serializes a <code>PropertyState</code> to the data output stream
 *
 * @param out the output stream//from w  w  w .j av a  2  s.  c om
 * @param state the property entry to store
 * @throws IOException if an I/O error occurs.
 */
public void writeState(DataOutputStream out, NodePropBundle.PropertyEntry state) throws IOException {
    // type & mod count
    out.writeInt(state.getType() | (state.getModCount() << 16));
    // multiValued
    out.writeBoolean(state.isMultiValued());
    // definitionId
    out.writeUTF(state.getPropDefId().toString());
    // values
    InternalValue[] values = state.getValues();
    out.writeInt(values.length); // count
    for (int i = 0; i < values.length; i++) {
        InternalValue val = values[i];
        switch (state.getType()) {
        case PropertyType.BINARY:
            try {
                long size = val.getLength();
                if (dataStore != null) {
                    int maxMemorySize = dataStore.getMinRecordLength() - 1;
                    if (size < maxMemorySize) {
                        writeSmallBinary(out, val, state, i);
                    } else {
                        out.writeInt(BINARY_IN_DATA_STORE);
                        val.store(dataStore);
                        out.writeUTF(val.toString());
                    }
                    break;
                }
                // special handling required for binary value:
                // spool binary value to file in blob store
                if (size < 0) {
                    log.warn("Blob has negative size. Potential loss of data. " + "id={} idx={}", state.getId(),
                            String.valueOf(i));
                    out.writeInt(0);
                    values[i] = InternalValue.create(new byte[0]);
                    val.discard();
                } else if (size > minBlobSize) {
                    out.writeInt(BINARY_IN_BLOB_STORE);
                    String blobId = state.getBlobId(i);
                    if (blobId == null) {
                        try {
                            InputStream in = val.getStream();
                            try {
                                blobId = blobStore.createId(state.getId(), i);
                                blobStore.put(blobId, in, size);
                                state.setBlobId(blobId, i);
                            } finally {
                                IOUtils.closeQuietly(in);
                            }
                        } catch (Exception e) {
                            String msg = "Error while storing blob. id=" + state.getId() + " idx=" + i
                                    + " size=" + size;
                            log.error(msg, e);
                            throw new IOException(msg);
                        }
                        try {
                            // replace value instance with value
                            // backed by resource in blob store and delete temp file
                            if (blobStore instanceof ResourceBasedBLOBStore) {
                                values[i] = InternalValue
                                        .create(((ResourceBasedBLOBStore) blobStore).getResource(blobId));
                            } else {
                                values[i] = InternalValue.create(blobStore.get(blobId));
                            }
                        } catch (Exception e) {
                            log.error("Error while reloading blob. truncating. id=" + state.getId() + " idx="
                                    + i + " size=" + size, e);
                            values[i] = InternalValue.create(new byte[0]);
                        }
                        val.discard();
                    }
                    // store id of blob as property value
                    out.writeUTF(blobId); // value
                } else {
                    // delete evt. blob
                    byte[] data = writeSmallBinary(out, val, state, i);
                    // replace value instance with value
                    // backed by resource in blob store and delete temp file
                    values[i] = InternalValue.create(data);
                    val.discard();
                }
            } catch (RepositoryException e) {
                String msg = "Error while storing blob. id=" + state.getId() + " idx=" + i + " value=" + val;
                log.error(msg, e);
                throw new IOException(msg);
            }
            break;
        case PropertyType.DOUBLE:
            try {
                out.writeDouble(val.getDouble());
            } catch (RepositoryException e) {
                // should never occur
                throw new IOException("Unexpected error while writing DOUBLE value.");
            }
            break;
        case PropertyType.DECIMAL:
            try {
                writeDecimal(out, val.getDecimal());
            } catch (RepositoryException e) {
                // should never occur
                throw new IOException("Unexpected error while writing DECIMAL value.");
            }
            break;
        case PropertyType.LONG:
            try {
                out.writeLong(val.getLong());
            } catch (RepositoryException e) {
                // should never occur
                throw new IOException("Unexpected error while writing LONG value.");
            }
            break;
        case PropertyType.BOOLEAN:
            try {
                out.writeBoolean(val.getBoolean());
            } catch (RepositoryException e) {
                // should never occur
                throw new IOException("Unexpected error while writing BOOLEAN value.");
            }
            break;
        case PropertyType.NAME:
            try {
                writeQName(out, val.getName());
            } catch (RepositoryException e) {
                // should never occur
                throw new IOException("Unexpected error while writing NAME value.");
            }
            break;
        case PropertyType.WEAKREFERENCE:
        case PropertyType.REFERENCE:
            writeID(out, val.getNodeId());
            break;
        default:
            // because writeUTF(String) has a size limit of 64k,
            // we're using write(byte[]) instead
            byte[] bytes = val.toString().getBytes("UTF-8");
            out.writeInt(bytes.length); // length of byte[]
            out.write(bytes); // byte[]
        }
    }
}

From source file:org.apache.jackrabbit.core.persistence.bundle.util.BundleBinding.java

/**
 * Serializes a <code>PropertyState</code> to the data output stream
 *
 * @param out the output stream/*  w  w  w. j  ava 2s  .  co m*/
 * @param state the property entry to store
 * @throws IOException if an I/O error occurs.
 */
public void writeState(DataOutputStream out, NodePropBundle.PropertyEntry state) throws IOException {
    // type & mod count
    out.writeInt(state.getType() | (state.getModCount() << 16));
    // multiValued
    out.writeBoolean(state.isMultiValued());
    // definitionId
    out.writeUTF(state.getPropDefId().toString());
    // values
    InternalValue[] values = state.getValues();
    out.writeInt(values.length); // count
    for (int i = 0; i < values.length; i++) {
        InternalValue val = values[i];
        switch (state.getType()) {
        case PropertyType.BINARY:
            try {
                long size = val.getLength();
                if (dataStore != null) {
                    int maxMemorySize = dataStore.getMinRecordLength() - 1;
                    if (size < maxMemorySize) {
                        writeSmallBinary(out, val, state, i);
                    } else {
                        out.writeInt(BINARY_IN_DATA_STORE);
                        val.store(dataStore);
                        out.writeUTF(val.toString());
                    }
                    break;
                }
                // special handling required for binary value:
                // spool binary value to file in blob store
                if (size < 0) {
                    log.warn("Blob has negative size. Potential loss of data. " + "id={} idx={}", state.getId(),
                            String.valueOf(i));
                    out.writeInt(0);
                    values[i] = InternalValue.create(new byte[0]);
                    val.discard();
                } else if (size > minBlobSize) {
                    out.writeInt(BINARY_IN_BLOB_STORE);
                    String blobId = state.getBlobId(i);
                    if (blobId == null) {
                        try {
                            InputStream in = val.getStream();
                            try {
                                blobId = blobStore.createId(state.getId(), i);
                                blobStore.put(blobId, in, size);
                                state.setBlobId(blobId, i);
                            } finally {
                                IOUtils.closeQuietly(in);
                            }
                        } catch (Exception e) {
                            String msg = "Error while storing blob. id=" + state.getId() + " idx=" + i
                                    + " size=" + size;
                            log.error(msg, e);
                            throw new IOException(msg);
                        }
                        try {
                            // replace value instance with value
                            // backed by resource in blob store and delete temp file
                            if (blobStore instanceof ResourceBasedBLOBStore) {
                                values[i] = InternalValue
                                        .create(((ResourceBasedBLOBStore) blobStore).getResource(blobId));
                            } else {
                                values[i] = InternalValue.create(blobStore.get(blobId));
                            }
                        } catch (Exception e) {
                            log.error("Error while reloading blob. truncating. id=" + state.getId() + " idx="
                                    + i + " size=" + size, e);
                            values[i] = InternalValue.create(new byte[0]);
                        }
                        val.discard();
                    }
                    // store id of blob as property value
                    out.writeUTF(blobId); // value
                } else {
                    // delete evt. blob
                    byte[] data = writeSmallBinary(out, val, state, i);
                    // replace value instance with value
                    // backed by resource in blob store and delete temp file
                    values[i] = InternalValue.create(data);
                    val.discard();
                }
            } catch (RepositoryException e) {
                String msg = "Error while storing blob. id=" + state.getId() + " idx=" + i + " value=" + val;
                log.error(msg, e);
                throw new IOException(msg);
            }
            break;
        case PropertyType.DOUBLE:
            try {
                out.writeDouble(val.getDouble());
            } catch (RepositoryException e) {
                // should never occur
                throw new IOException("Unexpected error while writing DOUBLE value.");
            }
            break;
        case PropertyType.DECIMAL:
            try {
                writeDecimal(out, val.getDecimal());
            } catch (RepositoryException e) {
                // should never occur
                throw new IOException("Unexpected error while writing DECIMAL value.");
            }
            break;
        case PropertyType.LONG:
            try {
                out.writeLong(val.getLong());
            } catch (RepositoryException e) {
                // should never occur
                throw new IOException("Unexpected error while writing LONG value.");
            }
            break;
        case PropertyType.BOOLEAN:
            try {
                out.writeBoolean(val.getBoolean());
            } catch (RepositoryException e) {
                // should never occur
                throw new IOException("Unexpected error while writing BOOLEAN value.");
            }
            break;
        case PropertyType.NAME:
            try {
                writeQName(out, val.getName());
            } catch (RepositoryException e) {
                // should never occur
                throw new IOException("Unexpected error while writing NAME value.");
            }
            break;
        case PropertyType.WEAKREFERENCE:
        case PropertyType.REFERENCE:
            writeUUID(out, val.getUUID());
            break;
        default:
            // because writeUTF(String) has a size limit of 64k,
            // we're using write(byte[]) instead
            byte[] bytes = val.toString().getBytes("UTF-8");
            out.writeInt(bytes.length); // length of byte[]
            out.write(bytes); // byte[]
        }
    }
}

From source file:carnero.cgeo.cgBase.java

public boolean runExternalMap(int application, Activity activity, Resources res, cgWarning warning,
        GoogleAnalyticsTracker tracker, cgCache cache, cgWaypoint waypoint, Double latitude, Double longitude) {
    if (cache == null && waypoint == null && latitude == null && longitude == null) {
        return false;
    }//from  w w w .j a va 2 s.c  o  m

    if (application == mapAppLocus) {
        // locus
        try {
            final Intent intentTest = new Intent(Intent.ACTION_VIEW);
            intentTest.setData(Uri.parse("menion.points:x"));

            if (isIntentAvailable(activity, intentTest) == true) {
                final ArrayList<cgWaypoint> waypoints = new ArrayList<cgWaypoint>();
                // get only waypoints with coordinates
                if (cache != null && cache.waypoints != null && cache.waypoints.isEmpty() == false) {
                    for (cgWaypoint wp : cache.waypoints) {
                        if (wp.latitude != null && wp.longitude != null) {
                            waypoints.add(wp);
                        }
                    }
                }

                final ByteArrayOutputStream baos = new ByteArrayOutputStream();
                final DataOutputStream dos = new DataOutputStream(baos);

                dos.writeInt(1); // not used
                if (cache != null) {
                    if (waypoints == null || waypoints.isEmpty() == true) {
                        dos.writeInt(1); // cache only
                    } else {
                        dos.writeInt((1 + waypoints.size())); // cache and waypoints
                    }
                } else {
                    dos.writeInt(1); // one waypoint
                }

                int icon = -1;
                if (cache != null) {
                    icon = getIcon(true, cache.type, cache.own, cache.found, cache.disabled || cache.archived);
                } else if (waypoint != null) {
                    icon = getIcon(false, waypoint.type, false, false, false);
                } else {
                    icon = getIcon(false, "waypoint", false, false, false);
                }

                if (icon > 0) {
                    // load icon
                    Bitmap bitmap = BitmapFactory.decodeResource(res, icon);
                    ByteArrayOutputStream baos2 = new ByteArrayOutputStream();
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos2);
                    byte[] image = baos2.toByteArray();

                    dos.writeInt(image.length);
                    dos.write(image);
                } else {
                    // no icon
                    dos.writeInt(0); // no image
                }

                // name
                if (cache != null && cache.name != null && cache.name.length() > 0) {
                    dos.writeUTF(cache.name);
                } else if (waypoint != null && waypoint.name != null && waypoint.name.length() > 0) {
                    dos.writeUTF(waypoint.name);
                } else {
                    dos.writeUTF("");
                }

                // description
                if (cache != null && cache.geocode != null && cache.geocode.length() > 0) {
                    dos.writeUTF(cache.geocode.toUpperCase());
                } else if (waypoint != null && waypoint.lookup != null && waypoint.lookup.length() > 0) {
                    dos.writeUTF(waypoint.lookup.toUpperCase());
                } else {
                    dos.writeUTF("");
                }

                // additional data :: keyword, button title, package, activity, data name, data content
                if (cache != null && cache.geocode != null && cache.geocode.length() > 0) {
                    dos.writeUTF("intent;c:geo;carnero.cgeo;carnero.cgeo.cgeodetail;geocode;" + cache.geocode);
                } else if (waypoint != null && waypoint.id != null && waypoint.id > 0) {
                    dos.writeUTF("intent;c:geo;carnero.cgeo;carnero.cgeo.cgeowaypoint;id;" + waypoint.id);
                } else {
                    dos.writeUTF("");
                }

                if (cache != null && cache.latitude != null && cache.longitude != null) {
                    dos.writeDouble(cache.latitude); // latitude
                    dos.writeDouble(cache.longitude); // longitude
                } else if (waypoint != null && waypoint.latitude != null && waypoint.longitude != null) {
                    dos.writeDouble(waypoint.latitude); // latitude
                    dos.writeDouble(waypoint.longitude); // longitude
                } else {
                    dos.writeDouble(latitude); // latitude
                    dos.writeDouble(longitude); // longitude
                }

                // cache waypoints
                if (waypoints != null && waypoints.isEmpty() == false) {
                    for (cgWaypoint wp : waypoints) {
                        if (wp == null || wp.latitude == null || wp.longitude == null) {
                            continue;
                        }

                        final int wpIcon = getIcon(false, wp.type, false, false, false);

                        if (wpIcon > 0) {
                            // load icon
                            Bitmap bitmap = BitmapFactory.decodeResource(res, wpIcon);
                            ByteArrayOutputStream baos2 = new ByteArrayOutputStream();
                            bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos2);
                            byte[] image = baos2.toByteArray();

                            dos.writeInt(image.length);
                            dos.write(image);
                        } else {
                            // no icon
                            dos.writeInt(0); // no image
                        }

                        // name
                        if (wp.lookup != null && wp.lookup.length() > 0) {
                            dos.writeUTF(wp.lookup.toUpperCase());
                        } else {
                            dos.writeUTF("");
                        }

                        // description
                        if (wp.name != null && wp.name.length() > 0) {
                            dos.writeUTF(wp.name);
                        } else {
                            dos.writeUTF("");
                        }

                        // additional data :: keyword, button title, package, activity, data name, data content
                        if (wp.id != null && wp.id > 0) {
                            dos.writeUTF("intent;c:geo;carnero.cgeo;carnero.cgeo.cgeowaypoint;id;" + wp.id);
                        } else {
                            dos.writeUTF("");
                        }

                        dos.writeDouble(wp.latitude); // latitude
                        dos.writeDouble(wp.longitude); // longitude
                    }
                }

                final Intent intent = new Intent();
                intent.setAction(Intent.ACTION_VIEW);
                intent.setData(Uri.parse("menion.points:data"));
                intent.putExtra("data", baos.toByteArray());

                activity.startActivity(intent);

                sendAnal(activity, tracker, "/external/locus");

                return true;
            }
        } catch (Exception e) {
            // nothing
        }
    }

    if (application == mapAppRmaps) {
        // rmaps
        try {
            final Intent intent = new Intent("com.robert.maps.action.SHOW_POINTS");

            if (isIntentAvailable(activity, intent) == true) {
                final ArrayList<String> locations = new ArrayList<String>();
                if (cache != null && cache.latitude != null && cache.longitude != null) {
                    locations.add(String.format((Locale) null, "%.6f", cache.latitude) + ","
                            + String.format((Locale) null, "%.6f", cache.longitude) + ";" + cache.geocode + ";"
                            + cache.name);
                } else if (waypoint != null && waypoint.latitude != null && waypoint.longitude != null) {
                    locations.add(String.format((Locale) null, "%.6f", waypoint.latitude) + ","
                            + String.format((Locale) null, "%.6f", waypoint.longitude) + ";" + waypoint.lookup
                            + ";" + waypoint.name);
                }

                intent.putStringArrayListExtra("locations", locations);

                activity.startActivity(intent);

                sendAnal(activity, tracker, "/external/rmaps");

                return true;
            }
        } catch (Exception e) {
            // nothing
        }
    }

    if (application == mapAppAny) {
        // fallback
        try {
            if (cache != null && cache.latitude != null && cache.longitude != null) {
                activity.startActivity(new Intent(Intent.ACTION_VIEW,
                        Uri.parse("geo:" + cache.latitude + "," + cache.longitude)));
                // INFO: q parameter works with Google Maps, but breaks cooperation with all other apps
            } else if (waypoint != null && waypoint.latitude != null && waypoint.longitude != null) {
                activity.startActivity(new Intent(Intent.ACTION_VIEW,
                        Uri.parse("geo:" + waypoint.latitude + "," + waypoint.longitude)));
                // INFO: q parameter works with Google Maps, but breaks cooperation with all other apps
            }

            sendAnal(activity, tracker, "/external/native/maps");

            return true;
        } catch (Exception e) {
            // nothing
        }
    }

    Log.i(cgSettings.tag, "cgBase.runExternalMap: No maps application available.");

    if (warning != null && res != null) {
        warning.showToast(res.getString(R.string.err_application_no));
    }

    return false;
}

From source file:be.ibridge.kettle.spoon.Spoon.java

private boolean save(TransMeta transMeta, String fname) {
    boolean saved = false;
    String xml = XMLHandler.getXMLHeader() + transMeta.getXML();
    try {//from ww  w . j  a  v a2  s.c  o m
        DataOutputStream dos = new DataOutputStream(KettleVFS.getOutputStream(fname, false));
        dos.write(xml.getBytes(Const.XML_ENCODING));
        dos.close();

        saved = true;

        // Handle last opened files...
        props.addLastFile(LastUsedFile.FILE_TYPE_TRANSFORMATION, fname, null, false, null);
        saveSettings();
        addMenuLast();

        transMeta.clearChanged();
        setShellText();
        log.logDebug(toString(), Messages.getString("Spoon.Log.FileWritten") + " [" + fname + "]"); //"File written to
    } catch (Exception e) {
        log.logDebug(toString(), Messages.getString("Spoon.Log.ErrorOpeningFileForWriting") + e.toString());//"Error opening file for writing! --> "
        MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR);
        mb.setMessage(Messages.getString("Spoon.Dialog.ErrorSavingFile.Message") + Const.CR + e.toString());//"Error saving file:"
        mb.setText(Messages.getString("Spoon.Dialog.ErrorSavingFile.Title"));//"ERROR"
        mb.open();
    }

    return saved;
}

From source file:be.ibridge.kettle.spoon.Spoon.java

private boolean saveJob(JobMeta jobMeta, String fname) {
    boolean saved = false;
    String xml = XMLHandler.getXMLHeader() + jobMeta.getXML();
    try {//from   w  ww . ja v  a2 s .c  o m
        DataOutputStream dos = new DataOutputStream(KettleVFS.getOutputStream(fname, false));
        dos.write(xml.getBytes(Const.XML_ENCODING));
        dos.close();

        saved = true;

        // Handle last opened files...
        props.addLastFile(LastUsedFile.FILE_TYPE_JOB, fname, RepositoryDirectory.DIRECTORY_SEPARATOR, false,
                ""); //$NON-NLS-1$
        saveSettings();
        addMenuLast();

        log.logDebug(toString(), "File written to [" + fname + "]"); //$NON-NLS-1$ //$NON-NLS-2$
        jobMeta.setFilename(fname);
        jobMeta.clearChanged();
        setShellText();
    } catch (Exception e) {
        log.logDebug(toString(), "Error opening file for writing! --> " + e.toString()); //$NON-NLS-1$
        MessageBox mb = new MessageBox(shell, SWT.OK | SWT.ICON_ERROR);
        mb.setMessage(Messages.getString("Spoon.Dialog.ErrorSavingFile.Message") + Const.CR + e.toString()); //$NON-NLS-1$
        mb.setText(Messages.getString("Spoon.Dialog.ErrorSavingFile.Title")); //$NON-NLS-1$
        mb.open();
    }
    return saved;
}

From source file:com.codename1.impl.android.AndroidImplementation.java

public static void appendNotification(String type, String body, String image, String category, Context a) {
    try {/*from w  w w.  j  a v  a 2 s.  c  om*/
        String[] fileList = a.fileList();
        byte[] data = null;
        for (int iter = 0; iter < fileList.length; iter++) {
            if (fileList[iter].equals("CN1$AndroidPendingNotifications")) {
                InputStream is = a.openFileInput("CN1$AndroidPendingNotifications");
                if (is != null) {
                    data = readInputStream(is);
                    sCleanup(a);
                    break;
                }
            }
        }
        DataOutputStream os = new DataOutputStream(a.openFileOutput("CN1$AndroidPendingNotifications", 0));
        if (data != null) {
            data[0]++;
            os.write(data);
        } else {
            os.writeByte(1);
        }
        String bodyType = type;
        if (image != null || category != null) {
            type = "99";
        }
        if (type != null) {
            os.writeBoolean(true);
            os.writeUTF(type);
        } else {
            os.writeBoolean(false);
        }
        if ("99".equals(type)) {
            String msg = "body=" + java.net.URLEncoder.encode(body, "UTF-8") + "&type="
                    + java.net.URLEncoder.encode(bodyType, "UTF-8");
            if (category != null) {
                msg += "&category=" + java.net.URLEncoder.encode(category, "UTF-8");
            }
            if (image != null) {
                image += "&image=" + java.net.URLEncoder.encode(image, "UTF-8");
            }
            os.writeUTF(msg);

        } else {
            os.writeUTF(body);
        }
        os.writeLong(System.currentTimeMillis());
    } catch (IOException err) {
        err.printStackTrace();
    }
}