Example usage for org.apache.hadoop.io BooleanWritable set

List of usage examples for org.apache.hadoop.io BooleanWritable set

Introduction

In this page you can find the example usage for org.apache.hadoop.io BooleanWritable set.

Prototype

public void set(boolean value) 

Source Link

Document

Set the value of the BooleanWritable

Usage

From source file:com.datasalt.utils.commons.TestExpiringSemaphore.java

License:Apache License

@Test
public void testParallelism() throws InterruptedException {
    final ExpiringSemaphore semaphore = new ExpiringSemaphore(1, 2000);
    final BooleanWritable flag = new BooleanWritable();

    Thread[] threads = new Thread[10];

    for (int i = 0; i < 10; i++) {
        threads[i] = new Thread() {
            @Override//ww  w.  j  a v  a  2 s. com
            public void run() {
                try {
                    for (int i = 0; i < 200; i++) {
                        semaphore.acquire();
                        if (flag.get()) {
                            throw new RuntimeException("Semaphore is not behaving as expected");
                        }
                        flag.set(true);
                        flag.set(false);
                        semaphore.release();
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        };
    }

    for (int i = 0; i < 10; i++) {
        threads[i].start();
    }

    for (int i = 0; i < 10; i++) {
        threads[i].join();
    }
}

From source file:com.ebay.nest.io.sede.binarysortable.BinarySortableSerDe.java

License:Apache License

static Object deserialize(InputByteBuffer buffer, TypeInfo type, boolean invert, Object reuse)
        throws IOException {

    // Is this field a null?
    byte isNull = buffer.read(invert);
    if (isNull == 0) {
        return null;
    }/*from w w  w. java  2 s  .  co m*/
    assert (isNull == 1);

    switch (type.getCategory()) {
    case PRIMITIVE: {
        PrimitiveTypeInfo ptype = (PrimitiveTypeInfo) type;
        switch (ptype.getPrimitiveCategory()) {
        case VOID: {
            return null;
        }
        case BOOLEAN: {
            BooleanWritable r = reuse == null ? new BooleanWritable() : (BooleanWritable) reuse;
            byte b = buffer.read(invert);
            assert (b == 1 || b == 2);
            r.set(b == 2);
            return r;
        }
        case BYTE: {
            ByteWritable r = reuse == null ? new ByteWritable() : (ByteWritable) reuse;
            r.set((byte) (buffer.read(invert) ^ 0x80));
            return r;
        }
        case SHORT: {
            ShortWritable r = reuse == null ? new ShortWritable() : (ShortWritable) reuse;
            int v = buffer.read(invert) ^ 0x80;
            v = (v << 8) + (buffer.read(invert) & 0xff);
            r.set((short) v);
            return r;
        }
        case INT: {
            IntWritable r = reuse == null ? new IntWritable() : (IntWritable) reuse;
            r.set(deserializeInt(buffer, invert));
            return r;
        }
        case LONG: {
            LongWritable r = reuse == null ? new LongWritable() : (LongWritable) reuse;
            long v = buffer.read(invert) ^ 0x80;
            for (int i = 0; i < 7; i++) {
                v = (v << 8) + (buffer.read(invert) & 0xff);
            }
            r.set(v);
            return r;
        }
        case FLOAT: {
            FloatWritable r = reuse == null ? new FloatWritable() : (FloatWritable) reuse;
            int v = 0;
            for (int i = 0; i < 4; i++) {
                v = (v << 8) + (buffer.read(invert) & 0xff);
            }
            if ((v & (1 << 31)) == 0) {
                // negative number, flip all bits
                v = ~v;
            } else {
                // positive number, flip the first bit
                v = v ^ (1 << 31);
            }
            r.set(Float.intBitsToFloat(v));
            return r;
        }
        case DOUBLE: {
            DoubleWritable r = reuse == null ? new DoubleWritable() : (DoubleWritable) reuse;
            long v = 0;
            for (int i = 0; i < 8; i++) {
                v = (v << 8) + (buffer.read(invert) & 0xff);
            }
            if ((v & (1L << 63)) == 0) {
                // negative number, flip all bits
                v = ~v;
            } else {
                // positive number, flip the first bit
                v = v ^ (1L << 63);
            }
            r.set(Double.longBitsToDouble(v));
            return r;
        }
        case STRING: {
            Text r = reuse == null ? new Text() : (Text) reuse;
            return deserializeText(buffer, invert, r);
        }

        case VARCHAR: {
            HiveVarcharWritable r = reuse == null ? new HiveVarcharWritable() : (HiveVarcharWritable) reuse;
            // Use HiveVarchar's internal Text member to read the value.
            deserializeText(buffer, invert, r.getTextValue());
            // If we cache helper data for deserialization we could avoid having
            // to call getVarcharMaxLength() on every deserialize call.
            r.enforceMaxLength(getVarcharMaxLength(type));
            return r;
        }

        case BINARY: {
            BytesWritable bw = new BytesWritable();
            // Get the actual length first
            int start = buffer.tell();
            int length = 0;
            do {
                byte b = buffer.read(invert);
                if (b == 0) {
                    // end of string
                    break;
                }
                if (b == 1) {
                    // the last char is an escape char. read the actual char
                    buffer.read(invert);
                }
                length++;
            } while (true);

            if (length == buffer.tell() - start) {
                // No escaping happened, so we are already done.
                bw.set(buffer.getData(), start, length);
            } else {
                // Escaping happened, we need to copy byte-by-byte.
                // 1. Set the length first.
                bw.set(buffer.getData(), start, length);
                // 2. Reset the pointer.
                buffer.seek(start);
                // 3. Copy the data.
                byte[] rdata = bw.getBytes();
                for (int i = 0; i < length; i++) {
                    byte b = buffer.read(invert);
                    if (b == 1) {
                        // The last char is an escape char, read the actual char.
                        // The serialization format escape \0 to \1, and \1 to \2,
                        // to make sure the string is null-terminated.
                        b = (byte) (buffer.read(invert) - 1);
                    }
                    rdata[i] = b;
                }
                // 4. Read the null terminator.
                byte b = buffer.read(invert);
                assert (b == 0);
            }
            return bw;
        }

        case DATE: {
            DateWritable d = reuse == null ? new DateWritable() : (DateWritable) reuse;
            d.set(deserializeInt(buffer, invert));
            return d;
        }

        case TIMESTAMP:
            TimestampWritable t = (reuse == null ? new TimestampWritable() : (TimestampWritable) reuse);
            byte[] bytes = new byte[TimestampWritable.BINARY_SORTABLE_LENGTH];

            for (int i = 0; i < bytes.length; i++) {
                bytes[i] = buffer.read(invert);
            }
            t.setBinarySortable(bytes, 0);
            return t;

        case DECIMAL: {
            // See serialization of decimal for explanation (below)

            HiveDecimalWritable bdw = (reuse == null ? new HiveDecimalWritable() : (HiveDecimalWritable) reuse);

            int b = buffer.read(invert) - 1;
            assert (b == 1 || b == -1 || b == 0);
            boolean positive = b != -1;

            int factor = buffer.read(invert) ^ 0x80;
            for (int i = 0; i < 3; i++) {
                factor = (factor << 8) + (buffer.read(invert) & 0xff);
            }

            if (!positive) {
                factor = -factor;
            }

            int start = buffer.tell();
            int length = 0;

            do {
                b = buffer.read(positive ? invert : !invert);
                assert (b != 1);

                if (b == 0) {
                    // end of digits
                    break;
                }

                length++;
            } while (true);

            if (decimalBuffer == null || decimalBuffer.length < length) {
                decimalBuffer = new byte[length];
            }

            buffer.seek(start);
            for (int i = 0; i < length; ++i) {
                decimalBuffer[i] = buffer.read(positive ? invert : !invert);
            }

            // read the null byte again
            buffer.read(positive ? invert : !invert);

            String digits = new String(decimalBuffer, 0, length, decimalCharSet);
            BigInteger bi = new BigInteger(digits);
            HiveDecimal bd = new HiveDecimal(bi).scaleByPowerOfTen(factor - length);

            if (!positive) {
                bd = bd.negate();
            }

            bdw.set(bd);
            return bdw;
        }

        default: {
            throw new RuntimeException("Unrecognized type: " + ptype.getPrimitiveCategory());
        }
        }
    }

    case LIST: {
        ListTypeInfo ltype = (ListTypeInfo) type;
        TypeInfo etype = ltype.getListElementTypeInfo();

        // Create the list if needed
        ArrayList<Object> r = reuse == null ? new ArrayList<Object>() : (ArrayList<Object>) reuse;

        // Read the list
        int size = 0;
        while (true) {
            int more = buffer.read(invert);
            if (more == 0) {
                // \0 to terminate
                break;
            }
            // \1 followed by each element
            assert (more == 1);
            if (size == r.size()) {
                r.add(null);
            }
            r.set(size, deserialize(buffer, etype, invert, r.get(size)));
            size++;
        }
        // Remove additional elements if the list is reused
        while (r.size() > size) {
            r.remove(r.size() - 1);
        }
        return r;
    }
    case MAP: {
        MapTypeInfo mtype = (MapTypeInfo) type;
        TypeInfo ktype = mtype.getMapKeyTypeInfo();
        TypeInfo vtype = mtype.getMapValueTypeInfo();

        // Create the map if needed
        Map<Object, Object> r;
        if (reuse == null) {
            r = new HashMap<Object, Object>();
        } else {
            r = (HashMap<Object, Object>) reuse;
            r.clear();
        }

        while (true) {
            int more = buffer.read(invert);
            if (more == 0) {
                // \0 to terminate
                break;
            }
            // \1 followed by each key and then each value
            assert (more == 1);
            Object k = deserialize(buffer, ktype, invert, null);
            Object v = deserialize(buffer, vtype, invert, null);
            r.put(k, v);
        }
        return r;
    }
    case STRUCT: {
        StructTypeInfo stype = (StructTypeInfo) type;
        List<TypeInfo> fieldTypes = stype.getAllStructFieldTypeInfos();
        int size = fieldTypes.size();
        // Create the struct if needed
        ArrayList<Object> r = reuse == null ? new ArrayList<Object>(size) : (ArrayList<Object>) reuse;
        assert (r.size() <= size);
        // Set the size of the struct
        while (r.size() < size) {
            r.add(null);
        }
        // Read one field by one field
        for (int eid = 0; eid < size; eid++) {
            r.set(eid, deserialize(buffer, fieldTypes.get(eid), invert, r.get(eid)));
        }
        return r;
    }
    case UNION: {
        UnionTypeInfo utype = (UnionTypeInfo) type;
        StandardUnion r = reuse == null ? new StandardUnion() : (StandardUnion) reuse;
        // Read the tag
        byte tag = buffer.read(invert);
        r.setTag(tag);
        r.setObject(deserialize(buffer, utype.getAllUnionObjectTypeInfos().get(tag), invert, null));
        return r;
    }
    default: {
        throw new RuntimeException("Unrecognized type: " + type.getCategory());
    }
    }
}

From source file:com.facebook.hive.orc.lazy.LazyBooleanTreeReader.java

License:Open Source License

BooleanWritable createWritable(Object previous, boolean v) throws IOException {
    BooleanWritable result = null;
    if (previous == null) {
        result = new BooleanWritable();
    } else {//w w  w.  ja va  2  s . co  m
        result = (BooleanWritable) previous;
    }
    result.set(v);
    return result;
}

From source file:com.jfolson.hive.serde.RBaseSerDe.java

License:Apache License

protected void serializeField(Object o, ObjectInspector oi, Object reuse) throws IOException {
    //LOG.info("Serializing hive type: "+oi.getTypeName());
    //LOG.info("Serializing category: "+oi.getCategory().toString());
    if (o == null) {
        tbOut.writeNull();//from  ww  w  .ja v a2s .c o  m
        return;
    }
    switch (oi.getCategory()) {
    case PRIMITIVE: {
        PrimitiveObjectInspector poi = (PrimitiveObjectInspector) oi;
        //LOG.info("Serializing primitive: "+poi.getPrimitiveCategory().toString());
        switch (poi.getPrimitiveCategory()) {
        case VOID: {
            return;
        }
        case BINARY: {
            BinaryObjectInspector boi = (BinaryObjectInspector) poi;
            TypedBytesWritable bytes = reuse == null ? new TypedBytesWritable() : (TypedBytesWritable) reuse;
            BytesWritable bytesWrite = boi.getPrimitiveWritableObject(o);
            if (bytesWrite != null) {
                bytes.set(bytesWrite);
                if (!RType.isValid(bytes)) {
                    LOG.error("Invalid typedbytes detected with type: " + RType.getType(bytes).code);
                    bytes.setValue(new Buffer(bytesWrite.getBytes(), 0, bytesWrite.getLength()));
                }
                //LOG.info("Writing binary primitive with class: "+bytes.getClass().getName());
                tbOut.write(bytes);
            }

            return;
        }
        case BOOLEAN: {
            BooleanObjectInspector boi = (BooleanObjectInspector) poi;
            BooleanWritable r = reuse == null ? new BooleanWritable() : (BooleanWritable) reuse;
            r.set(boi.get(o));
            tbOut.write(r);
            return;
        }
        case BYTE: {
            ByteObjectInspector boi = (ByteObjectInspector) poi;
            ByteWritable r = reuse == null ? new ByteWritable() : (ByteWritable) reuse;
            r.set(boi.get(o));
            tbOut.write(r);
            return;
        }
        case SHORT: {
            ShortObjectInspector spoi = (ShortObjectInspector) poi;
            ShortWritable r = reuse == null ? new ShortWritable() : (ShortWritable) reuse;
            r.set(spoi.get(o));
            tbOut.write(r);
            return;
        }
        case INT: {
            IntObjectInspector ioi = (IntObjectInspector) poi;
            IntWritable r = reuse == null ? new IntWritable() : (IntWritable) reuse;
            r.set(ioi.get(o));
            tbOut.write(r);
            return;
        }
        case LONG: {
            LongObjectInspector loi = (LongObjectInspector) poi;
            LongWritable r = reuse == null ? new LongWritable() : (LongWritable) reuse;
            r.set(loi.get(o));
            tbOut.write(r);
            return;
        }
        case FLOAT: {
            FloatObjectInspector foi = (FloatObjectInspector) poi;
            FloatWritable r = reuse == null ? new FloatWritable() : (FloatWritable) reuse;
            r.set(foi.get(o));
            tbOut.write(r);
            return;
        }
        case DOUBLE:
            DoubleObjectInspector doi = (DoubleObjectInspector) poi;
            DoubleWritable r = reuse == null ? new DoubleWritable() : (DoubleWritable) reuse;
            r.set(doi.get(o));
            tbOut.write(r);
            return;
        case STRING: {
            StringObjectInspector soi = (StringObjectInspector) poi;
            Text t = soi.getPrimitiveWritableObject(o);
            tbOut.write(t);
            return;
        }
        default: {
            throw new RuntimeException("Unrecognized type: " + poi.getPrimitiveCategory());
        }
        }
    }
    case LIST: {
        ListObjectInspector loi = (ListObjectInspector) oi;
        ObjectInspector elemOI = loi.getListElementObjectInspector();
        List l = loi.getList(o);
        // Don't use array (typecode: 144) until everything supports NA values in typedbytes
        if (false) {//(elemOI.getCategory()==ObjectInspector.Category.PRIMITIVE){
            tbOut.writeArray(l, (PrimitiveObjectInspector) elemOI);
        } else {
            tbOut.writeVector(l, (PrimitiveObjectInspector) elemOI);
        }
        return;
    }
    case MAP:
    case STRUCT: {
        // For complex object, serialize to JSON format
        String s = SerDeUtils.getJSONString(o, oi);
        Text t = reuse == null ? new Text() : (Text) reuse;

        // convert to Text and write it
        t.set(s);
        tbOut.write(t);
        return;
    }
    default: {
        throw new RuntimeException("Unrecognized type: " + oi.getCategory());
    }
    }
}

From source file:com.jfolson.hive.serde.RTypedBytesSerDe.java

License:Apache License

private void serializeField(Object o, ObjectInspector oi, Object reuse) throws IOException {
    //LOG.info("Serializing hive type: "+oi.getTypeName());
    //LOG.info("Serializing category: "+oi.getCategory().toString());
    if (o == null) {
        tbOut.writeNull();//from ww  w  .  j  a  v  a2s  . c om
        return;
    }
    switch (oi.getCategory()) {
    case PRIMITIVE: {
        PrimitiveObjectInspector poi = (PrimitiveObjectInspector) oi;
        //LOG.info("Serializing primitive: "+poi.getPrimitiveCategory().toString());
        switch (poi.getPrimitiveCategory()) {
        case VOID: {
            return;
        }
        case BINARY: {
            BinaryObjectInspector boi = (BinaryObjectInspector) poi;
            TypedBytesWritable bytes = reuse == null ? new TypedBytesWritable() : (TypedBytesWritable) reuse;
            BytesWritable bytesWrite = boi.getPrimitiveWritableObject(o);
            if (bytesWrite != null) {
                bytes.set(bytesWrite);
                if (!RType.isValid(bytes)) {
                    LOG.error("Invalid typedbytes detected with type: " + RType.getType(bytes).code);
                    bytes.setValue(new Buffer(bytesWrite.getBytes(), 0, bytesWrite.getLength()));
                }
                //LOG.info("Writing binary primitive with class: "+bytes.getClass().getName());
                tbOut.write(bytes);
            }

            return;
        }
        case BOOLEAN: {
            BooleanObjectInspector boi = (BooleanObjectInspector) poi;
            BooleanWritable r = reuse == null ? new BooleanWritable() : (BooleanWritable) reuse;
            r.set(boi.get(o));
            tbOut.write(r);
            return;
        }
        case BYTE: {
            ByteObjectInspector boi = (ByteObjectInspector) poi;
            ByteWritable r = reuse == null ? new ByteWritable() : (ByteWritable) reuse;
            r.set(boi.get(o));
            tbOut.write(r);
            return;
        }
        case SHORT: {
            ShortObjectInspector spoi = (ShortObjectInspector) poi;
            ShortWritable r = reuse == null ? new ShortWritable() : (ShortWritable) reuse;
            r.set(spoi.get(o));
            tbOut.write(r);
            return;
        }
        case INT: {
            IntObjectInspector ioi = (IntObjectInspector) poi;
            IntWritable r = reuse == null ? new IntWritable() : (IntWritable) reuse;
            r.set(ioi.get(o));
            tbOut.write(r);
            return;
        }
        case LONG: {
            LongObjectInspector loi = (LongObjectInspector) poi;
            LongWritable r = reuse == null ? new LongWritable() : (LongWritable) reuse;
            r.set(loi.get(o));
            tbOut.write(r);
            return;
        }
        case FLOAT: {
            FloatObjectInspector foi = (FloatObjectInspector) poi;
            FloatWritable r = reuse == null ? new FloatWritable() : (FloatWritable) reuse;
            r.set(foi.get(o));
            tbOut.write(r);
            return;
        }
        case DOUBLE:
            DoubleObjectInspector doi = (DoubleObjectInspector) poi;
            DoubleWritable r = reuse == null ? new DoubleWritable() : (DoubleWritable) reuse;
            r.set(doi.get(o));
            tbOut.write(r);
            return;
        case STRING: {
            StringObjectInspector soi = (StringObjectInspector) poi;
            Text t = soi.getPrimitiveWritableObject(o);
            tbOut.write(t);
            return;
        }
        default: {
            throw new RuntimeException("Unrecognized type: " + poi.getPrimitiveCategory());
        }
        }
    }
    case LIST: {
        ListObjectInspector loi = (ListObjectInspector) oi;
        ObjectInspector elemOI = loi.getListElementObjectInspector();
        List l = loi.getList(o);
        if (false) {//(elemOI.getCategory()==ObjectInspector.Category.PRIMITIVE){
            tbOut.writeArray(l, (PrimitiveObjectInspector) elemOI);
        } else {
            tbOut.writeVector(l, (PrimitiveObjectInspector) elemOI);
        }
        return;
    }
    case MAP:
    case STRUCT: {
        // For complex object, serialize to JSON format
        String s = SerDeUtils.getJSONString(o, oi);
        Text t = reuse == null ? new Text() : (Text) reuse;

        // convert to Text and write it
        t.set(s);
        tbOut.write(t);
        return;
    }
    default: {
        throw new RuntimeException("Unrecognized type: " + oi.getCategory());
    }
    }
}

From source file:com.jfolson.hive.serde.RTypedBytesWritableInput.java

License:Apache License

public BooleanWritable readBoolean(BooleanWritable bw) throws IOException {
    if (bw == null) {
        bw = new BooleanWritable();
    }/*from  w  w  w .  j av  a  2 s .  c om*/
    bw.set(in.readBool());
    return bw;
}

From source file:com.ricemap.spateDB.operations.RangeQuery.java

License:Apache License

public static void main(String[] args) throws IOException {
    CommandLineArguments cla = new CommandLineArguments(args);
    final QueryInput query = cla.getQuery();
    final Path[] paths = cla.getPaths();
    if (paths.length == 0 || (cla.getPrism() == null && cla.getSelectionRatio() < 0.0f)) {
        printUsage();/*from  www.ja v  a 2 s.co  m*/
        throw new RuntimeException("Illegal parameters");
    }
    JobConf conf = new JobConf(FileMBR.class);
    final Path inputFile = paths[0];
    final FileSystem fs = inputFile.getFileSystem(conf);
    if (!fs.exists(inputFile)) {
        printUsage();
        throw new RuntimeException("Input file does not exist");
    }
    final Path outputPath = paths.length > 1 ? paths[1] : null;
    final Prism[] queryRanges = cla.getPrisms();
    int concurrency = cla.getConcurrency();
    final Shape stockShape = cla.getShape(true);
    final boolean overwrite = cla.isOverwrite();

    final long[] results = new long[queryRanges.length];
    final Vector<Thread> threads = new Vector<Thread>();

    final BooleanWritable exceptionHappened = new BooleanWritable();

    Thread.UncaughtExceptionHandler h = new Thread.UncaughtExceptionHandler() {
        public void uncaughtException(Thread th, Throwable ex) {
            ex.printStackTrace();
            exceptionHappened.set(true);
        }
    };

    for (int i = 0; i < queryRanges.length; i++) {
        Thread t = new Thread() {
            @Override
            public void run() {
                try {
                    int thread_i = threads.indexOf(this);

                    long result_count = rangeQueryMapReduce(fs, inputFile, outputPath, queryRanges[thread_i],
                            stockShape, overwrite, false, query);
                    results[thread_i] = result_count;
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        };
        t.setUncaughtExceptionHandler(h);
        threads.add(t);
    }

    long t1 = System.currentTimeMillis();
    do {
        // Ensure that there is at least MaxConcurrentThreads running
        int i = 0;
        while (i < concurrency && i < threads.size()) {
            Thread.State state = threads.elementAt(i).getState();
            if (state == Thread.State.TERMINATED) {
                // Thread already terminated, remove from the queue
                threads.remove(i);
            } else if (state == Thread.State.NEW) {
                // Start the thread and move to next one
                threads.elementAt(i++).start();
            } else {
                // Thread is still running, skip over it
                i++;
            }
        }
        if (!threads.isEmpty()) {
            try {
                // Sleep for 10 seconds or until the first thread terminates
                threads.firstElement().join(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    } while (!threads.isEmpty());
    long t2 = System.currentTimeMillis();

    if (exceptionHappened.get())
        throw new RuntimeException("Not all jobs finished correctly");
    System.out.println("Time for " + queryRanges.length + " jobs is " + (t2 - t1) + " millis");

    System.out.print("Result size: [");
    for (long result : results) {
        System.out.print(result + ", ");
    }
    System.out.println("]");
}

From source file:edu.umn.cs.spatialHadoop.operations.KNN.java

License:Open Source License

public static void main(String[] args) throws IOException {
    final OperationsParams params = new OperationsParams(new GenericOptionsParser(args));
    Path[] paths = params.getPaths();
    if (paths.length <= 1 && !params.checkInput()) {
        printUsage();// w  w w.  j  a  v  a2s .  c  om
        System.exit(1);
    }
    if (paths.length > 1 && !params.checkInputOutput()) {
        printUsage();
        System.exit(1);
    }
    final Path inputFile = params.getInputPath();
    int count = params.getInt("count", 1);
    double closeness = params.getFloat("closeness", -1.0f);
    final Point[] queryPoints = closeness < 0 ? params.getShapes("point", new Point()) : new Point[count];
    final FileSystem fs = inputFile.getFileSystem(params);
    final int k = params.getInt("k", 1);
    int concurrency = params.getInt("concurrency", 100);
    if (k == 0) {
        LOG.warn("k = 0");
    }

    if (queryPoints.length == 0) {
        printUsage();
        throw new RuntimeException("Illegal arguments");
    }
    final Path outputPath = paths.length > 1 ? paths[1] : null;

    if (closeness >= 0) {
        // Get query points according to its closeness to grid intersections
        GlobalIndex<Partition> gindex = SpatialSite.getGlobalIndex(fs, inputFile);
        long seed = params.getLong("seed", System.currentTimeMillis());
        Random random = new Random(seed);
        for (int i = 0; i < count; i++) {
            int i_block = random.nextInt(gindex.size());
            int direction = random.nextInt(4);
            // Generate a point in the given direction
            // Get center point (x, y)
            Iterator<Partition> iterator = gindex.iterator();
            while (i_block-- >= 0)
                iterator.next();
            Partition partition = iterator.next();
            double cx = (partition.x1 + partition.x2) / 2;
            double cy = (partition.y1 + partition.y2) / 2;
            double cw = partition.x2 - partition.x1;
            double ch = partition.y2 - partition.y1;
            int signx = ((direction & 1) == 0) ? 1 : -1;
            int signy = ((direction & 2) == 1) ? 1 : -1;
            double x = cx + cw * closeness / 2 * signx;
            double y = cy + ch * closeness / 2 * signy;
            queryPoints[i] = new Point(x, y);
        }
    }

    final BooleanWritable exceptionHappened = new BooleanWritable();

    Thread.UncaughtExceptionHandler h = new Thread.UncaughtExceptionHandler() {
        public void uncaughtException(Thread th, Throwable ex) {
            ex.printStackTrace();
            exceptionHappened.set(true);
        }
    };

    // Run each query in a separate thread
    final Vector<Thread> threads = new Vector<Thread>();
    for (int i = 0; i < queryPoints.length; i++) {
        Thread thread = new Thread() {
            @Override
            public void run() {
                try {
                    Point query_point = queryPoints[threads.indexOf(this)];
                    OperationsParams newParams = new OperationsParams(params);
                    OperationsParams.setShape(newParams, "point", query_point);
                    Job job = knn(inputFile, outputPath, params);
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
        };
        thread.setUncaughtExceptionHandler(h);
        threads.add(thread);
    }

    long t1 = System.currentTimeMillis();
    do {
        // Ensure that there is at least MaxConcurrentThreads running
        int i = 0;
        while (i < concurrency && i < threads.size()) {
            Thread.State state = threads.elementAt(i).getState();
            if (state == Thread.State.TERMINATED) {
                // Thread already terminated, remove from the queue
                threads.remove(i);
            } else if (state == Thread.State.NEW) {
                // Start the thread and move to next one
                threads.elementAt(i++).start();
            } else {
                // Thread is still running, skip over it
                i++;
            }
        }
        if (!threads.isEmpty()) {
            try {
                // Sleep for 10 seconds or until the first thread terminates
                threads.firstElement().join(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    } while (!threads.isEmpty());
    long t2 = System.currentTimeMillis();
    if (exceptionHappened.get())
        throw new RuntimeException("Not all jobs finished correctly");

    System.out.println("Time for " + queryPoints.length + " jobs is " + (t2 - t1) + " millis");
    System.out.println("Total iterations: " + TotalIterations);
}

From source file:edu.umn.cs.sthadoop.operations.HSPKNNQ.java

License:Open Source License

public static void main(String[] args) throws IOException {

    //./hadoop jar /export/scratch/louai/idea-stHadoop/st-hadoop-uber.jar pknn /mntgIndex/yyyy-MM-dd/2017-08-03 /pknn k:2 point:-78.9659,35.7998 shape:edu.umn.cs.sthadoop.mntg.STPointMntg -overwrite  
    //    args = new String[8];
    //    args[0] = "/export/scratch/mntgData/mntgIndex";
    //    args[1] = "/export/scratch/mntgData/pknn";
    //    args[2] = "-overwrite";
    //    args[3] = "k:10";
    //    args[4] = "point:-78.9659063204100,35.7903907684998";
    //    args[5] = "shape:edu.umn.cs.sthadoop.trajectory.STPointTrajectory";
    //    args[6] = "interval:2017-08-03,2017-08-04";
    //    args[7] = "-overwrite";
    final OperationsParams params = new OperationsParams(new GenericOptionsParser(args));
    Path[] paths = params.getPaths();
    if (paths.length <= 1 && !params.checkInput()) {
        printUsage();/*from  ww  w.ja va  2s  . c  o m*/
        System.exit(1);
    }
    if (paths.length > 1 && !params.checkInputOutput()) {
        printUsage();
        System.exit(1);
    }

    if (params.get("interval") == null) {
        System.err.println("Temporal range missing");
        printUsage();
        System.exit(1);
    }

    TextSerializable inObj = params.getShape("shape");
    if (!(inObj instanceof STPoint)) {
        if (!(inObj instanceof STRectangle)) {
            LOG.error("Shape is not instance of STPoint or instance of STRectangle");
            printUsage();
            System.exit(1);
        }

    }

    // path to the spatio-temporal index.
    List<Path> STPaths = new ArrayList<Path>();

    try {
        STPaths = STRangeQuery.getIndexedSlices(params);

    } catch (Exception e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    for (Path input : STPaths) {

        final Path inputFile = input;
        int count = params.getInt("count", 1);
        double closeness = params.getFloat("closeness", -1.0f);
        final Point[] queryPoints = closeness < 0 ? params.getShapes("point", new Point()) : new Point[count];
        final FileSystem fs = inputFile.getFileSystem(params);
        final int k = params.getInt("k", 1);
        int concurrency = params.getInt("concurrency", 100);
        if (k == 0) {
            LOG.warn("k = 0");
        }

        if (queryPoints.length == 0) {
            printUsage();
            throw new RuntimeException("Illegal arguments");
        }
        final Path outputPath = paths.length > 1 ? new Path(paths[1].toUri() + "-" + input.getName()) : null;

        if (closeness >= 0) {
            // Get query points according to its closeness to grid intersections
            GlobalIndex<Partition> gindex = SpatialSite.getGlobalIndex(fs, inputFile);
            long seed = params.getLong("seed", System.currentTimeMillis());
            Random random = new Random(seed);
            for (int i = 0; i < count; i++) {
                int i_block = random.nextInt(gindex.size());
                int direction = random.nextInt(4);
                // Generate a point in the given direction
                // Get center point (x, y)
                Iterator<Partition> iterator = gindex.iterator();
                while (i_block-- >= 0)
                    iterator.next();
                Partition partition = iterator.next();
                double cx = (partition.x1 + partition.x2) / 2;
                double cy = (partition.y1 + partition.y2) / 2;
                double cw = partition.x2 - partition.x1;
                double ch = partition.y2 - partition.y1;
                int signx = ((direction & 1) == 0) ? 1 : -1;
                int signy = ((direction & 2) == 1) ? 1 : -1;
                double x = cx + cw * closeness / 2 * signx;
                double y = cy + ch * closeness / 2 * signy;
                queryPoints[i] = new Point(x, y);
            }
        }

        final BooleanWritable exceptionHappened = new BooleanWritable();

        Thread.UncaughtExceptionHandler h = new Thread.UncaughtExceptionHandler() {
            public void uncaughtException(Thread th, Throwable ex) {
                ex.printStackTrace();
                exceptionHappened.set(true);
            }
        };

        // Run each query in a separate thread
        final Vector<Thread> threads = new Vector<Thread>();
        for (int i = 0; i < queryPoints.length; i++) {
            Thread thread = new Thread() {
                @Override
                public void run() {
                    try {
                        Point query_point = queryPoints[threads.indexOf(this)];
                        OperationsParams newParams = new OperationsParams(params);
                        OperationsParams.setShape(newParams, "point", query_point);
                        Job job = knn(inputFile, outputPath, params);
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                }
            };
            thread.setUncaughtExceptionHandler(h);
            threads.add(thread);
        }

        long t1 = System.currentTimeMillis();
        do {
            // Ensure that there is at least MaxConcurrentThreads running
            int i = 0;
            while (i < concurrency && i < threads.size()) {
                Thread.State state = threads.elementAt(i).getState();
                if (state == Thread.State.TERMINATED) {
                    // Thread already terminated, remove from the queue
                    threads.remove(i);
                } else if (state == Thread.State.NEW) {
                    // Start the thread and move to next one
                    threads.elementAt(i++).start();
                } else {
                    // Thread is still running, skip over it
                    i++;
                }
            }
            if (!threads.isEmpty()) {
                try {
                    // Sleep for 10 seconds or until the first thread terminates
                    threads.firstElement().join(10000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        } while (!threads.isEmpty());
        long t2 = System.currentTimeMillis();
        if (exceptionHappened.get())
            throw new RuntimeException("Not all jobs finished correctly");

        System.out.println("Time for " + queryPoints.length + " jobs is " + (t2 - t1) + " millis");
        System.out.println("Total iterations: " + TotalIterations);
    }
}

From source file:edu.umn.cs.sthadoop.trajectory.KNNDTW.java

License:Open Source License

public static void main(String[] args) throws IOException {

    args = new String[10];
    args[0] = "/export/scratch/mntgData/geolifeGPS/geolife_Trajectories_1.3/HDFS/index_geolife/yyyy-MM/2008-05";
    args[1] = "/export/scratch/mntgData/geolifeGPS/geolife_Trajectories_1.3/HDFS/knn-dis-result";
    args[2] = "shape:edu.umn.cs.sthadoop.trajectory.GeolifeTrajectory";
    args[3] = "interval:2008-05-01,2008-05-30";
    args[4] = "time:month";
    args[5] = "k:1";
    args[6] = "traj:39.9119983,116.606835;39.9119783,116.6065483;39.9119599,116.6062649;39.9119416,116.6059899;39.9119233,116.6057282;39.9118999,116.6054783;39.9118849,116.6052366;39.9118666,116.6050099;39.91185,116.604775;39.9118299,116.604525;39.9118049,116.6042649;39.91177,116.6040166;39.9117516,116.6037583;39.9117349,116.6035066;39.9117199,116.6032666;39.9117083,116.6030232;39.9117,116.6027566;39.91128,116.5969383;39.9112583,116.5966766;39.9112383,116.5964232;39.9112149,116.5961699;39.9111933,116.5959249;39.9111716,116.5956883";
    args[7] = "-overwrite";
    args[8] = "-local";// "-no-local";
    args[9] = "point:39.9119983,116.606835";

    final OperationsParams params = new OperationsParams(new GenericOptionsParser(args));
    Path[] paths = params.getPaths();
    if (paths.length <= 1 && !params.checkInput()) {
        printUsage();/*  ww  w . j  a  v a  2s.c o  m*/
        System.exit(1);
    }
    if (paths.length > 1 && !params.checkInputOutput()) {
        printUsage();
        System.exit(1);
    }
    final Path inputFile = params.getInputPath();
    int count = params.getInt("count", 1);
    double closeness = params.getFloat("closeness", -1.0f);
    final Point[] queryPoints = closeness < 0 ? params.getShapes("point", new Point()) : new Point[count];
    final FileSystem fs = inputFile.getFileSystem(params);
    final int k = params.getInt("k", 1);
    int concurrency = params.getInt("concurrency", 100);
    if (k == 0) {
        LOG.warn("k = 0");
    }

    if (queryPoints.length == 0) {
        printUsage();
        throw new RuntimeException("Illegal arguments");
    }
    final Path outputPath = paths.length > 1 ? paths[1] : null;

    if (closeness >= 0) {
        // Get query points according to its closeness to grid intersections
        GlobalIndex<Partition> gindex = SpatialSite.getGlobalIndex(fs, inputFile);
        long seed = params.getLong("seed", System.currentTimeMillis());
        Random random = new Random(seed);
        for (int i = 0; i < count; i++) {
            int i_block = random.nextInt(gindex.size());
            int direction = random.nextInt(4);
            // Generate a point in the given direction
            // Get center point (x, y)
            Iterator<Partition> iterator = gindex.iterator();
            while (i_block-- >= 0)
                iterator.next();
            Partition partition = iterator.next();
            double cx = (partition.x1 + partition.x2) / 2;
            double cy = (partition.y1 + partition.y2) / 2;
            double cw = partition.x2 - partition.x1;
            double ch = partition.y2 - partition.y1;
            int signx = ((direction & 1) == 0) ? 1 : -1;
            int signy = ((direction & 2) == 1) ? 1 : -1;
            double x = cx + cw * closeness / 2 * signx;
            double y = cy + ch * closeness / 2 * signy;
            queryPoints[i] = new Point(x, y);
        }
    }

    final BooleanWritable exceptionHappened = new BooleanWritable();

    Thread.UncaughtExceptionHandler h = new Thread.UncaughtExceptionHandler() {
        public void uncaughtException(Thread th, Throwable ex) {
            ex.printStackTrace();
            exceptionHappened.set(true);
        }
    };

    // Run each query in a separate thread
    final Vector<Thread> threads = new Vector<Thread>();
    for (int i = 0; i < queryPoints.length; i++) {
        Thread thread = new Thread() {
            @Override
            public void run() {
                try {
                    Point query_point = queryPoints[threads.indexOf(this)];
                    OperationsParams newParams = new OperationsParams(params);
                    OperationsParams.setShape(newParams, "point", query_point);
                    Job job = knn(inputFile, outputPath, params);
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
        };
        thread.setUncaughtExceptionHandler(h);
        threads.add(thread);
    }

    long t1 = System.currentTimeMillis();
    do {
        // Ensure that there is at least MaxConcurrentThreads running
        int i = 0;
        while (i < concurrency && i < threads.size()) {
            Thread.State state = threads.elementAt(i).getState();
            if (state == Thread.State.TERMINATED) {
                // Thread already terminated, remove from the queue
                threads.remove(i);
            } else if (state == Thread.State.NEW) {
                // Start the thread and move to next one
                threads.elementAt(i++).start();
            } else {
                // Thread is still running, skip over it
                i++;
            }
        }
        if (!threads.isEmpty()) {
            try {
                // Sleep for 10 seconds or until the first thread terminates
                threads.firstElement().join(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    } while (!threads.isEmpty());
    long t2 = System.currentTimeMillis();
    if (exceptionHappened.get())
        throw new RuntimeException("Not all jobs finished correctly");

    System.out.println("Time for " + queryPoints.length + " jobs is " + (t2 - t1) + " millis");
    System.out.println("Total iterations: " + TotalIterations);
}