language
stringclasses
5 values
text
stringlengths
15
988k
Java
@API(API.Status.MAINTAINED) public class UnionCursor<T> extends UnionCursorBase<T, KeyedMergeCursorState<T>> { private final boolean reverse; private UnionCursor(boolean reverse, @Nonnull List<KeyedMergeCursorState<T>> cursorStates, @Nullable FDBStoreTimer timer) { super(cursorStates, timer); this.reverse = reverse; } @Nonnull @Override CompletableFuture<List<KeyedMergeCursorState<T>>> computeNextResultStates() { final List<KeyedMergeCursorState<T>> cursorStates = getCursorStates(); return whenAll(cursorStates).thenApply(vignore -> { boolean anyHasNext = false; for (KeyedMergeCursorState<T> cursorState : cursorStates) { if (cursorState.getResult().hasNext()) { anyHasNext = true; } else if (cursorState.getResult().getNoNextReason().isLimitReached()) { // If any side stopped due to limit reached, need to stop completely, // since might otherwise duplicate ones after that, if other side still available. return Collections.emptyList(); } } if (anyHasNext) { final long startTime = System.nanoTime(); List<KeyedMergeCursorState<T>> chosenStates = new ArrayList<>(cursorStates.size()); List<KeyedMergeCursorState<T>> otherStates = new ArrayList<>(cursorStates.size()); chooseStates(cursorStates, chosenStates, otherStates); logDuplicates(chosenStates, startTime); return chosenStates; } else { return Collections.emptyList(); } }); } private void chooseStates(@Nonnull List<KeyedMergeCursorState<T>> allStates, @Nonnull List<KeyedMergeCursorState<T>> chosenStates, @Nonnull List<KeyedMergeCursorState<T>> otherStates) { List<Object> nextKey = null; for (KeyedMergeCursorState<T> cursorState : allStates) { final RecordCursorResult<T> result = cursorState.getResult(); if (result.hasNext()) { int compare; final List<Object> resultKey = cursorState.getComparisonKey(); if (nextKey == null) { // This is the first key we've seen, so always chose it. compare = -1; } else { // Choose the minimum of the previous minimum key and this next one // If doing a reverse scan, choose the maximum. compare = KeyComparisons.KEY_COMPARATOR.compare(resultKey, nextKey) * (reverse ? -1 : 1); } if (compare < 0) { // We have a new next key. Reset the book-keeping information. otherStates.addAll(chosenStates); chosenStates.clear(); nextKey = resultKey; } if (compare <= 0) { chosenStates.add(cursorState); } else { otherStates.add(cursorState); } } else { otherStates.add(cursorState); } } } private void logDuplicates(@Nonnull List<?> chosenStates, long startTime) { if (chosenStates.isEmpty()) { throw new RecordCoreException("union with additional items had no next states"); } if (getTimer() != null) { if (chosenStates.size() == 1) { getTimer().increment(uniqueCounts); } else { // The number of duplicates is the number of minimum states // for this value except for the first one (hence the "- 1"). getTimer().increment(duplicateCounts, chosenStates.size() - 1); } getTimer().record(duringEvents, System.nanoTime() - startTime); } } @Nonnull protected static <T> List<KeyedMergeCursorState<T>> createCursorStates(@Nonnull Function<byte[], RecordCursor<T>> left, @Nonnull Function<byte[], RecordCursor<T>> right, @Nullable byte[] byteContinuation, @Nonnull Function<? super T, ? extends List<Object>> comparisonKeyFunction) { final UnionCursorContinuation continuation = UnionCursorContinuation.from(byteContinuation, 2); return ImmutableList.of( KeyedMergeCursorState.from(left, continuation.getContinuations().get(0), comparisonKeyFunction), KeyedMergeCursorState.from(right, continuation.getContinuations().get(1), comparisonKeyFunction)); } @Nonnull protected static <T> List<KeyedMergeCursorState<T>> createCursorStates(@Nonnull List<Function<byte[], RecordCursor<T>>> cursorFunctions, @Nullable byte[] byteContinuation, @Nonnull Function<? super T, ? extends List<Object>> comparisonKeyFunction) { final List<KeyedMergeCursorState<T>> cursorStates = new ArrayList<>(cursorFunctions.size()); final UnionCursorContinuation continuation = UnionCursorContinuation.from(byteContinuation, cursorFunctions.size()); int i = 0; for (Function<byte[], RecordCursor<T>> cursorFunction : cursorFunctions) { cursorStates.add(KeyedMergeCursorState.from(cursorFunction, continuation.getContinuations().get(i), comparisonKeyFunction)); i++; } return cursorStates; } /** * Create a union cursor from two compatibly-ordered cursors. This cursor * is identical to the cursor that would be produced by calling the overload of * {@link #create(FDBRecordStoreBase, KeyExpression, boolean, List, byte[]) create()} * that takes a list of cursors. * * @param store record store from which records will be fetched * @param comparisonKey the key expression used to compare records from different cursors * @param reverse whether records are returned in descending or ascending order by the comparison key * @param left a function to produce the first {@link RecordCursor} from a continuation * @param right a function to produce the second {@link RecordCursor} from a continuation * @param continuation any continuation from a previous scan * @param <M> the type of the Protobuf record elements of the cursor * @param <S> the type of record wrapping a record of type <code>M</code> * @return a cursor containing any records in any child cursors * @see #create(FDBRecordStoreBase, KeyExpression, boolean, List, byte[]) */ @Nonnull public static <M extends Message, S extends FDBRecord<M>> UnionCursor<S> create( @Nonnull FDBRecordStoreBase<M> store, @Nonnull KeyExpression comparisonKey, boolean reverse, @Nonnull Function<byte[], RecordCursor<S>> left, @Nonnull Function<byte[], RecordCursor<S>> right, @Nullable byte[] continuation) { return create( (S record) -> comparisonKey.evaluateSingleton(record).toTupleAppropriateList(), reverse, left, right, continuation, store.getTimer()); } /** * Create a union cursor from two compatibly-ordered cursors. This cursor * is identical to the cursor that would be produced by calling the overload of * {@link #create(Function, boolean, List, byte[], FDBStoreTimer) create()} * that takes a list of cursors. * * @param comparisonKeyFunction the function expression used to compare elements from different cursors * @param reverse whether records are returned in descending or ascending order by the comparison key * @param left a function to produce the first {@link RecordCursor} from a continuation * @param right a function to produce the second {@link RecordCursor} from a continuation * @param byteContinuation any continuation from a previous scan * @param timer the timer used to instrument events * @param <T> the type of elements returned by the cursor * @return a cursor containing all elements in both child cursors */ @Nonnull public static <T> UnionCursor<T> create( @Nonnull Function<? super T, ? extends List<Object>> comparisonKeyFunction, boolean reverse, @Nonnull Function<byte[], RecordCursor<T>> left, @Nonnull Function<byte[], RecordCursor<T>> right, @Nullable byte[] byteContinuation, @Nullable FDBStoreTimer timer) { final List<KeyedMergeCursorState<T>> cursorStates = createCursorStates(left, right, byteContinuation, comparisonKeyFunction); return new UnionCursor<>(reverse, cursorStates, timer); } /** * Create a union cursor from two or more compatibly-ordered cursors. * As its comparison key function, it will evaluate the provided comparison key * on each record from each cursor. This otherwise behaves exactly the same way * as the overload of this function that takes a function to extract a comparison * key. * * @param store record store from which records will be fetched * @param comparisonKey the key expression used to compare records from different cursors * @param reverse whether records are returned in descending or ascending order by the comparison key * @param cursorFunctions a list of functions to produce {@link RecordCursor}s from a continuation * @param continuation any continuation from a previous scan * @param <M> the type of the Protobuf record elements of the cursor * @param <S> the type of record wrapping a record of type <code>M</code> * @return a cursor containing any records in any child cursors * @see #create(Function, boolean, List, byte[], FDBStoreTimer) */ @Nonnull public static <M extends Message, S extends FDBRecord<M>> UnionCursor<S> create( @Nonnull FDBRecordStoreBase<M> store, @Nonnull KeyExpression comparisonKey, boolean reverse, @Nonnull List<Function<byte[], RecordCursor<S>>> cursorFunctions, @Nullable byte[] continuation) { return create( (S record) -> comparisonKey.evaluateSingleton(record).toTupleAppropriateList(), reverse, cursorFunctions, continuation, store.getTimer()); } /** * Create a union cursor from two or more compatibly-ordered cursors. * Note that this will throw an error if the list of cursors does not have at least two elements. * The returned cursor will return any records that appear in any of the provided * cursors, preserving order. All cursors must return records in the same order, * and that order should be determined by the comparison key function, i.e., if <code>reverse</code> * is <code>false</code>, then the records should be returned in ascending order by that key, * and if <code>reverse</code> is <code>true</code>, they should be returned in descending * order. Additionally, if the comparison key function evaluates to the same value when applied * to two records (possibly from different cursors), then those two elements * should be equal. In other words, the value of the comparison key should be the <i>only</i> * necessary data that need to be extracted from each element returned by the child cursors to * perform the union. Additionally, the provided comparison key function should not have * any side-effects and should produce the same output every time it is applied to the same input. * * <p> * The cursors are provided as a list of functions rather than a list of {@link RecordCursor}s. * These functions should create a new <code>RecordCursor</code> instance with a given * continuation appropriate for that cursor type. The value of that continuation will be determined * by this function from the <code>continuation</code> parameter for the union * cursor as a whole. * </p> * * @param comparisonKeyFunction the function evaluated to compare elements from different cursors * @param reverse whether records are returned in descending or ascending order by the comparison key * @param cursorFunctions a list of functions to produce {@link RecordCursor}s from a continuation * @param byteContinuation any continuation from a previous scan * @param timer the timer used to instrument events * @param <T> the type of elements returned by this cursor * @return a cursor containing any records in any child cursors */ @Nonnull public static <T> UnionCursor<T> create( @Nonnull Function<? super T, ? extends List<Object>> comparisonKeyFunction, boolean reverse, @Nonnull List<Function<byte[], RecordCursor<T>>> cursorFunctions, @Nullable byte[] byteContinuation, @Nullable FDBStoreTimer timer) { if (cursorFunctions.size() < 2) { throw new RecordCoreArgumentException("not enough child cursors provided to UnionCursor") .addLogInfo(LogMessageKeys.CHILD_COUNT, cursorFunctions.size()); } final List<KeyedMergeCursorState<T>> cursorStates = createCursorStates(cursorFunctions, byteContinuation, comparisonKeyFunction); return new UnionCursor<>(reverse, cursorStates, timer); } }
Java
public class SharedCounterTest extends VertxTestBase { protected Vertx getVertx() { return vertx; } @Test public void testIllegalArguments() throws Exception { assertNullPointerException(() -> getVertx().sharedData().getCounter(null, ar -> {})); assertNullPointerException(() -> getVertx().sharedData().getCounter("foo", null)); getVertx().sharedData().getCounter("foo", ar -> { Counter counter = ar.result(); assertNullPointerException(() -> counter.get(null)); assertNullPointerException(() -> counter.incrementAndGet(null)); assertNullPointerException(() -> counter.getAndIncrement(null)); assertNullPointerException(() -> counter.decrementAndGet(null)); assertNullPointerException(() -> counter.addAndGet(1, null)); assertNullPointerException(() -> counter.getAndAdd(1, null)); assertNullPointerException(() -> counter.compareAndSet(1, 1, null)); testComplete(); }); await(); } @Test public void testGet() { getVertx().sharedData().getCounter("foo", ar -> { assertTrue(ar.succeeded()); Counter counter = ar.result(); counter.get(ar2 -> { assertTrue(ar2.succeeded()); assertEquals(0l, ar2.result().longValue()); testComplete(); }); }); await(); } @Test public void testIncrementAndGet() { getVertx().sharedData().getCounter("foo", ar -> { assertTrue(ar.succeeded()); Counter counter = ar.result(); counter.incrementAndGet(ar2 -> { assertTrue(ar2.succeeded()); assertEquals(1l, ar2.result().longValue()); getVertx().sharedData().getCounter("foo", ar3 -> { assertTrue(ar3.succeeded()); Counter counter2 = ar3.result(); counter2.incrementAndGet(ar4 -> { assertTrue(ar4.succeeded()); assertEquals(2l, ar4.result().longValue()); testComplete(); }); }); }); }); await(); } @Test public void testGetAndIncrement() { getVertx().sharedData().getCounter("foo", ar -> { assertTrue(ar.succeeded()); Counter counter = ar.result(); counter.getAndIncrement(ar2 -> { assertTrue(ar2.succeeded()); assertEquals(0l, ar2.result().longValue()); getVertx().sharedData().getCounter("foo", ar3 -> { assertTrue(ar3.succeeded()); Counter counter2 = ar3.result(); counter2.getAndIncrement(ar4 -> { assertTrue(ar4.succeeded()); assertEquals(1l, ar4.result().longValue()); counter2.get(ar5 -> { assertTrue(ar5.succeeded()); assertEquals(2l, ar5.result().longValue()); testComplete(); }); }); }); }); }); await(); } @Test public void testDecrementAndGet() { getVertx().sharedData().getCounter("foo", ar -> { assertTrue(ar.succeeded()); Counter counter = ar.result(); counter.decrementAndGet(ar2 -> { assertTrue(ar2.succeeded()); assertEquals(-1l, ar2.result().longValue()); getVertx().sharedData().getCounter("foo", ar3 -> { assertTrue(ar3.succeeded()); Counter counter2 = ar3.result(); counter2.decrementAndGet(ar4 -> { assertTrue(ar4.succeeded()); assertEquals(-2l, ar4.result().longValue()); testComplete(); }); }); }); }); await(); } @Test public void testAddAndGet() { getVertx().sharedData().getCounter("foo", ar -> { assertTrue(ar.succeeded()); Counter counter = ar.result(); counter.addAndGet(2, ar2 -> { assertTrue(ar2.succeeded()); assertEquals(2l, ar2.result().longValue()); getVertx().sharedData().getCounter("foo", ar3 -> { assertTrue(ar3.succeeded()); Counter counter2 = ar3.result(); counter2.addAndGet(2l, ar4 -> { assertTrue(ar4.succeeded()); assertEquals(4l, ar4.result().longValue()); testComplete(); }); }); }); }); await(); } @Test public void getAndAdd() { getVertx().sharedData().getCounter("foo", ar -> { assertTrue(ar.succeeded()); Counter counter = ar.result(); counter.getAndAdd(2, ar2 -> { assertTrue(ar2.succeeded()); assertEquals(0l, ar2.result().longValue()); getVertx().sharedData().getCounter("foo", ar3 -> { assertTrue(ar3.succeeded()); Counter counter2 = ar3.result(); counter2.getAndAdd(2l, ar4 -> { assertTrue(ar4.succeeded()); assertEquals(2l, ar4.result().longValue()); counter2.get(ar5 -> { assertTrue(ar5.succeeded()); assertEquals(4l, ar5.result().longValue()); testComplete(); }); }); }); }); }); await(); } @Test public void testCompareAndSet() { getVertx().sharedData().getCounter("foo", ar -> { assertTrue(ar.succeeded()); Counter counter = ar.result(); counter.compareAndSet(0l, 2l, onSuccess(result -> { getVertx().sharedData().getCounter("foo", ar3 -> { assertTrue(ar3.succeeded()); Counter counter2 = ar3.result(); counter2.compareAndSet(2l, 4l, ar4 -> { assertTrue(ar4.succeeded()); assertTrue(ar4.result()); counter2.compareAndSet(3l, 5l, ar5 -> { assertTrue(ar5.succeeded()); assertFalse(ar5.result()); testComplete(); }); }); }); })); }); await(); } @Test public void testDifferentCounters() { getVertx().sharedData().getCounter("foo", ar -> { assertTrue(ar.succeeded()); Counter counter = ar.result(); counter.incrementAndGet(onSuccess(res -> { assertEquals(1l, res.longValue()); getVertx().sharedData().getCounter("bar", ar3 -> { assertTrue(ar3.succeeded()); Counter counter2 = ar3.result(); counter2.incrementAndGet(ar4 -> { assertEquals(1l, ar4.result().longValue()); counter.incrementAndGet(ar5 -> { assertEquals(2l, ar5.result().longValue()); testComplete(); }); }); }); })); }); await(); } }
Java
public final class ClientMain { private static final Logger LOGGER = LoggerFactory.getLogger(ClientMain.class); public static void main(String[] args) { final CommandLineParser commandLineParser = new DefaultParser(); final Options options = new Options(); options.addOption(Option.builder("h").longOpt("help").desc("Display this help message").build()); options.addOption(Option.builder("s") .longOpt("server") .argName("server-name") .desc("DNS name or IP address of the Mumble server") .hasArg() .required() .build()); options.addOption(Option.builder("p") .longOpt("port") .argName("port") .desc("Port number of the Mumble server") .hasArg() .type(Short.class) .build()); options.addOption(Option.builder() .longOpt("ignore-certs") .desc("Ignore TLS certificate validation errors") .build()); CommandLine commandLine = null; try { commandLine = commandLineParser.parse(options, args); } catch (ParseException e) { e.printStackTrace(); System.exit(-1); } if (commandLine.hasOption('h')) { final HelpFormatter helpFormatter = new HelpFormatter(); helpFormatter.printHelp("java -jar java-mumble-client.jar", options); } if (!commandLine.hasOption('s')) { throw new IllegalStateException("No server name specified."); } final String server = commandLine.getOptionValue('s'); final Short port = commandLine.hasOption('p') ? Short.valueOf(commandLine.getOptionValue('p')) : null; try ( final MumbleClient mumbleClient = new MumbleClient(Boolean.parseBoolean(commandLine.getOptionValue( "ignore-certs"))) ) { mumbleClient.connect(server, port, "Java-Mumble-User", null, null); // TODO: Add proper waiting, the client runs async in the background System.in.read(); } catch (final IOException | NoSuchAlgorithmException | KeyManagementException e) { LOGGER.error("Exception in client.", e); } } }
Java
private static class IndexedTestPredicate implements IndexAwarePredicate { static final AtomicBoolean INDEX_CALLED = new AtomicBoolean(false); @Override public Set<QueryableEntry> filter(QueryContext queryContext) { return null; } @Override public boolean isIndexed(QueryContext queryContext) { INDEX_CALLED.set(true); return true; } @Override public boolean apply(Map.Entry mapEntry) { return false; } }
Java
public class LedgerDirsManager { private static Logger LOG = LoggerFactory .getLogger(LedgerDirsManager.class); private volatile List<File> filledDirs; private final List<File> ledgerDirectories; private volatile List<File> writableLedgerDirectories; private final DiskChecker diskChecker; private final List<LedgerDirsListener> listeners; private final LedgerDirsMonitor monitor; private final Random rand = new Random(); private final ConcurrentMap<File, Float> diskUsages = new ConcurrentHashMap<File, Float>(); public LedgerDirsManager(ServerConfiguration conf, File[] dirs) { this(conf, dirs, NullStatsLogger.INSTANCE); } LedgerDirsManager(ServerConfiguration conf, File[] dirs, StatsLogger statsLogger) { this.ledgerDirectories = Arrays.asList(Bookie .getCurrentDirectories(dirs)); this.writableLedgerDirectories = new ArrayList<File>(ledgerDirectories); this.filledDirs = new ArrayList<File>(); listeners = new ArrayList<LedgerDirsListener>(); diskChecker = new DiskChecker(conf.getDiskUsageThreshold(), conf.getDiskUsageWarnThreshold()); monitor = new LedgerDirsMonitor(conf.getDiskCheckInterval()); for (File dir : dirs) { diskUsages.put(dir, 0f); String statName = "dir_" + dir.getPath().replace('/', '_') + "_usage"; final File targetDir = dir; statsLogger.registerGauge(statName, new Gauge<Number>() { @Override public Number getDefaultValue() { return 0; } @Override public Number getSample() { return diskUsages.get(targetDir) * 100; } }); } statsLogger.registerGauge("writable_dirs", new Gauge<Number>() { @Override public Number getDefaultValue() { return 0; } @Override public Number getSample() { return writableLedgerDirectories.size(); } }); } /** * Get all ledger dirs configured */ public List<File> getAllLedgerDirs() { return ledgerDirectories; } /** * Get only writable ledger dirs. */ public List<File> getWritableLedgerDirs() throws NoWritableLedgerDirException { if (writableLedgerDirectories.isEmpty()) { NoWritableLedgerDirException.logAndThrow(LOG, "Out of " + ledgerDirectories.size() + " directories none are writable " + filledDirs.size() + " are full"); } return writableLedgerDirectories; } /** * @return full-filled ledger dirs. */ public List<File> getFullFilledLedgerDirs() { return filledDirs; } /** * Get dirs, which are full more than threshold */ public boolean isDirFull(File dir) { return filledDirs.contains(dir); } /** * Add the dir to filled dirs list */ @VisibleForTesting public void addToFilledDirs(File dir) { if (!filledDirs.contains(dir)) { LOG.warn("{} is out of space. Adding it to filled dirs list", dir); // Update filled dirs list List<File> updatedFilledDirs = new ArrayList<File>(filledDirs); updatedFilledDirs.add(dir); filledDirs = updatedFilledDirs; // Update the writable ledgers list List<File> newDirs = new ArrayList<File>(writableLedgerDirectories); newDirs.removeAll(filledDirs); writableLedgerDirectories = newDirs; // Notify listeners about disk full for (LedgerDirsListener listener : listeners) { listener.diskFull(dir); } } } /** * Add the dir to writable dirs list. * * @param dir Dir */ public void addToWritableDirs(File dir, boolean underWarnThreshold) { if (writableLedgerDirectories.contains(dir)) { return; } LOG.info("{} becomes writable. Adding it to writable dirs list.", dir); // Update writable dirs list List<File> updatedWritableDirs = new ArrayList<File>(writableLedgerDirectories); updatedWritableDirs.add(dir); writableLedgerDirectories = updatedWritableDirs; // Update the filled dirs list List<File> newDirs = new ArrayList<File>(filledDirs); newDirs.removeAll(writableLedgerDirectories); filledDirs = newDirs; // Notify listeners about disk writable for (LedgerDirsListener listener : listeners) { if (underWarnThreshold) { listener.diskWritable(dir); } else { listener.diskJustWritable(dir); } } } /** * Returns one of the ledger dir from writable dirs list randomly. * Issue warning if the directory w/ given path is picked up. */ File pickRandomWritableDir(File dirExcl) throws NoWritableLedgerDirException { List<File> writableDirs = getWritableLedgerDirs(); assert writableDirs.size() > 0; File dir = writableDirs.get(rand.nextInt(writableDirs.size())); if (dirExcl != null) { if (dir.equals(dirExcl)) { // Just issue warning as some tests use identical dirs LOG.warn("The same file path is picked up to move index file"); } } return dir; } public void addLedgerDirsListener(LedgerDirsListener listener) { if (listener != null) { listeners.add(listener); } } /** * Sweep through all the directories to check disk errors or disk full. * * @throws DiskErrorException * If disk having errors * @throws NoWritableLedgerDirException * If all the configured ledger directories are full or having * less space than threshold */ public void checkAllDirs() throws DiskErrorException, NoWritableLedgerDirException { writableLedgerDirectories.addAll(filledDirs); filledDirs.clear(); monitor.checkDirs(writableLedgerDirectories); } // start the daemon for disk monitoring public void start() { monitor.setDaemon(true); monitor.start(); } // shutdown disk monitoring daemon public void shutdown() { monitor.interrupt(); try { monitor.join(); } catch (InterruptedException e) { // Ignore } } /** * Thread to monitor the disk space periodically. */ private class LedgerDirsMonitor extends BookieThread { int interval; public LedgerDirsMonitor(int interval) { super("LedgerDirsMonitorThread"); this.interval = interval; } @Override public void run() { while (true) { List<File> writableDirs; try { writableDirs = getWritableLedgerDirs(); } catch (NoWritableLedgerDirException e) { for (LedgerDirsListener listener : listeners) { listener.allDisksFull(); } break; } // Check all writable dirs disk space usage. for (File dir : writableDirs) { try { diskUsages.put(dir, diskChecker.checkDir(dir)); } catch (DiskErrorException e) { LOG.error("Ledger directory " + dir + " failed on disk checking : ", e); // Notify disk failure to all listeners for (LedgerDirsListener listener : listeners) { listener.diskFailed(dir); } } catch (DiskWarnThresholdException e) { LOG.warn("Ledger directory {} is almost full.", dir); diskUsages.put(dir, e.getUsage()); for (LedgerDirsListener listener : listeners) { listener.diskAlmostFull(dir); } } catch (DiskOutOfSpaceException e) { LOG.error("Ledger directory {} is out-of-space.", dir); diskUsages.put(dir, e.getUsage()); // Notify disk full to all listeners addToFilledDirs(dir); } } List<File> fullfilledDirs = new ArrayList<File>(getFullFilledLedgerDirs()); // Check all full-filled disk space usage for (File dir : fullfilledDirs) { try { diskUsages.put(dir, diskChecker.checkDir(dir)); addToWritableDirs(dir, true); } catch (DiskErrorException e) { //Notify disk failure to all the listeners for (LedgerDirsListener listener : listeners) { listener.diskFailed(dir); } } catch (DiskWarnThresholdException e) { diskUsages.put(dir, e.getUsage()); // the full-filled dir become writable but still above warn threshold addToWritableDirs(dir, false); } catch (DiskOutOfSpaceException e) { // the full-filled dir is still full-filled diskUsages.put(dir, e.getUsage()); } } try { Thread.sleep(interval); } catch (InterruptedException e) { LOG.info("LedgerDirsMonitor thread is interrupted"); break; } } } private void checkDirs(List<File> writableDirs) throws DiskErrorException, NoWritableLedgerDirException { for (File dir : writableDirs) { try { diskChecker.checkDir(dir); } catch (DiskWarnThresholdException e) { // nop } catch (DiskOutOfSpaceException e) { addToFilledDirs(dir); } } getWritableLedgerDirs(); } } /** * Indicates All configured ledger directories are full. */ public static class NoWritableLedgerDirException extends IOException { private static final long serialVersionUID = -8696901285061448421L; public NoWritableLedgerDirException(String message) { super(message); } public static void logAndThrow(Logger logger, String message) throws NoWritableLedgerDirException { NoWritableLedgerDirException exception = new NoWritableLedgerDirException(message); logger.error(message, exception); throw exception; } } /** * Listener for the disk check events will be notified from the * {@link LedgerDirsManager} whenever disk full/failure detected. */ public static interface LedgerDirsListener { /** * This will be notified on disk failure/disk error * * @param disk * Failed disk */ void diskFailed(File disk); /** * Notified when the disk usage warn threshold is exceeded on * the drive. * @param disk */ void diskAlmostFull(File disk); /** * This will be notified on disk detected as full * * @param disk * Filled disk */ void diskFull(File disk); /** * This will be notified on disk detected as writable and under warn threshold * * @param disk * Writable disk */ void diskWritable(File disk); /** * This will be notified on disk detected as writable but still in warn threshold * * @param disk * Writable disk */ void diskJustWritable(File disk); /** * This will be notified whenever all disks are detected as full. */ void allDisksFull(); /** * This will notify the fatal errors. */ void fatalError(); } }
Java
private class LedgerDirsMonitor extends BookieThread { int interval; public LedgerDirsMonitor(int interval) { super("LedgerDirsMonitorThread"); this.interval = interval; } @Override public void run() { while (true) { List<File> writableDirs; try { writableDirs = getWritableLedgerDirs(); } catch (NoWritableLedgerDirException e) { for (LedgerDirsListener listener : listeners) { listener.allDisksFull(); } break; } // Check all writable dirs disk space usage. for (File dir : writableDirs) { try { diskUsages.put(dir, diskChecker.checkDir(dir)); } catch (DiskErrorException e) { LOG.error("Ledger directory " + dir + " failed on disk checking : ", e); // Notify disk failure to all listeners for (LedgerDirsListener listener : listeners) { listener.diskFailed(dir); } } catch (DiskWarnThresholdException e) { LOG.warn("Ledger directory {} is almost full.", dir); diskUsages.put(dir, e.getUsage()); for (LedgerDirsListener listener : listeners) { listener.diskAlmostFull(dir); } } catch (DiskOutOfSpaceException e) { LOG.error("Ledger directory {} is out-of-space.", dir); diskUsages.put(dir, e.getUsage()); // Notify disk full to all listeners addToFilledDirs(dir); } } List<File> fullfilledDirs = new ArrayList<File>(getFullFilledLedgerDirs()); // Check all full-filled disk space usage for (File dir : fullfilledDirs) { try { diskUsages.put(dir, diskChecker.checkDir(dir)); addToWritableDirs(dir, true); } catch (DiskErrorException e) { //Notify disk failure to all the listeners for (LedgerDirsListener listener : listeners) { listener.diskFailed(dir); } } catch (DiskWarnThresholdException e) { diskUsages.put(dir, e.getUsage()); // the full-filled dir become writable but still above warn threshold addToWritableDirs(dir, false); } catch (DiskOutOfSpaceException e) { // the full-filled dir is still full-filled diskUsages.put(dir, e.getUsage()); } } try { Thread.sleep(interval); } catch (InterruptedException e) { LOG.info("LedgerDirsMonitor thread is interrupted"); break; } } } private void checkDirs(List<File> writableDirs) throws DiskErrorException, NoWritableLedgerDirException { for (File dir : writableDirs) { try { diskChecker.checkDir(dir); } catch (DiskWarnThresholdException e) { // nop } catch (DiskOutOfSpaceException e) { addToFilledDirs(dir); } } getWritableLedgerDirs(); } }
Java
public static class NoWritableLedgerDirException extends IOException { private static final long serialVersionUID = -8696901285061448421L; public NoWritableLedgerDirException(String message) { super(message); } public static void logAndThrow(Logger logger, String message) throws NoWritableLedgerDirException { NoWritableLedgerDirException exception = new NoWritableLedgerDirException(message); logger.error(message, exception); throw exception; } }
Java
public class Tile { @Getter @Setter public String id; public boolean isSpent; @Getter @Setter private Corporation memberOf; @Getter @Setter private Player owner; @Getter @Setter private Tile left; @Getter @Setter private Tile right; @Getter @Setter private Tile up; @Getter @Setter private Tile down; /** * Parameterized tile constructor * * @param id the letter-number id which determines tile position (from A1-I12) * @param isSpent true if tile is used, false otherwise * @param memberOf default Null, changes to the corporation that it is merged into * @param owner the player that placed the tile, (may be unneeded) * @param left the tile to the left (Null if in column 1) * @param right the tile to the right (Null if in column 12) * @param up the tile above (Null if in row A) * @param down the tile beneath (Null if in row I) */ public Tile(String id, boolean isSpent, Corporation memberOf, Player owner, Tile left, Tile right, Tile up, Tile down) { this.id = id; this.isSpent = isSpent; this.memberOf = memberOf; this.owner = owner; this.left = left; this.right = right; this.up = up; this.down = down; } /** * Default tile constructor */ public Tile(){} public void setSpent(boolean b) { isSpent = b; } public String nullCheckedToString() { String ncId = id; String ncIsSpent = String.valueOf(this.isSpent); String ncMemberOf = "null"; if (memberOf != null) { ncMemberOf = this.memberOf.getName(); } String ncOwner = "null"; if (owner != null) { ncOwner = String.valueOf(this.owner.playerIdentity); } String ncLeft = "null"; if (left != null) { ncLeft = this.left.id; } String ncRight = "null"; if (right != null) { ncRight = this.right.id; } String ncUp = "null"; if (up != null) { ncUp = this.up.id; } String ncDown = "null"; if (down != null) { ncDown = this.down.id; } return "Tile [id=" + ncId + ", isSpent=" + ncIsSpent + ", memberOf=" + ncMemberOf + ", owner=" + ncOwner + ", left=" + ncLeft + ", right=" + ncRight + ", up=" + ncUp + ", down=" + ncDown + "]"; } }
Java
@BindMap(Point3.class) public class Point3BindMap extends AbstractMapper<Point3> { @Override public int serializeOnJackson(Point3 object, JsonGenerator jacksonSerializer) throws Exception { jacksonSerializer.writeStartObject(); int fieldCount=0; // Serialized Field: // field x (mapped with "x") fieldCount++; jacksonSerializer.writeNumberField("x", object.x); // field y (mapped with "y") fieldCount++; jacksonSerializer.writeNumberField("y", object.y); // field z (mapped with "z") fieldCount++; jacksonSerializer.writeNumberField("z", object.z); jacksonSerializer.writeEndObject(); return fieldCount; } @Override public int serializeOnJacksonAsString(Point3 object, JsonGenerator jacksonSerializer) throws Exception { jacksonSerializer.writeStartObject(); int fieldCount=0; // Serialized Field: // field x (mapped with "x") jacksonSerializer.writeStringField("x", PrimitiveUtils.writeFloat(object.x)); // field y (mapped with "y") jacksonSerializer.writeStringField("y", PrimitiveUtils.writeFloat(object.y)); // field z (mapped with "z") jacksonSerializer.writeStringField("z", PrimitiveUtils.writeFloat(object.z)); jacksonSerializer.writeEndObject(); return fieldCount; } /** * method for xml serialization */ @Override public void serializeOnXml(Point3 object, XMLSerializer xmlSerializer, EventType currentEventType) throws Exception { if (currentEventType == EventType.START_DOCUMENT) { xmlSerializer.writeStartElement("point3"); } // Persisted fields: // field x (mapped with "x") xmlSerializer.writeAttribute("x", PrimitiveUtils.writeFloat(object.x)); // field y (mapped with "y") xmlSerializer.writeAttribute("y", PrimitiveUtils.writeFloat(object.y)); // field z (mapped with "z") xmlSerializer.writeAttribute("z", PrimitiveUtils.writeFloat(object.z)); if (currentEventType == EventType.START_DOCUMENT) { xmlSerializer.writeEndElement(); } } /** * parse with jackson */ @Override public Point3 parseOnJackson(JsonParser jacksonParser) throws Exception { Point3 instance = new Point3(); String fieldName; if (jacksonParser.currentToken() == null) { jacksonParser.nextToken(); } if (jacksonParser.currentToken() != JsonToken.START_OBJECT) { jacksonParser.skipChildren(); return instance; } while (jacksonParser.nextToken() != JsonToken.END_OBJECT) { fieldName = jacksonParser.getCurrentName(); jacksonParser.nextToken(); // Parse fields: switch (fieldName) { case "x": // field x (mapped with "x") instance.x=jacksonParser.getFloatValue(); break; case "y": // field y (mapped with "y") instance.y=jacksonParser.getFloatValue(); break; case "z": // field z (mapped with "z") instance.z=jacksonParser.getFloatValue(); break; default: jacksonParser.skipChildren(); break;} } return instance; } /** * parse with jackson */ @Override public Point3 parseOnJacksonAsString(JsonParser jacksonParser) throws Exception { Point3 instance = new Point3(); String fieldName; if (jacksonParser.getCurrentToken() == null) { jacksonParser.nextToken(); } if (jacksonParser.getCurrentToken() != JsonToken.START_OBJECT) { jacksonParser.skipChildren(); return instance; } while (jacksonParser.nextToken() != JsonToken.END_OBJECT) { fieldName = jacksonParser.getCurrentName(); jacksonParser.nextToken(); // Parse fields: switch (fieldName) { case "x": // field x (mapped with "x") instance.x=PrimitiveUtils.readFloat(jacksonParser.getText(), 0f); break; case "y": // field y (mapped with "y") instance.y=PrimitiveUtils.readFloat(jacksonParser.getText(), 0f); break; case "z": // field z (mapped with "z") instance.z=PrimitiveUtils.readFloat(jacksonParser.getText(), 0f); break; default: jacksonParser.skipChildren(); break;} } return instance; } /** * parse xml */ @Override public Point3 parseOnXml(XMLParser xmlParser, EventType currentEventType) throws Exception { Point3 instance = new Point3(); EventType eventType = currentEventType; boolean read=true; if (currentEventType == EventType.START_DOCUMENT) { eventType = xmlParser.next(); } else { eventType = xmlParser.getEventType(); } String currentTag = xmlParser.getName().toString(); String elementName = currentTag; // attributes String attributeName = null; int attributesCount = xmlParser.getAttributeCount();; for (int attributeIndex = 0; attributeIndex < attributesCount; attributeIndex++) { attributeName = xmlParser.getAttributeName(attributeIndex); switch(attributeName) { case "x": // field x (mapped by "x") instance.x=PrimitiveUtils.readFloat(xmlParser.getAttributeValue(attributeIndex), 0f); break; case "y": // field y (mapped by "y") instance.y=PrimitiveUtils.readFloat(xmlParser.getAttributeValue(attributeIndex), 0f); break; case "z": // field z (mapped by "z") instance.z=PrimitiveUtils.readFloat(xmlParser.getAttributeValue(attributeIndex), 0f); break; default: break; } } //sub-elements while (xmlParser.hasNext() && elementName!=null) { if (read) { eventType = xmlParser.next(); } else { eventType = xmlParser.getEventType(); } read=true; switch(eventType) { case START_TAG: currentTag = xmlParser.getName().toString(); // No property to manage here break; case END_TAG: if (elementName.equals(xmlParser.getName())) { currentTag = elementName; elementName = null; } break; case CDSECT: case TEXT: // no property is binded to VALUE o CDATA break; default: break; } } return instance; } }
Java
@JsonIgnoreProperties(ignoreUnknown = true) public class Tweet implements Comparable{ @JsonProperty(TweetConstantsKey.MESSAGE_ID) private String messageId; @JsonProperty(TweetConstantsKey.CREATED_AT) private Date creationDate; @JsonProperty(TweetConstantsKey.TEXT) private String messageText; @JsonProperty(TweetConstantsKey.AUTHOR) private Author author; public String getMessageId() { return messageId; } public Date getCreationDate() { return creationDate; } public String getMessageText() { return messageText; } public Author getAuthor() { return author; } public int compareTo(Object o) { final int EQUAL = 0; int result; Tweet oTweet = (Tweet) o; if(this == oTweet) result = EQUAL; else result = this.getCreationDate().compareTo(oTweet.getCreationDate()); return result; } @Override public String toString(){ return "Tweet: [" + TweetConstantsKey.MESSAGE_ID + ": " + messageId + "," + TweetConstantsKey.CREATED_AT + ": " + creationDate + "," + TweetConstantsKey.TEXT + ": " + messageText + "," + TweetConstantsKey.AUTHOR + ": " + author.toString() + "]"; } }
Java
public class WholeStringBuilder extends SpannableStringBuilder { public static CharSequence bold(final CharSequence text) { return new WholeStringBuilder(text, new StyleSpan(Typeface.BOLD)); } public WholeStringBuilder(final CharSequence text, final Object span) { super(text); setSpan(span, 0, text.length(), SpannableStringBuilder.SPAN_EXCLUSIVE_EXCLUSIVE); } }
Java
public abstract class AbstractJessopScriptBuilder implements JessopScriptBuilder { protected Logger logger = Logger.getLogger(AbstractJessopScriptBuilder.class); protected JessopDeclarations declarations; protected Tokeniser tokeniser; protected PrintWriter pw; @Override public void setPrintWriter(PrintWriter pw) { this.pw = pw; } @Override public void setTokeniserAndDeclarations(Tokeniser t, JessopDeclarations declarations) { this.tokeniser = t; this.declarations = declarations; } @Override public JessopDeclarations getDeclarations() { return declarations; } @Override public void emitDeclaration(int line, String s) throws ScriptException { // declType attr1="val1" attr2="val2" // don't really feel like tokenising this at the moment s = s.trim(); // can't do this in 1 regex for some reason // Pattern declPattern = Pattern.compile("([^\\s\"]+)\\s*(?:(\\S+)=\"([^\"]*)\"\\s*)*$"); // so breaking into subregexes String declType; Pattern declTypePattern = Pattern.compile("^([^\\s\"]+)"); Matcher m = declTypePattern.matcher(s); if (m.find()) { declType = m.group(1); } else { throw new ScriptException("Could not parse declaration '" + s + "'", null, line); } if (!declType.equals("jessop")) { logger.warn("Unknown declaration type '" + declType + "'"); // just ignore unknown declarations return; } s = s.substring(declType.length()).trim(); logger.debug("s=" + s); Pattern declAttrPattern = Pattern.compile("(\\S+)=\"([^\"]*)\""); m = declAttrPattern.matcher(s); while (m.find()) { // do something String attrName = m.group(1); String attrValue = m.group(2); if (attrName.equals("language")) { // change the JessopScriptBuilder based on the language // the registry of ScriptBuilders is kept in the EngineFactory JessopScriptEngineFactory jsf = (JessopScriptEngineFactory) tokeniser.jse.getFactory(); JessopScriptBuilder newBuilder = jsf.getJessopScriptBuilderForLanguage(attrValue); newBuilder.setPrintWriter(pw); newBuilder.setTokeniserAndDeclarations(tokeniser, declarations); // pass on tokeniser state and declarations to new jsb tokeniser.setJessopScriptBuilder(newBuilder); // tokeniser should use this jsb from this point on // should probably wait until all attributes are parsed, but hey //if (declarations.engine==null) { declarations.engine = newBuilder.getDefaultScriptEngineName(); declarations.exceptionConverter = newBuilder.getDefaultExceptionConverterClassName(); declarations.bindingsConverter = newBuilder.getDefaultBindingsConverterClassName(); //} /* JessopScriptBuilder newBuilder; if (attrValue.equals("javascript")) { newBuilder = new JavascriptJessopScriptBuilder(); newBuilder.setPrintWriter(pw); newBuilder.setTokeniser(tokeniser, declarations); // pass on tokeniser state and declarations to new jsb tokeniser.setJessopScriptBuilder(newBuilder); // tokeniser should use this jsb from this point on if (declarations.engine==null) { declarations.engine = "rhino"; } // default engine for javascript } else if (attrValue.equals("java")) { newBuilder = new JavaJessopScriptBuilder(); newBuilder.setPrintWriter(pw); newBuilder.setTokeniser(tokeniser, declarations); tokeniser.setJessopScriptBuilder(newBuilder); if (declarations.engine==null) { declarations.engine = "beanshell"; } // default engine for java } else if (attrValue.equals("lua")) { newBuilder = new LuaJessopScriptBuilder(); newBuilder.setPrintWriter(pw); newBuilder.setTokeniser(tokeniser, declarations); tokeniser.setJessopScriptBuilder(newBuilder); if (declarations.engine==null) { declarations.engine = "luaj"; } // default engine for lua } else if (attrValue.equals("python") || attrValue.equals("python2")) { newBuilder = new Python2JessopScriptBuilder(); newBuilder.setPrintWriter(pw); newBuilder.setTokeniser(tokeniser, declarations); tokeniser.setJessopScriptBuilder(newBuilder); if (declarations.engine==null) { declarations.engine = "jython"; } // default engine for lua } else { throw new IllegalArgumentException("Unknown language '" + attrValue + "'"); } */ } else if (attrName.equals("engine")) { // if we're changing engines, this will reset the default exception converter. // we may want to keep a registry of engine names -> ExceptionConverters // at a later stage if (!attrValue.equals(declarations.getEngine())) { declarations.setExceptionConverter(null); } declarations.setEngine(attrValue); } else if (attrName.equals("suppressEol")) { declarations.setSuppressEol(Boolean.valueOf(attrValue)); } else if (attrName.equals("compileTarget")) { declarations.setCompileTarget(Boolean.valueOf(attrValue)); } else if (attrName.equals("filename")) { declarations.setFilename(attrValue); } else if (attrName.equals("exceptionConverter")) { declarations.setExceptionConverter(attrValue); } else if (attrName.equals("bindingsConverter")) { declarations.setBindingsConverter(attrValue); } logger.debug("Found attr " + m.group(1) + "," + m.group(2)); } } @Override public abstract void emitText(int line, String s); @Override public abstract void emitExpression(int line, String s); @Override public abstract void emitScriptlet(int line, String s); @Override public String getDefaultExceptionConverterClassName() { return null; } @Override public String getDefaultBindingsConverterClassName() { return null; } /** Conditionally remove the first newline from the supplied string. * * <p>This method is used to perform <code>suppressEol</code> declaration processing. * * <p>When the <code>suppressEol</code> declaration is <code>true</code>, and the text to be emitted by the output script * immediately follows a scriptlet and begins with a newline (or whitespace followed by a newline), * then we want to remove that (whitespace and) newline. * * <p>If there are non-whitespace characters before the first newline, then it is not suppressed. * * @param s text which is to be emitted by the output script * @param suppressEol if true, remove the beginning whitespace and newline, if it exists. * * @return the supplied string, with the first newline conditionally removed */ protected String suppressEol(String s, boolean suppressEol) { // ok. if s starts with a newline, // *and* suppressEol is true, // *and* this text is being emitted on a line that has nothing but expressions (and whitespace), // then suppress the newline. if (s.indexOf("\n")!=-1 && suppressEol) { boolean isFirstLineJustWhitespace = true; int pos = 0; while (pos<s.length() && isFirstLineJustWhitespace) { char ch = s.charAt(pos); if (ch=='\n') { pos++; break; } if (!Character.isWhitespace(ch)) { isFirstLineJustWhitespace = false; break; } pos++; } if (isFirstLineJustWhitespace) { s = s.substring(pos); } } return s; } }
Java
public class RequestObject { private final HttpServletRequest request; private final HttpServletResponse response; private final Map<String, String> urlVariables; private final Map<String, String[]> queryString; private JsonElement payload; public RequestObject(HttpServletRequest request, HttpServletResponse response, Map<String, String> urlVariables, Map<String, String[]> queryString, JsonElement payload) { this.request = request; this.response = response; this.urlVariables = urlVariables; this.queryString = queryString; this.payload = payload; } public HttpServletRequest getRequest() { return request; } public HttpServletResponse getResponse() { return response; } public Map<String, String> getUrlVariables() { return urlVariables; } public Map<String, String[]> getQueryString() { return queryString; } public JsonElement getPayload() { return payload; } public void setPayload(JsonElement payload) { this.payload = payload; } public void throwHttpError(String className, StaticRules.ErrorCodes error, String message) { // set the HTTP status code to the correct status code this.response.setStatus(error.getHttpStatusCode()); //construct the JSON object to return Gson g = new Gson(); ErrorObject eo = new ErrorObject(); eo.setClassName(className); eo.setHttpStatusCode(error.getHttpStatusCode()); eo.setErrorId(error.getErrorId()); eo.setErrorMessage(message); String errorObject = g.toJson(eo); // write the response to the writer try { this.response.getWriter().write(errorObject); this.response.getWriter().close(); // ensure no other objects can be written to a closed header because the error was thrown } catch (IOException e) { Logging.log("Low", e); } } public void throwHttpError(String className, StaticRules.ErrorCodes error) { throwHttpError(className, error, error.getErrorMessage()); } }
Java
@Data public class RuleMetricsDocs { /** * Name of the metric, see {@link MetricRecordingSettings#getMetric()}. */ private final String name; /** * See {@link MetricRecordingSettings#getValue()}. */ private final String value; /** * See {@link MetricRecordingSettings#getDataTags()}. */ private final Map<String, String> dataTags; /** * See {@link MetricRecordingSettings#getConstantTags()}. */ private final Map<String, String> constantTags; }
Java
public class InviteTransactionServer extends TransactionServer { /** Default behavior for automatically sending 100 Trying on INVITE. */ public static boolean AUTO_TRYING = true; /** * the TransactionServerListener that captures the events fired by the * InviteTransactionServer */ InviteTransactionServerListener transaction_listener; /** last response message */ // Message response=null; /** retransmission timeout ("Timer G" in RFC 3261) */ Timer retransmission_to; /** end timeout ("Timer H" in RFC 3261) */ Timer end_to; /** clearing timeout ("Timer I" in RFC 3261) */ // Timer clearing_to; /** Whether automatically sending 100 Trying on INVITE. */ boolean auto_trying; /** Creates a new InviteTransactionServer. */ public InviteTransactionServer(SipProvider sip_provider, InviteTransactionServerListener listener) { super(sip_provider); init(listener, new TransactionIdentifier(SipMethods.INVITE), null); } /** * Creates a new InviteTransactionServer for the already received INVITE * request <i>invite</i>. */ public InviteTransactionServer(SipProvider sip_provider, Message invite, InviteTransactionServerListener listener) { super(sip_provider); request = new Message(invite); init(listener, request.getTransactionId(), request.getConnectionId()); changeStatus(STATE_TRYING); sip_provider.addSipProviderListener(transaction_id, this); // automatically send "100 Tryng" response and go to STATE_PROCEEDING if (auto_trying) { Message trying100 = MessageFactory.createResponse(request, 100, SipResponses.reasonOf(100), null); respondWith(trying100); // this method makes it going automatically // to STATE_PROCEEDING } } /** * Creates a new InviteTransactionServer for the already received INVITE * request <i>invite</i>. */ public InviteTransactionServer(SipProvider sip_provider, Message invite, boolean auto_trying, InviteTransactionServerListener listener) { super(sip_provider); request = new Message(invite); init(listener, request.getTransactionId(), request.getConnectionId()); this.auto_trying = auto_trying; changeStatus(STATE_TRYING); sip_provider.addSipProviderListener(transaction_id, this); // automatically send "100 Tryng" response and go to STATE_PROCEEDING if (auto_trying) { Message trying100 = MessageFactory.createResponse(request, 100, SipResponses.reasonOf(100), null); respondWith(trying100); // this method makes it going automatically // to STATE_PROCEEDING } } /** Initializes timeouts and listener. */ void init(InviteTransactionServerListener listener, TransactionIdentifier transaction_id, ConnectionIdentifier connection_id) { this.transaction_listener = listener; this.transaction_id = transaction_id; this.connection_id = connection_id; auto_trying = AUTO_TRYING; retransmission_to = new Timer(SipStack.retransmission_timeout, "Retransmission", this); end_to = new Timer(SipStack.transaction_timeout, "End", this); clearing_to = new Timer(SipStack.clearing_timeout, "Clearing", this); printLog("id: " + String.valueOf(transaction_id), LogLevel.HIGH); printLog("created", LogLevel.HIGH); } /** Whether automatically sending 100 Trying on INVITE. */ public void setAutoTrying(boolean auto_trying) { this.auto_trying = auto_trying; } /** Starts the InviteTransactionServer. */ public void listen() { printLog("start", LogLevel.LOW); if (statusIs(STATE_IDLE)) { changeStatus(STATE_WAITING); sip_provider.addSipProviderListener(new TransactionIdentifier( SipMethods.INVITE), this); sip_provider.addSipProviderListener(new TransactionIdentifier( SipMethods.OPTIONS), this); } } /** Sends a response message */ public void respondWith(Message resp) { response = resp; int code = response.getStatusLine().getCode(); if (statusIs(STATE_TRYING) || statusIs(STATE_PROCEEDING)) sip_provider.sendMessage(response, connection_id); if (code >= 100 && code < 200 && statusIs(STATE_TRYING)) { changeStatus(STATE_PROCEEDING); return; } if (code >= 200 && code < 300 && (statusIs(STATE_TRYING) || statusIs(STATE_PROCEEDING))) { sip_provider.removeSipProviderListener(transaction_id); changeStatus(STATE_TERMINATED); transaction_listener = null; return; } if (code >= 300 && code < 700 && (statusIs(STATE_TRYING) || statusIs(STATE_PROCEEDING))) { changeStatus(STATE_COMPLETED); // retransmission only in case of unreliable transport if (true || connection_id == null) { // modified retransmission_to.start(); end_to.start(); } else { printLog("No retransmissions for reliable transport (" + connection_id + ")", LogLevel.LOW); onTimeout(end_to); } } } /** * Method derived from interface SipListener. It's fired from the * SipProvider when a new message is catch for to the present * ServerTransaction. */ public void onReceivedMessage(SipProvider provider, Message msg) { if (msg.isRequest()) { String req_method = msg.getRequestLine().getMethod(); // invite received if (req_method.equals(SipMethods.INVITE)) { if (statusIs(STATE_WAITING)) { request = new Message(msg); connection_id = request.getConnectionId(); transaction_id = request.getTransactionId(); sip_provider.addSipProviderListener(transaction_id, this); sip_provider .removeSipProviderListener(new TransactionIdentifier( SipMethods.INVITE)); changeStatus(STATE_TRYING); // automatically send "100 Tryng" response and go to // STATE_PROCEEDING if (auto_trying) { Message trying100 = MessageFactory.createResponse( request, 100, SipResponses.reasonOf(100), null); respondWith(trying100); // this method makes it going // automatically to // STATE_PROCEEDING } if (transaction_listener != null) transaction_listener.onTransRequest(this, msg); return; } if (statusIs(STATE_PROCEEDING) || statusIs(STATE_COMPLETED)) { // retransmission // of // the // last // response sip_provider.sendMessage(response, connection_id); return; } } if (req_method.equals(SipMethods.OPTIONS)) { Message ok200 = MessageFactory.createResponse(msg, 200, SipResponses.reasonOf(200), null); ok200.removeServerHeader(); ok200.addContactHeader(new ContactHeader(ok200.getToHeader().getNameAddress()), false); sip_provider.sendMessage(ok200, connection_id); return; } // ack received if (req_method.equals(SipMethods.ACK) && statusIs(STATE_COMPLETED)) { retransmission_to.halt(); end_to.halt(); changeStatus(STATE_CONFIRMED); if (transaction_listener != null) transaction_listener.onTransFailureAck(this, msg); clearing_to.start(); return; } } } /** * Method derived from interface TimerListener. It's fired from an active * Timer. */ public void onTimeout(Timer to) { try { if (to.equals(retransmission_to) && statusIs(STATE_COMPLETED)) { printLog("Retransmission timeout expired", LogLevel.HIGH); long timeout = 2 * retransmission_to.getTime(); if (timeout > SipStack.max_retransmission_timeout) timeout = SipStack.max_retransmission_timeout; retransmission_to = new Timer(timeout, retransmission_to .getLabel(), this); retransmission_to.start(); sip_provider.sendMessage(response, connection_id); } if (to.equals(end_to) && statusIs(STATE_COMPLETED)) { printLog("End timeout expired", LogLevel.HIGH); retransmission_to.halt(); sip_provider.removeSipProviderListener(transaction_id); changeStatus(STATE_TERMINATED); transaction_listener = null; } if (to.equals(clearing_to) && statusIs(STATE_CONFIRMED)) { printLog("Clearing timeout expired", LogLevel.HIGH); sip_provider.removeSipProviderListener(transaction_id); changeStatus(STATE_TERMINATED); transaction_listener = null; } } catch (Exception e) { printException(e, LogLevel.HIGH); } } /** Method used to drop an active transaction */ public void terminate() { retransmission_to.halt(); clearing_to.halt(); end_to.halt(); if (statusIs(STATE_TRYING)) sip_provider.removeSipProviderListener(new TransactionIdentifier( SipMethods.INVITE)); else sip_provider.removeSipProviderListener(transaction_id); changeStatus(STATE_TERMINATED); transaction_listener = null; } }
Java
public class ArgumentStringArray extends Argument<String[]> { public ArgumentStringArray(String id) { super(id, true, true); } @NotNull @Override public String[] parse(@NotNull String input) { return input.split(Pattern.quote(StringUtils.SPACE)); } @Override public void processNodes(@NotNull NodeMaker nodeMaker, boolean executable) { DeclareCommandsPacket.Node argumentNode = simpleArgumentNode(this, executable, false, false); argumentNode.parser = "brigadier:string"; argumentNode.properties = packetWriter -> { packetWriter.writeVarInt(2); // Greedy phrase }; nodeMaker.addNodes(new DeclareCommandsPacket.Node[]{argumentNode}); } }
Java
public class OrderBookModelTest { OrderBookModel testObject; @Before public void setup(){ testObject = new OrderBookModel(); } @Test public void shouldAddItemToTable() { testObject.setValueAt("Some Value", 0, 0); String testResult = ((String) testObject.getValueAt(0, 0)); assertThat(testResult, equalTo("Some Value")); assertThat(testObject.getRowCount(), equalTo(1)); } @Test public void shouldUpdateExistingRowWhenPricePointExists(){ testObject.setValueAt("1.0", 0, 0); testObject.setValueAt("1.0", 0, 1); testObject.setValueAt("1", 0, 2); String testResult = ((String)testObject.getValueAt(0,0)); assertThat(testObject.getRowCount(), equalTo(1)); assertThat(testResult, equalTo("1.0")); OrderBookMessage message1 = new OrderBookMessage(); message1.setType("limit"); message1.setSide("buy"); message1.setPrice(new BigDecimal(1.5)); message1.setSize(new BigDecimal(3.0)); testObject.insertInto(message1); int firstRow = 0; assertThat(testObject.getRowCount(), equalTo(2)); assertThat(testObject.getValueAt(firstRow, 0), equalTo("1.50000")); assertThat(testObject.getValueAt(firstRow, 1), equalTo("3.00000")); assertThat(testObject.getValueAt(firstRow, 2), equalTo("1")); OrderBookMessage message2 = new OrderBookMessage(); message2.setType("limit"); message2.setSide("buy"); message2.setPrice(new BigDecimal(1.5)); message2.setSize(new BigDecimal(2.200)); testObject.insertInto(message2); assertThat(testObject.getRowCount(), equalTo(2)); assertThat(testObject.getValueAt(firstRow, 0), equalTo("1.50000")); assertThat(testObject.getValueAt(firstRow, 1), equalTo("5.20000")); assertThat(testObject.getValueAt(firstRow, 2), equalTo("2")); } @Test public void shouldInsertBuyOrderAsNewRowWhenPriceIsUnique(){ testObject.setValueAt("1.0", 0, 0); String testResult = ((String)testObject.getValueAt(0,0)); assertThat(testResult, equalTo("1.0")); assertThat(testObject.getRowCount(), equalTo(1)); OrderBookMessage message1 = new OrderBookMessage(); message1.setType("limit"); message1.setSide("buy"); message1.setPrice(new BigDecimal(1.5)); message1.setSize(new BigDecimal(3.0)); testObject.insertInto(message1); int firstRow = 0; assertThat(testObject.getValueAt(firstRow, 0), equalTo("1.50000")); assertThat(testObject.getValueAt(firstRow, 1), equalTo("3.00000")); assertThat(testObject.getValueAt(firstRow, 2), equalTo("1")); OrderBookMessage message2 = new OrderBookMessage(); message2.setPrice(new BigDecimal("3.8")); message2.setSize(new BigDecimal("0.43400")); message2.setSide("buy"); message2.setType("limit"); testObject.insertInto(message2); // item should appear at the top of the list since it's a new highest bidder/buy order assertThat(testObject.getValueAt(0, 0), equalTo("3.80000")); assertThat(testObject.getValueAt(0, 1), equalTo("0.43400")); assertThat(testObject.getValueAt(0, 2), equalTo("1")); } @Test public void shouldInsertSellOrderAsNewRowWhenPriceIsUnique(){ testObject.setValueAt("1.00000", 0, 0); String testResult = ((String)testObject.getValueAt(0,0)); assertThat(testResult, equalTo("1.00000")); assertThat(testObject.getRowCount(), equalTo(1)); OrderBookMessage message = new OrderBookMessage(); message.setPrice(new BigDecimal("3.8")); message.setSize(new BigDecimal("0.43400")); message.setSide("sell"); testObject.insertInto(message); int firstRow = 0; // item should appear at the top of the list since it's a new highest bidder/buy order assertThat(testObject.getValueAt(firstRow, 0), equalTo("3.80000")); assertThat(testObject.getValueAt(firstRow, 1), equalTo("0.43400")); assertThat(testObject.getValueAt(firstRow, 2), equalTo("1")); } @Test public void shouldUpdateExistingSellOrderWhenPriceIsNotUnique(){ int firstRow = 0; testObject.setValueAt("1.00000", firstRow, 0); testObject.setValueAt("0.87655",firstRow, 1); testObject.setValueAt("1",firstRow, 2); assertThat(((String)testObject.getValueAt(firstRow, 0)), equalTo("1.00000")); assertThat(((String)testObject.getValueAt(firstRow, 1)), equalTo("0.87655")); assertThat(((String)testObject.getValueAt(firstRow, 2)), equalTo("1")); assertThat(testObject.getRowCount(), equalTo(1)); // create a new order OrderBookMessage message = new OrderBookMessage(); message.setPrice(new BigDecimal("1.0")); message.setSize(new BigDecimal("0.43400")); message.setSide("sell"); // insert the new order testObject.insertInto(message); // item should appear at the top of the list since it's a new highest bidder/buy order assertThat(testObject.getRowCount(), equalTo(1)); assertThat(testObject.getValueAt(0, 0), equalTo("1.00000")); assertThat(testObject.getValueAt(0, 1), equalTo("1.31055")); assertThat(testObject.getValueAt(0, 2), equalTo("2")); } @Test public void shouldUpdateExistingBuyOrderWhenPriceIsNotUnique(){ int firstRow = 0; testObject.setValueAt("1.00000", firstRow, 0); testObject.setValueAt("0.87655",firstRow, 1); testObject.setValueAt("1",firstRow, 2); assertThat(((String)testObject.getValueAt(firstRow, 0)), equalTo("1.00000")); assertThat(((String)testObject.getValueAt(firstRow, 1)), equalTo("0.87655")); assertThat(((String)testObject.getValueAt(firstRow, 2)), equalTo("1")); assertThat(testObject.getRowCount(), equalTo(1)); // create a new order OrderBookMessage message = new OrderBookMessage(); message.setPrice(new BigDecimal("1.0")); message.setSize(new BigDecimal("0.43400")); message.setSide("buy"); // insert the new order testObject.insertInto(message); // item should appear at the top of the list since it's a new highest bidder/buy order assertThat(testObject.getValueAt(0, 0), equalTo("1.00000")); assertThat(testObject.getValueAt(0, 1), equalTo("1.31055")); assertThat(testObject.getValueAt(0, 2), equalTo("2")); assertThat(testObject.getRowCount(), equalTo(1)); } @Test public void shouldReduceQtyByOneForDoneOrder(){ int firstRow = 0; testObject.setValueAt("1.00000", firstRow, 0); testObject.setValueAt("0.87655",firstRow, 1); testObject.setValueAt("5",firstRow, 2); assertThat(((String)testObject.getValueAt(firstRow, 0)), equalTo("1.00000")); assertThat(((String)testObject.getValueAt(firstRow, 1)), equalTo("0.87655")); assertThat(((String)testObject.getValueAt(firstRow, 2)), equalTo("5")); assertThat(testObject.getRowCount(), equalTo(1)); // create a new order OrderBookMessage message = new OrderBookMessage(); message.setType("done"); message.setPrice(new BigDecimal("1.0")); message.setSize(new BigDecimal("0.43400")); message.setSide("buy"); // insert the new order testObject.insertInto(message); // item should appear at the top of the list since it's a new highest bidder/buy order assertThat(testObject.getValueAt(0, 0), equalTo("1.00000")); assertThat(testObject.getValueAt(0, 1), equalTo("0.44255")); assertThat(testObject.getValueAt(0, 2), equalTo("4")); assertThat(testObject.getRowCount(), equalTo(1)); } @Test public void shouldReduceQtyByOneForMatchedOrder(){ int firstRow = 0; testObject.setValueAt("1.00000", firstRow, 0); testObject.setValueAt("0.87655",firstRow, 1); testObject.setValueAt("5",firstRow, 2); assertThat(((String)testObject.getValueAt(firstRow, 0)), equalTo("1.00000")); assertThat(((String)testObject.getValueAt(firstRow, 1)), equalTo("0.87655")); assertThat(((String)testObject.getValueAt(firstRow, 2)), equalTo("5")); assertThat(testObject.getRowCount(), equalTo(1)); // create a new order OrderBookMessage message = new OrderBookMessage(); message.setType("matched"); message.setPrice(new BigDecimal("1.0")); message.setSize(new BigDecimal("0.43400")); message.setSide("buy"); // insert the new order testObject.insertInto(message); // item should appear at the top of the list since it's a new highest bidder/buy order assertThat(testObject.getValueAt(0, 0), equalTo("1.00000")); assertThat(testObject.getValueAt(0, 1), equalTo("0.44255")); assertThat(testObject.getValueAt(0, 2), equalTo("4")); assertThat(testObject.getRowCount(), equalTo(1)); } @Test public void shouldReduceQtyByOneForMatchedOrderWithRemainingSize(){ int firstRow = 0; testObject.setValueAt("1.00000", firstRow, 0); testObject.setValueAt("0.87655",firstRow, 1); testObject.setValueAt("5",firstRow, 2); assertThat(((String)testObject.getValueAt(firstRow, 0)), equalTo("1.00000")); assertThat(((String)testObject.getValueAt(firstRow, 1)), equalTo("0.87655")); assertThat(((String)testObject.getValueAt(firstRow, 2)), equalTo("5")); assertThat(testObject.getRowCount(), equalTo(1)); // create a new order OrderBookMessage message = new OrderBookMessage(); message.setType("matched"); message.setPrice(new BigDecimal("1.0")); message.setRemaining_size(new BigDecimal("0.43400")); message.setSide("buy"); // insert the new order testObject.insertInto(message); // item should appear at the top of the list since it's a new highest bidder/buy order assertThat(testObject.getValueAt(0, 0), equalTo("1.00000")); assertThat(testObject.getValueAt(0, 1), equalTo("0.43400")); assertThat(testObject.getValueAt(0, 2), equalTo("4")); assertThat(testObject.getRowCount(), equalTo(1)); } @Test public void shouldReduceQtyByOneForDoneOrderWithRemainingSize(){ int firstRow = 0; testObject.setValueAt("1.00000", firstRow, 0); testObject.setValueAt("0.87655",firstRow, 1); testObject.setValueAt("5",firstRow, 2); assertThat(((String)testObject.getValueAt(firstRow, 0)), equalTo("1.00000")); assertThat(((String)testObject.getValueAt(firstRow, 1)), equalTo("0.87655")); assertThat(((String)testObject.getValueAt(firstRow, 2)), equalTo("5")); assertThat(testObject.getRowCount(), equalTo(1)); // create a new order OrderBookMessage message = new OrderBookMessage(); message.setType("done"); message.setPrice(new BigDecimal("1.0")); message.setRemaining_size(new BigDecimal("0.43400")); message.setSide("buy"); // insert the new order testObject.insertInto(message); // item should appear at the top of the list since it's a new highest bidder/buy order assertThat(testObject.getValueAt(0, 0), equalTo("1.00000")); assertThat(testObject.getValueAt(0, 1), equalTo("0.43400")); assertThat(testObject.getValueAt(0, 2), equalTo("4")); assertThat(testObject.getRowCount(), equalTo(1)); } @Test public void shouldAddItemToLastOrdersList(){ // create a new order OrderBookMessage message = new OrderBookMessage(); message.setType("done"); message.setPrice(new BigDecimal("1.0")); message.setRemaining_size(new BigDecimal("0.43400")); message.setSide("buy"); message.setSequence(1L); testObject.checkSequence(message); assertThat(testObject.getLastOrders().size(), equalTo(1)); } @Test public void shouldInsertOrderBookMessageAfterExistingOrder(){ // create a new order OrderBookMessage message = new OrderBookMessage(); message.setType("done"); message.setPrice(new BigDecimal("1.0")); message.setRemaining_size(new BigDecimal("0.43400")); message.setSide("buy"); message.setSequence(1L); testObject.checkSequence(message); assertThat(testObject.getLastOrders().size(), equalTo(1)); OrderBookMessage newMessage = new OrderBookMessage(); newMessage.setSequence(2L); testObject.checkSequence(newMessage); assertThat(testObject.getLastOrders().size(), equalTo(2)); assertThat(testObject.getLastOrders().get(0).getSequence(), equalTo(1L)); assertThat(testObject.getLastOrders().get(1).getSequence(), equalTo(2L)); } @Test public void shouldInsertOrderBookMessageBeforeExistingOrder(){ // create a new order OrderBookMessage message = new OrderBookMessage(); message.setType("done"); message.setPrice(new BigDecimal(1.0)); message.setRemaining_size(new BigDecimal("0.43400")); message.setSide("buy"); message.setSequence(1L); testObject.checkSequence(message); assertThat(testObject.getLastOrders().size(), equalTo(1)); OrderBookMessage newMessage = new OrderBookMessage(); newMessage.setSequence(0L); testObject.checkSequence(newMessage); assertThat(testObject.getLastOrders().size(), equalTo(2)); assertThat(testObject.getLastOrders().get(0).getSequence(), equalTo(0L)); assertThat(testObject.getLastOrders().get(1).getSequence(), equalTo(1L)); } @Test public void shouldInsertOneOrderIntoTable(){ // create a new order OrderBookMessage message = new OrderBookMessage(); message.setType("limit"); message.setPrice(new BigDecimal("1.0")); message.setRemaining_size(new BigDecimal("0.43400")); message.setSide("buy"); message.setSequence(1L); testObject.incomingOrder(message); assertThat(testObject.getRowCount(), equalTo(1)); assertThat(testObject.getLastOrders().get(0).getSequence(), equalTo(1L)); } @Test public void shouldInsertTwoOrdersIntoTable(){ // create a new order OrderBookMessage message1 = new OrderBookMessage(); message1.setType("limit"); message1.setPrice(new BigDecimal("1.0")); message1.setRemaining_size(new BigDecimal("0.43400")); message1.setSide("buy"); message1.setSequence(1L); testObject.incomingOrder(message1); assertThat(testObject.getRowCount(), equalTo(1)); assertThat(testObject.getLastOrders().get(0).getSequence(), equalTo(1L)); OrderBookMessage message2 = new OrderBookMessage(); message2.setType("limit"); message2.setPrice(new BigDecimal("1.1")); message2.setRemaining_size(new BigDecimal("0.43400")); message2.setSide("buy"); message2.setSequence(2L); testObject.incomingOrder(message2); assertThat(testObject.getRowCount(), equalTo(2)); assertThat(testObject.getLastOrders().get(0).getSequence(), equalTo(1L)); assertThat(testObject.getLastOrders().get(1).getSequence(), equalTo(2L)); } @Test public void shouldInsertTwoOrdersIntoTableAfterMissingMessageIsReceived(){ // create a new order OrderBookMessage message1 = new OrderBookMessage(); message1.setType("limit"); message1.setPrice(new BigDecimal("1.0")); message1.setRemaining_size(new BigDecimal("0.43400")); message1.setSide("buy"); message1.setSequence(1L); testObject.incomingOrder(message1); assertThat(testObject.getRowCount(), equalTo(1)); assertThat(testObject.getLastOrders().get(0).getSequence(), equalTo(1L)); // third message will be received before 2nd message OrderBookMessage message3 = new OrderBookMessage(); message3.setType("limit"); message3.setPrice(new BigDecimal("1.1")); message3.setRemaining_size(new BigDecimal("0.43400")); message3.setSide("buy"); message3.setSequence(3L); testObject.incomingOrder(message3); assertThat(testObject.getRowCount(), equalTo(2)); assertThat(testObject.getLastOrders().get(0).getSequence(), equalTo(1L)); assertThat(testObject.getLastOrders().get(1).getSequence(), equalTo(3L)); // 2nd message arrived late... OrderBookMessage message2 = new OrderBookMessage(); message2.setType("limit"); message2.setPrice(new BigDecimal("1.3")); message2.setRemaining_size(new BigDecimal("0.43400")); message2.setSide("buy"); message2.setSequence(2L); testObject.incomingOrder(message2); assertThat(testObject.getRowCount(), equalTo(3)); assertThat(testObject.getLastOrders().get(0).getSequence(), equalTo(1L)); assertThat(testObject.getLastOrders().get(1).getSequence(), equalTo(2L)); assertThat(testObject.getLastOrders().get(2).getSequence(), equalTo(3L)); } }
Java
public class Page extends TextRectangle<Page> implements Content.Holder<Page>, PositionalContent.Holder<Page>, PageColor.Holder<Page>, PageLayout.Holder<Page> { private static final long serialVersionUID = 7244915848277591913L; @Override public List<Class<? extends ElementAttribute>> getDefaultLayout() { return this.hasAttribute(Content.class) ? Lists.mutable.of(Content.class) : Lists.mutable.of(PositionalContent.class); } }
Java
public final class TestSorters extends TestCase { public void testAttachmentChunksSorter() { AttachmentChunks[] chunks; // Simple chunks = new AttachmentChunks[] { new AttachmentChunks("__attach_version1.0_#00000001"), new AttachmentChunks("__attach_version1.0_#00000000"), }; Arrays.sort(chunks, new AttachmentChunksSorter()); assertEquals("__attach_version1.0_#00000000", chunks[0].getPOIFSName()); assertEquals("__attach_version1.0_#00000001", chunks[1].getPOIFSName()); // Lots, with gaps chunks = new AttachmentChunks[] { new AttachmentChunks("__attach_version1.0_#00000101"), new AttachmentChunks("__attach_version1.0_#00000001"), new AttachmentChunks("__attach_version1.0_#00000002"), new AttachmentChunks("__attach_version1.0_#00000005"), new AttachmentChunks("__attach_version1.0_#00000026"), new AttachmentChunks("__attach_version1.0_#00000000"), new AttachmentChunks("__attach_version1.0_#000000AB"), }; Arrays.sort(chunks, new AttachmentChunksSorter()); assertEquals("__attach_version1.0_#00000000", chunks[0].getPOIFSName()); assertEquals("__attach_version1.0_#00000001", chunks[1].getPOIFSName()); assertEquals("__attach_version1.0_#00000002", chunks[2].getPOIFSName()); assertEquals("__attach_version1.0_#00000005", chunks[3].getPOIFSName()); assertEquals("__attach_version1.0_#00000026", chunks[4].getPOIFSName()); assertEquals("__attach_version1.0_#000000AB", chunks[5].getPOIFSName()); assertEquals("__attach_version1.0_#00000101", chunks[6].getPOIFSName()); } public void testRecipientChunksSorter() { RecipientChunks[] chunks; // Simple chunks = new RecipientChunks[] { new RecipientChunks("__recip_version1.0_#00000001"), new RecipientChunks("__recip_version1.0_#00000000"), }; Arrays.sort(chunks, new RecipientChunksSorter()); assertEquals(0, chunks[0].recipientNumber); assertEquals(1, chunks[1].recipientNumber); // Lots, with gaps chunks = new RecipientChunks[] { new RecipientChunks("__recip_version1.0_#00020001"), new RecipientChunks("__recip_version1.0_#000000FF"), new RecipientChunks("__recip_version1.0_#00000205"), new RecipientChunks("__recip_version1.0_#00000001"), new RecipientChunks("__recip_version1.0_#00000005"), new RecipientChunks("__recip_version1.0_#00000009"), new RecipientChunks("__recip_version1.0_#00000404"), new RecipientChunks("__recip_version1.0_#00000000"), }; Arrays.sort(chunks, new RecipientChunksSorter()); assertEquals(0, chunks[0].recipientNumber); assertEquals(1, chunks[1].recipientNumber); assertEquals(5, chunks[2].recipientNumber); assertEquals(9, chunks[3].recipientNumber); assertEquals(0xFF, chunks[4].recipientNumber); assertEquals(0x205, chunks[5].recipientNumber); assertEquals(0x404, chunks[6].recipientNumber); assertEquals(0x20001, chunks[7].recipientNumber); } }
Java
class Compactor implements Consumer<Object> { private static final Log log = LogFactory.getLog(Compactor.class, Log.class); private final NonBlockingManager nonBlockingManager; private final ConcurrentMap<Integer, Stats> fileStats = new ConcurrentHashMap<>(); private final FileProvider fileProvider; private final TemporaryTable temporaryTable; private final Marshaller marshaller; private final TimeService timeService; private final KeyPartitioner keyPartitioner; private final int maxFileSize; private final double compactionThreshold; private final FlowableProcessor<Object> processor; private Index index; // as processing single scheduled compaction takes a lot of time, we don't use the queue to signalize private final AtomicBoolean clearSignal = new AtomicBoolean(); private volatile boolean terminateSignal = false; private CompletableFuture<Void> paused = CompletableFutures.completedNull(); // Special object used solely for the purpose of resuming the compactor after compacting a file and waiting for // all indices to be updated private static final Object RESUME_PILL = new Object(); // This buffer is used by the compactor thread to avoid allocating buffers per entry written that are smaller // than the header size private final java.nio.ByteBuffer REUSED_BUFFER = java.nio.ByteBuffer.allocate(EntryHeader.HEADER_SIZE_11_0); FileProvider.Log logFile = null; long nextExpirationTime = -1; int currentOffset = 0; public Compactor(NonBlockingManager nonBlockingManager, FileProvider fileProvider, TemporaryTable temporaryTable, Marshaller marshaller, TimeService timeService, KeyPartitioner keyPartitioner, int maxFileSize, double compactionThreshold, Executor blockingExecutor) { this.nonBlockingManager = nonBlockingManager; this.fileProvider = fileProvider; this.temporaryTable = temporaryTable; this.marshaller = marshaller; this.timeService = timeService; this.keyPartitioner = keyPartitioner; this.maxFileSize = maxFileSize; this.compactionThreshold = compactionThreshold; processor = UnicastProcessor.create().toSerialized(); Scheduler scheduler = Schedulers.from(blockingExecutor); processor.observeOn(scheduler) .delay(obj -> { // These types are special and should allow processing always if (obj == RESUME_PILL || obj instanceof CompletableFuture) { return Flowable.empty(); } return RxJavaInterop.voidCompletionStageToFlowable(paused); }) .subscribe(this, error -> log.compactorEncounteredException(error, -1)); } public void setIndex(Index index) { this.index = index; } public void releaseStats(int file) { fileStats.remove(file); } public void free(int file, int size) { // entries expired from compacted file are reported with file = -1 if (file < 0) return; recordFreeSpace(getStats(file, -1, -1), file, size); } public void completeFile(int file, int currentSize, long nextExpirationTime) { Stats stats = getStats(file, currentSize, nextExpirationTime); stats.setCompleted(); if (stats.readyToBeScheduled(compactionThreshold, stats.getFree())) { schedule(file, stats); } } public interface CompactionExpirationSubscriber { void onEntryPosition(EntryPosition entryPosition) throws IOException; void onEntryEntryRecord(EntryRecord entryRecord) throws IOException; void onComplete(); void onError(Throwable t); } public void performExpirationCompaction(CompactionExpirationSubscriber subscriber) { processor.onNext(subscriber); } // Present for testing only - note is still asynchronous if underlying executor is CompletionStage<Void> forceCompactionForAllNonLogFiles() { AggregateCompletionStage<Void> aggregateCompletionStage = CompletionStages.aggregateCompletionStage(); for (Map.Entry<Integer, Stats> stats : fileStats.entrySet()) { int fileId = stats.getKey(); if (!fileProvider.isLogFile(fileId) && !stats.getValue().markedForDeletion) { CompactionRequest compactionRequest = new CompactionRequest(fileId); processor.onNext(compactionRequest); aggregateCompletionStage.dependsOn(compactionRequest); } } return aggregateCompletionStage.freeze(); } // Present for testing only - so test can see what files are currently known to compactor Set<Integer> getFiles() { return fileStats.keySet(); } private Stats getStats(int file, int currentSize, long expirationTime) { Stats stats = fileStats.get(file); if (stats == null) { int fileSize = currentSize < 0 ? (int) fileProvider.getFileSize(file) : currentSize; stats = new Stats(fileSize, 0, expirationTime); Stats other = fileStats.putIfAbsent(file, stats); if (other != null) { if (fileSize > other.getTotal()) { other.setTotal(fileSize); } return other; } } if (stats.getTotal() < 0) { int fileSize = currentSize < 0 ? (int) fileProvider.getFileSize(file) : currentSize; if (fileSize >= 0) { stats.setTotal(fileSize); } } return stats; } private void recordFreeSpace(Stats stats, int file, int size) { if (stats.addFree(size, compactionThreshold)) { schedule(file, stats); } } private void schedule(int file, Stats stats) { boolean shouldSchedule = false; synchronized (stats) { if (!stats.isScheduled()) { log.debugf("Scheduling file %d for compaction: %d/%d free", file, stats.free.get(), stats.total); stats.setScheduled(); shouldSchedule = true; } } if (shouldSchedule) { CompactionRequest request = new CompactionRequest(file); processor.onNext(request); request.whenComplete((__, t) -> { if (t != null) { log.compactorEncounteredException(t, file); // Poor attempt to allow compactor to continue operating - file will never be compacted again fileStats.remove(file); } }); } } /** * Immediately sends a request to pause the compactor. The returned stage will complete when the * compactor is actually paused. To resume the compactor the {@link #resumeAfterClear()} method * must be invoked or else the compactor will not process new requests. * * @return a stage that when complete the compactor is paused */ public CompletionStage<Void> clearAndPause() { if (clearSignal.getAndSet(true)) { throw new IllegalStateException("Clear signal was already set for compactor, clear cannot be invoked " + "concurrently with another!"); } ClearFuture clearFuture = new ClearFuture(); // Make sure to do this before submitting to processor this is done in the blocking thread clearFuture.whenComplete((ignore, t) -> fileStats.clear()); processor.onNext(clearFuture); return clearFuture; } private static class ClearFuture extends CompletableFuture<Void> { @Override public String toString() { return "ClearFuture{}"; } } public void resumeAfterClear() { // This completion will push all the other tasks that have been delayed in this method call if (!clearSignal.getAndSet(false)) { throw new IllegalStateException("Resume of compactor invoked without first clear and pausing!"); } } private void resumeAfterPause() { processor.onNext(RESUME_PILL); } public void stopOperations() { terminateSignal = true; processor.onComplete(); Util.close(logFile); logFile = null; } private static class CompactionRequest extends CompletableFuture<Void> { private final int fileId; private CompactionRequest(int fileId) { this.fileId = fileId; } @Override public String toString() { return "CompactionRequest{" + "fileId=" + fileId + '}'; } } void handleIgnoredElement(Object o) { if (o instanceof CompactionExpirationSubscriber) { // We assume the subscriber handles blocking properly ((CompactionExpirationSubscriber) o).onComplete(); } else if (o instanceof CompletableFuture) { nonBlockingManager.complete((CompletableFuture<?>) o, null); } } @Override public void accept(Object o) throws Throwable { if (terminateSignal) { log.tracef("Compactor already terminated, ignoring request " + o); // Just ignore if terminated handleIgnoredElement(o); return; } if (o == RESUME_PILL) { log.tracef("Resuming compactor"); // This completion will push all the other tasks that have been delayed in this method call // Note this must be completed in the context of the compactor thread paused.complete(null); return; } // Note that this accept is only invoked from a single thread at a time so we don't have to worry about // any other threads decrementing clear signal. However, another thread can increment, that is okay for us if (clearSignal.get()) { // We ignore any entries since it was last cleared if (o instanceof ClearFuture) { log.tracef("Compactor ignoring all future compactions until resumed"); if (logFile != null) { logFile.close(); logFile = null; nextExpirationTime = -1; } nonBlockingManager.complete((CompletableFuture<?>) o, null); } else { log.tracef("Ignoring compaction request for %s as compactor is being cleared", o); handleIgnoredElement(o); } return; } if (o instanceof CompactionExpirationSubscriber) { CompactionExpirationSubscriber subscriber = (CompactionExpirationSubscriber) o; try { // We have to copy the file ids into its own collection because it can pickup the compactor files sometimes // causing extra unneeded churn in some cases Set<Integer> currentFiles = new HashSet<>(); for (CloseableIterator<Integer> iter = fileProvider.getFileIterator(); iter.hasNext(); ) { currentFiles.add(iter.next()); } for (int fileId : currentFiles) { Stats stats = fileStats.get(fileId); long currentTimeMilliseconds = timeService.wallClockTime(); boolean isLogFile = fileProvider.isLogFile(fileId); if (stats != null) { // Don't check for expired entries in any files that are marked for deletion or don't have entries // that can expire yet // Note that log files do not set the expiration time, so it is always -1 in that case, but we still // want to check just in case some files are expired there. if (stats.markedForDeletion() || (!isLogFile && stats.nextExpirationTime == -1) || stats.nextExpirationTime > currentTimeMilliseconds) { log.tracef("Skipping expiration for file %d since it is marked for deletion: %s or its expiration time %s is not yet", (Object) fileId, stats.markedForDeletion(), stats.nextExpirationTime); continue; } // Make sure we don't start another compactoin for this file while performing expiration stats.scheduled = true; } compactSingleFile(fileId, isLogFile, subscriber, currentTimeMilliseconds); } subscriber.onComplete(); } catch (Throwable t) { subscriber.onError(t); } return; } CompactionRequest request = (CompactionRequest) o; try { // Any other type submitted has to be a positive integer Stats stats = fileStats.get(request.fileId); // Double check that the file wasn't removed. If stats are null that means the file was previously removed // and also make sure the file wasn't marked for deletion, but hasn't yet if (stats != null && !stats.markedForDeletion()) { // If this was an explicit compaction, make sure we don't start another on accident stats.scheduled = true; compactSingleFile(request.fileId, false, null, timeService.wallClockTime()); } request.complete(null); } catch (Throwable t) { log.trace("Completing compaction for file: " + request.fileId + " due to exception!", t); request.completeExceptionally(t); } } /** * Compacts a single file into the current log file. This method has two modes of operation based on if the file * is a log file or not. If it is a log file non expired entries are ignored and only expired entries are "updated" * to be deleted in the new log file and expiration listener is notified. If it is not a log file all entries are * moved to the new log file and the current file is deleted afterwards. If an expired entry is found during compaction * of a non log file the expiration listener is notified and the entry is not moved, however if no expiration listener * is provided the expired entry is moved to the new file as is still expired. * @param scheduledFile the file identifier to compact * @param isLogFile whether the provided file as a log file, which means we only notify and compact expired * entries (ignore others) * @param subscriber the subscriber that is notified of various entries being expired * @throws IOException thrown if there was an issue with reading or writing to a file * @throws ClassNotFoundException thrown if there is an issue deserializing the key for an entry */ private void compactSingleFile(int scheduledFile, boolean isLogFile, CompactionExpirationSubscriber subscriber, long currentTimeMilliseconds) throws IOException, ClassNotFoundException { assert scheduledFile >= 0; if (subscriber == null) { log.tracef("Compacting file %d", scheduledFile); } else { log.tracef("Removing expired entries from file %d", scheduledFile); } int scheduledOffset = 0; // Store expired entries to remove after we update the index List<EntryPosition> expiredTemp = subscriber != null ? new ArrayList<>() : null; List<EntryRecord> expiredIndex = subscriber != null ? new ArrayList<>() : null; FileProvider.Handle handle = fileProvider.getFile(scheduledFile); if (handle == null) { throw new IllegalStateException("Compactor should not get deleted file for compaction!"); } try { AggregateCompletionStage<Void> aggregateCompletionStage = CompletionStages.aggregateCompletionStage(); while (!clearSignal.get() && !terminateSignal) { EntryHeader header = EntryRecord.readEntryHeader(handle, scheduledOffset); if (header == null) { break; } byte[] serializedKey = EntryRecord.readKey(handle, header, scheduledOffset); if (serializedKey == null) { throw new IllegalStateException("End of file reached when reading key on " + handle.getFileId() + ":" + scheduledOffset); } Object key = marshaller.objectFromByteBuffer(serializedKey); int segment = keyPartitioner.getSegment(key); int valueLength = header.valueLength(); int indexedOffset = valueLength > 0 ? scheduledOffset : ~scheduledOffset; // Whether to drop the entire index (this cannot be true if truncate is false) // We drop all entries by default unless it is a log file as we can't drop any of those since we may // try to compact a log file multiple times, note modifications to drop variable below should only be to set // it to false boolean drop = !isLogFile; // Whether to truncate the value boolean truncate = false; EntryPosition entry = temporaryTable.get(segment, key); if (entry != null) { synchronized (entry) { if (log.isTraceEnabled()) { log.tracef("Key for %d:%d was found in temporary table on %d:%d", scheduledFile, scheduledOffset, entry.file, entry.offset); } if (entry.file == scheduledFile && entry.offset == indexedOffset) { long entryExpiryTime = header.expiryTime(); // It's quite unlikely that we would compact a record that is not indexed yet, // but let's handle that if (entryExpiryTime >= 0 && entryExpiryTime <= currentTimeMilliseconds) { // We can only truncate expired entries if this was compacted with purge expire and this entry // isn't a removed marker if (expiredTemp != null && entry.offset >= 0) { truncate = true; expiredTemp.add(entry); } } else if (isLogFile) { // Non expired entry in a log file, just skip it scheduledOffset += header.totalLength(); continue; } } else if (entry.file == scheduledFile && entry.offset == ~scheduledOffset) { // The temporary table doesn't know how many entries we have for a key, so we shouldn't truncate // or drop log.tracef("Key for %d:%d ignored as it was expired"); scheduledOffset += header.totalLength(); continue; } else { truncate = true; } } // When we have found the entry in temporary table, it's possible that the delete operation // (that was recorded in temporary table) will arrive to index after DROPPED - in that case // we could remove the entry and delete would not find it drop = false; } else { EntryInfo info = index.getInfo(key, segment, serializedKey); assert info != null : "No index info found for key: " + key; assert info.numRecords > 0; if (info.file == scheduledFile && info.offset == scheduledOffset) { assert header.valueLength() > 0; long entryExpiryTime = header.expiryTime(); // live record with data if (entryExpiryTime >= 0 && entryExpiryTime <= currentTimeMilliseconds) { // We can only truncate expired entries if this was compacted with purge expire if (expiredIndex != null) { EntryRecord record = index.getRecordEvenIfExpired(key, segment, serializedKey); truncate = true; expiredIndex.add(record); // If there are more entries we cannot drop the index as we need a tombstone if (info.numRecords > 1) { drop = false; } } else { // We can't drop an expired entry without notifying, so we write it to the new compacted file drop = false; } } else if (isLogFile) { // Non expired entry in a log file, just skip it scheduledOffset += header.totalLength(); continue; } else { drop = false; } if (log.isTraceEnabled()) { log.tracef("Is %d:%d expired? %s, numRecords? %d", scheduledFile, scheduledOffset, truncate, info.numRecords); } } else if (isLogFile) { // If entry doesn't match the index we can't touch it when it is a log file scheduledOffset += header.totalLength(); continue; } else if (info.file == scheduledFile && info.offset == ~scheduledOffset && info.numRecords > 1) { // The entry was expired, but we have other records so we can't drop this one or else the index will rebuild incorrectly drop = false; } else if (log.isTraceEnabled()) { log.tracef("Key for %d:%d was found in index on %d:%d, %d record => drop", scheduledFile, scheduledOffset, info.file, info.offset, info.numRecords); } } if (drop) { if (log.isTraceEnabled()) { log.tracef("Drop %d:%d (%s)", scheduledFile, (Object) scheduledOffset, header.valueLength() > 0 ? "record" : "tombstone"); } index.handleRequest(IndexRequest.dropped(segment, key, ByteBufferImpl.create(serializedKey), scheduledFile, scheduledOffset)); } else { if (logFile == null || currentOffset + header.totalLength() > maxFileSize) { if (logFile != null) { logFile.close(); completeFile(logFile.fileId, currentOffset, nextExpirationTime); nextExpirationTime = -1; } currentOffset = 0; logFile = fileProvider.getFileForLog(); log.debugf("Compacting to %d", (Object) logFile.fileId); } byte[] serializedValue = null; EntryMetadata metadata = null; byte[] serializedInternalMetadata = null; int entryOffset; int writtenLength; if (header.valueLength() > 0 && !truncate) { if (header.metadataLength() > 0) { metadata = EntryRecord.readMetadata(handle, header, scheduledOffset); } serializedValue = EntryRecord.readValue(handle, header, scheduledOffset); if (header.internalMetadataLength() > 0) { serializedInternalMetadata = EntryRecord.readInternalMetadata(handle, header, scheduledOffset); } entryOffset = currentOffset; writtenLength = header.totalLength(); // Update the next expiration time only for entries that are not removed nextExpirationTime = ExpiryHelper.mostRecentExpirationTime(nextExpirationTime, header.expiryTime()); } else { entryOffset = ~currentOffset; writtenLength = header.getHeaderLength() + header.keyLength(); } EntryRecord.writeEntry(logFile.fileChannel, REUSED_BUFFER, serializedKey, metadata, serializedValue, serializedInternalMetadata, header.seqId(), header.expiryTime()); TemporaryTable.LockedEntry lockedEntry = temporaryTable.replaceOrLock(segment, key, logFile.fileId, entryOffset, scheduledFile, indexedOffset); if (lockedEntry == null) { if (log.isTraceEnabled()) { log.trace("Found entry in temporary table"); } } else { boolean update = false; try { EntryInfo info = index.getInfo(key, segment, serializedKey); if (info == null) { throw new IllegalStateException(String.format( "%s was not found in index but it was not in temporary table and there's entry on %d:%d", key, scheduledFile, indexedOffset)); } else { update = info.file == scheduledFile && info.offset == indexedOffset; } if (log.isTraceEnabled()) { log.tracef("In index the key is on %d:%d (%s)", info.file, info.offset, String.valueOf(update)); } } finally { if (update) { temporaryTable.updateAndUnlock(lockedEntry, logFile.fileId, entryOffset); } else { temporaryTable.removeAndUnlock(lockedEntry, segment, key); } } } if (log.isTraceEnabled()) { log.tracef("Update %d:%d -> %d:%d | %d,%d", scheduledFile, indexedOffset, logFile.fileId, entryOffset, logFile.fileChannel.position(), logFile.fileChannel.size()); } IndexRequest indexRequest; ByteBuffer keyBuffer = ByteBufferImpl.create(serializedKey); if (isLogFile) { // When it is a log file we are still keeping the original entry, we are just updating it to say // it was expired indexRequest = IndexRequest.update(segment, key, keyBuffer, logFile.fileId, entryOffset, writtenLength); } else { // entryFile cannot be used as we have to report the file due to free space statistics indexRequest = IndexRequest.moved(segment, key, keyBuffer, logFile.fileId, entryOffset, writtenLength, scheduledFile, indexedOffset); } aggregateCompletionStage.dependsOn(index.handleRequest(indexRequest)); currentOffset += writtenLength; } scheduledOffset += header.totalLength(); } if (!clearSignal.get()) { // We delay the next operation until all prior moves are done. By moving it can trigger another // compaction before the index has been fully updated. Thus we block any other compaction events // until all entries have been moved for this file CompletionStage<Void> aggregate = aggregateCompletionStage.freeze(); paused = new CompletableFuture<>(); // We resume after completed, Note that we must complete the {@code paused} variable inside the compactor // execution pipeline otherwise we can invoke compactor operations in the wrong thread aggregate.whenComplete((ignore, t) -> { resumeAfterPause(); if (t != null) { log.error("There was a problem moving indexes for compactor with file " + logFile.fileId, t); } }); } } finally { handle.close(); } if (subscriber != null) { for (EntryPosition entryPosition : expiredTemp) { subscriber.onEntryPosition(entryPosition); } for (EntryRecord entryRecord : expiredIndex) { subscriber.onEntryEntryRecord(entryRecord); } } if (isLogFile) { log.tracef("Finished expiring entries in log file %d, leaving file as is", scheduledFile); } else if (!terminateSignal && !clearSignal.get()) { // The deletion must be executed only after the index is fully updated. log.tracef("Finished compacting %d, scheduling delete", scheduledFile); // Mark the file for deletion so expiration won't check it Stats stats = fileStats.get(scheduledFile); if (stats != null) { stats.markForDeletion(); } index.deleteFileAsync(scheduledFile); } } private static class Stats { private final AtomicInteger free; private volatile int total; private final long nextExpirationTime; /* File is not 'completed' when we have not loaded that yet completely. Files created by log appender/compactor are completed as soon as it closes them. File cannot be scheduled for compaction until it's completed. */ private volatile boolean completed = false; private volatile boolean scheduled = false; private boolean markedForDeletion = false; private Stats(int total, int free, long nextExpirationTime) { this.free = new AtomicInteger(free); this.total = total; this.nextExpirationTime = nextExpirationTime; } public int getTotal() { return total; } public void setTotal(int total) { this.total = total; } public boolean addFree(int size, double compactionThreshold) { int free = this.free.addAndGet(size); return readyToBeScheduled(compactionThreshold, free); } public int getFree() { return free.get(); } public boolean readyToBeScheduled(double compactionThreshold, int free) { int total = this.total; return completed && !scheduled && total >= 0 && free >= total * compactionThreshold; } public boolean isScheduled() { return scheduled; } public void setScheduled() { scheduled = true; } public boolean isCompleted() { return completed; } public void setCompleted() { this.completed = true; } public void markForDeletion() { this.markedForDeletion = true; } public boolean markedForDeletion() { return this.markedForDeletion; } } }
Java
class Proc implements EventSink { private final Process process; private int exitValue; private long executionTime; private final OutputConsumptionThread err; private final String command; private final List<String> args; private final Long timeout; private final BlockingQueue<ExecutionEvent> eventQueue = new LinkedBlockingQueue<ExecutionEvent>(); private final IoHandler ioHandler; public Proc(String command, List<String> args, Map<String, String> env, InputStream stdin, Object stdout, File directory, Long timeout) throws StartupException, TimeoutException, ExternalProcessFailureException { this(command, args, env, stdin, stdout, directory, timeout, null); } public Proc(String command, List<String> args, Map<String, String> env, InputStream stdin, Object stdout, File directory, Long timeout, Object stderr) throws StartupException, TimeoutException, ExternalProcessFailureException { this.command = command; this.args = args; this.timeout = timeout; String[] envArray = getEnv(env); String[] cmdArray = concatenateCmdArgs(); long t1 = System.currentTimeMillis(); OutputConsumptionThread stdoutConsumer; try { process = Runtime.getRuntime().exec(cmdArray, envArray, directory); stdoutConsumer = createStreamConsumer(stdout); if(stderr == null) { err = new ByteArrayConsumptionThread(this); } else { err = createStreamConsumer(stderr); } ioHandler = new IoHandler(stdin, stdoutConsumer, err, process); } catch (IOException e) { throw new StartupException("Could not startup process '" + toString() + "'.", e); } try { startControlThread(); do { ExecutionEvent nextEvent = timeout == null ? eventQueue.poll(MAX_VALUE, HOURS) : eventQueue.poll(timeout, MILLISECONDS); if (nextEvent == null) { killCleanUpAndThrowTimeoutException(); } if (nextEvent == PROCESS_EXITED) { break; } if (nextEvent == EXCEPTION_IN_STREAM_HANDLING) { killProcessCleanup(); break; } throw new RuntimeException("Felix reckons we should never reach this point"); } while (true); List<Throwable> exceptions = ioHandler.joinConsumption(); if (!exceptions.isEmpty()) { throw new IllegalStateException("Exception in stream consumption", exceptions.get(0)); } executionTime = System.currentTimeMillis() - t1; } catch (InterruptedException e) { throw new RuntimeException("", e); } } private OutputConsumptionThread createStreamConsumer(Object stream) { if (stream instanceof OutputStream) { return new StreamCopyConsumptionThread((OutputStream)stream, this); } else if (stream instanceof StreamConsumer) { return new StreamConsumerConsumptionThread(Proc.this, (StreamConsumer)stream); } else {throw new RuntimeException("Badness, badness");} } byte[] getErrorBytes() { if(err instanceof ByteArrayConsumptionThread) { return ((ByteArrayConsumptionThread)err).getBytes(); } // Output stream/stream consumer was provided by user, we don't own it. return null; } public String getErrorString() { byte[] bytes = getErrorBytes(); return bytes != null ? new String(bytes, StandardCharsets.UTF_8) : null; } private void startControlThread() { new Thread(new Runnable() { public void run() { try { exitValue = process.waitFor(); dispatch(PROCESS_EXITED); } catch (InterruptedException e) { throw new RuntimeException("", e); } } }).start(); } private void killCleanUpAndThrowTimeoutException() { process.destroy(); ioHandler.cancelConsumption(); throw new TimeoutException(toString(), timeout); } private void killProcessCleanup() { process.destroy(); ioHandler.cancelConsumption(); } public void dispatch(ExecutionEvent event) { try { eventQueue.put(event); } catch (InterruptedException e) { throw new RuntimeException("${END}", e); } } private String[] getEnv(Map<String, String> env) { if (env == null || env.isEmpty()) { return null; } String[] retValue = new String[env.size()]; int i = 0; for (Map.Entry<String, String> entry : env.entrySet()) { retValue[i++] = entry.getKey() + "=" + entry.getValue(); } return retValue; } private String[] concatenateCmdArgs() { List<String> cmd = new ArrayList<String>(); cmd.add(command); cmd.addAll(args); return cmd.toArray(new String[cmd.size()]); } @Override public String toString() { return formatCommandLine(command, args); } static String formatCommandLine(String command, List<String> args) { return command + " " + argsString(args); } private static String argsString(List<String> args) { StringBuffer temp = new StringBuffer(); for (Iterator<String> stringIterator = args.iterator(); stringIterator.hasNext();) { String arg = stringIterator.next(); String escapedArg = naiveShellEscape(arg); temp.append(escapedArg); if (stringIterator.hasNext()) { temp.append(" "); } } return temp.toString(); } private static String naiveShellEscape(String arg) { Pattern p = Pattern.compile("\\s"); Matcher m = p.matcher(arg); String escapedArg; if (m.find()) { escapedArg = "'" + arg.replaceAll("'","'\"'\"'") + "'"; } else { escapedArg = arg; } return escapedArg; } public int getExitValue() { return exitValue; } public long getExecutionTime() { return executionTime; } }
Java
public class GenericValidator { /** * Boolean flag that indicates whether the dataset is valid. */ public boolean isValid = true; /** * Map of invalid Files (or Folders) that and the corresponding * List of Strings with all reasons/errors for being invalid. */ public Map<File, String> invalidFilesOrFolders = new HashMap<File, String>(); /** * Constructor */ public GenericValidator() { } }
Java
public class InfoPanel extends Composite implements InfoPanelDisplay { private InfoPanelDisplay IMPL = GWT.create(InfoPanelDisplay.class); private boolean iPreventDefault = false; public InfoPanel() { initWidget(IMPL.asWidget()); } @Override public String getText() { return IMPL.getText(); } @Override public void setText(String text) { IMPL.setText(text); } @Override public String getHint() { return IMPL.getHint(); } @Override public void setHint(String hint) { IMPL.setHint(hint); } @Override public void setUrl(String url) { IMPL.setUrl(url); } @Override public void setInfo(InfoInterface info) { IMPL.setInfo(info); } @Override public void setCallback(Callback callback) { IMPL.setCallback(callback); } @Override public boolean isPopupShowing() { return IMPL.isPopupShowing(); } @Override public void setClickHandler(ClickHandler handler) { IMPL.setClickHandler(handler); } @Override public String getAriaLabel() { return IMPL.getAriaLabel(); } @Override public void setAriaLabel(String text) { IMPL.setAriaLabel(text); } public boolean isPreventDefault() { return iPreventDefault; } public void setPreventDefault(boolean preventDefault) { iPreventDefault = preventDefault; } }
Java
@Generated("com.amazonaws:aws-java-sdk-code-generator") public class StudioComponent implements Serializable, Cloneable, StructuredPojo { /** * <p> * The ARN of the resource. * </p> */ private String arn; /** * <p> * The configuration of the studio component, based on component type. * </p> */ private StudioComponentConfiguration configuration; /** * <p> * The Unix epoch timestamp in seconds for when the resource was created. * </p> */ private java.util.Date createdAt; /** * <p> * The user ID of the user that created the studio component. * </p> */ private String createdBy; /** * <p> * A human-readable description for the studio component resource. * </p> */ private String description; /** * <p> * The EC2 security groups that control access to the studio component. * </p> */ private java.util.List<String> ec2SecurityGroupIds; /** * <p> * Initialization scripts for studio components. * </p> */ private java.util.List<StudioComponentInitializationScript> initializationScripts; /** * <p> * A friendly name for the studio component resource. * </p> */ private String name; /** * <p> * Parameters for the studio component scripts. * </p> */ private java.util.List<ScriptParameterKeyValue> scriptParameters; /** * <p> * The current state. * </p> */ private String state; /** * <p> * The status code. * </p> */ private String statusCode; /** * <p> * The status message for the studio component. * </p> */ private String statusMessage; /** * <p> * The unique identifier for a studio component resource. * </p> */ private String studioComponentId; /** * <p> * The specific subtype of a studio component. * </p> */ private String subtype; /** * <p> * A collection of labels, in the form of key:value pairs, that apply to this resource. * </p> */ private java.util.Map<String, String> tags; /** * <p> * The type of the studio component. * </p> */ private String type; /** * <p> * The Unix epoch timestamp in seconds for when the resource was updated. * </p> */ private java.util.Date updatedAt; /** * <p> * The user ID of the user that most recently updated the resource. * </p> */ private String updatedBy; /** * <p> * The ARN of the resource. * </p> * * @param arn * The ARN of the resource. */ public void setArn(String arn) { this.arn = arn; } /** * <p> * The ARN of the resource. * </p> * * @return The ARN of the resource. */ public String getArn() { return this.arn; } /** * <p> * The ARN of the resource. * </p> * * @param arn * The ARN of the resource. * @return Returns a reference to this object so that method calls can be chained together. */ public StudioComponent withArn(String arn) { setArn(arn); return this; } /** * <p> * The configuration of the studio component, based on component type. * </p> * * @param configuration * The configuration of the studio component, based on component type. */ public void setConfiguration(StudioComponentConfiguration configuration) { this.configuration = configuration; } /** * <p> * The configuration of the studio component, based on component type. * </p> * * @return The configuration of the studio component, based on component type. */ public StudioComponentConfiguration getConfiguration() { return this.configuration; } /** * <p> * The configuration of the studio component, based on component type. * </p> * * @param configuration * The configuration of the studio component, based on component type. * @return Returns a reference to this object so that method calls can be chained together. */ public StudioComponent withConfiguration(StudioComponentConfiguration configuration) { setConfiguration(configuration); return this; } /** * <p> * The Unix epoch timestamp in seconds for when the resource was created. * </p> * * @param createdAt * The Unix epoch timestamp in seconds for when the resource was created. */ public void setCreatedAt(java.util.Date createdAt) { this.createdAt = createdAt; } /** * <p> * The Unix epoch timestamp in seconds for when the resource was created. * </p> * * @return The Unix epoch timestamp in seconds for when the resource was created. */ public java.util.Date getCreatedAt() { return this.createdAt; } /** * <p> * The Unix epoch timestamp in seconds for when the resource was created. * </p> * * @param createdAt * The Unix epoch timestamp in seconds for when the resource was created. * @return Returns a reference to this object so that method calls can be chained together. */ public StudioComponent withCreatedAt(java.util.Date createdAt) { setCreatedAt(createdAt); return this; } /** * <p> * The user ID of the user that created the studio component. * </p> * * @param createdBy * The user ID of the user that created the studio component. */ public void setCreatedBy(String createdBy) { this.createdBy = createdBy; } /** * <p> * The user ID of the user that created the studio component. * </p> * * @return The user ID of the user that created the studio component. */ public String getCreatedBy() { return this.createdBy; } /** * <p> * The user ID of the user that created the studio component. * </p> * * @param createdBy * The user ID of the user that created the studio component. * @return Returns a reference to this object so that method calls can be chained together. */ public StudioComponent withCreatedBy(String createdBy) { setCreatedBy(createdBy); return this; } /** * <p> * A human-readable description for the studio component resource. * </p> * * @param description * A human-readable description for the studio component resource. */ public void setDescription(String description) { this.description = description; } /** * <p> * A human-readable description for the studio component resource. * </p> * * @return A human-readable description for the studio component resource. */ public String getDescription() { return this.description; } /** * <p> * A human-readable description for the studio component resource. * </p> * * @param description * A human-readable description for the studio component resource. * @return Returns a reference to this object so that method calls can be chained together. */ public StudioComponent withDescription(String description) { setDescription(description); return this; } /** * <p> * The EC2 security groups that control access to the studio component. * </p> * * @return The EC2 security groups that control access to the studio component. */ public java.util.List<String> getEc2SecurityGroupIds() { return ec2SecurityGroupIds; } /** * <p> * The EC2 security groups that control access to the studio component. * </p> * * @param ec2SecurityGroupIds * The EC2 security groups that control access to the studio component. */ public void setEc2SecurityGroupIds(java.util.Collection<String> ec2SecurityGroupIds) { if (ec2SecurityGroupIds == null) { this.ec2SecurityGroupIds = null; return; } this.ec2SecurityGroupIds = new java.util.ArrayList<String>(ec2SecurityGroupIds); } /** * <p> * The EC2 security groups that control access to the studio component. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setEc2SecurityGroupIds(java.util.Collection)} or {@link #withEc2SecurityGroupIds(java.util.Collection)} * if you want to override the existing values. * </p> * * @param ec2SecurityGroupIds * The EC2 security groups that control access to the studio component. * @return Returns a reference to this object so that method calls can be chained together. */ public StudioComponent withEc2SecurityGroupIds(String... ec2SecurityGroupIds) { if (this.ec2SecurityGroupIds == null) { setEc2SecurityGroupIds(new java.util.ArrayList<String>(ec2SecurityGroupIds.length)); } for (String ele : ec2SecurityGroupIds) { this.ec2SecurityGroupIds.add(ele); } return this; } /** * <p> * The EC2 security groups that control access to the studio component. * </p> * * @param ec2SecurityGroupIds * The EC2 security groups that control access to the studio component. * @return Returns a reference to this object so that method calls can be chained together. */ public StudioComponent withEc2SecurityGroupIds(java.util.Collection<String> ec2SecurityGroupIds) { setEc2SecurityGroupIds(ec2SecurityGroupIds); return this; } /** * <p> * Initialization scripts for studio components. * </p> * * @return Initialization scripts for studio components. */ public java.util.List<StudioComponentInitializationScript> getInitializationScripts() { return initializationScripts; } /** * <p> * Initialization scripts for studio components. * </p> * * @param initializationScripts * Initialization scripts for studio components. */ public void setInitializationScripts(java.util.Collection<StudioComponentInitializationScript> initializationScripts) { if (initializationScripts == null) { this.initializationScripts = null; return; } this.initializationScripts = new java.util.ArrayList<StudioComponentInitializationScript>(initializationScripts); } /** * <p> * Initialization scripts for studio components. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setInitializationScripts(java.util.Collection)} or * {@link #withInitializationScripts(java.util.Collection)} if you want to override the existing values. * </p> * * @param initializationScripts * Initialization scripts for studio components. * @return Returns a reference to this object so that method calls can be chained together. */ public StudioComponent withInitializationScripts(StudioComponentInitializationScript... initializationScripts) { if (this.initializationScripts == null) { setInitializationScripts(new java.util.ArrayList<StudioComponentInitializationScript>(initializationScripts.length)); } for (StudioComponentInitializationScript ele : initializationScripts) { this.initializationScripts.add(ele); } return this; } /** * <p> * Initialization scripts for studio components. * </p> * * @param initializationScripts * Initialization scripts for studio components. * @return Returns a reference to this object so that method calls can be chained together. */ public StudioComponent withInitializationScripts(java.util.Collection<StudioComponentInitializationScript> initializationScripts) { setInitializationScripts(initializationScripts); return this; } /** * <p> * A friendly name for the studio component resource. * </p> * * @param name * A friendly name for the studio component resource. */ public void setName(String name) { this.name = name; } /** * <p> * A friendly name for the studio component resource. * </p> * * @return A friendly name for the studio component resource. */ public String getName() { return this.name; } /** * <p> * A friendly name for the studio component resource. * </p> * * @param name * A friendly name for the studio component resource. * @return Returns a reference to this object so that method calls can be chained together. */ public StudioComponent withName(String name) { setName(name); return this; } /** * <p> * Parameters for the studio component scripts. * </p> * * @return Parameters for the studio component scripts. */ public java.util.List<ScriptParameterKeyValue> getScriptParameters() { return scriptParameters; } /** * <p> * Parameters for the studio component scripts. * </p> * * @param scriptParameters * Parameters for the studio component scripts. */ public void setScriptParameters(java.util.Collection<ScriptParameterKeyValue> scriptParameters) { if (scriptParameters == null) { this.scriptParameters = null; return; } this.scriptParameters = new java.util.ArrayList<ScriptParameterKeyValue>(scriptParameters); } /** * <p> * Parameters for the studio component scripts. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setScriptParameters(java.util.Collection)} or {@link #withScriptParameters(java.util.Collection)} if you * want to override the existing values. * </p> * * @param scriptParameters * Parameters for the studio component scripts. * @return Returns a reference to this object so that method calls can be chained together. */ public StudioComponent withScriptParameters(ScriptParameterKeyValue... scriptParameters) { if (this.scriptParameters == null) { setScriptParameters(new java.util.ArrayList<ScriptParameterKeyValue>(scriptParameters.length)); } for (ScriptParameterKeyValue ele : scriptParameters) { this.scriptParameters.add(ele); } return this; } /** * <p> * Parameters for the studio component scripts. * </p> * * @param scriptParameters * Parameters for the studio component scripts. * @return Returns a reference to this object so that method calls can be chained together. */ public StudioComponent withScriptParameters(java.util.Collection<ScriptParameterKeyValue> scriptParameters) { setScriptParameters(scriptParameters); return this; } /** * <p> * The current state. * </p> * * @param state * The current state. * @see StudioComponentState */ public void setState(String state) { this.state = state; } /** * <p> * The current state. * </p> * * @return The current state. * @see StudioComponentState */ public String getState() { return this.state; } /** * <p> * The current state. * </p> * * @param state * The current state. * @return Returns a reference to this object so that method calls can be chained together. * @see StudioComponentState */ public StudioComponent withState(String state) { setState(state); return this; } /** * <p> * The current state. * </p> * * @param state * The current state. * @return Returns a reference to this object so that method calls can be chained together. * @see StudioComponentState */ public StudioComponent withState(StudioComponentState state) { this.state = state.toString(); return this; } /** * <p> * The status code. * </p> * * @param statusCode * The status code. * @see StudioComponentStatusCode */ public void setStatusCode(String statusCode) { this.statusCode = statusCode; } /** * <p> * The status code. * </p> * * @return The status code. * @see StudioComponentStatusCode */ public String getStatusCode() { return this.statusCode; } /** * <p> * The status code. * </p> * * @param statusCode * The status code. * @return Returns a reference to this object so that method calls can be chained together. * @see StudioComponentStatusCode */ public StudioComponent withStatusCode(String statusCode) { setStatusCode(statusCode); return this; } /** * <p> * The status code. * </p> * * @param statusCode * The status code. * @return Returns a reference to this object so that method calls can be chained together. * @see StudioComponentStatusCode */ public StudioComponent withStatusCode(StudioComponentStatusCode statusCode) { this.statusCode = statusCode.toString(); return this; } /** * <p> * The status message for the studio component. * </p> * * @param statusMessage * The status message for the studio component. */ public void setStatusMessage(String statusMessage) { this.statusMessage = statusMessage; } /** * <p> * The status message for the studio component. * </p> * * @return The status message for the studio component. */ public String getStatusMessage() { return this.statusMessage; } /** * <p> * The status message for the studio component. * </p> * * @param statusMessage * The status message for the studio component. * @return Returns a reference to this object so that method calls can be chained together. */ public StudioComponent withStatusMessage(String statusMessage) { setStatusMessage(statusMessage); return this; } /** * <p> * The unique identifier for a studio component resource. * </p> * * @param studioComponentId * The unique identifier for a studio component resource. */ public void setStudioComponentId(String studioComponentId) { this.studioComponentId = studioComponentId; } /** * <p> * The unique identifier for a studio component resource. * </p> * * @return The unique identifier for a studio component resource. */ public String getStudioComponentId() { return this.studioComponentId; } /** * <p> * The unique identifier for a studio component resource. * </p> * * @param studioComponentId * The unique identifier for a studio component resource. * @return Returns a reference to this object so that method calls can be chained together. */ public StudioComponent withStudioComponentId(String studioComponentId) { setStudioComponentId(studioComponentId); return this; } /** * <p> * The specific subtype of a studio component. * </p> * * @param subtype * The specific subtype of a studio component. * @see StudioComponentSubtype */ public void setSubtype(String subtype) { this.subtype = subtype; } /** * <p> * The specific subtype of a studio component. * </p> * * @return The specific subtype of a studio component. * @see StudioComponentSubtype */ public String getSubtype() { return this.subtype; } /** * <p> * The specific subtype of a studio component. * </p> * * @param subtype * The specific subtype of a studio component. * @return Returns a reference to this object so that method calls can be chained together. * @see StudioComponentSubtype */ public StudioComponent withSubtype(String subtype) { setSubtype(subtype); return this; } /** * <p> * The specific subtype of a studio component. * </p> * * @param subtype * The specific subtype of a studio component. * @return Returns a reference to this object so that method calls can be chained together. * @see StudioComponentSubtype */ public StudioComponent withSubtype(StudioComponentSubtype subtype) { this.subtype = subtype.toString(); return this; } /** * <p> * A collection of labels, in the form of key:value pairs, that apply to this resource. * </p> * * @return A collection of labels, in the form of key:value pairs, that apply to this resource. */ public java.util.Map<String, String> getTags() { return tags; } /** * <p> * A collection of labels, in the form of key:value pairs, that apply to this resource. * </p> * * @param tags * A collection of labels, in the form of key:value pairs, that apply to this resource. */ public void setTags(java.util.Map<String, String> tags) { this.tags = tags; } /** * <p> * A collection of labels, in the form of key:value pairs, that apply to this resource. * </p> * * @param tags * A collection of labels, in the form of key:value pairs, that apply to this resource. * @return Returns a reference to this object so that method calls can be chained together. */ public StudioComponent withTags(java.util.Map<String, String> tags) { setTags(tags); return this; } /** * Add a single Tags entry * * @see StudioComponent#withTags * @returns a reference to this object so that method calls can be chained together. */ public StudioComponent addTagsEntry(String key, String value) { if (null == this.tags) { this.tags = new java.util.HashMap<String, String>(); } if (this.tags.containsKey(key)) throw new IllegalArgumentException("Duplicated keys (" + key.toString() + ") are provided."); this.tags.put(key, value); return this; } /** * Removes all the entries added into Tags. * * @return Returns a reference to this object so that method calls can be chained together. */ public StudioComponent clearTagsEntries() { this.tags = null; return this; } /** * <p> * The type of the studio component. * </p> * * @param type * The type of the studio component. * @see StudioComponentType */ public void setType(String type) { this.type = type; } /** * <p> * The type of the studio component. * </p> * * @return The type of the studio component. * @see StudioComponentType */ public String getType() { return this.type; } /** * <p> * The type of the studio component. * </p> * * @param type * The type of the studio component. * @return Returns a reference to this object so that method calls can be chained together. * @see StudioComponentType */ public StudioComponent withType(String type) { setType(type); return this; } /** * <p> * The type of the studio component. * </p> * * @param type * The type of the studio component. * @return Returns a reference to this object so that method calls can be chained together. * @see StudioComponentType */ public StudioComponent withType(StudioComponentType type) { this.type = type.toString(); return this; } /** * <p> * The Unix epoch timestamp in seconds for when the resource was updated. * </p> * * @param updatedAt * The Unix epoch timestamp in seconds for when the resource was updated. */ public void setUpdatedAt(java.util.Date updatedAt) { this.updatedAt = updatedAt; } /** * <p> * The Unix epoch timestamp in seconds for when the resource was updated. * </p> * * @return The Unix epoch timestamp in seconds for when the resource was updated. */ public java.util.Date getUpdatedAt() { return this.updatedAt; } /** * <p> * The Unix epoch timestamp in seconds for when the resource was updated. * </p> * * @param updatedAt * The Unix epoch timestamp in seconds for when the resource was updated. * @return Returns a reference to this object so that method calls can be chained together. */ public StudioComponent withUpdatedAt(java.util.Date updatedAt) { setUpdatedAt(updatedAt); return this; } /** * <p> * The user ID of the user that most recently updated the resource. * </p> * * @param updatedBy * The user ID of the user that most recently updated the resource. */ public void setUpdatedBy(String updatedBy) { this.updatedBy = updatedBy; } /** * <p> * The user ID of the user that most recently updated the resource. * </p> * * @return The user ID of the user that most recently updated the resource. */ public String getUpdatedBy() { return this.updatedBy; } /** * <p> * The user ID of the user that most recently updated the resource. * </p> * * @param updatedBy * The user ID of the user that most recently updated the resource. * @return Returns a reference to this object so that method calls can be chained together. */ public StudioComponent withUpdatedBy(String updatedBy) { setUpdatedBy(updatedBy); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getArn() != null) sb.append("Arn: ").append(getArn()).append(","); if (getConfiguration() != null) sb.append("Configuration: ").append(getConfiguration()).append(","); if (getCreatedAt() != null) sb.append("CreatedAt: ").append(getCreatedAt()).append(","); if (getCreatedBy() != null) sb.append("CreatedBy: ").append(getCreatedBy()).append(","); if (getDescription() != null) sb.append("Description: ").append("***Sensitive Data Redacted***").append(","); if (getEc2SecurityGroupIds() != null) sb.append("Ec2SecurityGroupIds: ").append(getEc2SecurityGroupIds()).append(","); if (getInitializationScripts() != null) sb.append("InitializationScripts: ").append(getInitializationScripts()).append(","); if (getName() != null) sb.append("Name: ").append("***Sensitive Data Redacted***").append(","); if (getScriptParameters() != null) sb.append("ScriptParameters: ").append("***Sensitive Data Redacted***").append(","); if (getState() != null) sb.append("State: ").append(getState()).append(","); if (getStatusCode() != null) sb.append("StatusCode: ").append(getStatusCode()).append(","); if (getStatusMessage() != null) sb.append("StatusMessage: ").append(getStatusMessage()).append(","); if (getStudioComponentId() != null) sb.append("StudioComponentId: ").append(getStudioComponentId()).append(","); if (getSubtype() != null) sb.append("Subtype: ").append(getSubtype()).append(","); if (getTags() != null) sb.append("Tags: ").append(getTags()).append(","); if (getType() != null) sb.append("Type: ").append(getType()).append(","); if (getUpdatedAt() != null) sb.append("UpdatedAt: ").append(getUpdatedAt()).append(","); if (getUpdatedBy() != null) sb.append("UpdatedBy: ").append(getUpdatedBy()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof StudioComponent == false) return false; StudioComponent other = (StudioComponent) obj; if (other.getArn() == null ^ this.getArn() == null) return false; if (other.getArn() != null && other.getArn().equals(this.getArn()) == false) return false; if (other.getConfiguration() == null ^ this.getConfiguration() == null) return false; if (other.getConfiguration() != null && other.getConfiguration().equals(this.getConfiguration()) == false) return false; if (other.getCreatedAt() == null ^ this.getCreatedAt() == null) return false; if (other.getCreatedAt() != null && other.getCreatedAt().equals(this.getCreatedAt()) == false) return false; if (other.getCreatedBy() == null ^ this.getCreatedBy() == null) return false; if (other.getCreatedBy() != null && other.getCreatedBy().equals(this.getCreatedBy()) == false) return false; if (other.getDescription() == null ^ this.getDescription() == null) return false; if (other.getDescription() != null && other.getDescription().equals(this.getDescription()) == false) return false; if (other.getEc2SecurityGroupIds() == null ^ this.getEc2SecurityGroupIds() == null) return false; if (other.getEc2SecurityGroupIds() != null && other.getEc2SecurityGroupIds().equals(this.getEc2SecurityGroupIds()) == false) return false; if (other.getInitializationScripts() == null ^ this.getInitializationScripts() == null) return false; if (other.getInitializationScripts() != null && other.getInitializationScripts().equals(this.getInitializationScripts()) == false) return false; if (other.getName() == null ^ this.getName() == null) return false; if (other.getName() != null && other.getName().equals(this.getName()) == false) return false; if (other.getScriptParameters() == null ^ this.getScriptParameters() == null) return false; if (other.getScriptParameters() != null && other.getScriptParameters().equals(this.getScriptParameters()) == false) return false; if (other.getState() == null ^ this.getState() == null) return false; if (other.getState() != null && other.getState().equals(this.getState()) == false) return false; if (other.getStatusCode() == null ^ this.getStatusCode() == null) return false; if (other.getStatusCode() != null && other.getStatusCode().equals(this.getStatusCode()) == false) return false; if (other.getStatusMessage() == null ^ this.getStatusMessage() == null) return false; if (other.getStatusMessage() != null && other.getStatusMessage().equals(this.getStatusMessage()) == false) return false; if (other.getStudioComponentId() == null ^ this.getStudioComponentId() == null) return false; if (other.getStudioComponentId() != null && other.getStudioComponentId().equals(this.getStudioComponentId()) == false) return false; if (other.getSubtype() == null ^ this.getSubtype() == null) return false; if (other.getSubtype() != null && other.getSubtype().equals(this.getSubtype()) == false) return false; if (other.getTags() == null ^ this.getTags() == null) return false; if (other.getTags() != null && other.getTags().equals(this.getTags()) == false) return false; if (other.getType() == null ^ this.getType() == null) return false; if (other.getType() != null && other.getType().equals(this.getType()) == false) return false; if (other.getUpdatedAt() == null ^ this.getUpdatedAt() == null) return false; if (other.getUpdatedAt() != null && other.getUpdatedAt().equals(this.getUpdatedAt()) == false) return false; if (other.getUpdatedBy() == null ^ this.getUpdatedBy() == null) return false; if (other.getUpdatedBy() != null && other.getUpdatedBy().equals(this.getUpdatedBy()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getArn() == null) ? 0 : getArn().hashCode()); hashCode = prime * hashCode + ((getConfiguration() == null) ? 0 : getConfiguration().hashCode()); hashCode = prime * hashCode + ((getCreatedAt() == null) ? 0 : getCreatedAt().hashCode()); hashCode = prime * hashCode + ((getCreatedBy() == null) ? 0 : getCreatedBy().hashCode()); hashCode = prime * hashCode + ((getDescription() == null) ? 0 : getDescription().hashCode()); hashCode = prime * hashCode + ((getEc2SecurityGroupIds() == null) ? 0 : getEc2SecurityGroupIds().hashCode()); hashCode = prime * hashCode + ((getInitializationScripts() == null) ? 0 : getInitializationScripts().hashCode()); hashCode = prime * hashCode + ((getName() == null) ? 0 : getName().hashCode()); hashCode = prime * hashCode + ((getScriptParameters() == null) ? 0 : getScriptParameters().hashCode()); hashCode = prime * hashCode + ((getState() == null) ? 0 : getState().hashCode()); hashCode = prime * hashCode + ((getStatusCode() == null) ? 0 : getStatusCode().hashCode()); hashCode = prime * hashCode + ((getStatusMessage() == null) ? 0 : getStatusMessage().hashCode()); hashCode = prime * hashCode + ((getStudioComponentId() == null) ? 0 : getStudioComponentId().hashCode()); hashCode = prime * hashCode + ((getSubtype() == null) ? 0 : getSubtype().hashCode()); hashCode = prime * hashCode + ((getTags() == null) ? 0 : getTags().hashCode()); hashCode = prime * hashCode + ((getType() == null) ? 0 : getType().hashCode()); hashCode = prime * hashCode + ((getUpdatedAt() == null) ? 0 : getUpdatedAt().hashCode()); hashCode = prime * hashCode + ((getUpdatedBy() == null) ? 0 : getUpdatedBy().hashCode()); return hashCode; } @Override public StudioComponent clone() { try { return (StudioComponent) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } @com.amazonaws.annotation.SdkInternalApi @Override public void marshall(ProtocolMarshaller protocolMarshaller) { com.amazonaws.services.nimblestudio.model.transform.StudioComponentMarshaller.getInstance().marshall(this, protocolMarshaller); } }
Java
public class RawAtlasSlicerTest { private static final CountryBoundaryMap boundary; private static final RelationOrAreaToMultiPolygonConverter converter; private static final JtsMultiPolygonToMultiPolygonConverter jtsConverter; static { boundary = CountryBoundaryMap .fromPlainText(new InputStreamResource(() -> RawAtlasSlicerTest.class .getResourceAsStream("CIV_GIN_LBR_osm_boundaries.txt.gz")) .withDecompressor(Decompressor.GZIP)); converter = new RelationOrAreaToMultiPolygonConverter(); jtsConverter = new JtsMultiPolygonToMultiPolygonConverter(); } @Rule public final RawAtlasSlicerTestRule setup = new RawAtlasSlicerTestRule(); /** * This test examines a number of important behaviors. For a closed edge, it's important that * slicing logic recognizes that it should be sliced linearly, as slicing polygonally would * destroy its ability to be converted to an Edge. Additionally, this test checks that the * line's points are preserved despite no specific tagging, and that synthetic boundary nodes * are present and match the slice location for both sliced lines. */ @Test public void testClosedEdgeSpanningTwoCountries() { final Atlas rawAtlas = this.setup.getClosedEdgeSpanningTwoCountriesAtlas(); final Atlas civSlicedAtlas = new RawAtlasSlicer( AtlasLoadingOption.createOptionWithAllEnabled(boundary).setCountryCode("CIV"), rawAtlas).slice(); final Atlas lbrSlicedAtlas = new RawAtlasSlicer( AtlasLoadingOption.createOptionWithAllEnabled(boundary).setCountryCode("LBR"), rawAtlas).slice(); final Line rawLine = rawAtlas.line(1); Assert.assertEquals(1, civSlicedAtlas.numberOfLines()); Assert.assertEquals(1, lbrSlicedAtlas.numberOfLines()); final CountrySlicingIdentifierFactory lineIdentifierFactory = new CountrySlicingIdentifierFactory( rawLine.getIdentifier()); final Line civLine = civSlicedAtlas.line(lineIdentifierFactory.nextIdentifier()); Assert.assertFalse(civLine.isClosed()); final Optional<String> civLineTag = civLine.getTag(ISOCountryTag.KEY); Assert.assertTrue(civLineTag.isPresent()); Assert.assertEquals("CIV", civLineTag.get()); Assert.assertEquals(rawLine.getOsmTags(), civLine.getOsmTags()); final Optional<String> civLineSlicedGeometryTag = civLine .getTag(SyntheticGeometrySlicedTag.KEY); Assert.assertTrue(civLineSlicedGeometryTag.isPresent()); Assert.assertEquals(SyntheticGeometrySlicedTag.YES.toString(), civLineSlicedGeometryTag.get()); final Line lbrLine = lbrSlicedAtlas.line(lineIdentifierFactory.nextIdentifier()); Assert.assertFalse(lbrLine.isClosed()); final Optional<String> lbrLineTag = lbrLine.getTag(ISOCountryTag.KEY); Assert.assertTrue(lbrLineTag.isPresent()); Assert.assertEquals("LBR", lbrLineTag.get()); Assert.assertEquals(rawLine.getOsmTags(), lbrLine.getOsmTags()); final Optional<String> lbrLineSlicedGeometryTag = lbrLine .getTag(SyntheticGeometrySlicedTag.KEY); Assert.assertTrue(lbrLineSlicedGeometryTag.isPresent()); Assert.assertEquals(SyntheticGeometrySlicedTag.YES.toString(), lbrLineSlicedGeometryTag.get()); // Check Point correctness Assert.assertEquals(4, civSlicedAtlas.numberOfPoints()); Assert.assertEquals(4, lbrSlicedAtlas.numberOfPoints()); for (final Point point : civSlicedAtlas.points()) { Assert.assertTrue(point.getTag(ISOCountryTag.KEY).isPresent()); if (point.getIdentifier() == 1 || point.getIdentifier() == 2) { Assert.assertEquals(rawAtlas.point(point.getIdentifier()).getOsmTags(), point.getOsmTags()); Assert.assertEquals("CIV", point.getTag(ISOCountryTag.KEY).get()); Assert.assertFalse(point.getTag(SyntheticBoundaryNodeTag.KEY).isPresent()); } else { Assert.assertEquals("CIV,LBR", point.getTag(ISOCountryTag.KEY).get()); Assert.assertTrue(point.getOsmTags().isEmpty()); Assert.assertTrue(point.getTag(SyntheticBoundaryNodeTag.KEY).isPresent()); Assert.assertEquals(SyntheticBoundaryNodeTag.YES.toString(), point.getTag(SyntheticBoundaryNodeTag.KEY).get()); civSlicedAtlas.linesContaining(point.getLocation()).forEach(lineContaining -> { Assert.assertTrue(lineContaining.asPolyLine().last().equals(point.getLocation()) || lineContaining.asPolyLine().first().equals(point.getLocation())); }); // boundary nodes should be in both Atlases! final Point lbrBoundaryNode = lbrSlicedAtlas.point(point.getIdentifier()); Assert.assertEquals(point.getLocation(), lbrBoundaryNode.getLocation()); Assert.assertEquals(point.getTags(), lbrBoundaryNode.getTags()); } } for (final Point point : lbrSlicedAtlas.points()) { Assert.assertTrue(point.getTag(ISOCountryTag.KEY).isPresent()); if (point.getIdentifier() == 3 || point.getIdentifier() == 4) { Assert.assertEquals(rawAtlas.point(point.getIdentifier()).getOsmTags(), point.getOsmTags()); Assert.assertEquals("LBR", point.getTag(ISOCountryTag.KEY).get()); Assert.assertFalse(point.getTag(SyntheticBoundaryNodeTag.KEY).isPresent()); } else { Assert.assertEquals("CIV,LBR", point.getTag(ISOCountryTag.KEY).get()); Assert.assertTrue(point.getOsmTags().isEmpty()); Assert.assertTrue(point.getTag(SyntheticBoundaryNodeTag.KEY).isPresent()); Assert.assertEquals(SyntheticBoundaryNodeTag.YES.toString(), point.getTag(SyntheticBoundaryNodeTag.KEY).get()); civSlicedAtlas.linesContaining(point.getLocation()).forEach(lineContaining -> { Assert.assertTrue(lineContaining.asPolyLine().last().equals(point.getLocation()) || lineContaining.asPolyLine().first().equals(point.getLocation())); }); // boundary nodes should be in both Atlases! final Point civBoundaryNode = civSlicedAtlas.point(point.getIdentifier()); Assert.assertEquals(point.getLocation(), civBoundaryNode.getLocation()); Assert.assertEquals(point.getTags(), civBoundaryNode.getTags()); } } } /** * This is a pretty straightforward case-- just looking to confirm the geometry isn't altered, * the country tag is updated, and the tagless points are removed */ @Test public void testClosedLineInsideSingleCountry() { final Atlas rawAtlas = this.setup.getClosedLineFullyInOneCountryAtlas(); final Atlas slicedAtlas = new RawAtlasSlicer( AtlasLoadingOption.createOptionWithAllEnabled(boundary).setCountryCode("GIN"), rawAtlas).slice(); Assert.assertEquals(1, slicedAtlas.numberOfLines()); Assert.assertTrue(slicedAtlas.line(1).isClosed()); Assert.assertEquals(rawAtlas.line(1).asPolyLine(), slicedAtlas.line(1).asPolyLine()); Assert.assertEquals("GIN", slicedAtlas.line(1).getTag(ISOCountryTag.KEY).get()); Assert.assertTrue(slicedAtlas.line(1).getTag(SyntheticGeometrySlicedTag.KEY).isEmpty()); Assert.assertEquals(0, slicedAtlas.numberOfPoints()); } /** * This is the same geometry as the line in testClosedEdgeSpanningTwoCountries(), but the * tagging here no longer qualifies it as an Edge. The result should be different, accordingly, * as the closed line will now be sliced as a polygon and tagless points will be removed. */ @Test public void testClosedLineSpanningTwoCountries() { final Atlas rawAtlas = this.setup.getClosedLineSpanningTwoCountriesAtlas(); final Atlas civSlicedAtlas = new RawAtlasSlicer( AtlasLoadingOption.createOptionWithAllEnabled(boundary).setCountryCode("CIV"), rawAtlas).slice(); final Atlas lbrSlicedAtlas = new RawAtlasSlicer( AtlasLoadingOption.createOptionWithAllEnabled(boundary).setCountryCode("LBR"), rawAtlas).slice(); Assert.assertEquals(1, civSlicedAtlas.numberOfAreas()); Assert.assertEquals(1, lbrSlicedAtlas.numberOfAreas()); final Area rawArea = rawAtlas.area(1); final CountrySlicingIdentifierFactory lineIdentifierFactory = new CountrySlicingIdentifierFactory( rawArea.getIdentifier()); final Area civSlicedArea = civSlicedAtlas.area(lineIdentifierFactory.nextIdentifier()); Assert.assertEquals("CIV", civSlicedArea.getTag(ISOCountryTag.KEY).get()); Assert.assertEquals(SyntheticGeometrySlicedTag.YES.toString(), civSlicedArea.getTag(SyntheticGeometrySlicedTag.KEY).get()); Assert.assertEquals(rawArea.getOsmTags(), civSlicedArea.getOsmTags()); Assert.assertFalse(civSlicedArea.asPolygon().isClockwise()); final Area lbrSlicedArea = lbrSlicedAtlas.area(lineIdentifierFactory.nextIdentifier()); Assert.assertEquals("LBR", lbrSlicedArea.getTag(ISOCountryTag.KEY).get()); Assert.assertEquals(SyntheticGeometrySlicedTag.YES.toString(), lbrSlicedArea.getTag(SyntheticGeometrySlicedTag.KEY).get()); Assert.assertEquals(rawArea.getOsmTags(), lbrSlicedArea.getOsmTags()); Assert.assertFalse(lbrSlicedArea.asPolygon().isClockwise()); Assert.assertEquals(0, civSlicedAtlas.numberOfPoints()); Assert.assertEquals(0, lbrSlicedAtlas.numberOfPoints()); } /** * Test examining the creation of synthetic boundary nodes for existing points. Should slice * line into two pieces, one for CIV and one for LBR. All points should be preserved, and point * 2 should be tagged as a SyntheticBoundaryNode.EXISTING as well as be the first location of * the CIV sliced line and the last location of the LBR sliced line. */ @Test public void testCreatingExistingSyntheticBoundaryNode() { final Atlas rawAtlas = this.setup.getRoadAcrossTwoCountriesWithPointOnBorderAtlas(); final Atlas civSlicedAtlas = new RawAtlasSlicer( AtlasLoadingOption.createOptionWithAllEnabled(boundary).setCountryCode("CIV"), rawAtlas).slice(); final Atlas lbrSlicedAtlas = new RawAtlasSlicer( AtlasLoadingOption.createOptionWithAllEnabled(boundary).setCountryCode("LBR"), rawAtlas).slice(); Assert.assertEquals(1, civSlicedAtlas.numberOfLines()); Assert.assertEquals(1, lbrSlicedAtlas.numberOfLines()); final Line rawLine = rawAtlas.line(1); final CountrySlicingIdentifierFactory lineIdentifierFactory = new CountrySlicingIdentifierFactory( rawLine.getIdentifier()); final Line civLine = civSlicedAtlas.line(lineIdentifierFactory.nextIdentifier()); Assert.assertEquals("CIV", civLine.getTag(ISOCountryTag.KEY).get()); Assert.assertEquals(SyntheticGeometrySlicedTag.YES.toString(), civLine.getTag(SyntheticGeometrySlicedTag.KEY).get()); Assert.assertEquals(rawLine.getOsmTags(), civLine.getOsmTags()); final Line lbrLine = lbrSlicedAtlas.line(lineIdentifierFactory.nextIdentifier()); Assert.assertEquals("LBR", lbrLine.getTag(ISOCountryTag.KEY).get()); Assert.assertEquals(SyntheticGeometrySlicedTag.YES.toString(), lbrLine.getTag(SyntheticGeometrySlicedTag.KEY).get()); Assert.assertEquals(rawLine.getOsmTags(), lbrLine.getOsmTags()); Assert.assertEquals(2, civSlicedAtlas.numberOfPoints()); Assert.assertEquals(2, lbrSlicedAtlas.numberOfPoints()); Assert.assertEquals("CIV", civSlicedAtlas.point(3).getTag(ISOCountryTag.KEY).get()); Assert.assertEquals("LBR", lbrSlicedAtlas.point(1).getTag(ISOCountryTag.KEY).get()); Assert.assertEquals(SyntheticBoundaryNodeTag.EXISTING.toString(), civSlicedAtlas.point(2).getTag(SyntheticBoundaryNodeTag.KEY).get()); Assert.assertEquals(SyntheticBoundaryNodeTag.EXISTING.toString(), lbrSlicedAtlas.point(2).getTag(SyntheticBoundaryNodeTag.KEY).get()); Assert.assertEquals("CIV,LBR", civSlicedAtlas.point(2).getTag(ISOCountryTag.KEY).get()); Assert.assertEquals("CIV,LBR", lbrSlicedAtlas.point(2).getTag(ISOCountryTag.KEY).get()); Assert.assertEquals(civSlicedAtlas.point(2).getLocation(), civLine.asPolyLine().first()); Assert.assertEquals(lbrSlicedAtlas.point(2).getLocation(), lbrLine.asPolyLine().last()); } /** * This line is a highway entirely inside a country and should only be updated with an * ISOCountryTag. Points should be preserved since it will be an Edge */ @Test public void testEdgeFullyInsideOneCountry() { final Atlas rawAtlas = this.setup.getRoadFullyInOneCountryAtlas(); final Atlas slicedAtlas = new RawAtlasSlicer( AtlasLoadingOption.createOptionWithAllEnabled(boundary).setCountryCode("CIV"), rawAtlas).slice(); Assert.assertEquals(rawAtlas.numberOfLines(), slicedAtlas.numberOfLines()); Assert.assertEquals("CIV", slicedAtlas.line(1).getTag(ISOCountryTag.KEY).get()); Assert.assertTrue(slicedAtlas.line(1).getTag(SyntheticGeometrySlicedTag.KEY).isEmpty()); Assert.assertEquals(rawAtlas.line(1).getOsmTags(), slicedAtlas.line(1).getOsmTags()); // Check Point correctness Assert.assertEquals(rawAtlas.numberOfPoints(), slicedAtlas.numberOfPoints()); slicedAtlas.points().forEach(point -> { Assert.assertEquals("CIV", point.getTag(ISOCountryTag.KEY).get()); Assert.assertFalse(point.getTag(SyntheticBoundaryNodeTag.KEY).isPresent()); Assert.assertEquals(rawAtlas.point(point.getIdentifier()).getOsmTags(), point.getOsmTags()); }); } /** * This line is an Edge candidate that goes across the boundary multiple times. Expect geometry * to be sliced and new synthetic nodes to be made. */ @Test public void testEdgeWeavingAcrossBoundary() { final Atlas rawAtlas = this.setup.getRoadWeavingAlongBoundaryAtlas(); final Atlas civSlicedAtlas = new RawAtlasSlicer( AtlasLoadingOption.createOptionWithAllEnabled(boundary).setCountryCode("CIV"), rawAtlas).slice(); final Atlas lbrSlicedAtlas = new RawAtlasSlicer( AtlasLoadingOption.createOptionWithAllEnabled(boundary).setCountryCode("LBR"), rawAtlas).slice(); Assert.assertEquals(2, civSlicedAtlas.numberOfLines()); Assert.assertEquals(2, lbrSlicedAtlas.numberOfLines()); final CountrySlicingIdentifierFactory lineIdentifierFactory = new CountrySlicingIdentifierFactory( 1); final Line firstCreatedLine = civSlicedAtlas.line(lineIdentifierFactory.nextIdentifier()); Assert.assertNotNull("Check new way addition", firstCreatedLine); Assert.assertEquals("Expect the first segment to be on the Ivory Coast side", "CIV", firstCreatedLine.getTag(ISOCountryTag.KEY).get()); final Line secondCreatedLine = civSlicedAtlas.line(lineIdentifierFactory.nextIdentifier()); Assert.assertNotNull("Check new way addition", secondCreatedLine); Assert.assertEquals("Expect the second segment to be on the Ivory Coast side", "CIV", secondCreatedLine.getTag(ISOCountryTag.KEY).get()); final Line thirdCreatedLine = lbrSlicedAtlas.line(lineIdentifierFactory.nextIdentifier()); Assert.assertNotNull("Check new way addition", thirdCreatedLine); Assert.assertEquals("Expect the third segment to be on the Liberia side", "LBR", thirdCreatedLine.getTag(ISOCountryTag.KEY).get()); final Line fourthCreatedLine = lbrSlicedAtlas.line(lineIdentifierFactory.nextIdentifier()); Assert.assertNotNull("Check new way addition", fourthCreatedLine); Assert.assertEquals("Expect the fourth segment to be on the Liberia side", "LBR", fourthCreatedLine.getTag(ISOCountryTag.KEY).get()); Assert.assertEquals(6, civSlicedAtlas.numberOfPoints()); Assert.assertEquals(5, lbrSlicedAtlas.numberOfPoints()); for (final Point point : civSlicedAtlas.points()) { if (rawAtlas.point(point.getIdentifier()) != null) { Assert.assertEquals(rawAtlas.point(point.getIdentifier()).getOsmTags(), point.getOsmTags()); Assert.assertEquals("CIV", point.getTag(ISOCountryTag.KEY).get()); } else { Assert.assertEquals("CIV,LBR", point.getTag(ISOCountryTag.KEY).get()); Assert.assertEquals(SyntheticBoundaryNodeTag.YES.toString(), point.getTag(SyntheticBoundaryNodeTag.KEY).get()); Assert.assertNotNull(lbrSlicedAtlas.point(point.getIdentifier())); civSlicedAtlas.linesContaining(point.getLocation()).forEach(lineContaining -> { Assert.assertTrue(lineContaining.asPolyLine().first() .equals(point.getLocation()) || lineContaining.asPolyLine().last().equals(point.getLocation())); }); } } for (final Point point : lbrSlicedAtlas.points()) { if (rawAtlas.point(point.getIdentifier()) != null) { Assert.assertEquals(rawAtlas.point(point.getIdentifier()).getOsmTags(), point.getOsmTags()); Assert.assertEquals("LBR", point.getTag(ISOCountryTag.KEY).get()); } else { Assert.assertEquals("CIV,LBR", point.getTag(ISOCountryTag.KEY).get()); Assert.assertEquals(SyntheticBoundaryNodeTag.YES.toString(), point.getTag(SyntheticBoundaryNodeTag.KEY).get()); Assert.assertNotNull(civSlicedAtlas.point(point.getIdentifier())); civSlicedAtlas.linesContaining(point.getLocation()).forEach(lineContaining -> { Assert.assertTrue(lineContaining.asPolyLine().first() .equals(point.getLocation()) || lineContaining.asPolyLine().last().equals(point.getLocation())); }); } } } /** * This tests a relation with two closed lines in LBR that overlap, forming an invalid * multipolygon. Expect only country code assignment, all points removed (since they have no * tags), no geometry slicing, and no relation slicing */ @Test public void testInnerIntersectingOuterRelation() { final Atlas rawAtlas = this.setup.getIntersectingInnerAndOuterMembersAtlas(); final Atlas slicedAtlas = new RawAtlasSlicer( AtlasLoadingOption.createOptionWithAllEnabled(boundary).setCountryCode("LBR"), rawAtlas).slice(); Assert.assertEquals(0, slicedAtlas.numberOfPoints()); Assert.assertEquals(rawAtlas.numberOfLines(), slicedAtlas.numberOfLines()); Assert.assertEquals(rawAtlas.numberOfRelations(), slicedAtlas.numberOfRelations()); Assert.assertTrue(Iterables.stream(slicedAtlas.entities()) .allMatch(entity -> entity.getTag(ISOCountryTag.KEY).get().equals("LBR") && entity.getTag(SyntheticGeometrySlicedTag.KEY).isEmpty())); } /** * This relation is made up two closed lines, both on the Liberia side. However, the inner and * outer roles are reversed, causing an invalid multipolygon. Expect only country code * assignment, all points removed (since they have no tags), no geometry slicing, and no * relation slicing */ @Test public void testInnerOutsideOuterRelation() { final Atlas rawAtlas = this.setup.getInnerOutsideOuterRelationAtlas(); final Atlas slicedAtlas = new RawAtlasSlicer( AtlasLoadingOption.createOptionWithAllEnabled(boundary).setCountryCode("LBR"), rawAtlas).slice(); // Assert that we cannot build a valid building with this relation new ComplexBuildingFinder().find(slicedAtlas) .forEach(building -> Assert.assertTrue(building.getError().isPresent())); // Nothing should have been sliced, verify identical counts Assert.assertEquals(0, slicedAtlas.numberOfPoints()); Assert.assertEquals(rawAtlas.numberOfLines(), slicedAtlas.numberOfLines()); Assert.assertEquals(rawAtlas.numberOfRelations(), slicedAtlas.numberOfRelations()); Assert.assertTrue(Iterables.stream(slicedAtlas.entities()) .allMatch(entity -> entity.getTag(ISOCountryTag.KEY).get().equals("LBR") && entity.getTag(SyntheticGeometrySlicedTag.KEY).isEmpty())); } /** * This relation is made up of a single closed line straddling the CIV/LBR boundary, which is * the sole member in the relation with inner role. This is an invalid multipolygon, since it * doesn't have an outer. Expect only country code assignment, all points removed (since they * have no tags), no geometry slicing, and no relation slicing. Additionally, because * multipolygon relation slicing requires lines sliced linearly, but the line is closed, expect * to see both the linearly sliced line in the atlas Lines, and the polygonally sliced line in * the atlas Areas. The areas should *not* be part of the relation. */ @Test public void testInnerWithoutOuterAcrossBoundary() { final Atlas rawAtlas = this.setup.getInnerWithoutOuterAcrossBoundaryAtlas(); final Atlas civSlicedAtlas = new RawAtlasSlicer( AtlasLoadingOption.createOptionWithAllEnabled(boundary).setCountryCode("CIV"), rawAtlas).slice(); final Atlas lbrSlicedAtlas = new RawAtlasSlicer( AtlasLoadingOption.createOptionWithAllEnabled(boundary).setCountryCode("LBR"), rawAtlas).slice(); Assert.assertEquals(0, civSlicedAtlas.numberOfPoints()); Assert.assertEquals(0, lbrSlicedAtlas.numberOfPoints()); // Line was cut into two pieces, and each relation contains the piece as an inner Assert.assertEquals(1, civSlicedAtlas.numberOfAreas()); Assert.assertEquals(1, lbrSlicedAtlas.numberOfAreas()); Assert.assertEquals(1, civSlicedAtlas.numberOfRelations()); Assert.assertEquals(1, lbrSlicedAtlas.numberOfRelations()); final CountrySlicingIdentifierFactory lineIdentifierFactory = new CountrySlicingIdentifierFactory( 108768000000L); final Area rawArea = rawAtlas.area(108768000000L); final Line civLine = civSlicedAtlas.line(lineIdentifierFactory.nextIdentifier()); Assert.assertEquals("CIV", civLine.getTag(ISOCountryTag.KEY).get()); Assert.assertEquals(SyntheticGeometrySlicedTag.YES.toString(), civLine.getTag(SyntheticGeometrySlicedTag.KEY).get()); Assert.assertEquals(rawArea.getOsmTags(), civLine.getOsmTags()); final Line lbrLine = lbrSlicedAtlas.line(lineIdentifierFactory.nextIdentifier()); Assert.assertEquals("LBR", lbrLine.getTag(ISOCountryTag.KEY).get()); Assert.assertEquals(SyntheticGeometrySlicedTag.YES.toString(), lbrLine.getTag(SyntheticGeometrySlicedTag.KEY).get()); Assert.assertEquals(rawArea.getOsmTags(), lbrLine.getOsmTags()); final Area civArea = civSlicedAtlas.area(civLine.getIdentifier()); Assert.assertEquals("CIV", civArea.getTag(ISOCountryTag.KEY).get()); Assert.assertEquals(SyntheticGeometrySlicedTag.YES.toString(), civArea.getTag(SyntheticGeometrySlicedTag.KEY).get()); Assert.assertEquals(rawArea.getOsmTags(), civArea.getOsmTags()); final Area lbrArea = lbrSlicedAtlas.area(lbrLine.getIdentifier()); Assert.assertEquals("LBR", lbrArea.getTag(ISOCountryTag.KEY).get()); Assert.assertEquals(SyntheticGeometrySlicedTag.YES.toString(), lbrArea.getTag(SyntheticGeometrySlicedTag.KEY).get()); Assert.assertEquals(rawArea.getOsmTags(), lbrArea.getOsmTags()); Assert.assertEquals("CIV", civSlicedAtlas.relation(1).getTag(ISOCountryTag.KEY).get()); Assert.assertTrue( civSlicedAtlas.relation(1).getTag(SyntheticGeometrySlicedTag.KEY).isEmpty()); Assert.assertEquals(1, civSlicedAtlas.relation(1).members().size()); Assert.assertEquals(ItemType.LINE, civSlicedAtlas.relation(1).members().get(0).getEntity().getType()); Assert.assertEquals(civLine.getIdentifier(), civSlicedAtlas.relation(1).members().get(0).getEntity().getIdentifier()); Assert.assertTrue(civSlicedAtlas.relation(1) .getTag(SyntheticInvalidMultiPolygonRelationMembersRemovedTag.KEY).isEmpty()); Assert.assertEquals(rawAtlas.relation(1).getOsmTags(), civSlicedAtlas.relation(1).getOsmTags()); Assert.assertEquals("LBR", lbrSlicedAtlas.relation(1).getTag(ISOCountryTag.KEY).get()); Assert.assertTrue( lbrSlicedAtlas.relation(1).getTag(SyntheticGeometrySlicedTag.KEY).isEmpty()); Assert.assertEquals(1, lbrSlicedAtlas.relation(1).members().size()); Assert.assertEquals(ItemType.LINE, lbrSlicedAtlas.relation(1).members().get(0).getEntity().getType()); Assert.assertEquals(lbrLine.getIdentifier(), lbrSlicedAtlas.relation(1).members().get(0).getEntity().getIdentifier()); Assert.assertTrue(lbrSlicedAtlas.relation(1) .getTag(SyntheticInvalidMultiPolygonRelationMembersRemovedTag.KEY).isEmpty()); Assert.assertEquals(rawAtlas.relation(1).getOsmTags(), lbrSlicedAtlas.relation(1).getOsmTags()); } /** * This relation is made up of a single closed line inside LBR, which is the sole member in the * relation with inner role. This is an invalid multipolygon, since it doesn't have an outer. * Expect only country code assignment, all points removed (since they have no tags), no * geometry slicing, and no relation slicing */ @Test public void testInnerWithoutOuterRelationInOneCountry() { final Atlas rawAtlas = this.setup.getInnerWithoutOuterInOneCountryAtlas(); final Atlas slicedAtlas = new RawAtlasSlicer( AtlasLoadingOption.createOptionWithAllEnabled(boundary).setCountryCode("LBR"), rawAtlas).slice(); // Assert that we cannot build a valid building with this relation new ComplexBuildingFinder().find(slicedAtlas) .forEach(building -> Assert.assertTrue(building.getError().isPresent())); // Nothing should have been sliced, verify identical counts Assert.assertEquals(0, slicedAtlas.numberOfPoints()); Assert.assertEquals(rawAtlas.numberOfLines(), slicedAtlas.numberOfLines()); Assert.assertEquals(rawAtlas.numberOfRelations(), slicedAtlas.numberOfRelations()); Assert.assertTrue(Iterables.stream(slicedAtlas.entities()) .allMatch(entity -> entity.getTag(ISOCountryTag.KEY).get().equals("LBR") && entity.getTag(SyntheticGeometrySlicedTag.KEY).isEmpty())); } /** * This relation is made up of three closed lines, each serving as an outer to a multipolygon * relation. Two of the outers span the border of two countries, while one is entirely within a * country. */ @Test public void testMultiPolygonRelationSpanningTwoCountries() { final Atlas rawAtlas = this.setup.getSimpleMultiPolygonAtlas(); final Atlas civSlicedAtlas = new RawAtlasSlicer( AtlasLoadingOption.createOptionWithAllEnabled(boundary).setCountryCode("CIV"), rawAtlas).slice(); final Atlas lbrSlicedAtlas = new RawAtlasSlicer( AtlasLoadingOption.createOptionWithAllEnabled(boundary).setCountryCode("LBR"), rawAtlas).slice(); Assert.assertEquals(0, civSlicedAtlas.numberOfPoints()); Assert.assertEquals(4, civSlicedAtlas.numberOfLines()); Assert.assertEquals(2, civSlicedAtlas.numberOfAreas()); Assert.assertEquals(1, civSlicedAtlas.numberOfRelations()); Assert.assertTrue(Iterables.stream(civSlicedAtlas.entities()) .allMatch(entity -> entity.getTag(ISOCountryTag.KEY).get().equals("CIV"))); Assert.assertEquals(4, lbrSlicedAtlas.numberOfLines()); Assert.assertEquals(3, lbrSlicedAtlas.numberOfAreas()); Assert.assertEquals(0, lbrSlicedAtlas.numberOfPoints()); Assert.assertEquals(1, lbrSlicedAtlas.numberOfRelations()); Assert.assertTrue(Iterables.stream(lbrSlicedAtlas.entities()) .allMatch(entity -> entity.getTag(ISOCountryTag.KEY).get().equals("LBR"))); final SortedSet<String> civSyntheticRelationMembers = new TreeSet<>(); civSlicedAtlas.lines().forEach(line -> { if (line.getTag(SyntheticGeometrySlicedTag.KEY).isPresent()) { final Area rawArea = rawAtlas.areas(rawAreaCandidate -> rawAreaCandidate .getOsmIdentifier() == line.getOsmIdentifier()).iterator().next(); Assert.assertNotNull(civSlicedAtlas.area(line.getIdentifier())); Assert.assertEquals(rawArea.getOsmTags(), line.getOsmTags()); Assert.assertEquals(rawArea.getOsmTags(), civSlicedAtlas.area(line.getIdentifier()).getOsmTags()); Assert.assertEquals(1, line.relations().size()); Assert.assertEquals(0, civSlicedAtlas.area(line.getIdentifier()).relations().size()); } else { Assert.assertTrue(line.getTag(SyntheticSyntheticRelationMemberTag.KEY).isPresent()); civSyntheticRelationMembers.add(Long.toString(line.getIdentifier())); } }); final SortedSet<String> lbrSyntheticRelationMembers = new TreeSet<>(); lbrSlicedAtlas.lines().forEach(line -> { if (line.getTag(SyntheticGeometrySlicedTag.KEY).isPresent()) { final Area rawArea = rawAtlas.areas(rawAreaCandidate -> rawAreaCandidate .getOsmIdentifier() == line.getOsmIdentifier()).iterator().next(); Assert.assertNotNull(lbrSlicedAtlas.area(line.getIdentifier())); Assert.assertEquals(rawArea.getOsmTags(), line.getOsmTags()); Assert.assertEquals(rawArea.getOsmTags(), lbrSlicedAtlas.area(line.getIdentifier()).getOsmTags()); Assert.assertEquals(1, line.relations().size()); Assert.assertEquals(0, lbrSlicedAtlas.area(line.getIdentifier()).relations().size()); } else if (rawAtlas.line(line.getIdentifier()) != null) { Assert.assertEquals(rawAtlas.line(line.getIdentifier()).getOsmTags(), line.getOsmTags()); Assert.assertEquals(rawAtlas.line(line.getIdentifier()).asPolyLine(), line.asPolyLine()); Assert.assertEquals(1, line.relations().size()); } else { Assert.assertTrue(line.getTag(SyntheticSyntheticRelationMemberTag.KEY).isPresent()); lbrSyntheticRelationMembers.add(Long.toString(line.getIdentifier())); } }); final CountrySlicingIdentifierFactory relationIdentifierFactory = new CountrySlicingIdentifierFactory( 1); final Relation civRelation = civSlicedAtlas .relation(relationIdentifierFactory.nextIdentifier()); final Relation lbrRelation = lbrSlicedAtlas .relation(relationIdentifierFactory.nextIdentifier()); Assert.assertEquals("CIV", civRelation.getTag(ISOCountryTag.KEY).get()); Assert.assertEquals(SyntheticGeometrySlicedTag.YES.toString(), civRelation.getTag(SyntheticGeometrySlicedTag.KEY).get()); Assert.assertEquals( String.join(SyntheticRelationMemberAdded.MEMBER_DELIMITER, civSyntheticRelationMembers), civRelation.getTag(SyntheticRelationMemberAdded.KEY).get()); Assert.assertTrue(civRelation .getTag(SyntheticInvalidMultiPolygonRelationMembersRemovedTag.KEY).isEmpty()); Assert.assertEquals("LBR", lbrRelation.getTag(ISOCountryTag.KEY).get()); Assert.assertEquals(SyntheticGeometrySlicedTag.YES.toString(), lbrRelation.getTag(SyntheticGeometrySlicedTag.KEY).get()); Assert.assertEquals( String.join(SyntheticRelationMemberAdded.MEMBER_DELIMITER, lbrSyntheticRelationMembers), lbrRelation.getTag(SyntheticRelationMemberAdded.KEY).get()); Assert.assertTrue(lbrRelation .getTag(SyntheticInvalidMultiPolygonRelationMembersRemovedTag.KEY).isEmpty()); Assert.assertTrue(jtsConverter.backwardConvert(converter.convert(civRelation)).isValid()); Assert.assertTrue(jtsConverter.backwardConvert(converter.convert(lbrRelation)).isValid()); } /** * This relation is made up of closed lines, tied together by a relation, to create a * MultiPolygon with the outer spanning two countries and the inner fully inside one country. */ @Test public void testMultiPolygonWithClosedLinesSpanningTwoCountries() { final Atlas rawAtlas = this.setup.getComplexMultiPolygonWithHoleUsingClosedLinesAtlas(); final Atlas civSlicedAtlas = new RawAtlasSlicer( AtlasLoadingOption.createOptionWithAllEnabled(boundary).setCountryCode("CIV"), rawAtlas).slice(); final Atlas lbrSlicedAtlas = new RawAtlasSlicer( AtlasLoadingOption.createOptionWithAllEnabled(boundary).setCountryCode("LBR"), rawAtlas).slice(); Assert.assertEquals(2, civSlicedAtlas.numberOfLines()); Assert.assertEquals(1, civSlicedAtlas.numberOfAreas()); Assert.assertEquals(0, civSlicedAtlas.numberOfPoints()); Assert.assertEquals(1, civSlicedAtlas.numberOfRelations()); final Iterable<ComplexWaterEntity> civWaterEntities = new ComplexWaterEntityFinder() .find(civSlicedAtlas, Finder::ignore); Assert.assertEquals(1, Iterables.size(civWaterEntities)); Assert.assertEquals(2, lbrSlicedAtlas.numberOfLines()); Assert.assertEquals(2, lbrSlicedAtlas.numberOfAreas()); Assert.assertEquals(0, lbrSlicedAtlas.numberOfPoints()); Assert.assertEquals(1, lbrSlicedAtlas.numberOfRelations()); final Iterable<ComplexWaterEntity> lbrWaterEntities = new ComplexWaterEntityFinder() .find(lbrSlicedAtlas, Finder::ignore); Assert.assertEquals(1, Iterables.size(lbrWaterEntities)); final SortedSet<String> civSyntheticRelationMembers = new TreeSet<>(); civSlicedAtlas.lines().forEach(line -> { if (line.getTag(SyntheticGeometrySlicedTag.KEY).isPresent()) { final Area rawArea = rawAtlas.areas(rawAreaCandidate -> rawAreaCandidate .getOsmIdentifier() == line.getOsmIdentifier()).iterator().next(); Assert.assertNotNull(civSlicedAtlas.area(line.getIdentifier())); Assert.assertEquals(rawArea.getOsmTags(), line.getOsmTags()); Assert.assertEquals(rawArea.getOsmTags(), civSlicedAtlas.area(line.getIdentifier()).getOsmTags()); Assert.assertEquals(1, line.relations().size()); Assert.assertEquals(0, civSlicedAtlas.area(line.getIdentifier()).relations().size()); } else if (rawAtlas.line(line.getIdentifier()) != null) { Assert.assertEquals(rawAtlas.line(line.getIdentifier()).getOsmTags(), line.getOsmTags()); Assert.assertEquals(rawAtlas.line(line.getIdentifier()).asPolyLine(), line.asPolyLine()); Assert.assertEquals(1, line.relations().size()); } else { Assert.assertTrue(line.getTag(SyntheticSyntheticRelationMemberTag.KEY).isPresent()); civSyntheticRelationMembers.add(Long.toString(line.getIdentifier())); } }); final SortedSet<String> lbrSyntheticRelationMembers = new TreeSet<>(); lbrSlicedAtlas.lines().forEach(line -> { if (line.getTag(SyntheticGeometrySlicedTag.KEY).isPresent()) { final Area rawArea = rawAtlas.areas(rawAreaCandidate -> rawAreaCandidate .getOsmIdentifier() == line.getOsmIdentifier()).iterator().next(); Assert.assertNotNull(lbrSlicedAtlas.area(line.getIdentifier())); Assert.assertEquals(rawArea.getOsmTags(), line.getOsmTags()); Assert.assertEquals(rawArea.getOsmTags(), lbrSlicedAtlas.area(line.getIdentifier()).getOsmTags()); Assert.assertEquals(1, line.relations().size()); Assert.assertEquals(0, lbrSlicedAtlas.area(line.getIdentifier()).relations().size()); } else if (rawAtlas.line(line.getIdentifier()) != null) { Assert.assertEquals(rawAtlas.line(line.getIdentifier()).getOsmTags(), line.getOsmTags()); Assert.assertEquals(rawAtlas.line(line.getIdentifier()).asPolyLine(), line.asPolyLine()); Assert.assertEquals(1, line.relations().size()); } else { Assert.assertTrue(line.getTag(SyntheticSyntheticRelationMemberTag.KEY).isPresent()); lbrSyntheticRelationMembers.add(Long.toString(line.getIdentifier())); } }); final CountrySlicingIdentifierFactory relationIdentifierFactory = new CountrySlicingIdentifierFactory( 214805000000L); final Relation civRelation = civSlicedAtlas .relation(relationIdentifierFactory.nextIdentifier()); final Relation lbrRelation = lbrSlicedAtlas .relation(relationIdentifierFactory.nextIdentifier()); Assert.assertEquals("CIV", civRelation.getTag(ISOCountryTag.KEY).get()); Assert.assertEquals(SyntheticGeometrySlicedTag.YES.toString(), civRelation.getTag(SyntheticGeometrySlicedTag.KEY).get()); Assert.assertEquals( String.join(SyntheticRelationMemberAdded.MEMBER_DELIMITER, civSyntheticRelationMembers), civRelation.getTag(SyntheticRelationMemberAdded.KEY).get()); Assert.assertTrue(civRelation .getTag(SyntheticInvalidMultiPolygonRelationMembersRemovedTag.KEY).isEmpty()); Assert.assertEquals("LBR", lbrRelation.getTag(ISOCountryTag.KEY).get()); Assert.assertEquals(SyntheticGeometrySlicedTag.YES.toString(), lbrRelation.getTag(SyntheticGeometrySlicedTag.KEY).get()); Assert.assertEquals( String.join(SyntheticRelationMemberAdded.MEMBER_DELIMITER, lbrSyntheticRelationMembers), lbrRelation.getTag(SyntheticRelationMemberAdded.KEY).get()); Assert.assertTrue(lbrRelation .getTag(SyntheticInvalidMultiPolygonRelationMembersRemovedTag.KEY).isEmpty()); } /** * This test is the same as testSimpleMultiPolygonWithHoleSpanningTwoCountries(), but this * version contains invalid members. Check to see multipolygon relation is still properly sliced * but that invalid members have been filtered out and tag has been updated correctly */ @Test public void testMultiPolygonWithInvalidMembers() { final Atlas rawAtlas = this.setup.getRelationWithInvalidMultiPolygonMembers(); final Atlas civSlicedAtlas = new RawAtlasSlicer( AtlasLoadingOption.createOptionWithAllEnabled(boundary).setCountryCode("CIV"), rawAtlas).slice(); final Atlas lbrSlicedAtlas = new RawAtlasSlicer( AtlasLoadingOption.createOptionWithAllEnabled(boundary).setCountryCode("LBR"), rawAtlas).slice(); Assert.assertEquals(0, civSlicedAtlas.numberOfPoints()); Assert.assertEquals(5, civSlicedAtlas.numberOfLines()); Assert.assertEquals(3, civSlicedAtlas.numberOfAreas()); Assert.assertEquals(1, civSlicedAtlas.numberOfRelations()); final Iterable<ComplexBuilding> civBuildings = new ComplexBuildingFinder() .find(civSlicedAtlas, Finder::ignore); Assert.assertEquals(1, Iterables.size(civBuildings)); Assert.assertEquals(0, lbrSlicedAtlas.numberOfPoints()); Assert.assertEquals(5, lbrSlicedAtlas.numberOfLines()); Assert.assertEquals(3, lbrSlicedAtlas.numberOfAreas()); Assert.assertEquals(1, lbrSlicedAtlas.numberOfRelations()); final Iterable<ComplexBuilding> lbrBuildings = new ComplexBuildingFinder() .find(lbrSlicedAtlas, Finder::ignore); Assert.assertEquals(1, Iterables.size(lbrBuildings)); final SortedSet<String> civSyntheticRelationMembers = new TreeSet<>(); civSlicedAtlas.lines().forEach(line -> { if (line.getTag(SyntheticGeometrySlicedTag.KEY).isPresent()) { final Area rawArea = rawAtlas.areas(rawAreaCandidate -> rawAreaCandidate .getOsmIdentifier() == line.getOsmIdentifier()).iterator().next(); Assert.assertEquals(rawArea.getOsmTags(), line.getOsmTags()); } else { Assert.assertTrue(line.getTag(SyntheticSyntheticRelationMemberTag.KEY).isPresent()); civSyntheticRelationMembers.add(Long.toString(line.getIdentifier())); } }); final SortedSet<String> lbrSyntheticRelationMembers = new TreeSet<>(); lbrSlicedAtlas.lines().forEach(line -> { if (line.getTag(SyntheticGeometrySlicedTag.KEY).isPresent()) { final Area rawArea = rawAtlas.areas(rawAreaCandidate -> rawAreaCandidate .getOsmIdentifier() == line.getOsmIdentifier()).iterator().next(); Assert.assertEquals(rawArea.getOsmTags(), line.getOsmTags()); } else if (rawAtlas.line(line.getIdentifier()) != null) { Assert.assertEquals(rawAtlas.line(line.getIdentifier()).getOsmTags(), line.getOsmTags()); Assert.assertEquals(rawAtlas.line(line.getIdentifier()).asPolyLine(), line.asPolyLine()); Assert.assertEquals(1, line.relations().size()); } else { Assert.assertTrue(line.getTag(SyntheticSyntheticRelationMemberTag.KEY).isPresent()); lbrSyntheticRelationMembers.add(Long.toString(line.getIdentifier())); } }); final CountrySlicingIdentifierFactory relationIdentifierFactory = new CountrySlicingIdentifierFactory( 0L); final Relation civRelation = civSlicedAtlas .relation(relationIdentifierFactory.nextIdentifier()); final Relation lbrRelation = lbrSlicedAtlas .relation(relationIdentifierFactory.nextIdentifier()); Assert.assertEquals("CIV", civRelation.getTag(ISOCountryTag.KEY).get()); Assert.assertEquals(SyntheticGeometrySlicedTag.YES.toString(), civRelation.getTag(SyntheticGeometrySlicedTag.KEY).get()); Assert.assertEquals( String.join(SyntheticRelationMemberAdded.MEMBER_DELIMITER, civSyntheticRelationMembers), civRelation.getTag(SyntheticRelationMemberAdded.KEY).get()); Assert.assertEquals("5,1000,108752000000", civRelation .getTag(SyntheticInvalidMultiPolygonRelationMembersRemovedTag.KEY).get()); Assert.assertEquals("LBR", lbrRelation.getTag(ISOCountryTag.KEY).get()); Assert.assertEquals(SyntheticGeometrySlicedTag.YES.toString(), lbrRelation.getTag(SyntheticGeometrySlicedTag.KEY).get()); Assert.assertEquals( String.join(SyntheticRelationMemberAdded.MEMBER_DELIMITER, lbrSyntheticRelationMembers), lbrRelation.getTag(SyntheticRelationMemberAdded.KEY).get()); Assert.assertEquals("5,2000,108752000000", lbrRelation .getTag(SyntheticInvalidMultiPolygonRelationMembersRemovedTag.KEY).get()); } /** * This relation is made up of open lines, tied together by a relation to create a MultiPolygon * with the outer spanning two countries and the inner fully inside one country. */ @Test public void testMultiPolygonWithOpenLinesSpanningTwoCountries() { final Atlas rawAtlas = this.setup.getComplexMultiPolygonWithHoleUsingOpenLinesAtlas(); final Atlas civSlicedAtlas = new RawAtlasSlicer( AtlasLoadingOption.createOptionWithAllEnabled(boundary).setCountryCode("CIV"), rawAtlas).slice(); final Atlas lbrSlicedAtlas = new RawAtlasSlicer( AtlasLoadingOption.createOptionWithAllEnabled(boundary).setCountryCode("LBR"), rawAtlas).slice(); Assert.assertEquals(3, civSlicedAtlas.numberOfLines()); Assert.assertEquals(0, civSlicedAtlas.numberOfAreas()); Assert.assertEquals(0, civSlicedAtlas.numberOfPoints()); Assert.assertEquals(1, civSlicedAtlas.numberOfRelations()); final Iterable<ComplexWaterEntity> civWaterEntities = new ComplexWaterEntityFinder() .find(civSlicedAtlas, Finder::ignore); Assert.assertEquals(1, Iterables.size(civWaterEntities)); Assert.assertEquals(5, lbrSlicedAtlas.numberOfLines()); Assert.assertEquals(0, lbrSlicedAtlas.numberOfAreas()); Assert.assertEquals(0, lbrSlicedAtlas.numberOfPoints()); Assert.assertEquals(1, lbrSlicedAtlas.numberOfRelations()); final Iterable<ComplexWaterEntity> lbrWaterEntities = new ComplexWaterEntityFinder() .find(lbrSlicedAtlas, Finder::ignore); Assert.assertEquals(1, Iterables.size(lbrWaterEntities)); final SortedSet<String> civSyntheticRelationMembers = new TreeSet<>(); civSlicedAtlas.lines().forEach(line -> { if (line.getTag(SyntheticGeometrySlicedTag.KEY).isPresent()) { final Line rawLine = rawAtlas.lines(rawLineCandidate -> rawLineCandidate .getOsmIdentifier() == line.getOsmIdentifier()).iterator().next(); Assert.assertEquals(rawLine.getOsmTags(), line.getOsmTags()); Assert.assertEquals(1, line.relations().size()); } else { Assert.assertTrue(line.getTag(SyntheticSyntheticRelationMemberTag.KEY).isPresent()); civSyntheticRelationMembers.add(Long.toString(line.getIdentifier())); } }); final SortedSet<String> lbrSyntheticRelationMembers = new TreeSet<>(); lbrSlicedAtlas.lines().forEach(line -> { if (line.getTag(SyntheticGeometrySlicedTag.KEY).isPresent()) { final Line rawLine = rawAtlas.lines(rawLineCandidate -> rawLineCandidate .getOsmIdentifier() == line.getOsmIdentifier()).iterator().next(); Assert.assertEquals(rawLine.getOsmTags(), line.getOsmTags()); Assert.assertEquals(1, line.relations().size()); } else if (rawAtlas.line(line.getIdentifier()) != null) { Assert.assertEquals(rawAtlas.line(line.getIdentifier()).getOsmTags(), line.getOsmTags()); Assert.assertEquals(rawAtlas.line(line.getIdentifier()).asPolyLine(), line.asPolyLine()); Assert.assertEquals(1, line.relations().size()); } else { Assert.assertTrue(line.getTag(SyntheticSyntheticRelationMemberTag.KEY).isPresent()); lbrSyntheticRelationMembers.add(Long.toString(line.getIdentifier())); } }); final CountrySlicingIdentifierFactory relationIdentifierFactory = new CountrySlicingIdentifierFactory( 214805000000L); final Relation civRelation = civSlicedAtlas .relation(relationIdentifierFactory.nextIdentifier()); final Relation lbrRelation = lbrSlicedAtlas .relation(relationIdentifierFactory.nextIdentifier()); Assert.assertEquals("CIV", civRelation.getTag(ISOCountryTag.KEY).get()); Assert.assertEquals(SyntheticGeometrySlicedTag.YES.toString(), civRelation.getTag(SyntheticGeometrySlicedTag.KEY).get()); Assert.assertEquals( String.join(SyntheticRelationMemberAdded.MEMBER_DELIMITER, civSyntheticRelationMembers), civRelation.getTag(SyntheticRelationMemberAdded.KEY).get()); Assert.assertTrue(civRelation .getTag(SyntheticInvalidMultiPolygonRelationMembersRemovedTag.KEY).isEmpty()); Assert.assertEquals("LBR", lbrRelation.getTag(ISOCountryTag.KEY).get()); Assert.assertEquals(SyntheticGeometrySlicedTag.YES.toString(), lbrRelation.getTag(SyntheticGeometrySlicedTag.KEY).get()); Assert.assertEquals( String.join(SyntheticRelationMemberAdded.MEMBER_DELIMITER, lbrSyntheticRelationMembers), lbrRelation.getTag(SyntheticRelationMemberAdded.KEY).get()); Assert.assertTrue(lbrRelation .getTag(SyntheticInvalidMultiPolygonRelationMembersRemovedTag.KEY).isEmpty()); } @Test public void testMultiPolygonWithOverlappingSlicedInners() { final Atlas rawAtlas = this.setup.getMultiPolygonWithOverlappingSlicedInners(); final Atlas lbrSlicedAtlas = new RawAtlasSlicer( AtlasLoadingOption.createOptionWithAllEnabled(boundary).setCountryCode("LBR"), rawAtlas).slice(); lbrSlicedAtlas.relations().forEach(relation -> { Assert.assertTrue(relation.getTag(SyntheticInvalidGeometryTag.KEY).isPresent()); Assert.assertFalse(relation.getTag(SyntheticGeometrySlicedTag.KEY).isPresent()); }); final Atlas civSlicedAtlas = new RawAtlasSlicer( AtlasLoadingOption.createOptionWithAllEnabled(boundary).setCountryCode("CIV"), rawAtlas).slice(); civSlicedAtlas.relations().forEach(relation -> { Assert.assertTrue(relation.getTag(SyntheticInvalidGeometryTag.KEY).isPresent()); Assert.assertFalse(relation.getTag(SyntheticGeometrySlicedTag.KEY).isPresent()); }); } @Test public void testMultiPolygonWithOverlappingUnslicedInners() { final Atlas rawAtlas = this.setup.getMultiPolygonWithOverlappingUnslicedInners(); final Atlas lbrSlicedAtlas = new RawAtlasSlicer( AtlasLoadingOption.createOptionWithAllEnabled(boundary).setCountryCode("LBR"), rawAtlas).slice(); lbrSlicedAtlas.relations().forEach(relation -> { Assert.assertFalse(relation.getTag(SyntheticInvalidGeometryTag.KEY).isPresent()); Assert.assertTrue(relation.getTag(SyntheticGeometrySlicedTag.KEY).isPresent()); }); final Atlas civSlicedAtlas = new RawAtlasSlicer( AtlasLoadingOption.createOptionWithAllEnabled(boundary).setCountryCode("CIV"), rawAtlas).slice(); civSlicedAtlas.relations().forEach(relation -> { Assert.assertFalse(relation.getTag(SyntheticInvalidGeometryTag.KEY).isPresent()); Assert.assertTrue(relation.getTag(SyntheticGeometrySlicedTag.KEY).isPresent()); }); } /** * This relation is made up of a single open line straddling the country boundary, which is the * sole member in the relation with outer role. This is an invalid multipolygon, since it isn't * closed. We expect slicing to add a new point, on the boundary and create a relation for each * country, holding a piece of the sliced line in each one. */ @Test public void testOpenMultiPolygonRelationAcrossBoundary() { final Atlas rawAtlas = this.setup.getOpenMultiPolygonAcrossBoundaryAtlas(); final Atlas civSlicedAtlas = new RawAtlasSlicer( AtlasLoadingOption.createOptionWithAllEnabled(boundary).setCountryCode("CIV"), rawAtlas).slice(); final Atlas lbrSlicedAtlas = new RawAtlasSlicer( AtlasLoadingOption.createOptionWithAllEnabled(boundary).setCountryCode("LBR"), rawAtlas).slice(); Assert.assertEquals(0, civSlicedAtlas.numberOfPoints()); Assert.assertEquals(1, civSlicedAtlas.numberOfLines()); Assert.assertEquals(0, civSlicedAtlas.numberOfAreas()); Assert.assertEquals(1, civSlicedAtlas.numberOfRelations()); new ComplexBuildingFinder().find(civSlicedAtlas) .forEach(building -> Assert.assertTrue(building.getError().isPresent())); Assert.assertEquals(0, lbrSlicedAtlas.numberOfPoints()); Assert.assertEquals(1, lbrSlicedAtlas.numberOfLines()); Assert.assertEquals(0, lbrSlicedAtlas.numberOfAreas()); Assert.assertEquals(1, lbrSlicedAtlas.numberOfRelations()); new ComplexBuildingFinder().find(lbrSlicedAtlas) .forEach(building -> Assert.assertTrue(building.getError().isPresent())); final Relation civRelation = civSlicedAtlas.relation(1); Assert.assertEquals(1, civRelation.members().size()); Assert.assertEquals("CIV", civRelation.getTag(ISOCountryTag.KEY).get()); final Relation lbrRelation = lbrSlicedAtlas.relation(1); Assert.assertEquals(1, lbrRelation.members().size()); Assert.assertEquals("LBR", lbrRelation.getTag(ISOCountryTag.KEY).get()); } /** * This relation is made up of a single open line inside LBR, which is the sole member in the * relation with outer role. This is an invalid multipolygon, since it isn't closed. We expect * slicing to add country codes to all points/lines/relations, but leave the geometry and roles * unchanged. */ @Test public void testOpenMultiPolygonRelationInOneCountry() { final Atlas rawAtlas = this.setup.getOpenMultiPolygonInOneCountryAtlas(); final Atlas lbrSlicedAtlas = new RawAtlasSlicer( AtlasLoadingOption.createOptionWithAllEnabled(boundary).setCountryCode("LBR"), rawAtlas).slice(); Assert.assertEquals(0, lbrSlicedAtlas.numberOfPoints()); Assert.assertEquals(1, lbrSlicedAtlas.numberOfLines()); Assert.assertEquals(0, lbrSlicedAtlas.numberOfAreas()); Assert.assertEquals(1, lbrSlicedAtlas.numberOfRelations()); new ComplexBuildingFinder().find(lbrSlicedAtlas) .forEach(building -> Assert.assertTrue(building.getError().isPresent())); Assert.assertTrue(Iterables.stream(lbrSlicedAtlas.entities()) .allMatch(entity -> entity.getTag(ISOCountryTag.KEY).get().equals("LBR") && entity.getTag(SyntheticGeometrySlicedTag.KEY).isEmpty())); } /** * This relation is made up of two lines. The first one is a closed line on the LBR side. The * second is an open line spanning the boundary of LBR and CIV. Both lines are outer members in * a relation. We expect slicing to leave the closed line and to cut the open line as well as * create a new relation on the CIV side with a piece of the outer open line as a single member. */ @Test public void testRelationWithOneClosedAndOpenMember() { final Atlas rawAtlas = this.setup.getRelationWithOneClosedAndOneOpenMemberAtlas(); final Atlas civSlicedAtlas = new RawAtlasSlicer( AtlasLoadingOption.createOptionWithAllEnabled(boundary).setCountryCode("CIV"), rawAtlas).slice(); final Atlas lbrSlicedAtlas = new RawAtlasSlicer( AtlasLoadingOption.createOptionWithAllEnabled(boundary).setCountryCode("LBR"), rawAtlas).slice(); Assert.assertEquals(0, civSlicedAtlas.numberOfPoints()); Assert.assertEquals(1, civSlicedAtlas.numberOfLines()); Assert.assertEquals(0, civSlicedAtlas.numberOfAreas()); Assert.assertEquals(1, civSlicedAtlas.numberOfRelations()); new ComplexBuildingFinder().find(civSlicedAtlas) .forEach(building -> Assert.assertTrue(building.getError().isPresent())); Assert.assertEquals(0, lbrSlicedAtlas.numberOfPoints()); Assert.assertEquals(2, lbrSlicedAtlas.numberOfLines()); Assert.assertEquals(0, lbrSlicedAtlas.numberOfAreas()); Assert.assertEquals(1, lbrSlicedAtlas.numberOfRelations()); new ComplexBuildingFinder().find(lbrSlicedAtlas) .forEach(building -> Assert.assertTrue(building.getError().isPresent())); } /** * This relation is made up of two lines. The first is a closed line, with an inner role, fully * on the LBR side. The second is a self-intersecting closed outer, stretching across the * boundary. Since that line is invalid geometry, it should not be sliced and instead be tagged * with both CIV and LBR country tags, and this should propogate up to the unsliced relation * which should have the same country tags. */ @Test public void testSelfIntersectingOuterRelationAcrossBoundary() { final Atlas rawAtlas = this.setup .getSelfIntersectingOuterMemberRelationAcrossBoundaryAtlas(); final Atlas civSlicedAtlas = new RawAtlasSlicer( AtlasLoadingOption.createOptionWithAllEnabled(boundary).setCountryCode("CIV"), rawAtlas).slice(); final Atlas lbrSlicedAtlas = new RawAtlasSlicer( AtlasLoadingOption.createOptionWithAllEnabled(boundary).setCountryCode("LBR"), rawAtlas).slice(); Assert.assertEquals(0, civSlicedAtlas.numberOfPoints()); Assert.assertEquals(0, civSlicedAtlas.numberOfLines()); Assert.assertEquals(1, civSlicedAtlas.numberOfAreas()); Assert.assertEquals(1, civSlicedAtlas.numberOfRelations()); Assert.assertEquals("CIV,LBR", civSlicedAtlas.area(108768000000L).getTag(ISOCountryTag.KEY).get()); Assert.assertEquals(rawAtlas.area(108768000000L).asPolygon(), civSlicedAtlas.area(108768000000L).asPolygon()); Assert.assertEquals("CIV,LBR", civSlicedAtlas.relation(1).getTag(ISOCountryTag.KEY).get()); Assert.assertTrue( civSlicedAtlas.relation(1).getTag(SyntheticGeometrySlicedTag.KEY).isEmpty()); Assert.assertTrue( civSlicedAtlas.relation(1).getTag(SyntheticRelationMemberAdded.KEY).isEmpty()); Assert.assertTrue(civSlicedAtlas.relation(1) .getTag(SyntheticInvalidMultiPolygonRelationMembersRemovedTag.KEY).isEmpty()); Assert.assertEquals(0, lbrSlicedAtlas.numberOfPoints()); Assert.assertEquals(0, lbrSlicedAtlas.numberOfLines()); Assert.assertEquals(2, lbrSlicedAtlas.numberOfAreas()); Assert.assertEquals(1, lbrSlicedAtlas.numberOfRelations()); Assert.assertEquals("CIV,LBR", lbrSlicedAtlas.area(108768000000L).getTag(ISOCountryTag.KEY).get()); Assert.assertEquals(rawAtlas.area(108768000000L).asPolygon(), lbrSlicedAtlas.area(108768000000L).asPolygon()); Assert.assertEquals("CIV,LBR", lbrSlicedAtlas.relation(1).getTag(ISOCountryTag.KEY).get()); Assert.assertTrue( lbrSlicedAtlas.relation(1).getTag(SyntheticGeometrySlicedTag.KEY).isEmpty()); Assert.assertTrue( lbrSlicedAtlas.relation(1).getTag(SyntheticRelationMemberAdded.KEY).isEmpty()); Assert.assertTrue(lbrSlicedAtlas.relation(1) .getTag(SyntheticInvalidMultiPolygonRelationMembersRemovedTag.KEY).isEmpty()); } /** * This relation is made up of two lines. Both lines are on the LBR side. The first is a closed * line, with an inner role. The second is a self-intersecting closed outer. We expect no * slicing or merging to take place, other than country code assignment. The line with invalid * geometry will get tagged as CIV,LBR due to a quirk in geometry polygon handling, but this is * not very concerning as invalid geometry is not expected to be fully supported by slicing-- * the country codes here are a best guess. */ @Test public void testSelfIntersectingOuterRelationInOneCountry() { final Atlas rawAtlas = this.setup.getSelfIntersectingOuterMemberRelationAtlas(); final Atlas lbrSlicedAtlas = new RawAtlasSlicer( AtlasLoadingOption.createOptionWithAllEnabled(boundary).setCountryCode("LBR"), rawAtlas).slice(); // Assert that we CAN build a valid building with this relation new ComplexBuildingFinder().find(lbrSlicedAtlas) .forEach(building -> Assert.assertFalse(building.getError().isPresent())); Assert.assertEquals(0, lbrSlicedAtlas.numberOfPoints()); Assert.assertEquals(rawAtlas.numberOfLines(), lbrSlicedAtlas.numberOfLines()); Assert.assertEquals(rawAtlas.numberOfRelations(), lbrSlicedAtlas.numberOfRelations()); Assert.assertTrue(Iterables.stream(lbrSlicedAtlas.entities()) .allMatch(entity -> (entity.getTag(ISOCountryTag.KEY).get().equals("LBR") || entity.getTag(ISOCountryTag.KEY).get().equals("CIV,LBR")) && entity.getTag(SyntheticGeometrySlicedTag.KEY).isEmpty())); } /** * This relation is made up of two closed lines, forming a multi-polygon with one inner and one * outer, both spanning the boundary of two countries. */ @Test public void testSimpleMultiPolygonWithHoleSpanningTwoCountries() { final Atlas rawAtlas = this.setup.getSimpleMultiPolygonWithHoleAtlas(); final Atlas civSlicedAtlas = new RawAtlasSlicer( AtlasLoadingOption.createOptionWithAllEnabled(boundary).setCountryCode("CIV"), rawAtlas).slice(); final Atlas lbrSlicedAtlas = new RawAtlasSlicer( AtlasLoadingOption.createOptionWithAllEnabled(boundary).setCountryCode("LBR"), rawAtlas).slice(); Assert.assertEquals(0, civSlicedAtlas.numberOfPoints()); Assert.assertEquals(4, civSlicedAtlas.numberOfLines()); Assert.assertEquals(2, civSlicedAtlas.numberOfAreas()); Assert.assertEquals(1, civSlicedAtlas.numberOfRelations()); final Iterable<ComplexBuilding> civBuildings = new ComplexBuildingFinder() .find(civSlicedAtlas, Finder::ignore); Assert.assertEquals(1, Iterables.size(civBuildings)); Assert.assertEquals(0, lbrSlicedAtlas.numberOfPoints()); Assert.assertEquals(4, lbrSlicedAtlas.numberOfLines()); Assert.assertEquals(2, lbrSlicedAtlas.numberOfAreas()); Assert.assertEquals(1, lbrSlicedAtlas.numberOfRelations()); final Iterable<ComplexBuilding> lbrBuildings = new ComplexBuildingFinder() .find(lbrSlicedAtlas, Finder::ignore); Assert.assertEquals(1, Iterables.size(lbrBuildings)); final SortedSet<String> civSyntheticRelationMembers = new TreeSet<>(); civSlicedAtlas.lines().forEach(line -> { if (line.getTag(SyntheticGeometrySlicedTag.KEY).isPresent()) { final Area rawArea = rawAtlas.areas(rawAreaCandidate -> rawAreaCandidate .getOsmIdentifier() == line.getOsmIdentifier()).iterator().next(); Assert.assertEquals(rawArea.getOsmTags(), line.getOsmTags()); Assert.assertEquals(1, line.relations().size()); } else { Assert.assertTrue(line.getTag(SyntheticSyntheticRelationMemberTag.KEY).isPresent()); civSyntheticRelationMembers.add(Long.toString(line.getIdentifier())); } }); final SortedSet<String> lbrSyntheticRelationMembers = new TreeSet<>(); lbrSlicedAtlas.lines().forEach(line -> { if (line.getTag(SyntheticGeometrySlicedTag.KEY).isPresent()) { final Area rawArea = rawAtlas.areas(rawAreaCandidate -> rawAreaCandidate .getOsmIdentifier() == line.getOsmIdentifier()).iterator().next(); Assert.assertEquals(rawArea.getOsmTags(), line.getOsmTags()); Assert.assertEquals(1, line.relations().size()); } else if (rawAtlas.line(line.getIdentifier()) != null) { Assert.assertEquals(rawAtlas.line(line.getIdentifier()).getOsmTags(), line.getOsmTags()); Assert.assertEquals(rawAtlas.line(line.getIdentifier()).asPolyLine(), line.asPolyLine()); Assert.assertEquals(1, line.relations().size()); } else { Assert.assertTrue(line.getTag(SyntheticSyntheticRelationMemberTag.KEY).isPresent()); lbrSyntheticRelationMembers.add(Long.toString(line.getIdentifier())); } }); final CountrySlicingIdentifierFactory relationIdentifierFactory = new CountrySlicingIdentifierFactory( 0L); final Relation civRelation = civSlicedAtlas .relation(relationIdentifierFactory.nextIdentifier()); final Relation lbrRelation = lbrSlicedAtlas .relation(relationIdentifierFactory.nextIdentifier()); Assert.assertEquals("CIV", civRelation.getTag(ISOCountryTag.KEY).get()); Assert.assertEquals(SyntheticGeometrySlicedTag.YES.toString(), civRelation.getTag(SyntheticGeometrySlicedTag.KEY).get()); Assert.assertEquals( String.join(SyntheticRelationMemberAdded.MEMBER_DELIMITER, civSyntheticRelationMembers), civRelation.getTag(SyntheticRelationMemberAdded.KEY).get()); Assert.assertTrue(civRelation .getTag(SyntheticInvalidMultiPolygonRelationMembersRemovedTag.KEY).isEmpty()); Assert.assertEquals("LBR", lbrRelation.getTag(ISOCountryTag.KEY).get()); Assert.assertEquals(SyntheticGeometrySlicedTag.YES.toString(), lbrRelation.getTag(SyntheticGeometrySlicedTag.KEY).get()); Assert.assertEquals( String.join(SyntheticRelationMemberAdded.MEMBER_DELIMITER, lbrSyntheticRelationMembers), lbrRelation.getTag(SyntheticRelationMemberAdded.KEY).get()); Assert.assertTrue(lbrRelation .getTag(SyntheticInvalidMultiPolygonRelationMembersRemovedTag.KEY).isEmpty()); } /** * This simple test covers the case of a line with invalid geometry due to only having one node, * repeated */ @Test public void testSingleNodeLine() { final Atlas rawAtlas = this.setup.getSingleNodeLine(); final Atlas lbrSlicedAtlas = new RawAtlasSlicer( AtlasLoadingOption.createOptionWithAllEnabled(boundary).setCountryCode("LBR"), rawAtlas).slice(); Assert.assertEquals(0, lbrSlicedAtlas.numberOfPoints()); Assert.assertEquals(2, lbrSlicedAtlas.numberOfLines()); Assert.assertEquals(0, lbrSlicedAtlas.numberOfAreas()); Assert.assertEquals(0, lbrSlicedAtlas.numberOfRelations()); Assert.assertTrue(Iterables.stream(lbrSlicedAtlas.entities()) .allMatch(entity -> (entity.getTag(ISOCountryTag.KEY).get().equals("LBR") || entity.getTag(ISOCountryTag.KEY).get().equals("CIV,LBR")) && entity.getTag(SyntheticGeometrySlicedTag.KEY).isEmpty())); } /** * This relation is made up of two open lines, both Edges, both crossing the country boundary * and forming a multipolygon with one outer. */ @Test public void testSingleOuterMadeOfOpenLinesSpanningTwoCountries() { final Atlas rawAtlas = this.setup.getSingleOuterMadeOfOpenLinesSpanningTwoCountriesAtlas(); final Atlas civSlicedAtlas = new RawAtlasSlicer( AtlasLoadingOption.createOptionWithAllEnabled(boundary).setCountryCode("CIV"), rawAtlas).slice(); final Atlas lbrSlicedAtlas = new RawAtlasSlicer( AtlasLoadingOption.createOptionWithAllEnabled(boundary).setCountryCode("LBR"), rawAtlas).slice(); Assert.assertEquals(3, civSlicedAtlas.numberOfPoints()); Assert.assertEquals(3, civSlicedAtlas.numberOfLines()); Assert.assertEquals(0, civSlicedAtlas.numberOfAreas()); Assert.assertEquals(1, civSlicedAtlas.numberOfRelations()); Assert.assertEquals(8, lbrSlicedAtlas.numberOfPoints()); Assert.assertEquals(3, lbrSlicedAtlas.numberOfLines()); Assert.assertEquals(0, lbrSlicedAtlas.numberOfAreas()); Assert.assertEquals(1, lbrSlicedAtlas.numberOfRelations()); final SortedSet<String> civSyntheticRelationMembers = new TreeSet<>(); civSlicedAtlas.lines().forEach(line -> { if (line.getTag(SyntheticGeometrySlicedTag.KEY).isPresent()) { final Line rawLine = rawAtlas.lines(rawLineCandidate -> rawLineCandidate .getOsmIdentifier() == line.getOsmIdentifier()).iterator().next(); Assert.assertEquals(rawLine.getOsmTags(), line.getOsmTags()); Assert.assertEquals(1, line.relations().size()); } else { Assert.assertTrue(line.getTag(SyntheticSyntheticRelationMemberTag.KEY).isPresent()); civSyntheticRelationMembers.add(Long.toString(line.getIdentifier())); } }); final SortedSet<String> lbrSyntheticRelationMembers = new TreeSet<>(); lbrSlicedAtlas.lines().forEach(line -> { if (line.getTag(SyntheticGeometrySlicedTag.KEY).isPresent()) { final Line rawLine = rawAtlas.lines(rawLineCandidate -> rawLineCandidate .getOsmIdentifier() == line.getOsmIdentifier()).iterator().next(); Assert.assertEquals(rawLine.getOsmTags(), line.getOsmTags()); Assert.assertEquals(1, line.relations().size()); } else if (rawAtlas.line(line.getIdentifier()) != null) { Assert.assertEquals(rawAtlas.line(line.getIdentifier()).getOsmTags(), line.getOsmTags()); Assert.assertEquals(rawAtlas.line(line.getIdentifier()).asPolyLine(), line.asPolyLine()); Assert.assertEquals(1, line.relations().size()); } else { Assert.assertTrue(line.getTag(SyntheticSyntheticRelationMemberTag.KEY).isPresent()); lbrSyntheticRelationMembers.add(Long.toString(line.getIdentifier())); } }); final CountrySlicingIdentifierFactory relationIdentifierFactory = new CountrySlicingIdentifierFactory( 214805000000L); final Relation civRelation = civSlicedAtlas .relation(relationIdentifierFactory.nextIdentifier()); Assert.assertTrue(jtsConverter.backwardConvert(converter.convert(civRelation)).isValid()); Assert.assertEquals("CIV", civRelation.getTag(ISOCountryTag.KEY).get()); Assert.assertEquals(SyntheticGeometrySlicedTag.YES.toString(), civRelation.getTag(SyntheticGeometrySlicedTag.KEY).get()); Assert.assertEquals( String.join(SyntheticRelationMemberAdded.MEMBER_DELIMITER, civSyntheticRelationMembers), civRelation.getTag(SyntheticRelationMemberAdded.KEY).get()); Assert.assertTrue(civRelation .getTag(SyntheticInvalidMultiPolygonRelationMembersRemovedTag.KEY).isEmpty()); final Relation lbrRelation = lbrSlicedAtlas .relation(relationIdentifierFactory.nextIdentifier()); Assert.assertTrue(jtsConverter.backwardConvert(converter.convert(lbrRelation)).isValid()); Assert.assertEquals("LBR", lbrRelation.getTag(ISOCountryTag.KEY).get()); Assert.assertEquals(SyntheticGeometrySlicedTag.YES.toString(), lbrRelation.getTag(SyntheticGeometrySlicedTag.KEY).get()); Assert.assertEquals( String.join(SyntheticRelationMemberAdded.MEMBER_DELIMITER, lbrSyntheticRelationMembers), lbrRelation.getTag(SyntheticRelationMemberAdded.KEY).get()); Assert.assertTrue(lbrRelation .getTag(SyntheticInvalidMultiPolygonRelationMembersRemovedTag.KEY).isEmpty()); } /** * This relation is made up of two open lines, both crossing the country boundary and forming a * multipolygon with one outer. */ @Test public void testSingleOuterMadeOfOpenLinesSpanningTwoCountriesWithDuplicatePoints() { final Atlas rawAtlas = this.setup .getSingleOuterMadeOfOpenLinesSpanningTwoCountriesAtlasWithDuplicatePoints(); final Atlas civSlicedAtlas = new RawAtlasSlicer( AtlasLoadingOption.createOptionWithAllEnabled(boundary).setCountryCode("CIV"), rawAtlas).slice(); final Atlas lbrSlicedAtlas = new RawAtlasSlicer( AtlasLoadingOption.createOptionWithAllEnabled(boundary).setCountryCode("LBR"), rawAtlas).slice(); Assert.assertEquals(3, civSlicedAtlas.numberOfPoints()); Assert.assertEquals(3, civSlicedAtlas.numberOfLines()); Assert.assertEquals(0, civSlicedAtlas.numberOfAreas()); Assert.assertEquals(1, civSlicedAtlas.numberOfRelations()); Assert.assertEquals(8, lbrSlicedAtlas.numberOfPoints()); Assert.assertEquals(3, lbrSlicedAtlas.numberOfLines()); Assert.assertEquals(0, lbrSlicedAtlas.numberOfAreas()); Assert.assertEquals(1, lbrSlicedAtlas.numberOfRelations()); final SortedSet<String> civSyntheticRelationMembers = new TreeSet<>(); civSlicedAtlas.lines().forEach(line -> { final Iterator<Location> lineLocations = line.iterator(); Location previous = lineLocations.next(); while (lineLocations.hasNext()) { final Location current = lineLocations.next(); Assert.assertNotEquals(current, previous); previous = current; } if (line.getTag(SyntheticGeometrySlicedTag.KEY).isPresent()) { final Line rawLine = rawAtlas.lines(rawLineCandidate -> rawLineCandidate .getOsmIdentifier() == line.getOsmIdentifier()).iterator().next(); Assert.assertEquals(rawLine.getOsmTags(), line.getOsmTags()); Assert.assertEquals(1, line.relations().size()); } else { Assert.assertTrue(line.getTag(SyntheticSyntheticRelationMemberTag.KEY).isPresent()); civSyntheticRelationMembers.add(Long.toString(line.getIdentifier())); } }); final SortedSet<String> lbrSyntheticRelationMembers = new TreeSet<>(); lbrSlicedAtlas.lines().forEach(line -> { final Iterator<Location> lineLocations = line.iterator(); Location previous = lineLocations.next(); while (lineLocations.hasNext()) { final Location current = lineLocations.next(); Assert.assertNotEquals(current, previous); previous = current; } if (line.getTag(SyntheticGeometrySlicedTag.KEY).isPresent()) { final Line rawLine = rawAtlas.lines(rawLineCandidate -> rawLineCandidate .getOsmIdentifier() == line.getOsmIdentifier()).iterator().next(); Assert.assertEquals(rawLine.getOsmTags(), line.getOsmTags()); Assert.assertEquals(1, line.relations().size()); } else if (rawAtlas.line(line.getIdentifier()) != null) { Assert.assertEquals(rawAtlas.line(line.getIdentifier()).getOsmTags(), line.getOsmTags()); Assert.assertEquals(rawAtlas.line(line.getIdentifier()).asPolyLine(), line.asPolyLine()); Assert.assertEquals(1, line.relations().size()); } else { Assert.assertTrue(line.getTag(SyntheticSyntheticRelationMemberTag.KEY).isPresent()); lbrSyntheticRelationMembers.add(Long.toString(line.getIdentifier())); } }); final CountrySlicingIdentifierFactory relationIdentifierFactory = new CountrySlicingIdentifierFactory( 214805000000L); final Relation civRelation = civSlicedAtlas .relation(relationIdentifierFactory.nextIdentifier()); Assert.assertTrue(jtsConverter.backwardConvert(converter.convert(civRelation)).isValid()); Assert.assertEquals("CIV", civRelation.getTag(ISOCountryTag.KEY).get()); Assert.assertEquals(SyntheticGeometrySlicedTag.YES.toString(), civRelation.getTag(SyntheticGeometrySlicedTag.KEY).get()); Assert.assertEquals( String.join(SyntheticRelationMemberAdded.MEMBER_DELIMITER, civSyntheticRelationMembers), civRelation.getTag(SyntheticRelationMemberAdded.KEY).get()); Assert.assertTrue(civRelation .getTag(SyntheticInvalidMultiPolygonRelationMembersRemovedTag.KEY).isEmpty()); final Relation lbrRelation = lbrSlicedAtlas .relation(relationIdentifierFactory.nextIdentifier()); Assert.assertTrue(jtsConverter.backwardConvert(converter.convert(lbrRelation)).isValid()); Assert.assertEquals("LBR", lbrRelation.getTag(ISOCountryTag.KEY).get()); Assert.assertEquals(SyntheticGeometrySlicedTag.YES.toString(), lbrRelation.getTag(SyntheticGeometrySlicedTag.KEY).get()); Assert.assertEquals( String.join(SyntheticRelationMemberAdded.MEMBER_DELIMITER, lbrSyntheticRelationMembers), lbrRelation.getTag(SyntheticRelationMemberAdded.KEY).get()); Assert.assertTrue(lbrRelation .getTag(SyntheticInvalidMultiPolygonRelationMembersRemovedTag.KEY).isEmpty()); } @Test public void testSlicingOnRelationWithOnlyRelationsAsMembers() { final Atlas rawAtlas = this.setup.getRelationWithOnlyRelationsAsMembers(); final Atlas lbrSlicedAtlas = new RawAtlasSlicer( AtlasLoadingOption.createOptionWithAllEnabled(boundary).setCountryCode("LBR"), rawAtlas).slice(); for (final Relation relation : lbrSlicedAtlas.relations()) { Assert.assertEquals("LBR", relation.getTag(ISOCountryTag.KEY).get()); } } }
Java
@SuppressWarnings({"checkstyle:ClassDataAbstractionCoupling", "ClassFanOutComplexity"}) public class CreateExecPlanNodeVisitor implements PlanNodeVisitor { /** Operation handler. */ private final QueryOperationHandler operationHandler; /** Node service provider. */ private final NodeServiceProvider nodeServiceProvider; /** Serialization service. */ private final InternalSerializationService serializationService; /** Local member ID. */ private final UUID localMemberId; /** Operation. */ private final QueryExecuteOperation operation; /** Factory to create flow control objects. */ private final FlowControlFactory flowControlFactory; /** Partitions owned by this data node. */ private final PartitionIdSet localParts; /** Recommended outbox batch size in bytes. */ private final int outboxBatchSize; /** Hook to alter produced Exec (for testing purposes). */ private final CreateExecPlanNodeVisitorHook hook; /** Stack of elements to be merged. */ private final ArrayList<Exec> stack = new ArrayList<>(1); /** Result. */ private Exec exec; /** Inboxes. */ private final Map<Integer, InboundHandler> inboxes = new HashMap<>(); /** Outboxes. */ private final Map<Integer, Map<UUID, OutboundHandler>> outboxes = new HashMap<>(); public CreateExecPlanNodeVisitor( QueryOperationHandler operationHandler, NodeServiceProvider nodeServiceProvider, InternalSerializationService serializationService, UUID localMemberId, QueryExecuteOperation operation, FlowControlFactory flowControlFactory, PartitionIdSet localParts, int outboxBatchSize, CreateExecPlanNodeVisitorHook hook ) { this.operationHandler = operationHandler; this.nodeServiceProvider = nodeServiceProvider; this.serializationService = serializationService; this.localMemberId = localMemberId; this.operation = operation; this.flowControlFactory = flowControlFactory; this.localParts = localParts; this.outboxBatchSize = outboxBatchSize; this.hook = hook; } @Override public void onRootNode(RootPlanNode node) { assert stack.size() == 1; exec = new RootExec( node.getId(), pop(), operation.getRootConsumer(), operation.getRootBatchSize() ); } @Override public void onReceiveNode(ReceivePlanNode node) { // Navigate to sender exec and calculate total number of sender stripes. int edgeId = node.getEdgeId(); int sendFragmentPos = operation.getOutboundEdgeMap().get(edgeId); QueryExecuteOperationFragment sendFragment = operation.getFragments().get(sendFragmentPos); int fragmentMemberCount = getFragmentMembers(sendFragment).size(); // Create and register inbox. Inbox inbox = new Inbox( operationHandler, operation.getQueryId(), edgeId, node.getSchema().getEstimatedRowSize(), localMemberId, fragmentMemberCount, createFlowControl(edgeId) ); inboxes.put(edgeId, inbox); // Instantiate executor and put it to stack. ReceiveExec res = new ReceiveExec(node.getId(), inbox); push(res); } @Override public void onReceiveSortMergeNode(ReceiveSortMergePlanNode node) { // Navigate to sender exec and calculate total number of sender stripes. int edgeId = node.getEdgeId(); // Create and register inbox. int sendFragmentPos = operation.getOutboundEdgeMap().get(edgeId); QueryExecuteOperationFragment sendFragment = operation.getFragments().get(sendFragmentPos); StripedInbox inbox = new StripedInbox( operationHandler, operation.getQueryId(), edgeId, node.getSchema().getEstimatedRowSize(), localMemberId, getFragmentMembers(sendFragment), createFlowControl(edgeId) ); inboxes.put(edgeId, inbox); // Instantiate executor and put it to stack. ReceiveSortMergeExec res = new ReceiveSortMergeExec( node.getId(), inbox, node.getExpressions(), node.getAscs(), node.getFetch(), node.getOffset() ); push(res); } @Override public void onRootSendNode(RootSendPlanNode node) { Outbox[] outboxes = prepareOutboxes(node); assert outboxes.length == 1; exec = new SendExec(node.getId(), pop(), outboxes[0]); } @Override public void onUnicastSendNode(UnicastSendPlanNode node) { Outbox[] outboxes = prepareOutboxes(node); if (outboxes.length == 1) { exec = new SendExec(node.getId(), pop(), outboxes[0]); } else { int[] partitionOutboxIndexes = new int[localParts.getPartitionCount()]; for (int outboxIndex = 0; outboxIndex < outboxes.length; outboxIndex++) { final int outboxIndex0 = outboxIndex; PartitionIdSet partitions = operation.getPartitionMap().get(outboxes[outboxIndex0].getTargetMemberId()); partitions.forEach((part) -> partitionOutboxIndexes[part] = outboxIndex0); } exec = new UnicastSendExec( node.getId(), pop(), outboxes, node.getPartitioner(), partitionOutboxIndexes, serializationService ); } } @Override public void onBroadcastSendNode(BroadcastSendPlanNode node) { Outbox[] outboxes = prepareOutboxes(node); if (outboxes.length == 1) { exec = new SendExec(node.getId(), pop(), outboxes[0]); } else { exec = new BroadcastSendExec(node.getId(), pop(), outboxes); } } /** * Prepare outboxes for the given sender node. * * @param node Node. * @return Outboxes. */ private Outbox[] prepareOutboxes(EdgeAwarePlanNode node) { int edgeId = node.getEdgeId(); int rowWidth = node.getSchema().getEstimatedRowSize(); int receiveFragmentPos = operation.getInboundEdgeMap().get(edgeId); QueryExecuteOperationFragment receiveFragment = operation.getFragments().get(receiveFragmentPos); Collection<UUID> receiveFragmentMemberIds = getFragmentMembers(receiveFragment); Outbox[] res = new Outbox[receiveFragmentMemberIds.size()]; int i = 0; Map<UUID, OutboundHandler> edgeOutboxes = new HashMap<>(); outboxes.put(edgeId, edgeOutboxes); for (UUID receiveMemberId : receiveFragmentMemberIds) { Outbox outbox = new Outbox( operationHandler, operation.getQueryId(), edgeId, rowWidth, localMemberId, receiveMemberId, outboxBatchSize, operation.getEdgeInitialMemoryMap().get(edgeId) ); edgeOutboxes.put(receiveMemberId, outbox); res[i++] = outbox; } return res; } @Override public void onProjectNode(ProjectPlanNode node) { Exec res = new ProjectExec( node.getId(), pop(), node.getProjects() ); push(res); } @Override public void onFilterNode(FilterPlanNode node) { Exec res = new FilterExec( node.getId(), pop(), node.getFilter() ); push(res); } @Override public void onEmptyNode(EmptyPlanNode node) { Exec res = new EmptyExec( node.getId() ); push(res); } @Override public void onMapScanNode(MapScanPlanNode node) { Exec res; if (localParts.isEmpty()) { res = new EmptyExec(node.getId()); } else { String mapName = node.getMapName(); MapContainer map = nodeServiceProvider.getMap(mapName); if (map == null) { res = new EmptyExec(node.getId()); } else { res = new MapScanExec( node.getId(), map, localParts, node.getKeyDescriptor(), node.getValueDescriptor(), node.getFieldPaths(), node.getFieldTypes(), node.getProjects(), node.getFilter(), serializationService ); } } push(res); } @Override public void onMapIndexScanNode(MapIndexScanPlanNode node) { Exec res; if (localParts.isEmpty()) { res = new EmptyExec(node.getId()); } else { String mapName = node.getMapName(); MapContainer map = nodeServiceProvider.getMap(mapName); if (map == null) { res = new EmptyExec(node.getId()); } else { res = new MapIndexScanExec( node.getId(), map, localParts, node.getKeyDescriptor(), node.getValueDescriptor(), node.getFieldPaths(), node.getFieldTypes(), node.getProjects(), node.getFilter(), serializationService, node.getIndexName(), node.getIndexComponentCount(), node.getIndexFilter(), node.getConverterTypes() ); } } push(res); } @Override public void onReplicatedMapScanNode(ReplicatedMapScanPlanNode node) { String mapName = node.getMapName(); ReplicatedMapProxy<?, ?> map = nodeServiceProvider.getReplicatedMap(mapName); Exec res = new ReplicatedMapScanExec( node.getId(), map, node.getKeyDescriptor(), node.getValueDescriptor(), node.getFieldPaths(), node.getFieldTypes(), node.getProjects(), node.getFilter(), serializationService ); push(res); } @Override public void onSortNode(SortPlanNode node) { Exec res = new SortExec( node.getId(), pop(), node.getExpressions(), node.getAscs(), node.getFetch(), node.getOffset() ); push(res); } @Override public void onAggregateNode(AggregatePlanNode node) { Exec res = new AggregateExec( node.getId(), pop(), node.getGroupKey(), node.getExpressions(), node.getSortedGroupKeySize() ); push(res); } @Override public void onNestedLoopJoinNode(NestedLoopJoinPlanNode node) { Exec res = new NestedLoopJoinExec( node.getId(), pop(), pop(), node.getCondition(), node.isOuter(), node.isSemi(), node.getRightRowColumnCount() ); push(res); } @Override public void onHashJoinNode(HashJoinPlanNode node) { Exec res = new HashJoinExec( node.getId(), pop(), pop(), node.getCondition(), node.getLeftHashKeys(), node.getRightHashKeys(), node.isOuter(), node.isSemi(), node.getRightRowColumnCount() ); push(res); } @Override public void onMaterializedInputNode(MaterializedInputPlanNode node) { Exec upstream = pop(); MaterializedInputExec res = new MaterializedInputExec( node.getId(), upstream ); push(res); } @Override public void onReplicatedToPartitionedNode(ReplicatedToPartitionedPlanNode node) { Exec upstream = pop(); Exec res; if (localParts.isEmpty()) { res = new EmptyExec(node.getId()); } else { res = new ReplicatedToPartitionedExec( node.getId(), upstream, node.getPartitioner(), localParts, serializationService ); } push(res); } @Override public void onFetchNode(FetchPlanNode node) { Exec upstream = pop(); FetchExec res = new FetchExec( node.getId(), upstream, node.getFetch(), node.getOffset() ); push(res); } @Override public void onOtherNode(PlanNode node) { if (node instanceof CreateExecPlanNodeVisitorCallback) { ((CreateExecPlanNodeVisitorCallback) node).onVisit(this); } else { throw new UnsupportedOperationException("Unsupported node: " + node); } } public Exec getExec() { return exec; } /** * For testing only. */ public void setExec(Exec exec) { this.exec = exec; } public Map<Integer, InboundHandler> getInboxes() { return inboxes; } public Map<Integer, Map<UUID, OutboundHandler>> getOutboxes() { return outboxes; } /** * Public for testing purposes only. */ public Exec pop() { return stack.remove(stack.size() - 1); } /** * Public for testing purposes only. */ public void push(Exec exec) { CreateExecPlanNodeVisitorHook hook0 = hook; if (hook0 != null) { exec = hook0.onExec(exec); } stack.add(exec); } private FlowControl createFlowControl(int edgeId) { long initialMemory = operation.getEdgeInitialMemoryMap().get(edgeId); return flowControlFactory.create(initialMemory); } private Collection<UUID> getFragmentMembers(QueryExecuteOperationFragment fragment) { if (fragment.getMapping() == QueryExecuteOperationFragmentMapping.EXPLICIT) { return fragment.getMemberIds(); } assert fragment.getMapping() == QueryExecuteOperationFragmentMapping.DATA_MEMBERS; return operation.getPartitionMap().keySet(); } }
Java
public class SimpleTableReq { private Map<String, String> queryMap = new HashMap<String, String>();// 条件查询 /** * Gets query map. * * @return the query map */ public Map<String, String> getQueryMap() { return queryMap; } /** * Sets query map. * * @param queryMap the query map */ public void setQueryMap(Map<String, String> queryMap) { this.queryMap = queryMap; } }
Java
public class TwitterRouteBuilderCamelTest extends SourceRouteBuilderBaseCamelTest<TwitterRouteBuilder> { public TwitterRouteBuilderCamelTest() { super(TwitterRouteBuilder.class); // TimeZone.setDefault(TimeZone.getTimeZone("PST")); disableDateHeaderTest = true; } @Test public void testTwitterRoute() throws Exception { launchContext(); await().untilCall(to(messages).size(), is(greaterThanOrEqualTo(1))); assertThat(messages, hasSize(1)); assertThat(messages.get(0), is(getFirstMsgBody())); } // --- @Override protected String getFirstMsgBody() { // computing timezone in under to allow the test to run in remote CI server (which is in another timezone) String timezone = TimeZone.getDefault().getDisplayName(false, TimeZone.SHORT, Locale.US); // From Date.toString() ... return "Sat Jan 05 12:34:00 " + timezone + " 2013 (ippontech) a first tweet"; } @Override protected void launchContext() throws Exception { // we replace the input (twitter connector) of the route with a "direct" endpoint : String routeDefId = "twitter-ippon.fr"; context.getRouteDefinition(routeDefId).adviceWith(context, new AdviceWithRouteBuilder() { @Override public void configure() throws Exception { replaceFromWith("direct:twitterRouteTest"); } }); context.start(); // necessary because of isUseAdviceWith=true simulateInputMessage(); } private void simulateInputMessage() throws ParseException { Status fakeStatus = fakeTwitterStatus("2013/01/05 12:34", "ippontech", "a first tweet"); template.sendBody("direct:twitterRouteTest", fakeStatus); } private Status fakeTwitterStatus(String createdAtAsStr, String screenName, String text) throws ParseException { // cf {@link TwitterConverter.toString} : we only need date, user and text at the moment User user = mock(User.class); when(user.getScreenName()).thenReturn(screenName); Status status = mock(Status.class); Date createdAt = new SimpleDateFormat("yyyy/MM/dd HH:mm").parse(createdAtAsStr); when(status.getUser()).thenReturn(user); when(status.getCreatedAt()).thenReturn(createdAt); when(status.getText()).thenReturn(text); return status; } @Override protected TatamibotConfiguration getBotConfiguration() { TatamibotConfiguration configuration = new TatamibotConfiguration(); configuration.setTatamibotConfigurationId("TEST_CONFIG_ID"); configuration.setType(TatamibotConfiguration.TatamibotType.TWITTER); configuration.setDomain("ippon.fr"); // configuration.setUrl("??"); configuration.setPollingDelay(60); // not used here configuration.setLastUpdateDate(DateTime.parse("2010-01-01T00:00:00").toDate()); return configuration; } }
Java
public class BaseConversationMessage extends LinearLayout { private String IMAGE_CACHE_DIR = "message_icons"; private final String myName = "Me"; private final String friendName = "Jane"; /** * Constructor for conversation message * @param context current context * @param message message to be constructed * @param user current user */ public BaseConversationMessage( Context context, ConversationMessage message, User user) { super(context); init(context, message, user); } /** * Initialize the layout of conversation message * @param context current context * @param message message to be initialized * @param user current user */ public void init(Context context, ConversationMessage message, User user) { LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view; if (message.getIsIncomingMessage()) { view = inflater.inflate(R.layout.conversation_message_style1, null); Friend friend = message.getConversation().getFriend(); if (friend != null) { TextView name = (TextView) view.findViewById(R.id.name); name.setText(friend.getName()); // friendName ImageView icon = (ImageView) view.findViewById(R.id.icon); CommunicatorActivity activity = (CommunicatorActivity) context; String iconAddress = friend.getIconAddress(); if (iconAddress == null || iconAddress.length() == 0) { Bitmap bitmap = BitmapUtils.decodeSampledBitmapFromResource(getResources(), R.drawable.default_avatar, icon.getLayoutParams().width, icon.getLayoutParams().height); icon.setImageBitmap(bitmap); } else { ImageDownloader imageDownloader = activity.getImageDownloader(); if (imageDownloader != null) { imageDownloader.download(iconAddress,R.drawable.avatar, icon.getLayoutParams().width, icon.getLayoutParams().height, icon); } } } } else { view = inflater.inflate(R.layout.conversation_message_style2, null); TextView name = (TextView) view.findViewById(R.id.name); name.setText(myName); if (user != null) { ImageView icon = (ImageView) view.findViewById(R.id.icon); CommunicatorActivity activity = (CommunicatorActivity) context; String iconAddress = user.getIconAddress(); if (iconAddress == null || iconAddress.length() == 0) { Bitmap bitmap = BitmapUtils.decodeSampledBitmapFromResource(getResources(), R.drawable.default_avatar, icon.getLayoutParams().width, icon.getLayoutParams().height); icon.setImageBitmap(bitmap); } else { ImageDownloader imageDownloader = activity.getImageDownloader(); if (imageDownloader != null) { imageDownloader.download(iconAddress, R.drawable.avatar, icon.getLayoutParams().width, icon.getLayoutParams().height, icon); } } } } ConversationTextView content = (ConversationTextView) view.findViewById(R.id.message); content.setText(message.getContent()); addView(view); } }
Java
class MBeanRegistrar { private static final String JMX_OBJECT_NAME_PREFIX = "org.jeasy.props:"; private static final Logger LOGGER = LoggerFactory.getLogger(MBeanRegistrar.class); private final MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer(); void registerMBeanFor(final Object object) { if (shouldBeManaged(object)) { Manageable manageable = object.getClass().getAnnotation(Manageable.class); String name = manageable.name().trim().isEmpty() ? object.getClass().getName() : manageable.name(); ObjectName objectName; try { objectName = new ObjectName(JMX_OBJECT_NAME_PREFIX + "name=" + name); if (!mBeanServer.isRegistered(objectName)) { mBeanServer.registerMBean(object, objectName); } } catch (Exception e) { LOGGER.error("Unable to register a JMX MBean for object '" + object + "'", e); } } } private boolean shouldBeManaged(Object object) { return object.getClass().isAnnotationPresent(Manageable.class); } }
Java
public class MarkLogicWriter implements Writer{ private static final Logger logger = LoggerFactory.getLogger(MarkLogicWriter.class); private static final ObjectMapper MAPPER = new ObjectMapper(); private static final String URL = "url"; private final JSONDocumentManager manager; protected final DatabaseClient client; public MarkLogicWriter(final Map<String, String> config){ client = DatabaseClientFactory.newClient(config.get(MarkLogicSinkConfig.CONNECTION_HOST), Integer.valueOf(config.get(MarkLogicSinkConfig.CONNECTION_PORT)), new DigestAuthContext(config.get(MarkLogicSinkConfig.CONNECTION_USER), config.get(MarkLogicSinkConfig.CONNECTION_PASSWORD))); manager = client.newJSONDocumentManager(); } public void write(final Collection<SinkRecord> recrods){ recrods.forEach(r -> { logger.debug("received value {}, and collection {}", r.value(), r.topic()); final Map<?, ?> v = new LinkedHashMap<>((Map<?,?>) r.value()); try { manager.write(url(v), handle(v)); } catch (Exception e) { logger.error(e.getMessage(), e); throw new RuntimeException(e); } }); } protected String url(final Map<?, ?> valueMap ){ return valueMap.get(URL) == null ? UUID.randomUUID().toString() : valueMap.remove(URL).toString(); } protected JacksonHandle handle(final Map<?, ?> valueMap ){ return new JacksonHandle(MAPPER.convertValue(valueMap, JsonNode.class)); } }
Java
public class JsonbGeometryAdapter implements JsonbAdapter<Geometry, String> { private static final Logger LOG = Logger.getLogger(JsonbGeometryAdapter.class.getName()); /** * {@inheritDoc} Important. Must specify a 3D WKT Writer to output the * Z-component of the geometry. "toString()" and the default WKTWriter are * 2-dimensional and do not output the Z-component. */ @Override public String adaptToJson(Geometry obj) throws Exception { return new WKTWriter(3).write(obj); } /** * {@inheritDoc} */ @Override public Geometry adaptFromJson(String obj) throws Exception { try { return new WKTReader().read(obj); } catch (ParseException ex) { LOG.log(Level.WARNING, "WKT geometry parse error {0}. {1}", new Object[]{ex.getMessage(), obj}); return null; } } }
Java
public class LogentriesAppender extends AppenderSkeleton { /* * Fields */ /** Asynchronous Background logger */ AsyncLogger le_async; public LogentriesAppender() { le_async = new AsyncLogger(); } /* * Public methods to send log4j parameters to AsyncLogger */ /** * Sets the token * * @param token */ public void setToken( String token) { this.le_async.setToken(token); } /** * Sets the HTTP PUT boolean flag. Send logs via HTTP PUT instead of default Token TCP * * @param httpput HttpPut flag to set */ public void setHttpPut( boolean HttpPut) { this.le_async.setHttpPut(HttpPut); } /** Sets the ACCOUNT KEY value for HTTP PUT * * @param account_key */ public void setKey( String account_key) { this.le_async.setKey(account_key); } /** * Sets the LOCATION value for HTTP PUT * * @param log_location */ public void setLocation( String log_location) { this.le_async.setLocation(log_location); } /** * Sets the SSL boolean flag * * @param ssl */ public void setSsl( boolean ssl) { this.le_async.setSsl(ssl); } /** * Sets the debug flag. Appender in debug mode will print error messages on * error console. * * @param debug debug flag to set */ public void setDebug( boolean debug) { this.le_async.setDebug(debug); } /** * Sets the flag which determines if DataHub instance is used instead of Logentries service. * * @param useDataHub set to true to send log messaged to a DataHub instance. */ public void setIsUsingDataHub(boolean useDataHub){ this.le_async.setUseDataHub(useDataHub); } /** * Sets the address where DataHub server resides. * * @param dataHubAddr address like "127.0.0.1" */ public void setDataHubAddr(String dataHubAddr){ this.le_async.setDataHubAddr(dataHubAddr); } /** * Sets the port number on which DataHub instance waits for log messages. * * @param dataHubPort */ public void setDataHubPort(int dataHubPort){ this.le_async.setDataHubPort(dataHubPort); } /** * Determines whether to send HostName alongside with the log message * * @param logHostName */ public void setLogHostName(boolean logHostName) { this.le_async.setLogHostName(logHostName); } /** * Sets the HostName from the configuration * * @param hostName */ public void setHostName(String hostName) { this.le_async.setHostName(hostName); } /** * Sets LogID parameter from the configuration * * @param logID */ public void setLogID(String logID) { this.le_async.setLogID(logID); } /** * Implements AppenderSkeleton Append method, handles time and format * * @event event to log */ @Override protected void append( LoggingEvent event) { // Render the event according to layout String formattedEvent = layout.format( event); // Append stack trace if present and layout does not handle it if (layout.ignoresThrowable()) { String[] stack = event.getThrowableStrRep(); if (stack != null) { int len = stack.length; formattedEvent += ", "; for(int i = 0; i < len; i++) { formattedEvent += stack[i]; if(i < len - 1) formattedEvent += "\u2028"; } } } // Prepare to be queued this.le_async.addLineToQueue(formattedEvent); } /** * Closes all connections to Logentries */ @Override public void close() { this.le_async.close(); } @Override public boolean requiresLayout() { return true; } }
Java
@BeanDefinition(style = "light") public final class ResolvedFixedCouponBondSettlement implements ImmutableBean, Serializable { /** * The settlement date. */ @PropertyDefinition(validate = "notNull") private final LocalDate settlementDate; /** * The <i>clean</i> price at which the bond was traded. * <p> * The "clean" price excludes any accrued interest. * <p> * Strata uses <i>decimal prices</i> for bonds in the trade model, pricers and market data. * For example, a price of 99.32% is represented in Strata by 0.9932. */ @PropertyDefinition(validate = "ArgChecker.notNegative") private final double price; //------------------------------------------------------------------------- /** * Obtains an instance from the settlement date and price. * * @param settlementDate the settlement date * @param price the price at which the trade was agreed * @return the settlement information */ public static ResolvedFixedCouponBondSettlement of(LocalDate settlementDate, double price) { return new ResolvedFixedCouponBondSettlement(settlementDate, price); } //------------------------- AUTOGENERATED START ------------------------- /** * The meta-bean for {@code ResolvedFixedCouponBondSettlement}. */ private static final TypedMetaBean<ResolvedFixedCouponBondSettlement> META_BEAN = LightMetaBean.of( ResolvedFixedCouponBondSettlement.class, MethodHandles.lookup(), new String[] { "settlementDate", "price"}, new Object[0]); /** * The meta-bean for {@code ResolvedFixedCouponBondSettlement}. * @return the meta-bean, not null */ public static TypedMetaBean<ResolvedFixedCouponBondSettlement> meta() { return META_BEAN; } static { MetaBean.register(META_BEAN); } /** * The serialization version id. */ private static final long serialVersionUID = 1L; private ResolvedFixedCouponBondSettlement( LocalDate settlementDate, double price) { JodaBeanUtils.notNull(settlementDate, "settlementDate"); ArgChecker.notNegative(price, "price"); this.settlementDate = settlementDate; this.price = price; } @Override public TypedMetaBean<ResolvedFixedCouponBondSettlement> metaBean() { return META_BEAN; } //----------------------------------------------------------------------- /** * Gets the settlement date. * @return the value of the property, not null */ public LocalDate getSettlementDate() { return settlementDate; } //----------------------------------------------------------------------- /** * Gets the <i>clean</i> price at which the bond was traded. * <p> * The "clean" price excludes any accrued interest. * <p> * Strata uses <i>decimal prices</i> for bonds in the trade model, pricers and market data. * For example, a price of 99.32% is represented in Strata by 0.9932. * @return the value of the property */ public double getPrice() { return price; } //----------------------------------------------------------------------- @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj != null && obj.getClass() == this.getClass()) { ResolvedFixedCouponBondSettlement other = (ResolvedFixedCouponBondSettlement) obj; return JodaBeanUtils.equal(settlementDate, other.settlementDate) && JodaBeanUtils.equal(price, other.price); } return false; } @Override public int hashCode() { int hash = getClass().hashCode(); hash = hash * 31 + JodaBeanUtils.hashCode(settlementDate); hash = hash * 31 + JodaBeanUtils.hashCode(price); return hash; } @Override public String toString() { StringBuilder buf = new StringBuilder(96); buf.append("ResolvedFixedCouponBondSettlement{"); buf.append("settlementDate").append('=').append(JodaBeanUtils.toString(settlementDate)).append(',').append(' '); buf.append("price").append('=').append(JodaBeanUtils.toString(price)); buf.append('}'); return buf.toString(); } //-------------------------- AUTOGENERATED END -------------------------- }
Java
public class GooglePlaySubscriptionStatus { private boolean autoRenewing; private long startTimeMillis; private String kind; private long expiryTimeMillis; public boolean isAutoRenewing() { return autoRenewing; } public void setAutoRenewing( boolean autoRenewing ) { this.autoRenewing = autoRenewing; } public long getStartTimeMillis() { return startTimeMillis; } public void setStartTimeMillis( long startTimeMillis ) { this.startTimeMillis = startTimeMillis; } public String getKind() { return kind; } public void setKind( String kind ) { this.kind = kind; } public long getExpiryTimeMillis() { return expiryTimeMillis; } public void setExpiryTimeMillis( long expiryTimeMillis ) { this.expiryTimeMillis = expiryTimeMillis; } }
Java
public class TerminatorSet implements Terminator { protected final Set<Terminator> terminators; /** * Injection constructor used with guice's set multibinder, see * {@link EeModule}. * * @param terminators the set of terminators configured by guice modules */ @Inject public TerminatorSet(final Set<Terminator> terminators) { this.terminators = terminators; } @SuppressWarnings("rawtypes") @Override public Future<String> terminate() { final Promise<String> resultPromise = Promise.promise(); final List<Future> termFutures = terminators.stream(). // map(Terminator::terminate). // collect(Collectors.toList()); CompositeFuture.join(termFutures).onComplete(asyncRes -> { if (asyncRes.succeeded()) { resultPromise.complete(); } else { resultPromise.fail(new IllegalStateException("Termination Error")); } }); return resultPromise.future(); } }
Java
private final class Marc21Handler implements FieldHandler { @Override public void referenceField(final char[] tag, final char[] implDefinedPart, final String value) { getReceiver().literal(String.valueOf(tag), value); } @Override public void startDataField(final char[] tag, final char[] implDefinedPart, final char[] indicators) { getReceiver().startEntity(buildName(tag, indicators)); } private String buildName(final char[] tag, final char[] indicators) { final char[] name = new char[5]; name[0] = tag[0]; name[1] = tag[1]; name[2] = tag[2]; name[3] = indicators[0]; name[4] = indicators[1]; return String.valueOf(name); } @Override public void endDataField() { getReceiver().endEntity(); } @Override public void additionalImplDefinedPart(final char[] implDefinedPart) { // Nothing to do. MARC 21 does not use implementation defined parts. } @Override public void data(final char[] identifier, final String value) { getReceiver().literal(String.valueOf(identifier[0]), value); } }
Java
public abstract class VisorCoordinatorNodeTask<A, R> extends VisorOneNodeTask<A, R> { /** {@inheritDoc} */ @Override protected Collection<UUID> jobNodes(VisorTaskArgument<A> arg) { ClusterNode crd = ignite.context().discovery().discoCache().oldestAliveServerNode(); Collection<UUID> nids = new ArrayList<>(1); nids.add(crd == null ? ignite.localNode().id() : crd.id()); return nids; } }
Java
public final class SDL_Keymod { public static final int NONE = 0x0000, LSHIFT = 0x0001, RSHIFT = 0x0002, LCTRL = 0x0040, RCTRL = 0x0080, LALT = 0x0100, RALT = 0x0200, LGUI = 0x0400, RGUI = 0x0800, NUM = 0x1000, CAPS = 0x2000, MODE = 0x4000, RESERVED = 0x8000, CTRL = LCTRL | RCTRL, SHIFT = LSHIFT | RSHIFT, ALT = LALT | RALT, GUI = LGUI | RGUI; }
Java
public class AlternateEndpointLocation { private String endpointHostReplacementPattern; private String endpointHostReplacementValue; public String getEndpointHostReplacementPattern() { return this.endpointHostReplacementPattern; } public void setEndpointHostReplacementPattern(String endpointHostReplacementPattern) { this.endpointHostReplacementPattern = endpointHostReplacementPattern; } public String getEndpointHostReplacementValue() { return this.endpointHostReplacementValue; } public void setEndpointHostReplacementValue(String endpointHostReplacementValue) { this.endpointHostReplacementValue = endpointHostReplacementValue; } }
Java
public class TrendrrInitializationException extends TrendrrException { protected static Log log = LogFactory .getLog(TrendrrInitializationException.class); public TrendrrInitializationException () { this(null, null); } public TrendrrInitializationException(String message) { this(message, null); } public TrendrrInitializationException(String message, Exception cause) { super(message, cause); } public TrendrrInitializationException(Exception cause) { this(null, cause); } }
Java
@LooperMode(LooperMode.Mode.LEGACY) @RunWith(LithoTestRunner.class) public class TreePropSectionTest { private SectionContext mContext; @Before public void setUp() { final Activity activity = Robolectric.buildActivity(Activity.class).create().get(); mContext = new SectionContext(activity); } /** * Tests that a TreeProp is propagated down a Section Tree, is scoped correctly, and can be * overwritten. */ @Test public void testTreePropsPropagated() { final Result propALeaf1 = new Result(); final Result propBLeaf1 = new Result(); final Result propBLeaf2 = new Result(); final TreePropNumberType treePropA = new TreePropNumberType(9); final TreePropStringType treePropB = new TreePropStringType("propB"); final TreePropStringType treePropBChanged = new TreePropStringType("propB_changed"); final SectionTree tree = SectionTree.create(mContext, new TestTarget()).build(); tree.setRoot( TreePropSectionTestParentGroup.create(mContext) .propA(treePropA) .propB(treePropB) .resultPropALeaf1(propALeaf1) .resultPropBLeaf1(propBLeaf1) .resultPropBLeaf2(propBLeaf2) .build()); assertThat(propALeaf1.mProp).isEqualTo(treePropA); // TreePropSectionTestMiddleGroupSpec modifies "propB". assertThat(propBLeaf1.mProp).isEqualTo(treePropBChanged); // The second LeafGroupSpec does not see the modification to "propB" // because its not a descendant of MiddleGroupSpec. assertThat(propBLeaf2.mProp).isEqualTo(treePropB); } }
Java
public final class ObaContract { public static final String TAG = "ObaContract"; /** The authority portion of the URI - defined in build.gradle */ public static final String AUTHORITY = BuildConfig.DATABASE_AUTHORITY; /** The base URI for the Oba provider */ public static final Uri AUTHORITY_URI = Uri.parse("content://" + AUTHORITY); protected interface StopsColumns { /** * The code for the stop, e.g. 001_123 * <P> * Type: TEXT * </P> */ public static final String CODE = "code"; /** * The user specified name of the stop, e.g. "13th Ave E & John St" * <P> * Type: TEXT * </P> */ public static final String NAME = "name"; /** * The stop direction, one of: N, NE, NW, E, SE, SW, S, W or null * <P> * Type: TEXT * </P> */ public static final String DIRECTION = "direction"; /** * The latitude of the stop location. * <P> * Type: DOUBLE * </P> */ public static final String LATITUDE = "latitude"; /** * The longitude of the stop location. * <P> * Type: DOUBLE * </P> */ public static final String LONGITUDE = "longitude"; /** * The region ID * <P> * Type: INTEGER * </P> */ public static final String REGION_ID = "region_id"; } protected interface RoutesColumns { /** * The short name of the route, e.g. "10" * <P> * Type: TEXT * </P> */ public static final String SHORTNAME = "short_name"; /** * The long name of the route, e.g "Downtown to U-District" * <P> * Type: TEXT * </P> */ public static final String LONGNAME = "long_name"; /** * Returns the URL of the route schedule. * <P> * Type: TEXT * </P> */ public static final String URL = "url"; /** * The region ID * <P> * Type: INTEGER * </P> */ public static final String REGION_ID = "region_id"; } protected interface StopRouteKeyColumns { /** * The referenced Stop ID. This may or may not represent a key in the * Stops table. * <P> * Type: TEXT * </P> */ public static final String STOP_ID = "stop_id"; /** * The referenced Route ID. This may or may not represent a key in the * Routes table. * <P> * Type: TEXT * </P> */ public static final String ROUTE_ID = "route_id"; } protected interface StopRouteFilterColumns extends StopRouteKeyColumns { // No additional columns } protected interface TripsColumns extends StopRouteKeyColumns { /** * The scheduled departure time for the trip in milliseconds. * <P> * Type: INTEGER * </P> */ public static final String DEPARTURE = "departure"; /** * The headsign of the trip, e.g., "Capitol Hill" * <P> * Type: TEXT * </P> */ public static final String HEADSIGN = "headsign"; /** * The user specified name of the trip. * <P> * Type: TEXT * </P> */ public static final String NAME = "name"; /** * The number of minutes before the arrival to notify the user * <P> * Type: INTEGER * </P> */ public static final String REMINDER = "reminder"; /** * A bitmask representing the days the reminder should be used. * <P> * Type: INTEGER * </P> */ public static final String DAYS = "days"; } protected interface TripAlertsColumns { /** * The trip_id key of the corresponding trip. * <P> * Type: TEXT * </P> */ public static final String TRIP_ID = "trip_id"; /** * The stop_id key of the corresponding trip. * <P> * Type: TEXT * </P> */ public static final String STOP_ID = "stop_id"; /** * The time in milliseconds to begin the polling. Unlike the "reminder" * time in the Trips columns, this represents a specific time. * <P> * Type: INTEGER * </P> */ public static final String START_TIME = "start_time"; /** * The state of the the alert. Can be SCHEDULED, POLLING, NOTIFY, * CANCELED * <P> * Type: INTEGER * </P> */ public static final String STATE = "state"; } protected interface UserColumns { /** * The number of times this resource has been accessed by the user. * <P> * Type: INTEGER * </P> */ public static final String USE_COUNT = "use_count"; /** * The user specified name given to this resource. * <P> * Type: TEXT * </P> */ public static final String USER_NAME = "user_name"; /** * The last time the user accessed the resource. * <P> * Type: INTEGER * </P> */ public static final String ACCESS_TIME = "access_time"; /** * Whether or not the resource is marked as a favorite (starred) * <P> * Type: INTEGER (1 or 0) * </P> */ public static final String FAVORITE = "favorite"; /** * This returns the user specified name, or the default name. * <P> * Type: TEXT * </P> */ public static final String UI_NAME = "ui_name"; } protected interface ServiceAlertsColumns { /** * The time it was marked as read. * <P> * Type: TEXT * </P> */ public static final String MARKED_READ_TIME = "marked_read_time"; /** * Whether or not the alert has been hidden by the user. * <P> * Type: BOOLEAN * </P> */ public static final String HIDDEN = "hidden"; } protected interface RegionsColumns { /** * The name of the region. * <P> * Type: TEXT * </P> */ public static final String NAME = "name"; /** * The base OBA URL. * <P> * Type: TEXT * </P> */ public static final String OBA_BASE_URL = "oba_base_url"; /** * The base SIRI URL. * <P> * Type: TEXT * </P> */ public static final String SIRI_BASE_URL = "siri_base_url"; /** * The locale of the API server. * <P> * Type: TEXT * </P> */ public static final String LANGUAGE = "lang"; /** * The email of the person responsible for this server. * <P> * Type: TEXT * </P> */ public static final String CONTACT_EMAIL = "contact_email"; /** * Whether or not the server supports OBA discovery APIs. * <P> * Type: BOOLEAN * </P> */ public static final String SUPPORTS_OBA_DISCOVERY = "supports_api_discovery"; /** * Whether or not the server supports OBA realtime APIs. * <P> * Type: BOOLEAN * </P> */ public static final String SUPPORTS_OBA_REALTIME = "supports_api_realtime"; /** * Whether or not the server supports SIRI realtime APIs. * <P> * Type: BOOLEAN * </P> */ public static final String SUPPORTS_SIRI_REALTIME = "supports_siri_realtime"; /** * The Twitter URL for the region. * <P> * Type: TEXT * </P> */ public static final String TWITTER_URL = "twitter_url"; /** * Whether or not the server is experimental (i.e., not production). * <P> * Type: BOOLEAN * </P> */ public static final String EXPERIMENTAL = "experimental"; /** * The StopInfo URL for the region (see #103) * <P> * Type: TEXT * </P> */ public static final String STOP_INFO_URL = "stop_info_url"; /** * The OpenTripPlanner URL for the region * <P> * Type: TEXT * </P> */ public static final String OTP_BASE_URL = "otp_base_url"; /** * The email of the person responsible for the OTP server. * <P> * Type: TEXT * </P> */ public static final String OTP_CONTACT_EMAIL = "otp_contact_email"; /** * Whether or not the region supports bikeshare information through integration with OTP * <P> * Type: BOOLEAN * </P> */ public static final String SUPPORTS_OTP_BIKESHARE = "supports_otp_bikeshare"; /** * Whether or not the server supports Embedded Social * <P> * Type: BOOLEAN * </P> */ public static final String SUPPORTS_EMBEDDED_SOCIAL = "supports_embedded_social"; /** * The Android App ID for the payment app used in the region * <P> * Type: TEXT * </P> */ public static final String PAYMENT_ANDROID_APP_ID = "payment_android_app_id"; /** * The title of a warning dialog that should be shown to the user the first time they select the fare payment option, or empty if no warning should be shown to the user. * <P> * Type: TEXT * </P> */ public static final String PAYMENT_WARNING_TITLE = "payment_warning_title"; /** * The body text of a warning dialog that should be shown to the user the first time they select the fare payment option, or empty if no warning should be shown to the user. * <P> * Type: TEXT * </P> */ public static final String PAYMENT_WARNING_BODY = "payment_warning_body"; } protected interface RegionBoundsColumns { /** * The region ID * <P> * Type: INTEGER * </P> */ public static final String REGION_ID = "region_id"; /** * The latitude center of the agencies coverage area * <P> * Type: REAL * </P> */ public static final String LATITUDE = "lat"; /** * The longitude center of the agencies coverage area * <P> * Type: REAL * </P> */ public static final String LONGITUDE = "lon"; /** * The height of the agencies bounding box * <P> * Type: REAL * </P> */ public static final String LAT_SPAN = "lat_span"; /** * The width of the agencies bounding box * <P> * Type: REAL * </P> */ public static final String LON_SPAN = "lon_span"; } protected interface RegionOpen311ServersColumns { /** * The region ID * <P> * Type: INTEGER * </P> */ public static final String REGION_ID = "region_id"; /** * The jurisdiction id of the open311 server * <P> * Type: TEXT * </P> */ public static final String JURISDICTION = "jurisdiction"; /** * The api key of the open311 server * <P> * Type: TEXT * </P> */ public static final String API_KEY = "api_key"; /** * The url of the open311 server * <P> * Type: TEXT * </P> */ public static final String BASE_URL = "open311_base_url"; } protected interface RouteHeadsignKeyColumns extends StopRouteKeyColumns { /** * The referenced headsign. This may or may not represent a value in the * Trips table. * <P> * Type: TEXT * </P> */ public static final String HEADSIGN = "headsign"; /** * Whether or not this stop should be excluded as a favorite. This is to allow a user to * star a route/headsign for all stops, and then remove the star from selected stops. * <P> * Type: BOOLEAN * </P> */ public static final String EXCLUDE = "exclude"; } public static class Stops implements BaseColumns, StopsColumns, UserColumns { // Cannot be instantiated private Stops() { } /** The URI path portion for this table */ public static final String PATH = "stops"; /** The content:// style URI for this table */ public static final Uri CONTENT_URI = Uri.withAppendedPath( AUTHORITY_URI, PATH); public static final String CONTENT_TYPE = "vnd.android.cursor.item/" + BuildConfig.DATABASE_AUTHORITY + ".stop"; public static final String CONTENT_DIR_TYPE = "vnd.android.dir/" + BuildConfig.DATABASE_AUTHORITY + ".stop"; public static Uri insertOrUpdate(String id, ContentValues values, boolean markAsUsed) { ContentResolver cr = Application.get().getContentResolver(); final Uri uri = Uri.withAppendedPath(CONTENT_URI, id); Cursor c = cr.query(uri, new String[]{USE_COUNT}, null, null, null); Uri result; if (c != null && c.getCount() > 0) { // Update if (markAsUsed) { c.moveToFirst(); int count = c.getInt(0); values.put(USE_COUNT, count + 1); values.put(ACCESS_TIME, System.currentTimeMillis()); } cr.update(uri, values, null, null); result = uri; } else { // Insert if (markAsUsed) { values.put(USE_COUNT, 1); values.put(ACCESS_TIME, System.currentTimeMillis()); } else { values.put(USE_COUNT, 0); } values.put(_ID, id); result = cr.insert(CONTENT_URI, values); } if (c != null) { c.close(); } return result; } public static boolean markAsFavorite(Context context, Uri uri, boolean favorite) { ContentResolver cr = context.getContentResolver(); ContentValues values = new ContentValues(); values.put(ObaContract.Stops.FAVORITE, favorite ? 1 : 0); return cr.update(uri, values, null, null) > 0; } public static boolean markAsUnused(Context context, Uri uri) { ContentResolver cr = context.getContentResolver(); ContentValues values = new ContentValues(); values.put(ObaContract.Stops.USE_COUNT, 0); values.putNull(ObaContract.Stops.ACCESS_TIME); return cr.update(uri, values, null, null) > 0; } } public static class Routes implements BaseColumns, RoutesColumns, UserColumns { // Cannot be instantiated private Routes() { } /** The URI path portion for this table */ public static final String PATH = "routes"; /** The content:// style URI for this table */ public static final Uri CONTENT_URI = Uri.withAppendedPath( AUTHORITY_URI, PATH); public static final String CONTENT_TYPE = "vnd.android.cursor.item/" + BuildConfig.DATABASE_AUTHORITY + ".route"; public static final String CONTENT_DIR_TYPE = "vnd.android.dir/" + BuildConfig.DATABASE_AUTHORITY + ".route"; public static Uri insertOrUpdate(Context context, String id, ContentValues values, boolean markAsUsed) { ContentResolver cr = context.getContentResolver(); final Uri uri = Uri.withAppendedPath(CONTENT_URI, id); Cursor c = cr.query(uri, new String[]{USE_COUNT}, null, null, null); Uri result; if (c != null && c.getCount() > 0) { // Update if (markAsUsed) { c.moveToFirst(); int count = c.getInt(0); values.put(USE_COUNT, count + 1); values.put(ACCESS_TIME, System.currentTimeMillis()); } cr.update(uri, values, null, null); result = uri; } else { // Insert if (markAsUsed) { values.put(USE_COUNT, 1); values.put(ACCESS_TIME, System.currentTimeMillis()); } else { values.put(USE_COUNT, 0); } values.put(_ID, id); result = cr.insert(CONTENT_URI, values); } if (c != null) { c.close(); } return result; } protected static boolean markAsFavorite(Context context, Uri uri, boolean favorite) { ContentResolver cr = context.getContentResolver(); ContentValues values = new ContentValues(); values.put(ObaContract.Routes.FAVORITE, favorite ? 1 : 0); return cr.update(uri, values, null, null) > 0; } public static boolean markAsUnused(Context context, Uri uri) { ContentResolver cr = context.getContentResolver(); ContentValues values = new ContentValues(); values.put(ObaContract.Routes.USE_COUNT, 0); values.putNull(ObaContract.Routes.ACCESS_TIME); return cr.update(uri, values, null, null) > 0; } /** * Returns true if this route is a favorite, false if it does not * * Note that this is NOT specific to headsign. If you want to know if a combination of a * routeId and headsign is a user favorite, see * RouteHeadsignFavorites.isFavorite(context, routeId, headsign). * * @param routeUri Uri for a route * @return true if this route is a favorite, false if it does not */ public static boolean isFavorite(Context context, Uri routeUri) { ContentResolver cr = context.getContentResolver(); String[] ROUTE_USER_PROJECTION = {ObaContract.Routes.FAVORITE}; Cursor c = cr.query(routeUri, ROUTE_USER_PROJECTION, null, null, null); if (c != null) { try { if (c.moveToNext()) { return (c.getInt(0) == 1); } } finally { c.close(); } } // If we get this far, assume its not return false; } } public static class StopRouteFilters implements StopRouteFilterColumns { // Cannot be instantiated private StopRouteFilters() { } /** The URI path portion for this table */ public static final String PATH = "stop_routes_filter"; /** The content:// style URI for this table */ public static final Uri CONTENT_URI = Uri.withAppendedPath( AUTHORITY_URI, PATH); public static final String CONTENT_DIR_TYPE = "vnd.android.dir/" + BuildConfig.DATABASE_AUTHORITY + ".stoproutefilter"; private static final String FILTER_WHERE = STOP_ID + "=?"; /** * Gets the filter for the specified Stop ID. * * @param context The context. * @param stopId The stop ID. * @return The filter. If there is no filter (or on error), it returns * an empty list. */ public static ArrayList<String> get(Context context, String stopId) { final String[] selection = {ROUTE_ID}; final String[] selectionArgs = {stopId}; ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(CONTENT_URI, selection, FILTER_WHERE, selectionArgs, null); ArrayList<String> result = new ArrayList<String>(); if (c != null) { try { while (c.moveToNext()) { result.add(c.getString(0)); } } finally { c.close(); } } return result; } /** * Sets the filter for the particular stop ID. * * @param context The context. * @param stopId The stop ID. * @param filter An array of route IDs to filter. */ public static void set(Context context, String stopId, ArrayList<String> filter) { if (context == null) { return; } // First, delete any existing rows for this stop. // Then, insert all of these rows. // Should we put this in a transaction? We could, // but it's not terribly important. final String[] selectionArgs = {stopId}; ContentResolver cr = context.getContentResolver(); cr.delete(CONTENT_URI, FILTER_WHERE, selectionArgs); ContentValues args = new ContentValues(); args.put(STOP_ID, stopId); final int len = filter.size(); for (int i = 0; i < len; ++i) { args.put(ROUTE_ID, filter.get(i)); cr.insert(CONTENT_URI, args); } } } public static class Trips implements BaseColumns, StopRouteKeyColumns, TripsColumns { // Cannot be instantiated private Trips() { } /** The URI path portion for this table */ public static final String PATH = "trips"; /** * The content:// style URI for this table URI is of the form * content://<authority>/trips/<tripId>/<stopId> */ public static final Uri CONTENT_URI = Uri.withAppendedPath( AUTHORITY_URI, PATH); public static final String CONTENT_TYPE = "vnd.android.cursor.item/" + BuildConfig.DATABASE_AUTHORITY + ".trip"; public static final String CONTENT_DIR_TYPE = "vnd.android.dir/" + BuildConfig.DATABASE_AUTHORITY + ".trip"; public static final int DAY_MON = 0x1; public static final int DAY_TUE = 0x2; public static final int DAY_WED = 0x4; public static final int DAY_THU = 0x8; public static final int DAY_FRI = 0x10; public static final int DAY_SAT = 0x20; public static final int DAY_SUN = 0x40; public static final int DAY_WEEKDAY = DAY_MON | DAY_TUE | DAY_WED | DAY_THU | DAY_FRI; public static final int DAY_ALL = DAY_WEEKDAY | DAY_SUN | DAY_SAT; public static Uri buildUri(String tripId, String stopId) { return CONTENT_URI.buildUpon().appendPath(tripId) .appendPath(stopId).build(); } /** * Converts a days bitmask into a boolean[] array * * @param days A DB compatible days bitmask. * @return A boolean array representing the days set in the bitmask, * Mon=0 to Sun=6 */ public static boolean[] daysToArray(int days) { final boolean[] result = { (days & ObaContract.Trips.DAY_MON) == ObaContract.Trips.DAY_MON, (days & ObaContract.Trips.DAY_TUE) == ObaContract.Trips.DAY_TUE, (days & ObaContract.Trips.DAY_WED) == ObaContract.Trips.DAY_WED, (days & ObaContract.Trips.DAY_THU) == ObaContract.Trips.DAY_THU, (days & ObaContract.Trips.DAY_FRI) == ObaContract.Trips.DAY_FRI, (days & ObaContract.Trips.DAY_SAT) == ObaContract.Trips.DAY_SAT, (days & ObaContract.Trips.DAY_SUN) == ObaContract.Trips.DAY_SUN,}; return result; } /** * Converts a boolean[] array to a DB compatible days bitmask * * @param days boolean array as returned by daysToArray * @return A DB compatible days bitmask */ public static int arrayToDays(boolean[] days) { if (days.length != 7) { throw new IllegalArgumentException("days.length must be 7"); } int result = 0; for (int i = 0; i < days.length; ++i) { final int bit = days[i] ? 1 : 0; result |= bit << i; } return result; } /** * Converts a 'minutes-to-midnight' value into a Unix time. * * @param minutes from midnight in UTC. * @return A Unix time representing the time in the current day. */ // Helper functions to convert the DB DepartureTime value public static long convertDBToTime(int minutes) { // This converts the minutes-to-midnight to a time of the current // day. Time t = new Time(); t.setToNow(); t.set(0, minutes, 0, t.monthDay, t.month, t.year); return t.toMillis(false); } /** * Converts a Unix time into a 'minutes-to-midnight' in UTC. * * @param departureTime A Unix time. * @return minutes from midnight in UTC. */ public static int convertTimeToDB(long departureTime) { // This converts a time_t to minutes-to-midnight. Time t = new Time(); t.set(departureTime); return t.hour * 60 + t.minute; } /** * Converts a weekday value from a android.text.format.Time to a bit. * * @param weekday The weekDay value from android.text.format.Time * @return A DB compatible bit. */ public static int getDayBit(int weekday) { switch (weekday) { case Time.MONDAY: return ObaContract.Trips.DAY_MON; case Time.TUESDAY: return ObaContract.Trips.DAY_TUE; case Time.WEDNESDAY: return ObaContract.Trips.DAY_WED; case Time.THURSDAY: return ObaContract.Trips.DAY_THU; case Time.FRIDAY: return ObaContract.Trips.DAY_FRI; case Time.SATURDAY: return ObaContract.Trips.DAY_SAT; case Time.SUNDAY: return ObaContract.Trips.DAY_SUN; } return 0; } } public static class TripAlerts implements BaseColumns, TripAlertsColumns { // Cannot be instantiated private TripAlerts() { } /** The URI path portion for this table */ public static final String PATH = "trip_alerts"; /** * The content:// style URI for this table URI is of the form * content://<authority>/trip_alerts/<id> */ public static final Uri CONTENT_URI = Uri.withAppendedPath( AUTHORITY_URI, PATH); public static final String CONTENT_TYPE = "vnd.android.cursor.item/" + BuildConfig.DATABASE_AUTHORITY + ".trip_alert"; public static final String CONTENT_DIR_TYPE = "vnd.android.dir/" + BuildConfig.DATABASE_AUTHORITY + ".trip_alert"; public static final int STATE_SCHEDULED = 0; public static final int STATE_POLLING = 1; public static final int STATE_NOTIFY = 2; public static final int STATE_CANCELLED = 3; public static Uri buildUri(int id) { return CONTENT_URI.buildUpon().appendPath(String.valueOf(id)) .build(); } public static Uri insertIfNotExists(Context context, String tripId, String stopId, long startTime) { return insertIfNotExists(context.getContentResolver(), tripId, stopId, startTime); } public static Uri insertIfNotExists(ContentResolver cr, String tripId, String stopId, long startTime) { Uri result; Cursor c = cr.query(CONTENT_URI, new String[]{_ID}, String.format("%s=? AND %s=? AND %s=?", TRIP_ID, STOP_ID, START_TIME), new String[]{tripId, stopId, String.valueOf(startTime)}, null); if (c != null && c.moveToNext()) { result = buildUri(c.getInt(0)); } else { ContentValues values = new ContentValues(); values.put(TRIP_ID, tripId); values.put(STOP_ID, stopId); values.put(START_TIME, startTime); result = cr.insert(CONTENT_URI, values); } if (c != null) { c.close(); } return result; } public static void setState(Context context, Uri uri, int state) { setState(context.getContentResolver(), uri, state); } public static void setState(ContentResolver cr, Uri uri, int state) { ContentValues values = new ContentValues(); values.put(STATE, state); cr.update(uri, values, null, null); } } public static class ServiceAlerts implements BaseColumns, ServiceAlertsColumns { // Cannot be instantiated private ServiceAlerts() { } /** The URI path portion for this table */ public static final String PATH = "service_alerts"; /** * The content:// style URI for this table URI is of the form * content://<authority>/service_alerts/<id> */ public static final Uri CONTENT_URI = Uri.withAppendedPath( AUTHORITY_URI, PATH); public static final String CONTENT_TYPE = "vnd.android.cursor.item/" + BuildConfig.DATABASE_AUTHORITY + ".service_alert"; public static final String CONTENT_DIR_TYPE = "vnd.android.dir/" + BuildConfig.DATABASE_AUTHORITY + ".service_alert"; /** * @param markAsRead true if this alert should be marked as read with the timestamp of * System.currentTimeMillis(), * false if the alert should not be marked as read with the timestamp of * System.currentTimeMillis() * @param hidden true if this alert should be marked as hidden by the user, false if * it should be marked as not * hidden by the user, or null if the hidden value shouldn't be * changed */ public static Uri insertOrUpdate(String id, ContentValues values, boolean markAsRead, Boolean hidden) { if (id == null) { return null; } if (values == null) { values = new ContentValues(); } ContentResolver cr = Application.get().getContentResolver(); final Uri uri = Uri.withAppendedPath(CONTENT_URI, id); Cursor c = cr.query(uri, new String[]{}, null, null, null); Uri result; if (c != null && c.getCount() > 0) { // Update if (markAsRead) { c.moveToFirst(); values.put(MARKED_READ_TIME, System.currentTimeMillis()); } if (hidden != null) { c.moveToFirst(); if (hidden) { values.put(HIDDEN, 1); } else { values.put(HIDDEN, 0); } } if (values.size() != 0) { cr.update(uri, values, null, null); } result = uri; } else { // Insert if (markAsRead) { values.put(MARKED_READ_TIME, System.currentTimeMillis()); } if (hidden != null) { if (hidden) { values.put(HIDDEN, 1); } else { values.put(HIDDEN, 0); } } values.put(_ID, id); result = cr.insert(CONTENT_URI, values); } if (c != null) { c.close(); } return result; } /** * Returns true if this service alert (situation) has been previously hidden by the * user, false it if has not * * @param situationId The ID of the situation (service alert) * @return true if this service alert (situation) has been previously hidden by the user, * false it if has not */ public static boolean isHidden(String situationId) { final String[] selection = {_ID, HIDDEN}; final String[] selectionArgs = {situationId, Integer.toString(1)}; final String WHERE = _ID + "=? AND " + HIDDEN + "=?"; ContentResolver cr = Application.get().getContentResolver(); Cursor c = cr.query(CONTENT_URI, selection, WHERE, selectionArgs, null); boolean hidden; if (c != null && c.getCount() > 0) { hidden = true; } else { hidden = false; } if (c != null) { c.close(); } return hidden; } /** * Marks all alerts as not hidden, and therefore visible * * @return the number of rows updated */ public static int showAllAlerts() { ContentResolver cr = Application.get().getContentResolver(); ContentValues values = new ContentValues(); values.put(HIDDEN, 0); return cr.update(CONTENT_URI, values, null, null); } } public static class Regions implements BaseColumns, RegionsColumns { // Cannot be instantiated private Regions() { } /** The URI path portion for this table */ public static final String PATH = "regions"; /** * The content:// style URI for this table URI is of the form * content://<authority>/regions/<id> */ public static final Uri CONTENT_URI = Uri.withAppendedPath( AUTHORITY_URI, PATH); public static final String CONTENT_TYPE = "vnd.android.cursor.item/" + BuildConfig.DATABASE_AUTHORITY + ".region"; public static final String CONTENT_DIR_TYPE = "vnd.android.dir/" + BuildConfig.DATABASE_AUTHORITY + ".region"; public static Uri buildUri(int id) { return ContentUris.withAppendedId(CONTENT_URI, id); } public static Uri insertOrUpdate(Context context, int id, ContentValues values) { return insertOrUpdate(context.getContentResolver(), id, values); } public static Uri insertOrUpdate(ContentResolver cr, int id, ContentValues values) { final Uri uri = Uri.withAppendedPath(CONTENT_URI, String.valueOf(id)); Cursor c = cr.query(uri, new String[]{}, null, null, null); Uri result; if (c != null && c.getCount() > 0) { cr.update(uri, values, null, null); result = uri; } else { values.put(_ID, id); result = cr.insert(CONTENT_URI, values); } if (c != null) { c.close(); } return result; } public static ObaRegion get(Context context, int id) { return get(context.getContentResolver(), id); } public static ObaRegion get(ContentResolver cr, int id) { final String[] PROJECTION = { _ID, NAME, OBA_BASE_URL, SIRI_BASE_URL, LANGUAGE, CONTACT_EMAIL, SUPPORTS_OBA_DISCOVERY, SUPPORTS_OBA_REALTIME, SUPPORTS_SIRI_REALTIME, TWITTER_URL, EXPERIMENTAL, STOP_INFO_URL, OTP_BASE_URL, OTP_CONTACT_EMAIL, SUPPORTS_OTP_BIKESHARE, SUPPORTS_EMBEDDED_SOCIAL, PAYMENT_ANDROID_APP_ID, PAYMENT_WARNING_TITLE, PAYMENT_WARNING_BODY }; Cursor c = cr.query(buildUri((int) id), PROJECTION, null, null, null); if (c != null) { try { if (c.getCount() == 0) { return null; } c.moveToFirst(); return new ObaRegionElement(id, // id c.getString(1), // Name true, // Active c.getString(2), // OBA Base URL c.getString(3), // SIRI Base URL RegionBounds.getRegion(cr, id), // Bounds RegionOpen311Servers.getOpen311Server(cr, id), // Open311 servers c.getString(4), // Lang c.getString(5), // Contact Email c.getInt(6) > 0, // Supports Oba Discovery c.getInt(7) > 0, // Supports Oba Realtime c.getInt(8) > 0, // Supports Siri Realtime c.getString(9), // Twitter URL c.getInt(10) > 0, // Experimental c.getString(11), // StopInfoUrl c.getString(12), // OtpBaseUrl c.getString(13), // OtpContactEmail c.getInt(14) > 0, // Supports OTP Bikeshare c.getInt(15) > 0, // Supports Embedded Social c.getString(16), // Payment Android App ID c.getString(17), // Payment Warning Title c.getString(18) // Payment Warning Body ); } finally { c.close(); } } return null; } } public static class RegionBounds implements BaseColumns, RegionBoundsColumns { // Cannot be instantiated private RegionBounds() { } /** The URI path portion for this table */ public static final String PATH = "region_bounds"; /** * The content:// style URI for this table URI is of the form * content://<authority>/region_bounds/<id> */ public static final Uri CONTENT_URI = Uri.withAppendedPath( AUTHORITY_URI, PATH); public static final String CONTENT_TYPE = "vnd.android.cursor.item/" + BuildConfig.DATABASE_AUTHORITY + ".region_bounds"; public static final String CONTENT_DIR_TYPE = "vnd.android.dir/" + BuildConfig.DATABASE_AUTHORITY + ".region_bounds"; public static Uri buildUri(int id) { return ContentUris.withAppendedId(CONTENT_URI, id); } public static ObaRegionElement.Bounds[] getRegion(ContentResolver cr, int regionId) { final String[] PROJECTION = { LATITUDE, LONGITUDE, LAT_SPAN, LON_SPAN }; Cursor c = cr.query(CONTENT_URI, PROJECTION, "(" + RegionBounds.REGION_ID + " = " + regionId + ")", null, null); if (c != null) { try { ObaRegionElement.Bounds[] results = new ObaRegionElement.Bounds[c.getCount()]; if (c.getCount() == 0) { return results; } int i = 0; c.moveToFirst(); do { results[i] = new ObaRegionElement.Bounds( c.getDouble(0), c.getDouble(1), c.getDouble(2), c.getDouble(3)); i++; } while (c.moveToNext()); return results; } finally { c.close(); } } return null; } } public static class RegionOpen311Servers implements BaseColumns, RegionOpen311ServersColumns { // Cannot be instantiated private RegionOpen311Servers() { } /** The URI path portion for this table */ public static final String PATH = "open311_servers"; /** * The content:// style URI for this table URI is of the form * content://<authority>/region_open311_servers/<id> */ public static final Uri CONTENT_URI = Uri.withAppendedPath( AUTHORITY_URI, PATH); public static final String CONTENT_TYPE = "vnd.android.cursor.item/" + BuildConfig.DATABASE_AUTHORITY + ".open311_servers"; public static final String CONTENT_DIR_TYPE = "vnd.android.dir/" + BuildConfig.DATABASE_AUTHORITY + ".open311_servers"; public static Uri buildUri(int id) { return ContentUris.withAppendedId(CONTENT_URI, id); } public static ObaRegionElement.Open311Server[] getOpen311Server (ContentResolver cr, int regionId) { final String[] PROJECTION = { JURISDICTION, API_KEY, BASE_URL }; Cursor c = cr.query(CONTENT_URI, PROJECTION, "(" + RegionOpen311Servers.REGION_ID + " = " + regionId + ")", null, null); if (c != null) { try { ObaRegionElement.Open311Server[] results = new ObaRegionElement.Open311Server[c.getCount()]; if (c.getCount() == 0) { return results; } int i = 0; c.moveToFirst(); do { results[i] = new ObaRegionElement.Open311Server( c.getString(0), c.getString(1), c.getString(2)); i++; } while (c.moveToNext()); return results; } finally { c.close(); } } return null; } } /** * Supports storing user-defined favorites for route/headsign/stop combinations. This is * currently implemented without requiring knowledge of a full set of stops for a route. This * allows some flexibility in terms of changes server-side without invalidating user's * favorites - as long as the routeId/headsign combination remains consistent (and stopId, * when a particular stop is referenced), then user favorites should survive changes in the * composition of stops for a route. * * When the user favorites a route/headsign combination in the ArrivalsListFragment/Header, * they are prompted if they would like to make it a favorite for the current stop, or for all * stops. If they make it a favorite for the current stop, a record with * routeId/headsign/stopId is created, with "exclude" value of false (0). If they make it a * favorite for all stops, a record with routeId/headsign/ALL_STOPS is created with exclude * value of false. When arrival times are displayed for a given stopId, if a record in the * database with routeId/headsign/ALL_STOPS or routeId?headsign/stopId matches AND exclude is * set to false, then it is shown as a favorite. Otherwise, it is not shown as a favorite. * If the user unstars a stop, then routeId/headsign/stopId is inserted with an exclude value of * true (1).S */ public static class RouteHeadsignFavorites implements RouteHeadsignKeyColumns, UserColumns { // Cannot be instantiated private RouteHeadsignFavorites() { } /** The URI path portion for this table */ public static final String PATH = "route_headsign_favorites"; /** The content:// style URI for this table */ public static final Uri CONTENT_URI = Uri.withAppendedPath( AUTHORITY_URI, PATH); public static final String CONTENT_DIR_TYPE = "vnd.android.dir/" + BuildConfig.DATABASE_AUTHORITY + ".routeheadsignfavorites"; // String used to indicate that a route/headsign combination is a favorite for all stops private static final String ALL_STOPS = "all"; /** * Set the specified route and headsign combination as a favorite, optionally for a specific * stop. Note that this will also handle the marking/unmarking of the designated route as * the favorite as well. The route is marked as not a favorite when no more * routeId/headsign combinations remain. If marking the route/headsign as favorite for * all stops, then stopId should be null. * * @param routeId routeId to be marked as favorite, in combination with headsign * @param headsign headsign to be marked as favorite, in combination with routeId * @param stopId stopId to be marked as a favorite, or null if all stopIds should be marked * for this routeId/headsign combo. * @param favorite true if this route and headsign combination should be marked as a * favorite, false if it should not */ public static void markAsFavorite(Context context, String routeId, String headsign, String stopId, boolean favorite) { if (context == null) { return; } if (headsign == null) { headsign = ""; } ContentResolver cr = context.getContentResolver(); Uri routeUri = Uri.withAppendedPath(ObaContract.Routes.CONTENT_URI, routeId); String stopIdInternal; if (stopId != null) { stopIdInternal = stopId; } else { stopIdInternal = ALL_STOPS; } final String WHERE = ROUTE_ID + "=? AND " + HEADSIGN + "=? AND " + STOP_ID + "=?"; final String[] selectionArgs = {routeId, headsign, stopIdInternal}; if (favorite) { if (stopIdInternal != ALL_STOPS) { // First, delete any potential exclusion records for this stop by removing all records cr.delete(CONTENT_URI, WHERE, selectionArgs); } // Mark as favorite by inserting a record for this route/headsign combo ContentValues values = new ContentValues(); values.put(ROUTE_ID, routeId); values.put(HEADSIGN, headsign); values.put(STOP_ID, stopIdInternal); values.put(EXCLUDE, 0); cr.insert(CONTENT_URI, values); // Mark the route as a favorite also in the routes table Routes.markAsFavorite(context, routeUri, true); } else { // Deselect it as favorite by deleting all records for this route/headsign/stopId combo cr.delete(CONTENT_URI, WHERE, selectionArgs); if (stopIdInternal == ALL_STOPS) { // Also make sure we've deleted the single record for this specific stop, if it exists // We don't have the stopId here, so we can just delete all records for this routeId/headsign final String[] selectionArgs2 = {routeId, headsign}; final String WHERE2 = ROUTE_ID + "=? AND " + HEADSIGN + "=?"; cr.delete(CONTENT_URI, WHERE2, selectionArgs2); } // If there are no more route/headsign combinations that are favorites for this route, // then mark the route as not a favorite if (!isFavorite(context, routeId)) { Routes.markAsFavorite(context, routeUri, false); } // If a single stop is unstarred, but isFavorite(...) == true due to starring all // stops, insert exclusion record if (stopIdInternal != ALL_STOPS && isFavorite(routeId, headsign, stopId)) { // Insert an exclusion record for this single stop, in case the user is unstarring it // after starring the entire route ContentValues values = new ContentValues(); values.put(ROUTE_ID, routeId); values.put(HEADSIGN, headsign); values.put(STOP_ID, stopIdInternal); values.put(EXCLUDE, 1); cr.insert(CONTENT_URI, values); } } StringBuilder analyicsLabel = new StringBuilder(); if (favorite) { analyicsLabel.append(context.getString(R.string.analytics_label_star_route)); } else { analyicsLabel.append(context.getString(R.string.analytics_label_unstar_route)); } analyicsLabel.append(" ").append(routeId).append("_").append(headsign).append(" for "); if (stopId != null) { analyicsLabel.append(stopId); } else { analyicsLabel.append("all stops"); } ObaAnalytics.reportEventWithCategory( ObaAnalytics.ObaEventCategory.UI_ACTION.toString(), context.getString(R.string.analytics_action_edit_field), analyicsLabel.toString()); } /** * Returns true if this combination of routeId and headsign is a favorite for this stop * or all stops (and that stop is not excluded as a favorite), false if it is not * * @param routeId The routeId to check for favorite * @param headsign The headsign to check for favorite * @param stopId The stopId to check for favorite * @return true if this combination of routeId and headsign is a favorite for this stop * or all stops (and that stop is not excluded as a favorite), false if it is not */ public static boolean isFavorite(String routeId, String headsign, String stopId) { if (headsign == null) { headsign = ""; } final String[] selection = {ROUTE_ID, HEADSIGN, STOP_ID, EXCLUDE}; final String[] selectionArgs = {routeId, headsign, stopId, Integer.toString(0)}; ContentResolver cr = Application.get().getContentResolver(); final String FILTER_WHERE_ALL_FIELDS = ROUTE_ID + "=? AND " + HEADSIGN + "=? AND " + STOP_ID + "=? AND " + EXCLUDE + "=?"; Cursor c = cr.query(CONTENT_URI, selection, FILTER_WHERE_ALL_FIELDS, selectionArgs, null); boolean favorite; if (c != null && c.getCount() > 0) { favorite = true; } else { // Check again to see if the user has favorited this route/headsign combo for all stops final String[] selectionArgs2 = {routeId, headsign, ALL_STOPS}; String WHERE_PARTIAL = ROUTE_ID + "=? AND " + HEADSIGN + "=? AND " + STOP_ID + "=?"; Cursor c2 = cr.query(CONTENT_URI, selection, WHERE_PARTIAL, selectionArgs2, null); favorite = c2 != null && c2.getCount() > 0; if (c2 != null) { c2.close(); } if (favorite) { // Finally, make sure the user hasn't excluded this stop as a favorite final String[] selectionArgs3 = {routeId, headsign, stopId, Integer.toString(1)}; Cursor c3 = cr.query(CONTENT_URI, selection, FILTER_WHERE_ALL_FIELDS, selectionArgs3, null); // If this query returns at least one record, it means the stop has been excluded as // a favorite (i.e., the user explicitly de-selected it) boolean isStopExcluded = c3 != null && c3.getCount() > 0; favorite = !isStopExcluded; if (c3 != null) { c3.close(); } } } if (c != null) { c.close(); } return favorite; } /** * Returns true if this routeId is listed as a favorite for at least one headsign with * EXCLUDED set to false, or false if it is not * * @param routeId The routeId to check for favorite * @return true if this routeId is listed as a favorite for at least one headsign without * EXCLUDE being set to true, or false if it is not */ private static boolean isFavorite(Context context, String routeId) { final String[] selection = {ROUTE_ID, EXCLUDE}; final String[] selectionArgs = {routeId, Integer.toString(0)}; final String WHERE = ROUTE_ID + "=? AND " + EXCLUDE + "=?"; ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(CONTENT_URI, selection, WHERE, selectionArgs, null); boolean favorite = false; if (c != null && c.getCount() > 0) { favorite = true; } else { favorite = false; } if (c != null) { c.close(); } return favorite; } } }
Java
public static class RouteHeadsignFavorites implements RouteHeadsignKeyColumns, UserColumns { // Cannot be instantiated private RouteHeadsignFavorites() { } /** The URI path portion for this table */ public static final String PATH = "route_headsign_favorites"; /** The content:// style URI for this table */ public static final Uri CONTENT_URI = Uri.withAppendedPath( AUTHORITY_URI, PATH); public static final String CONTENT_DIR_TYPE = "vnd.android.dir/" + BuildConfig.DATABASE_AUTHORITY + ".routeheadsignfavorites"; // String used to indicate that a route/headsign combination is a favorite for all stops private static final String ALL_STOPS = "all"; /** * Set the specified route and headsign combination as a favorite, optionally for a specific * stop. Note that this will also handle the marking/unmarking of the designated route as * the favorite as well. The route is marked as not a favorite when no more * routeId/headsign combinations remain. If marking the route/headsign as favorite for * all stops, then stopId should be null. * * @param routeId routeId to be marked as favorite, in combination with headsign * @param headsign headsign to be marked as favorite, in combination with routeId * @param stopId stopId to be marked as a favorite, or null if all stopIds should be marked * for this routeId/headsign combo. * @param favorite true if this route and headsign combination should be marked as a * favorite, false if it should not */ public static void markAsFavorite(Context context, String routeId, String headsign, String stopId, boolean favorite) { if (context == null) { return; } if (headsign == null) { headsign = ""; } ContentResolver cr = context.getContentResolver(); Uri routeUri = Uri.withAppendedPath(ObaContract.Routes.CONTENT_URI, routeId); String stopIdInternal; if (stopId != null) { stopIdInternal = stopId; } else { stopIdInternal = ALL_STOPS; } final String WHERE = ROUTE_ID + "=? AND " + HEADSIGN + "=? AND " + STOP_ID + "=?"; final String[] selectionArgs = {routeId, headsign, stopIdInternal}; if (favorite) { if (stopIdInternal != ALL_STOPS) { // First, delete any potential exclusion records for this stop by removing all records cr.delete(CONTENT_URI, WHERE, selectionArgs); } // Mark as favorite by inserting a record for this route/headsign combo ContentValues values = new ContentValues(); values.put(ROUTE_ID, routeId); values.put(HEADSIGN, headsign); values.put(STOP_ID, stopIdInternal); values.put(EXCLUDE, 0); cr.insert(CONTENT_URI, values); // Mark the route as a favorite also in the routes table Routes.markAsFavorite(context, routeUri, true); } else { // Deselect it as favorite by deleting all records for this route/headsign/stopId combo cr.delete(CONTENT_URI, WHERE, selectionArgs); if (stopIdInternal == ALL_STOPS) { // Also make sure we've deleted the single record for this specific stop, if it exists // We don't have the stopId here, so we can just delete all records for this routeId/headsign final String[] selectionArgs2 = {routeId, headsign}; final String WHERE2 = ROUTE_ID + "=? AND " + HEADSIGN + "=?"; cr.delete(CONTENT_URI, WHERE2, selectionArgs2); } // If there are no more route/headsign combinations that are favorites for this route, // then mark the route as not a favorite if (!isFavorite(context, routeId)) { Routes.markAsFavorite(context, routeUri, false); } // If a single stop is unstarred, but isFavorite(...) == true due to starring all // stops, insert exclusion record if (stopIdInternal != ALL_STOPS && isFavorite(routeId, headsign, stopId)) { // Insert an exclusion record for this single stop, in case the user is unstarring it // after starring the entire route ContentValues values = new ContentValues(); values.put(ROUTE_ID, routeId); values.put(HEADSIGN, headsign); values.put(STOP_ID, stopIdInternal); values.put(EXCLUDE, 1); cr.insert(CONTENT_URI, values); } } StringBuilder analyicsLabel = new StringBuilder(); if (favorite) { analyicsLabel.append(context.getString(R.string.analytics_label_star_route)); } else { analyicsLabel.append(context.getString(R.string.analytics_label_unstar_route)); } analyicsLabel.append(" ").append(routeId).append("_").append(headsign).append(" for "); if (stopId != null) { analyicsLabel.append(stopId); } else { analyicsLabel.append("all stops"); } ObaAnalytics.reportEventWithCategory( ObaAnalytics.ObaEventCategory.UI_ACTION.toString(), context.getString(R.string.analytics_action_edit_field), analyicsLabel.toString()); } /** * Returns true if this combination of routeId and headsign is a favorite for this stop * or all stops (and that stop is not excluded as a favorite), false if it is not * * @param routeId The routeId to check for favorite * @param headsign The headsign to check for favorite * @param stopId The stopId to check for favorite * @return true if this combination of routeId and headsign is a favorite for this stop * or all stops (and that stop is not excluded as a favorite), false if it is not */ public static boolean isFavorite(String routeId, String headsign, String stopId) { if (headsign == null) { headsign = ""; } final String[] selection = {ROUTE_ID, HEADSIGN, STOP_ID, EXCLUDE}; final String[] selectionArgs = {routeId, headsign, stopId, Integer.toString(0)}; ContentResolver cr = Application.get().getContentResolver(); final String FILTER_WHERE_ALL_FIELDS = ROUTE_ID + "=? AND " + HEADSIGN + "=? AND " + STOP_ID + "=? AND " + EXCLUDE + "=?"; Cursor c = cr.query(CONTENT_URI, selection, FILTER_WHERE_ALL_FIELDS, selectionArgs, null); boolean favorite; if (c != null && c.getCount() > 0) { favorite = true; } else { // Check again to see if the user has favorited this route/headsign combo for all stops final String[] selectionArgs2 = {routeId, headsign, ALL_STOPS}; String WHERE_PARTIAL = ROUTE_ID + "=? AND " + HEADSIGN + "=? AND " + STOP_ID + "=?"; Cursor c2 = cr.query(CONTENT_URI, selection, WHERE_PARTIAL, selectionArgs2, null); favorite = c2 != null && c2.getCount() > 0; if (c2 != null) { c2.close(); } if (favorite) { // Finally, make sure the user hasn't excluded this stop as a favorite final String[] selectionArgs3 = {routeId, headsign, stopId, Integer.toString(1)}; Cursor c3 = cr.query(CONTENT_URI, selection, FILTER_WHERE_ALL_FIELDS, selectionArgs3, null); // If this query returns at least one record, it means the stop has been excluded as // a favorite (i.e., the user explicitly de-selected it) boolean isStopExcluded = c3 != null && c3.getCount() > 0; favorite = !isStopExcluded; if (c3 != null) { c3.close(); } } } if (c != null) { c.close(); } return favorite; } /** * Returns true if this routeId is listed as a favorite for at least one headsign with * EXCLUDED set to false, or false if it is not * * @param routeId The routeId to check for favorite * @return true if this routeId is listed as a favorite for at least one headsign without * EXCLUDE being set to true, or false if it is not */ private static boolean isFavorite(Context context, String routeId) { final String[] selection = {ROUTE_ID, EXCLUDE}; final String[] selectionArgs = {routeId, Integer.toString(0)}; final String WHERE = ROUTE_ID + "=? AND " + EXCLUDE + "=?"; ContentResolver cr = context.getContentResolver(); Cursor c = cr.query(CONTENT_URI, selection, WHERE, selectionArgs, null); boolean favorite = false; if (c != null && c.getCount() > 0) { favorite = true; } else { favorite = false; } if (c != null) { c.close(); } return favorite; } }
Java
public class ValidationError { private String message; private String objectId; /** * @deprecated */ public String getMessage() { return message; } /** * @deprecated */ public void setMessage(String message) { this.message = message; } /** * @deprecated */ public String getObjectId() { return objectId; } /** * @deprecated */ public void setObjectId(String objectId) { this.objectId = objectId; } }
Java
public class StepPlugin extends Plugin implements ParserPlugin, InterpreterPlugin, VocabularyExtender { public static final String PLUGIN_NAME = StepPlugin.class.getSimpleName(); public static final VersionInfo vinfo = new VersionInfo(1, 0, 1, "alpha"); public static final String CTL_STATE_FUNC_NAME = "stepControlState"; private String[] keywords = {"step", "then", "stepwise"}; private String[] operators = {}; private ParserFragments parsers; private HashSet<String> functionNames; private Map<String,FunctionElement> functions = null; /* Control states of agents in the system */ private Map<Element, SystemControlState> controlStates; public StepPlugin() { functionNames = new HashSet<String>(); functionNames.add(CTL_STATE_FUNC_NAME); } @Override public void initialize() throws InitializationFailedException { controlStates = new HashMap<Element, SystemControlState>(); } protected synchronized SystemControlState getControlState(Element agent) { SystemControlState result = controlStates.get(agent); if (result == null) { result = new SystemControlState(); controlStates.put(agent, result); } return result; } @Override public String[] getKeywords() { return keywords; } @Override public Set<Parser<? extends Object>> getLexers() { return Collections.emptySet(); } @Override public String[] getOperators() { return operators; } @Override public Parser<Node> getParser(String nonterminal) { final GrammarRule gr = getParsers().get(nonterminal); if (gr != null) return gr.parser; else return null; } @Override public Map<String, GrammarRule> getParsers() { if (parsers == null) { parsers = new ParserFragments(); KernelServices kernel = (KernelServices)capi.getPlugin("Kernel").getPluginInterface(); //Parser<Node> termParser = kernel.getTermParser(); Parser<Node> ruleParser = kernel.getRuleParser(); ParserTools pTools = ParserTools.getInstance(capi); final String grName = "StepRule"; final String blockGRName = "StepBlock"; Parser<Node> stepRuleParser = Parsers.array( new Parser[] { pTools.getKeywParser("step", PLUGIN_NAME), ruleParser, pTools.getKeywParser("then", PLUGIN_NAME).optional(null), ruleParser }).map( new ParserTools.ArrayParseMap(PLUGIN_NAME) { @Override public Node apply(Object[] vals) { Node node = new StepRuleNode(((Node)vals[0]).getScannerInfo()); boolean first = true; for (Object o: vals) { if (o != null) { Node n = (Node)o; if (n instanceof ASTNode) if (first) { node.addChild("alpha", n); first = false; } else node.addChild("beta", n); else node.addChild(n); } } return node; } }); final GrammarRule gr = new GrammarRule(grName, "'step' Rule 'then'? Rule", stepRuleParser, PLUGIN_NAME); parsers.add(gr); Parser<Node> stepBlockRuleParser = Parsers.array( new Parser[] { pTools.getKeywParser("stepwise", PLUGIN_NAME), pTools.getOprParser("{"), pTools.plus(ruleParser), pTools.getOprParser("}") }).map( new ParserTools.ArrayParseMap(PLUGIN_NAME) { @Override public Node apply(Object[] vals) { Node node = new StepBlockRuleNode(((Node)vals[0]).getScannerInfo()); addChildren(node, vals); return node; } }); final GrammarRule blockGR = new GrammarRule(blockGRName, "'stepwise' '{' Rule+ '}'", stepBlockRuleParser, PLUGIN_NAME); parsers.add(blockGR); final GrammarRule stepRules = new GrammarRule("StepRules", gr.name + " | " + blockGRName, Parsers.or(stepRuleParser, stepBlockRuleParser), PLUGIN_NAME); parsers.add(stepRules); parsers.put("Rule", stepRules); } return parsers; } @Override public ASTNode interpret(Interpreter interpreter, ASTNode pos) throws InterpreterException { if (pos instanceof StepRuleNode) { StepRuleNode node = (StepRuleNode)pos; ASTNode alpha = node.getFirstRule(); ASTNode beta = node.getSecondRule(); SystemControlState ctlstate = getControlState(interpreter.getSelf()); if (!alpha.isEvaluated() && !beta.isEvaluated()) { ControlStateElement ctlstate_alpha = uniqueCtlState(alpha, interpreter); if (ctlstate.contains(ctlstate_alpha)) return alpha; else if (ctlstate.contains(uniqueCtlState(beta, interpreter))) return beta; else ctlstate.value.add(ctlstate_alpha); } else if (alpha.isEvaluated() && !beta.isEvaluated()) { ControlStateElement ctlstate_alpha = uniqueCtlState(alpha, interpreter); if (!substateExists(ctlstate_alpha, ctlstate)) { ctlstate.value.remove(ctlstate_alpha); ctlstate.value.add(uniqueCtlState(beta, interpreter)); } pos.setNode(null, alpha.getUpdates(), null); } else { ControlStateElement ctlstate_beta = uniqueCtlState(beta, interpreter); if (!substateExists(ctlstate_beta, ctlstate)) ctlstate.value.remove(ctlstate_beta); pos.setNode(null, beta.getUpdates(), null); } } else if (pos instanceof StepBlockRuleNode) { StepBlockRuleNode node = (StepBlockRuleNode)pos; ASTNode lastEvaluatedRule = null; SystemControlState ctlstate = getControlState(interpreter.getSelf()); for (ASTNode cn: node.getAbstractChildNodes()) if (cn.isEvaluated()) { lastEvaluatedRule = cn; break; } if (lastEvaluatedRule == null) { for (ASTNode cn: node.getAbstractChildNodes()) if (ctlstate.contains(uniqueCtlState(cn, interpreter))) return cn; // implicit else ctlstate.value.add(uniqueCtlState(node.getFirst(), interpreter)); } else { // if (lastEvaluatedRule != null) { ControlStateElement ctlstate_last = uniqueCtlState(lastEvaluatedRule, interpreter); if (!substateExists(ctlstate_last, ctlstate)) { ctlstate.value.remove(ctlstate_last); if (lastEvaluatedRule.getNext() != null) ctlstate.value.add(uniqueCtlState(lastEvaluatedRule.getNext(), interpreter)); } pos.setNode(null, lastEvaluatedRule.getUpdates(), null); } } return pos; } private boolean substateExists(ControlStateElement cse, SystemControlState scs) { boolean result = false; for (ControlStateElement csei: scs.value) if (cse.isSuperControlStateOf(csei)) { result = true; break; } return result; } @Override public Set<String> getBackgroundNames() { return Collections.emptySet(); } @Override public Map<String, BackgroundElement> getBackgrounds() { return Collections.emptyMap(); } @Override public Set<String> getFunctionNames() { return functionNames; } @Override public Map<String, FunctionElement> getFunctions() { if (functions == null) { functions = new HashMap<String, FunctionElement>(); functions.put(CTL_STATE_FUNC_NAME, new CtrlStateFunctionElement(this)); } return functions; } @Override public Set<String> getRuleNames() { return Collections.emptySet(); } @Override public Map<String, RuleElement> getRules() { return Collections.emptyMap(); } @Override public Set<String> getUniverseNames() { return Collections.emptySet(); } @Override public Map<String, UniverseElement> getUniverses() { return Collections.emptyMap(); } @Override public VersionInfo getVersionInfo() { return vinfo; } public ControlStateElement uniqueCtlState(ASTNode node, Interpreter interpreter) { return new ControlStateElement(interpreter.getCurrentCallStack(), node); } }
Java
public class MessageCode { // Author public static final String AUTHOR_NOT_FOUND = "author.not.found"; public static final String AUTHOR_DUPLICATE = "author.duplicate"; public static final String AUTHOR_NAME_REQUIRED = "author.name.required"; public static final String AUTHOR_NAME_TOO_LONG = "author.name.too.long"; public static final String AUTHOR_DELETE_SUCCESS = "author.delete.success"; // Book public static final String BOOK_NOT_FOUND = "book.not.found"; public static final String BOOK_DUPLICATE = "book.duplicate"; public static final String BOOK_NAME_REQUIRED = "book.name.required"; public static final String BOOK_NAME_TOO_LONG = "book.name.too.long"; public static final String BOOK_DELETE_SUCCESS = "book.delete.success"; // assign public static final String ASSIGN_AUTHOR_REQUIRE_AUTHOR_ID = "assign.author.require.author.id"; public static final String ASSIGN_BOOK_REQUIRE_BOOK_ID = "assign.book.require.book.id"; }
Java
public class App extends Application implements PropertyChangeListener { private SnakeMoveTimer timer; private StackPane pane; private Score scoring; /** * Application entry point, everything starts here * @param args String[] Command line arguments (not used) */ public static void main(String[] args) { launch(); } @Override public void start(Stage stage) { // Class shared between the Scene and the AnimationTimer for handling key strokes final KeyStrokeManager strokeManager = new KeyStrokeManager(); // Set up the window where the game will take place final Canvas canvas = new Canvas(CANVAS_WIDTH, CANVAS_HEIGHT); pane = new StackPane(); pane.getChildren().add(canvas); final Scene scene = new Scene(pane, SCENE_WIDTH, SCENE_HEIGHT, Color.DARKSLATEBLUE); scene.setOnKeyPressed(new KeyPressedHandler(strokeManager)); scene.setOnKeyReleased(new KeyReleasedHandler(strokeManager)); stage.setTitle("Snake"); stage.setScene(scene); try (InputStream snakeIcon = getClass().getResourceAsStream("Cute-Green-Snake-64x64.png")) { stage.getIcons().add(new Image(snakeIcon)); } catch (IOException | NullPointerException e) { System.err.println("Could not load icon"); } stage.show(); // Create the game // Use an observer pattern for the score scoring = new Score(); scoring.addPropertyChangeListener(this); final Grid board = new Grid(canvas.getGraphicsContext2D()); final GameController game = new GameController(board, scoring); // Start the game timer = new SnakeMoveTimer(game, strokeManager); timer.start(); } @Override public void propertyChange(PropertyChangeEvent evt) { switch(evt.getPropertyName()) { case Score.GAME_OVER: timer.stop(); final Label gameOver = new Label("GAME OVER! SCORE: " + scoring.getPoints()); gameOver.setTextFill(Color.FLORALWHITE); pane.getChildren().add(gameOver); break; case Score.POINTS: break; } } }
Java
public class MainTestTKS { public static void main(String[] arg) throws IOException { // Load a sequence database String input = fileToPath("contextPrefixSpan.txt"); String output = ".//output.txt"; int k = 5; // Create an instance of the algorithm AlgoTKS algo = new AlgoTKS(); // This optional parameter allows to specify the minimum pattern length: // algo.setMinimumPatternLength(0); // optional // This optional parameter allows to specify the maximum pattern length: // algo.setMaximumPatternLength(4); // optional // This optional parameter allows to specify constraints that some // items MUST appear in the patterns found by TKS // E.g.: This requires that items 1 and 3 appears in every patterns found // algo.setMustAppearItems(new int[] {1,3}); // This optional parameter allows to specify the max gap between two // itemsets in a pattern. If set to 1, only patterns of contiguous itemsets // will be found (no gap). //algo.setMaxGap(1); // if you set the following parameter to true, the sequence ids of the sequences where // each pattern appears will be shown in the result // algo.showSequenceIdentifiersInOutput(true); // execute the algorithm, which returns some patterns PriorityQueue<PatternTKS> patterns = algo.runAlgorithm(input, output, k); // save results to file algo.writeResultTofile(output); algo.printStatistics(); } public static String fileToPath(String filename) throws UnsupportedEncodingException { URL url = MainTestTKS.class.getResource(filename); return java.net.URLDecoder.decode(url.getPath(), "UTF-8"); } }
Java
@Module( library = true ) public final class ActivityModule { private final Activity activity; public ActivityModule(Activity activity) { this.activity = activity; } @ActivityContext @Provides Context provideActivityContext() { return activity; } }
Java
public class CmdLine { private static void doQuery(CommandLine cmd, String queryfilepath, int hashes_per_segment, int overlap_per_segment, int nranks, int subsampling, TranspositionEstimator tpe, int ntransp, double minkurtosis, QueryPruningStrategy qps, boolean verbose) { // TODO if verbose, print out the number of skipped hashes try { QueryResults qres = QueryMethods.query(new FileInputStream(queryfilepath), new File(cmd.getArgs()[0]), hashes_per_segment, overlap_per_segment, nranks, subsampling, tpe, ntransp, minkurtosis, qps); Map<String, Double> res = qres.getResults(); int r = 1; System.out.println("query: " + queryfilepath); for (DocScorePair p : DocScorePair.docscore2scoredoc(res)) { System.out.println(String.format("rank %5d: %10.6f - %s", r++, p.getScore(), p.getDoc())); if (r == 1001) break; } if (verbose) { System.out.println(String.format("pruned|total %d %d", qres.getPrunedHashes(), qres.getTotalConsideredHashes())); } } catch (IOException ex) { Logger.getLogger(CmdLine.class.getName()).log(Level.SEVERE, null, ex); } catch (QueryParsingException ex) { Logger.getLogger(CmdLine.class.getName()).log(Level.SEVERE, null, ex); } catch (InterruptedException ex) { Logger.getLogger(CmdLine.class.getName()).log(Level.SEVERE, null, ex); } } private static int[] parseIntArray(String s) { StringTokenizer t = new StringTokenizer(s, ","); int[] ia = new int[t.countTokens()]; int ti = 0; while (t.hasMoreTokens()) ia[ti] = Integer.parseInt(t.nextToken()); return ia; } public static void main(String[] args) { // last argument is always index path Options options = new Options(); // one of these actions has to be specified OptionGroup actionGroup = new OptionGroup(); actionGroup.addOption(new Option("i", true, "perform indexing")); // if dir, all files, else only one file actionGroup.addOption(new Option("q", true, "perform a single query")); actionGroup.addOption(new Option("b", false, "perform a query batch (read from stdin)")); actionGroup.setRequired(true); options.addOptionGroup(actionGroup); // other options options.addOption(new Option("l", "segment-length", true, "length of a segment (# of chroma vectors)")); options.addOption(new Option("o", "segment-overlap", true, "overlap portion of a segment (# of chroma vectors)")); options.addOption(new Option("Q", "quantization-level", true, "quantization level for chroma vectors")); options.addOption(new Option("k", "min-kurtosis", true, "minimum kurtosis for indexing chroma vectors")); options.addOption(new Option("s", "sub-sampling", true, "sub-sampling of chroma features")); options.addOption(new Option("v", "verbose", false, "verbose output (including timing info)")); options.addOption(new Option("T", "transposition-estimator-strategy", true, "parametrization for the transposition estimator strategy")); options.addOption(new Option("t", "n-transp", true, "number of transposition; if not specified, no transposition is performed")); options.addOption(new Option("f", "force-transp", true, "force transposition by an amount of semitones")); options.addOption(new Option("p", "pruning", false, "enable query pruning; if -P is unspecified, use default strategy")); options.addOption(new Option("P", "pruning-custom", true, "custom query pruning strategy")); // parse HelpFormatter formatter = new HelpFormatter(); CommandLineParser parser = new PosixParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); if (cmd.getArgs().length != 1) throw new ParseException("no index path was specified"); } catch (ParseException ex) { System.err.println("ERROR - parsing command line:"); System.err.println(ex.getMessage()); formatter.printHelp("falcon -{i,q,b} [options] index_path", options); return; } // default values final float[] DEFAULT_TRANSPOSITION_ESTIMATOR_STRATEGY = new float[]{0.65192807f, 0.0f, 0.0f, 0.0f, 0.3532628f, 0.4997167f, 0.0f, 0.41703504f, 0.0f, 0.16297342f, 0.0f, 0.0f}; final String DEFAULT_QUERY_PRUNING_STRATEGY = "ntf:0.340765*[0.001694,0.995720];ndf:0.344143*[0.007224,0.997113];" + "ncf:0.338766*[0.001601,0.995038];nmf:0.331577*[0.002352,0.997884];"; // TODO not the final one int hashes_per_segment = Integer.parseInt(cmd.getOptionValue("l", "150")); int overlap_per_segment = Integer.parseInt(cmd.getOptionValue("o", "50")); int nranks = Integer.parseInt(cmd.getOptionValue("Q", "3")); int subsampling = Integer.parseInt(cmd.getOptionValue("s", "1")); double minkurtosis = Float.parseFloat(cmd.getOptionValue("k", "-100.")); boolean verbose = cmd.hasOption("v"); int ntransp = Integer.parseInt(cmd.getOptionValue("t", "1")); TranspositionEstimator tpe = null; if (cmd.hasOption("t")) { if (cmd.hasOption("T")) { // TODO this if branch is yet to test Pattern p = Pattern.compile("\\d\\.\\d*"); LinkedList<Double> tokens = new LinkedList<Double>(); Matcher m = p.matcher(cmd.getOptionValue("T")); while (m.find()) tokens.addLast(new Double(cmd.getOptionValue("T").substring(m.start(), m.end()))); float[] strategy = new float[tokens.size()]; if (strategy.length != 12) { System.err.println("invalid transposition estimator strategy"); System.exit(1); } for (int i = 0; i < strategy.length; i++) strategy[i] = new Float(tokens.pollFirst()); } else { tpe = new TranspositionEstimator(DEFAULT_TRANSPOSITION_ESTIMATOR_STRATEGY); } } else if (cmd.hasOption("f")) { int[] transps = parseIntArray(cmd.getOptionValue("f")); tpe = new ForcedTranspositionEstimator(transps); ntransp = transps.length; } QueryPruningStrategy qpe = null; if (cmd.hasOption("p")) { if (cmd.hasOption("P")) { qpe = new StaticQueryPruningStrategy(cmd.getOptionValue("P")); } else { qpe = new StaticQueryPruningStrategy(DEFAULT_QUERY_PRUNING_STRATEGY); } } // action if (cmd.hasOption("i")) { try { Indexing.index(new File(cmd.getOptionValue("i")), new File(cmd.getArgs()[0]), hashes_per_segment, overlap_per_segment, subsampling, nranks, minkurtosis, tpe, verbose); } catch (IndexingException ex) { Logger.getLogger(CmdLine.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(CmdLine.class.getName()).log(Level.SEVERE, null, ex); } } if (cmd.hasOption("q")) { String queryfilepath = cmd.getOptionValue("q"); doQuery(cmd, queryfilepath, hashes_per_segment, overlap_per_segment, nranks, subsampling, tpe, ntransp, minkurtosis, qpe, verbose); } if (cmd.hasOption("b")) { try { long starttime = System.currentTimeMillis(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String line = null; while ((line = in.readLine()) != null && !line.trim().isEmpty()) doQuery(cmd, line, hashes_per_segment, overlap_per_segment, nranks, subsampling, tpe, ntransp, minkurtosis, qpe, verbose); in.close(); long endtime = System.currentTimeMillis(); System.out.println(String.format("total time: %ds", (endtime - starttime) / 1000)); } catch (IOException ex) { Logger.getLogger(CmdLine.class.getName()).log(Level.SEVERE, null, ex); } } } }
Java
public class PluginPersistenceModule extends AbstractPersistenceModule { /** * <p>Constructs new <code>PluginPersistenceModule</code> instance. This implementation does nothing.</p> */ public PluginPersistenceModule(ServletContext context) { super(context); } /** * <p>Gets the name of Java package containing the MyBatis mapper classes to be used by the persistence layer of the * application.</p> * * @return a fully-qualified name of package with MyBatis mapper classes. */ @Override protected String getMapperPackageName() { return "com.hmdm.plugin.persistence.mapper"; } /** * <p>Gets the name of Java package containing the Domain Object classes to be used by the persistence layer of the * application.</p> * * @return a fully-qualified name of package with Domain Object classes. */ @Override protected String getDomainObjectsPackageName() { return "com.hmdm.plugin.persistence.domain"; } }
Java
public final class PaginatedRequest { private final String baseUrl; private final HttpServletRequest request; private final String cacheId; private final int start; private final int end; private PaginatedRequest( String baseUrl, HttpServletRequest request, String cacheId, int start, int end) { this.baseUrl = baseUrl; this.request = request; this.cacheId = cacheId; this.start = start; this.end = end; } public int getStart() { return start; } public int getEnd() { return end; } public boolean isPaginated() { return start != 0; } public URI getNext() throws URISyntaxException { URI base = new URI(baseUrl); String query = request.getQueryString() != null ? request.getQueryString() : ""; List<NameValuePair> pairs = URLEncodedUtils.parse(query, Charset.forName("UTF-8")); return new URIBuilder() .setScheme(request.getScheme()) .setHost(base.getHost()) .setPort(base.getPort()) .setPath(request.getRequestURI()) .setParameters(pairs) .setParameter("size", String.valueOf(end - start)) // TODO: This might have to be end + 1 .setParameter("pos", String.valueOf(end)) .setParameter("id", cacheId) .build(); } @Override public String toString() { return "PaginatedRequest{" + "start=" + start + ", end=" + end + '}'; } public static PaginatedRequest fromRequest( String baseUrl, HttpServletRequest request, String cacheId) { // TODO: This already has a better solution, just have to consolidate size parameter handling String size = request.getParameter("size") != null ? request.getParameter("size") : "25"; String pos = request.getParameter("pos"); if (size == null) { return new PaginatedRequest(baseUrl, request, cacheId, 0, 0); } if (pos == null) { return new PaginatedRequest(baseUrl, request, cacheId, 0, Integer.parseInt(size)); } int s = Integer.parseInt(size); int p = Integer.parseInt(pos); return new PaginatedRequest(baseUrl, request, cacheId, p, p + s); } }
Java
public abstract class MasterToSlaveFileCallable<T> implements FileCallable<T> { @Override public void checkRoles(RoleChecker checker) throws SecurityException { checker.check(this, Roles.SLAVE); } private static final long serialVersionUID = 1L; }
Java
public class Certificate { private static final Logger log = LoggerFactory.getLogger(Certificate.class); public enum Algorithm { SHA1("SHA1withRSA"), SHA256("SHA256withRSA"), SHA512("SHA512withRSA"); String name; Algorithm(String name) { this.name = name; } } public static Certificate trustedRootCert = null; public static final String[] saveFields = new String[] {"fingerprint", "commonName", "organization", "validFrom", "validTo", "valid"}; // Valid date range allows UI to only show "Expired" text for valid certificates private static final Instant UNKNOWN_MIN = LocalDateTime.MIN.toInstant(ZoneOffset.UTC); private static final Instant UNKNOWN_MAX = LocalDateTime.MAX.toInstant(ZoneOffset.UTC); private static boolean overrideTrustedRootCert = false; private static DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); private static DateTimeFormatter dateParse = DateTimeFormatter.ofPattern("uuuu-MM-dd['T'][ ]HH:mm:ss[.n]['Z']"); //allow parsing of both ISO and custom formatted dates private X509Certificate theCertificate; private String fingerprint; private String commonName; private String organization; private Instant validFrom; private Instant validTo; //used by review sites UI only private boolean expired = false; private boolean valid = true; //Pre-set certificate for use when missing public static final Certificate UNKNOWN; static { HashMap<String,String> map = new HashMap<>(); map.put("fingerprint", "UNKNOWN REQUEST"); map.put("commonName", "An anonymous request"); map.put("organization", "Unknown"); map.put("validFrom", UNKNOWN_MIN.toString()); map.put("validTo", UNKNOWN_MAX.toString()); map.put("valid", "false"); UNKNOWN = Certificate.loadCertificate(map); } static { try { Security.addProvider(new BouncyCastleProvider()); checkOverrideCertPath(); if (trustedRootCert == null) { trustedRootCert = new Certificate("-----BEGIN CERTIFICATE-----\n" + "MIIELzCCAxegAwIBAgIJALm151zCHDxiMA0GCSqGSIb3DQEBCwUAMIGsMQswCQYD\n" + "VQQGEwJVUzELMAkGA1UECAwCTlkxEjAQBgNVBAcMCUNhbmFzdG90YTEbMBkGA1UE\n" + "CgwSUVogSW5kdXN0cmllcywgTExDMRswGQYDVQQLDBJRWiBJbmR1c3RyaWVzLCBM\n" + "TEMxGTAXBgNVBAMMEHF6aW5kdXN0cmllcy5jb20xJzAlBgkqhkiG9w0BCQEWGHN1\n" + "cHBvcnRAcXppbmR1c3RyaWVzLmNvbTAgFw0xNTAzMDEyMzM4MjlaGA8yMTE1MDMw\n" + "MjIzMzgyOVowgawxCzAJBgNVBAYTAlVTMQswCQYDVQQIDAJOWTESMBAGA1UEBwwJ\n" + "Q2FuYXN0b3RhMRswGQYDVQQKDBJRWiBJbmR1c3RyaWVzLCBMTEMxGzAZBgNVBAsM\n" + "ElFaIEluZHVzdHJpZXMsIExMQzEZMBcGA1UEAwwQcXppbmR1c3RyaWVzLmNvbTEn\n" + "MCUGCSqGSIb3DQEJARYYc3VwcG9ydEBxemluZHVzdHJpZXMuY29tMIIBIjANBgkq\n" + "hkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuWsBa6uk+RM4OKBZTRfIIyqaaFD71FAS\n" + "7kojAQ+ySMpYuqLjIVZuCh92o1FGBvyBKUFc6knAHw5749yhLCYLXhzWwiNW2ri1\n" + "Jwx/d83Wnaw6qA3lt++u3tmiA8tsFtss0QZW0YBpFsIqhamvB3ypwu0bdUV/oH7g\n" + "/s8TFR5LrDfnfxlLFYhTUVWuWzMqEFAGnFG3uw/QMWZnQgkGbx0LMcYzdqFb7/vz\n" + "rTSHfjJsisUTWPjo7SBnAtNYCYaGj0YH5RFUdabnvoTdV2XpA5IPYa9Q597g/M0z\n" + "icAjuaK614nKXDaAUCbjki8RL3OK9KY920zNFboq/jKG6rKW2t51ZQIDAQABo1Aw\n" + "TjAdBgNVHQ4EFgQUA0XGTcD6jqkL2oMPQaVtEgZDqV4wHwYDVR0jBBgwFoAUA0XG\n" + "TcD6jqkL2oMPQaVtEgZDqV4wDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOC\n" + "AQEAijcT5QMVqrWWqpNEe1DidzQfSnKo17ZogHW+BfUbxv65JbDIntnk1XgtLTKB\n" + "VAdIWUtGZbXxrp16NEsh96V2hjDIoiAaEpW+Cp6AHhIVgVh7Q9Knq9xZ1t6H8PL5\n" + "QiYQKQgJ0HapdCxlPKBfUm/Mj1ppNl9mPFJwgHmzORexbxrzU/M5i2jlies+CXNq\n" + "cvmF2l33QNHnLwpFGwYKs08pyHwUPp6+bfci6lRvavztgvnKroWWIRq9ZPlC0yVK\n" + "FFemhbCd7ZVbrTo0NcWZM1PTAbvlOikV9eh3i1Vot+3dJ8F27KwUTtnV0B9Jrxum\n" + "W9P3C48mvwTxYZJFOu0N9UBLLg==\n" + "-----END CERTIFICATE-----"); CRL.getInstance(); // Fetch the CRL } trustedRootCert.valid = true; log.debug("Using trusted root certificate: CN={}, O={} ({})", trustedRootCert.getCommonName(), trustedRootCert.getOrganization(), trustedRootCert.getFingerprint()); } catch(CertificateParsingException e) { e.printStackTrace(); } } private static void checkOverrideCertPath() { // Priority: Check environmental variable String override = System.getProperty("trustedRootCert"); String helpText = "System property \"trustedRootCert\""; if(setOverrideCert(override, helpText, false)) { return; } // Preferred: Look for file called "override.crt" in installation directory override = FileUtilities.getParentDirectory(SystemUtilities.getJarPath()) + File.separator + Constants.OVERRIDE_CERT; helpText = String.format("Override cert \"%s\"", Constants.OVERRIDE_CERT); if(setOverrideCert(override, helpText, true)) { return; } // Fallback (deprecated): Parse "authcert.override" from qz-tray.properties // Entry was created by 2.0 build system, removed in newer versions in favor of the hard-coded filename Properties props = PrintSocketServer.getTrayProperties(); helpText = "Properties file entry \"authcert.override\""; if(props != null && setOverrideCert(props.getProperty("authcert.override"), helpText, false)) { log.warn("Deprecation warning: \"authcert.override\" is no longer supported.\n" + "{} will look for the system property \"trustedRootCert\", or look for" + "a file called {} in the working path.", Constants.ABOUT_TITLE, Constants.OVERRIDE_CERT); return; } } private static boolean setOverrideCert(String path, String helpText, boolean quiet) { if(path != null && !path.trim().isEmpty()) { if (new File(path).exists()) { try { log.error("Using override cert: {}", path); trustedRootCert = new Certificate(FileUtilities.readLocalFile(path)); overrideTrustedRootCert = true; return true; } catch(Exception e) { log.error("Error loading override cert: {}", path, e); } } else if(!quiet) { log.warn("{} \"{}\" was provided, but could not be found, skipping.", helpText, path); } } return false; } /** Decodes a certificate and intermediate certificate from the given string */ @SuppressWarnings("deprecation") public Certificate(String in) throws CertificateParsingException { try { //Setup X.509 CertificateFactory cf = CertificateFactory.getInstance("X.509"); //Strip beginning and end String[] split = in.split("--START INTERMEDIATE CERT--"); byte[] serverCertificate = Base64.decodeBase64(split[0].replaceAll(X509Constants.BEGIN_CERT, "").replaceAll(X509Constants.END_CERT, "")); X509Certificate theIntermediateCertificate; if (split.length == 2) { byte[] intermediateCertificate = Base64.decodeBase64(split[1].replaceAll(X509Constants.BEGIN_CERT, "").replaceAll(X509Constants.END_CERT, "")); theIntermediateCertificate = (X509Certificate)cf.generateCertificate(new ByteArrayInputStream(intermediateCertificate)); } else { theIntermediateCertificate = null; //Self-signed } //Generate cert theCertificate = (X509Certificate)cf.generateCertificate(new ByteArrayInputStream(serverCertificate)); commonName = String.valueOf(PrincipalUtil.getSubjectX509Principal(theCertificate).getValues(X509Name.CN).get(0)); fingerprint = makeThumbPrint(theCertificate); organization = String.valueOf(PrincipalUtil.getSubjectX509Principal(theCertificate).getValues(X509Name.O).get(0)); validFrom = theCertificate.getNotBefore().toInstant(); validTo = theCertificate.getNotAfter().toInstant(); if (trustedRootCert != null) { HashSet<X509Certificate> chain = new HashSet<>(); try { chain.add(trustedRootCert.theCertificate); if (theIntermediateCertificate != null) { chain.add(theIntermediateCertificate); } X509Certificate[] x509Certificates = X509CertificateChainBuilder.buildPath(theCertificate, chain); for(X509Certificate x509Certificate : x509Certificates) { if (x509Certificate.equals(trustedRootCert.theCertificate)) { Instant now = Instant.now(); expired = validFrom.isAfter(now) || validTo.isBefore(now); if (expired) { valid = false; } } } } catch(Exception e) { log.error("Problem building certificate chain", e); } } try { readRenewalInfo(); } catch(Exception e) { log.error("Error reading certificate renewal info", e); } // Only do CRL checks on QZ-issued certificates if (trustedRootCert != null && !overrideTrustedRootCert) { CRL qzCrl = CRL.getInstance(); if (qzCrl.isLoaded()) { if (qzCrl.isRevoked(getFingerprint()) || theIntermediateCertificate == null || qzCrl.isRevoked(makeThumbPrint(theIntermediateCertificate))) { log.warn("Problem verifying certificate with CRL"); valid = false; } } else { //Assume nothing is revoked, because we can't get the CRL log.warn("Failed to retrieve QZ CRL, skipping CRL check"); } } } catch(Exception e) { CertificateParsingException certificateParsingException = new CertificateParsingException(); certificateParsingException.initCause(e); throw certificateParsingException; } } private void readRenewalInfo() throws Exception { // "id-at-description" = "2.5.4.13" Vector values = PrincipalUtil.getSubjectX509Principal(theCertificate).getValues(new ASN1ObjectIdentifier("2.5.4.13")); if (values.isEmpty()) { return; } String renewalInfo = String.valueOf(values.get(0)); String renewalPrefix = "renewal-of-"; if (!renewalInfo.startsWith(renewalPrefix)) { throw new CertificateParsingException("Malformed renewal info"); } String previousFingerprint = renewalInfo.substring(renewalPrefix.length()); if (previousFingerprint.length() != 40) { throw new CertificateParsingException("Malformed renewal fingerprint"); } // Add this certificate to the whitelist if the previous certificate was whitelisted File allowed = FileUtilities.getFile(Constants.ALLOW_FILE, true); if (existsInAnyFile(previousFingerprint, allowed)) { FileUtilities.printLineToFile(Constants.ALLOW_FILE, data()); } } private Certificate() {} /** * Used to rebuild a certificate for the 'Saved Sites' screen without having to decrypt the certificates again */ public static Certificate loadCertificate(HashMap<String,String> data) { Certificate cert = new Certificate(); cert.fingerprint = data.get("fingerprint"); cert.commonName = data.get("commonName"); cert.organization = data.get("organization"); try { cert.validFrom = Instant.from(LocalDateTime.from(dateParse.parse(data.get("validFrom"))).atZone(ZoneOffset.UTC)); cert.validTo = Instant.from(LocalDateTime.from(dateParse.parse(data.get("validTo"))).atZone(ZoneOffset.UTC)); } catch(DateTimeException e) { cert.validFrom = UNKNOWN_MIN; cert.validTo = UNKNOWN_MAX; log.error("Unable to parse certificate date", e); } cert.valid = Boolean.parseBoolean(data.get("valid")); return cert; } /** * Checks given signature for given data against this certificate, * ensuring it is properly signed * * @param signature the signature appended to the data, base64 encoded * @param data the data to check * @return true if signature valid, false if not */ public boolean isSignatureValid(Algorithm algorithm, String signature, String data) { if (!signature.isEmpty()) { //On errors, assume failure. try { Signature verifier = Signature.getInstance(algorithm.name); verifier.initVerify(theCertificate.getPublicKey()); verifier.update(StringUtils.getBytesUtf8(DigestUtils.sha256Hex(data))); return verifier.verify(Base64.decodeBase64(signature)); } catch(GeneralSecurityException e) { log.error("Unable to verify signature", e); } } return false; } /** Checks if the certificate has been added to the local trusted store */ public boolean isSaved() { File allowed = FileUtilities.getFile(Constants.ALLOW_FILE, true); File allowedShared = FileUtilities.getFile(Constants.ALLOW_FILE, false); return existsInAnyFile(getFingerprint(), allowedShared, allowed); } /** Checks if the certificate has been added to the local blocked store */ public boolean isBlocked() { File blocks = FileUtilities.getFile(Constants.BLOCK_FILE, true); File blocksShared = FileUtilities.getFile(Constants.BLOCK_FILE, false); return existsInAnyFile(getFingerprint(), blocksShared, blocks); } private static boolean existsInAnyFile(String fingerprint, File... files) { for(File file : files) { if (file == null) { continue; } try(BufferedReader br = new BufferedReader(new FileReader(file))) { String line; while((line = br.readLine()) != null) { if (line.contains("\t")) { String print = line.substring(0, line.indexOf("\t")); if (print.equals(fingerprint)) { return true; } } } } catch(IOException e) { e.printStackTrace(); } } return false; } public String getFingerprint() { return fingerprint; } public String getCommonName() { return commonName; } public String getOrganization() { return organization; } public String getValidFrom() { if (validFrom.isAfter(UNKNOWN_MIN)) { return dateFormat.format(validFrom.atZone(ZoneOffset.UTC)); } else { return "Not Provided"; } } public String getValidTo() { if (validTo.isBefore(UNKNOWN_MAX)) { return dateFormat.format(validTo.atZone(ZoneOffset.UTC)); } else { return "Not Provided"; } } public Instant getValidFromDate() { return validFrom; } public Instant getValidToDate() { return validTo; } /** * Validates certificate against embedded cert. */ public boolean isTrusted() { return isValid() && !isExpired(); } public boolean isValid() { return valid; } public boolean isExpired() { return expired; } public static String makeThumbPrint(X509Certificate cert) throws NoSuchAlgorithmException, CertificateEncodingException { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(cert.getEncoded()); return ByteUtilities.bytesToHex(md.digest(), false); } public String data() { return getFingerprint() + "\t" + getCommonName() + "\t" + getOrganization() + "\t" + getValidFrom() + "\t" + getValidTo() + "\t" + isTrusted(); } @Override public String toString() { return getOrganization() + " (" + getCommonName() + ")"; } @Override public boolean equals(Object obj) { if (obj instanceof Certificate) { return ((Certificate)obj).data().equals(data()); } return super.equals(obj); } }
Java
@SuppressWarnings("javadoc") public final class HistogramResults extends com.google.api.client.json.GenericJson { /** * Specifies compensation field-based histogram results that match * HistogramFacets.compensation_histogram_requests. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<CompensationHistogramResult> compensationHistogramResults; static { // hack to force ProGuard to consider CompensationHistogramResult used, since otherwise it would be stripped out // see https://github.com/google/google-api-java-client/issues/543 com.google.api.client.util.Data.nullOf(CompensationHistogramResult.class); } /** * Specifies histogram results for custom attributes that match * HistogramFacets.custom_attribute_histogram_facets. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<CustomAttributeHistogramResult> customAttributeHistogramResults; static { // hack to force ProGuard to consider CustomAttributeHistogramResult used, since otherwise it would be stripped out // see https://github.com/google/google-api-java-client/issues/543 com.google.api.client.util.Data.nullOf(CustomAttributeHistogramResult.class); } /** * Specifies histogram results that matches HistogramFacets.simple_histogram_facets. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<HistogramResult> simpleHistogramResults; static { // hack to force ProGuard to consider HistogramResult used, since otherwise it would be stripped out // see https://github.com/google/google-api-java-client/issues/543 com.google.api.client.util.Data.nullOf(HistogramResult.class); } /** * Specifies compensation field-based histogram results that match * HistogramFacets.compensation_histogram_requests. * @return value or {@code null} for none */ public java.util.List<CompensationHistogramResult> getCompensationHistogramResults() { return compensationHistogramResults; } /** * Specifies compensation field-based histogram results that match * HistogramFacets.compensation_histogram_requests. * @param compensationHistogramResults compensationHistogramResults or {@code null} for none */ public HistogramResults setCompensationHistogramResults(java.util.List<CompensationHistogramResult> compensationHistogramResults) { this.compensationHistogramResults = compensationHistogramResults; return this; } /** * Specifies histogram results for custom attributes that match * HistogramFacets.custom_attribute_histogram_facets. * @return value or {@code null} for none */ public java.util.List<CustomAttributeHistogramResult> getCustomAttributeHistogramResults() { return customAttributeHistogramResults; } /** * Specifies histogram results for custom attributes that match * HistogramFacets.custom_attribute_histogram_facets. * @param customAttributeHistogramResults customAttributeHistogramResults or {@code null} for none */ public HistogramResults setCustomAttributeHistogramResults(java.util.List<CustomAttributeHistogramResult> customAttributeHistogramResults) { this.customAttributeHistogramResults = customAttributeHistogramResults; return this; } /** * Specifies histogram results that matches HistogramFacets.simple_histogram_facets. * @return value or {@code null} for none */ public java.util.List<HistogramResult> getSimpleHistogramResults() { return simpleHistogramResults; } /** * Specifies histogram results that matches HistogramFacets.simple_histogram_facets. * @param simpleHistogramResults simpleHistogramResults or {@code null} for none */ public HistogramResults setSimpleHistogramResults(java.util.List<HistogramResult> simpleHistogramResults) { this.simpleHistogramResults = simpleHistogramResults; return this; } @Override public HistogramResults set(String fieldName, Object value) { return (HistogramResults) super.set(fieldName, value); } @Override public HistogramResults clone() { return (HistogramResults) super.clone(); } }
Java
@Component public class TrackedEntityCriteriaMapper { private final CurrentUserService currentUserService; private final OrganisationUnitService organisationUnitService; private final ProgramService programService; private final TrackedEntityTypeService trackedEntityTypeService; private final TrackedEntityAttributeService attributeService; public TrackedEntityCriteriaMapper( CurrentUserService currentUserService, OrganisationUnitService organisationUnitService, ProgramService programService, TrackedEntityAttributeService attributeService, TrackedEntityTypeService trackedEntityTypeService ) { checkNotNull( currentUserService ); checkNotNull( organisationUnitService ); checkNotNull( programService ); checkNotNull( attributeService ); checkNotNull( trackedEntityTypeService ); this.currentUserService = currentUserService; this.organisationUnitService = organisationUnitService; this.programService = programService; this.attributeService = attributeService; this.trackedEntityTypeService = trackedEntityTypeService; } @Transactional( readOnly = true ) public TrackedEntityInstanceQueryParams map( TrackedEntityInstanceCriteria criteria ) { TrackedEntityInstanceQueryParams params = new TrackedEntityInstanceQueryParams(); final Date programEnrollmentStartDate = ObjectUtils.firstNonNull( criteria.getProgramEnrollmentStartDate(), criteria.getProgramStartDate() ); final Date programEnrollmentEndDate = ObjectUtils.firstNonNull( criteria.getProgramEnrollmentEndDate(), criteria.getProgramEndDate() ); Set<OrganisationUnit> possibleSearchOrgUnits = new HashSet<>(); User user = currentUserService.getCurrentUser(); if ( user != null ) { possibleSearchOrgUnits = user.getTeiSearchOrganisationUnitsWithFallback(); } QueryFilter queryFilter = getQueryFilter( criteria.getQuery() ); if ( criteria.getAttribute() != null ) { for ( String attr : criteria.getAttribute() ) { QueryItem it = getQueryItem( attr ); params.getAttributes().add( it ); } } if ( criteria.getFilter() != null ) { for ( String filt : criteria.getFilter() ) { QueryItem it = getQueryItem( filt ); params.getFilters().add( it ); } } for ( String orgUnit : criteria.getOrgUnits() ) { OrganisationUnit organisationUnit = organisationUnitService.getOrganisationUnit( orgUnit ); if ( organisationUnit == null ) { throw new IllegalQueryException( "Organisation unit does not exist: " + orgUnit ); } if ( !organisationUnitService.isInUserHierarchy( organisationUnit.getUid(), possibleSearchOrgUnits ) ) { throw new IllegalQueryException( "Organisation unit is not part of the search scope: " + orgUnit ); } params.getOrganisationUnits().add( organisationUnit ); } validateAssignedUser( criteria ); if ( criteria.getOuMode() == OrganisationUnitSelectionMode.CAPTURE && user != null ) { params.getOrganisationUnits().addAll( user.getOrganisationUnits() ); } Program program = validateProgram( criteria ); params.setQuery( queryFilter ) .setProgram( program ) .setProgramStage( validateProgramStage( criteria, program) ) .setProgramStatus( criteria.getProgramStatus() ) .setFollowUp( criteria.getFollowUp() ) .setLastUpdatedStartDate( criteria.getLastUpdatedStartDate() ) .setLastUpdatedEndDate( criteria.getLastUpdatedEndDate() ) .setLastUpdatedDuration( criteria.getLastUpdatedDuration() ) .setProgramEnrollmentStartDate( programEnrollmentStartDate ) .setProgramEnrollmentEndDate( programEnrollmentEndDate ) .setProgramIncidentStartDate( criteria.getProgramIncidentStartDate() ) .setProgramIncidentEndDate( criteria.getProgramIncidentEndDate() ) .setTrackedEntityType( validateTrackedEntityType( criteria ) ) .setOrganisationUnitMode( criteria.getOuMode() ) .setEventStatus( criteria.getEventStatus() ) .setEventStartDate( criteria.getEventStartDate() ) .setEventEndDate( criteria.getEventEndDate() ) .setAssignedUserSelectionMode( criteria.getAssignedUserMode() ) .setAssignedUsers( criteria.getAssignedUsers() ) .setTrackedEntityInstanceUids( criteria.getTrackedEntityInstances() ) .setSkipMeta( criteria.isSkipMeta() ) .setPage( criteria.getPage() ) .setPageSize( criteria.getPageSize() ) .setTotalPages( criteria.isTotalPages() ) .setSkipPaging( PagerUtils.isSkipPaging( criteria.getSkipPaging(), criteria.getPaging() ) ) .setIncludeDeleted( criteria.isIncludeDeleted() ) .setIncludeAllAttributes( criteria.isIncludeAllAttributes() ) .setUser( user ) .setOrders( getOrderParams( criteria ) ); return params; } /** * Creates a QueryFilter from the given query string. Query is on format * {operator}:{filter-value}. Only the filter-value is mandatory. The EQ * QueryOperator is used as operator if not specified. */ private QueryFilter getQueryFilter( String query ) { if ( query == null || query.isEmpty() ) { return null; } if ( !query.contains( DimensionalObject.DIMENSION_NAME_SEP ) ) { return new QueryFilter( QueryOperator.EQ, query ); } else { String[] split = query.split( DimensionalObject.DIMENSION_NAME_SEP ); if ( split.length != 2 ) { throw new IllegalQueryException( "Query has invalid format: " + query ); } QueryOperator op = QueryOperator.fromString( split[0] ); return new QueryFilter( op, split[1] ); } } /** * Creates a QueryItem from the given item string. Item is on format * {attribute-id}:{operator}:{filter-value}[:{operator}:{filter-value}]. Only * the attribute-id is mandatory. */ private QueryItem getQueryItem( String item ) { String[] split = item.split( DimensionalObject.DIMENSION_NAME_SEP ); if ( split.length % 2 != 1 ) { throw new IllegalQueryException( "Query item or filter is invalid: " + item ); } QueryItem queryItem = getItem( split[0] ); if ( split.length > 1 ) // Filters specified { for ( int i = 1; i < split.length; i += 2 ) { QueryOperator operator = QueryOperator.fromString( split[i] ); queryItem.getFilters().add( new QueryFilter( operator, split[i + 1] ) ); } } return queryItem; } private QueryItem getItem( String item ) { TrackedEntityAttribute at = attributeService.getTrackedEntityAttribute( item ); if ( at == null ) { throw new IllegalQueryException( "Attribute does not exist: " + item ); } return new QueryItem( at, null, at.getValueType(), at.getAggregationType(), at.getOptionSet(), at.isUnique() ); } private Program validateProgram( TrackedEntityInstanceCriteria criteria ) { Function<String, Program> getProgram = uid -> { if ( isNotEmpty( uid ) ) { return programService.getProgram( uid ); } return null; }; final Program program = getProgram.apply( criteria.getProgram() ); if ( isNotEmpty( criteria.getProgram() ) && program == null ) { throw new IllegalQueryException( "Program does not exist: " + criteria.getProgram() ); } return program; } private ProgramStage validateProgramStage( TrackedEntityInstanceCriteria criteria, Program program ) { final String programStage = criteria.getProgramStage(); ProgramStage ps = programStage != null ? getProgramStageFromProgram( program, programStage ) : null; if ( programStage != null && ps == null ) { throw new IllegalQueryException( "Program does not contain the specified programStage: " + programStage ); } return ps; } private TrackedEntityType validateTrackedEntityType( TrackedEntityInstanceCriteria criteria ) { Function<String, TrackedEntityType> getTeiType = uid -> { if ( isNotEmpty( uid ) ) { return trackedEntityTypeService.getTrackedEntityType( uid ); } return null; }; final TrackedEntityType trackedEntityType = getTeiType.apply( criteria.getTrackedEntityType() ); if ( isNotEmpty( criteria.getTrackedEntityType() ) && trackedEntityType == null ) { throw new IllegalQueryException( "Tracked entity type does not exist: " + criteria.getTrackedEntityType() ); } return trackedEntityType; } private void validateAssignedUser( TrackedEntityInstanceCriteria criteria ) { if ( criteria.getAssignedUserMode() != null && !criteria.getAssignedUsers().isEmpty() && !criteria.getAssignedUserMode().equals( AssignedUserSelectionMode.PROVIDED ) ) { throw new IllegalQueryException( "Assigned User uid(s) cannot be specified if selectionMode is not PROVIDED" ); } } private List<String> getOrderParams( TrackedEntityInstanceCriteria criteria ) { if ( !StringUtils.isEmpty( criteria.getOrder() ) ) { return Arrays.asList( criteria.getOrder().split( "," ) ); } return null; } private ProgramStage getProgramStageFromProgram( Program program, String programStage ) { if ( program == null ) { return null; } return program.getProgramStages().stream().filter( ps -> ps.getUid().equals( programStage ) ).findFirst() .orElse( null ); } }
Java
public class GcmService { private Logger logger = Logger.getLogger(getClass().getName()); private ObjectMapper mapper; public static final String DEFAULT_ACTION = "default"; public static final String EVENT_ACTION = "event"; @Autowired private UserDao userDao; public GcmService() { mapper = new ObjectMapper(); } public void notifyFriendRequest(String name, int userId) { notifyUser(name + " har sendt deg en venneforespørsel!", userId, DEFAULT_ACTION, -1); } public void notifyFriendAccepted(String name, int userId) { notifyUser(name + " har godtatt din venneforespørsel!", userId, DEFAULT_ACTION, -1); } public void notifyInactiveWeek(Set<Integer> ids) { for(Integer id: ids) { notifyUser("Meld deg på eller lag en aktivitet denne uka, så blir uka topp :)", id, DEFAULT_ACTION, -1); } } public void notifyNewEvent(int adminId, String firstname, String lastname, int eventId) { List<Friendship> friendships = userDao.findFriends(adminId); Set<Integer> ids = userDao.findFriendsIds(adminId); for(Integer id: ids) { notifyUser(firstname + " har akkurat opprettet en aktivitet!", id, EVENT_ACTION, eventId); } } /* * Only for test purposes */ public void notifyTest(String msg, int userId) { notifyUser(msg, userId, DEFAULT_ACTION, -1); } /* * General purpose notification service, that receives the msg to display and the user's id */ private void notifyUser(String msg, int userId, String action, int actionId) {action: new Thread() { public void run() { String data = "{ \"data\": {\"msg\":\"" + msg + "\", \"action\":\"" + action + "\", \"actionId\":\"" + actionId + "\"}"; Set<String> gcmTokens = userDao.getGcmTokensByUserId(userId); for(String token: gcmTokens) { ResponseEntity<String> response; RestTemplate template = new RestTemplate(); ((SimpleClientHttpRequestFactory) template.getRequestFactory()).setConnectTimeout(1000 * 10); HttpHeaders headers = new HttpHeaders(); headers.set("Content-Type", "application/json; charset=utf-8"); headers.add("Authorization", "key=" + "AIzaSyAzGkBvA_kYil5hLdPSv-26MdezrXJZfqo"); HttpEntity<String> entity = new HttpEntity(data + ",\"to\" : \"" + token + "\"}", headers); try { response = template.exchange("https://gcm-http.googleapis.com/gcm/send", HttpMethod.POST, entity, String.class); final JsonNode node = mapper.readTree(response.getBody()); //if node not registered if ("0".equals(node.get("success").asText())) { final JsonNode arrNode = node.get("results"); for (JsonNode node1 : arrNode) { if (node1.get("error").asText().equals("NotRegistered") || node1.get("error").asText().equals("InvalidRegistration")) { userDao.removeGcmToken(userId, token); } } } } catch (IOException e) { logger.warning("Gcm failed at " + new Date() + " for user " + userId + " and token " + token + ". Reason: " + e.getMessage()); } } } }.start(); } }
Java
@ToString public class Response { /** * The HTTP status code for the response, if any. */ private @Getter int statusCode; /** * Wether the raw body has been parsed into JSON. */ private @Getter boolean parsed; /** * The parsed JSON received from the API, if the result was JSON. */ private @Getter JsonObject result; /** * The data extracted from the JSON data - if the body contained JSON. */ private @Getter JsonElement data; /** * The warnings received from the API call. */ private @Getter JsonElement warnings; /** * The raw body received from the API. */ private @Getter String body; /** * The actual Request object used to make this API call. */ private @Getter Request request; protected Response(Request request) { this.request = request; } // Tries to parse the raw response from the request. protected void parse(HTTPClient client) { parseStatusCode(); if (this.statusCode != 204) { parseData(client); } } // Detects of any exceptions have occured and throws the appropriate exceptions. protected void detectError(HTTPClient client) throws ResponseException { ResponseException exception = null; if (statusCode >= 500) { exception = new ServerException(this); } else if (statusCode == 404) { exception = new NotFoundException(this); } else if (statusCode == 401) { exception = new AuthenticationException(this); } else if (statusCode >= 400) { exception = new ClientException(this); } else if (statusCode == 204) { return; } else if (!parsed) { exception = new ParserException(this); } if (exception != null) { exception.log(client.getConfiguration()); throw exception; } } // Tries to parse the status code. Catches any exceptions and defaults to // status 0 if an error occurred. private void parseStatusCode() { try { this.statusCode = getRequest().getConnection().getResponseCode(); } catch (IOException e) { this.statusCode = 0; } } // Tries to parse the data private void parseData(HTTPClient client) { this.parsed = false; this.body = readBody(); this.result = parseJson(client); this.parsed = this.result != null; if (parsed && result.has("data")) { if (result.get("data").isJsonArray()) { this.data = result.get("data").getAsJsonArray(); } if (result.get("data").isJsonObject()) { this.data = result.get("data").getAsJsonObject(); } } if (parsed && result.has("warnings")) { if (result.get("warnings").isJsonArray()) { this.warnings = result.get("warnings").getAsJsonArray(); } if (result.get("warnings").isJsonObject()) { this.warnings = result.get("warnings").getAsJsonObject(); } } } // Tries to read the body. private String readBody() { // Get the connection HttpURLConnection connection = getRequest().getConnection(); // Try to get the input stream InputStream inputStream = null; try { inputStream = connection.getInputStream(); } catch (IOException e) { inputStream = connection.getErrorStream(); } // Try to parse the input stream try { InputStreamReader inputStreamReader = new InputStreamReader(inputStream); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); StringBuffer body = new StringBuffer(); String inputLine; while ((inputLine = bufferedReader.readLine()) != null) { body.append(inputLine); } bufferedReader.close(); // Return the response body return body.toString(); } catch (IOException e) { // return null if we could not parse the input stream return null; } } // Ties to parse the response body into a JSON Object private JsonObject parseJson(HTTPClient client) { if (isJson()) { return new JsonParser().parse(getBody()).getAsJsonObject(); } return null; } // Checks if the response is likely to be JSON. private boolean isJson() { return hasJsonHeader() && hasBody(); } // Checks if the response headers include a JSON mime-type. private boolean hasJsonHeader() { String contentType = getRequest().getConnection().getHeaderField(Constants.CONTENT_TYPE); String[] expectedContentTypes = new String[] { "application/json", "application/vnd.amadeus+json" }; return Arrays.asList(expectedContentTypes).contains(contentType); } // Checks if the response has a body private boolean hasBody() { return !(body == null || body.isEmpty()); } }
Java
@Mixin(method="prop") public class Document_nextCategorisationTaskRoleAssignedTo extends DomainObject_nextTaskRoleAssignedToAbstract< Document, IncomingDocumentCategorisationStateTransition, IncomingDocumentCategorisationStateTransitionType, IncomingDocumentCategorisationState> { public Document_nextCategorisationTaskRoleAssignedTo(final Document document) { super(document, IncomingDocumentCategorisationStateTransition.class); } public boolean hideProp() { return !DocumentTypeData.hasIncomingType(domainObject) || super.hideProp(); } }
Java
@JsType(namespace = "swell", name = "runtime") public class ServiceEntryPoint implements EntryPoint { private static ServiceContext context; private static ServiceFrontend service; private static PromisableFrontend promisableService; @JsMethod(name = "getCallbackable") public static ServiceFrontend getCallbackableInstance() { return service; } @JsMethod(name = "get") public static PromisableFrontend getPromisableInstance() { return promisableService; } @JsIgnore public static ServiceConnection getServiceConnection() { return service; } @JsIgnore public static ServiceContext getServiceContext() { return context; } private static String getServerURL() { String url = GWT.getModuleBaseURL(); int c = 3; String s = url; int index = -1; while (c > 0) { index = s.indexOf("/", index + 1); if (index == -1) break; c--; } if (c == 0) url = url.substring(0, index); return url; } /** * Client apps can register handlers to be notified when SwellRT library is * fully functional. * <p> * See "swellrt.js" file for details. */ private static native void notifyOnLoadHandlers( PromisableFrontend sf) /*-{ if (!$wnd.swell) { console.log("Swell object not ready yet! wtf?") } for(var i in $wnd._lh) { $wnd._lh[i](sf); } delete $wnd._lh; }-*/; private static native void getEditorConfigProvider() /*-{ if (!$wnd.__swell_editor_config) { $wnd.__swell_editor_config = {}; } }-*/; private static native ServiceConfigProvider getConfigProvider() /*-{ if (!$wnd.__swell_config) { $wnd.__swell_config = {}; } return $wnd.__swell_config = {}; }-*/; @JsIgnore @Override public void onModuleLoad() { // Making sure Editor registries are initialized before // getting any instance of ContentDocument SEditorStatics.initRegistries(); ModelFactory.instance = new WebModelFactory(); WaveDeps.logFactory = new Log.Factory() { @Override public Log create(Class<? extends Object> clazz) { return new WebLog(clazz); } }; WaveDeps.loaderFactory = new WaveLoader.Factory() { @Override public WaveLoader create(WaveId waveId, RemoteViewServiceMultiplexer channel, IdGenerator idGenerator, String localDomain, Set<ParticipantId> participants, ParticipantId loggedInUser, UnsavedDataListener dataListener, TurbulenceListener turbulenceListener, DiffProvider diffProvider) { return new StagedWaveLoader(waveId, channel, idGenerator, localDomain, participants, loggedInUser, dataListener, turbulenceListener, diffProvider); } }; WaveDeps.intRandomGeneratorInstance = new WaveDeps.IntRandomGenerator() { @Override public int nextInt() { return Random.nextInt(); } }; WaveDeps.protocolMessageUtils = new JsProtocolMessageUtils(); WaveDeps.websocketFactory = new WebSocket.Factory() { @Override public WebSocket create() { return new WebWebSocket(); } }; WaveDeps.json = new JsonParser() { @Override public <T, R extends T> T parse(String json, Class<R> dataType) { return JSON.<T> parse(json); } @Override public <O> String serialize(O data) { if (data != null) { if (data instanceof JavaScriptObject) { return JsonUtils.stringify((JavaScriptObject) data); } } return null; } }; WaveDeps.sJsonFactory = new SJsonFactoryWeb(); WaveDeps.lowPriorityTimer = SchedulerInstance.getLowPriorityTimer(); WaveDeps.mediumPriorityTimer = SchedulerInstance.getMediumPriorityTimer(); WaveDeps.highPriorityTimer = SchedulerInstance.getHighPriorityTimer(); WaveDeps.colorGeneratorInstance = new WaveDeps.ColorGenerator() { @Override public RgbColor getColor(String id) { int colorIndex = id.hashCode() % RgbColorPalette.PALETTE.length; colorIndex = colorIndex < 0 ? -colorIndex : colorIndex; RgbColor colour = RgbColorPalette.PALETTE[colorIndex].get("400"); return colour; } }; ServiceDeps.serviceSessionFactory = new ServiceSession.Factory() { @Override public ServiceSession create(Account account) { return new WebServiceSession(account); } @Override public String getWindowId() { return WebServiceSession.WINDOW_ID; } }; ServiceConfig.configProvider = getConfigProvider(); getEditorConfigProvider(); if (ServiceConfig.captureExceptions() || LogLevel.showErrors()) { GWT.setUncaughtExceptionHandler(new GWT.UncaughtExceptionHandler() { @Override public void onUncaughtException(Throwable e) { GWT.log("Uncaught Exception", e); e.printStackTrace(System.err); } }); } else { GWT.setUncaughtExceptionHandler(null); } // Notify the host page that client is already loaded Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand() { @Override public void execute() { context = new ServiceContext(getServerURL(), new DiffProvider.Factory() { @Override public DiffProvider get(WaveId waveId) { return new RemoteDiffProvider(waveId, context); } }); ServiceDeps.serviceContext = context; ServiceDeps.remoteOperationExecutor = new WebServerOperationExecutor(context); service = DefaultFrontend.create(context, ServiceDeps.remoteOperationExecutor); promisableService = new PromisableFrontend(service); notifyOnLoadHandlers(promisableService); } }); } }
Java
public class GACallSet { /** * The call set ID. */ private String id; /** * The call set name. */ private String name; /** * The sample this call set's data was generated from. */ private String sampleId; /** * The IDs of the variant sets this call set has calls in. */ private List<String> variantSetIds; /** * The date this call set was created in milliseconds from the epoch. */ private long created; /** * The time at which this call set was last updated in milliseconds from the epoch. */ private long updated; /** * A map of additional call set information. */ private Map<String, List> info; public GACallSet(String id, String sampleId) { this(id, null, sampleId, null, 0, 0, null); } public GACallSet(String id, String name, String sampleId, List<String> variantSetIds, long created, long updated, Map<String, List> info) { this.id = id; this.name = name; this.sampleId = sampleId; this.variantSetIds = variantSetIds != null ? variantSetIds : new ArrayList<String>(); this.created = created; this.updated = updated; this.info = info != null ? info : new HashMap<String, List>(); } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSampleId() { return sampleId; } public void setSampleId(String sampleId) { this.sampleId = sampleId; } public List<String> getVariantSetIds() { return variantSetIds; } public void setVariantSetIds(List<String> variantSetIds) { this.variantSetIds = variantSetIds; } public long getCreated() { return created; } public void setCreated(long created) { this.created = created; } public long getUpdated() { return updated; } public void setUpdated(long updated) { this.updated = updated; } public Map<String, List> getInfo() { return info; } public void setInfo(Map<String, List> info) { this.info = info; } }
Java
class SelectionMessage extends SelectionRerouteEdge { /** * Logger. */ private static final Logger LOG = Logger.getLogger(SelectionMessage.class.getName()); /** * The constructor. * * @param feme the fig. */ public SelectionMessage(FigEdgeModelElement feme) { super(feme); } @Override public void keyPressed(KeyEvent ke) { if (ke.getKeyCode() == KeyEvent.VK_LEFT || ke.getKeyCode() == KeyEvent.VK_RIGHT) { // we don't let the user move the messages horizontally. ke.consume(); } else { handleMovement(); } } @Override public void mousePressed(MouseEvent me) { FigMessage message = (FigMessage) getContent(); if (!message.isSelfMessage()) { super.mousePressed(me); } } @Override public void dragHandle(int x, int y, int w, int h, Handle handle) { FigMessage message = (FigMessage) getContent(); if (message.isSelfMessage()) { message.translate(0, y - message.getY()); } else { super.dragHandle(x, y, w, h, handle); handleMovement(); } } private void handleMovement() { FigMessage figMessage = (FigMessage) getContent(); FigClassifierRole source = (FigClassifierRole) figMessage.getSourceFigNode(); FigClassifierRole dest = (FigClassifierRole) figMessage.getDestFigNode(); // if the edge is near the bottom of the classifier roles, // we enlarge all the FigClassifierRoles in the diagram. if (figMessage.getFinalY() > source.getY() + source.getHeight() - 10) { final int newHeight = source.getHeight() + 10; final List<Fig> figs = getContent().getLayer().getContents(); for (Fig workOnFig : figs) { if (workOnFig instanceof FigClassifierRole) { workOnFig.setHeight(newHeight); } } } dest.positionHead(figMessage); // we recalculate all the activations source.createActivations(); if (!figMessage.isSelfMessage()) { dest.createActivations(); } } }
Java
class Text extends BaseTemplate { /** * The plain text. Required. */ private String text; /** The escape's char or empty. */ private String escapeChar; /** * Creates a new {@link Text}. * * @param handlebars A handlebars instance. Required. * @param text The text content. Required. * @param escapeChar The escape char or empty. */ public Text(final Handlebars handlebars, final String text, final String escapeChar) { super(handlebars); this.text = notNull(text, "The text content is required."); this.escapeChar = escapeChar; } /** * Creates a new {@link Text}. * * @param handlebars A handlebars instance. Required. * @param text The text content. Required. */ public Text(final Handlebars handlebars, final String text) { this(handlebars, text, ""); } @Override public String text() { return escapeChar + text; } /** * @return Same as {@link #text()} without the escape char. */ public String textWithoutEscapeChar() { return text; } @Override protected void merge(final Context scope, final Writer writer) throws IOException { writer.append(text); } /** * Append text. * * @param text The text to append. * @return This object. */ public Text append(final String text) { this.text += text; return this; } }
Java
public class DPExpList { public static HashMap<String, List<String>> getInfo() { HashMap<String, List<String>> CarDetails = new HashMap<String, List<String>>(); List<String> Truck_Type = new ArrayList<String>(); Truck_Type.add("34 TK 0001"); Truck_Type.add("34 TK 0002"); Truck_Type.add("34 TK 0003"); Truck_Type.add("34 TK 0004"); List<String> TIR_Type = new ArrayList<String>(); TIR_Type.add("34 TR 0001"); TIR_Type.add("34 TR 0002"); TIR_Type.add("34 TR 0003"); TIR_Type.add("34 TR 0004"); List<String> Automobile_Type = new ArrayList<String>(); Automobile_Type.add("34 AU 0001"); Automobile_Type.add("34 AU 0002"); Automobile_Type.add("34 AU 0003"); Automobile_Type.add("34 AU 0004"); List<String> Motorcycle_Type = new ArrayList<String>(); Motorcycle_Type.add("34 MC 0001"); Motorcycle_Type.add("34 MC 0002"); Motorcycle_Type.add("34 MC 0003"); Motorcycle_Type.add("34 MC 0004"); CarDetails.put("Trucks",Truck_Type); CarDetails.put("TIR",TIR_Type); CarDetails.put("Automobiles",Automobile_Type); CarDetails.put("Motorcycles",Motorcycle_Type); return CarDetails; } }
Java
public abstract class AbstractFilteredComponentsExportIndication extends AbstractExportIndication { private final Collection<String> componentIds = Sets.newHashSet(); public AbstractFilteredComponentsExportIndication(final SignalProtocol<?> protocol, final short exportSignal) { super(protocol, exportSignal); } @Override protected void postIndicating(ExtendedDataInputStream in) throws Exception { final int size = in.readInt(); for (int i = 0; i < size; i++) { componentIds.add(in.readUTF()); } } public Collection<String> getComponentIds() { return componentIds; } }
Java
@WebFilter(filterName = "f1", urlPatterns = { "/servleti/*" }) public class ConnectionSetterFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void destroy() { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { DataSource ds = (DataSource) request.getServletContext().getAttribute("hr.fer.zemris.dbpool"); Connection con = null; try { con = ds.getConnection(); } catch (SQLException e) { throw new IOException("Baza podataka nije dostupna.", e); } SQLConnectionProvider.setConnection(con); try { chain.doFilter(request, response); } finally { SQLConnectionProvider.setConnection(null); try { con.close(); } catch (SQLException ignorable) { } } } }
Java
public class RegexUtil { /** * Given a string in the command format, extract the argument values * An argument can be repeated more than once, thus each argument has * an ArrayList of string values. * * @param command command header for the input * @param args arguments to search for * @param input input string * @return ArrayList of each argument's ArrayList of values */ public static ArrayList<ArrayList<String>> parseCommandFormat(String command, String[] args, String input) { ArrayList<String> inp = new ArrayList<>(Arrays .asList(command.length() == 0 ? input : input.split("^" + ignoreCase(command) + "\\s*")[1])); ArrayList<Integer> ain = new ArrayList<>(Arrays.asList(-1)); ArrayList<ArrayList<String>> res = new ArrayList<>(); for (int i = 0; i < args.length; i++) { res.add(new ArrayList<>()); for (int j = 0; j < inp.size(); j++) { String[] sub = inp.get(j).split(args[i]); for (int l = 0; l < sub.length; l++) { sub[l] = sub[l].replaceAll("\\s+$", ""); } inp.set(j, sub[0]); for (int k = 1; k < sub.length; k++) { j++; inp.add(j, sub[k]); ain.add(j, i); } } } for (int i = 1; i < inp.size(); i++) { res.get(ain.get(i)).add(inp.get(i)); } return res; } /** * Generate regex to match a command format input. * * @param command command header * @param args arguments in the command * @return regex matching the command format */ public static String commandFormatRegex(String command, String[] args) { return Arrays.stream(args).reduce("^" + ignoreCase(command), (a, v) -> a + argGroup(v), String::join) + ".*"; } /** * Returns a regex for an argument in a command. * * @param arg argument text * @return regex for an argument in a command */ public static String argGroup(String arg) { return lookAhead(ignoreCase(arg)); } /** * Returns a regex that expects a regex paired with string * * @param arg argument regex * @return regex paired with string */ public static String pairWith(String arg) { return pairWith(arg, false); } /** * Returns a regex that expects a regex paired with string or number. * * @param arg argument regex * @param num true; pairs with number, false; any string * @return regex paired with string or number */ public static String pairWith(String arg, Boolean num) { return arg + "\\s*" + (num ? "[0-9]+" : "\\S"); } /** * Returns a regex that looks ahead for regex. * * @param arg argument regex * @return lookahead regex */ public static String lookAhead(String arg) { return "(?=.*" + arg + ")"; } /** * Returns a regex that ignore case for argument. * * @param arg argument regex * @return ignore case regex result */ public static String ignoreCase(String arg) { return "((?i)" + arg + ")"; } }
Java
public class UpdatePluginData extends ConfluenceActionSupport { private final ActiveObjects ao; private final UserDetailsManager userDetailsManager; private UpdatePluginDataThread updatePluginDataThread; private float updateStatusPercentage; private String userProfileUpdateIsInProgress = "false"; private final PersonalInformationManager personalInformationManager; private final AvatarManager avatarManager; public UpdatePluginData(ActiveObjects ao, UserDetailsManager userDetailsManager, PersonalInformationManager personalInformationManager, AvatarManager avatarManager) { this.ao = ao; this.userDetailsManager = userDetailsManager; this.personalInformationManager = personalInformationManager; this.avatarManager = avatarManager; } @Override public String execute() throws Exception { List<User> userNameList = userAccessor.getUsers().getCurrentPage(); int noOfUsers = userNameList.size(); int noOfThreads = 5; if (noOfUsers <= noOfThreads) { noOfThreads = 1; } int threadSize = noOfUsers / noOfThreads + 1; int startIndex = 0; int endIndex = threadSize; UpdatePluginDataThread.setUserCnt(1); UpdatePluginDataThread.setSchedulerStatus("false"); UpdatePluginDataThread.setSchedulerValue(0.0f); for (int i = 0; i < noOfThreads; i++) { if (endIndex > noOfUsers) { endIndex = noOfUsers; } updatePluginDataThread = new UpdatePluginDataThread(ao, userDetailsManager, userNameList.subList(startIndex, endIndex), noOfUsers, personalInformationManager, avatarManager); Thread thread = new Thread(updatePluginDataThread); thread.start(); startIndex = startIndex + threadSize; endIndex = endIndex + threadSize; if (startIndex > noOfUsers) { return SUCCESS; } } return SUCCESS; } @Override public String doDefault() throws Exception { return SUCCESS; } public float getUpdateStatusPercentage() { return updateStatusPercentage; } public String isUserProfileUpdateIsInProgress() { return userProfileUpdateIsInProgress; } }
Java
public class Menu { public static HashMap<Integer, IMenuItem> createMenu(BookLibrary bookLibrary, MovieLibrary movieLibrary){ HashMap<Integer,IMenuItem> menuOptions = new HashMap<Integer, IMenuItem>(); menuOptions.put(1,new DisplayBookList(bookLibrary)); menuOptions.put(2, new CheckoutBook(bookLibrary)); menuOptions.put(3, new ReturnItem(bookLibrary)); menuOptions.put(4, new DisplayMyBookList(bookLibrary)); menuOptions.put(5, new DisplayMovieList(movieLibrary)); menuOptions.put(6, new CheckoutMovie(movieLibrary)); menuOptions.put(9, new Logout()); menuOptions.put(0, new Exit()); return menuOptions; } }
Java
public class ByteStreamWritingMessageHandler extends AbstractMessageHandler { private final BufferedOutputStream stream; public ByteStreamWritingMessageHandler(OutputStream stream) { this(stream, -1); } public ByteStreamWritingMessageHandler(OutputStream stream, int bufferSize) { if (bufferSize > 0) { this.stream = new BufferedOutputStream(stream, bufferSize); } else { this.stream = new BufferedOutputStream(stream); } } @Override public String getComponentType() { return "stream:outbound-channel-adapter(byte)"; } @Override protected void handleMessageInternal(Message<?> message) { Object payload = message.getPayload(); try { if (payload instanceof String) { this.stream.write(((String) payload).getBytes()); } else if (payload instanceof byte[]) { this.stream.write((byte[]) payload); } else { throw new MessagingException(this.getClass().getSimpleName() + " only supports byte array and String-based messages"); } this.stream.flush(); } catch (IOException e) { throw new MessagingException("IO failure occurred in target", e); } } }
Java
@Weave(type = MatchType.BaseClass, originalName = "com.netflix.hystrix.HystrixCollapser") public abstract class WeaveHystrixCollapser<BatchReturnType, ResponseType, RequestArgumentType> { @Trace public abstract Future<ResponseType> queue(); @Trace public abstract Observable<ResponseType> toObservable(Scheduler observeOn); }
Java
@RunWith(PowerMockRunner.class) // Support for mocking static methods @PrepareForTest(Logger.class) // We mock the Logger class to avoid its calls to android.util.log public class Vec3Test { final static double TOLERANCE = 1e-10; /** * Tests default constructor member initialization. * * @throws Exception */ @Test public void testConstructor_Default() throws Exception { Vec3 u = new Vec3(); assertNotNull(u); assertEquals("x", 0d, u.x, 0d); assertEquals("y", 0d, u.y, 0d); assertEquals("z", 0d, u.z, 0d); } /** * Tests constructor member initialization from doubles. * * @throws Exception */ @Test public void testConstructor_Doubles() throws Exception { final double x1 = 3.1; final double y1 = 4.2; final double z1 = 5.3; Vec3 u = new Vec3(x1, y1, z1); assertNotNull(u); assertEquals("x", x1, u.x, 0d); assertEquals("y", y1, u.y, 0d); assertEquals("y", z1, u.z, 0d); } /** * Ensures equality of object and its members. * * @throws Exception */ @Test public void testEquals() throws Exception { final double x1 = 3.1; final double y1 = 4.2; final double z1 = 5.3; Vec3 u = new Vec3(x1, y1, z1); Vec3 v = new Vec3(x1, y1, z1); assertEquals("equality: x", x1, u.x, 0); assertEquals("equality: y", y1, u.y, 0); assertEquals("equality: z", z1, u.z, 0); assertEquals("equality", u, u); // equality with self assertEquals("equality", u, v); // equality with other } /** * Ensures inequality with null object. * * @throws Exception */ @Test public void testEquals_WithNull() throws Exception { Vec3 u = new Vec3(); Vec3 v = null; assertNotEquals("inequality with null", u, v); } /** * Ensures inequality of object and members. * * @throws Exception */ @Test public void testEquals_Inequality() throws Exception { final double x1 = 3.1; final double y1 = 4.2; final double z1 = 5.3; final double val = 17d; Vec3 u = new Vec3(x1, y1, z1); // Vary a each component to assert equals() tests all components Vec3 vx = new Vec3(val, y1, z1); Vec3 vy = new Vec3(x1, val, z1); Vec3 vz = new Vec3(x1, y1, val); assertNotEquals("inequality: x component", u, vx); assertNotEquals("inequality: y component", u, vy); assertNotEquals("inequality: z component", u, vz); } /** * Ensures string output contains member representations. * * @throws Exception */ @Test public void testToString() throws Exception { final double x1 = 3.1; final double y1 = 4.2; final double z1 = 5.3; Vec3 u = new Vec3(x1, y1, z1); String string = u.toString(); assertTrue("x", string.contains(Double.toString(x1))); assertTrue("y", string.contains(Double.toString(y1))); assertTrue("z", string.contains(Double.toString(z1))); } /** * Ensures the correct computation of vector's magnitude, or length.. * * @throws Exception */ @Test public void testMagnitude() throws Exception { final double x1 = 3.1; final double y1 = 4.2; final double z1 = -5.3; Vec3 u = new Vec3(x1, y1, z1); double magnitude = u.magnitude(); assertEquals("magnitude", Math.sqrt(x1 * x1 + y1 * y1 + z1 * z1), magnitude, Double.MIN_VALUE); } /** * Ensures a zero length vector from default constructor. * * @throws Exception */ @Test public void testMagnitude_ZeroLength() throws Exception { Vec3 u = new Vec3(); double magnitude = u.magnitude(); assertEquals("zero length", 0d, magnitude, 0); } /** * Ensures length is NaN when a member is NaN. * * @throws Exception */ @Test public void testMagnitude_NaN() throws Exception { final double x1 = 3.1; final double y1 = 4.2; final double z1 = Double.NaN; Vec3 u = new Vec3(x1, y1, z1); double magnitude = u.magnitude(); assertTrue("Nan", Double.isNaN(magnitude)); } /** * Tests the squared length of a vector with a well known right-triangle. * * @throws Exception */ @Test public void testMagnitudeSquared() throws Exception { final double x1 = 3.1; final double y1 = 4.2; final double z1 = -5.3; Vec3 u = new Vec3(x1, y1, z1); double magnitudeSquared = u.magnitudeSquared(); assertEquals("magnitude squared", x1 * x1 + y1 * y1 + z1 * z1, magnitudeSquared, Double.MIN_VALUE); } /** * Tests the distance (or displacement) between two opposing position-vectors. * * @throws Exception */ @Test public void testDistanceTo() throws Exception { final double x1 = 3.1; final double y1 = 4.2; final double z1 = -5.3; final double x2 = -x1; final double y2 = -y1; final double z2 = -z1; Vec3 u = new Vec3(x1, y1, z1); Vec3 v = new Vec3(x2, y2, z2); double magnitude = u.magnitude(); double distanceTo = u.distanceTo(v); assertEquals("distance", magnitude * 2, distanceTo, Double.MIN_VALUE); } /** * Ensures distanceTo with null argument is handled correctly. * * @throws Exception */ @Test(expected = IllegalArgumentException.class) public void testDistanceTo_NullArgument() throws Exception { // Mock all the static methods in Logger PowerMockito.mockStatic(Logger.class); Vec3 u = new Vec3(3, 4, 5); double distanceTo = u.distanceTo(null); fail("Expected an IllegalArgumentException to be thrown."); } /** * Tests the squared distance (or displacement) between two opposing position-vectors. * * @throws Exception */ @Test public void testDistanceToSquared() throws Exception { final double x1 = 3.1; final double y1 = 4.2; final double z1 = -5.3; final double x2 = -x1; final double y2 = -y1; final double z2 = -z1; Vec3 u = new Vec3(x1, y1, z1); Vec3 v = new Vec3(x2, y2, z2); double magnitude = u.magnitude(); double distanceToSquared = u.distanceToSquared(v); assertEquals("distance squared", Math.pow(magnitude * 2, 2), distanceToSquared, Double.MIN_VALUE); } /** * Ensures distanceToSquared with null argument is handled correctly. * * @throws Exception */ @Test(expected = IllegalArgumentException.class) public void testDistanceToSquared_NullArgument() throws Exception { // Mock all the static methods in Logger PowerMockito.mockStatic(Logger.class); Vec3 u = new Vec3(3, 4, 5); double distanceToSquared = u.distanceToSquared(null); fail("Expected an IllegalArgumentException to be thrown."); } /** * Ensures the members are equal to the set method arguments. * * @throws Exception */ @Test public void testSet() throws Exception { final double x1 = 3.1; final double y1 = 4.2; final double z1 = -5.3; Vec3 u = new Vec3(x1, y1, z1); Vec3 v = u.set(x1, y1, z1); assertEquals("x", x1, u.x, 0d); assertEquals("y", y1, u.y, 0d); assertEquals("z", z1, u.z, 0d); // Assert fluent API returns u assertEquals("v == u", u, v); } /** * Ensures the components of the two vectors are swapped and the fluent API is maintained. * * @throws Exception */ @Test public void testSwap() throws Exception { final double x1 = 3.1; final double y1 = 4.2; final double z1 = -5.3; final double x2 = -6.4; final double y2 = -7.5; final double z2 = -8.6; Vec3 u = new Vec3(x1, y1, z1); Vec3 v = new Vec3(x2, y2, z2); Vec3 w = u.swap(v); assertEquals("u.x", x2, u.x, 0d); assertEquals("u.y", y2, u.y, 0d); assertEquals("u.z", z2, u.z, 0d); assertEquals("v.x", x1, v.x, 0d); assertEquals("v.y", y1, v.y, 0d); assertEquals("v.z", z1, v.z, 0d); // Assert fluent API returns u assertSame("w == u", u, w); } /** * Ensures swap with null argument is handled correctly. * * @throws Exception */ @Test(expected = IllegalArgumentException.class) public void testSwap_WithNull() throws Exception { PowerMockito.mockStatic(Logger.class); Vec3 u = new Vec3(3, 4, 5); u.swap(null); fail("Expected an IllegalArgumentException to be thrown."); } /** * Ensures the correct addition of two vectors, arguments are not mutated, and the proper fluent API result. * * @throws Exception */ @Test public void testAdd() throws Exception { final double x1 = 3.1d; final double y1 = 4.3d; final double z1 = 5.5d; final double x2 = 6.2d; final double y2 = 7.4d; final double z2 = 8.6d; Vec3 u = new Vec3(x1, y1, z1); Vec3 v = new Vec3(x2, y2, z2); Vec3 w = u.add(v); assertEquals("u.x", x1 + x2, u.x, 0d); assertEquals("u.y", y1 + y2, u.y, 0d); assertEquals("u.z", z1 + z2, u.z, 0d); // Assert v is not altered assertEquals("v.x", x2, v.x, 0d); assertEquals("v.y", y2, v.y, 0d); assertEquals("v.z", z2, v.z, 0d); // Assert fluent API returns u assertSame("w == u", u, w); } /** * Ensures add with null argument is handled correctly. * * @throws Exception */ @Test(expected = IllegalArgumentException.class) public void testAdd_WithNull() throws Exception { PowerMockito.mockStatic(Logger.class); Vec3 u = new Vec3(3, 4, 5); u.add(null); fail("Expected an IllegalArgumentException to be thrown."); } /** * Ensures the correct subtraction of two vectors, arguments are not mutated, and the proper fluent API result. * * @throws Exception */ @Test public void testSubtract() throws Exception { final double x1 = 3.1d; final double y1 = 4.3d; final double z1 = 5.5d; final double x2 = 6.2d; final double y2 = 7.4d; final double z2 = 8.6d; Vec3 u = new Vec3(x1, y1, z1); Vec3 v = new Vec3(x2, y2, z2); Vec3 w = u.subtract(v); assertEquals("u.x", x1 - x2, u.x, 0d); assertEquals("u.y", y1 - y2, u.y, 0d); assertEquals("u.z", z1 - z2, u.z, 0d); // Assert v is not altered assertEquals("v.x", x2, v.x, 0d); assertEquals("v.y", y2, v.y, 0d); assertEquals("v.z", z2, v.z, 0d); // Assert fluent API returns u assertSame("w == u", u, w); } /** * Ensures subtract with null argument is handled correctly. * * @throws Exception */ @Test(expected = IllegalArgumentException.class) public void testSubtract_WithNull() throws Exception { PowerMockito.mockStatic(Logger.class); Vec3 u = new Vec3(3, 4, 5); u.subtract(null); fail("Expected an IllegalArgumentException to be thrown."); } /** * Ensures the correct multiplication of a vector and a scalar, and the proper fluent API result. * * @throws Exception */ @Test public void testMultiply() throws Exception { final double x1 = 3d; final double y1 = 4d; final double z1 = 5d; final double scalar = 6d; Vec3 u = new Vec3(x1, y1, z1); Vec3 v = u.multiply(scalar); assertEquals("u.x", x1 * scalar, u.x, 0d); assertEquals("u.y", y1 * scalar, u.y, 0d); assertEquals("u.z", z1 * scalar, u.z, 0d); // Assert fluent API returns u assertSame("v == u", u, v); } @Test public void testMultiplyByMatrix() throws Exception { double theta = 30d; double x = 2; double y = 3; double z = 0; // Rotate and translate a unit vector Matrix4 m = new Matrix4().multiplyByRotation(0, 0, 1, theta).setTranslation(x, y, z); Vec3 u = new Vec3(1, 0, 0).multiplyByMatrix(m); assertEquals("acos u.x", theta, Math.toDegrees(Math.acos(u.x - x)), 1e-10); assertEquals("asin u.y", theta, Math.toDegrees(Math.asin(u.y - y)), 1e-10); } /** * Ensures the correct division of a vector by a divisor, and the proper fluent API result. * * @throws Exception */ @Test public void testDivide() throws Exception { final double x1 = 3d; final double y1 = 4d; final double z1 = 5d; final double divisor = 6d; Vec3 u = new Vec3(x1, y1, z1); Vec3 v = u.divide(divisor); assertEquals("u.x", x1 / divisor, u.x, 0d); assertEquals("u.y", y1 / divisor, u.y, 0d); assertEquals("u.z", z1 / divisor, u.z, 0d); // Assert fluent API returns u assertSame("v == u", u, v); } /** * Ensures the correct negation of the components and the proper fluent API result. * * @throws Exception */ @Test public void testNegate() throws Exception { final double x1 = 3d; final double y1 = -4d; final double z1 = 5d; Vec3 u = new Vec3(x1, y1, z1); Vec3 v = u.negate(); assertEquals("u.x", -x1, u.x, 0d); assertEquals("u.y", -y1, u.y, 0d); assertEquals("u.z", -z1, u.z, 0d); // Assert fluent API returns u assertSame("v == u", u, v); } /** * Ensures the correct unit vector components and length and the proper fluent API result. * * @throws Exception */ @Test public void testNormalize() throws Exception { final double x1 = 3d; final double y1 = 4d; final double z1 = 5d; final double length = Math.sqrt(50); Vec3 u = new Vec3(x1, y1, z1); Vec3 v = u.normalize(); double magnitude = u.magnitude(); assertEquals("u.x", (1 / length) * x1, u.x, 0d); assertEquals("u.y", (1 / length) * y1, u.y, 0d); assertEquals("u.z", (1 / length) * z1, u.z, 0d); assertEquals("unit length", 1.0, magnitude, TOLERANCE); // Assert fluent API returns u assertSame("v == u", u, v); } /** * Ensures the correct dot product (or inner product) of two vectors and vectors are not mutated. * * @throws Exception */ @Test public void testDot() throws Exception { final double x1 = 3.1d; final double y1 = 4.3d; final double z1 = 5.5d; final double x2 = 6.2d; final double y2 = 7.4d; final double z2 = 8.6d; Vec3 u = new Vec3(x1, y1, z1); Vec3 v = new Vec3(x2, y2, z2); double dot = u.dot(v); assertEquals("dot", x1 * x2 + y1 * y2 + z1 * z2, dot, 0d); // Assert u is not altered assertEquals("u.x", x1, u.x, 0d); assertEquals("u.y", y1, u.y, 0d); assertEquals("u.z", z1, u.z, 0d); // Assert v is not altered assertEquals("v.x", x2, v.x, 0d); assertEquals("v.y", y2, v.y, 0d); assertEquals("v.z", z2, v.z, 0d); } /** * Ensures dot with null argument is handled correctly. * * @throws Exception */ @Test(expected = IllegalArgumentException.class) public void testDot_WithNull() throws Exception { PowerMockito.mockStatic(Logger.class); Vec3 u = new Vec3(3, 4, 5); double dot = u.dot(null); fail("Expected an IllegalArgumentException to be thrown."); } /** * Ensures the correct cross product (or outer product), arguments are not mutated, and the fluent API is * maintained. * * @throws Exception */ @Test public void testCross() throws Exception { final double x1 = 1d; final double y1 = 3d; final double z1 = -4d; final double x2 = 2d; final double y2 = -5d; final double z2 = 8d; // expected result final double x3 = 4d; final double y3 = -16d; final double z3 = -11d; Vec3 u = new Vec3(x1, y1, z1); Vec3 v = new Vec3(x2, y2, z2); Vec3 r = new Vec3(x3, y3, z3); Vec3 w = u.cross(v); assertEquals("u.x", y1 * z2 - z1 * y2, u.x, 0d); assertEquals("u.y", z1 * x2 - x1 * z2, u.y, 0d); assertEquals("u.z", x1 * y2 - y1 * x2, u.z, 0d); assertEquals("u == r", r, u); // Assert v is not altered assertEquals("v.x", x2, v.x, 0d); assertEquals("v.y", y2, v.y, 0d); assertEquals("v.z", z2, v.z, 0d); // Assert fluent API returns u assertSame("w == u", u, w); } /** * Ensures cross with null argument is handled correctly. * * @throws Exception */ @Test(expected = IllegalArgumentException.class) public void testCross_WithNull() throws Exception { PowerMockito.mockStatic(Logger.class); Vec3 u = new Vec3(3, 4, 5); u.cross(null); fail("Expected an IllegalArgumentException to be thrown."); } /** * Ensures the correct interpolation between two vectors, arguments are not mutated, and the proper fluent API * result. * * @throws Exception */ @Test public void testMix() throws Exception { final double weight = 0.75; final double x1 = 3.1d; final double y1 = 4.3d; final double z1 = 5.5d; final double x2 = 6.2d; final double y2 = 7.4d; final double z2 = 8.6d; Vec3 u = new Vec3(x1, y1, z1); Vec3 v = new Vec3(x2, y2, z2); Vec3 w = u.mix(v, weight); assertEquals("u.x", x1 + ((x2 - x1) * weight), u.x, TOLERANCE); assertEquals("u.y", y1 + ((y2 - y1) * weight), u.y, TOLERANCE); assertEquals("u.z", z1 + ((z2 - z1) * weight), u.z, TOLERANCE); // Assert v is not altered assertEquals("v.x", x2, v.x, 0d); assertEquals("v.y", y2, v.y, 0d); assertEquals("v.z", z2, v.z, 0d); // Assert fluent API returns u assertSame("w == u", u, w); } /** * Ensures mix with null argument is handled correctly. * * @throws Exception */ @Test(expected = IllegalArgumentException.class) public void testMix_WithNull() throws Exception { PowerMockito.mockStatic(Logger.class); final double weight = 5d; Vec3 u = new Vec3(3, 4, 5); u.mix(null, weight); fail("Expected an IllegalArgumentException to be thrown."); } @Ignore("not implemented") @Test public void testAverageOfBuffer() throws Exception { fail("The test case is a stub."); } @Ignore("not implemented") @Test public void testPrincipalAxesOfBuffer() throws Exception { fail("The test case is a stub."); } @Test public void testAverageOfList() throws Exception { List<Vec3> list = new ArrayList<>(); list.add(new Vec3(1, 2, 3)); list.add(new Vec3(7, 8, 9)); list.add(new Vec3(7, 8, 9)); Vec3 r = new Vec3(5, 6, 7); // result: simple avg of components Vec3 u = new Vec3(); Vec3 w = u.averageOfList(list); assertEquals("u.x", r.x, u.x, 0); assertEquals("u.y", r.y, u.y, 0); assertEquals("u.z", r.z, u.z, 0); // Assert fluent API returns u assertSame("w == u", u, w); } /** * Ensures averageOfList handles a null list correctly. * * @throws Exception */ @Test(expected = IllegalArgumentException.class) public void testAverageOfList_NullList() throws Exception { PowerMockito.mockStatic(Logger.class); Vec3 u = new Vec3(); Vec3 w = u.averageOfList(null); fail("Expected an IllegalArgumentException to be thrown."); } /** * Ensures averageOfList handles an empty list correctly. * * @throws Exception */ @Test(expected = IllegalArgumentException.class) public void testAverageOfList_EmptyList() throws Exception { PowerMockito.mockStatic(Logger.class); Vec3 u = new Vec3(); u.averageOfList(new ArrayList<Vec3>()); fail("Expected an IllegalArgumentException to be thrown."); } @Ignore("not implemented") @Test public void testTriangleNormal() throws Exception { fail("The test case is a stub."); } }
Java
public class PaymentDetails { /** * Contains the total amount of the payment request. */ @JsonProperty(value = "total") private PaymentItem total; /** * Contains line items for the payment request that the user agent may * display. */ @JsonProperty(value = "displayItems") private List<PaymentItem> displayItems; /** * A sequence containing the different shipping options for the user to * choose from. */ @JsonProperty(value = "shippingOptions") private List<PaymentShippingOption> shippingOptions; /** * Contains modifiers for particular payment method identifiers. */ @JsonProperty(value = "modifiers") private List<PaymentDetailsModifier> modifiers; /** * Error description. */ @JsonProperty(value = "error") private String error; /** * Get the total value. * * @return the total value */ public PaymentItem total() { return this.total; } /** * Set the total value. * * @param total the total value to set * @return the PaymentDetails object itself. */ public PaymentDetails withTotal(PaymentItem total) { this.total = total; return this; } /** * Get the displayItems value. * * @return the displayItems value */ public List<PaymentItem> displayItems() { return this.displayItems; } /** * Set the displayItems value. * * @param displayItems the displayItems value to set * @return the PaymentDetails object itself. */ public PaymentDetails withDisplayItems(List<PaymentItem> displayItems) { this.displayItems = displayItems; return this; } /** * Get the shippingOptions value. * * @return the shippingOptions value */ public List<PaymentShippingOption> shippingOptions() { return this.shippingOptions; } /** * Set the shippingOptions value. * * @param shippingOptions the shippingOptions value to set * @return the PaymentDetails object itself. */ public PaymentDetails withShippingOptions(List<PaymentShippingOption> shippingOptions) { this.shippingOptions = shippingOptions; return this; } /** * Get the modifiers value. * * @return the modifiers value */ public List<PaymentDetailsModifier> modifiers() { return this.modifiers; } /** * Set the modifiers value. * * @param modifiers the modifiers value to set * @return the PaymentDetails object itself. */ public PaymentDetails withModifiers(List<PaymentDetailsModifier> modifiers) { this.modifiers = modifiers; return this; } /** * Get the error value. * * @return the error value */ public String error() { return this.error; } /** * Set the error value. * * @param error the error value to set * @return the PaymentDetails object itself. */ public PaymentDetails withError(String error) { this.error = error; return this; } }
Java
@Internal public final class DataStructureConverters { private static final Map<ConverterIdentifier<?>, DataStructureConverterFactory> converters = new HashMap<>(); static { // ordered by type root and conversion class definition putConverter(LogicalTypeRoot.CHAR, String.class, constructor(StringStringConverter::new)); putConverter( LogicalTypeRoot.CHAR, byte[].class, constructor(StringByteArrayConverter::new)); putConverter(LogicalTypeRoot.CHAR, StringData.class, identity()); putConverter( LogicalTypeRoot.VARCHAR, String.class, constructor(StringStringConverter::new)); putConverter( LogicalTypeRoot.VARCHAR, byte[].class, constructor(StringByteArrayConverter::new)); putConverter(LogicalTypeRoot.VARCHAR, StringData.class, identity()); putConverter(LogicalTypeRoot.BOOLEAN, Boolean.class, identity()); putConverter(LogicalTypeRoot.BOOLEAN, boolean.class, identity()); putConverter(LogicalTypeRoot.BINARY, byte[].class, identity()); putConverter(LogicalTypeRoot.VARBINARY, byte[].class, identity()); putConverter(LogicalTypeRoot.DECIMAL, BigDecimal.class, DecimalBigDecimalConverter::create); putConverter(LogicalTypeRoot.DECIMAL, DecimalData.class, identity()); putConverter(LogicalTypeRoot.TINYINT, Byte.class, identity()); putConverter(LogicalTypeRoot.TINYINT, byte.class, identity()); putConverter(LogicalTypeRoot.SMALLINT, Short.class, identity()); putConverter(LogicalTypeRoot.SMALLINT, short.class, identity()); putConverter(LogicalTypeRoot.INTEGER, Integer.class, identity()); putConverter(LogicalTypeRoot.INTEGER, int.class, identity()); putConverter(LogicalTypeRoot.BIGINT, Long.class, identity()); putConverter(LogicalTypeRoot.BIGINT, long.class, identity()); putConverter(LogicalTypeRoot.FLOAT, Float.class, identity()); putConverter(LogicalTypeRoot.FLOAT, float.class, identity()); putConverter(LogicalTypeRoot.DOUBLE, Double.class, identity()); putConverter(LogicalTypeRoot.DOUBLE, double.class, identity()); putConverter( LogicalTypeRoot.DATE, java.sql.Date.class, constructor(DateDateConverter::new)); putConverter( LogicalTypeRoot.DATE, java.time.LocalDate.class, constructor(DateLocalDateConverter::new)); putConverter(LogicalTypeRoot.DATE, Integer.class, identity()); putConverter(LogicalTypeRoot.DATE, int.class, identity()); putConverter( LogicalTypeRoot.TIME_WITHOUT_TIME_ZONE, java.sql.Time.class, constructor(TimeTimeConverter::new)); putConverter( LogicalTypeRoot.TIME_WITHOUT_TIME_ZONE, java.time.LocalTime.class, constructor(TimeLocalTimeConverter::new)); putConverter(LogicalTypeRoot.TIME_WITHOUT_TIME_ZONE, Integer.class, identity()); putConverter(LogicalTypeRoot.TIME_WITHOUT_TIME_ZONE, int.class, identity()); putConverter( LogicalTypeRoot.TIME_WITHOUT_TIME_ZONE, Long.class, constructor(TimeLongConverter::new)); putConverter( LogicalTypeRoot.TIME_WITHOUT_TIME_ZONE, long.class, constructor(TimeLongConverter::new)); putConverter( LogicalTypeRoot.TIMESTAMP_WITHOUT_TIME_ZONE, java.sql.Timestamp.class, constructor(TimestampTimestampConverter::new)); putConverter( LogicalTypeRoot.TIMESTAMP_WITHOUT_TIME_ZONE, java.time.LocalDateTime.class, constructor(TimestampLocalDateTimeConverter::new)); putConverter(LogicalTypeRoot.TIMESTAMP_WITHOUT_TIME_ZONE, TimestampData.class, identity()); putConverter( LogicalTypeRoot.TIMESTAMP_WITH_TIME_ZONE, java.time.ZonedDateTime.class, unsupported()); putConverter( LogicalTypeRoot.TIMESTAMP_WITH_TIME_ZONE, java.time.OffsetDateTime.class, unsupported()); putConverter( LogicalTypeRoot.TIMESTAMP_WITH_LOCAL_TIME_ZONE, java.time.Instant.class, constructor(LocalZonedTimestampInstantConverter::new)); putConverter( LogicalTypeRoot.TIMESTAMP_WITH_LOCAL_TIME_ZONE, Integer.class, constructor(LocalZonedTimestampIntConverter::new)); putConverter( LogicalTypeRoot.TIMESTAMP_WITH_LOCAL_TIME_ZONE, int.class, constructor(LocalZonedTimestampIntConverter::new)); putConverter( LogicalTypeRoot.TIMESTAMP_WITH_LOCAL_TIME_ZONE, Long.class, constructor(LocalZonedTimestampLongConverter::new)); putConverter( LogicalTypeRoot.TIMESTAMP_WITH_LOCAL_TIME_ZONE, long.class, constructor(LocalZonedTimestampLongConverter::new)); putConverter( LogicalTypeRoot.TIMESTAMP_WITH_LOCAL_TIME_ZONE, TimestampData.class, identity()); putConverter( LogicalTypeRoot.INTERVAL_YEAR_MONTH, java.time.Period.class, YearMonthIntervalPeriodConverter::create); putConverter(LogicalTypeRoot.INTERVAL_YEAR_MONTH, Integer.class, identity()); putConverter(LogicalTypeRoot.INTERVAL_YEAR_MONTH, int.class, identity()); putConverter( LogicalTypeRoot.INTERVAL_DAY_TIME, java.time.Duration.class, constructor(DayTimeIntervalDurationConverter::new)); putConverter(LogicalTypeRoot.INTERVAL_DAY_TIME, Long.class, identity()); putConverter(LogicalTypeRoot.INTERVAL_DAY_TIME, long.class, identity()); putConverter(LogicalTypeRoot.ARRAY, ArrayData.class, identity()); putConverter( LogicalTypeRoot.ARRAY, boolean[].class, constructor(ArrayBooleanArrayConverter::new)); putConverter( LogicalTypeRoot.ARRAY, byte[].class, constructor(ArrayByteArrayConverter::new)); putConverter( LogicalTypeRoot.ARRAY, short[].class, constructor(ArrayShortArrayConverter::new)); putConverter(LogicalTypeRoot.ARRAY, int[].class, constructor(ArrayIntArrayConverter::new)); putConverter( LogicalTypeRoot.ARRAY, long[].class, constructor(ArrayLongArrayConverter::new)); putConverter( LogicalTypeRoot.ARRAY, float[].class, constructor(ArrayFloatArrayConverter::new)); putConverter( LogicalTypeRoot.ARRAY, double[].class, constructor(ArrayDoubleArrayConverter::new)); putConverter(LogicalTypeRoot.MULTISET, MapData.class, identity()); putConverter(LogicalTypeRoot.MAP, MapData.class, identity()); putConverter(LogicalTypeRoot.ROW, Row.class, RowRowConverter::create); putConverter(LogicalTypeRoot.ROW, RowData.class, identity()); putConverter(LogicalTypeRoot.STRUCTURED_TYPE, Row.class, RowRowConverter::create); putConverter(LogicalTypeRoot.STRUCTURED_TYPE, RowData.class, identity()); putConverter(LogicalTypeRoot.RAW, byte[].class, RawByteArrayConverter::create); putConverter(LogicalTypeRoot.RAW, RawValueData.class, identity()); } /** Returns a converter for the given {@link DataType}. */ @SuppressWarnings("unchecked") public static DataStructureConverter<Object, Object> getConverter(DataType dataType) { // cast to Object for ease of use return (DataStructureConverter<Object, Object>) getConverterInternal(dataType); } private static DataStructureConverter<?, ?> getConverterInternal(DataType dataType) { final LogicalType logicalType = dataType.getLogicalType(); final DataStructureConverterFactory factory = converters.get( new ConverterIdentifier<>( logicalType.getTypeRoot(), dataType.getConversionClass())); if (factory != null) { return factory.createConverter(dataType); } // special cases switch (logicalType.getTypeRoot()) { case ARRAY: // for subclasses of List if (List.class.isAssignableFrom(dataType.getConversionClass())) { return ArrayListConverter.create(dataType); } // for non-primitive arrays return ArrayObjectArrayConverter.create(dataType); case MULTISET: // for subclasses of Map return MapMapConverter.createForMultisetType(dataType); case MAP: // for subclasses of Map return MapMapConverter.createForMapType(dataType); case DISTINCT_TYPE: return getConverterInternal(dataType.getChildren().get(0)); case STRUCTURED_TYPE: return StructuredObjectConverter.create(dataType); case RAW: return RawObjectConverter.create(dataType); default: throw new TableException("Could not find converter for data type: " + dataType); } } // -------------------------------------------------------------------------------------------- // Helper methods // -------------------------------------------------------------------------------------------- private static <E> void putConverter( LogicalTypeRoot root, Class<E> conversionClass, DataStructureConverterFactory factory) { converters.put(new ConverterIdentifier<>(root, conversionClass), factory); } private static DataStructureConverterFactory identity() { return constructor(IdentityConverter::new); } private static DataStructureConverterFactory constructor( Supplier<DataStructureConverter<?, ?>> supplier) { return dataType -> supplier.get(); } private static DataStructureConverterFactory unsupported() { return dataType -> { throw new TableException("Unsupported data type: " + dataType); }; } // -------------------------------------------------------------------------------------------- // Helper classes // -------------------------------------------------------------------------------------------- private static class ConverterIdentifier<E> { final LogicalTypeRoot root; final Class<E> conversionClass; ConverterIdentifier(LogicalTypeRoot root, Class<E> conversionClass) { this.root = root; this.conversionClass = conversionClass; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ConverterIdentifier<?> that = (ConverterIdentifier<?>) o; return root == that.root && conversionClass.equals(that.conversionClass); } @Override public int hashCode() { return Objects.hash(root, conversionClass); } } private interface DataStructureConverterFactory { DataStructureConverter<?, ?> createConverter(DataType dt); } }
Java
@SuppressWarnings("javadoc") public class CloudScheduler extends com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient { // Note: Leave this static initializer at the top of the file. static { com.google.api.client.util.Preconditions.checkState( com.google.api.client.googleapis.GoogleUtils.MAJOR_VERSION == 1 && com.google.api.client.googleapis.GoogleUtils.MINOR_VERSION >= 15, "You are currently running with version %s of google-api-client. " + "You need at least version 1.15 of google-api-client to run version " + "1.30.10 of the Cloud Scheduler API library.", com.google.api.client.googleapis.GoogleUtils.VERSION); } /** * The default encoded root URL of the service. This is determined when the library is generated * and normally should not be changed. * * @since 1.7 */ public static final String DEFAULT_ROOT_URL = "https://cloudscheduler.googleapis.com/"; /** * The default encoded service path of the service. This is determined when the library is * generated and normally should not be changed. * * @since 1.7 */ public static final String DEFAULT_SERVICE_PATH = ""; /** * The default encoded batch path of the service. This is determined when the library is * generated and normally should not be changed. * * @since 1.23 */ public static final String DEFAULT_BATCH_PATH = "batch"; /** * The default encoded base URL of the service. This is determined when the library is generated * and normally should not be changed. */ public static final String DEFAULT_BASE_URL = DEFAULT_ROOT_URL + DEFAULT_SERVICE_PATH; /** * Constructor. * * <p> * Use {@link Builder} if you need to specify any of the optional parameters. * </p> * * @param transport HTTP transport, which should normally be: * <ul> * <li>Google App Engine: * {@code com.google.api.client.extensions.appengine.http.UrlFetchTransport}</li> * <li>Android: {@code newCompatibleTransport} from * {@code com.google.api.client.extensions.android.http.AndroidHttp}</li> * <li>Java: {@link com.google.api.client.googleapis.javanet.GoogleNetHttpTransport#newTrustedTransport()} * </li> * </ul> * @param jsonFactory JSON factory, which may be: * <ul> * <li>Jackson: {@code com.google.api.client.json.jackson2.JacksonFactory}</li> * <li>Google GSON: {@code com.google.api.client.json.gson.GsonFactory}</li> * <li>Android Honeycomb or higher: * {@code com.google.api.client.extensions.android.json.AndroidJsonFactory}</li> * </ul> * @param httpRequestInitializer HTTP request initializer or {@code null} for none * @since 1.7 */ public CloudScheduler(com.google.api.client.http.HttpTransport transport, com.google.api.client.json.JsonFactory jsonFactory, com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) { this(new Builder(transport, jsonFactory, httpRequestInitializer)); } /** * @param builder builder */ CloudScheduler(Builder builder) { super(builder); } @Override protected void initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest<?> httpClientRequest) throws java.io.IOException { super.initialize(httpClientRequest); } /** * An accessor for creating requests from the Projects collection. * * <p>The typical use is:</p> * <pre> * {@code CloudScheduler cloudscheduler = new CloudScheduler(...);} * {@code CloudScheduler.Projects.List request = cloudscheduler.projects().list(parameters ...)} * </pre> * * @return the resource collection */ public Projects projects() { return new Projects(); } /** * The "projects" collection of methods. */ public class Projects { /** * An accessor for creating requests from the Locations collection. * * <p>The typical use is:</p> * <pre> * {@code CloudScheduler cloudscheduler = new CloudScheduler(...);} * {@code CloudScheduler.Locations.List request = cloudscheduler.locations().list(parameters ...)} * </pre> * * @return the resource collection */ public Locations locations() { return new Locations(); } /** * The "locations" collection of methods. */ public class Locations { /** * Gets information about a location. * * Create a request for the method "locations.get". * * This request holds the parameters needed by the cloudscheduler server. After setting any * optional parameters, call the {@link Get#execute()} method to invoke the remote operation. * * @param name Resource name for the location. * @return the request */ public Get get(java.lang.String name) throws java.io.IOException { Get result = new Get(name); initialize(result); return result; } public class Get extends CloudSchedulerRequest<com.google.api.services.cloudscheduler.v1.model.Location> { private static final String REST_PATH = "v1/{+name}"; private final java.util.regex.Pattern NAME_PATTERN = java.util.regex.Pattern.compile("^projects/[^/]+/locations/[^/]+$"); /** * Gets information about a location. * * Create a request for the method "locations.get". * * This request holds the parameters needed by the the cloudscheduler server. After setting any * optional parameters, call the {@link Get#execute()} method to invoke the remote operation. <p> * {@link Get#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} * must be called to initialize this instance immediately after invoking the constructor. </p> * * @param name Resource name for the location. * @since 1.13 */ protected Get(java.lang.String name) { super(CloudScheduler.this, "GET", REST_PATH, null, com.google.api.services.cloudscheduler.v1.model.Location.class); this.name = com.google.api.client.util.Preconditions.checkNotNull(name, "Required parameter name must be specified."); if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(), "Parameter name must conform to the pattern " + "^projects/[^/]+/locations/[^/]+$"); } } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public Get set$Xgafv(java.lang.String $Xgafv) { return (Get) super.set$Xgafv($Xgafv); } @Override public Get setAccessToken(java.lang.String accessToken) { return (Get) super.setAccessToken(accessToken); } @Override public Get setAlt(java.lang.String alt) { return (Get) super.setAlt(alt); } @Override public Get setCallback(java.lang.String callback) { return (Get) super.setCallback(callback); } @Override public Get setFields(java.lang.String fields) { return (Get) super.setFields(fields); } @Override public Get setKey(java.lang.String key) { return (Get) super.setKey(key); } @Override public Get setOauthToken(java.lang.String oauthToken) { return (Get) super.setOauthToken(oauthToken); } @Override public Get setPrettyPrint(java.lang.Boolean prettyPrint) { return (Get) super.setPrettyPrint(prettyPrint); } @Override public Get setQuotaUser(java.lang.String quotaUser) { return (Get) super.setQuotaUser(quotaUser); } @Override public Get setUploadType(java.lang.String uploadType) { return (Get) super.setUploadType(uploadType); } @Override public Get setUploadProtocol(java.lang.String uploadProtocol) { return (Get) super.setUploadProtocol(uploadProtocol); } /** Resource name for the location. */ @com.google.api.client.util.Key private java.lang.String name; /** Resource name for the location. */ public java.lang.String getName() { return name; } /** Resource name for the location. */ public Get setName(java.lang.String name) { if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(), "Parameter name must conform to the pattern " + "^projects/[^/]+/locations/[^/]+$"); } this.name = name; return this; } @Override public Get set(String parameterName, Object value) { return (Get) super.set(parameterName, value); } } /** * Lists information about the supported locations for this service. * * Create a request for the method "locations.list". * * This request holds the parameters needed by the cloudscheduler server. After setting any * optional parameters, call the {@link List#execute()} method to invoke the remote operation. * * @param name The resource that owns the locations collection, if applicable. * @return the request */ public List list(java.lang.String name) throws java.io.IOException { List result = new List(name); initialize(result); return result; } public class List extends CloudSchedulerRequest<com.google.api.services.cloudscheduler.v1.model.ListLocationsResponse> { private static final String REST_PATH = "v1/{+name}/locations"; private final java.util.regex.Pattern NAME_PATTERN = java.util.regex.Pattern.compile("^projects/[^/]+$"); /** * Lists information about the supported locations for this service. * * Create a request for the method "locations.list". * * This request holds the parameters needed by the the cloudscheduler server. After setting any * optional parameters, call the {@link List#execute()} method to invoke the remote operation. <p> * {@link List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} * must be called to initialize this instance immediately after invoking the constructor. </p> * * @param name The resource that owns the locations collection, if applicable. * @since 1.13 */ protected List(java.lang.String name) { super(CloudScheduler.this, "GET", REST_PATH, null, com.google.api.services.cloudscheduler.v1.model.ListLocationsResponse.class); this.name = com.google.api.client.util.Preconditions.checkNotNull(name, "Required parameter name must be specified."); if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(), "Parameter name must conform to the pattern " + "^projects/[^/]+$"); } } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public List set$Xgafv(java.lang.String $Xgafv) { return (List) super.set$Xgafv($Xgafv); } @Override public List setAccessToken(java.lang.String accessToken) { return (List) super.setAccessToken(accessToken); } @Override public List setAlt(java.lang.String alt) { return (List) super.setAlt(alt); } @Override public List setCallback(java.lang.String callback) { return (List) super.setCallback(callback); } @Override public List setFields(java.lang.String fields) { return (List) super.setFields(fields); } @Override public List setKey(java.lang.String key) { return (List) super.setKey(key); } @Override public List setOauthToken(java.lang.String oauthToken) { return (List) super.setOauthToken(oauthToken); } @Override public List setPrettyPrint(java.lang.Boolean prettyPrint) { return (List) super.setPrettyPrint(prettyPrint); } @Override public List setQuotaUser(java.lang.String quotaUser) { return (List) super.setQuotaUser(quotaUser); } @Override public List setUploadType(java.lang.String uploadType) { return (List) super.setUploadType(uploadType); } @Override public List setUploadProtocol(java.lang.String uploadProtocol) { return (List) super.setUploadProtocol(uploadProtocol); } /** The resource that owns the locations collection, if applicable. */ @com.google.api.client.util.Key private java.lang.String name; /** The resource that owns the locations collection, if applicable. */ public java.lang.String getName() { return name; } /** The resource that owns the locations collection, if applicable. */ public List setName(java.lang.String name) { if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(), "Parameter name must conform to the pattern " + "^projects/[^/]+$"); } this.name = name; return this; } /** The standard list filter. */ @com.google.api.client.util.Key private java.lang.String filter; /** The standard list filter. */ public java.lang.String getFilter() { return filter; } /** The standard list filter. */ public List setFilter(java.lang.String filter) { this.filter = filter; return this; } /** The standard list page size. */ @com.google.api.client.util.Key private java.lang.Integer pageSize; /** The standard list page size. */ public java.lang.Integer getPageSize() { return pageSize; } /** The standard list page size. */ public List setPageSize(java.lang.Integer pageSize) { this.pageSize = pageSize; return this; } /** The standard list page token. */ @com.google.api.client.util.Key private java.lang.String pageToken; /** The standard list page token. */ public java.lang.String getPageToken() { return pageToken; } /** The standard list page token. */ public List setPageToken(java.lang.String pageToken) { this.pageToken = pageToken; return this; } @Override public List set(String parameterName, Object value) { return (List) super.set(parameterName, value); } } /** * An accessor for creating requests from the Jobs collection. * * <p>The typical use is:</p> * <pre> * {@code CloudScheduler cloudscheduler = new CloudScheduler(...);} * {@code CloudScheduler.Jobs.List request = cloudscheduler.jobs().list(parameters ...)} * </pre> * * @return the resource collection */ public Jobs jobs() { return new Jobs(); } /** * The "jobs" collection of methods. */ public class Jobs { /** * Creates a job. * * Create a request for the method "jobs.create". * * This request holds the parameters needed by the cloudscheduler server. After setting any * optional parameters, call the {@link Create#execute()} method to invoke the remote operation. * * @param parent Required. The location name. For example: `projects/PROJECT_ID/locations/LOCATION_ID`. * @param content the {@link com.google.api.services.cloudscheduler.v1.model.Job} * @return the request */ public Create create(java.lang.String parent, com.google.api.services.cloudscheduler.v1.model.Job content) throws java.io.IOException { Create result = new Create(parent, content); initialize(result); return result; } public class Create extends CloudSchedulerRequest<com.google.api.services.cloudscheduler.v1.model.Job> { private static final String REST_PATH = "v1/{+parent}/jobs"; private final java.util.regex.Pattern PARENT_PATTERN = java.util.regex.Pattern.compile("^projects/[^/]+/locations/[^/]+$"); /** * Creates a job. * * Create a request for the method "jobs.create". * * This request holds the parameters needed by the the cloudscheduler server. After setting any * optional parameters, call the {@link Create#execute()} method to invoke the remote operation. * <p> {@link * Create#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param parent Required. The location name. For example: `projects/PROJECT_ID/locations/LOCATION_ID`. * @param content the {@link com.google.api.services.cloudscheduler.v1.model.Job} * @since 1.13 */ protected Create(java.lang.String parent, com.google.api.services.cloudscheduler.v1.model.Job content) { super(CloudScheduler.this, "POST", REST_PATH, content, com.google.api.services.cloudscheduler.v1.model.Job.class); this.parent = com.google.api.client.util.Preconditions.checkNotNull(parent, "Required parameter parent must be specified."); if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(PARENT_PATTERN.matcher(parent).matches(), "Parameter parent must conform to the pattern " + "^projects/[^/]+/locations/[^/]+$"); } } @Override public Create set$Xgafv(java.lang.String $Xgafv) { return (Create) super.set$Xgafv($Xgafv); } @Override public Create setAccessToken(java.lang.String accessToken) { return (Create) super.setAccessToken(accessToken); } @Override public Create setAlt(java.lang.String alt) { return (Create) super.setAlt(alt); } @Override public Create setCallback(java.lang.String callback) { return (Create) super.setCallback(callback); } @Override public Create setFields(java.lang.String fields) { return (Create) super.setFields(fields); } @Override public Create setKey(java.lang.String key) { return (Create) super.setKey(key); } @Override public Create setOauthToken(java.lang.String oauthToken) { return (Create) super.setOauthToken(oauthToken); } @Override public Create setPrettyPrint(java.lang.Boolean prettyPrint) { return (Create) super.setPrettyPrint(prettyPrint); } @Override public Create setQuotaUser(java.lang.String quotaUser) { return (Create) super.setQuotaUser(quotaUser); } @Override public Create setUploadType(java.lang.String uploadType) { return (Create) super.setUploadType(uploadType); } @Override public Create setUploadProtocol(java.lang.String uploadProtocol) { return (Create) super.setUploadProtocol(uploadProtocol); } /** * Required. The location name. For example: `projects/PROJECT_ID/locations/LOCATION_ID`. */ @com.google.api.client.util.Key private java.lang.String parent; /** Required. The location name. For example: `projects/PROJECT_ID/locations/LOCATION_ID`. */ public java.lang.String getParent() { return parent; } /** * Required. The location name. For example: `projects/PROJECT_ID/locations/LOCATION_ID`. */ public Create setParent(java.lang.String parent) { if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(PARENT_PATTERN.matcher(parent).matches(), "Parameter parent must conform to the pattern " + "^projects/[^/]+/locations/[^/]+$"); } this.parent = parent; return this; } @Override public Create set(String parameterName, Object value) { return (Create) super.set(parameterName, value); } } /** * Deletes a job. * * Create a request for the method "jobs.delete". * * This request holds the parameters needed by the cloudscheduler server. After setting any * optional parameters, call the {@link Delete#execute()} method to invoke the remote operation. * * @param name Required. The job name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. * @return the request */ public Delete delete(java.lang.String name) throws java.io.IOException { Delete result = new Delete(name); initialize(result); return result; } public class Delete extends CloudSchedulerRequest<com.google.api.services.cloudscheduler.v1.model.Empty> { private static final String REST_PATH = "v1/{+name}"; private final java.util.regex.Pattern NAME_PATTERN = java.util.regex.Pattern.compile("^projects/[^/]+/locations/[^/]+/jobs/[^/]+$"); /** * Deletes a job. * * Create a request for the method "jobs.delete". * * This request holds the parameters needed by the the cloudscheduler server. After setting any * optional parameters, call the {@link Delete#execute()} method to invoke the remote operation. * <p> {@link * Delete#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param name Required. The job name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. * @since 1.13 */ protected Delete(java.lang.String name) { super(CloudScheduler.this, "DELETE", REST_PATH, null, com.google.api.services.cloudscheduler.v1.model.Empty.class); this.name = com.google.api.client.util.Preconditions.checkNotNull(name, "Required parameter name must be specified."); if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(), "Parameter name must conform to the pattern " + "^projects/[^/]+/locations/[^/]+/jobs/[^/]+$"); } } @Override public Delete set$Xgafv(java.lang.String $Xgafv) { return (Delete) super.set$Xgafv($Xgafv); } @Override public Delete setAccessToken(java.lang.String accessToken) { return (Delete) super.setAccessToken(accessToken); } @Override public Delete setAlt(java.lang.String alt) { return (Delete) super.setAlt(alt); } @Override public Delete setCallback(java.lang.String callback) { return (Delete) super.setCallback(callback); } @Override public Delete setFields(java.lang.String fields) { return (Delete) super.setFields(fields); } @Override public Delete setKey(java.lang.String key) { return (Delete) super.setKey(key); } @Override public Delete setOauthToken(java.lang.String oauthToken) { return (Delete) super.setOauthToken(oauthToken); } @Override public Delete setPrettyPrint(java.lang.Boolean prettyPrint) { return (Delete) super.setPrettyPrint(prettyPrint); } @Override public Delete setQuotaUser(java.lang.String quotaUser) { return (Delete) super.setQuotaUser(quotaUser); } @Override public Delete setUploadType(java.lang.String uploadType) { return (Delete) super.setUploadType(uploadType); } @Override public Delete setUploadProtocol(java.lang.String uploadProtocol) { return (Delete) super.setUploadProtocol(uploadProtocol); } /** * Required. The job name. For example: * `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. */ @com.google.api.client.util.Key private java.lang.String name; /** Required. The job name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. */ public java.lang.String getName() { return name; } /** * Required. The job name. For example: * `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. */ public Delete setName(java.lang.String name) { if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(), "Parameter name must conform to the pattern " + "^projects/[^/]+/locations/[^/]+/jobs/[^/]+$"); } this.name = name; return this; } @Override public Delete set(String parameterName, Object value) { return (Delete) super.set(parameterName, value); } } /** * Gets a job. * * Create a request for the method "jobs.get". * * This request holds the parameters needed by the cloudscheduler server. After setting any * optional parameters, call the {@link Get#execute()} method to invoke the remote operation. * * @param name Required. The job name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. * @return the request */ public Get get(java.lang.String name) throws java.io.IOException { Get result = new Get(name); initialize(result); return result; } public class Get extends CloudSchedulerRequest<com.google.api.services.cloudscheduler.v1.model.Job> { private static final String REST_PATH = "v1/{+name}"; private final java.util.regex.Pattern NAME_PATTERN = java.util.regex.Pattern.compile("^projects/[^/]+/locations/[^/]+/jobs/[^/]+$"); /** * Gets a job. * * Create a request for the method "jobs.get". * * This request holds the parameters needed by the the cloudscheduler server. After setting any * optional parameters, call the {@link Get#execute()} method to invoke the remote operation. <p> * {@link Get#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} * must be called to initialize this instance immediately after invoking the constructor. </p> * * @param name Required. The job name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. * @since 1.13 */ protected Get(java.lang.String name) { super(CloudScheduler.this, "GET", REST_PATH, null, com.google.api.services.cloudscheduler.v1.model.Job.class); this.name = com.google.api.client.util.Preconditions.checkNotNull(name, "Required parameter name must be specified."); if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(), "Parameter name must conform to the pattern " + "^projects/[^/]+/locations/[^/]+/jobs/[^/]+$"); } } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public Get set$Xgafv(java.lang.String $Xgafv) { return (Get) super.set$Xgafv($Xgafv); } @Override public Get setAccessToken(java.lang.String accessToken) { return (Get) super.setAccessToken(accessToken); } @Override public Get setAlt(java.lang.String alt) { return (Get) super.setAlt(alt); } @Override public Get setCallback(java.lang.String callback) { return (Get) super.setCallback(callback); } @Override public Get setFields(java.lang.String fields) { return (Get) super.setFields(fields); } @Override public Get setKey(java.lang.String key) { return (Get) super.setKey(key); } @Override public Get setOauthToken(java.lang.String oauthToken) { return (Get) super.setOauthToken(oauthToken); } @Override public Get setPrettyPrint(java.lang.Boolean prettyPrint) { return (Get) super.setPrettyPrint(prettyPrint); } @Override public Get setQuotaUser(java.lang.String quotaUser) { return (Get) super.setQuotaUser(quotaUser); } @Override public Get setUploadType(java.lang.String uploadType) { return (Get) super.setUploadType(uploadType); } @Override public Get setUploadProtocol(java.lang.String uploadProtocol) { return (Get) super.setUploadProtocol(uploadProtocol); } /** * Required. The job name. For example: * `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. */ @com.google.api.client.util.Key private java.lang.String name; /** Required. The job name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. */ public java.lang.String getName() { return name; } /** * Required. The job name. For example: * `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. */ public Get setName(java.lang.String name) { if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(), "Parameter name must conform to the pattern " + "^projects/[^/]+/locations/[^/]+/jobs/[^/]+$"); } this.name = name; return this; } @Override public Get set(String parameterName, Object value) { return (Get) super.set(parameterName, value); } } /** * Lists jobs. * * Create a request for the method "jobs.list". * * This request holds the parameters needed by the cloudscheduler server. After setting any * optional parameters, call the {@link List#execute()} method to invoke the remote operation. * * @param parent Required. The location name. For example: `projects/PROJECT_ID/locations/LOCATION_ID`. * @return the request */ public List list(java.lang.String parent) throws java.io.IOException { List result = new List(parent); initialize(result); return result; } public class List extends CloudSchedulerRequest<com.google.api.services.cloudscheduler.v1.model.ListJobsResponse> { private static final String REST_PATH = "v1/{+parent}/jobs"; private final java.util.regex.Pattern PARENT_PATTERN = java.util.regex.Pattern.compile("^projects/[^/]+/locations/[^/]+$"); /** * Lists jobs. * * Create a request for the method "jobs.list". * * This request holds the parameters needed by the the cloudscheduler server. After setting any * optional parameters, call the {@link List#execute()} method to invoke the remote operation. <p> * {@link List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} * must be called to initialize this instance immediately after invoking the constructor. </p> * * @param parent Required. The location name. For example: `projects/PROJECT_ID/locations/LOCATION_ID`. * @since 1.13 */ protected List(java.lang.String parent) { super(CloudScheduler.this, "GET", REST_PATH, null, com.google.api.services.cloudscheduler.v1.model.ListJobsResponse.class); this.parent = com.google.api.client.util.Preconditions.checkNotNull(parent, "Required parameter parent must be specified."); if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(PARENT_PATTERN.matcher(parent).matches(), "Parameter parent must conform to the pattern " + "^projects/[^/]+/locations/[^/]+$"); } } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public List set$Xgafv(java.lang.String $Xgafv) { return (List) super.set$Xgafv($Xgafv); } @Override public List setAccessToken(java.lang.String accessToken) { return (List) super.setAccessToken(accessToken); } @Override public List setAlt(java.lang.String alt) { return (List) super.setAlt(alt); } @Override public List setCallback(java.lang.String callback) { return (List) super.setCallback(callback); } @Override public List setFields(java.lang.String fields) { return (List) super.setFields(fields); } @Override public List setKey(java.lang.String key) { return (List) super.setKey(key); } @Override public List setOauthToken(java.lang.String oauthToken) { return (List) super.setOauthToken(oauthToken); } @Override public List setPrettyPrint(java.lang.Boolean prettyPrint) { return (List) super.setPrettyPrint(prettyPrint); } @Override public List setQuotaUser(java.lang.String quotaUser) { return (List) super.setQuotaUser(quotaUser); } @Override public List setUploadType(java.lang.String uploadType) { return (List) super.setUploadType(uploadType); } @Override public List setUploadProtocol(java.lang.String uploadProtocol) { return (List) super.setUploadProtocol(uploadProtocol); } /** * Required. The location name. For example: `projects/PROJECT_ID/locations/LOCATION_ID`. */ @com.google.api.client.util.Key private java.lang.String parent; /** Required. The location name. For example: `projects/PROJECT_ID/locations/LOCATION_ID`. */ public java.lang.String getParent() { return parent; } /** * Required. The location name. For example: `projects/PROJECT_ID/locations/LOCATION_ID`. */ public List setParent(java.lang.String parent) { if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(PARENT_PATTERN.matcher(parent).matches(), "Parameter parent must conform to the pattern " + "^projects/[^/]+/locations/[^/]+$"); } this.parent = parent; return this; } /** * Requested page size. The maximum page size is 500. If unspecified, the page size will * be the maximum. Fewer jobs than requested might be returned, even if more jobs exist; * use next_page_token to determine if more jobs exist. */ @com.google.api.client.util.Key private java.lang.Integer pageSize; /** Requested page size. The maximum page size is 500. If unspecified, the page size will be the maximum. Fewer jobs than requested might be returned, even if more jobs exist; use next_page_token to determine if more jobs exist. */ public java.lang.Integer getPageSize() { return pageSize; } /** * Requested page size. The maximum page size is 500. If unspecified, the page size will * be the maximum. Fewer jobs than requested might be returned, even if more jobs exist; * use next_page_token to determine if more jobs exist. */ public List setPageSize(java.lang.Integer pageSize) { this.pageSize = pageSize; return this; } /** * A token identifying a page of results the server will return. To request the first page * results, page_token must be empty. To request the next page of results, page_token must * be the value of next_page_token returned from the previous call to ListJobs. It is an * error to switch the value of filter or order_by while iterating through pages. */ @com.google.api.client.util.Key private java.lang.String pageToken; /** A token identifying a page of results the server will return. To request the first page results, page_token must be empty. To request the next page of results, page_token must be the value of next_page_token returned from the previous call to ListJobs. It is an error to switch the value of filter or order_by while iterating through pages. */ public java.lang.String getPageToken() { return pageToken; } /** * A token identifying a page of results the server will return. To request the first page * results, page_token must be empty. To request the next page of results, page_token must * be the value of next_page_token returned from the previous call to ListJobs. It is an * error to switch the value of filter or order_by while iterating through pages. */ public List setPageToken(java.lang.String pageToken) { this.pageToken = pageToken; return this; } @Override public List set(String parameterName, Object value) { return (List) super.set(parameterName, value); } } /** * Updates a job. If successful, the updated Job is returned. If the job does not exist, `NOT_FOUND` * is returned. If UpdateJob does not successfully return, it is possible for the job to be in an * Job.State.UPDATE_FAILED state. A job in this state may not be executed. If this happens, retry * the UpdateJob request until a successful response is received. * * Create a request for the method "jobs.patch". * * This request holds the parameters needed by the cloudscheduler server. After setting any * optional parameters, call the {@link Patch#execute()} method to invoke the remote operation. * * @param name Optionally caller-specified in CreateJob, after which it becomes output only. The job name. For * example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. * `PROJECT_ID` can * contain letters ([A-Za-z]), numbers ([0-9]), hyphens (-), colons (:), or periods (.). For * more information, see [Identifying projects](https://cloud.google.com/resource- * manager/docs/creating-managing-projects#identifying_projects) * `LOCATION_ID` is the * canonical ID for the job's location. The list of available locations can be obtained by * calling ListLocations. For more information, see * https://cloud.google.com/about/locations/. * `JOB_ID` can contain only letters ([A-Za-z]), * numbers ([0-9]), hyphens (-), or underscores (_). The maximum length is 500 characters. * @param content the {@link com.google.api.services.cloudscheduler.v1.model.Job} * @return the request */ public Patch patch(java.lang.String name, com.google.api.services.cloudscheduler.v1.model.Job content) throws java.io.IOException { Patch result = new Patch(name, content); initialize(result); return result; } public class Patch extends CloudSchedulerRequest<com.google.api.services.cloudscheduler.v1.model.Job> { private static final String REST_PATH = "v1/{+name}"; private final java.util.regex.Pattern NAME_PATTERN = java.util.regex.Pattern.compile("^projects/[^/]+/locations/[^/]+/jobs/[^/]+$"); /** * Updates a job. If successful, the updated Job is returned. If the job does not exist, * `NOT_FOUND` is returned. If UpdateJob does not successfully return, it is possible for the job * to be in an Job.State.UPDATE_FAILED state. A job in this state may not be executed. If this * happens, retry the UpdateJob request until a successful response is received. * * Create a request for the method "jobs.patch". * * This request holds the parameters needed by the the cloudscheduler server. After setting any * optional parameters, call the {@link Patch#execute()} method to invoke the remote operation. * <p> {@link * Patch#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param name Optionally caller-specified in CreateJob, after which it becomes output only. The job name. For * example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. * `PROJECT_ID` can * contain letters ([A-Za-z]), numbers ([0-9]), hyphens (-), colons (:), or periods (.). For * more information, see [Identifying projects](https://cloud.google.com/resource- * manager/docs/creating-managing-projects#identifying_projects) * `LOCATION_ID` is the * canonical ID for the job's location. The list of available locations can be obtained by * calling ListLocations. For more information, see * https://cloud.google.com/about/locations/. * `JOB_ID` can contain only letters ([A-Za-z]), * numbers ([0-9]), hyphens (-), or underscores (_). The maximum length is 500 characters. * @param content the {@link com.google.api.services.cloudscheduler.v1.model.Job} * @since 1.13 */ protected Patch(java.lang.String name, com.google.api.services.cloudscheduler.v1.model.Job content) { super(CloudScheduler.this, "PATCH", REST_PATH, content, com.google.api.services.cloudscheduler.v1.model.Job.class); this.name = com.google.api.client.util.Preconditions.checkNotNull(name, "Required parameter name must be specified."); if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(), "Parameter name must conform to the pattern " + "^projects/[^/]+/locations/[^/]+/jobs/[^/]+$"); } } @Override public Patch set$Xgafv(java.lang.String $Xgafv) { return (Patch) super.set$Xgafv($Xgafv); } @Override public Patch setAccessToken(java.lang.String accessToken) { return (Patch) super.setAccessToken(accessToken); } @Override public Patch setAlt(java.lang.String alt) { return (Patch) super.setAlt(alt); } @Override public Patch setCallback(java.lang.String callback) { return (Patch) super.setCallback(callback); } @Override public Patch setFields(java.lang.String fields) { return (Patch) super.setFields(fields); } @Override public Patch setKey(java.lang.String key) { return (Patch) super.setKey(key); } @Override public Patch setOauthToken(java.lang.String oauthToken) { return (Patch) super.setOauthToken(oauthToken); } @Override public Patch setPrettyPrint(java.lang.Boolean prettyPrint) { return (Patch) super.setPrettyPrint(prettyPrint); } @Override public Patch setQuotaUser(java.lang.String quotaUser) { return (Patch) super.setQuotaUser(quotaUser); } @Override public Patch setUploadType(java.lang.String uploadType) { return (Patch) super.setUploadType(uploadType); } @Override public Patch setUploadProtocol(java.lang.String uploadProtocol) { return (Patch) super.setUploadProtocol(uploadProtocol); } /** * Optionally caller-specified in CreateJob, after which it becomes output only. The job * name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. * * `PROJECT_ID` can contain letters ([A-Za-z]), numbers ([0-9]), hyphens (-), colons (:), * or periods (.). For more information, see [Identifying * projects](https://cloud.google.com/resource-manager/docs/creating-managing- * projects#identifying_projects) * `LOCATION_ID` is the canonical ID for the job's * location. The list of available locations can be obtained by calling ListLocations. For * more information, see https://cloud.google.com/about/locations/. * `JOB_ID` can contain * only letters ([A-Za-z]), numbers ([0-9]), hyphens (-), or underscores (_). The maximum * length is 500 characters. */ @com.google.api.client.util.Key private java.lang.String name; /** Optionally caller-specified in CreateJob, after which it becomes output only. The job name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. * `PROJECT_ID` can contain letters ([A-Za-z]), numbers ([0-9]), hyphens (-), colons (:), or periods (.). For more information, see [Identifying projects](https://cloud.google.com/resource-manager/docs/creating-managing- projects#identifying_projects) * `LOCATION_ID` is the canonical ID for the job's location. The list of available locations can be obtained by calling ListLocations. For more information, see https://cloud.google.com/about/locations/. * `JOB_ID` can contain only letters ([A-Za-z]), numbers ([0-9]), hyphens (-), or underscores (_). The maximum length is 500 characters. */ public java.lang.String getName() { return name; } /** * Optionally caller-specified in CreateJob, after which it becomes output only. The job * name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. * * `PROJECT_ID` can contain letters ([A-Za-z]), numbers ([0-9]), hyphens (-), colons (:), * or periods (.). For more information, see [Identifying * projects](https://cloud.google.com/resource-manager/docs/creating-managing- * projects#identifying_projects) * `LOCATION_ID` is the canonical ID for the job's * location. The list of available locations can be obtained by calling ListLocations. For * more information, see https://cloud.google.com/about/locations/. * `JOB_ID` can contain * only letters ([A-Za-z]), numbers ([0-9]), hyphens (-), or underscores (_). The maximum * length is 500 characters. */ public Patch setName(java.lang.String name) { if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(), "Parameter name must conform to the pattern " + "^projects/[^/]+/locations/[^/]+/jobs/[^/]+$"); } this.name = name; return this; } /** A mask used to specify which fields of the job are being updated. */ @com.google.api.client.util.Key private String updateMask; /** A mask used to specify which fields of the job are being updated. */ public String getUpdateMask() { return updateMask; } /** A mask used to specify which fields of the job are being updated. */ public Patch setUpdateMask(String updateMask) { this.updateMask = updateMask; return this; } @Override public Patch set(String parameterName, Object value) { return (Patch) super.set(parameterName, value); } } /** * Pauses a job. If a job is paused then the system will stop executing the job until it is re- * enabled via ResumeJob. The state of the job is stored in state; if paused it will be set to * Job.State.PAUSED. A job must be in Job.State.ENABLED to be paused. * * Create a request for the method "jobs.pause". * * This request holds the parameters needed by the cloudscheduler server. After setting any * optional parameters, call the {@link Pause#execute()} method to invoke the remote operation. * * @param name Required. The job name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. * @param content the {@link com.google.api.services.cloudscheduler.v1.model.PauseJobRequest} * @return the request */ public Pause pause(java.lang.String name, com.google.api.services.cloudscheduler.v1.model.PauseJobRequest content) throws java.io.IOException { Pause result = new Pause(name, content); initialize(result); return result; } public class Pause extends CloudSchedulerRequest<com.google.api.services.cloudscheduler.v1.model.Job> { private static final String REST_PATH = "v1/{+name}:pause"; private final java.util.regex.Pattern NAME_PATTERN = java.util.regex.Pattern.compile("^projects/[^/]+/locations/[^/]+/jobs/[^/]+$"); /** * Pauses a job. If a job is paused then the system will stop executing the job until it is re- * enabled via ResumeJob. The state of the job is stored in state; if paused it will be set to * Job.State.PAUSED. A job must be in Job.State.ENABLED to be paused. * * Create a request for the method "jobs.pause". * * This request holds the parameters needed by the the cloudscheduler server. After setting any * optional parameters, call the {@link Pause#execute()} method to invoke the remote operation. * <p> {@link * Pause#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param name Required. The job name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. * @param content the {@link com.google.api.services.cloudscheduler.v1.model.PauseJobRequest} * @since 1.13 */ protected Pause(java.lang.String name, com.google.api.services.cloudscheduler.v1.model.PauseJobRequest content) { super(CloudScheduler.this, "POST", REST_PATH, content, com.google.api.services.cloudscheduler.v1.model.Job.class); this.name = com.google.api.client.util.Preconditions.checkNotNull(name, "Required parameter name must be specified."); if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(), "Parameter name must conform to the pattern " + "^projects/[^/]+/locations/[^/]+/jobs/[^/]+$"); } } @Override public Pause set$Xgafv(java.lang.String $Xgafv) { return (Pause) super.set$Xgafv($Xgafv); } @Override public Pause setAccessToken(java.lang.String accessToken) { return (Pause) super.setAccessToken(accessToken); } @Override public Pause setAlt(java.lang.String alt) { return (Pause) super.setAlt(alt); } @Override public Pause setCallback(java.lang.String callback) { return (Pause) super.setCallback(callback); } @Override public Pause setFields(java.lang.String fields) { return (Pause) super.setFields(fields); } @Override public Pause setKey(java.lang.String key) { return (Pause) super.setKey(key); } @Override public Pause setOauthToken(java.lang.String oauthToken) { return (Pause) super.setOauthToken(oauthToken); } @Override public Pause setPrettyPrint(java.lang.Boolean prettyPrint) { return (Pause) super.setPrettyPrint(prettyPrint); } @Override public Pause setQuotaUser(java.lang.String quotaUser) { return (Pause) super.setQuotaUser(quotaUser); } @Override public Pause setUploadType(java.lang.String uploadType) { return (Pause) super.setUploadType(uploadType); } @Override public Pause setUploadProtocol(java.lang.String uploadProtocol) { return (Pause) super.setUploadProtocol(uploadProtocol); } /** * Required. The job name. For example: * `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. */ @com.google.api.client.util.Key private java.lang.String name; /** Required. The job name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. */ public java.lang.String getName() { return name; } /** * Required. The job name. For example: * `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. */ public Pause setName(java.lang.String name) { if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(), "Parameter name must conform to the pattern " + "^projects/[^/]+/locations/[^/]+/jobs/[^/]+$"); } this.name = name; return this; } @Override public Pause set(String parameterName, Object value) { return (Pause) super.set(parameterName, value); } } /** * Resume a job. This method reenables a job after it has been Job.State.PAUSED. The state of a job * is stored in Job.state; after calling this method it will be set to Job.State.ENABLED. A job must * be in Job.State.PAUSED to be resumed. * * Create a request for the method "jobs.resume". * * This request holds the parameters needed by the cloudscheduler server. After setting any * optional parameters, call the {@link Resume#execute()} method to invoke the remote operation. * * @param name Required. The job name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. * @param content the {@link com.google.api.services.cloudscheduler.v1.model.ResumeJobRequest} * @return the request */ public Resume resume(java.lang.String name, com.google.api.services.cloudscheduler.v1.model.ResumeJobRequest content) throws java.io.IOException { Resume result = new Resume(name, content); initialize(result); return result; } public class Resume extends CloudSchedulerRequest<com.google.api.services.cloudscheduler.v1.model.Job> { private static final String REST_PATH = "v1/{+name}:resume"; private final java.util.regex.Pattern NAME_PATTERN = java.util.regex.Pattern.compile("^projects/[^/]+/locations/[^/]+/jobs/[^/]+$"); /** * Resume a job. This method reenables a job after it has been Job.State.PAUSED. The state of a * job is stored in Job.state; after calling this method it will be set to Job.State.ENABLED. A * job must be in Job.State.PAUSED to be resumed. * * Create a request for the method "jobs.resume". * * This request holds the parameters needed by the the cloudscheduler server. After setting any * optional parameters, call the {@link Resume#execute()} method to invoke the remote operation. * <p> {@link * Resume#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param name Required. The job name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. * @param content the {@link com.google.api.services.cloudscheduler.v1.model.ResumeJobRequest} * @since 1.13 */ protected Resume(java.lang.String name, com.google.api.services.cloudscheduler.v1.model.ResumeJobRequest content) { super(CloudScheduler.this, "POST", REST_PATH, content, com.google.api.services.cloudscheduler.v1.model.Job.class); this.name = com.google.api.client.util.Preconditions.checkNotNull(name, "Required parameter name must be specified."); if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(), "Parameter name must conform to the pattern " + "^projects/[^/]+/locations/[^/]+/jobs/[^/]+$"); } } @Override public Resume set$Xgafv(java.lang.String $Xgafv) { return (Resume) super.set$Xgafv($Xgafv); } @Override public Resume setAccessToken(java.lang.String accessToken) { return (Resume) super.setAccessToken(accessToken); } @Override public Resume setAlt(java.lang.String alt) { return (Resume) super.setAlt(alt); } @Override public Resume setCallback(java.lang.String callback) { return (Resume) super.setCallback(callback); } @Override public Resume setFields(java.lang.String fields) { return (Resume) super.setFields(fields); } @Override public Resume setKey(java.lang.String key) { return (Resume) super.setKey(key); } @Override public Resume setOauthToken(java.lang.String oauthToken) { return (Resume) super.setOauthToken(oauthToken); } @Override public Resume setPrettyPrint(java.lang.Boolean prettyPrint) { return (Resume) super.setPrettyPrint(prettyPrint); } @Override public Resume setQuotaUser(java.lang.String quotaUser) { return (Resume) super.setQuotaUser(quotaUser); } @Override public Resume setUploadType(java.lang.String uploadType) { return (Resume) super.setUploadType(uploadType); } @Override public Resume setUploadProtocol(java.lang.String uploadProtocol) { return (Resume) super.setUploadProtocol(uploadProtocol); } /** * Required. The job name. For example: * `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. */ @com.google.api.client.util.Key private java.lang.String name; /** Required. The job name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. */ public java.lang.String getName() { return name; } /** * Required. The job name. For example: * `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. */ public Resume setName(java.lang.String name) { if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(), "Parameter name must conform to the pattern " + "^projects/[^/]+/locations/[^/]+/jobs/[^/]+$"); } this.name = name; return this; } @Override public Resume set(String parameterName, Object value) { return (Resume) super.set(parameterName, value); } } /** * Forces a job to run now. When this method is called, Cloud Scheduler will dispatch the job, even * if the job is already running. * * Create a request for the method "jobs.run". * * This request holds the parameters needed by the cloudscheduler server. After setting any * optional parameters, call the {@link Run#execute()} method to invoke the remote operation. * * @param name Required. The job name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. * @param content the {@link com.google.api.services.cloudscheduler.v1.model.RunJobRequest} * @return the request */ public Run run(java.lang.String name, com.google.api.services.cloudscheduler.v1.model.RunJobRequest content) throws java.io.IOException { Run result = new Run(name, content); initialize(result); return result; } public class Run extends CloudSchedulerRequest<com.google.api.services.cloudscheduler.v1.model.Job> { private static final String REST_PATH = "v1/{+name}:run"; private final java.util.regex.Pattern NAME_PATTERN = java.util.regex.Pattern.compile("^projects/[^/]+/locations/[^/]+/jobs/[^/]+$"); /** * Forces a job to run now. When this method is called, Cloud Scheduler will dispatch the job, * even if the job is already running. * * Create a request for the method "jobs.run". * * This request holds the parameters needed by the the cloudscheduler server. After setting any * optional parameters, call the {@link Run#execute()} method to invoke the remote operation. <p> * {@link Run#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} * must be called to initialize this instance immediately after invoking the constructor. </p> * * @param name Required. The job name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. * @param content the {@link com.google.api.services.cloudscheduler.v1.model.RunJobRequest} * @since 1.13 */ protected Run(java.lang.String name, com.google.api.services.cloudscheduler.v1.model.RunJobRequest content) { super(CloudScheduler.this, "POST", REST_PATH, content, com.google.api.services.cloudscheduler.v1.model.Job.class); this.name = com.google.api.client.util.Preconditions.checkNotNull(name, "Required parameter name must be specified."); if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(), "Parameter name must conform to the pattern " + "^projects/[^/]+/locations/[^/]+/jobs/[^/]+$"); } } @Override public Run set$Xgafv(java.lang.String $Xgafv) { return (Run) super.set$Xgafv($Xgafv); } @Override public Run setAccessToken(java.lang.String accessToken) { return (Run) super.setAccessToken(accessToken); } @Override public Run setAlt(java.lang.String alt) { return (Run) super.setAlt(alt); } @Override public Run setCallback(java.lang.String callback) { return (Run) super.setCallback(callback); } @Override public Run setFields(java.lang.String fields) { return (Run) super.setFields(fields); } @Override public Run setKey(java.lang.String key) { return (Run) super.setKey(key); } @Override public Run setOauthToken(java.lang.String oauthToken) { return (Run) super.setOauthToken(oauthToken); } @Override public Run setPrettyPrint(java.lang.Boolean prettyPrint) { return (Run) super.setPrettyPrint(prettyPrint); } @Override public Run setQuotaUser(java.lang.String quotaUser) { return (Run) super.setQuotaUser(quotaUser); } @Override public Run setUploadType(java.lang.String uploadType) { return (Run) super.setUploadType(uploadType); } @Override public Run setUploadProtocol(java.lang.String uploadProtocol) { return (Run) super.setUploadProtocol(uploadProtocol); } /** * Required. The job name. For example: * `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. */ @com.google.api.client.util.Key private java.lang.String name; /** Required. The job name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. */ public java.lang.String getName() { return name; } /** * Required. The job name. For example: * `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. */ public Run setName(java.lang.String name) { if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(), "Parameter name must conform to the pattern " + "^projects/[^/]+/locations/[^/]+/jobs/[^/]+$"); } this.name = name; return this; } @Override public Run set(String parameterName, Object value) { return (Run) super.set(parameterName, value); } } } } } /** * Builder for {@link CloudScheduler}. * * <p> * Implementation is not thread-safe. * </p> * * @since 1.3.0 */ public static final class Builder extends com.google.api.client.googleapis.services.json.AbstractGoogleJsonClient.Builder { /** * Returns an instance of a new builder. * * @param transport HTTP transport, which should normally be: * <ul> * <li>Google App Engine: * {@code com.google.api.client.extensions.appengine.http.UrlFetchTransport}</li> * <li>Android: {@code newCompatibleTransport} from * {@code com.google.api.client.extensions.android.http.AndroidHttp}</li> * <li>Java: {@link com.google.api.client.googleapis.javanet.GoogleNetHttpTransport#newTrustedTransport()} * </li> * </ul> * @param jsonFactory JSON factory, which may be: * <ul> * <li>Jackson: {@code com.google.api.client.json.jackson2.JacksonFactory}</li> * <li>Google GSON: {@code com.google.api.client.json.gson.GsonFactory}</li> * <li>Android Honeycomb or higher: * {@code com.google.api.client.extensions.android.json.AndroidJsonFactory}</li> * </ul> * @param httpRequestInitializer HTTP request initializer or {@code null} for none * @since 1.7 */ public Builder(com.google.api.client.http.HttpTransport transport, com.google.api.client.json.JsonFactory jsonFactory, com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) { super( transport, jsonFactory, DEFAULT_ROOT_URL, DEFAULT_SERVICE_PATH, httpRequestInitializer, false); setBatchPath(DEFAULT_BATCH_PATH); } /** Builds a new instance of {@link CloudScheduler}. */ @Override public CloudScheduler build() { return new CloudScheduler(this); } @Override public Builder setRootUrl(String rootUrl) { return (Builder) super.setRootUrl(rootUrl); } @Override public Builder setServicePath(String servicePath) { return (Builder) super.setServicePath(servicePath); } @Override public Builder setBatchPath(String batchPath) { return (Builder) super.setBatchPath(batchPath); } @Override public Builder setHttpRequestInitializer(com.google.api.client.http.HttpRequestInitializer httpRequestInitializer) { return (Builder) super.setHttpRequestInitializer(httpRequestInitializer); } @Override public Builder setApplicationName(String applicationName) { return (Builder) super.setApplicationName(applicationName); } @Override public Builder setSuppressPatternChecks(boolean suppressPatternChecks) { return (Builder) super.setSuppressPatternChecks(suppressPatternChecks); } @Override public Builder setSuppressRequiredParameterChecks(boolean suppressRequiredParameterChecks) { return (Builder) super.setSuppressRequiredParameterChecks(suppressRequiredParameterChecks); } @Override public Builder setSuppressAllChecks(boolean suppressAllChecks) { return (Builder) super.setSuppressAllChecks(suppressAllChecks); } /** * Set the {@link CloudSchedulerRequestInitializer}. * * @since 1.12 */ public Builder setCloudSchedulerRequestInitializer( CloudSchedulerRequestInitializer cloudschedulerRequestInitializer) { return (Builder) super.setGoogleClientRequestInitializer(cloudschedulerRequestInitializer); } @Override public Builder setGoogleClientRequestInitializer( com.google.api.client.googleapis.services.GoogleClientRequestInitializer googleClientRequestInitializer) { return (Builder) super.setGoogleClientRequestInitializer(googleClientRequestInitializer); } } }
Java
public class Projects { /** * An accessor for creating requests from the Locations collection. * * <p>The typical use is:</p> * <pre> * {@code CloudScheduler cloudscheduler = new CloudScheduler(...);} * {@code CloudScheduler.Locations.List request = cloudscheduler.locations().list(parameters ...)} * </pre> * * @return the resource collection */ public Locations locations() { return new Locations(); } /** * The "locations" collection of methods. */ public class Locations { /** * Gets information about a location. * * Create a request for the method "locations.get". * * This request holds the parameters needed by the cloudscheduler server. After setting any * optional parameters, call the {@link Get#execute()} method to invoke the remote operation. * * @param name Resource name for the location. * @return the request */ public Get get(java.lang.String name) throws java.io.IOException { Get result = new Get(name); initialize(result); return result; } public class Get extends CloudSchedulerRequest<com.google.api.services.cloudscheduler.v1.model.Location> { private static final String REST_PATH = "v1/{+name}"; private final java.util.regex.Pattern NAME_PATTERN = java.util.regex.Pattern.compile("^projects/[^/]+/locations/[^/]+$"); /** * Gets information about a location. * * Create a request for the method "locations.get". * * This request holds the parameters needed by the the cloudscheduler server. After setting any * optional parameters, call the {@link Get#execute()} method to invoke the remote operation. <p> * {@link Get#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} * must be called to initialize this instance immediately after invoking the constructor. </p> * * @param name Resource name for the location. * @since 1.13 */ protected Get(java.lang.String name) { super(CloudScheduler.this, "GET", REST_PATH, null, com.google.api.services.cloudscheduler.v1.model.Location.class); this.name = com.google.api.client.util.Preconditions.checkNotNull(name, "Required parameter name must be specified."); if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(), "Parameter name must conform to the pattern " + "^projects/[^/]+/locations/[^/]+$"); } } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public Get set$Xgafv(java.lang.String $Xgafv) { return (Get) super.set$Xgafv($Xgafv); } @Override public Get setAccessToken(java.lang.String accessToken) { return (Get) super.setAccessToken(accessToken); } @Override public Get setAlt(java.lang.String alt) { return (Get) super.setAlt(alt); } @Override public Get setCallback(java.lang.String callback) { return (Get) super.setCallback(callback); } @Override public Get setFields(java.lang.String fields) { return (Get) super.setFields(fields); } @Override public Get setKey(java.lang.String key) { return (Get) super.setKey(key); } @Override public Get setOauthToken(java.lang.String oauthToken) { return (Get) super.setOauthToken(oauthToken); } @Override public Get setPrettyPrint(java.lang.Boolean prettyPrint) { return (Get) super.setPrettyPrint(prettyPrint); } @Override public Get setQuotaUser(java.lang.String quotaUser) { return (Get) super.setQuotaUser(quotaUser); } @Override public Get setUploadType(java.lang.String uploadType) { return (Get) super.setUploadType(uploadType); } @Override public Get setUploadProtocol(java.lang.String uploadProtocol) { return (Get) super.setUploadProtocol(uploadProtocol); } /** Resource name for the location. */ @com.google.api.client.util.Key private java.lang.String name; /** Resource name for the location. */ public java.lang.String getName() { return name; } /** Resource name for the location. */ public Get setName(java.lang.String name) { if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(), "Parameter name must conform to the pattern " + "^projects/[^/]+/locations/[^/]+$"); } this.name = name; return this; } @Override public Get set(String parameterName, Object value) { return (Get) super.set(parameterName, value); } } /** * Lists information about the supported locations for this service. * * Create a request for the method "locations.list". * * This request holds the parameters needed by the cloudscheduler server. After setting any * optional parameters, call the {@link List#execute()} method to invoke the remote operation. * * @param name The resource that owns the locations collection, if applicable. * @return the request */ public List list(java.lang.String name) throws java.io.IOException { List result = new List(name); initialize(result); return result; } public class List extends CloudSchedulerRequest<com.google.api.services.cloudscheduler.v1.model.ListLocationsResponse> { private static final String REST_PATH = "v1/{+name}/locations"; private final java.util.regex.Pattern NAME_PATTERN = java.util.regex.Pattern.compile("^projects/[^/]+$"); /** * Lists information about the supported locations for this service. * * Create a request for the method "locations.list". * * This request holds the parameters needed by the the cloudscheduler server. After setting any * optional parameters, call the {@link List#execute()} method to invoke the remote operation. <p> * {@link List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} * must be called to initialize this instance immediately after invoking the constructor. </p> * * @param name The resource that owns the locations collection, if applicable. * @since 1.13 */ protected List(java.lang.String name) { super(CloudScheduler.this, "GET", REST_PATH, null, com.google.api.services.cloudscheduler.v1.model.ListLocationsResponse.class); this.name = com.google.api.client.util.Preconditions.checkNotNull(name, "Required parameter name must be specified."); if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(), "Parameter name must conform to the pattern " + "^projects/[^/]+$"); } } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public List set$Xgafv(java.lang.String $Xgafv) { return (List) super.set$Xgafv($Xgafv); } @Override public List setAccessToken(java.lang.String accessToken) { return (List) super.setAccessToken(accessToken); } @Override public List setAlt(java.lang.String alt) { return (List) super.setAlt(alt); } @Override public List setCallback(java.lang.String callback) { return (List) super.setCallback(callback); } @Override public List setFields(java.lang.String fields) { return (List) super.setFields(fields); } @Override public List setKey(java.lang.String key) { return (List) super.setKey(key); } @Override public List setOauthToken(java.lang.String oauthToken) { return (List) super.setOauthToken(oauthToken); } @Override public List setPrettyPrint(java.lang.Boolean prettyPrint) { return (List) super.setPrettyPrint(prettyPrint); } @Override public List setQuotaUser(java.lang.String quotaUser) { return (List) super.setQuotaUser(quotaUser); } @Override public List setUploadType(java.lang.String uploadType) { return (List) super.setUploadType(uploadType); } @Override public List setUploadProtocol(java.lang.String uploadProtocol) { return (List) super.setUploadProtocol(uploadProtocol); } /** The resource that owns the locations collection, if applicable. */ @com.google.api.client.util.Key private java.lang.String name; /** The resource that owns the locations collection, if applicable. */ public java.lang.String getName() { return name; } /** The resource that owns the locations collection, if applicable. */ public List setName(java.lang.String name) { if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(), "Parameter name must conform to the pattern " + "^projects/[^/]+$"); } this.name = name; return this; } /** The standard list filter. */ @com.google.api.client.util.Key private java.lang.String filter; /** The standard list filter. */ public java.lang.String getFilter() { return filter; } /** The standard list filter. */ public List setFilter(java.lang.String filter) { this.filter = filter; return this; } /** The standard list page size. */ @com.google.api.client.util.Key private java.lang.Integer pageSize; /** The standard list page size. */ public java.lang.Integer getPageSize() { return pageSize; } /** The standard list page size. */ public List setPageSize(java.lang.Integer pageSize) { this.pageSize = pageSize; return this; } /** The standard list page token. */ @com.google.api.client.util.Key private java.lang.String pageToken; /** The standard list page token. */ public java.lang.String getPageToken() { return pageToken; } /** The standard list page token. */ public List setPageToken(java.lang.String pageToken) { this.pageToken = pageToken; return this; } @Override public List set(String parameterName, Object value) { return (List) super.set(parameterName, value); } } /** * An accessor for creating requests from the Jobs collection. * * <p>The typical use is:</p> * <pre> * {@code CloudScheduler cloudscheduler = new CloudScheduler(...);} * {@code CloudScheduler.Jobs.List request = cloudscheduler.jobs().list(parameters ...)} * </pre> * * @return the resource collection */ public Jobs jobs() { return new Jobs(); } /** * The "jobs" collection of methods. */ public class Jobs { /** * Creates a job. * * Create a request for the method "jobs.create". * * This request holds the parameters needed by the cloudscheduler server. After setting any * optional parameters, call the {@link Create#execute()} method to invoke the remote operation. * * @param parent Required. The location name. For example: `projects/PROJECT_ID/locations/LOCATION_ID`. * @param content the {@link com.google.api.services.cloudscheduler.v1.model.Job} * @return the request */ public Create create(java.lang.String parent, com.google.api.services.cloudscheduler.v1.model.Job content) throws java.io.IOException { Create result = new Create(parent, content); initialize(result); return result; } public class Create extends CloudSchedulerRequest<com.google.api.services.cloudscheduler.v1.model.Job> { private static final String REST_PATH = "v1/{+parent}/jobs"; private final java.util.regex.Pattern PARENT_PATTERN = java.util.regex.Pattern.compile("^projects/[^/]+/locations/[^/]+$"); /** * Creates a job. * * Create a request for the method "jobs.create". * * This request holds the parameters needed by the the cloudscheduler server. After setting any * optional parameters, call the {@link Create#execute()} method to invoke the remote operation. * <p> {@link * Create#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param parent Required. The location name. For example: `projects/PROJECT_ID/locations/LOCATION_ID`. * @param content the {@link com.google.api.services.cloudscheduler.v1.model.Job} * @since 1.13 */ protected Create(java.lang.String parent, com.google.api.services.cloudscheduler.v1.model.Job content) { super(CloudScheduler.this, "POST", REST_PATH, content, com.google.api.services.cloudscheduler.v1.model.Job.class); this.parent = com.google.api.client.util.Preconditions.checkNotNull(parent, "Required parameter parent must be specified."); if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(PARENT_PATTERN.matcher(parent).matches(), "Parameter parent must conform to the pattern " + "^projects/[^/]+/locations/[^/]+$"); } } @Override public Create set$Xgafv(java.lang.String $Xgafv) { return (Create) super.set$Xgafv($Xgafv); } @Override public Create setAccessToken(java.lang.String accessToken) { return (Create) super.setAccessToken(accessToken); } @Override public Create setAlt(java.lang.String alt) { return (Create) super.setAlt(alt); } @Override public Create setCallback(java.lang.String callback) { return (Create) super.setCallback(callback); } @Override public Create setFields(java.lang.String fields) { return (Create) super.setFields(fields); } @Override public Create setKey(java.lang.String key) { return (Create) super.setKey(key); } @Override public Create setOauthToken(java.lang.String oauthToken) { return (Create) super.setOauthToken(oauthToken); } @Override public Create setPrettyPrint(java.lang.Boolean prettyPrint) { return (Create) super.setPrettyPrint(prettyPrint); } @Override public Create setQuotaUser(java.lang.String quotaUser) { return (Create) super.setQuotaUser(quotaUser); } @Override public Create setUploadType(java.lang.String uploadType) { return (Create) super.setUploadType(uploadType); } @Override public Create setUploadProtocol(java.lang.String uploadProtocol) { return (Create) super.setUploadProtocol(uploadProtocol); } /** * Required. The location name. For example: `projects/PROJECT_ID/locations/LOCATION_ID`. */ @com.google.api.client.util.Key private java.lang.String parent; /** Required. The location name. For example: `projects/PROJECT_ID/locations/LOCATION_ID`. */ public java.lang.String getParent() { return parent; } /** * Required. The location name. For example: `projects/PROJECT_ID/locations/LOCATION_ID`. */ public Create setParent(java.lang.String parent) { if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(PARENT_PATTERN.matcher(parent).matches(), "Parameter parent must conform to the pattern " + "^projects/[^/]+/locations/[^/]+$"); } this.parent = parent; return this; } @Override public Create set(String parameterName, Object value) { return (Create) super.set(parameterName, value); } } /** * Deletes a job. * * Create a request for the method "jobs.delete". * * This request holds the parameters needed by the cloudscheduler server. After setting any * optional parameters, call the {@link Delete#execute()} method to invoke the remote operation. * * @param name Required. The job name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. * @return the request */ public Delete delete(java.lang.String name) throws java.io.IOException { Delete result = new Delete(name); initialize(result); return result; } public class Delete extends CloudSchedulerRequest<com.google.api.services.cloudscheduler.v1.model.Empty> { private static final String REST_PATH = "v1/{+name}"; private final java.util.regex.Pattern NAME_PATTERN = java.util.regex.Pattern.compile("^projects/[^/]+/locations/[^/]+/jobs/[^/]+$"); /** * Deletes a job. * * Create a request for the method "jobs.delete". * * This request holds the parameters needed by the the cloudscheduler server. After setting any * optional parameters, call the {@link Delete#execute()} method to invoke the remote operation. * <p> {@link * Delete#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param name Required. The job name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. * @since 1.13 */ protected Delete(java.lang.String name) { super(CloudScheduler.this, "DELETE", REST_PATH, null, com.google.api.services.cloudscheduler.v1.model.Empty.class); this.name = com.google.api.client.util.Preconditions.checkNotNull(name, "Required parameter name must be specified."); if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(), "Parameter name must conform to the pattern " + "^projects/[^/]+/locations/[^/]+/jobs/[^/]+$"); } } @Override public Delete set$Xgafv(java.lang.String $Xgafv) { return (Delete) super.set$Xgafv($Xgafv); } @Override public Delete setAccessToken(java.lang.String accessToken) { return (Delete) super.setAccessToken(accessToken); } @Override public Delete setAlt(java.lang.String alt) { return (Delete) super.setAlt(alt); } @Override public Delete setCallback(java.lang.String callback) { return (Delete) super.setCallback(callback); } @Override public Delete setFields(java.lang.String fields) { return (Delete) super.setFields(fields); } @Override public Delete setKey(java.lang.String key) { return (Delete) super.setKey(key); } @Override public Delete setOauthToken(java.lang.String oauthToken) { return (Delete) super.setOauthToken(oauthToken); } @Override public Delete setPrettyPrint(java.lang.Boolean prettyPrint) { return (Delete) super.setPrettyPrint(prettyPrint); } @Override public Delete setQuotaUser(java.lang.String quotaUser) { return (Delete) super.setQuotaUser(quotaUser); } @Override public Delete setUploadType(java.lang.String uploadType) { return (Delete) super.setUploadType(uploadType); } @Override public Delete setUploadProtocol(java.lang.String uploadProtocol) { return (Delete) super.setUploadProtocol(uploadProtocol); } /** * Required. The job name. For example: * `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. */ @com.google.api.client.util.Key private java.lang.String name; /** Required. The job name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. */ public java.lang.String getName() { return name; } /** * Required. The job name. For example: * `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. */ public Delete setName(java.lang.String name) { if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(), "Parameter name must conform to the pattern " + "^projects/[^/]+/locations/[^/]+/jobs/[^/]+$"); } this.name = name; return this; } @Override public Delete set(String parameterName, Object value) { return (Delete) super.set(parameterName, value); } } /** * Gets a job. * * Create a request for the method "jobs.get". * * This request holds the parameters needed by the cloudscheduler server. After setting any * optional parameters, call the {@link Get#execute()} method to invoke the remote operation. * * @param name Required. The job name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. * @return the request */ public Get get(java.lang.String name) throws java.io.IOException { Get result = new Get(name); initialize(result); return result; } public class Get extends CloudSchedulerRequest<com.google.api.services.cloudscheduler.v1.model.Job> { private static final String REST_PATH = "v1/{+name}"; private final java.util.regex.Pattern NAME_PATTERN = java.util.regex.Pattern.compile("^projects/[^/]+/locations/[^/]+/jobs/[^/]+$"); /** * Gets a job. * * Create a request for the method "jobs.get". * * This request holds the parameters needed by the the cloudscheduler server. After setting any * optional parameters, call the {@link Get#execute()} method to invoke the remote operation. <p> * {@link Get#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} * must be called to initialize this instance immediately after invoking the constructor. </p> * * @param name Required. The job name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. * @since 1.13 */ protected Get(java.lang.String name) { super(CloudScheduler.this, "GET", REST_PATH, null, com.google.api.services.cloudscheduler.v1.model.Job.class); this.name = com.google.api.client.util.Preconditions.checkNotNull(name, "Required parameter name must be specified."); if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(), "Parameter name must conform to the pattern " + "^projects/[^/]+/locations/[^/]+/jobs/[^/]+$"); } } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public Get set$Xgafv(java.lang.String $Xgafv) { return (Get) super.set$Xgafv($Xgafv); } @Override public Get setAccessToken(java.lang.String accessToken) { return (Get) super.setAccessToken(accessToken); } @Override public Get setAlt(java.lang.String alt) { return (Get) super.setAlt(alt); } @Override public Get setCallback(java.lang.String callback) { return (Get) super.setCallback(callback); } @Override public Get setFields(java.lang.String fields) { return (Get) super.setFields(fields); } @Override public Get setKey(java.lang.String key) { return (Get) super.setKey(key); } @Override public Get setOauthToken(java.lang.String oauthToken) { return (Get) super.setOauthToken(oauthToken); } @Override public Get setPrettyPrint(java.lang.Boolean prettyPrint) { return (Get) super.setPrettyPrint(prettyPrint); } @Override public Get setQuotaUser(java.lang.String quotaUser) { return (Get) super.setQuotaUser(quotaUser); } @Override public Get setUploadType(java.lang.String uploadType) { return (Get) super.setUploadType(uploadType); } @Override public Get setUploadProtocol(java.lang.String uploadProtocol) { return (Get) super.setUploadProtocol(uploadProtocol); } /** * Required. The job name. For example: * `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. */ @com.google.api.client.util.Key private java.lang.String name; /** Required. The job name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. */ public java.lang.String getName() { return name; } /** * Required. The job name. For example: * `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. */ public Get setName(java.lang.String name) { if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(), "Parameter name must conform to the pattern " + "^projects/[^/]+/locations/[^/]+/jobs/[^/]+$"); } this.name = name; return this; } @Override public Get set(String parameterName, Object value) { return (Get) super.set(parameterName, value); } } /** * Lists jobs. * * Create a request for the method "jobs.list". * * This request holds the parameters needed by the cloudscheduler server. After setting any * optional parameters, call the {@link List#execute()} method to invoke the remote operation. * * @param parent Required. The location name. For example: `projects/PROJECT_ID/locations/LOCATION_ID`. * @return the request */ public List list(java.lang.String parent) throws java.io.IOException { List result = new List(parent); initialize(result); return result; } public class List extends CloudSchedulerRequest<com.google.api.services.cloudscheduler.v1.model.ListJobsResponse> { private static final String REST_PATH = "v1/{+parent}/jobs"; private final java.util.regex.Pattern PARENT_PATTERN = java.util.regex.Pattern.compile("^projects/[^/]+/locations/[^/]+$"); /** * Lists jobs. * * Create a request for the method "jobs.list". * * This request holds the parameters needed by the the cloudscheduler server. After setting any * optional parameters, call the {@link List#execute()} method to invoke the remote operation. <p> * {@link List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} * must be called to initialize this instance immediately after invoking the constructor. </p> * * @param parent Required. The location name. For example: `projects/PROJECT_ID/locations/LOCATION_ID`. * @since 1.13 */ protected List(java.lang.String parent) { super(CloudScheduler.this, "GET", REST_PATH, null, com.google.api.services.cloudscheduler.v1.model.ListJobsResponse.class); this.parent = com.google.api.client.util.Preconditions.checkNotNull(parent, "Required parameter parent must be specified."); if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(PARENT_PATTERN.matcher(parent).matches(), "Parameter parent must conform to the pattern " + "^projects/[^/]+/locations/[^/]+$"); } } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public List set$Xgafv(java.lang.String $Xgafv) { return (List) super.set$Xgafv($Xgafv); } @Override public List setAccessToken(java.lang.String accessToken) { return (List) super.setAccessToken(accessToken); } @Override public List setAlt(java.lang.String alt) { return (List) super.setAlt(alt); } @Override public List setCallback(java.lang.String callback) { return (List) super.setCallback(callback); } @Override public List setFields(java.lang.String fields) { return (List) super.setFields(fields); } @Override public List setKey(java.lang.String key) { return (List) super.setKey(key); } @Override public List setOauthToken(java.lang.String oauthToken) { return (List) super.setOauthToken(oauthToken); } @Override public List setPrettyPrint(java.lang.Boolean prettyPrint) { return (List) super.setPrettyPrint(prettyPrint); } @Override public List setQuotaUser(java.lang.String quotaUser) { return (List) super.setQuotaUser(quotaUser); } @Override public List setUploadType(java.lang.String uploadType) { return (List) super.setUploadType(uploadType); } @Override public List setUploadProtocol(java.lang.String uploadProtocol) { return (List) super.setUploadProtocol(uploadProtocol); } /** * Required. The location name. For example: `projects/PROJECT_ID/locations/LOCATION_ID`. */ @com.google.api.client.util.Key private java.lang.String parent; /** Required. The location name. For example: `projects/PROJECT_ID/locations/LOCATION_ID`. */ public java.lang.String getParent() { return parent; } /** * Required. The location name. For example: `projects/PROJECT_ID/locations/LOCATION_ID`. */ public List setParent(java.lang.String parent) { if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(PARENT_PATTERN.matcher(parent).matches(), "Parameter parent must conform to the pattern " + "^projects/[^/]+/locations/[^/]+$"); } this.parent = parent; return this; } /** * Requested page size. The maximum page size is 500. If unspecified, the page size will * be the maximum. Fewer jobs than requested might be returned, even if more jobs exist; * use next_page_token to determine if more jobs exist. */ @com.google.api.client.util.Key private java.lang.Integer pageSize; /** Requested page size. The maximum page size is 500. If unspecified, the page size will be the maximum. Fewer jobs than requested might be returned, even if more jobs exist; use next_page_token to determine if more jobs exist. */ public java.lang.Integer getPageSize() { return pageSize; } /** * Requested page size. The maximum page size is 500. If unspecified, the page size will * be the maximum. Fewer jobs than requested might be returned, even if more jobs exist; * use next_page_token to determine if more jobs exist. */ public List setPageSize(java.lang.Integer pageSize) { this.pageSize = pageSize; return this; } /** * A token identifying a page of results the server will return. To request the first page * results, page_token must be empty. To request the next page of results, page_token must * be the value of next_page_token returned from the previous call to ListJobs. It is an * error to switch the value of filter or order_by while iterating through pages. */ @com.google.api.client.util.Key private java.lang.String pageToken; /** A token identifying a page of results the server will return. To request the first page results, page_token must be empty. To request the next page of results, page_token must be the value of next_page_token returned from the previous call to ListJobs. It is an error to switch the value of filter or order_by while iterating through pages. */ public java.lang.String getPageToken() { return pageToken; } /** * A token identifying a page of results the server will return. To request the first page * results, page_token must be empty. To request the next page of results, page_token must * be the value of next_page_token returned from the previous call to ListJobs. It is an * error to switch the value of filter or order_by while iterating through pages. */ public List setPageToken(java.lang.String pageToken) { this.pageToken = pageToken; return this; } @Override public List set(String parameterName, Object value) { return (List) super.set(parameterName, value); } } /** * Updates a job. If successful, the updated Job is returned. If the job does not exist, `NOT_FOUND` * is returned. If UpdateJob does not successfully return, it is possible for the job to be in an * Job.State.UPDATE_FAILED state. A job in this state may not be executed. If this happens, retry * the UpdateJob request until a successful response is received. * * Create a request for the method "jobs.patch". * * This request holds the parameters needed by the cloudscheduler server. After setting any * optional parameters, call the {@link Patch#execute()} method to invoke the remote operation. * * @param name Optionally caller-specified in CreateJob, after which it becomes output only. The job name. For * example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. * `PROJECT_ID` can * contain letters ([A-Za-z]), numbers ([0-9]), hyphens (-), colons (:), or periods (.). For * more information, see [Identifying projects](https://cloud.google.com/resource- * manager/docs/creating-managing-projects#identifying_projects) * `LOCATION_ID` is the * canonical ID for the job's location. The list of available locations can be obtained by * calling ListLocations. For more information, see * https://cloud.google.com/about/locations/. * `JOB_ID` can contain only letters ([A-Za-z]), * numbers ([0-9]), hyphens (-), or underscores (_). The maximum length is 500 characters. * @param content the {@link com.google.api.services.cloudscheduler.v1.model.Job} * @return the request */ public Patch patch(java.lang.String name, com.google.api.services.cloudscheduler.v1.model.Job content) throws java.io.IOException { Patch result = new Patch(name, content); initialize(result); return result; } public class Patch extends CloudSchedulerRequest<com.google.api.services.cloudscheduler.v1.model.Job> { private static final String REST_PATH = "v1/{+name}"; private final java.util.regex.Pattern NAME_PATTERN = java.util.regex.Pattern.compile("^projects/[^/]+/locations/[^/]+/jobs/[^/]+$"); /** * Updates a job. If successful, the updated Job is returned. If the job does not exist, * `NOT_FOUND` is returned. If UpdateJob does not successfully return, it is possible for the job * to be in an Job.State.UPDATE_FAILED state. A job in this state may not be executed. If this * happens, retry the UpdateJob request until a successful response is received. * * Create a request for the method "jobs.patch". * * This request holds the parameters needed by the the cloudscheduler server. After setting any * optional parameters, call the {@link Patch#execute()} method to invoke the remote operation. * <p> {@link * Patch#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param name Optionally caller-specified in CreateJob, after which it becomes output only. The job name. For * example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. * `PROJECT_ID` can * contain letters ([A-Za-z]), numbers ([0-9]), hyphens (-), colons (:), or periods (.). For * more information, see [Identifying projects](https://cloud.google.com/resource- * manager/docs/creating-managing-projects#identifying_projects) * `LOCATION_ID` is the * canonical ID for the job's location. The list of available locations can be obtained by * calling ListLocations. For more information, see * https://cloud.google.com/about/locations/. * `JOB_ID` can contain only letters ([A-Za-z]), * numbers ([0-9]), hyphens (-), or underscores (_). The maximum length is 500 characters. * @param content the {@link com.google.api.services.cloudscheduler.v1.model.Job} * @since 1.13 */ protected Patch(java.lang.String name, com.google.api.services.cloudscheduler.v1.model.Job content) { super(CloudScheduler.this, "PATCH", REST_PATH, content, com.google.api.services.cloudscheduler.v1.model.Job.class); this.name = com.google.api.client.util.Preconditions.checkNotNull(name, "Required parameter name must be specified."); if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(), "Parameter name must conform to the pattern " + "^projects/[^/]+/locations/[^/]+/jobs/[^/]+$"); } } @Override public Patch set$Xgafv(java.lang.String $Xgafv) { return (Patch) super.set$Xgafv($Xgafv); } @Override public Patch setAccessToken(java.lang.String accessToken) { return (Patch) super.setAccessToken(accessToken); } @Override public Patch setAlt(java.lang.String alt) { return (Patch) super.setAlt(alt); } @Override public Patch setCallback(java.lang.String callback) { return (Patch) super.setCallback(callback); } @Override public Patch setFields(java.lang.String fields) { return (Patch) super.setFields(fields); } @Override public Patch setKey(java.lang.String key) { return (Patch) super.setKey(key); } @Override public Patch setOauthToken(java.lang.String oauthToken) { return (Patch) super.setOauthToken(oauthToken); } @Override public Patch setPrettyPrint(java.lang.Boolean prettyPrint) { return (Patch) super.setPrettyPrint(prettyPrint); } @Override public Patch setQuotaUser(java.lang.String quotaUser) { return (Patch) super.setQuotaUser(quotaUser); } @Override public Patch setUploadType(java.lang.String uploadType) { return (Patch) super.setUploadType(uploadType); } @Override public Patch setUploadProtocol(java.lang.String uploadProtocol) { return (Patch) super.setUploadProtocol(uploadProtocol); } /** * Optionally caller-specified in CreateJob, after which it becomes output only. The job * name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. * * `PROJECT_ID` can contain letters ([A-Za-z]), numbers ([0-9]), hyphens (-), colons (:), * or periods (.). For more information, see [Identifying * projects](https://cloud.google.com/resource-manager/docs/creating-managing- * projects#identifying_projects) * `LOCATION_ID` is the canonical ID for the job's * location. The list of available locations can be obtained by calling ListLocations. For * more information, see https://cloud.google.com/about/locations/. * `JOB_ID` can contain * only letters ([A-Za-z]), numbers ([0-9]), hyphens (-), or underscores (_). The maximum * length is 500 characters. */ @com.google.api.client.util.Key private java.lang.String name; /** Optionally caller-specified in CreateJob, after which it becomes output only. The job name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. * `PROJECT_ID` can contain letters ([A-Za-z]), numbers ([0-9]), hyphens (-), colons (:), or periods (.). For more information, see [Identifying projects](https://cloud.google.com/resource-manager/docs/creating-managing- projects#identifying_projects) * `LOCATION_ID` is the canonical ID for the job's location. The list of available locations can be obtained by calling ListLocations. For more information, see https://cloud.google.com/about/locations/. * `JOB_ID` can contain only letters ([A-Za-z]), numbers ([0-9]), hyphens (-), or underscores (_). The maximum length is 500 characters. */ public java.lang.String getName() { return name; } /** * Optionally caller-specified in CreateJob, after which it becomes output only. The job * name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. * * `PROJECT_ID` can contain letters ([A-Za-z]), numbers ([0-9]), hyphens (-), colons (:), * or periods (.). For more information, see [Identifying * projects](https://cloud.google.com/resource-manager/docs/creating-managing- * projects#identifying_projects) * `LOCATION_ID` is the canonical ID for the job's * location. The list of available locations can be obtained by calling ListLocations. For * more information, see https://cloud.google.com/about/locations/. * `JOB_ID` can contain * only letters ([A-Za-z]), numbers ([0-9]), hyphens (-), or underscores (_). The maximum * length is 500 characters. */ public Patch setName(java.lang.String name) { if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(), "Parameter name must conform to the pattern " + "^projects/[^/]+/locations/[^/]+/jobs/[^/]+$"); } this.name = name; return this; } /** A mask used to specify which fields of the job are being updated. */ @com.google.api.client.util.Key private String updateMask; /** A mask used to specify which fields of the job are being updated. */ public String getUpdateMask() { return updateMask; } /** A mask used to specify which fields of the job are being updated. */ public Patch setUpdateMask(String updateMask) { this.updateMask = updateMask; return this; } @Override public Patch set(String parameterName, Object value) { return (Patch) super.set(parameterName, value); } } /** * Pauses a job. If a job is paused then the system will stop executing the job until it is re- * enabled via ResumeJob. The state of the job is stored in state; if paused it will be set to * Job.State.PAUSED. A job must be in Job.State.ENABLED to be paused. * * Create a request for the method "jobs.pause". * * This request holds the parameters needed by the cloudscheduler server. After setting any * optional parameters, call the {@link Pause#execute()} method to invoke the remote operation. * * @param name Required. The job name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. * @param content the {@link com.google.api.services.cloudscheduler.v1.model.PauseJobRequest} * @return the request */ public Pause pause(java.lang.String name, com.google.api.services.cloudscheduler.v1.model.PauseJobRequest content) throws java.io.IOException { Pause result = new Pause(name, content); initialize(result); return result; } public class Pause extends CloudSchedulerRequest<com.google.api.services.cloudscheduler.v1.model.Job> { private static final String REST_PATH = "v1/{+name}:pause"; private final java.util.regex.Pattern NAME_PATTERN = java.util.regex.Pattern.compile("^projects/[^/]+/locations/[^/]+/jobs/[^/]+$"); /** * Pauses a job. If a job is paused then the system will stop executing the job until it is re- * enabled via ResumeJob. The state of the job is stored in state; if paused it will be set to * Job.State.PAUSED. A job must be in Job.State.ENABLED to be paused. * * Create a request for the method "jobs.pause". * * This request holds the parameters needed by the the cloudscheduler server. After setting any * optional parameters, call the {@link Pause#execute()} method to invoke the remote operation. * <p> {@link * Pause#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param name Required. The job name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. * @param content the {@link com.google.api.services.cloudscheduler.v1.model.PauseJobRequest} * @since 1.13 */ protected Pause(java.lang.String name, com.google.api.services.cloudscheduler.v1.model.PauseJobRequest content) { super(CloudScheduler.this, "POST", REST_PATH, content, com.google.api.services.cloudscheduler.v1.model.Job.class); this.name = com.google.api.client.util.Preconditions.checkNotNull(name, "Required parameter name must be specified."); if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(), "Parameter name must conform to the pattern " + "^projects/[^/]+/locations/[^/]+/jobs/[^/]+$"); } } @Override public Pause set$Xgafv(java.lang.String $Xgafv) { return (Pause) super.set$Xgafv($Xgafv); } @Override public Pause setAccessToken(java.lang.String accessToken) { return (Pause) super.setAccessToken(accessToken); } @Override public Pause setAlt(java.lang.String alt) { return (Pause) super.setAlt(alt); } @Override public Pause setCallback(java.lang.String callback) { return (Pause) super.setCallback(callback); } @Override public Pause setFields(java.lang.String fields) { return (Pause) super.setFields(fields); } @Override public Pause setKey(java.lang.String key) { return (Pause) super.setKey(key); } @Override public Pause setOauthToken(java.lang.String oauthToken) { return (Pause) super.setOauthToken(oauthToken); } @Override public Pause setPrettyPrint(java.lang.Boolean prettyPrint) { return (Pause) super.setPrettyPrint(prettyPrint); } @Override public Pause setQuotaUser(java.lang.String quotaUser) { return (Pause) super.setQuotaUser(quotaUser); } @Override public Pause setUploadType(java.lang.String uploadType) { return (Pause) super.setUploadType(uploadType); } @Override public Pause setUploadProtocol(java.lang.String uploadProtocol) { return (Pause) super.setUploadProtocol(uploadProtocol); } /** * Required. The job name. For example: * `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. */ @com.google.api.client.util.Key private java.lang.String name; /** Required. The job name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. */ public java.lang.String getName() { return name; } /** * Required. The job name. For example: * `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. */ public Pause setName(java.lang.String name) { if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(), "Parameter name must conform to the pattern " + "^projects/[^/]+/locations/[^/]+/jobs/[^/]+$"); } this.name = name; return this; } @Override public Pause set(String parameterName, Object value) { return (Pause) super.set(parameterName, value); } } /** * Resume a job. This method reenables a job after it has been Job.State.PAUSED. The state of a job * is stored in Job.state; after calling this method it will be set to Job.State.ENABLED. A job must * be in Job.State.PAUSED to be resumed. * * Create a request for the method "jobs.resume". * * This request holds the parameters needed by the cloudscheduler server. After setting any * optional parameters, call the {@link Resume#execute()} method to invoke the remote operation. * * @param name Required. The job name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. * @param content the {@link com.google.api.services.cloudscheduler.v1.model.ResumeJobRequest} * @return the request */ public Resume resume(java.lang.String name, com.google.api.services.cloudscheduler.v1.model.ResumeJobRequest content) throws java.io.IOException { Resume result = new Resume(name, content); initialize(result); return result; } public class Resume extends CloudSchedulerRequest<com.google.api.services.cloudscheduler.v1.model.Job> { private static final String REST_PATH = "v1/{+name}:resume"; private final java.util.regex.Pattern NAME_PATTERN = java.util.regex.Pattern.compile("^projects/[^/]+/locations/[^/]+/jobs/[^/]+$"); /** * Resume a job. This method reenables a job after it has been Job.State.PAUSED. The state of a * job is stored in Job.state; after calling this method it will be set to Job.State.ENABLED. A * job must be in Job.State.PAUSED to be resumed. * * Create a request for the method "jobs.resume". * * This request holds the parameters needed by the the cloudscheduler server. After setting any * optional parameters, call the {@link Resume#execute()} method to invoke the remote operation. * <p> {@link * Resume#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param name Required. The job name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. * @param content the {@link com.google.api.services.cloudscheduler.v1.model.ResumeJobRequest} * @since 1.13 */ protected Resume(java.lang.String name, com.google.api.services.cloudscheduler.v1.model.ResumeJobRequest content) { super(CloudScheduler.this, "POST", REST_PATH, content, com.google.api.services.cloudscheduler.v1.model.Job.class); this.name = com.google.api.client.util.Preconditions.checkNotNull(name, "Required parameter name must be specified."); if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(), "Parameter name must conform to the pattern " + "^projects/[^/]+/locations/[^/]+/jobs/[^/]+$"); } } @Override public Resume set$Xgafv(java.lang.String $Xgafv) { return (Resume) super.set$Xgafv($Xgafv); } @Override public Resume setAccessToken(java.lang.String accessToken) { return (Resume) super.setAccessToken(accessToken); } @Override public Resume setAlt(java.lang.String alt) { return (Resume) super.setAlt(alt); } @Override public Resume setCallback(java.lang.String callback) { return (Resume) super.setCallback(callback); } @Override public Resume setFields(java.lang.String fields) { return (Resume) super.setFields(fields); } @Override public Resume setKey(java.lang.String key) { return (Resume) super.setKey(key); } @Override public Resume setOauthToken(java.lang.String oauthToken) { return (Resume) super.setOauthToken(oauthToken); } @Override public Resume setPrettyPrint(java.lang.Boolean prettyPrint) { return (Resume) super.setPrettyPrint(prettyPrint); } @Override public Resume setQuotaUser(java.lang.String quotaUser) { return (Resume) super.setQuotaUser(quotaUser); } @Override public Resume setUploadType(java.lang.String uploadType) { return (Resume) super.setUploadType(uploadType); } @Override public Resume setUploadProtocol(java.lang.String uploadProtocol) { return (Resume) super.setUploadProtocol(uploadProtocol); } /** * Required. The job name. For example: * `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. */ @com.google.api.client.util.Key private java.lang.String name; /** Required. The job name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. */ public java.lang.String getName() { return name; } /** * Required. The job name. For example: * `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. */ public Resume setName(java.lang.String name) { if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(), "Parameter name must conform to the pattern " + "^projects/[^/]+/locations/[^/]+/jobs/[^/]+$"); } this.name = name; return this; } @Override public Resume set(String parameterName, Object value) { return (Resume) super.set(parameterName, value); } } /** * Forces a job to run now. When this method is called, Cloud Scheduler will dispatch the job, even * if the job is already running. * * Create a request for the method "jobs.run". * * This request holds the parameters needed by the cloudscheduler server. After setting any * optional parameters, call the {@link Run#execute()} method to invoke the remote operation. * * @param name Required. The job name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. * @param content the {@link com.google.api.services.cloudscheduler.v1.model.RunJobRequest} * @return the request */ public Run run(java.lang.String name, com.google.api.services.cloudscheduler.v1.model.RunJobRequest content) throws java.io.IOException { Run result = new Run(name, content); initialize(result); return result; } public class Run extends CloudSchedulerRequest<com.google.api.services.cloudscheduler.v1.model.Job> { private static final String REST_PATH = "v1/{+name}:run"; private final java.util.regex.Pattern NAME_PATTERN = java.util.regex.Pattern.compile("^projects/[^/]+/locations/[^/]+/jobs/[^/]+$"); /** * Forces a job to run now. When this method is called, Cloud Scheduler will dispatch the job, * even if the job is already running. * * Create a request for the method "jobs.run". * * This request holds the parameters needed by the the cloudscheduler server. After setting any * optional parameters, call the {@link Run#execute()} method to invoke the remote operation. <p> * {@link Run#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} * must be called to initialize this instance immediately after invoking the constructor. </p> * * @param name Required. The job name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. * @param content the {@link com.google.api.services.cloudscheduler.v1.model.RunJobRequest} * @since 1.13 */ protected Run(java.lang.String name, com.google.api.services.cloudscheduler.v1.model.RunJobRequest content) { super(CloudScheduler.this, "POST", REST_PATH, content, com.google.api.services.cloudscheduler.v1.model.Job.class); this.name = com.google.api.client.util.Preconditions.checkNotNull(name, "Required parameter name must be specified."); if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(), "Parameter name must conform to the pattern " + "^projects/[^/]+/locations/[^/]+/jobs/[^/]+$"); } } @Override public Run set$Xgafv(java.lang.String $Xgafv) { return (Run) super.set$Xgafv($Xgafv); } @Override public Run setAccessToken(java.lang.String accessToken) { return (Run) super.setAccessToken(accessToken); } @Override public Run setAlt(java.lang.String alt) { return (Run) super.setAlt(alt); } @Override public Run setCallback(java.lang.String callback) { return (Run) super.setCallback(callback); } @Override public Run setFields(java.lang.String fields) { return (Run) super.setFields(fields); } @Override public Run setKey(java.lang.String key) { return (Run) super.setKey(key); } @Override public Run setOauthToken(java.lang.String oauthToken) { return (Run) super.setOauthToken(oauthToken); } @Override public Run setPrettyPrint(java.lang.Boolean prettyPrint) { return (Run) super.setPrettyPrint(prettyPrint); } @Override public Run setQuotaUser(java.lang.String quotaUser) { return (Run) super.setQuotaUser(quotaUser); } @Override public Run setUploadType(java.lang.String uploadType) { return (Run) super.setUploadType(uploadType); } @Override public Run setUploadProtocol(java.lang.String uploadProtocol) { return (Run) super.setUploadProtocol(uploadProtocol); } /** * Required. The job name. For example: * `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. */ @com.google.api.client.util.Key private java.lang.String name; /** Required. The job name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. */ public java.lang.String getName() { return name; } /** * Required. The job name. For example: * `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. */ public Run setName(java.lang.String name) { if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(), "Parameter name must conform to the pattern " + "^projects/[^/]+/locations/[^/]+/jobs/[^/]+$"); } this.name = name; return this; } @Override public Run set(String parameterName, Object value) { return (Run) super.set(parameterName, value); } } } } }
Java
public class Locations { /** * Gets information about a location. * * Create a request for the method "locations.get". * * This request holds the parameters needed by the cloudscheduler server. After setting any * optional parameters, call the {@link Get#execute()} method to invoke the remote operation. * * @param name Resource name for the location. * @return the request */ public Get get(java.lang.String name) throws java.io.IOException { Get result = new Get(name); initialize(result); return result; } public class Get extends CloudSchedulerRequest<com.google.api.services.cloudscheduler.v1.model.Location> { private static final String REST_PATH = "v1/{+name}"; private final java.util.regex.Pattern NAME_PATTERN = java.util.regex.Pattern.compile("^projects/[^/]+/locations/[^/]+$"); /** * Gets information about a location. * * Create a request for the method "locations.get". * * This request holds the parameters needed by the the cloudscheduler server. After setting any * optional parameters, call the {@link Get#execute()} method to invoke the remote operation. <p> * {@link Get#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} * must be called to initialize this instance immediately after invoking the constructor. </p> * * @param name Resource name for the location. * @since 1.13 */ protected Get(java.lang.String name) { super(CloudScheduler.this, "GET", REST_PATH, null, com.google.api.services.cloudscheduler.v1.model.Location.class); this.name = com.google.api.client.util.Preconditions.checkNotNull(name, "Required parameter name must be specified."); if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(), "Parameter name must conform to the pattern " + "^projects/[^/]+/locations/[^/]+$"); } } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public Get set$Xgafv(java.lang.String $Xgafv) { return (Get) super.set$Xgafv($Xgafv); } @Override public Get setAccessToken(java.lang.String accessToken) { return (Get) super.setAccessToken(accessToken); } @Override public Get setAlt(java.lang.String alt) { return (Get) super.setAlt(alt); } @Override public Get setCallback(java.lang.String callback) { return (Get) super.setCallback(callback); } @Override public Get setFields(java.lang.String fields) { return (Get) super.setFields(fields); } @Override public Get setKey(java.lang.String key) { return (Get) super.setKey(key); } @Override public Get setOauthToken(java.lang.String oauthToken) { return (Get) super.setOauthToken(oauthToken); } @Override public Get setPrettyPrint(java.lang.Boolean prettyPrint) { return (Get) super.setPrettyPrint(prettyPrint); } @Override public Get setQuotaUser(java.lang.String quotaUser) { return (Get) super.setQuotaUser(quotaUser); } @Override public Get setUploadType(java.lang.String uploadType) { return (Get) super.setUploadType(uploadType); } @Override public Get setUploadProtocol(java.lang.String uploadProtocol) { return (Get) super.setUploadProtocol(uploadProtocol); } /** Resource name for the location. */ @com.google.api.client.util.Key private java.lang.String name; /** Resource name for the location. */ public java.lang.String getName() { return name; } /** Resource name for the location. */ public Get setName(java.lang.String name) { if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(), "Parameter name must conform to the pattern " + "^projects/[^/]+/locations/[^/]+$"); } this.name = name; return this; } @Override public Get set(String parameterName, Object value) { return (Get) super.set(parameterName, value); } } /** * Lists information about the supported locations for this service. * * Create a request for the method "locations.list". * * This request holds the parameters needed by the cloudscheduler server. After setting any * optional parameters, call the {@link List#execute()} method to invoke the remote operation. * * @param name The resource that owns the locations collection, if applicable. * @return the request */ public List list(java.lang.String name) throws java.io.IOException { List result = new List(name); initialize(result); return result; } public class List extends CloudSchedulerRequest<com.google.api.services.cloudscheduler.v1.model.ListLocationsResponse> { private static final String REST_PATH = "v1/{+name}/locations"; private final java.util.regex.Pattern NAME_PATTERN = java.util.regex.Pattern.compile("^projects/[^/]+$"); /** * Lists information about the supported locations for this service. * * Create a request for the method "locations.list". * * This request holds the parameters needed by the the cloudscheduler server. After setting any * optional parameters, call the {@link List#execute()} method to invoke the remote operation. <p> * {@link List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} * must be called to initialize this instance immediately after invoking the constructor. </p> * * @param name The resource that owns the locations collection, if applicable. * @since 1.13 */ protected List(java.lang.String name) { super(CloudScheduler.this, "GET", REST_PATH, null, com.google.api.services.cloudscheduler.v1.model.ListLocationsResponse.class); this.name = com.google.api.client.util.Preconditions.checkNotNull(name, "Required parameter name must be specified."); if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(), "Parameter name must conform to the pattern " + "^projects/[^/]+$"); } } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public List set$Xgafv(java.lang.String $Xgafv) { return (List) super.set$Xgafv($Xgafv); } @Override public List setAccessToken(java.lang.String accessToken) { return (List) super.setAccessToken(accessToken); } @Override public List setAlt(java.lang.String alt) { return (List) super.setAlt(alt); } @Override public List setCallback(java.lang.String callback) { return (List) super.setCallback(callback); } @Override public List setFields(java.lang.String fields) { return (List) super.setFields(fields); } @Override public List setKey(java.lang.String key) { return (List) super.setKey(key); } @Override public List setOauthToken(java.lang.String oauthToken) { return (List) super.setOauthToken(oauthToken); } @Override public List setPrettyPrint(java.lang.Boolean prettyPrint) { return (List) super.setPrettyPrint(prettyPrint); } @Override public List setQuotaUser(java.lang.String quotaUser) { return (List) super.setQuotaUser(quotaUser); } @Override public List setUploadType(java.lang.String uploadType) { return (List) super.setUploadType(uploadType); } @Override public List setUploadProtocol(java.lang.String uploadProtocol) { return (List) super.setUploadProtocol(uploadProtocol); } /** The resource that owns the locations collection, if applicable. */ @com.google.api.client.util.Key private java.lang.String name; /** The resource that owns the locations collection, if applicable. */ public java.lang.String getName() { return name; } /** The resource that owns the locations collection, if applicable. */ public List setName(java.lang.String name) { if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(), "Parameter name must conform to the pattern " + "^projects/[^/]+$"); } this.name = name; return this; } /** The standard list filter. */ @com.google.api.client.util.Key private java.lang.String filter; /** The standard list filter. */ public java.lang.String getFilter() { return filter; } /** The standard list filter. */ public List setFilter(java.lang.String filter) { this.filter = filter; return this; } /** The standard list page size. */ @com.google.api.client.util.Key private java.lang.Integer pageSize; /** The standard list page size. */ public java.lang.Integer getPageSize() { return pageSize; } /** The standard list page size. */ public List setPageSize(java.lang.Integer pageSize) { this.pageSize = pageSize; return this; } /** The standard list page token. */ @com.google.api.client.util.Key private java.lang.String pageToken; /** The standard list page token. */ public java.lang.String getPageToken() { return pageToken; } /** The standard list page token. */ public List setPageToken(java.lang.String pageToken) { this.pageToken = pageToken; return this; } @Override public List set(String parameterName, Object value) { return (List) super.set(parameterName, value); } } /** * An accessor for creating requests from the Jobs collection. * * <p>The typical use is:</p> * <pre> * {@code CloudScheduler cloudscheduler = new CloudScheduler(...);} * {@code CloudScheduler.Jobs.List request = cloudscheduler.jobs().list(parameters ...)} * </pre> * * @return the resource collection */ public Jobs jobs() { return new Jobs(); } /** * The "jobs" collection of methods. */ public class Jobs { /** * Creates a job. * * Create a request for the method "jobs.create". * * This request holds the parameters needed by the cloudscheduler server. After setting any * optional parameters, call the {@link Create#execute()} method to invoke the remote operation. * * @param parent Required. The location name. For example: `projects/PROJECT_ID/locations/LOCATION_ID`. * @param content the {@link com.google.api.services.cloudscheduler.v1.model.Job} * @return the request */ public Create create(java.lang.String parent, com.google.api.services.cloudscheduler.v1.model.Job content) throws java.io.IOException { Create result = new Create(parent, content); initialize(result); return result; } public class Create extends CloudSchedulerRequest<com.google.api.services.cloudscheduler.v1.model.Job> { private static final String REST_PATH = "v1/{+parent}/jobs"; private final java.util.regex.Pattern PARENT_PATTERN = java.util.regex.Pattern.compile("^projects/[^/]+/locations/[^/]+$"); /** * Creates a job. * * Create a request for the method "jobs.create". * * This request holds the parameters needed by the the cloudscheduler server. After setting any * optional parameters, call the {@link Create#execute()} method to invoke the remote operation. * <p> {@link * Create#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param parent Required. The location name. For example: `projects/PROJECT_ID/locations/LOCATION_ID`. * @param content the {@link com.google.api.services.cloudscheduler.v1.model.Job} * @since 1.13 */ protected Create(java.lang.String parent, com.google.api.services.cloudscheduler.v1.model.Job content) { super(CloudScheduler.this, "POST", REST_PATH, content, com.google.api.services.cloudscheduler.v1.model.Job.class); this.parent = com.google.api.client.util.Preconditions.checkNotNull(parent, "Required parameter parent must be specified."); if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(PARENT_PATTERN.matcher(parent).matches(), "Parameter parent must conform to the pattern " + "^projects/[^/]+/locations/[^/]+$"); } } @Override public Create set$Xgafv(java.lang.String $Xgafv) { return (Create) super.set$Xgafv($Xgafv); } @Override public Create setAccessToken(java.lang.String accessToken) { return (Create) super.setAccessToken(accessToken); } @Override public Create setAlt(java.lang.String alt) { return (Create) super.setAlt(alt); } @Override public Create setCallback(java.lang.String callback) { return (Create) super.setCallback(callback); } @Override public Create setFields(java.lang.String fields) { return (Create) super.setFields(fields); } @Override public Create setKey(java.lang.String key) { return (Create) super.setKey(key); } @Override public Create setOauthToken(java.lang.String oauthToken) { return (Create) super.setOauthToken(oauthToken); } @Override public Create setPrettyPrint(java.lang.Boolean prettyPrint) { return (Create) super.setPrettyPrint(prettyPrint); } @Override public Create setQuotaUser(java.lang.String quotaUser) { return (Create) super.setQuotaUser(quotaUser); } @Override public Create setUploadType(java.lang.String uploadType) { return (Create) super.setUploadType(uploadType); } @Override public Create setUploadProtocol(java.lang.String uploadProtocol) { return (Create) super.setUploadProtocol(uploadProtocol); } /** * Required. The location name. For example: `projects/PROJECT_ID/locations/LOCATION_ID`. */ @com.google.api.client.util.Key private java.lang.String parent; /** Required. The location name. For example: `projects/PROJECT_ID/locations/LOCATION_ID`. */ public java.lang.String getParent() { return parent; } /** * Required. The location name. For example: `projects/PROJECT_ID/locations/LOCATION_ID`. */ public Create setParent(java.lang.String parent) { if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(PARENT_PATTERN.matcher(parent).matches(), "Parameter parent must conform to the pattern " + "^projects/[^/]+/locations/[^/]+$"); } this.parent = parent; return this; } @Override public Create set(String parameterName, Object value) { return (Create) super.set(parameterName, value); } } /** * Deletes a job. * * Create a request for the method "jobs.delete". * * This request holds the parameters needed by the cloudscheduler server. After setting any * optional parameters, call the {@link Delete#execute()} method to invoke the remote operation. * * @param name Required. The job name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. * @return the request */ public Delete delete(java.lang.String name) throws java.io.IOException { Delete result = new Delete(name); initialize(result); return result; } public class Delete extends CloudSchedulerRequest<com.google.api.services.cloudscheduler.v1.model.Empty> { private static final String REST_PATH = "v1/{+name}"; private final java.util.regex.Pattern NAME_PATTERN = java.util.regex.Pattern.compile("^projects/[^/]+/locations/[^/]+/jobs/[^/]+$"); /** * Deletes a job. * * Create a request for the method "jobs.delete". * * This request holds the parameters needed by the the cloudscheduler server. After setting any * optional parameters, call the {@link Delete#execute()} method to invoke the remote operation. * <p> {@link * Delete#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param name Required. The job name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. * @since 1.13 */ protected Delete(java.lang.String name) { super(CloudScheduler.this, "DELETE", REST_PATH, null, com.google.api.services.cloudscheduler.v1.model.Empty.class); this.name = com.google.api.client.util.Preconditions.checkNotNull(name, "Required parameter name must be specified."); if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(), "Parameter name must conform to the pattern " + "^projects/[^/]+/locations/[^/]+/jobs/[^/]+$"); } } @Override public Delete set$Xgafv(java.lang.String $Xgafv) { return (Delete) super.set$Xgafv($Xgafv); } @Override public Delete setAccessToken(java.lang.String accessToken) { return (Delete) super.setAccessToken(accessToken); } @Override public Delete setAlt(java.lang.String alt) { return (Delete) super.setAlt(alt); } @Override public Delete setCallback(java.lang.String callback) { return (Delete) super.setCallback(callback); } @Override public Delete setFields(java.lang.String fields) { return (Delete) super.setFields(fields); } @Override public Delete setKey(java.lang.String key) { return (Delete) super.setKey(key); } @Override public Delete setOauthToken(java.lang.String oauthToken) { return (Delete) super.setOauthToken(oauthToken); } @Override public Delete setPrettyPrint(java.lang.Boolean prettyPrint) { return (Delete) super.setPrettyPrint(prettyPrint); } @Override public Delete setQuotaUser(java.lang.String quotaUser) { return (Delete) super.setQuotaUser(quotaUser); } @Override public Delete setUploadType(java.lang.String uploadType) { return (Delete) super.setUploadType(uploadType); } @Override public Delete setUploadProtocol(java.lang.String uploadProtocol) { return (Delete) super.setUploadProtocol(uploadProtocol); } /** * Required. The job name. For example: * `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. */ @com.google.api.client.util.Key private java.lang.String name; /** Required. The job name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. */ public java.lang.String getName() { return name; } /** * Required. The job name. For example: * `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. */ public Delete setName(java.lang.String name) { if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(), "Parameter name must conform to the pattern " + "^projects/[^/]+/locations/[^/]+/jobs/[^/]+$"); } this.name = name; return this; } @Override public Delete set(String parameterName, Object value) { return (Delete) super.set(parameterName, value); } } /** * Gets a job. * * Create a request for the method "jobs.get". * * This request holds the parameters needed by the cloudscheduler server. After setting any * optional parameters, call the {@link Get#execute()} method to invoke the remote operation. * * @param name Required. The job name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. * @return the request */ public Get get(java.lang.String name) throws java.io.IOException { Get result = new Get(name); initialize(result); return result; } public class Get extends CloudSchedulerRequest<com.google.api.services.cloudscheduler.v1.model.Job> { private static final String REST_PATH = "v1/{+name}"; private final java.util.regex.Pattern NAME_PATTERN = java.util.regex.Pattern.compile("^projects/[^/]+/locations/[^/]+/jobs/[^/]+$"); /** * Gets a job. * * Create a request for the method "jobs.get". * * This request holds the parameters needed by the the cloudscheduler server. After setting any * optional parameters, call the {@link Get#execute()} method to invoke the remote operation. <p> * {@link Get#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} * must be called to initialize this instance immediately after invoking the constructor. </p> * * @param name Required. The job name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. * @since 1.13 */ protected Get(java.lang.String name) { super(CloudScheduler.this, "GET", REST_PATH, null, com.google.api.services.cloudscheduler.v1.model.Job.class); this.name = com.google.api.client.util.Preconditions.checkNotNull(name, "Required parameter name must be specified."); if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(), "Parameter name must conform to the pattern " + "^projects/[^/]+/locations/[^/]+/jobs/[^/]+$"); } } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public Get set$Xgafv(java.lang.String $Xgafv) { return (Get) super.set$Xgafv($Xgafv); } @Override public Get setAccessToken(java.lang.String accessToken) { return (Get) super.setAccessToken(accessToken); } @Override public Get setAlt(java.lang.String alt) { return (Get) super.setAlt(alt); } @Override public Get setCallback(java.lang.String callback) { return (Get) super.setCallback(callback); } @Override public Get setFields(java.lang.String fields) { return (Get) super.setFields(fields); } @Override public Get setKey(java.lang.String key) { return (Get) super.setKey(key); } @Override public Get setOauthToken(java.lang.String oauthToken) { return (Get) super.setOauthToken(oauthToken); } @Override public Get setPrettyPrint(java.lang.Boolean prettyPrint) { return (Get) super.setPrettyPrint(prettyPrint); } @Override public Get setQuotaUser(java.lang.String quotaUser) { return (Get) super.setQuotaUser(quotaUser); } @Override public Get setUploadType(java.lang.String uploadType) { return (Get) super.setUploadType(uploadType); } @Override public Get setUploadProtocol(java.lang.String uploadProtocol) { return (Get) super.setUploadProtocol(uploadProtocol); } /** * Required. The job name. For example: * `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. */ @com.google.api.client.util.Key private java.lang.String name; /** Required. The job name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. */ public java.lang.String getName() { return name; } /** * Required. The job name. For example: * `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. */ public Get setName(java.lang.String name) { if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(), "Parameter name must conform to the pattern " + "^projects/[^/]+/locations/[^/]+/jobs/[^/]+$"); } this.name = name; return this; } @Override public Get set(String parameterName, Object value) { return (Get) super.set(parameterName, value); } } /** * Lists jobs. * * Create a request for the method "jobs.list". * * This request holds the parameters needed by the cloudscheduler server. After setting any * optional parameters, call the {@link List#execute()} method to invoke the remote operation. * * @param parent Required. The location name. For example: `projects/PROJECT_ID/locations/LOCATION_ID`. * @return the request */ public List list(java.lang.String parent) throws java.io.IOException { List result = new List(parent); initialize(result); return result; } public class List extends CloudSchedulerRequest<com.google.api.services.cloudscheduler.v1.model.ListJobsResponse> { private static final String REST_PATH = "v1/{+parent}/jobs"; private final java.util.regex.Pattern PARENT_PATTERN = java.util.regex.Pattern.compile("^projects/[^/]+/locations/[^/]+$"); /** * Lists jobs. * * Create a request for the method "jobs.list". * * This request holds the parameters needed by the the cloudscheduler server. After setting any * optional parameters, call the {@link List#execute()} method to invoke the remote operation. <p> * {@link List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} * must be called to initialize this instance immediately after invoking the constructor. </p> * * @param parent Required. The location name. For example: `projects/PROJECT_ID/locations/LOCATION_ID`. * @since 1.13 */ protected List(java.lang.String parent) { super(CloudScheduler.this, "GET", REST_PATH, null, com.google.api.services.cloudscheduler.v1.model.ListJobsResponse.class); this.parent = com.google.api.client.util.Preconditions.checkNotNull(parent, "Required parameter parent must be specified."); if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(PARENT_PATTERN.matcher(parent).matches(), "Parameter parent must conform to the pattern " + "^projects/[^/]+/locations/[^/]+$"); } } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public List set$Xgafv(java.lang.String $Xgafv) { return (List) super.set$Xgafv($Xgafv); } @Override public List setAccessToken(java.lang.String accessToken) { return (List) super.setAccessToken(accessToken); } @Override public List setAlt(java.lang.String alt) { return (List) super.setAlt(alt); } @Override public List setCallback(java.lang.String callback) { return (List) super.setCallback(callback); } @Override public List setFields(java.lang.String fields) { return (List) super.setFields(fields); } @Override public List setKey(java.lang.String key) { return (List) super.setKey(key); } @Override public List setOauthToken(java.lang.String oauthToken) { return (List) super.setOauthToken(oauthToken); } @Override public List setPrettyPrint(java.lang.Boolean prettyPrint) { return (List) super.setPrettyPrint(prettyPrint); } @Override public List setQuotaUser(java.lang.String quotaUser) { return (List) super.setQuotaUser(quotaUser); } @Override public List setUploadType(java.lang.String uploadType) { return (List) super.setUploadType(uploadType); } @Override public List setUploadProtocol(java.lang.String uploadProtocol) { return (List) super.setUploadProtocol(uploadProtocol); } /** * Required. The location name. For example: `projects/PROJECT_ID/locations/LOCATION_ID`. */ @com.google.api.client.util.Key private java.lang.String parent; /** Required. The location name. For example: `projects/PROJECT_ID/locations/LOCATION_ID`. */ public java.lang.String getParent() { return parent; } /** * Required. The location name. For example: `projects/PROJECT_ID/locations/LOCATION_ID`. */ public List setParent(java.lang.String parent) { if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(PARENT_PATTERN.matcher(parent).matches(), "Parameter parent must conform to the pattern " + "^projects/[^/]+/locations/[^/]+$"); } this.parent = parent; return this; } /** * Requested page size. The maximum page size is 500. If unspecified, the page size will * be the maximum. Fewer jobs than requested might be returned, even if more jobs exist; * use next_page_token to determine if more jobs exist. */ @com.google.api.client.util.Key private java.lang.Integer pageSize; /** Requested page size. The maximum page size is 500. If unspecified, the page size will be the maximum. Fewer jobs than requested might be returned, even if more jobs exist; use next_page_token to determine if more jobs exist. */ public java.lang.Integer getPageSize() { return pageSize; } /** * Requested page size. The maximum page size is 500. If unspecified, the page size will * be the maximum. Fewer jobs than requested might be returned, even if more jobs exist; * use next_page_token to determine if more jobs exist. */ public List setPageSize(java.lang.Integer pageSize) { this.pageSize = pageSize; return this; } /** * A token identifying a page of results the server will return. To request the first page * results, page_token must be empty. To request the next page of results, page_token must * be the value of next_page_token returned from the previous call to ListJobs. It is an * error to switch the value of filter or order_by while iterating through pages. */ @com.google.api.client.util.Key private java.lang.String pageToken; /** A token identifying a page of results the server will return. To request the first page results, page_token must be empty. To request the next page of results, page_token must be the value of next_page_token returned from the previous call to ListJobs. It is an error to switch the value of filter or order_by while iterating through pages. */ public java.lang.String getPageToken() { return pageToken; } /** * A token identifying a page of results the server will return. To request the first page * results, page_token must be empty. To request the next page of results, page_token must * be the value of next_page_token returned from the previous call to ListJobs. It is an * error to switch the value of filter or order_by while iterating through pages. */ public List setPageToken(java.lang.String pageToken) { this.pageToken = pageToken; return this; } @Override public List set(String parameterName, Object value) { return (List) super.set(parameterName, value); } } /** * Updates a job. If successful, the updated Job is returned. If the job does not exist, `NOT_FOUND` * is returned. If UpdateJob does not successfully return, it is possible for the job to be in an * Job.State.UPDATE_FAILED state. A job in this state may not be executed. If this happens, retry * the UpdateJob request until a successful response is received. * * Create a request for the method "jobs.patch". * * This request holds the parameters needed by the cloudscheduler server. After setting any * optional parameters, call the {@link Patch#execute()} method to invoke the remote operation. * * @param name Optionally caller-specified in CreateJob, after which it becomes output only. The job name. For * example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. * `PROJECT_ID` can * contain letters ([A-Za-z]), numbers ([0-9]), hyphens (-), colons (:), or periods (.). For * more information, see [Identifying projects](https://cloud.google.com/resource- * manager/docs/creating-managing-projects#identifying_projects) * `LOCATION_ID` is the * canonical ID for the job's location. The list of available locations can be obtained by * calling ListLocations. For more information, see * https://cloud.google.com/about/locations/. * `JOB_ID` can contain only letters ([A-Za-z]), * numbers ([0-9]), hyphens (-), or underscores (_). The maximum length is 500 characters. * @param content the {@link com.google.api.services.cloudscheduler.v1.model.Job} * @return the request */ public Patch patch(java.lang.String name, com.google.api.services.cloudscheduler.v1.model.Job content) throws java.io.IOException { Patch result = new Patch(name, content); initialize(result); return result; } public class Patch extends CloudSchedulerRequest<com.google.api.services.cloudscheduler.v1.model.Job> { private static final String REST_PATH = "v1/{+name}"; private final java.util.regex.Pattern NAME_PATTERN = java.util.regex.Pattern.compile("^projects/[^/]+/locations/[^/]+/jobs/[^/]+$"); /** * Updates a job. If successful, the updated Job is returned. If the job does not exist, * `NOT_FOUND` is returned. If UpdateJob does not successfully return, it is possible for the job * to be in an Job.State.UPDATE_FAILED state. A job in this state may not be executed. If this * happens, retry the UpdateJob request until a successful response is received. * * Create a request for the method "jobs.patch". * * This request holds the parameters needed by the the cloudscheduler server. After setting any * optional parameters, call the {@link Patch#execute()} method to invoke the remote operation. * <p> {@link * Patch#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param name Optionally caller-specified in CreateJob, after which it becomes output only. The job name. For * example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. * `PROJECT_ID` can * contain letters ([A-Za-z]), numbers ([0-9]), hyphens (-), colons (:), or periods (.). For * more information, see [Identifying projects](https://cloud.google.com/resource- * manager/docs/creating-managing-projects#identifying_projects) * `LOCATION_ID` is the * canonical ID for the job's location. The list of available locations can be obtained by * calling ListLocations. For more information, see * https://cloud.google.com/about/locations/. * `JOB_ID` can contain only letters ([A-Za-z]), * numbers ([0-9]), hyphens (-), or underscores (_). The maximum length is 500 characters. * @param content the {@link com.google.api.services.cloudscheduler.v1.model.Job} * @since 1.13 */ protected Patch(java.lang.String name, com.google.api.services.cloudscheduler.v1.model.Job content) { super(CloudScheduler.this, "PATCH", REST_PATH, content, com.google.api.services.cloudscheduler.v1.model.Job.class); this.name = com.google.api.client.util.Preconditions.checkNotNull(name, "Required parameter name must be specified."); if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(), "Parameter name must conform to the pattern " + "^projects/[^/]+/locations/[^/]+/jobs/[^/]+$"); } } @Override public Patch set$Xgafv(java.lang.String $Xgafv) { return (Patch) super.set$Xgafv($Xgafv); } @Override public Patch setAccessToken(java.lang.String accessToken) { return (Patch) super.setAccessToken(accessToken); } @Override public Patch setAlt(java.lang.String alt) { return (Patch) super.setAlt(alt); } @Override public Patch setCallback(java.lang.String callback) { return (Patch) super.setCallback(callback); } @Override public Patch setFields(java.lang.String fields) { return (Patch) super.setFields(fields); } @Override public Patch setKey(java.lang.String key) { return (Patch) super.setKey(key); } @Override public Patch setOauthToken(java.lang.String oauthToken) { return (Patch) super.setOauthToken(oauthToken); } @Override public Patch setPrettyPrint(java.lang.Boolean prettyPrint) { return (Patch) super.setPrettyPrint(prettyPrint); } @Override public Patch setQuotaUser(java.lang.String quotaUser) { return (Patch) super.setQuotaUser(quotaUser); } @Override public Patch setUploadType(java.lang.String uploadType) { return (Patch) super.setUploadType(uploadType); } @Override public Patch setUploadProtocol(java.lang.String uploadProtocol) { return (Patch) super.setUploadProtocol(uploadProtocol); } /** * Optionally caller-specified in CreateJob, after which it becomes output only. The job * name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. * * `PROJECT_ID` can contain letters ([A-Za-z]), numbers ([0-9]), hyphens (-), colons (:), * or periods (.). For more information, see [Identifying * projects](https://cloud.google.com/resource-manager/docs/creating-managing- * projects#identifying_projects) * `LOCATION_ID` is the canonical ID for the job's * location. The list of available locations can be obtained by calling ListLocations. For * more information, see https://cloud.google.com/about/locations/. * `JOB_ID` can contain * only letters ([A-Za-z]), numbers ([0-9]), hyphens (-), or underscores (_). The maximum * length is 500 characters. */ @com.google.api.client.util.Key private java.lang.String name; /** Optionally caller-specified in CreateJob, after which it becomes output only. The job name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. * `PROJECT_ID` can contain letters ([A-Za-z]), numbers ([0-9]), hyphens (-), colons (:), or periods (.). For more information, see [Identifying projects](https://cloud.google.com/resource-manager/docs/creating-managing- projects#identifying_projects) * `LOCATION_ID` is the canonical ID for the job's location. The list of available locations can be obtained by calling ListLocations. For more information, see https://cloud.google.com/about/locations/. * `JOB_ID` can contain only letters ([A-Za-z]), numbers ([0-9]), hyphens (-), or underscores (_). The maximum length is 500 characters. */ public java.lang.String getName() { return name; } /** * Optionally caller-specified in CreateJob, after which it becomes output only. The job * name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. * * `PROJECT_ID` can contain letters ([A-Za-z]), numbers ([0-9]), hyphens (-), colons (:), * or periods (.). For more information, see [Identifying * projects](https://cloud.google.com/resource-manager/docs/creating-managing- * projects#identifying_projects) * `LOCATION_ID` is the canonical ID for the job's * location. The list of available locations can be obtained by calling ListLocations. For * more information, see https://cloud.google.com/about/locations/. * `JOB_ID` can contain * only letters ([A-Za-z]), numbers ([0-9]), hyphens (-), or underscores (_). The maximum * length is 500 characters. */ public Patch setName(java.lang.String name) { if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(), "Parameter name must conform to the pattern " + "^projects/[^/]+/locations/[^/]+/jobs/[^/]+$"); } this.name = name; return this; } /** A mask used to specify which fields of the job are being updated. */ @com.google.api.client.util.Key private String updateMask; /** A mask used to specify which fields of the job are being updated. */ public String getUpdateMask() { return updateMask; } /** A mask used to specify which fields of the job are being updated. */ public Patch setUpdateMask(String updateMask) { this.updateMask = updateMask; return this; } @Override public Patch set(String parameterName, Object value) { return (Patch) super.set(parameterName, value); } } /** * Pauses a job. If a job is paused then the system will stop executing the job until it is re- * enabled via ResumeJob. The state of the job is stored in state; if paused it will be set to * Job.State.PAUSED. A job must be in Job.State.ENABLED to be paused. * * Create a request for the method "jobs.pause". * * This request holds the parameters needed by the cloudscheduler server. After setting any * optional parameters, call the {@link Pause#execute()} method to invoke the remote operation. * * @param name Required. The job name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. * @param content the {@link com.google.api.services.cloudscheduler.v1.model.PauseJobRequest} * @return the request */ public Pause pause(java.lang.String name, com.google.api.services.cloudscheduler.v1.model.PauseJobRequest content) throws java.io.IOException { Pause result = new Pause(name, content); initialize(result); return result; } public class Pause extends CloudSchedulerRequest<com.google.api.services.cloudscheduler.v1.model.Job> { private static final String REST_PATH = "v1/{+name}:pause"; private final java.util.regex.Pattern NAME_PATTERN = java.util.regex.Pattern.compile("^projects/[^/]+/locations/[^/]+/jobs/[^/]+$"); /** * Pauses a job. If a job is paused then the system will stop executing the job until it is re- * enabled via ResumeJob. The state of the job is stored in state; if paused it will be set to * Job.State.PAUSED. A job must be in Job.State.ENABLED to be paused. * * Create a request for the method "jobs.pause". * * This request holds the parameters needed by the the cloudscheduler server. After setting any * optional parameters, call the {@link Pause#execute()} method to invoke the remote operation. * <p> {@link * Pause#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param name Required. The job name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. * @param content the {@link com.google.api.services.cloudscheduler.v1.model.PauseJobRequest} * @since 1.13 */ protected Pause(java.lang.String name, com.google.api.services.cloudscheduler.v1.model.PauseJobRequest content) { super(CloudScheduler.this, "POST", REST_PATH, content, com.google.api.services.cloudscheduler.v1.model.Job.class); this.name = com.google.api.client.util.Preconditions.checkNotNull(name, "Required parameter name must be specified."); if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(), "Parameter name must conform to the pattern " + "^projects/[^/]+/locations/[^/]+/jobs/[^/]+$"); } } @Override public Pause set$Xgafv(java.lang.String $Xgafv) { return (Pause) super.set$Xgafv($Xgafv); } @Override public Pause setAccessToken(java.lang.String accessToken) { return (Pause) super.setAccessToken(accessToken); } @Override public Pause setAlt(java.lang.String alt) { return (Pause) super.setAlt(alt); } @Override public Pause setCallback(java.lang.String callback) { return (Pause) super.setCallback(callback); } @Override public Pause setFields(java.lang.String fields) { return (Pause) super.setFields(fields); } @Override public Pause setKey(java.lang.String key) { return (Pause) super.setKey(key); } @Override public Pause setOauthToken(java.lang.String oauthToken) { return (Pause) super.setOauthToken(oauthToken); } @Override public Pause setPrettyPrint(java.lang.Boolean prettyPrint) { return (Pause) super.setPrettyPrint(prettyPrint); } @Override public Pause setQuotaUser(java.lang.String quotaUser) { return (Pause) super.setQuotaUser(quotaUser); } @Override public Pause setUploadType(java.lang.String uploadType) { return (Pause) super.setUploadType(uploadType); } @Override public Pause setUploadProtocol(java.lang.String uploadProtocol) { return (Pause) super.setUploadProtocol(uploadProtocol); } /** * Required. The job name. For example: * `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. */ @com.google.api.client.util.Key private java.lang.String name; /** Required. The job name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. */ public java.lang.String getName() { return name; } /** * Required. The job name. For example: * `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. */ public Pause setName(java.lang.String name) { if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(), "Parameter name must conform to the pattern " + "^projects/[^/]+/locations/[^/]+/jobs/[^/]+$"); } this.name = name; return this; } @Override public Pause set(String parameterName, Object value) { return (Pause) super.set(parameterName, value); } } /** * Resume a job. This method reenables a job after it has been Job.State.PAUSED. The state of a job * is stored in Job.state; after calling this method it will be set to Job.State.ENABLED. A job must * be in Job.State.PAUSED to be resumed. * * Create a request for the method "jobs.resume". * * This request holds the parameters needed by the cloudscheduler server. After setting any * optional parameters, call the {@link Resume#execute()} method to invoke the remote operation. * * @param name Required. The job name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. * @param content the {@link com.google.api.services.cloudscheduler.v1.model.ResumeJobRequest} * @return the request */ public Resume resume(java.lang.String name, com.google.api.services.cloudscheduler.v1.model.ResumeJobRequest content) throws java.io.IOException { Resume result = new Resume(name, content); initialize(result); return result; } public class Resume extends CloudSchedulerRequest<com.google.api.services.cloudscheduler.v1.model.Job> { private static final String REST_PATH = "v1/{+name}:resume"; private final java.util.regex.Pattern NAME_PATTERN = java.util.regex.Pattern.compile("^projects/[^/]+/locations/[^/]+/jobs/[^/]+$"); /** * Resume a job. This method reenables a job after it has been Job.State.PAUSED. The state of a * job is stored in Job.state; after calling this method it will be set to Job.State.ENABLED. A * job must be in Job.State.PAUSED to be resumed. * * Create a request for the method "jobs.resume". * * This request holds the parameters needed by the the cloudscheduler server. After setting any * optional parameters, call the {@link Resume#execute()} method to invoke the remote operation. * <p> {@link * Resume#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param name Required. The job name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. * @param content the {@link com.google.api.services.cloudscheduler.v1.model.ResumeJobRequest} * @since 1.13 */ protected Resume(java.lang.String name, com.google.api.services.cloudscheduler.v1.model.ResumeJobRequest content) { super(CloudScheduler.this, "POST", REST_PATH, content, com.google.api.services.cloudscheduler.v1.model.Job.class); this.name = com.google.api.client.util.Preconditions.checkNotNull(name, "Required parameter name must be specified."); if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(), "Parameter name must conform to the pattern " + "^projects/[^/]+/locations/[^/]+/jobs/[^/]+$"); } } @Override public Resume set$Xgafv(java.lang.String $Xgafv) { return (Resume) super.set$Xgafv($Xgafv); } @Override public Resume setAccessToken(java.lang.String accessToken) { return (Resume) super.setAccessToken(accessToken); } @Override public Resume setAlt(java.lang.String alt) { return (Resume) super.setAlt(alt); } @Override public Resume setCallback(java.lang.String callback) { return (Resume) super.setCallback(callback); } @Override public Resume setFields(java.lang.String fields) { return (Resume) super.setFields(fields); } @Override public Resume setKey(java.lang.String key) { return (Resume) super.setKey(key); } @Override public Resume setOauthToken(java.lang.String oauthToken) { return (Resume) super.setOauthToken(oauthToken); } @Override public Resume setPrettyPrint(java.lang.Boolean prettyPrint) { return (Resume) super.setPrettyPrint(prettyPrint); } @Override public Resume setQuotaUser(java.lang.String quotaUser) { return (Resume) super.setQuotaUser(quotaUser); } @Override public Resume setUploadType(java.lang.String uploadType) { return (Resume) super.setUploadType(uploadType); } @Override public Resume setUploadProtocol(java.lang.String uploadProtocol) { return (Resume) super.setUploadProtocol(uploadProtocol); } /** * Required. The job name. For example: * `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. */ @com.google.api.client.util.Key private java.lang.String name; /** Required. The job name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. */ public java.lang.String getName() { return name; } /** * Required. The job name. For example: * `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. */ public Resume setName(java.lang.String name) { if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(), "Parameter name must conform to the pattern " + "^projects/[^/]+/locations/[^/]+/jobs/[^/]+$"); } this.name = name; return this; } @Override public Resume set(String parameterName, Object value) { return (Resume) super.set(parameterName, value); } } /** * Forces a job to run now. When this method is called, Cloud Scheduler will dispatch the job, even * if the job is already running. * * Create a request for the method "jobs.run". * * This request holds the parameters needed by the cloudscheduler server. After setting any * optional parameters, call the {@link Run#execute()} method to invoke the remote operation. * * @param name Required. The job name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. * @param content the {@link com.google.api.services.cloudscheduler.v1.model.RunJobRequest} * @return the request */ public Run run(java.lang.String name, com.google.api.services.cloudscheduler.v1.model.RunJobRequest content) throws java.io.IOException { Run result = new Run(name, content); initialize(result); return result; } public class Run extends CloudSchedulerRequest<com.google.api.services.cloudscheduler.v1.model.Job> { private static final String REST_PATH = "v1/{+name}:run"; private final java.util.regex.Pattern NAME_PATTERN = java.util.regex.Pattern.compile("^projects/[^/]+/locations/[^/]+/jobs/[^/]+$"); /** * Forces a job to run now. When this method is called, Cloud Scheduler will dispatch the job, * even if the job is already running. * * Create a request for the method "jobs.run". * * This request holds the parameters needed by the the cloudscheduler server. After setting any * optional parameters, call the {@link Run#execute()} method to invoke the remote operation. <p> * {@link Run#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} * must be called to initialize this instance immediately after invoking the constructor. </p> * * @param name Required. The job name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. * @param content the {@link com.google.api.services.cloudscheduler.v1.model.RunJobRequest} * @since 1.13 */ protected Run(java.lang.String name, com.google.api.services.cloudscheduler.v1.model.RunJobRequest content) { super(CloudScheduler.this, "POST", REST_PATH, content, com.google.api.services.cloudscheduler.v1.model.Job.class); this.name = com.google.api.client.util.Preconditions.checkNotNull(name, "Required parameter name must be specified."); if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(), "Parameter name must conform to the pattern " + "^projects/[^/]+/locations/[^/]+/jobs/[^/]+$"); } } @Override public Run set$Xgafv(java.lang.String $Xgafv) { return (Run) super.set$Xgafv($Xgafv); } @Override public Run setAccessToken(java.lang.String accessToken) { return (Run) super.setAccessToken(accessToken); } @Override public Run setAlt(java.lang.String alt) { return (Run) super.setAlt(alt); } @Override public Run setCallback(java.lang.String callback) { return (Run) super.setCallback(callback); } @Override public Run setFields(java.lang.String fields) { return (Run) super.setFields(fields); } @Override public Run setKey(java.lang.String key) { return (Run) super.setKey(key); } @Override public Run setOauthToken(java.lang.String oauthToken) { return (Run) super.setOauthToken(oauthToken); } @Override public Run setPrettyPrint(java.lang.Boolean prettyPrint) { return (Run) super.setPrettyPrint(prettyPrint); } @Override public Run setQuotaUser(java.lang.String quotaUser) { return (Run) super.setQuotaUser(quotaUser); } @Override public Run setUploadType(java.lang.String uploadType) { return (Run) super.setUploadType(uploadType); } @Override public Run setUploadProtocol(java.lang.String uploadProtocol) { return (Run) super.setUploadProtocol(uploadProtocol); } /** * Required. The job name. For example: * `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. */ @com.google.api.client.util.Key private java.lang.String name; /** Required. The job name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. */ public java.lang.String getName() { return name; } /** * Required. The job name. For example: * `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. */ public Run setName(java.lang.String name) { if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(), "Parameter name must conform to the pattern " + "^projects/[^/]+/locations/[^/]+/jobs/[^/]+$"); } this.name = name; return this; } @Override public Run set(String parameterName, Object value) { return (Run) super.set(parameterName, value); } } } }
Java
public class Jobs { /** * Creates a job. * * Create a request for the method "jobs.create". * * This request holds the parameters needed by the cloudscheduler server. After setting any * optional parameters, call the {@link Create#execute()} method to invoke the remote operation. * * @param parent Required. The location name. For example: `projects/PROJECT_ID/locations/LOCATION_ID`. * @param content the {@link com.google.api.services.cloudscheduler.v1.model.Job} * @return the request */ public Create create(java.lang.String parent, com.google.api.services.cloudscheduler.v1.model.Job content) throws java.io.IOException { Create result = new Create(parent, content); initialize(result); return result; } public class Create extends CloudSchedulerRequest<com.google.api.services.cloudscheduler.v1.model.Job> { private static final String REST_PATH = "v1/{+parent}/jobs"; private final java.util.regex.Pattern PARENT_PATTERN = java.util.regex.Pattern.compile("^projects/[^/]+/locations/[^/]+$"); /** * Creates a job. * * Create a request for the method "jobs.create". * * This request holds the parameters needed by the the cloudscheduler server. After setting any * optional parameters, call the {@link Create#execute()} method to invoke the remote operation. * <p> {@link * Create#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param parent Required. The location name. For example: `projects/PROJECT_ID/locations/LOCATION_ID`. * @param content the {@link com.google.api.services.cloudscheduler.v1.model.Job} * @since 1.13 */ protected Create(java.lang.String parent, com.google.api.services.cloudscheduler.v1.model.Job content) { super(CloudScheduler.this, "POST", REST_PATH, content, com.google.api.services.cloudscheduler.v1.model.Job.class); this.parent = com.google.api.client.util.Preconditions.checkNotNull(parent, "Required parameter parent must be specified."); if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(PARENT_PATTERN.matcher(parent).matches(), "Parameter parent must conform to the pattern " + "^projects/[^/]+/locations/[^/]+$"); } } @Override public Create set$Xgafv(java.lang.String $Xgafv) { return (Create) super.set$Xgafv($Xgafv); } @Override public Create setAccessToken(java.lang.String accessToken) { return (Create) super.setAccessToken(accessToken); } @Override public Create setAlt(java.lang.String alt) { return (Create) super.setAlt(alt); } @Override public Create setCallback(java.lang.String callback) { return (Create) super.setCallback(callback); } @Override public Create setFields(java.lang.String fields) { return (Create) super.setFields(fields); } @Override public Create setKey(java.lang.String key) { return (Create) super.setKey(key); } @Override public Create setOauthToken(java.lang.String oauthToken) { return (Create) super.setOauthToken(oauthToken); } @Override public Create setPrettyPrint(java.lang.Boolean prettyPrint) { return (Create) super.setPrettyPrint(prettyPrint); } @Override public Create setQuotaUser(java.lang.String quotaUser) { return (Create) super.setQuotaUser(quotaUser); } @Override public Create setUploadType(java.lang.String uploadType) { return (Create) super.setUploadType(uploadType); } @Override public Create setUploadProtocol(java.lang.String uploadProtocol) { return (Create) super.setUploadProtocol(uploadProtocol); } /** * Required. The location name. For example: `projects/PROJECT_ID/locations/LOCATION_ID`. */ @com.google.api.client.util.Key private java.lang.String parent; /** Required. The location name. For example: `projects/PROJECT_ID/locations/LOCATION_ID`. */ public java.lang.String getParent() { return parent; } /** * Required. The location name. For example: `projects/PROJECT_ID/locations/LOCATION_ID`. */ public Create setParent(java.lang.String parent) { if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(PARENT_PATTERN.matcher(parent).matches(), "Parameter parent must conform to the pattern " + "^projects/[^/]+/locations/[^/]+$"); } this.parent = parent; return this; } @Override public Create set(String parameterName, Object value) { return (Create) super.set(parameterName, value); } } /** * Deletes a job. * * Create a request for the method "jobs.delete". * * This request holds the parameters needed by the cloudscheduler server. After setting any * optional parameters, call the {@link Delete#execute()} method to invoke the remote operation. * * @param name Required. The job name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. * @return the request */ public Delete delete(java.lang.String name) throws java.io.IOException { Delete result = new Delete(name); initialize(result); return result; } public class Delete extends CloudSchedulerRequest<com.google.api.services.cloudscheduler.v1.model.Empty> { private static final String REST_PATH = "v1/{+name}"; private final java.util.regex.Pattern NAME_PATTERN = java.util.regex.Pattern.compile("^projects/[^/]+/locations/[^/]+/jobs/[^/]+$"); /** * Deletes a job. * * Create a request for the method "jobs.delete". * * This request holds the parameters needed by the the cloudscheduler server. After setting any * optional parameters, call the {@link Delete#execute()} method to invoke the remote operation. * <p> {@link * Delete#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param name Required. The job name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. * @since 1.13 */ protected Delete(java.lang.String name) { super(CloudScheduler.this, "DELETE", REST_PATH, null, com.google.api.services.cloudscheduler.v1.model.Empty.class); this.name = com.google.api.client.util.Preconditions.checkNotNull(name, "Required parameter name must be specified."); if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(), "Parameter name must conform to the pattern " + "^projects/[^/]+/locations/[^/]+/jobs/[^/]+$"); } } @Override public Delete set$Xgafv(java.lang.String $Xgafv) { return (Delete) super.set$Xgafv($Xgafv); } @Override public Delete setAccessToken(java.lang.String accessToken) { return (Delete) super.setAccessToken(accessToken); } @Override public Delete setAlt(java.lang.String alt) { return (Delete) super.setAlt(alt); } @Override public Delete setCallback(java.lang.String callback) { return (Delete) super.setCallback(callback); } @Override public Delete setFields(java.lang.String fields) { return (Delete) super.setFields(fields); } @Override public Delete setKey(java.lang.String key) { return (Delete) super.setKey(key); } @Override public Delete setOauthToken(java.lang.String oauthToken) { return (Delete) super.setOauthToken(oauthToken); } @Override public Delete setPrettyPrint(java.lang.Boolean prettyPrint) { return (Delete) super.setPrettyPrint(prettyPrint); } @Override public Delete setQuotaUser(java.lang.String quotaUser) { return (Delete) super.setQuotaUser(quotaUser); } @Override public Delete setUploadType(java.lang.String uploadType) { return (Delete) super.setUploadType(uploadType); } @Override public Delete setUploadProtocol(java.lang.String uploadProtocol) { return (Delete) super.setUploadProtocol(uploadProtocol); } /** * Required. The job name. For example: * `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. */ @com.google.api.client.util.Key private java.lang.String name; /** Required. The job name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. */ public java.lang.String getName() { return name; } /** * Required. The job name. For example: * `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. */ public Delete setName(java.lang.String name) { if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(), "Parameter name must conform to the pattern " + "^projects/[^/]+/locations/[^/]+/jobs/[^/]+$"); } this.name = name; return this; } @Override public Delete set(String parameterName, Object value) { return (Delete) super.set(parameterName, value); } } /** * Gets a job. * * Create a request for the method "jobs.get". * * This request holds the parameters needed by the cloudscheduler server. After setting any * optional parameters, call the {@link Get#execute()} method to invoke the remote operation. * * @param name Required. The job name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. * @return the request */ public Get get(java.lang.String name) throws java.io.IOException { Get result = new Get(name); initialize(result); return result; } public class Get extends CloudSchedulerRequest<com.google.api.services.cloudscheduler.v1.model.Job> { private static final String REST_PATH = "v1/{+name}"; private final java.util.regex.Pattern NAME_PATTERN = java.util.regex.Pattern.compile("^projects/[^/]+/locations/[^/]+/jobs/[^/]+$"); /** * Gets a job. * * Create a request for the method "jobs.get". * * This request holds the parameters needed by the the cloudscheduler server. After setting any * optional parameters, call the {@link Get#execute()} method to invoke the remote operation. <p> * {@link Get#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} * must be called to initialize this instance immediately after invoking the constructor. </p> * * @param name Required. The job name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. * @since 1.13 */ protected Get(java.lang.String name) { super(CloudScheduler.this, "GET", REST_PATH, null, com.google.api.services.cloudscheduler.v1.model.Job.class); this.name = com.google.api.client.util.Preconditions.checkNotNull(name, "Required parameter name must be specified."); if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(), "Parameter name must conform to the pattern " + "^projects/[^/]+/locations/[^/]+/jobs/[^/]+$"); } } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public Get set$Xgafv(java.lang.String $Xgafv) { return (Get) super.set$Xgafv($Xgafv); } @Override public Get setAccessToken(java.lang.String accessToken) { return (Get) super.setAccessToken(accessToken); } @Override public Get setAlt(java.lang.String alt) { return (Get) super.setAlt(alt); } @Override public Get setCallback(java.lang.String callback) { return (Get) super.setCallback(callback); } @Override public Get setFields(java.lang.String fields) { return (Get) super.setFields(fields); } @Override public Get setKey(java.lang.String key) { return (Get) super.setKey(key); } @Override public Get setOauthToken(java.lang.String oauthToken) { return (Get) super.setOauthToken(oauthToken); } @Override public Get setPrettyPrint(java.lang.Boolean prettyPrint) { return (Get) super.setPrettyPrint(prettyPrint); } @Override public Get setQuotaUser(java.lang.String quotaUser) { return (Get) super.setQuotaUser(quotaUser); } @Override public Get setUploadType(java.lang.String uploadType) { return (Get) super.setUploadType(uploadType); } @Override public Get setUploadProtocol(java.lang.String uploadProtocol) { return (Get) super.setUploadProtocol(uploadProtocol); } /** * Required. The job name. For example: * `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. */ @com.google.api.client.util.Key private java.lang.String name; /** Required. The job name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. */ public java.lang.String getName() { return name; } /** * Required. The job name. For example: * `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. */ public Get setName(java.lang.String name) { if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(), "Parameter name must conform to the pattern " + "^projects/[^/]+/locations/[^/]+/jobs/[^/]+$"); } this.name = name; return this; } @Override public Get set(String parameterName, Object value) { return (Get) super.set(parameterName, value); } } /** * Lists jobs. * * Create a request for the method "jobs.list". * * This request holds the parameters needed by the cloudscheduler server. After setting any * optional parameters, call the {@link List#execute()} method to invoke the remote operation. * * @param parent Required. The location name. For example: `projects/PROJECT_ID/locations/LOCATION_ID`. * @return the request */ public List list(java.lang.String parent) throws java.io.IOException { List result = new List(parent); initialize(result); return result; } public class List extends CloudSchedulerRequest<com.google.api.services.cloudscheduler.v1.model.ListJobsResponse> { private static final String REST_PATH = "v1/{+parent}/jobs"; private final java.util.regex.Pattern PARENT_PATTERN = java.util.regex.Pattern.compile("^projects/[^/]+/locations/[^/]+$"); /** * Lists jobs. * * Create a request for the method "jobs.list". * * This request holds the parameters needed by the the cloudscheduler server. After setting any * optional parameters, call the {@link List#execute()} method to invoke the remote operation. <p> * {@link List#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} * must be called to initialize this instance immediately after invoking the constructor. </p> * * @param parent Required. The location name. For example: `projects/PROJECT_ID/locations/LOCATION_ID`. * @since 1.13 */ protected List(java.lang.String parent) { super(CloudScheduler.this, "GET", REST_PATH, null, com.google.api.services.cloudscheduler.v1.model.ListJobsResponse.class); this.parent = com.google.api.client.util.Preconditions.checkNotNull(parent, "Required parameter parent must be specified."); if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(PARENT_PATTERN.matcher(parent).matches(), "Parameter parent must conform to the pattern " + "^projects/[^/]+/locations/[^/]+$"); } } @Override public com.google.api.client.http.HttpResponse executeUsingHead() throws java.io.IOException { return super.executeUsingHead(); } @Override public com.google.api.client.http.HttpRequest buildHttpRequestUsingHead() throws java.io.IOException { return super.buildHttpRequestUsingHead(); } @Override public List set$Xgafv(java.lang.String $Xgafv) { return (List) super.set$Xgafv($Xgafv); } @Override public List setAccessToken(java.lang.String accessToken) { return (List) super.setAccessToken(accessToken); } @Override public List setAlt(java.lang.String alt) { return (List) super.setAlt(alt); } @Override public List setCallback(java.lang.String callback) { return (List) super.setCallback(callback); } @Override public List setFields(java.lang.String fields) { return (List) super.setFields(fields); } @Override public List setKey(java.lang.String key) { return (List) super.setKey(key); } @Override public List setOauthToken(java.lang.String oauthToken) { return (List) super.setOauthToken(oauthToken); } @Override public List setPrettyPrint(java.lang.Boolean prettyPrint) { return (List) super.setPrettyPrint(prettyPrint); } @Override public List setQuotaUser(java.lang.String quotaUser) { return (List) super.setQuotaUser(quotaUser); } @Override public List setUploadType(java.lang.String uploadType) { return (List) super.setUploadType(uploadType); } @Override public List setUploadProtocol(java.lang.String uploadProtocol) { return (List) super.setUploadProtocol(uploadProtocol); } /** * Required. The location name. For example: `projects/PROJECT_ID/locations/LOCATION_ID`. */ @com.google.api.client.util.Key private java.lang.String parent; /** Required. The location name. For example: `projects/PROJECT_ID/locations/LOCATION_ID`. */ public java.lang.String getParent() { return parent; } /** * Required. The location name. For example: `projects/PROJECT_ID/locations/LOCATION_ID`. */ public List setParent(java.lang.String parent) { if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(PARENT_PATTERN.matcher(parent).matches(), "Parameter parent must conform to the pattern " + "^projects/[^/]+/locations/[^/]+$"); } this.parent = parent; return this; } /** * Requested page size. The maximum page size is 500. If unspecified, the page size will * be the maximum. Fewer jobs than requested might be returned, even if more jobs exist; * use next_page_token to determine if more jobs exist. */ @com.google.api.client.util.Key private java.lang.Integer pageSize; /** Requested page size. The maximum page size is 500. If unspecified, the page size will be the maximum. Fewer jobs than requested might be returned, even if more jobs exist; use next_page_token to determine if more jobs exist. */ public java.lang.Integer getPageSize() { return pageSize; } /** * Requested page size. The maximum page size is 500. If unspecified, the page size will * be the maximum. Fewer jobs than requested might be returned, even if more jobs exist; * use next_page_token to determine if more jobs exist. */ public List setPageSize(java.lang.Integer pageSize) { this.pageSize = pageSize; return this; } /** * A token identifying a page of results the server will return. To request the first page * results, page_token must be empty. To request the next page of results, page_token must * be the value of next_page_token returned from the previous call to ListJobs. It is an * error to switch the value of filter or order_by while iterating through pages. */ @com.google.api.client.util.Key private java.lang.String pageToken; /** A token identifying a page of results the server will return. To request the first page results, page_token must be empty. To request the next page of results, page_token must be the value of next_page_token returned from the previous call to ListJobs. It is an error to switch the value of filter or order_by while iterating through pages. */ public java.lang.String getPageToken() { return pageToken; } /** * A token identifying a page of results the server will return. To request the first page * results, page_token must be empty. To request the next page of results, page_token must * be the value of next_page_token returned from the previous call to ListJobs. It is an * error to switch the value of filter or order_by while iterating through pages. */ public List setPageToken(java.lang.String pageToken) { this.pageToken = pageToken; return this; } @Override public List set(String parameterName, Object value) { return (List) super.set(parameterName, value); } } /** * Updates a job. If successful, the updated Job is returned. If the job does not exist, `NOT_FOUND` * is returned. If UpdateJob does not successfully return, it is possible for the job to be in an * Job.State.UPDATE_FAILED state. A job in this state may not be executed. If this happens, retry * the UpdateJob request until a successful response is received. * * Create a request for the method "jobs.patch". * * This request holds the parameters needed by the cloudscheduler server. After setting any * optional parameters, call the {@link Patch#execute()} method to invoke the remote operation. * * @param name Optionally caller-specified in CreateJob, after which it becomes output only. The job name. For * example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. * `PROJECT_ID` can * contain letters ([A-Za-z]), numbers ([0-9]), hyphens (-), colons (:), or periods (.). For * more information, see [Identifying projects](https://cloud.google.com/resource- * manager/docs/creating-managing-projects#identifying_projects) * `LOCATION_ID` is the * canonical ID for the job's location. The list of available locations can be obtained by * calling ListLocations. For more information, see * https://cloud.google.com/about/locations/. * `JOB_ID` can contain only letters ([A-Za-z]), * numbers ([0-9]), hyphens (-), or underscores (_). The maximum length is 500 characters. * @param content the {@link com.google.api.services.cloudscheduler.v1.model.Job} * @return the request */ public Patch patch(java.lang.String name, com.google.api.services.cloudscheduler.v1.model.Job content) throws java.io.IOException { Patch result = new Patch(name, content); initialize(result); return result; } public class Patch extends CloudSchedulerRequest<com.google.api.services.cloudscheduler.v1.model.Job> { private static final String REST_PATH = "v1/{+name}"; private final java.util.regex.Pattern NAME_PATTERN = java.util.regex.Pattern.compile("^projects/[^/]+/locations/[^/]+/jobs/[^/]+$"); /** * Updates a job. If successful, the updated Job is returned. If the job does not exist, * `NOT_FOUND` is returned. If UpdateJob does not successfully return, it is possible for the job * to be in an Job.State.UPDATE_FAILED state. A job in this state may not be executed. If this * happens, retry the UpdateJob request until a successful response is received. * * Create a request for the method "jobs.patch". * * This request holds the parameters needed by the the cloudscheduler server. After setting any * optional parameters, call the {@link Patch#execute()} method to invoke the remote operation. * <p> {@link * Patch#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param name Optionally caller-specified in CreateJob, after which it becomes output only. The job name. For * example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. * `PROJECT_ID` can * contain letters ([A-Za-z]), numbers ([0-9]), hyphens (-), colons (:), or periods (.). For * more information, see [Identifying projects](https://cloud.google.com/resource- * manager/docs/creating-managing-projects#identifying_projects) * `LOCATION_ID` is the * canonical ID for the job's location. The list of available locations can be obtained by * calling ListLocations. For more information, see * https://cloud.google.com/about/locations/. * `JOB_ID` can contain only letters ([A-Za-z]), * numbers ([0-9]), hyphens (-), or underscores (_). The maximum length is 500 characters. * @param content the {@link com.google.api.services.cloudscheduler.v1.model.Job} * @since 1.13 */ protected Patch(java.lang.String name, com.google.api.services.cloudscheduler.v1.model.Job content) { super(CloudScheduler.this, "PATCH", REST_PATH, content, com.google.api.services.cloudscheduler.v1.model.Job.class); this.name = com.google.api.client.util.Preconditions.checkNotNull(name, "Required parameter name must be specified."); if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(), "Parameter name must conform to the pattern " + "^projects/[^/]+/locations/[^/]+/jobs/[^/]+$"); } } @Override public Patch set$Xgafv(java.lang.String $Xgafv) { return (Patch) super.set$Xgafv($Xgafv); } @Override public Patch setAccessToken(java.lang.String accessToken) { return (Patch) super.setAccessToken(accessToken); } @Override public Patch setAlt(java.lang.String alt) { return (Patch) super.setAlt(alt); } @Override public Patch setCallback(java.lang.String callback) { return (Patch) super.setCallback(callback); } @Override public Patch setFields(java.lang.String fields) { return (Patch) super.setFields(fields); } @Override public Patch setKey(java.lang.String key) { return (Patch) super.setKey(key); } @Override public Patch setOauthToken(java.lang.String oauthToken) { return (Patch) super.setOauthToken(oauthToken); } @Override public Patch setPrettyPrint(java.lang.Boolean prettyPrint) { return (Patch) super.setPrettyPrint(prettyPrint); } @Override public Patch setQuotaUser(java.lang.String quotaUser) { return (Patch) super.setQuotaUser(quotaUser); } @Override public Patch setUploadType(java.lang.String uploadType) { return (Patch) super.setUploadType(uploadType); } @Override public Patch setUploadProtocol(java.lang.String uploadProtocol) { return (Patch) super.setUploadProtocol(uploadProtocol); } /** * Optionally caller-specified in CreateJob, after which it becomes output only. The job * name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. * * `PROJECT_ID` can contain letters ([A-Za-z]), numbers ([0-9]), hyphens (-), colons (:), * or periods (.). For more information, see [Identifying * projects](https://cloud.google.com/resource-manager/docs/creating-managing- * projects#identifying_projects) * `LOCATION_ID` is the canonical ID for the job's * location. The list of available locations can be obtained by calling ListLocations. For * more information, see https://cloud.google.com/about/locations/. * `JOB_ID` can contain * only letters ([A-Za-z]), numbers ([0-9]), hyphens (-), or underscores (_). The maximum * length is 500 characters. */ @com.google.api.client.util.Key private java.lang.String name; /** Optionally caller-specified in CreateJob, after which it becomes output only. The job name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. * `PROJECT_ID` can contain letters ([A-Za-z]), numbers ([0-9]), hyphens (-), colons (:), or periods (.). For more information, see [Identifying projects](https://cloud.google.com/resource-manager/docs/creating-managing- projects#identifying_projects) * `LOCATION_ID` is the canonical ID for the job's location. The list of available locations can be obtained by calling ListLocations. For more information, see https://cloud.google.com/about/locations/. * `JOB_ID` can contain only letters ([A-Za-z]), numbers ([0-9]), hyphens (-), or underscores (_). The maximum length is 500 characters. */ public java.lang.String getName() { return name; } /** * Optionally caller-specified in CreateJob, after which it becomes output only. The job * name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. * * `PROJECT_ID` can contain letters ([A-Za-z]), numbers ([0-9]), hyphens (-), colons (:), * or periods (.). For more information, see [Identifying * projects](https://cloud.google.com/resource-manager/docs/creating-managing- * projects#identifying_projects) * `LOCATION_ID` is the canonical ID for the job's * location. The list of available locations can be obtained by calling ListLocations. For * more information, see https://cloud.google.com/about/locations/. * `JOB_ID` can contain * only letters ([A-Za-z]), numbers ([0-9]), hyphens (-), or underscores (_). The maximum * length is 500 characters. */ public Patch setName(java.lang.String name) { if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(), "Parameter name must conform to the pattern " + "^projects/[^/]+/locations/[^/]+/jobs/[^/]+$"); } this.name = name; return this; } /** A mask used to specify which fields of the job are being updated. */ @com.google.api.client.util.Key private String updateMask; /** A mask used to specify which fields of the job are being updated. */ public String getUpdateMask() { return updateMask; } /** A mask used to specify which fields of the job are being updated. */ public Patch setUpdateMask(String updateMask) { this.updateMask = updateMask; return this; } @Override public Patch set(String parameterName, Object value) { return (Patch) super.set(parameterName, value); } } /** * Pauses a job. If a job is paused then the system will stop executing the job until it is re- * enabled via ResumeJob. The state of the job is stored in state; if paused it will be set to * Job.State.PAUSED. A job must be in Job.State.ENABLED to be paused. * * Create a request for the method "jobs.pause". * * This request holds the parameters needed by the cloudscheduler server. After setting any * optional parameters, call the {@link Pause#execute()} method to invoke the remote operation. * * @param name Required. The job name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. * @param content the {@link com.google.api.services.cloudscheduler.v1.model.PauseJobRequest} * @return the request */ public Pause pause(java.lang.String name, com.google.api.services.cloudscheduler.v1.model.PauseJobRequest content) throws java.io.IOException { Pause result = new Pause(name, content); initialize(result); return result; } public class Pause extends CloudSchedulerRequest<com.google.api.services.cloudscheduler.v1.model.Job> { private static final String REST_PATH = "v1/{+name}:pause"; private final java.util.regex.Pattern NAME_PATTERN = java.util.regex.Pattern.compile("^projects/[^/]+/locations/[^/]+/jobs/[^/]+$"); /** * Pauses a job. If a job is paused then the system will stop executing the job until it is re- * enabled via ResumeJob. The state of the job is stored in state; if paused it will be set to * Job.State.PAUSED. A job must be in Job.State.ENABLED to be paused. * * Create a request for the method "jobs.pause". * * This request holds the parameters needed by the the cloudscheduler server. After setting any * optional parameters, call the {@link Pause#execute()} method to invoke the remote operation. * <p> {@link * Pause#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param name Required. The job name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. * @param content the {@link com.google.api.services.cloudscheduler.v1.model.PauseJobRequest} * @since 1.13 */ protected Pause(java.lang.String name, com.google.api.services.cloudscheduler.v1.model.PauseJobRequest content) { super(CloudScheduler.this, "POST", REST_PATH, content, com.google.api.services.cloudscheduler.v1.model.Job.class); this.name = com.google.api.client.util.Preconditions.checkNotNull(name, "Required parameter name must be specified."); if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(), "Parameter name must conform to the pattern " + "^projects/[^/]+/locations/[^/]+/jobs/[^/]+$"); } } @Override public Pause set$Xgafv(java.lang.String $Xgafv) { return (Pause) super.set$Xgafv($Xgafv); } @Override public Pause setAccessToken(java.lang.String accessToken) { return (Pause) super.setAccessToken(accessToken); } @Override public Pause setAlt(java.lang.String alt) { return (Pause) super.setAlt(alt); } @Override public Pause setCallback(java.lang.String callback) { return (Pause) super.setCallback(callback); } @Override public Pause setFields(java.lang.String fields) { return (Pause) super.setFields(fields); } @Override public Pause setKey(java.lang.String key) { return (Pause) super.setKey(key); } @Override public Pause setOauthToken(java.lang.String oauthToken) { return (Pause) super.setOauthToken(oauthToken); } @Override public Pause setPrettyPrint(java.lang.Boolean prettyPrint) { return (Pause) super.setPrettyPrint(prettyPrint); } @Override public Pause setQuotaUser(java.lang.String quotaUser) { return (Pause) super.setQuotaUser(quotaUser); } @Override public Pause setUploadType(java.lang.String uploadType) { return (Pause) super.setUploadType(uploadType); } @Override public Pause setUploadProtocol(java.lang.String uploadProtocol) { return (Pause) super.setUploadProtocol(uploadProtocol); } /** * Required. The job name. For example: * `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. */ @com.google.api.client.util.Key private java.lang.String name; /** Required. The job name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. */ public java.lang.String getName() { return name; } /** * Required. The job name. For example: * `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. */ public Pause setName(java.lang.String name) { if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(), "Parameter name must conform to the pattern " + "^projects/[^/]+/locations/[^/]+/jobs/[^/]+$"); } this.name = name; return this; } @Override public Pause set(String parameterName, Object value) { return (Pause) super.set(parameterName, value); } } /** * Resume a job. This method reenables a job after it has been Job.State.PAUSED. The state of a job * is stored in Job.state; after calling this method it will be set to Job.State.ENABLED. A job must * be in Job.State.PAUSED to be resumed. * * Create a request for the method "jobs.resume". * * This request holds the parameters needed by the cloudscheduler server. After setting any * optional parameters, call the {@link Resume#execute()} method to invoke the remote operation. * * @param name Required. The job name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. * @param content the {@link com.google.api.services.cloudscheduler.v1.model.ResumeJobRequest} * @return the request */ public Resume resume(java.lang.String name, com.google.api.services.cloudscheduler.v1.model.ResumeJobRequest content) throws java.io.IOException { Resume result = new Resume(name, content); initialize(result); return result; } public class Resume extends CloudSchedulerRequest<com.google.api.services.cloudscheduler.v1.model.Job> { private static final String REST_PATH = "v1/{+name}:resume"; private final java.util.regex.Pattern NAME_PATTERN = java.util.regex.Pattern.compile("^projects/[^/]+/locations/[^/]+/jobs/[^/]+$"); /** * Resume a job. This method reenables a job after it has been Job.State.PAUSED. The state of a * job is stored in Job.state; after calling this method it will be set to Job.State.ENABLED. A * job must be in Job.State.PAUSED to be resumed. * * Create a request for the method "jobs.resume". * * This request holds the parameters needed by the the cloudscheduler server. After setting any * optional parameters, call the {@link Resume#execute()} method to invoke the remote operation. * <p> {@link * Resume#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} must * be called to initialize this instance immediately after invoking the constructor. </p> * * @param name Required. The job name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. * @param content the {@link com.google.api.services.cloudscheduler.v1.model.ResumeJobRequest} * @since 1.13 */ protected Resume(java.lang.String name, com.google.api.services.cloudscheduler.v1.model.ResumeJobRequest content) { super(CloudScheduler.this, "POST", REST_PATH, content, com.google.api.services.cloudscheduler.v1.model.Job.class); this.name = com.google.api.client.util.Preconditions.checkNotNull(name, "Required parameter name must be specified."); if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(), "Parameter name must conform to the pattern " + "^projects/[^/]+/locations/[^/]+/jobs/[^/]+$"); } } @Override public Resume set$Xgafv(java.lang.String $Xgafv) { return (Resume) super.set$Xgafv($Xgafv); } @Override public Resume setAccessToken(java.lang.String accessToken) { return (Resume) super.setAccessToken(accessToken); } @Override public Resume setAlt(java.lang.String alt) { return (Resume) super.setAlt(alt); } @Override public Resume setCallback(java.lang.String callback) { return (Resume) super.setCallback(callback); } @Override public Resume setFields(java.lang.String fields) { return (Resume) super.setFields(fields); } @Override public Resume setKey(java.lang.String key) { return (Resume) super.setKey(key); } @Override public Resume setOauthToken(java.lang.String oauthToken) { return (Resume) super.setOauthToken(oauthToken); } @Override public Resume setPrettyPrint(java.lang.Boolean prettyPrint) { return (Resume) super.setPrettyPrint(prettyPrint); } @Override public Resume setQuotaUser(java.lang.String quotaUser) { return (Resume) super.setQuotaUser(quotaUser); } @Override public Resume setUploadType(java.lang.String uploadType) { return (Resume) super.setUploadType(uploadType); } @Override public Resume setUploadProtocol(java.lang.String uploadProtocol) { return (Resume) super.setUploadProtocol(uploadProtocol); } /** * Required. The job name. For example: * `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. */ @com.google.api.client.util.Key private java.lang.String name; /** Required. The job name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. */ public java.lang.String getName() { return name; } /** * Required. The job name. For example: * `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. */ public Resume setName(java.lang.String name) { if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(), "Parameter name must conform to the pattern " + "^projects/[^/]+/locations/[^/]+/jobs/[^/]+$"); } this.name = name; return this; } @Override public Resume set(String parameterName, Object value) { return (Resume) super.set(parameterName, value); } } /** * Forces a job to run now. When this method is called, Cloud Scheduler will dispatch the job, even * if the job is already running. * * Create a request for the method "jobs.run". * * This request holds the parameters needed by the cloudscheduler server. After setting any * optional parameters, call the {@link Run#execute()} method to invoke the remote operation. * * @param name Required. The job name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. * @param content the {@link com.google.api.services.cloudscheduler.v1.model.RunJobRequest} * @return the request */ public Run run(java.lang.String name, com.google.api.services.cloudscheduler.v1.model.RunJobRequest content) throws java.io.IOException { Run result = new Run(name, content); initialize(result); return result; } public class Run extends CloudSchedulerRequest<com.google.api.services.cloudscheduler.v1.model.Job> { private static final String REST_PATH = "v1/{+name}:run"; private final java.util.regex.Pattern NAME_PATTERN = java.util.regex.Pattern.compile("^projects/[^/]+/locations/[^/]+/jobs/[^/]+$"); /** * Forces a job to run now. When this method is called, Cloud Scheduler will dispatch the job, * even if the job is already running. * * Create a request for the method "jobs.run". * * This request holds the parameters needed by the the cloudscheduler server. After setting any * optional parameters, call the {@link Run#execute()} method to invoke the remote operation. <p> * {@link Run#initialize(com.google.api.client.googleapis.services.AbstractGoogleClientRequest)} * must be called to initialize this instance immediately after invoking the constructor. </p> * * @param name Required. The job name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. * @param content the {@link com.google.api.services.cloudscheduler.v1.model.RunJobRequest} * @since 1.13 */ protected Run(java.lang.String name, com.google.api.services.cloudscheduler.v1.model.RunJobRequest content) { super(CloudScheduler.this, "POST", REST_PATH, content, com.google.api.services.cloudscheduler.v1.model.Job.class); this.name = com.google.api.client.util.Preconditions.checkNotNull(name, "Required parameter name must be specified."); if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(), "Parameter name must conform to the pattern " + "^projects/[^/]+/locations/[^/]+/jobs/[^/]+$"); } } @Override public Run set$Xgafv(java.lang.String $Xgafv) { return (Run) super.set$Xgafv($Xgafv); } @Override public Run setAccessToken(java.lang.String accessToken) { return (Run) super.setAccessToken(accessToken); } @Override public Run setAlt(java.lang.String alt) { return (Run) super.setAlt(alt); } @Override public Run setCallback(java.lang.String callback) { return (Run) super.setCallback(callback); } @Override public Run setFields(java.lang.String fields) { return (Run) super.setFields(fields); } @Override public Run setKey(java.lang.String key) { return (Run) super.setKey(key); } @Override public Run setOauthToken(java.lang.String oauthToken) { return (Run) super.setOauthToken(oauthToken); } @Override public Run setPrettyPrint(java.lang.Boolean prettyPrint) { return (Run) super.setPrettyPrint(prettyPrint); } @Override public Run setQuotaUser(java.lang.String quotaUser) { return (Run) super.setQuotaUser(quotaUser); } @Override public Run setUploadType(java.lang.String uploadType) { return (Run) super.setUploadType(uploadType); } @Override public Run setUploadProtocol(java.lang.String uploadProtocol) { return (Run) super.setUploadProtocol(uploadProtocol); } /** * Required. The job name. For example: * `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. */ @com.google.api.client.util.Key private java.lang.String name; /** Required. The job name. For example: `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. */ public java.lang.String getName() { return name; } /** * Required. The job name. For example: * `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. */ public Run setName(java.lang.String name) { if (!getSuppressPatternChecks()) { com.google.api.client.util.Preconditions.checkArgument(NAME_PATTERN.matcher(name).matches(), "Parameter name must conform to the pattern " + "^projects/[^/]+/locations/[^/]+/jobs/[^/]+$"); } this.name = name; return this; } @Override public Run set(String parameterName, Object value) { return (Run) super.set(parameterName, value); } } }
Java
public class BaseController { protected void refreshXUser(XUser xUser) { XUserSessionManager.getCurrent().setXUser(xUser); } public XUser getXUser() { return XUserSessionManager.getCurrent().getXUser(); } public void addAttrToXUserSession(String key,Object value) { XUserSessionManager.getCurrent().setAttr(key,value); } public String getRandomCode() { return XUserSessionManager.getCurrent().getRandomCode(); } public String getToken() { return XUserSessionManager.getCurrent().getToken(); } }
Java
public class RatingModel implements Comparable<RatingModel> { public ArrayList<String> getId() { return ids; } private ArrayList<String> ids; public Float getRating() { return rating.get(); } private FloatWritable rating; public RatingModel(ArrayList<String> ids, float rating) { this.ids = ids; this.rating = new FloatWritable(rating); } @Override public int compareTo(RatingModel ratingObj){ return this.rating.compareTo(ratingObj.rating); } @Override public String toString(){ return this.ids+"\t"+this.rating; } }
Java
public class GenerateJflexTLDMacros { public static void main(String... args) throws Exception { if (args.length != 2 || args[0].equals("--help") || args[0].equals("-help")) { System.err.println("Cmd line params:"); System.err.println( "\tjava " + GenerateJflexTLDMacros.class.getName() + "<ZoneFileURL> <JFlexOutputFile>"); System.exit(1); } new GenerateJflexTLDMacros(args[0], args[1]).execute(); } private static final String NL = System.getProperty("line.separator"); private static final String APACHE_LICENSE = "/*" + NL + " * Licensed to the Apache Software Foundation (ASF) under one or more" + NL + " * contributor license agreements. See the NOTICE file distributed with" + NL + " * this work for additional information regarding copyright ownership." + NL + " * The ASF licenses this file to You under the Apache License, Version 2.0" + NL + " * (the \"License\"); you may not use this file except in compliance with" + NL + " * the License. You may obtain a copy of the License at" + NL + " *" + NL + " * http://www.apache.org/licenses/LICENSE-2.0" + NL + " *" + NL + " * Unless required by applicable law or agreed to in writing, software" + NL + " * distributed under the License is distributed on an \"AS IS\" BASIS," + NL + " * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied." + NL + " * See the License for the specific language governing permissions and" + NL + " * limitations under the License." + NL + " */" + NL; private static final Pattern TLD_PATTERN_1 = Pattern.compile("([-A-Za-z0-9]+)\\.\\s+NS\\s+.*"); private static final Pattern TLD_PATTERN_2 = Pattern.compile("([-A-Za-z0-9]+)\\.\\s+\\d+\\s+IN\\s+NS\\s+.*"); private final URL tldFileURL; private long tldFileLastModified = -1L; private final File outputFile; private final SortedMap<String, Boolean> processedTLDsLongestFirst = new TreeMap<>( Comparator.comparing(String::length).reversed().thenComparing(String::compareTo)); private final List<SortedSet<String>> TLDsBySuffixLength = new ArrayList<>(); // list position indicates suffix length public GenerateJflexTLDMacros(String tldFileURL, String outputFile) throws Exception { this.tldFileURL = new URL(tldFileURL); this.outputFile = new File(outputFile); } /** * Downloads the IANA Root Zone Database, extracts the ASCII TLDs, then writes a set of JFlex * macros accepting any of them case-insensitively out to the specified output file. * * @throws IOException if there is a problem either downloading the database or writing out the * output file. */ public void execute() throws IOException { getIANARootZoneDatabase(); partitionTLDprefixesBySuffixLength(); writeOutput(); System.out.println("Wrote TLD macros to '" + outputFile + "':"); int totalDomains = 0; for (int suffixLength = 0; suffixLength < TLDsBySuffixLength.size(); ++suffixLength) { int domainsAtThisSuffixLength = TLDsBySuffixLength.get(suffixLength).size(); totalDomains += domainsAtThisSuffixLength; System.out.printf("%30s: %4d TLDs%n", getMacroName(suffixLength), domainsAtThisSuffixLength); } System.out.printf("%30s: %4d TLDs%n", "Total", totalDomains); } /** * Downloads the IANA Root Zone Database. * * @throws java.io.IOException if there is a problem downloading the database */ private void getIANARootZoneDatabase() throws IOException { final URLConnection connection = tldFileURL.openConnection(); connection.setUseCaches(false); connection.addRequestProperty("Cache-Control", "no-cache"); connection.connect(); tldFileLastModified = connection.getLastModified(); try (BufferedReader reader = new BufferedReader( new InputStreamReader(connection.getInputStream(), StandardCharsets.US_ASCII))) { String line; while (null != (line = reader.readLine())) { Matcher matcher = TLD_PATTERN_1.matcher(line); if (matcher.matches()) { // System.out.println("Found: " + matcher.group(1).toLowerCase(Locale.ROOT)); processedTLDsLongestFirst.put(matcher.group(1).toLowerCase(Locale.ROOT), Boolean.FALSE); } else { matcher = TLD_PATTERN_2.matcher(line); if (matcher.matches()) { // System.out.println("Found: " + matcher.group(1).toLowerCase(Locale.ROOT)); processedTLDsLongestFirst.put(matcher.group(1).toLowerCase(Locale.ROOT), Boolean.FALSE); } } } } System.out.println( "Found " + processedTLDsLongestFirst.size() + " TLDs in IANA Root Zone Database at " + tldFileURL); } /** * Partition TLDs by whether they are prefixes of other TLDs and then by suffix length. We only * care about TLDs that are prefixes and are exactly one character shorter than another TLD. See * LUCENE-8278 and LUCENE-5391. */ private void partitionTLDprefixesBySuffixLength() { TLDsBySuffixLength.add(new TreeSet<>()); // initialize set for zero-suffix TLDs for (SortedMap.Entry<String, Boolean> entry : processedTLDsLongestFirst.entrySet()) { String TLD = entry.getKey(); if (entry.getValue()) { // System.out.println("Skipping already processed: " + TLD); continue; } // System.out.println("Adding zero-suffix TLD: " + TLD); TLDsBySuffixLength.get(0).add(TLD); for (int suffixLength = 1; (TLD.length() - suffixLength) >= 2; ++suffixLength) { String TLDprefix = TLD.substring(0, TLD.length() - suffixLength); if (false == processedTLDsLongestFirst.containsKey(TLDprefix)) { // System.out.println("Ignoring non-TLD prefix: " + TLDprefix); break; // shorter prefixes can be ignored } if (processedTLDsLongestFirst.get(TLDprefix)) { // System.out.println("Skipping already processed prefix: " + TLDprefix); break; // shorter prefixes have already been processed } processedTLDsLongestFirst.put(TLDprefix, true); // mark as processed if (TLDsBySuffixLength.size() == suffixLength) TLDsBySuffixLength.add(new TreeSet<>()); SortedSet<String> TLDbucket = TLDsBySuffixLength.get(suffixLength); TLDbucket.add(TLDprefix); // System.out.println("Adding TLD prefix of " + TLD + " with suffix length " + suffixLength // + ": " + TLDprefix); } } } /** * Writes a file containing a JFlex macro that will accept any of the given TLDs * case-insensitively. */ private void writeOutput() throws IOException { final DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, Locale.ROOT); dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); try (Writer writer = new OutputStreamWriter(new FileOutputStream(outputFile), StandardCharsets.UTF_8)) { writer.write(APACHE_LICENSE); writer.write("// Generated from IANA Root Zone Database <"); writer.write(tldFileURL.toString()); writer.write(">"); writer.write(NL); if (tldFileLastModified > 0L) { writer.write("// file version from "); writer.write(dateFormat.format(tldFileLastModified)); writer.write(NL); } writer.write("// generated on "); writer.write(dateFormat.format(new Date())); writer.write(NL); writer.write("// by "); writer.write(this.getClass().getName()); writer.write(NL); writer.write(NL); for (int i = 0; i < TLDsBySuffixLength.size(); ++i) { String macroName = getMacroName(i); writer.write("// LUCENE-8278: "); if (i == 0) { writer.write( "None of the TLDs in {" + macroName + "} is a 1-character-shorter prefix of another TLD"); } else { writer.write("Each TLD in {" + macroName + "} is a prefix of another TLD by"); writer.write(" " + i + " character"); if (i > 1) { writer.write("s"); } } writer.write(NL); writeTLDmacro(writer, macroName, TLDsBySuffixLength.get(i)); } } } private String getMacroName(int suffixLength) { return "ASCIITLD" + (suffixLength > 0 ? "prefix_" + suffixLength + "CharSuffix" : ""); } private void writeTLDmacro(Writer writer, String macroName, SortedSet<String> TLDs) throws IOException { writer.write(macroName); writer.write(" = \".\" ("); writer.write(NL); boolean isFirst = true; for (String TLD : TLDs) { writer.write("\t"); if (isFirst) { isFirst = false; writer.write(" "); } else { writer.write("| "); } writer.write(getCaseInsensitiveRegex(TLD)); writer.write(NL); } writer.write("\t) \".\"? // Accept trailing root (empty) domain"); writer.write(NL); writer.write(NL); } /** * Returns a regex that will accept the given ASCII TLD case-insensitively. * * @param ASCIITLD The ASCII TLD to generate a regex for * @return a regex that will accept the given ASCII TLD case-insensitively */ private String getCaseInsensitiveRegex(String ASCIITLD) { StringBuilder builder = new StringBuilder(); for (int pos = 0; pos < ASCIITLD.length(); ++pos) { char ch = ASCIITLD.charAt(pos); if (Character.isDigit(ch) || ch == '-') { builder.append(ch); } else { builder.append("[").append(ch).append(Character.toUpperCase(ch)).append("]"); } } return builder.toString(); } }
Java
public class Bank { /** * Коллекция типа "карта", хранит пользователей и их счета. */ private Map<User, List<Account>> bank = new TreeMap<>(); /** * Метод добавляет нового пользователя. * @param user новый пользователь. */ public void addUser(User user) { this.bank.putIfAbsent(user, new ArrayList<>()); } /** * Метод удаяет пользователя. * @param user пользователь для удаления. */ public void deleteUser(User user) { this.bank.remove(user); } /** * Метод добавляет новый счет пользоватею. * @param passport номер паспорта пользователя. * @param account счет пользователя. */ public void addAccountToUser(String passport, Account account) { User user = getUserByPassport(passport); if (user != null && account != null) { this.bank.get(user).add(account); } } /** * Метод удаляет счет пользователя. * @param passport номер паспорта пользователя. * @param account счет пользователя. */ public void deleteAccountFromUser(String passport, Account account) { User user = getUserByPassport(passport); if (user != null && account != null) { this.bank.get(user).remove(account); } } /** * Метод получает список всех считов пользователя. * @param passport номер паспорта пользователя. * @return список счетов. */ public List<Account> getUserAccounts(String passport) { List<Account> accounts = null; User user = getUserByPassport(passport); if (user != null) { accounts = this.bank.get(user); } return accounts; } /** * Метод осуществляет перевод средств с одного счета на другой. * @param srcPassport номер паспорта пользователя отправителя. * @param srcRequisite реквезиты счета отправителя. * @param destPassport номер паспорта пользователя получателя. * @param dstRequisite реквезиты счета получателя. * @param amount сумма перевода. * @return флаг операции (успешно / неуспешно) */ public boolean transferMoney(String srcPassport, String srcRequisite, String destPassport, String dstRequisite, double amount) { boolean result = false; Account srcAccount = getAccountByPassportAndRequisite(srcPassport, srcRequisite); Account destAccount = getAccountByPassportAndRequisite(destPassport, dstRequisite); if (srcAccount != null && destAccount != null) { result = srcAccount.transfer(destAccount, amount); } return result; } /** * Метод предоставляет доступ к пользователям и их считам. * @return коллекция типа "карта". */ public Map<User, List<Account>> getBank() { return this.bank; } @Override public String toString() { return "Bank{" + "bank=" + bank + '}'; } /** * Метод находит пользователя по номеру паспорта. * @param passport номер паспорта пользователя. * @return искомый пользователь. */ public User getUserByPassport(String passport) { return this.bank.entrySet() .stream() .map(Map.Entry::getKey) .filter(u -> u.getPassport().equals(passport)) .findFirst() .orElse(null); } /** * Метод находит счет пользователя по номеру паспорта и реквезитам счета. * @param passport номер паспорта пользователя. * @param requisite номер счета пользователя. * @return счет пользователя. */ public Account getAccountByPassportAndRequisite(String passport, String requisite) { User user = getUserByPassport(passport); Account account = null; if (user != null) { account = this.bank.get(user) .stream() .filter(u -> u.getRequisites().equals(requisite)) .findAny() .orElse(null); } return account; } }
Java
public class DatatypeFlavorValidationResultDetail extends DatatypeValidationResultDetail { // Serialization version unique identifier private static final long serialVersionUID = 1L; // The name of the flavor the datatype instance failed to meet private String m_flavorName; /** * Creates a new instance of the DatatypeFlavorValidationResultDetail having the specified datatypeName and flavorName * @param datatypeName The name of the datatype that was validated * @param flavorName The flavor that the datatype instance failed to meet criteria */ public DatatypeFlavorValidationResultDetail(String datatypeName, String flavorName) { this(ResultDetailType.ERROR, datatypeName, flavorName, null); } /** * Creates a new instance of the DatatypeFlavorValidationResultDetail having the specified datatypeName, flavorName, type and location * @param type The type of issue being constructed (error, warning, information) * @param datatypeName The name of the datatype that is in violation * @param flavorName The name of the flavor that the datatype instance failed to meet * @param location The location of the datatype instance in a message */ public DatatypeFlavorValidationResultDetail(ResultDetailType type, String datatypeName, String flavorName, String location) { super(type, datatypeName, location); this.m_flavorName = flavorName; } /** * Gets a descriptive message */ @Override public String getMessage() { return String.format("Datatype '%s' failed validation criteria for flavor '%s'. Please refer to development guide for more information", this.getDatatypeName(), this.m_flavorName); } /** * Get the name of the flavor that the datatype instance failed to meet */ public String getFlavorName() { return m_flavorName; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + ((m_flavorName == null) ? 0 : m_flavorName.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; DatatypeFlavorValidationResultDetail other = (DatatypeFlavorValidationResultDetail) obj; if (m_flavorName == null) { if (other.m_flavorName != null) return false; } else if (!m_flavorName.equals(other.m_flavorName)) return false; return true; } }
Java
public class IcebergMaterializedViewDefinition { private static final String MATERIALIZED_VIEW_PREFIX = "/* Presto Materialized View: "; private static final String MATERIALIZED_VIEW_SUFFIX = " */"; private static final JsonCodec<IcebergMaterializedViewDefinition> materializedViewCodec = new JsonCodecFactory(new ObjectMapperProvider()).jsonCodec(IcebergMaterializedViewDefinition.class); private final String originalSql; private final Optional<String> catalog; private final Optional<String> schema; private final List<Column> columns; private final Optional<String> comment; private final String owner; public static String encodeMaterializedViewData(IcebergMaterializedViewDefinition definition) { byte[] bytes = materializedViewCodec.toJsonBytes(definition); String data = Base64.getEncoder().encodeToString(bytes); return MATERIALIZED_VIEW_PREFIX + data + MATERIALIZED_VIEW_SUFFIX; } public static IcebergMaterializedViewDefinition decodeMaterializedViewData(String data) { checkCondition(data.startsWith(MATERIALIZED_VIEW_PREFIX), HIVE_INVALID_VIEW_DATA, "Materialized View data missing prefix: %s", data); checkCondition(data.endsWith(MATERIALIZED_VIEW_SUFFIX), HIVE_INVALID_VIEW_DATA, "Materialized View data missing suffix: %s", data); data = data.substring(MATERIALIZED_VIEW_PREFIX.length()); data = data.substring(0, data.length() - MATERIALIZED_VIEW_SUFFIX.length()); byte[] bytes = Base64.getDecoder().decode(data); return materializedViewCodec.fromJson(bytes); } public static IcebergMaterializedViewDefinition fromConnectorMaterializedViewDefinition(ConnectorMaterializedViewDefinition definition) { return new IcebergMaterializedViewDefinition( definition.getOriginalSql(), definition.getCatalog(), definition.getSchema(), definition.getColumns().stream() .map(column -> new Column(column.getName(), column.getType())) .collect(toImmutableList()), definition.getComment(), definition.getOwner()); } @JsonCreator public IcebergMaterializedViewDefinition( @JsonProperty("originalSql") String originalSql, @JsonProperty("catalog") Optional<String> catalog, @JsonProperty("schema") Optional<String> schema, @JsonProperty("columns") List<Column> columns, @JsonProperty("comment") Optional<String> comment, @JsonProperty("owner") String owner) { this.originalSql = requireNonNull(originalSql, "originalSql is null"); this.catalog = requireNonNull(catalog, "catalog is null"); this.schema = requireNonNull(schema, "schema is null"); this.columns = List.copyOf(requireNonNull(columns, "columns is null")); this.comment = requireNonNull(comment, "comment is null"); this.owner = requireNonNull(owner, "owner is null"); if (catalog.isEmpty() && schema.isPresent()) { throw new IllegalArgumentException("catalog must be present if schema is present"); } if (columns.isEmpty()) { throw new IllegalArgumentException("columns list is empty"); } } @JsonProperty public String getOriginalSql() { return originalSql; } @JsonProperty public Optional<String> getCatalog() { return catalog; } @JsonProperty public Optional<String> getSchema() { return schema; } @JsonProperty public List<Column> getColumns() { return columns; } @JsonProperty public Optional<String> getComment() { return comment; } @JsonProperty public String getOwner() { return owner; } @Override public String toString() { StringJoiner joiner = new StringJoiner(", ", "[", "]"); joiner.add("originalSql=[" + originalSql + "]"); catalog.ifPresent(value -> joiner.add("catalog=" + value)); schema.ifPresent(value -> joiner.add("schema=" + value)); joiner.add("columns=" + columns); comment.ifPresent(value -> joiner.add("comment=" + value)); joiner.add("owner=" + owner); return getClass().getSimpleName() + joiner; } public static final class Column { private final String name; private final TypeId type; @JsonCreator public Column( @JsonProperty("name") String name, @JsonProperty("type") TypeId type) { this.name = requireNonNull(name, "name is null"); this.type = requireNonNull(type, "type is null"); } @JsonProperty public String getName() { return name; } @JsonProperty public TypeId getType() { return type; } @Override public String toString() { return name + " " + type; } } }
Java
public class ShootAnimation extends BaseAnim { private float speed; private float y; public ShootAnimation(float y, float v) { this.speed = v; this.y = y; animating = true; animType = AnimType.SHOOT; } @Override public Float2 adjustPosition(Float2 original) { y = original.y += speed; return original; } @Override public boolean adjustAlive(boolean ori) { if (y < 0 || y > UIdefaultData.screenHeight) { ori = false; } return ori; } }
Java
public class QueryManager { private static Firebase fireData = new Firebase("https://uni-database.firebaseio.com/"); public Map <String, String> courseMap; public List<String> courseList; /* Function adds lists of either Courses/Interests/Groups into the database Target locations: User, School->Interests/Classes/Groups This is only used when the Tutorial Activity is called. */ public void setListData(User user, String label, List<String> data){ Firebase userDataRef = fireData.child("users").child(user.getUid()); //firebase reference userDataRef.child(label).setValue(data); } public void setMapData(User user, String label, Map<String, String> data){ Firebase userDataRef = fireData.child("users").child(user.getUid()); userDataRef.child(label).setValue(data); } /* Set user's 'courses' field in the database as a map with course codes as keys and course names as values */ public void setUserCourses(User user, List<String> courses){ courseList = courses; courseMap = new HashMap<String, String>(); final String uid = user.getUid(); fireData.child("schools").child(user.getSid()).child("courses").addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot snapshot) { for (String course : courseList) { String name = snapshot.child(course).child("name").getValue(String.class); courseMap.put(course, name); } fireData.child("users").child(uid).child("courses").setValue(courseMap); } @Override public void onCancelled(FirebaseError firebaseError) { System.out.println("The course read failed: " + firebaseError.getMessage()); } }); } /* Function allows user to edit only these categories in DB: email, name, school, isTutorialDone */ public User setUserStringData(User user, String label, String data){ Firebase userDataRef = fireData.child("users").child(user.getUid()); //firebase reference if(label.equals("email")){ user.setEmail(data); } else if(label.equals("name")){ user.setName(data); } else if(label.equals("school")){ user.setSid(data); } else if(!(label.equals("isTutorialDone"))){ //show some sort of error } userDataRef.child(label).setValue(data); return user; } public void updateRoster(User user, String label, List<String> data){ Firebase schoolRef = fireData.child("schools").child(user.getSid()); Map<String, Object> addUser = new HashMap<String, Object>(); addUser.put(user.getUid(), user.getName()); for(String key : data){ if(label.equals("courses")) { schoolRef.child(label).child(key).child("roster").updateChildren(addUser); }else{ //If interests schoolRef.child(label).child(key).updateChildren(addUser); } } } /* public User modifyingUserListData(User user, String label, List<String> data){ Firebase addingDataRef = fireData.child(getResources().getString(R.string.database_users_key)).child(user.getUid()); //firebase reference if(label.equals(getResources().getString(R.string.user_courses_key))){ addingDataRef.child(getResources().getString(R.string.user_courses_key)).setValue(getResources().getString(R.string.user_courses_key), data); Firebase addingToSchool = fireData.child("school").child(user.getSchoolId()); user.setEmail(data); addingDataRef.child(label).setValue(data); } else if(label.equals("interests")){ user.setName(data); addingDataRef.child(label).setValue(data); } else if(label.equals("groups")){ user.setSchoolId(data); addingDataRef.child(label).setValue(data); }else if(label.equals("isTutorialDone")){ addingDataRef.child(label).setValue(data); }else{ //show some sort of error } return user; } */ }
Java
@RunWith(SpringRunner.class) @DataJpaTest @ContextConfiguration(classes = ServicesTestConfig.class) public class UserManagementServiceTest { @Autowired private UserManagementService userManagementService; @Test public void testName() throws Exception { User userProfile = new User("1201994", "Grass Root", null); userProfile = userManagementService.createUserProfile(userProfile); assertThat(userProfile.getDisplayName(), equalTo("Grass Root")); } @Test public void shouldLoadOrSave() { User user = userManagementService.loadOrCreateUser("0826607135", UserInterfaceType.USSD); Assert.assertNotEquals(Long.parseLong("0"),Long.parseLong(user.getId().toString())); } }
Java
public abstract class Line2D extends Object { // Result data for checking if a point is on a line. public static class PointOnLineResult { // Is the point on the line? public final boolean isOnLine; // The value with which the line vector needs to be scaled to yield the // point. public final double parametricValue; public PointOnLineResult() { this.isOnLine = false; this.parametricValue = 0.0; } public PointOnLineResult(double parametricVal) { this.isOnLine = true; this.parametricValue = parametricVal; } } // Point that anchors the line in the coordinate system. For line types that // have a start point it is guaranteed to be the start point. protected final Point2D anchor; // Direction of line. Whether the length of the direction vector has meaning // is up to each derived class. protected final Vector2D dir; // Ctor to initialize the final members. protected Line2D(Point2D anchor, Vector2D direction) { this.anchor = anchor; this.dir = direction; } // Creates a copy of line object. public abstract Line2D copy(); // Checks if the line degenerates into a point. public boolean isPoint() { return dir.isZeroVector(); } public Point2D anchorPoint() { return anchor; } public abstract boolean hasStartPoint(); // Returns start point of line or null if it doesn't have one. public abstract Point2D startPoint(); public abstract boolean hasEndPoint(); // Returns end point of line or null if it doesn't have one. public abstract Point2D endPoint(); public Vector2D direction() { return dir; } // Checks if a given point is on the line. public PointOnLineResult isPointOnLine(Point2D pt) { // Default to negative result. Subclasses should customize this method. return new PointOnLineResult(); } // Checks if a given point is on the infinite extension of the line. public PointOnLineResult isPointOnInfiniteLine(Point2D pt) { double parametricVal = calcParametricValue(pt); if (parametricVal == Double.MAX_VALUE) return new PointOnLineResult(); return new PointOnLineResult(parametricVal); } // Calculates the parametric value of a given point along the line. // Returns 'Double.MAX_VALUE' if the point is not on the line. public double calcParametricValue(Point2D pt) { final double NOT_FOUND = Double.MAX_VALUE; if (isPoint()) return (pt.equals(anchor)) ? 0.0 : NOT_FOUND; Vector2D v = new Vector2D(anchor, pt); if (!v.isParallel(dir)) return NOT_FOUND; // length != 0 is assured by checking whether line is a point above. double parametricVal = v.length() / dir.length(); if (!v.hasSameDirection(dir)) parametricVal *= -1; return parametricVal; } // Returns the point at a given parametric value along the line. public Point2D calcPointAt(double parametricVal) { Vector2D v = dir.scale(parametricVal); return anchor.offset(v); } // Checks if a given line is parallel to this line. public boolean isParallel(Line2D line) { return dir.isParallel(line.direction().normalize()); } // Checks if a given line is on the same inifinite line as this line. public boolean isCoincident(Line2D line) { return isParallel(line) && isPointOnInfiniteLine(line.anchor).isOnLine; } // Intersects given line with this line. public LineIntersection2D.Result intersect(Line2D other) { return LineIntersection2D.intersect(this, other); } }
Java
public static class PointOnLineResult { // Is the point on the line? public final boolean isOnLine; // The value with which the line vector needs to be scaled to yield the // point. public final double parametricValue; public PointOnLineResult() { this.isOnLine = false; this.parametricValue = 0.0; } public PointOnLineResult(double parametricVal) { this.isOnLine = true; this.parametricValue = parametricVal; } }
Java
@XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "FinancialInstrument69", propOrder = { "lineId", "instrm", "qty", "trfTp", "convs", "unitsDtls", "clntRef", "ctrPtyRef", "bizFlowTp", "avrgAcqstnPric", "trfCcy", "ttlBookVal", "trfeeAcct", "trfr", "reqdTrfDt", "reqdTradDt", "reqdSttlmDt", "pmtDtls", "crstllstnDtls", "taxValtnPt", "sttlmPtiesDtls", "addtlInf" }) public class FinancialInstrument69 { @XmlElement(name = "LineId") protected String lineId; @XmlElement(name = "Instrm", required = true) protected FinancialInstrument1Choice instrm; @XmlElement(name = "Qty") protected Quantity44Choice qty; @XmlElement(name = "TrfTp", required = true) protected TransferType1Choice trfTp; @XmlElement(name = "Convs") protected Conversion1 convs; @XmlElement(name = "UnitsDtls") protected List<Unit11> unitsDtls; @XmlElement(name = "ClntRef") protected AdditionalReference10 clntRef; @XmlElement(name = "CtrPtyRef") protected AdditionalReference10 ctrPtyRef; @XmlElement(name = "BizFlowTp") @XmlSchemaType(name = "string") protected BusinessFlowType1Code bizFlowTp; @XmlElement(name = "AvrgAcqstnPric") protected ActiveOrHistoricCurrencyAndAmount avrgAcqstnPric; @XmlElement(name = "TrfCcy") protected String trfCcy; @XmlElement(name = "TtlBookVal") protected DateAndAmount2 ttlBookVal; @XmlElement(name = "TrfeeAcct") protected Account28 trfeeAcct; @XmlElement(name = "Trfr") protected Account28 trfr; @XmlElement(name = "ReqdTrfDt", type = String.class) @XmlJavaTypeAdapter(IsoDateAdapter.class) @XmlSchemaType(name = "date") protected XMLGregorianCalendar reqdTrfDt; @XmlElement(name = "ReqdTradDt", type = String.class) @XmlJavaTypeAdapter(IsoDateAdapter.class) @XmlSchemaType(name = "date") protected XMLGregorianCalendar reqdTradDt; @XmlElement(name = "ReqdSttlmDt", type = String.class) @XmlJavaTypeAdapter(IsoDateAdapter.class) @XmlSchemaType(name = "date") protected XMLGregorianCalendar reqdSttlmDt; @XmlElement(name = "PmtDtls") protected PaymentInstrument14 pmtDtls; @XmlElement(name = "CrstllstnDtls") protected Crystallisation1 crstllstnDtls; @XmlElement(name = "TaxValtnPt") protected Tax36 taxValtnPt; @XmlElement(name = "SttlmPtiesDtls") protected FundSettlementParameters14 sttlmPtiesDtls; @XmlElement(name = "AddtlInf") protected List<AdditionalInformation15> addtlInf; /** * Gets the value of the lineId property. * * @return * possible object is * {@link String } * */ public String getLineId() { return lineId; } /** * Sets the value of the lineId property. * * @param value * allowed object is * {@link String } * */ public FinancialInstrument69 setLineId(String value) { this.lineId = value; return this; } /** * Gets the value of the instrm property. * * @return * possible object is * {@link FinancialInstrument1Choice } * */ public FinancialInstrument1Choice getInstrm() { return instrm; } /** * Sets the value of the instrm property. * * @param value * allowed object is * {@link FinancialInstrument1Choice } * */ public FinancialInstrument69 setInstrm(FinancialInstrument1Choice value) { this.instrm = value; return this; } /** * Gets the value of the qty property. * * @return * possible object is * {@link Quantity44Choice } * */ public Quantity44Choice getQty() { return qty; } /** * Sets the value of the qty property. * * @param value * allowed object is * {@link Quantity44Choice } * */ public FinancialInstrument69 setQty(Quantity44Choice value) { this.qty = value; return this; } /** * Gets the value of the trfTp property. * * @return * possible object is * {@link TransferType1Choice } * */ public TransferType1Choice getTrfTp() { return trfTp; } /** * Sets the value of the trfTp property. * * @param value * allowed object is * {@link TransferType1Choice } * */ public FinancialInstrument69 setTrfTp(TransferType1Choice value) { this.trfTp = value; return this; } /** * Gets the value of the convs property. * * @return * possible object is * {@link Conversion1 } * */ public Conversion1 getConvs() { return convs; } /** * Sets the value of the convs property. * * @param value * allowed object is * {@link Conversion1 } * */ public FinancialInstrument69 setConvs(Conversion1 value) { this.convs = value; return this; } /** * Gets the value of the unitsDtls property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the unitsDtls property. * * <p> * For example, to add a new item, do as follows: * <pre> * getUnitsDtls().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link Unit11 } * * */ public List<Unit11> getUnitsDtls() { if (unitsDtls == null) { unitsDtls = new ArrayList<Unit11>(); } return this.unitsDtls; } /** * Gets the value of the clntRef property. * * @return * possible object is * {@link AdditionalReference10 } * */ public AdditionalReference10 getClntRef() { return clntRef; } /** * Sets the value of the clntRef property. * * @param value * allowed object is * {@link AdditionalReference10 } * */ public FinancialInstrument69 setClntRef(AdditionalReference10 value) { this.clntRef = value; return this; } /** * Gets the value of the ctrPtyRef property. * * @return * possible object is * {@link AdditionalReference10 } * */ public AdditionalReference10 getCtrPtyRef() { return ctrPtyRef; } /** * Sets the value of the ctrPtyRef property. * * @param value * allowed object is * {@link AdditionalReference10 } * */ public FinancialInstrument69 setCtrPtyRef(AdditionalReference10 value) { this.ctrPtyRef = value; return this; } /** * Gets the value of the bizFlowTp property. * * @return * possible object is * {@link BusinessFlowType1Code } * */ public BusinessFlowType1Code getBizFlowTp() { return bizFlowTp; } /** * Sets the value of the bizFlowTp property. * * @param value * allowed object is * {@link BusinessFlowType1Code } * */ public FinancialInstrument69 setBizFlowTp(BusinessFlowType1Code value) { this.bizFlowTp = value; return this; } /** * Gets the value of the avrgAcqstnPric property. * * @return * possible object is * {@link ActiveOrHistoricCurrencyAndAmount } * */ public ActiveOrHistoricCurrencyAndAmount getAvrgAcqstnPric() { return avrgAcqstnPric; } /** * Sets the value of the avrgAcqstnPric property. * * @param value * allowed object is * {@link ActiveOrHistoricCurrencyAndAmount } * */ public FinancialInstrument69 setAvrgAcqstnPric(ActiveOrHistoricCurrencyAndAmount value) { this.avrgAcqstnPric = value; return this; } /** * Gets the value of the trfCcy property. * * @return * possible object is * {@link String } * */ public String getTrfCcy() { return trfCcy; } /** * Sets the value of the trfCcy property. * * @param value * allowed object is * {@link String } * */ public FinancialInstrument69 setTrfCcy(String value) { this.trfCcy = value; return this; } /** * Gets the value of the ttlBookVal property. * * @return * possible object is * {@link DateAndAmount2 } * */ public DateAndAmount2 getTtlBookVal() { return ttlBookVal; } /** * Sets the value of the ttlBookVal property. * * @param value * allowed object is * {@link DateAndAmount2 } * */ public FinancialInstrument69 setTtlBookVal(DateAndAmount2 value) { this.ttlBookVal = value; return this; } /** * Gets the value of the trfeeAcct property. * * @return * possible object is * {@link Account28 } * */ public Account28 getTrfeeAcct() { return trfeeAcct; } /** * Sets the value of the trfeeAcct property. * * @param value * allowed object is * {@link Account28 } * */ public FinancialInstrument69 setTrfeeAcct(Account28 value) { this.trfeeAcct = value; return this; } /** * Gets the value of the trfr property. * * @return * possible object is * {@link Account28 } * */ public Account28 getTrfr() { return trfr; } /** * Sets the value of the trfr property. * * @param value * allowed object is * {@link Account28 } * */ public FinancialInstrument69 setTrfr(Account28 value) { this.trfr = value; return this; } /** * Gets the value of the reqdTrfDt property. * * @return * possible object is * {@link String } * */ public XMLGregorianCalendar getReqdTrfDt() { return reqdTrfDt; } /** * Sets the value of the reqdTrfDt property. * * @param value * allowed object is * {@link String } * */ public FinancialInstrument69 setReqdTrfDt(XMLGregorianCalendar value) { this.reqdTrfDt = value; return this; } /** * Gets the value of the reqdTradDt property. * * @return * possible object is * {@link String } * */ public XMLGregorianCalendar getReqdTradDt() { return reqdTradDt; } /** * Sets the value of the reqdTradDt property. * * @param value * allowed object is * {@link String } * */ public FinancialInstrument69 setReqdTradDt(XMLGregorianCalendar value) { this.reqdTradDt = value; return this; } /** * Gets the value of the reqdSttlmDt property. * * @return * possible object is * {@link String } * */ public XMLGregorianCalendar getReqdSttlmDt() { return reqdSttlmDt; } /** * Sets the value of the reqdSttlmDt property. * * @param value * allowed object is * {@link String } * */ public FinancialInstrument69 setReqdSttlmDt(XMLGregorianCalendar value) { this.reqdSttlmDt = value; return this; } /** * Gets the value of the pmtDtls property. * * @return * possible object is * {@link PaymentInstrument14 } * */ public PaymentInstrument14 getPmtDtls() { return pmtDtls; } /** * Sets the value of the pmtDtls property. * * @param value * allowed object is * {@link PaymentInstrument14 } * */ public FinancialInstrument69 setPmtDtls(PaymentInstrument14 value) { this.pmtDtls = value; return this; } /** * Gets the value of the crstllstnDtls property. * * @return * possible object is * {@link Crystallisation1 } * */ public Crystallisation1 getCrstllstnDtls() { return crstllstnDtls; } /** * Sets the value of the crstllstnDtls property. * * @param value * allowed object is * {@link Crystallisation1 } * */ public FinancialInstrument69 setCrstllstnDtls(Crystallisation1 value) { this.crstllstnDtls = value; return this; } /** * Gets the value of the taxValtnPt property. * * @return * possible object is * {@link Tax36 } * */ public Tax36 getTaxValtnPt() { return taxValtnPt; } /** * Sets the value of the taxValtnPt property. * * @param value * allowed object is * {@link Tax36 } * */ public FinancialInstrument69 setTaxValtnPt(Tax36 value) { this.taxValtnPt = value; return this; } /** * Gets the value of the sttlmPtiesDtls property. * * @return * possible object is * {@link FundSettlementParameters14 } * */ public FundSettlementParameters14 getSttlmPtiesDtls() { return sttlmPtiesDtls; } /** * Sets the value of the sttlmPtiesDtls property. * * @param value * allowed object is * {@link FundSettlementParameters14 } * */ public FinancialInstrument69 setSttlmPtiesDtls(FundSettlementParameters14 value) { this.sttlmPtiesDtls = value; return this; } /** * Gets the value of the addtlInf property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the addtlInf property. * * <p> * For example, to add a new item, do as follows: * <pre> * getAddtlInf().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link AdditionalInformation15 } * * */ public List<AdditionalInformation15> getAddtlInf() { if (addtlInf == null) { addtlInf = new ArrayList<AdditionalInformation15>(); } return this.addtlInf; } @Override public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); } @Override public boolean equals(Object that) { return EqualsBuilder.reflectionEquals(this, that); } @Override public int hashCode() { return HashCodeBuilder.reflectionHashCode(this); } /** * Adds a new item to the unitsDtls list. * @see #getUnitsDtls() * */ public FinancialInstrument69 addUnitsDtls(Unit11 unitsDtls) { getUnitsDtls().add(unitsDtls); return this; } /** * Adds a new item to the addtlInf list. * @see #getAddtlInf() * */ public FinancialInstrument69 addAddtlInf(AdditionalInformation15 addtlInf) { getAddtlInf().add(addtlInf); return this; } }
Java
public class RolePermissions extends MtWilsonClient { Logger log = LoggerFactory.getLogger(getClass().getName()); /** * Constructor. * * @param properties This java properties model must include server connection details for the API client initialization. * <pre> * mtwilson.api.url - Host Verification Service (HVS) base URL for accessing REST APIs * * // basic authentication * mtwilson.api.username - Username for API basic authentication with the HVS * mtwilson.api.password - Password for API basic authentication with the HVS * * <b>Example:</b> * Properties properties = new Properties(); * properties.put(“mtwilson.api.url”, “https://server.com:port/mtwilson/v2”); * * // basic authentication * properties.put("mtwilson.api.username", "admin"); * properties.put("mtwilson.api.password", "password"); * properties.put("mtwilson.api.tls.policy.certificate.sha256", "bfc4884d748eff5304f326f34a986c0b3ff0b3b08eec281e6d08815fafdb8b02"); * RolePermissions client = new RolePermissions(properties); * </pre> * @throws Exception */ public RolePermissions(Properties properties) throws Exception { super(properties); } /** * Create a user role permission(s). * @param item The serialized RolePermission java model object represents the content of the request body.<br/> * <pre> * * permit_domain (optional) resources on which permissions apply (eg. hosts, flavors). * * permit_action (optional) actions on which the permission is required (eg. add, delete). * * permit_selection (optional) user can specify a condition and if that evaluates to true, it will get the required permissions. By default, it is set to * * </pre> * @return The serialized RolePermissionCollection java model object that was created with collection of flavors each containing: * <pre> * roleId * permitDomain * permitAction * permitSelection * </pre> * @since ISecL 1.0 * @mtwRequiresPermissions role_permissions:create * @mtwContentTypeReturned JSON/XML/YAML * @mtwMethodType POST * @mtwPreRequisite Role Create API * @mtwSampleRestCall * <pre> * https://server.com:8443/mtwilson/v2/roles/9e5c1b6b-44d6-40ea-90f3-4a8c32c140c2/permissions * input: * { * "permit_domain":"user_mgmt", * "permit_action":"add,delete", * "permit_selection":"*" * } * output: * { * "id":"9b35b89c-c5f0-4ffb-8f94-a7f73eef8f76", * "role_id":"05f80052-2642-480a-8504-880e27ce8b57", * "permit_domain":"user_mgmt", * "permit_action":"add,delete", * "permit_selection":"*" * } * </pre> * @mtwSampleApiCall * <div style="word-wrap: break-word; width: 1024px"><pre> * // Create the role permission model * RolePermission rolePermission = new RolePermission(); * rolePermission.setRoleId("05f80052-2642-480a-8504-880e27ce8b57"); * rolePermission.setPermitDomain("user_mgmt"); * rolePermission.setPermitAction("add,delete"); * rolePermission.setPermitSelection("*"); * * // Create the client and call the create API * RolePermissions client = new RolePermissions(properties); * RolePermissionCollection rolePermissionCollection = client.create(rolePermission); * </pre></div> */ public RolePermissionCollection create(RolePermission item) { log.debug("target: {}", getTarget().getUri().toString()); HashMap<String,Object> map = new HashMap<>(); map.put("role_id", item.getRoleId().toString()); RolePermissionCollection newRolePermission = getTarget().path("roles/{role_id}/permissions").resolveTemplates(map).request().accept(MediaType.APPLICATION_JSON).post(Entity.json(item), RolePermissionCollection.class); return newRolePermission; } /** * Search for user role permission(s). * @param criteria The content models of the RolePermissionFilterCriteria java model object can be used as query parameters. * <pre> * filter Boolean value to indicate whether the response should be filtered to return no results instead of listing all flavors. Default value is true. * * roleId Role ID. * * actionEqualTo permision action regex pattern. * * domainEqualTo resource name regex pattern. * * Only one of the above parameters can be specified. The parameters listed here are in the order of priority that will be evaluated. * * </pre> * @return The serialized RolePermissionCollection java model object that was searched with list of role permissions each containing: * <pre> * roldeId * permitDomain * permitAction * permitSelection * </pre> * @since ISecL 1.0 * @mtwRequiresPermissions role_permissions:search * @mtwContentTypeReturned JSON/XML/YAML * @mtwMethodType GET * @mtwPreRequisite Role Create API * @mtwSampleRestCall * <pre> * https://server.com:8443/mtwilson/v2/roles/05f80052-2642-480a-8504-880e27ce8b57/permissions?actionEqualTo=* * output: * { * "role_permissions":[{ * "role_id":"05f80052-2642-480a-8504-880e27ce8b57", * "permit_domain":"user_mgmt", * "permit_action":"*","permit_selection":"*" * }] * } * </pre> * @mtwSampleApiCall * <div style="word-wrap: break-word; width: 1024px"><pre> * // Create the role permission filter criteria model and set the role id and filter * RolePermissionFilterCriteria criteria = new RolePermissionFilterCriteria(); * criteria.roleId = UUID.valueOf("05f80052-2642-480a-8504-880e27ce8b57"); * criteria.filter = false; * * // Create the client and call the search API * RolePermissions client = new RolePermissions(properties); * RolePermissionCollection rolePermissions = client.search(criteria); * </pre></div> */ public RolePermissionCollection search(RolePermissionFilterCriteria criteria) { log.debug("target: {}", getTarget().getUri().toString()); HashMap<String,Object> map = new HashMap<>(); map.put("role_id", criteria.roleId); RolePermissionCollection rolePermissions = getTargetPathWithQueryParams("roles/{role_id}/permissions", criteria) .resolveTemplates(map).request(MediaType.APPLICATION_JSON).get(RolePermissionCollection.class); return rolePermissions; } }
Java
public class SocialTextCleaner { private static final String CHAR_FILTER = "[^\\p{L}\\p{M}\\p{N}\\p{P}\\p{Z}\\p{Cf}\\p{Cs}\\s]"; private static final String URL_FILTER = "(https?://)?(www\\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\\.[a-zA-Z0-9()]{1,6}\\b([-a-zA-Z0-9()@:%_+.~#?&/=]*)"; private static final String USERNAME_FILTER = "@[\\S]+"; private static final String HASHTAG_FILTER = "#"; private static final String SPACE_FILTER = "[\\s]+"; private SocialTextCleaner(){} public static String removeInvalidChars(String txt) { return txt.replaceAll(CHAR_FILTER, ""); } public static String removeURLS(String txt) { return txt.replaceAll(URL_FILTER, ""); } public static String removeHashtags(String txt) { return txt.replace(HASHTAG_FILTER, ""); } /** * Changes usernames based on the format "@[^\\s]+" to generic "Tom" */ public static String removeUsernames(String txt) { return txt.replaceAll(USERNAME_FILTER, "Tom"); } public static String removeExtraSpaces(String txt) { return txt.trim().replaceAll(SPACE_FILTER, " "); } /** * Applies all cleaning functions to a String * * {@link SocialTextCleaner#removeExtraSpaces(String)} * {@link SocialTextCleaner#removeInvalidChars(String)} * {@link SocialTextCleaner#removeURLS(String)} * {@link SocialTextCleaner#removeHashtags(String)} * {@link SocialTextCleaner#removeUsernames(String)} */ public static String clean(String txt) { String result = removeInvalidChars(txt); result = removeURLS(result); result = removeHashtags(result); result = removeUsernames(result); result = removeExtraSpaces(result); return result; } /** * Applies the clean process. * * {@link SocialTextCleaner#clean(String)} * * @param messages List of Strings to be cleaned */ public static void clean(List<String> messages) { messages.replaceAll(SocialTextCleaner::clean); } /** * Applies the clean process. * * {@link SocialTextCleaner#clean(String)} * * @param messages List of {@link SocialNetworkMessage} to be cleaned */ public static void clean(Collection<SocialNetworkMessage> messages) { messages.forEach(c -> c.setMessage(clean(c.getMessage()))); } }
Java
class Solution2 implements Solution { @Override public int[] intersection(int[] nums1, int[] nums2) { HashSet<Integer> set1 = new HashSet<>(); for (Integer n : nums1) set1.add(n); HashSet<Integer> set2 = new HashSet<>(); for (Integer n : nums2) set2.add(n); set1.retainAll(set2); int [] output = new int[set1.size()]; int idx = 0; for (int s : set1) output[idx++] = s; return output; } }
Java
public class Control { /** The control's x location */ protected int x; /** The control's y location */ protected int y; /** The control's width */ protected int width; /** The control's height */ protected int height; /** The parent of the control. */ protected Container parent; /** The control's next sibling. */ protected Control next; /** The control's previous sibling. */ protected Control prev; /** * Adds a timer to a control. Each time the timer ticks, a TIMER * event will be posted to the control. The timer does * not interrupt the program during its execution at the timer interval, * it is scheduled along with application events. The timer object * returned from this method can be passed to removeTimer() to * remove the timer. Under Windows, the timer has a minimum resolution * of 55ms due to the native Windows system clock resolution of 55ms. * * @param millis the timer tick interval in milliseconds * @see ControlEvent */ public Timer addTimer(int millis) { MainWindow win = MainWindow.getMainWindow(); return win.addTimer(this, millis); } /** * Removes a timer from a control. True is returned if the timer was * found and removed and false is returned if the timer could not be * found (meaning it was not active). */ public boolean removeTimer(Timer timer) { MainWindow win = MainWindow.getMainWindow(); return win.removeTimer(timer); } /** Returns the font metrics for a given font. */ public FontMetrics getFontMetrics(Font font) { MainWindow win = MainWindow.getMainWindow(); return win.getFontMetrics(font); } /** Sets or changes a control's position and size. */ public void setRect(int x, int y, int width, int height) { if (parent != null) repaint(); this.x = x; this.y = y; this.width = width; this.height = height; if (parent != null) repaint(); } /** * Returns a copy of the control's rectangle. A control's rectangle * defines its location and size. */ public Rect getRect() { return new Rect(this.x, this.y, this.width, this.height); } /** Returns the control's parent container. */ public Container getParent() { return parent; } /** Returns the next child in the parent's list of controls. */ public Control getNext() { return next; } /** * Returns true if the given x and y coordinate in the parent's * coordinate system is contained within this control. */ public boolean contains(int x, int y) { int rx = this.x; int ry = this.y; if (x < rx || x >= rx + this.width || y < ry || y > ry + this.height) return false; return true; } /** Redraws the control. */ public void repaint() { int x = 0; int y = 0; Control c = this; while (!(c instanceof Window)) { x += c.x; y += c.y; c = c.parent; if (c == null) return; } Window win = (Window)c; win.damageRect(x, y, this.width, this.height); } /// PROPOSED CHANGE // Move the functionality of createGraphics() to getGraphics() // and deprecate createGraphics() to be more compatible with the JDK /// PROPOSED CHANGE // Make getGraphics() recursive rather than iterative. It's a little // slower but permits supercontainers to modify the graphics as they // need to on the way up to Window. Suggested by Scott Cytacki. /** * Creates a Graphics object which can be used to draw in the control. * This method finds the surface associated with the control, creates * a graphics assoicated with it and translates the graphics to the * origin of the control. It does not set a clipping rectangle on the * graphics. @deprecated */ public Graphics createGraphics() { return getGraphics(); } /** * Creates a Graphics object which can be used to draw in the control. * This method finds the surface associated with the control, creates * a graphics assoicated with it and translates the graphics to the * origin of the control. It does not set a clipping rectangle on the * graphics. */ public Graphics getGraphics() { if (this instanceof Window) return new Graphics((Window)this); else if (parent!=null) { Graphics g = parent.getGraphics(); if (g!=null) g.translate(x,y); return g; } else return null; } /*public Graphics getGraphics() { int x = 0; int y = 0; Control c = this; while (!(c instanceof Window)) { x += c.x; y += c.y; c = c.parent; if (c == null) return null; } Window win = (Window)c; Graphics g = new Graphics(win); g.translate(x, y); return g; } */ /** * Posts an event. The event pass will be posted to this control * and all the parent controls of this control (all the containers * this control is within). * @see Event */ public void postEvent(Event event) { Control c; c = this; while (c != null) { c.onEvent(event); c = c.parent; } } /** * Called to process key, pen, control and other posted events. * @param event the event to process * @see Event * @see KeyEvent * @see PenEvent */ public void onEvent(Event event) { } /** * Called to draw the control. When this method is called, the graphics * object passed has been translated into the coordinate system of the * control and the area behind the control has * already been painted. The background is painted by the top-level * window control. * @param g the graphics object for drawing * @see Graphics */ public void onPaint(Graphics g) { } }
Java
@SpringBootApplication @EnableEurekaClient @EnableFeignClients @ServletComponentScan(value = "com.cloud.example.filter") public class ExampleSsoWebApplication { public static void main(String[] args) { SpringApplication.run(ExampleSsoWebApplication.class, args); } @Bean public AsyncTaskExecutor taskExecutor() { ThreadPoolTaskExecutor asyncTaskThreadPool = new ThreadPoolTaskExecutor(); asyncTaskThreadPool.setCorePoolSize(20); asyncTaskThreadPool.setMaxPoolSize(200); asyncTaskThreadPool.setQueueCapacity(11); asyncTaskThreadPool.setKeepAliveSeconds(30); asyncTaskThreadPool.setThreadFactory(new ThreadFactoryBuilder().setNameFormat("Async-sso-example-%d").build()); // rejection-policy:当pool已经达到max size的时候,如何处理新任务 // CALLER_RUNS:不在新线程中执行任务,而是由调用者所在的线程来执行 asyncTaskThreadPool.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); asyncTaskThreadPool.initialize(); return asyncTaskThreadPool; } /** * redisTemplate * * @param redisConnectionFactory * @return */ @Bean public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(redisConnectionFactory); // 使用Jackson2JsonRedisSerialize 替换默认序列化 Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(objectMapper); // 设置value的序列化规则和 key的序列化规则 redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.setValueSerializer(jackson2JsonRedisSerializer); redisTemplate.setHashKeySerializer(new StringRedisSerializer()); redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer); redisTemplate.afterPropertiesSet(); return redisTemplate; } }
Java
public class WampClientBuilder { private String uri; private String realm; private int nrReconnects = 0; private int reconnectInterval = DEFAULT_RECONNECT_INTERVAL; private boolean useStrictUriValidation = false; private boolean closeOnErrors = true; private EnumSet<WampRoles> roles; private List<WampSerialization> serializations = new ArrayList<WampSerialization>(); private String authId = null; private List<ClientSideAuthentication> authMethods = new ArrayList<ClientSideAuthentication>(); private IWampClientConnectionConfig connectionConfiguration = null; private IWampConnectorProvider connectorProvider = null; private ObjectMapper objectMapper = null; /** The default reconnect interval in milliseconds.<br>This is set to 5s */ public static final int DEFAULT_RECONNECT_INTERVAL = 5000; /** The minimum reconnect interval in milliseconds.<br>This is set to 100ms */ public static final int MIN_RECONNECT_INTERVAL = 100; /** * Construct a new WampClientBuilder object. */ public WampClientBuilder() { // Add the default roles roles = EnumSet.of( WampRoles.Caller, WampRoles.Callee, WampRoles.Publisher, WampRoles.Subscriber); WampSerialization.addDefaultSerializations(serializations); } /** * Builds a new {@link WampClient WAMP client} from the information given in this builder.<br> * At least the uri of the router and the name of the realm have to be * set for a proper operation. * @return The created WAMP client * @throws WampError if any parameter is not invalid */ public WampClient build() throws Exception { if (uri == null) throw new ApplicationError(ApplicationError.INVALID_URI); URI routerUri; try { routerUri = new URI(uri); } catch (Throwable t) { throw new ApplicationError(ApplicationError.INVALID_URI); } if (realm == null) throw new ApplicationError(ApplicationError.INVALID_REALM); try { UriValidator.validate(realm, useStrictUriValidation); } catch (Exception e) { throw new ApplicationError(ApplicationError.INVALID_REALM); } if (roles.size() == 0) { throw new ApplicationError(ApplicationError.INVALID_ROLES); } // Build the roles array from the roles set WampRoles[] rolesArray = new WampRoles[roles.size()]; int i = 0; for (WampRoles r : roles) { rolesArray[i] = r; i++; } if (serializations.size() == 0) { throw new ApplicationError(ApplicationError.INVALID_SERIALIZATIONS); } if (connectorProvider == null) throw new ApplicationError(ApplicationError.INVALID_CONNECTOR_PROVIDER); // Build a connector that can be used by the client afterwards // This can throw! IWampConnector connector = connectorProvider.createConnector(routerUri, connectionConfiguration, serializations); // Use default object mapper if (objectMapper == null) objectMapper = new ObjectMapper(); ClientConfiguration clientConfig = new ClientConfiguration( closeOnErrors, authId, authMethods, routerUri, realm, useStrictUriValidation, rolesArray, nrReconnects, reconnectInterval, connectorProvider, connector, objectMapper); return new WampClient(clientConfig); } /** * Sets the address of the router to which the new client shall connect. * @param uri The address of the router, e.g. ws://wamp.ws/ws * @return The {@link WampClientBuilder} object */ public WampClientBuilder withUri(String uri) { this.uri = uri; return this; } /** * Sets the name of the realm on the router which shall be used for the session. * @param realm The name of the realm to which shall be connected. * @return The {@link WampClientBuilder} object */ public WampClientBuilder withRealm(String realm) { this.realm = realm; return this; } /** * Adjusts the roles that this client should have in the session.<br> * By default a client will have all roles (caller, callee, publisher, subscriber). * Use this function to adjust the roles if not all are needed. * @param roles The set of roles that the client should fulfill in the session. * At least one role is required, otherwise the session can not be established. * @return The {@link WampClientBuilder} object */ public WampClientBuilder withRoles(WampRoles[] roles) { this.roles.clear(); if (roles == null) return this; // Will throw on build() for (WampRoles role : roles) { this.roles.add(role); } return this; } /** * Assigns a connector provider to the WampClient. This provider will be used to * establish connections to the server.<br> * By using a different ConnectorProvider a different transport framework can be used * for data exchange between client and server. * @param provider The {@link IWampConnectorProvider} that should be used * @return The {@link WampClientBuilder} object */ public WampClientBuilder withConnectorProvider(IWampConnectorProvider provider) { this.connectorProvider = provider; return this; } /** * Assigns additional configuration data for a connection that should be used.<br> * The type of this configuration data depends on the used {@link IWampConnectorProvider}.<br> * Depending on the provider this might be null or not. * @param configuration The {@link IWampClientConnectionConfig} that should be used * @return The {@link WampClientBuilder} object */ public WampClientBuilder withConnectionConfiguration(IWampClientConnectionConfig configuration) { this.connectionConfiguration = configuration; return this; } /** * Adjusts the serializations that this client supports in the session.<br> * By default a client will have all serializations (JSON, MessagePack).<br> * The order of the list indicates client preference to the router during * negotiation.<br> * Use this function to adjust the serializations if not all are needed or * a different order is desired. * @param serializations The set of serializations that the client supports. * @return The {@link WampClientBuilder} object */ public WampClientBuilder withSerializations(WampSerialization[] serializations) throws ApplicationError { this.serializations.clear(); if (serializations == null) return this; // Will throw on build() for (WampSerialization serialization : serializations) { if (serialization == WampSerialization.Invalid) throw new ApplicationError(ApplicationError.INVALID_SERIALIZATIONS); if (!this.serializations.contains(serialization)) this.serializations.add(serialization); } return this; } /** * Allows to activate or deactivate the validation of all WAMP Uris according to the * strict URI validation rules which are described in the WAMP specification. * By default the loose Uri validation rules will be used. * @param useStrictUriValidation true if strict Uri validation rules shall be applied, * false if loose Uris shall be used. * @return The {@link WampClientBuilder} object */ public WampClientBuilder withStrictUriValidation(boolean useStrictUriValidation) { this.useStrictUriValidation = useStrictUriValidation; return this; } /** * Sets whether the client should be closed when an error besides * a connection loss happens.<br> * Other reasons are the reception of invalid messages from the remote * or the abortion of the session by the remote.<br> * When this flag is set to true no reconnect attempts will be performed. * <br> * The default is true. This is to avoid endless reconnects in case of * a malfunctioning remote. * @param closeOnErrors True if the client should be closed on such * errors, false if not. * @return The {@link WampClientBuilder} object */ public WampClientBuilder withCloseOnErrors(boolean closeOnErrors) { this.closeOnErrors = closeOnErrors; return this; } /** * Sets the amount of reconnect attempts to perform to a dealer. * @param nrReconnects The amount of connects to perform. Must be > 0. * @return The {@link WampClientBuilder} object * @throws WampError if the nr of reconnects is negative */ public WampClientBuilder withNrReconnects(int nrReconnects) throws ApplicationError { if (nrReconnects < 0) throw new ApplicationError(ApplicationError.INVALID_PARAMETER); this.nrReconnects = nrReconnects; return this; } /** * Sets the amount of reconnect attempts to perform to a dealer * to infinite. * @return The {@link WampClientBuilder} object */ public WampClientBuilder withInfiniteReconnects() { this.nrReconnects = -1; return this; } /** * Sets the amount of time that should be waited until a reconnect attempt is performed.<br> * The default value is {@link #DEFAULT_RECONNECT_INTERVAL}. * @param interval The interval that should be waited until a reconnect attempt<br> * is performed. The interval must be bigger than {@link #MIN_RECONNECT_INTERVAL}. * @param unit The unit of the interval * @return The {@link WampClientBuilder} object * @throws WampError If the interval is invalid */ public WampClientBuilder withReconnectInterval(int interval, TimeUnit unit) throws ApplicationError { long intervalMs = unit.toMillis(interval); if (intervalMs < MIN_RECONNECT_INTERVAL || intervalMs > Integer.MAX_VALUE) throw new ApplicationError(ApplicationError.INVALID_RECONNECT_INTERVAL); this.reconnectInterval = (int)intervalMs; return this; } /** * Set the authId to use. If not called, no authId is used. * @param authId the authId * @return The {@link WampClientBuilder} object */ public WampClientBuilder withAuthId(String authId) { this.authId = authId; return this; } /** * Use a specific auth method. Can be called multiple times to specify multiple * supported auth methods. If this method is not called, anonymous auth is used. * @param authMethod The {@link ClientSideAuthentication} to add * @return The {@link WampClientBuilder} object */ public WampClientBuilder withAuthMethod(ClientSideAuthentication authMethod) { this.authMethods.add( authMethod ); return this; } /** * Set custom, pre-configured {@link ObjectMapper}. * This instance will be used instead of default for serialization and deserialization. * @param objectMapper The {@link ObjectMapper} instance * @return The {@link WampClientBuilder} object */ public WampClientBuilder withObjectMapper(ObjectMapper objectMapper) { this.objectMapper = objectMapper; return this; } }
Java
public class PointCircle implements IIntersectionSolver2 { public static final PointCircle instance = new PointCircle(); @Override public boolean solve(Geometry2D A, Geometry2D B) { Circle cir = (Circle) A; Point p = (Point) B; return cir.isInside(p.x, p.y); } }
Java
public class TestContext { private String managerToken; private Map<String, BridgeContext> bridges = new HashMap<>(); private Map<String, String> cloudEvents = new HashMap<>(); private Map<String, String> uuids = new HashMap<>(); private Scenario scenario; public TestContext() { } public String getManagerToken() { return this.managerToken; } public void setManagerToken(String managerToken) { this.managerToken = managerToken; } /** * This creates a new bridge in the test context * * @param testBridgeName Name of the new bridge so you are able to easily * reference it in your tests without having to care * about the uniqueness of the name * @param systemBridgeName Used name of the bridge on the system which will so * be unique on the system where the test happens * @return the new test bridge context */ public BridgeContext newBridge(String testBridgeName, String bridgeId, String systemBridgeName) { if (this.bridges.containsKey(testBridgeName)) { throw new RuntimeException("Bridge with name " + testBridgeName + " is already created in context."); } else { scenario.log("Creating new Bridge context with test name '" + testBridgeName + "' and system name '" + systemBridgeName + "'"); BridgeContext bridgeContext = new BridgeContext(this.scenario, bridgeId, systemBridgeName); this.bridges.put(testBridgeName, bridgeContext); } return getBridge(testBridgeName); } public void removeBridge(String testBridgeName) { this.bridges.get(testBridgeName).setDeleted(true); } public BridgeContext getBridge(String testBridgeName) { if (!this.bridges.containsKey(testBridgeName)) { throw new RuntimeException("Bridge with name " + testBridgeName + " does not exist in context."); } return this.bridges.get(testBridgeName); } public Map<String, BridgeContext> getAllBridges() { return this.bridges; } public String getUuid(String uuidName) { if (!this.uuids.containsKey(uuidName)) { String uuidValue = UUID.randomUUID().toString(); scenario.log("Generating new uuid '" + uuidName + "' value '" + uuidValue + "'"); this.uuids.put(uuidName, uuidValue); } return this.uuids.get(uuidName); } public Scenario getScenario() { return this.scenario; } public void setScenario(Scenario scenario) { this.scenario = scenario; } /** * @param testCloudEventId ID of the new Cloud event sent so you are able to * easily reference it in your tests without having to * care about the uniqueness of the name */ public void storeCloudEventInContext(String testCloudEventId) { if (cloudEvents.containsKey(testCloudEventId)) { throw new RuntimeException("Cloud event with id " + testCloudEventId + " is already created in context."); } String systemCloudEventId = UUID.randomUUID().toString(); scenario.log("Store cloud event with test id '" + testCloudEventId + "' and system id '" + systemCloudEventId + "'"); cloudEvents.put(testCloudEventId, systemCloudEventId); } public String getCloudEventSystemId(String testCloudEventId) { if (!cloudEvents.containsKey(testCloudEventId)) { throw new RuntimeException("Cloud event with id " + testCloudEventId + " not found."); } return cloudEvents.get(testCloudEventId); } }
Java
public class JndiLdapRealm extends AuthorizingRealm implements ICacheableAuthorizationRealm { private static final Logger LOGGER = LoggerFactory.getLogger(JndiLdapRealm.class); //The zero index currently means nothing, but could be utilized in the future for other substitution techniques. private static final String USERDN_SUBSTITUTION_TOKEN = "{0}"; private String userDnPrefix; private String userDnSuffix; //Matches the attributes of the external system to enable search private String phoneAttributeId; private String nameAttributeId; private String emailAttributeId; /*-------------------------------------------- | I N S T A N C E V A R I A B L E S | ============================================*/ /** * The LdapContextFactory instance used to acquire {@link javax.naming.ldap.LdapContext LdapContext}'s at runtime * to acquire connections to the LDAP directory to perform authentication attempts and authorizatino queries. */ private LdapContextFactory contextFactory; /*-------------------------------------------- | C O N S T R U C T O R S | ============================================*/ /** * Default no-argument constructor that defaults the internal {@link LdapContextFactory} instance to a * {@link JndiLdapContextFactory}. */ public JndiLdapRealm() { //Credentials Matching is not necessary - the LDAP directory will do it automatically: setCredentialsMatcher(new AllowAllCredentialsMatcher()); //Any Object principal and Object credentials may be passed to the LDAP provider, so accept any token: setAuthenticationTokenClass(AuthenticationToken.class); this.contextFactory = new JndiLdapContextFactory(); } /*-------------------------------------------- | A C C E S S O R S / M O D I F I E R S | ============================================*/ /** * Returns the User DN prefix to use when building a runtime User DN value or {@code null} if no * {@link #getUserDnTemplate() userDnTemplate} has been configured. If configured, this value is the text that * occurs before the {@link #USERDN_SUBSTITUTION_TOKEN} in the {@link #getUserDnTemplate() userDnTemplate} value. * * @return the the User DN prefix to use when building a runtime User DN value or {@code null} if no * {@link #getUserDnTemplate() userDnTemplate} has been configured. */ protected String getUserDnPrefix() { return userDnPrefix; } /** * Returns the User DN suffix to use when building a runtime User DN value. or {@code null} if no * {@link #getUserDnTemplate() userDnTemplate} has been configured. If configured, this value is the text that * occurs after the {@link #USERDN_SUBSTITUTION_TOKEN} in the {@link #getUserDnTemplate() userDnTemplate} value. * * @return the User DN suffix to use when building a runtime User DN value or {@code null} if no * {@link #getUserDnTemplate() userDnTemplate} has been configured. */ protected String getUserDnSuffix() { return userDnSuffix; } /*-------------------------------------------- | M E T H O D S | ============================================*/ /** * Sets the User Distinguished Name (DN) template to use when creating User DNs at runtime. A User DN is an LDAP * fully-qualified unique user identifier which is required to establish a connection with the LDAP * directory to authenticate users and query for authorization information. * <h2>Usage</h2> * User DN formats are unique to the LDAP directory's schema, and each environment differs - you will need to * specify the format corresponding to your directory. You do this by specifying the full User DN as normal, but * but you use a <b>{@code {0}}</b> placeholder token in the string representing the location where the * user's submitted principal (usually a username or uid) will be substituted at runtime. * <p/> * For example, if your directory * uses an LDAP {@code uid} attribute to represent usernames, the User DN for the {@code jsmith} user may look like * this: * <p/> * <pre>uid=jsmith,ou=users,dc=mycompany,dc=com</pre> * <p/> * in which case you would set this property with the following template value: * <p/> * <pre>uid=<b>{0}</b>,ou=users,dc=mycompany,dc=com</pre> * <p/> * If no template is configured, the raw {@code AuthenticationToken} * {@link AuthenticationToken#getPrincipal() principal} will be used as the LDAP principal. This is likely * incorrect as most LDAP directories expect a fully-qualified User DN as opposed to the raw uid or username. So, * ensure you set this property to match your environment! * * @param template the User Distinguished Name template to use for runtime substitution * @throws IllegalArgumentException if the template is null, empty, or does not contain the * {@code {0}} substitution token. * @see LdapContextFactory#getLdapContext(Object,Object) */ public void setUserDnTemplate(String template) throws IllegalArgumentException { if (!StringUtils.hasText(template)) { String msg = "User DN template cannot be null or empty."; throw new IllegalArgumentException(msg); } int index = template.indexOf(USERDN_SUBSTITUTION_TOKEN); if (index < 0) { String msg = "User DN template must contain the '" + USERDN_SUBSTITUTION_TOKEN + "' replacement token to understand where to " + "insert the runtime authentication principal."; throw new IllegalArgumentException(msg); } String prefix = template.substring(0, index); String suffix = template.substring(prefix.length() + USERDN_SUBSTITUTION_TOKEN.length()); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Determined user DN prefix [{}] and suffix [{}]", prefix, suffix); } this.userDnPrefix = prefix; this.userDnSuffix = suffix; } /** * Returns the User Distinguished Name (DN) template to use when creating User DNs at runtime - see the * {@link #setUserDnTemplate(String) setUserDnTemplate} JavaDoc for a full explanation. * * @return the User Distinguished Name (DN) template to use when creating User DNs at runtime. */ public String getUserDnTemplate() { return getUserDn(USERDN_SUBSTITUTION_TOKEN); } /** * Returns the LDAP User Distinguished Name (DN) to use when acquiring an * {@link javax.naming.ldap.LdapContext LdapContext} from the {@link LdapContextFactory}. * <p/> * If the the {@link #getUserDnTemplate() userDnTemplate} property has been set, this implementation will construct * the User DN by substituting the specified {@code principal} into the configured template. If the * {@link #getUserDnTemplate() userDnTemplate} has not been set, the method argument will be returned directly * (indicating that the submitted authentication token principal <em>is</em> the User DN). * * @param principal the principal to substitute into the configured {@link #getUserDnTemplate() userDnTemplate}. * @return the constructed User DN to use at runtime when acquiring an {@link javax.naming.ldap.LdapContext}. * @throws IllegalArgumentException if the method argument is null or empty * @throws IllegalStateException if the {@link #getUserDnTemplate userDnTemplate} has not been set. * @see LdapContextFactory#getLdapContext(Object, Object) */ protected String getUserDn(String principal) throws IllegalArgumentException, IllegalStateException { if (!StringUtils.hasText(principal)) { throw new IllegalArgumentException("User principal cannot be null or empty for User DN construction."); } String prefix = getUserDnPrefix(); String suffix = getUserDnSuffix(); if (prefix == null && suffix == null) { LOGGER.debug("userDnTemplate property has not been configured, indicating the submitted " + "AuthenticationToken's principal is the same as the User DN. Returning the method argument " + "as is."); return principal; } int prefixLength = prefix != null ? prefix.length() : 0; int suffixLength = suffix != null ? suffix.length() : 0; StringBuilder sb = new StringBuilder(prefixLength + principal.length() + suffixLength); if (prefixLength > 0) { sb.append(prefix); } sb.append(principal); if (suffixLength > 0) { sb.append(suffix); } return sb.toString(); } /** * Sets the LdapContextFactory instance used to acquire connections to the LDAP directory during authentication * attempts and authorization queries. Unless specified otherwise, the default is a {@link JndiLdapContextFactory} * instance. * * @param contextFactory the LdapContextFactory instance used to acquire connections to the LDAP directory during * authentication attempts and authorization queries */ public void setContextFactory(LdapContextFactory contextFactory) { this.contextFactory = contextFactory; } /** * Returns the LdapContextFactory instance used to acquire connections to the LDAP directory during authentication * attempts and authorization queries. Unless specified otherwise, the default is a {@link JndiLdapContextFactory} * instance. * * @return the LdapContextFactory instance used to acquire connections to the LDAP directory during * authentication attempts and authorization queries */ public LdapContextFactory getContextFactory() { return this.contextFactory; } /*-------------------------------------------- | M E T H O D S | ============================================*/ /** * Delegates to {@link #queryForAuthenticationInfo(org.apache.shiro.authc.AuthenticationToken, LdapContextFactory)}, * wrapping any {@link NamingException}s in a Shiro {@link AuthenticationException} to satisfy the parent method * signature. * * @param token the authentication token containing the user's principal and credentials. * @return the {@link AuthenticationInfo} acquired after a successful authentication attempt * @throws AuthenticationException if the authentication attempt fails or if a * {@link NamingException} occurs. */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { AuthenticationInfo info; try { info = queryForAuthenticationInfo(token, getContextFactory()); } catch (AuthenticationNotSupportedException e) { String msg = "Unsupported configured authentication mechanism"; throw new UnsupportedAuthenticationMechanismException(msg, e); } catch (javax.naming.AuthenticationException e) { throw new AuthenticationException("LDAP authentication failed.", e); } catch (NamingException e) { String msg = "LDAP naming error while attempting to authenticate user."; throw new AuthenticationException(msg, e); } return info; } @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { AuthorizationInfo info; try { info = queryForAuthorizationInfo(principals, getContextFactory()); } catch (NamingException e) { String msg = "LDAP naming error while attempting to retrieve authorization for user [" + principals + "]."; throw new AuthorizationException(msg, e); } return info; } /** * Returns the principal to use when creating the LDAP connection for an authentication attempt. * <p/> * This implementation uses a heuristic: it checks to see if the specified token's * {@link AuthenticationToken#getPrincipal() principal} is a {@code String}, and if so, * {@link #getUserDn(String) converts it} from what is * assumed to be a raw uid or username {@code String} into a User DN {@code String}. Almost all LDAP directories * expect the authentication connection to present a User DN and not an unqualified username or uid. * <p/> * If the token's {@code principal} is not a String, it is assumed to already be in the format supported by the * underlying {@link LdapContextFactory} implementation and the raw principal is returned directly. * * @param token the {@link AuthenticationToken} submitted during the authentication process * @return the User DN or raw principal to use to acquire the LdapContext. * @see LdapContextFactory#getLdapContext(Object, Object) */ protected Object getLdapPrincipal(AuthenticationToken token) { Object principal = token.getPrincipal(); if (principal instanceof String) { String sPrincipal = (String) principal; return getUserDn(sPrincipal); } return principal; } /** * This implementation opens an LDAP connection using the token's * {@link #getLdapPrincipal(org.apache.shiro.authc.AuthenticationToken) discovered principal} and provided * {@link AuthenticationToken#getCredentials() credentials}. If the connection opens successfully, the * authentication attempt is immediately considered successful and a new * {@link AuthenticationInfo} instance is * {@link #createAuthenticationInfo(org.apache.shiro.authc.AuthenticationToken, Object, Object, javax.naming.ldap.LdapContext) created} * and returned. If the connection cannot be opened, either because LDAP authentication failed or some other * JNDI problem, an {@link NamingException} will be thrown. * * @param token the submitted authentication token that triggered the authentication attempt. * @param ldapContextFactory factory used to retrieve LDAP connections. * @return an {@link AuthenticationInfo} instance representing the authenticated user's information. * @throws NamingException if any LDAP errors occur. */ // LdapContext ctx = null; // public LdapContext getContext() { // return this.ctx; // } Hashtable<?,?> environment=null; public Hashtable<?,?> getEnvironment() { return environment; } protected AuthenticationInfo queryForAuthenticationInfo(AuthenticationToken token, LdapContextFactory ldapContextFactory) throws NamingException { Object principal = token.getPrincipal(); Object credentials = token.getCredentials(); LOGGER.debug("Authenticating user '{}' through LDAP", principal); principal = getLdapPrincipal(token); LdapContext ctx = null; try { ctx = ldapContextFactory.getLdapContext(principal, credentials); environment= ctx.getEnvironment(); //context was opened successfully, which means their credentials were valid. Return the AuthenticationInfo: return createAuthenticationInfo(token, principal, credentials, ctx); } finally { LdapUtils.closeContext(ctx); } } /** * Returns the {@link AuthenticationInfo} resulting from a Subject's successful LDAP authentication attempt. * <p/> * This implementation ignores the {@code ldapPrincipal}, {@code ldapCredentials}, and the opened * {@code ldapContext} arguments and merely returns an {@code AuthenticationInfo} instance mirroring the * submitted token's principal and credentials. This is acceptable because this method is only ever invoked after * a successful authentication attempt, which means the provided principal and credentials were correct, and can * be used directly to populate the (now verified) {@code AuthenticationInfo}. * <p/> * Subclasses however are free to override this method for more advanced construction logic. * * @param token the submitted {@code AuthenticationToken} that resulted in a successful authentication * @param ldapPrincipal the LDAP principal used when creating the LDAP connection. Unlike the token's * {@link AuthenticationToken#getPrincipal() principal}, this value is usually a constructed * User DN and not a simple username or uid. The exact value is depending on the * configured * <a href="http://download-llnw.oracle.com/javase/tutorial/jndi/ldap/auth_mechs.html"> * LDAP authentication mechanism</a> in use. * @param ldapCredentials the LDAP credentials used when creating the LDAP connection. * @param ldapContext the LdapContext created that resulted in a successful authentication. It can be used * further by subclasses for more complex operations. It does not need to be closed - * it will be closed automatically after this method returns. * @return the {@link AuthenticationInfo} resulting from a Subject's successful LDAP authentication attempt. * @throws NamingException if there was any problem using the {@code LdapContext} */ protected AuthenticationInfo createAuthenticationInfo(AuthenticationToken token, Object ldapPrincipal, Object ldapCredentials, LdapContext ldapContext) throws NamingException { return new SimpleAuthenticationInfo(token.getPrincipal(), token.getCredentials(), getName()); } /** * Method that should be implemented by subclasses to build an * {@link AuthorizationInfo} object by querying the LDAP context for the * specified principal.</p> * * @param principals the principals of the Subject whose AuthenticationInfo should be queried from the LDAP server. * @param ldapContextFactory factory used to retrieve LDAP connections. * @return an {@link AuthorizationInfo} instance containing information retrieved from the LDAP server. * @throws NamingException if any LDAP errors occur during the search. */ protected AuthorizationInfo queryForAuthorizationInfo(PrincipalCollection principals, LdapContextFactory ldapContextFactory) throws NamingException { return null; } /** * @return the phoneAttributeId */ public String getPhoneAttributeId() { return phoneAttributeId; } /** * @param phoneAttributeId the phoneAttributeId to set */ public void setPhoneAttributeId(String phoneAttributeId) { this.phoneAttributeId = phoneAttributeId; } /** * @return the nameAttributeId */ public String getNameAttributeId() { return nameAttributeId; } /** * @param nameAttributeId the nameAttributeId to set */ public void setNameAttributeId(String nameAttributeId) { this.nameAttributeId = nameAttributeId; } /** * @return the emailAttributeId */ public String getEmailAttributeId() { return emailAttributeId; } /** * @param emailAttributeId the emailAttributeId to set */ public void setEmailAttributeId(String emailAttributeId) { this.emailAttributeId = emailAttributeId; } @Override public void clearAuthorizationCache() { clearCachedAuthorizationInfo(SecurityUtils.getSubject().getPrincipals()); } }