repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
antlr/codebuff | output/java_guava/1.4.18/AbstractService.java | 19642 | /*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.common.util.concurrent;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.util.concurrent.Service.State.FAILED;
import static com.google.common.util.concurrent.Service.State.NEW;
import static com.google.common.util.concurrent.Service.State.RUNNING;
import static com.google.common.util.concurrent.Service.State.STARTING;
import static com.google.common.util.concurrent.Service.State.STOPPING;
import static com.google.common.util.concurrent.Service.State.TERMINATED;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.util.concurrent.ListenerCallQueue.Callback;
import com.google.common.util.concurrent.Monitor.Guard;
import com.google.common.util.concurrent.Service.State; // javadoc needs this
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.j2objc.annotations.WeakOuter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import javax.annotation.Nullable;
import javax.annotation.concurrent.GuardedBy;
import javax.annotation.concurrent.Immutable;
/**
* Base class for implementing services that can handle {@link #doStart} and {@link #doStop}
* requests, responding to them with {@link #notifyStarted()} and {@link #notifyStopped()}
* callbacks. Its subclasses must manage threads manually; consider {@link
* AbstractExecutionThreadService} if you need only a single execution thread.
*
* @author Jesse Wilson
* @author Luke Sandberg
* @since 1.0
*/
@Beta
@GwtIncompatible
public abstract class AbstractService implements Service {
private static final Callback<Listener> STARTING_CALLBACK = new Callback<Listener>("starting()") {
@Override
void call(Listener listener) {
listener.starting();
}
};
private static final Callback<Listener> RUNNING_CALLBACK = new Callback<Listener>("running()") {
@Override
void call(Listener listener) {
listener.running();
}
};
private static final Callback<Listener> STOPPING_FROM_STARTING_CALLBACK = stoppingCallback(STARTING);
private static final Callback<Listener> STOPPING_FROM_RUNNING_CALLBACK = stoppingCallback(RUNNING);
private static final Callback<Listener> TERMINATED_FROM_NEW_CALLBACK = terminatedCallback(NEW);
private static final Callback<Listener> TERMINATED_FROM_RUNNING_CALLBACK = terminatedCallback(RUNNING);
private static final Callback<Listener> TERMINATED_FROM_STOPPING_CALLBACK = terminatedCallback(STOPPING);
private static Callback<Listener> terminatedCallback(final State from) {
return new Callback<Listener>("terminated({from = " + from + "})") {
@Override
void call(Listener listener) {
listener.terminated(from);
}
};
}
private static Callback<Listener> stoppingCallback(final State from) {
return new Callback<Listener>("stopping({from = " + from + "})") {
@Override
void call(Listener listener) {
listener.stopping(from);
}
};
}
private final Monitor monitor = new Monitor();
private final Guard isStartable = new IsStartableGuard();
@WeakOuter
private final class IsStartableGuard extends Guard {
IsStartableGuard() {
super(AbstractService.this.monitor);
}
@Override
public boolean isSatisfied() {
return state() == NEW;
}
}
private final Guard isStoppable = new IsStoppableGuard();
@WeakOuter
private final class IsStoppableGuard extends Guard {
IsStoppableGuard() {
super(AbstractService.this.monitor);
}
@Override
public boolean isSatisfied() {
return state().compareTo(RUNNING) <= 0;
}
}
private final Guard hasReachedRunning = new HasReachedRunningGuard();
@WeakOuter
private final class HasReachedRunningGuard extends Guard {
HasReachedRunningGuard() {
super(AbstractService.this.monitor);
}
@Override
public boolean isSatisfied() {
return state().compareTo(RUNNING) >= 0;
}
}
private final Guard isStopped = new IsStoppedGuard();
@WeakOuter
private final class IsStoppedGuard extends Guard {
IsStoppedGuard() {
super(AbstractService.this.monitor);
}
@Override
public boolean isSatisfied() {
return state().isTerminal();
}
}
/**
* The listeners to notify during a state transition.
*/
@GuardedBy("monitor")
private final List<ListenerCallQueue<Listener>> listeners = Collections.synchronizedList(new ArrayList<ListenerCallQueue<Listener>>());
/**
* The current state of the service. This should be written with the lock held but can be read
* without it because it is an immutable object in a volatile field. This is desirable so that
* methods like {@link #state}, {@link #failureCause} and notably {@link #toString} can be run
* without grabbing the lock.
*
* <p>To update this field correctly the lock must be held to guarantee that the state is
* consistent.
*/
@GuardedBy("monitor")
private volatile StateSnapshot snapshot = new StateSnapshot(NEW);
/** Constructor for use by subclasses. */
protected AbstractService() {}
/**
* This method is called by {@link #startAsync} to initiate service startup. The invocation of
* this method should cause a call to {@link #notifyStarted()}, either during this method's run,
* or after it has returned. If startup fails, the invocation should cause a call to {@link
* #notifyFailed(Throwable)} instead.
*
* <p>This method should return promptly; prefer to do work on a different thread where it is
* convenient. It is invoked exactly once on service startup, even when {@link #startAsync} is
* called multiple times.
*/
protected abstract void doStart();
/**
* This method should be used to initiate service shutdown. The invocation of this method should
* cause a call to {@link #notifyStopped()}, either during this method's run, or after it has
* returned. If shutdown fails, the invocation should cause a call to {@link
* #notifyFailed(Throwable)} instead.
*
* <p>This method should return promptly; prefer to do work on a different thread where it is
* convenient. It is invoked exactly once on service shutdown, even when {@link #stopAsync} is
* called multiple times.
*/
protected abstract void doStop();
@CanIgnoreReturnValue
@Override
public final Service startAsync() {
if (monitor.enterIf(isStartable)) {
try {
snapshot = new StateSnapshot(STARTING);
starting();
doStart();
} catch (Throwable startupFailure) {
notifyFailed(startupFailure);
} finally {
monitor.leave();
executeListeners();
}
} else {
throw new IllegalStateException("Service " + this + " has already been started");
}
return this;
}
@CanIgnoreReturnValue
@Override
public final Service stopAsync() {
if (monitor.enterIf(isStoppable)) {
try {
State previous = state();
switch (previous) {
case NEW:
snapshot = new StateSnapshot(TERMINATED);
terminated(NEW);
break;
case STARTING:
snapshot = new StateSnapshot(STARTING, true, null);
stopping(STARTING);
break;
case RUNNING:
snapshot = new StateSnapshot(STOPPING);
stopping(RUNNING);
doStop();
break;
case STOPPING:
case TERMINATED:
case FAILED:
// These cases are impossible due to the if statement above.
throw new AssertionError("isStoppable is incorrectly implemented, saw: " + previous);
default:
throw new AssertionError("Unexpected state: " + previous);
}
} catch (Throwable shutdownFailure) {
notifyFailed(shutdownFailure);
} finally {
monitor.leave();
executeListeners();
}
}
return this;
}
@Override
public final void awaitRunning() {
monitor.enterWhenUninterruptibly(hasReachedRunning);
try {
checkCurrentState(RUNNING);
} finally {
monitor.leave();
}
}
@Override
public final void awaitRunning(long timeout, TimeUnit unit) throws TimeoutException {
if (monitor.enterWhenUninterruptibly(hasReachedRunning, timeout, unit)) {
try {
checkCurrentState(RUNNING);
} finally {
monitor.leave();
}
} else {
// It is possible due to races the we are currently in the expected state even though we
// timed out. e.g. if we weren't event able to grab the lock within the timeout we would never
// even check the guard. I don't think we care too much about this use case but it could lead
// to a confusing error message.
throw new TimeoutException("Timed out waiting for " + this + " to reach the RUNNING state.");
}
}
@Override
public final void awaitTerminated() {
monitor.enterWhenUninterruptibly(isStopped);
try {
checkCurrentState(TERMINATED);
} finally {
monitor.leave();
}
}
@Override
public final void awaitTerminated(long timeout, TimeUnit unit) throws TimeoutException {
if (monitor.enterWhenUninterruptibly(isStopped, timeout, unit)) {
try {
checkCurrentState(TERMINATED);
} finally {
monitor.leave();
}
} else {
// It is possible due to races the we are currently in the expected state even though we
// timed out. e.g. if we weren't event able to grab the lock within the timeout we would never
// even check the guard. I don't think we care too much about this use case but it could lead
// to a confusing error message.
throw new TimeoutException("Timed out waiting for " + this + " to reach a terminal state. "
+ "Current state: "
+ state());
}
}
/** Checks that the current state is equal to the expected state. */
@GuardedBy("monitor")
private void checkCurrentState(State expected) {
State actual = state();
if (actual != expected) {
if (actual == FAILED) {
// Handle this specially so that we can include the failureCause, if there is one.
throw new IllegalStateException("Expected the service " + this + " to be " + expected
+ ", but the service has FAILED",
failureCause());
}
throw new IllegalStateException("Expected the service " + this + " to be " + expected + ", but was " + actual);
}
}
/**
* Implementing classes should invoke this method once their service has started. It will cause
* the service to transition from {@link State#STARTING} to {@link State#RUNNING}.
*
* @throws IllegalStateException if the service is not {@link State#STARTING}.
*/
protected final void notifyStarted() {
monitor.enter();
try {
// We have to examine the internal state of the snapshot here to properly handle the stop
// while starting case.
if (snapshot.state != STARTING) {
IllegalStateException failure = new IllegalStateException("Cannot notifyStarted() when the service is " + snapshot.state);
notifyFailed(failure);
throw failure;
}
if (snapshot.shutdownWhenStartupFinishes) {
snapshot = new StateSnapshot(STOPPING);
// We don't call listeners here because we already did that when we set the
// shutdownWhenStartupFinishes flag.
doStop();
} else {
snapshot = new StateSnapshot(RUNNING);
running();
}
} finally {
monitor.leave();
executeListeners();
}
}
/**
* Implementing classes should invoke this method once their service has stopped. It will cause
* the service to transition from {@link State#STOPPING} to {@link State#TERMINATED}.
*
* @throws IllegalStateException if the service is neither {@link State#STOPPING} nor {@link
* State#RUNNING}.
*/
protected final void notifyStopped() {
monitor.enter();
try {
// We check the internal state of the snapshot instead of state() directly so we don't allow
// notifyStopped() to be called while STARTING, even if stop() has already been called.
State previous = snapshot.state;
if (previous != STOPPING && previous != RUNNING) {
IllegalStateException failure = new IllegalStateException("Cannot notifyStopped() when the service is " + previous);
notifyFailed(failure);
throw failure;
}
snapshot = new StateSnapshot(TERMINATED);
terminated(previous);
} finally {
monitor.leave();
executeListeners();
}
}
/**
* Invoke this method to transition the service to the {@link State#FAILED}. The service will
* <b>not be stopped</b> if it is running. Invoke this method when a service has failed critically
* or otherwise cannot be started nor stopped.
*/
protected final void notifyFailed(Throwable cause) {
checkNotNull(cause);
monitor.enter();
try {
State previous = state();
switch (previous) {
case NEW:
case TERMINATED:
throw new IllegalStateException("Failed while in state:" + previous, cause);
case RUNNING:
case STARTING:
case STOPPING:
snapshot = new StateSnapshot(FAILED, false, cause);
failed(previous, cause);
break;
case FAILED:
// Do nothing
break;
default:
throw new AssertionError("Unexpected state: " + previous);
}
} finally {
monitor.leave();
executeListeners();
}
}
@Override
public final boolean isRunning() {
return state() == RUNNING;
}
@Override
public final State state() {
return snapshot.externalState();
}
/**
* @since 14.0
*/
@Override
public final Throwable failureCause() {
return snapshot.failureCause();
}
/**
* @since 13.0
*/
@Override
public final void addListener(Listener listener, Executor executor) {
checkNotNull(listener, "listener");
checkNotNull(executor, "executor");
monitor.enter();
try {
if (!state().isTerminal()) {
listeners.add(new ListenerCallQueue<Listener>(listener, executor));
}
} finally {
monitor.leave();
}
}
@Override
public String toString() {
return getClass().getSimpleName() + " [" + state() + "]";
}
/**
* Attempts to execute all the listeners in {@link #listeners} while not holding the
* {@link #monitor}.
*/
private void executeListeners() {
if (!monitor.isOccupiedByCurrentThread()) {
// iterate by index to avoid concurrent modification exceptions
for (int i = 0; i < listeners.size(); i++) {
listeners.get(i).execute();
}
}
}
@GuardedBy("monitor")
private void starting() {
STARTING_CALLBACK.enqueueOn(listeners);
}
@GuardedBy("monitor")
private void running() {
RUNNING_CALLBACK.enqueueOn(listeners);
}
@GuardedBy("monitor")
private void stopping(final State from) {
if (from == State.STARTING) {
STOPPING_FROM_STARTING_CALLBACK.enqueueOn(listeners);
} else if (from == State.RUNNING) {
STOPPING_FROM_RUNNING_CALLBACK.enqueueOn(listeners);
} else {
throw new AssertionError();
}
}
@GuardedBy("monitor")
private void terminated(final State from) {
switch (from) {
case NEW:
TERMINATED_FROM_NEW_CALLBACK.enqueueOn(listeners);
break;
case RUNNING:
TERMINATED_FROM_RUNNING_CALLBACK.enqueueOn(listeners);
break;
case STOPPING:
TERMINATED_FROM_STOPPING_CALLBACK.enqueueOn(listeners);
break;
case STARTING:
case TERMINATED:
case FAILED:
default:
throw new AssertionError();
}
}
@GuardedBy("monitor")
private void failed(
final State from, final Throwable cause) {
// can't memoize this one due to the exception
new Callback<Listener>("failed({from = " + from + ", cause = " + cause + "})") {
@Override
void call(Listener listener) {
listener.failed(from, cause);
}
}.enqueueOn(listeners);
}
/**
* An immutable snapshot of the current state of the service. This class represents a consistent
* snapshot of the state and therefore it can be used to answer simple queries without needing to
* grab a lock.
*/
@Immutable
private static final class StateSnapshot {
/**
* The internal state, which equals external state unless shutdownWhenStartupFinishes is true.
*/
final State state;
/**
* If true, the user requested a shutdown while the service was still starting up.
*/
final boolean shutdownWhenStartupFinishes;
/**
* The exception that caused this service to fail. This will be {@code null} unless the service
* has failed.
*/
@Nullable final Throwable failure;
StateSnapshot(State internalState) {
this(internalState, false, null);
}
StateSnapshot(State internalState, boolean shutdownWhenStartupFinishes, @Nullable Throwable failure) {
checkArgument(!shutdownWhenStartupFinishes || internalState == STARTING, "shudownWhenStartupFinishes can only be set if state is STARTING. Got %s instead.", internalState);
checkArgument(!(failure != null ^ internalState == FAILED),
"A failure cause should be set if and only if the state is failed. Got %s and %s "
+ "instead.", internalState, failure);
this.state = internalState;
this.shutdownWhenStartupFinishes = shutdownWhenStartupFinishes;
this.failure = failure;
}
/** @see Service#state() */
State externalState() {
if (shutdownWhenStartupFinishes && state == STARTING) {
return STOPPING;
} else {
return state;
}
}
/** @see Service#failureCause() */
Throwable failureCause() {
checkState(state == FAILED,
"failureCause() is only valid if the service has failed, service is %s",
state);
return failure;
}
}
} | bsd-2-clause |
vilmospapp/jodd | jodd-proxetta/src/test/java/jodd/proxetta/advice/DelegateAdviceTest.java | 2534 | // Copyright (c) 2003-present, Jodd Team (http://jodd.org)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
package jodd.proxetta.advice;
import jodd.proxetta.fixtures.data.Calc;
import jodd.proxetta.fixtures.data.CalcImpl;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.fail;
public class DelegateAdviceTest {
@Test
public void testCalcImplDelegate() {
CalcImpl calc = new CalcImpl();
Calc newCalc = DelegateAdviceUtil.applyAdvice(CalcImpl.class);
DelegateAdviceUtil.injectTargetIntoProxy(newCalc, calc);
assertNotEquals(newCalc.getClass(), calc.getClass());
assertEquals(calc.calculate(2, 8), newCalc.calculate(2, 8));
assertEquals(calc.calculate(2L, 8L), newCalc.calculate(2L, 8L));
assertEquals(calc.calculate(2.5d, 8.5d), newCalc.calculate(2.5d, 8.5d), 0.1);
assertEquals(calc.calculate(2.5f, 8.5f), newCalc.calculate(2.5f, 8.5f), 0.1);
assertEquals(calc.calculate((byte)2, (byte)8), newCalc.calculate((byte)2, (byte)8));
assertEquals(calc.calculate((short)2, (short)8), newCalc.calculate((short)2, (short)8));
try {
newCalc.hello();
} catch (Exception ex) {
ex.printStackTrace();
fail(ex.toString());
}
}
} | bsd-2-clause |
clementval/claw-compiler | cx2t/src/claw/tatsu/analysis/dependency/DependenceDirection.java | 310 | /*
* This file is released under terms of BSD license
* See LICENSE file for more information
*/
package claw.tatsu.analysis.dependency;
/**
* Small enumeration that indicates the direction of a loop dependency.
*
* @author clementval
*/
public enum DependenceDirection {
FORWARD, BACKWARD, NONE
}
| bsd-2-clause |
yajunyang/BioImage | lib/VIB-lib-master/src/main/java/landmarks/FineTuneThread.java | 3764 | /* -*- mode: java; c-basic-offset: 8; indent-tabs-mode: t; tab-width: 8 -*- */
package landmarks;
import ij.ImagePlus;
import pal.math.ConjugateDirectionSearch;
/* This can all get very confusing, so to make my convention clear:
green channel == fixed image == current image
magenta channel == transformed image == cropped template image
So we're transforming the template onto the current image.
templatePoint is in the template
guessedPoint is in the current image
*/
public class FineTuneThread extends Thread {
boolean keepResults = true;
int method;
double cubeSide;
ImagePlus croppedTemplate;
ImagePlus template;
NamedPointWorld templatePoint;
ImagePlus newImage;
NamedPointWorld guessedPoint;
double [] initialTransformation;
double [] guessedTransformation;
ProgressWindow progressWindow;
FineTuneProgressListener listener;
public void setInitialTransformation( double [] initialTransformation ) {
if( initialTransformation.length != 6 )
throw new RuntimeException( "initialTransformation passed to FineTuneThread must be 6 in length" );
this.initialTransformation = initialTransformation;
}
public FineTuneThread(
int method,
double cubeSide,
ImagePlus croppedTemplate, // The cropped template image.
ImagePlus template, // The full template image.
NamedPointWorld templatePoint,
ImagePlus newImage, // The full current image.
NamedPointWorld guessedPoint,
double [] initialTransformation,
double [] guessedTransformation,
ProgressWindow progressWindow, // May be null if there's no GUI
FineTuneProgressListener listener ) {
this.method = method;
this.cubeSide = cubeSide;
this.croppedTemplate = croppedTemplate;
this.template = template;
this.templatePoint = templatePoint;
this.newImage = newImage;
this.guessedPoint = guessedPoint;
if( initialTransformation != null && initialTransformation.length != 6 )
throw new RuntimeException( "initialTransformation passed to FineTuneThread must be 6 in length" );
this.initialTransformation = initialTransformation;
if( guessedTransformation != null && guessedTransformation.length != 6 )
throw new RuntimeException( "guessedTransformation passed to FineTuneThread must be 6 in length, if non-null" );
this.guessedTransformation = guessedTransformation;
this.progressWindow = progressWindow;
this.listener = listener;
}
ConjugateDirectionSearch optimizer;
@Override
public void run() {
double [] startValues = initialTransformation.clone();
optimizer = new ConjugateDirectionSearch();
optimizer.step = 1;
optimizer.scbd = 10.0;
optimizer.illc = true;
TransformationAttempt attempt = new TransformationAttempt(
cubeSide,
croppedTemplate,
templatePoint,
newImage,
guessedPoint,
method,
listener,
progressWindow );
optimizer.optimize(attempt, startValues, 2, 2);
if( pleaseStop ) {
listener.fineTuneThreadFinished( FineTuneProgressListener.CANCELLED, null, this );
return;
}
// Now it should be optimized such that our result
// is in startValues.
/*
System.out.println("startValues now: ");
NamePoints.printParameters(startValues);
*/
if( pleaseStop ) {
listener.fineTuneThreadFinished( FineTuneProgressListener.CANCELLED, null, this );
return;
}
// Now reproduce those results; they might be good...
RegistrationResult r = NamePoints.mapImageWith(
croppedTemplate,
newImage,
templatePoint,
guessedPoint,
startValues,
cubeSide,
method,
"score: ");
listener.fineTuneThreadFinished( FineTuneProgressListener.COMPLETED, r, this );
}
volatile boolean pleaseStop = false;
public void askToFinish() {
pleaseStop = true;
if( optimizer != null )
optimizer.interrupt = true;
}
}
| bsd-2-clause |
runelite/runelite | runelite-client/src/main/java/net/runelite/client/plugins/cluescrolls/clues/CrypticClue.java | 62334 | /*
* Copyright (c) 2018, Lotto <https://github.com/devLotto>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package net.runelite.client.plugins.cluescrolls.clues;
import com.google.common.collect.ImmutableList;
import java.awt.Color;
import java.awt.Graphics2D;
import java.util.List;
import javax.annotation.Nullable;
import lombok.Getter;
import net.runelite.api.NPC;
import static net.runelite.api.NullObjectID.NULL_1293;
import net.runelite.api.ObjectComposition;
import static net.runelite.api.ObjectID.*;
import net.runelite.api.TileObject;
import net.runelite.api.coords.LocalPoint;
import net.runelite.api.coords.WorldPoint;
import static net.runelite.client.plugins.cluescrolls.ClueScrollOverlay.TITLED_CONTENT_COLOR;
import net.runelite.client.plugins.cluescrolls.ClueScrollPlugin;
import static net.runelite.client.plugins.cluescrolls.ClueScrollWorldOverlay.CLICKBOX_BORDER_COLOR;
import static net.runelite.client.plugins.cluescrolls.ClueScrollWorldOverlay.CLICKBOX_FILL_COLOR;
import static net.runelite.client.plugins.cluescrolls.ClueScrollWorldOverlay.CLICKBOX_HOVER_BORDER_COLOR;
import static net.runelite.client.plugins.cluescrolls.ClueScrollWorldOverlay.IMAGE_Z_OFFSET;
import net.runelite.client.ui.overlay.OverlayUtil;
import net.runelite.client.ui.overlay.components.LineComponent;
import net.runelite.client.ui.overlay.components.PanelComponent;
import net.runelite.client.ui.overlay.components.TitleComponent;
@Getter
public class CrypticClue extends ClueScroll implements TextClueScroll, NpcClueScroll, ObjectClueScroll
{
public static final List<CrypticClue> CLUES = ImmutableList.of(
new CrypticClue("Show this to Sherlock.", "Sherlock", new WorldPoint(2733, 3415, 0), "Sherlock is located to the east of the Sorcerer's tower in Seers' Village."),
new CrypticClue("Talk to the bartender of the Rusty Anchor in Port Sarim.", "Bartender", new WorldPoint(3045, 3256, 0), "The Rusty Anchor is located in the north of Port Sarim."),
new CrypticClue("The keeper of Melzars... Spare? Skeleton? Anar?", "Oziach", new WorldPoint(3068, 3516, 0), "Speak to Oziach in Edgeville."),
new CrypticClue("Speak to Ulizius.", "Ulizius", new WorldPoint(3444, 3461, 0), "Ulizius is the monk who guards the gate into Mort Myre Swamp. South of fairy ring CKS."),
new CrypticClue("Search for a crate in a building in Hemenster.", CRATE_357, new WorldPoint(2636, 3453, 0), "House northwest of the Ranging Guild. West of Grandpa Jack."),
new CrypticClue("A reck you say; let's pray there aren't any ghosts.", "Father Aereck", new WorldPoint(3242, 3207, 0), "Speak to Father Aereck in Lumbridge."),
new CrypticClue("Search the bucket in the Port Sarim jail.", BUCKET_9568, new WorldPoint(3013, 3179, 0), "Talk to Shantay & identify yourself as an outlaw, refuse to pay the 5gp fine twice and you will be sent to the Port Sarim jail."),
new CrypticClue("Search the crates in a bank in Varrock.", CRATE_5107, new WorldPoint(3187, 9825, 0), "Search in the basement of the West Varrock bank."),
new CrypticClue("Falo the bard wants to see you.", "Falo the Bard", new WorldPoint(2689, 3550, 0), "Speak to Falo the Bard located between Seers' Village and Rellekka. Southwest of fairy ring CJR."),
new CrypticClue("Search a bookcase in the Wizards tower.", BOOKCASE_12539, new WorldPoint(3113, 3159, 0), "The bookcase located on the ground floor of the Wizards' Tower. Fairy ring DIS."),
new CrypticClue("Come have a cip with this great soot covered denizen.", "Miner Magnus", new WorldPoint(2527, 3891, 0), "Talk to Miner Magnus on Miscellania, east of the fairy ring CIP. Answer: 8", "How many coal rocks are around here?"),
new CrypticClue("Citric cellar.", "Heckel Funch", new WorldPoint(2490, 3488, 0), "Speak to Heckel Funch on the first floor in the Grand Tree."),
new CrypticClue("I burn between heroes and legends.", "Candle maker", new WorldPoint(2799, 3438, 0), "Speak to the Candle maker in Catherby."),
new CrypticClue("Speak to Sarah at Falador farm.", "Sarah", new WorldPoint(3038, 3292, 0), "Talk to Sarah at Falador farm, north of Port Sarim."),
new CrypticClue("Search for a crate on the ground floor of a house in Seers' Village.", CRATE_25775, new WorldPoint(2699, 3470, 0), "Search inside Phantuwti Fanstuwi Farsight's house, located south of the pub in Seers' Village."),
new CrypticClue("Snah? I feel all confused, like one of those cakes...", "Hans", new WorldPoint(3211, 3219, 0), "Talk to Hans roaming around Lumbridge Castle."),
new CrypticClue("Speak to Sir Kay in Camelot Castle.", "Sir Kay", new WorldPoint(2759, 3497, 0), "Sir Kay can be found in the courtyard at Camelot castle."),
new CrypticClue("Gold I see, yet gold I require. Give me 875 if death you desire.", "Saniboch", new WorldPoint(2745, 3151, 0), "Speak to Saniboch at the Brimhaven Dungeon entrance."),
new CrypticClue("Find a crate close to the monks that like to paaarty!", CRATE_354, new WorldPoint(2614, 3204, 0), "The crate is in the east side of the Ardougne monastery, near Brother Omad."),
new CrypticClue("Identify the back of this over-acting brother. (He's a long way from home.)", "Hamid", new WorldPoint(3376, 3284, 0), "Talk to Hamid, the monk at the altar in the Duel Arena."),
new CrypticClue("In a town where thieves steal from stalls, search for some drawers in the upstairs of a house near the bank.", "Guard", DRAWERS, new WorldPoint(2611, 3324, 1), "Kill any Guard located around East Ardougne for a medium key. Then search the drawers in the upstairs hallway of Jerico's house, which is the house with pigeon cages located south of the northern East Ardougne bank."),
new CrypticClue("His bark is worse than his bite.", "Barker", new WorldPoint(3499, 3503, 0), "Speak to the Barker at Canifis's Barkers' Haberdashery."),
new CrypticClue("The beasts to my east snap claws and tails, The rest to my west can slide and eat fish. The force to my north will jump and they'll wail, Come dig by my fire and make a wish.", new WorldPoint(2598, 3267, 0), "Dig by the torch in the Ardougne Zoo, between the penguins and the scorpions."),
new CrypticClue("A town with a different sort of night-life is your destination. Search for some crates in one of the houses.", CRATE_24344, new WorldPoint(3498, 3507, 0), "Search the crate inside of the clothes shop in Canifis."),
new CrypticClue("Search the crate near a cart in Port Khazard.", CRATE_366, new WorldPoint(2660, 3149, 0), "Search by the southern Khazard General Store in Port Khazard."),
new CrypticClue("Speak to the bartender of the Blue Moon Inn in Varrock.", "Bartender", new WorldPoint(3226, 3399, 0), "Talk to the bartender in Blue Moon Inn in Varrock."),
new CrypticClue("This aviator is at the peak of his profession.", "Captain Bleemadge", new WorldPoint(2847, 3499, 0), "Captain Bleemadge, the gnome glider pilot, is found at the top of White Wolf Mountain."),
new CrypticClue("Search the crates in the shed just north of East Ardougne.", CRATE_355, new WorldPoint(2617, 3347, 0), "The crates in the shed north of the northern Ardougne bank."),
new CrypticClue("I wouldn't wear this jean on my legs.", "Father Jean", new WorldPoint(1734, 3576, 0), "Talk to father Jean in the Hosidius church."),
new CrypticClue("Search the crate in the Toad and Chicken pub.", CRATE_354, new WorldPoint(2913, 3536, 0), "The Toad and Chicken pub is located in Burthorpe."),
new CrypticClue("Search chests found in the upstairs of shops in Port Sarim.", CLOSED_CHEST_375, new WorldPoint(3016, 3205, 1), "Search the chest on the east wall found upstairs of Wydin's Food Store in Port Sarim."),
new CrypticClue("Right on the blessed border, cursed by the evil ones. On the spot inaccessible by both; I will be waiting. The bugs' imminent possession holds the answer.", new WorldPoint(3410, 3324, 0), "B I P. Dig right under the fairy ring."),
new CrypticClue("The dead, red dragon watches over this chest. He must really dig the view.", "Barbarian", 375, new WorldPoint(3353, 3332, 0), "Search the chest underneath the Red Dragon's head in the Exam Centre. Kill a MALE Barbarian in Barbarian Village or Barbarian Outpost to receive the key."),
new CrypticClue("My home is grey, and made of stone; A castle with a search for a meal. Hidden in some drawers I am, across from a wooden wheel.", DRAWERS_5618, new WorldPoint(3213, 3216, 1), "Open the drawers inside the room with the spinning wheel on the first floor of Lumbridge Castle."),
new CrypticClue("Come to the evil ledge, Yew know yew want to. Try not to get stung.", new WorldPoint(3089, 3468, 0), "Dig in Edgeville, just east of the Southern Yew tree."),
new CrypticClue("Look in the ground floor crates of houses in Falador.", CRATES_24088, new WorldPoint(3029, 3355, 0), "The house east of the eastern bank in Falador."),
new CrypticClue("You were 3 and I was the 6th. Come speak to me.", "Vannaka", new WorldPoint(3146, 9913, 0), "Speak to Vannaka in Edgeville Dungeon."),
new CrypticClue("Search the crates in Draynor Manor.", CRATE_11485, new WorldPoint(3106, 3369, 2), "Top floor of the Draynor Manor."),
new CrypticClue("Search the crates near a cart in Varrock.", CRATE_5107, new WorldPoint(3226, 3452, 0), "South east of Varrock Palace, south of the tree farming patch."),
new CrypticClue("A Guthixian ring lies between two peaks. Search the stones and you'll find what you seek.", STONES_26633, new WorldPoint(2922, 3484, 0), "Search the stones several steps west of the Guthixian stone circle in Taverley."),
new CrypticClue("Search the boxes in the house near the south entrance to Varrock.", BOXES_5111, new WorldPoint(3203, 3384, 0), "The first house on the left when entering Varrock from the southern entrance."),
new CrypticClue("His head might be hollow, but the crates nearby are filled with surprises.", CRATE_354, new WorldPoint(3478, 3091, 0), "Search the crates near the Clay golem in the ruins of Uzer."),
new CrypticClue("One of the sailors in Port Sarim is your next destination.", "Captain Tobias", new WorldPoint(3026, 3216, 0), "Speak to Captain Tobias on the docks of Port Sarim."),
new CrypticClue("THEY'RE EVERYWHERE!!!! But they were here first. Dig for treasure where the ground is rich with ore.", new WorldPoint(3081, 3421, 0), "Dig at Barbarian Village, next to the Stronghold of Security."),
new CrypticClue("Talk to the mother of a basement dwelling son.", "Doris", new WorldPoint(3079, 3493, 0), "Evil Dave's mother, Doris, is located in the house west of Edgeville bank."),
new CrypticClue("Speak to Ned in Draynor Village.", "Ned", new WorldPoint(3098, 3258, 0), "Ned is found north of the Draynor bank."),
new CrypticClue("Speak to Hans to solve the clue.", "Hans", new WorldPoint(3211, 3219, 0), "Hans can be found at Lumbridge Castle."),
new CrypticClue("Search the crates in Canifis.", CRATE_24344, new WorldPoint(3509, 3497, 0), "Search inside Rufus' Meat Emporium in Canifis."),
new CrypticClue("Search the crates in the Dwarven mine.", CRATE_357, new WorldPoint(3035, 9849, 0), "Search the crate in the room east of the Ice Mountain ladder entrance in the Drogo's Mining Emporium in the Dwarven Mine."),
new CrypticClue("A crate found in the tower of a church is your next location.", CRATE_357, new WorldPoint(2612, 3304, 1), "Climb the ladder and search the crates on the first floor in the Church in Ardougne."),
new CrypticClue("Covered in shadows, the centre of the circle is where you will find the answer.", new WorldPoint(3488, 3289, 0), "Dig in the centre of Mort'ton, where the roads intersect."),
new CrypticClue("I lie lonely and forgotten in mid wilderness, where the dead rise from their beds. Feel free to quarrel and wind me up, and dig while you shoot their heads.", new WorldPoint(3174, 3663, 0), "Directly under the crossbow respawn in the Graveyard of Shadows in level 18 Wilderness."),
new CrypticClue("In the city where merchants are said to have lived, talk to a man with a splendid cape, but a hat dropped by goblins.", "Head chef", new WorldPoint(3143, 3445, 0), "Talk to the Head chef in Cooks' Guild west of Varrock. You will need a chef's hat, Varrock armour 3 or 4, or the Cooking cape to enter."),
new CrypticClue("The mother of the reptilian sacrifice.", "Zul-Cheray", new WorldPoint(2204, 3050, 0), "Talk to Zul-Cheray in a house near the sacrificial boat at Zul-Andra."),
new CrypticClue("I watch the sea. I watch you fish. I watch your tree.", "Ellena", new WorldPoint(2860, 3431, 0), "Speak to Ellena at Catherby fruit tree patch."),
new CrypticClue("Dig between some ominous stones in Falador.", new WorldPoint(3040, 3399, 0), "Three standing stones inside a walled area. East of the northern Falador gate."),
new CrypticClue("Speak to Rusty north of Falador.", "Rusty", new WorldPoint(2979, 3435, 0), "Rusty can be found northeast of Falador on the way to the Mind altar."),
new CrypticClue("Search a wardrobe in Draynor.", WARDROBE_5622, new WorldPoint(3087, 3261, 0), "Go to Aggie's house in Draynor Village and search the wardrobe in northern wall."),
new CrypticClue("I have many arms but legs, I have just one. I have little family but my seed you can grow on, I am not dead, yet I am but a spirit, and my power, on your quests, you will earn the right to free it.", NULL_1293, new WorldPoint(2544, 3170, 0), "Spirit Tree in Tree Gnome Village. Answer: 13112221", "What is the next number in the sequence? 1, 11, 21, 1211, 111221, 312211"),
new CrypticClue("I am the one who watches the giants. The giants in turn watch me. I watch with two while they watch with one. Come seek where I may be.", "Kamfreena", new WorldPoint(2845, 3539, 0), "Speak to Kamfreena on the top floor of the Warriors' Guild."),
new CrypticClue("In a town where wizards are known to gather, search upstairs in a large house to the north.", "Man", 375, new WorldPoint(2593, 3108, 1), "Search the chest upstairs in the house north of Yanille Wizard's Guild. Kill a man for the key."),
new CrypticClue("Probably filled with wizards socks.", "Wizard", DRAWERS_350, new WorldPoint(3116, 9562, 0), "Search the drawers in the basement of the Wizard's Tower south of Draynor Village. Kill one of the Wizards for the key. Fairy ring DIS"),
new CrypticClue("Even the seers say this clue goes right over their heads.", CRATE_14934, new WorldPoint(2707, 3488, 2), "Search the crate on the Seers Agility Course in Seers Village"),
new CrypticClue("Speak to a Wyse man.", "Wyson the gardener", new WorldPoint(3026, 3378, 0), "Talk to Wyson the gardener at Falador Park."),
new CrypticClue("You'll need to look for a town with a central fountain. Look for a locked chest in the town's chapel.", "Monk" , CLOSED_CHEST_5108, new WorldPoint(3256, 3487, 0), "Search the chest by the stairs in the Varrock church. Kill a Monk in Ardougne Monastery to obtain the key."),
new CrypticClue("Talk to Ambassador Spanfipple in the White Knights Castle.", "Ambassador Spanfipple", new WorldPoint(2979, 3340, 0), "Ambassador Spanfipple can be found roaming on the first floor of the White Knights Castle."),
new CrypticClue("Mine was the strangest birth under the sun. I left the crimson sack, yet life had not begun. Entered the world, and yet was seen by none.", new WorldPoint(2832, 9586, 0), "Inside Karamja Volcano, dig directly underneath the Red spiders' eggs respawn."),
new CrypticClue("Search for a crate in Varrock Castle.", CRATE_5113, new WorldPoint(3224, 3492, 0), "Search the crate in the corner of the kitchen in Varrock Castle."),
new CrypticClue("And so on, and so on, and so on. Walking from the land of many unimportant things leads to a choice of paths.", new WorldPoint(2591, 3879, 0), "Dig on Etceteria next to the Evergreen tree in front of the castle walls."),
new CrypticClue("Speak to Donovan, the Family Handyman.", "Donovan the Family Handyman", new WorldPoint(2743, 3578, 0), "Donovan the Family Handyman is found on the first floor of Sinclair Mansion, north of Seers' Village."),
new CrypticClue("Search the crates in the Barbarian Village helmet shop.", CRATES_11600, new WorldPoint(3073, 3430, 0), "Peksa's Helmet Shop in Barbarian Village."),
new CrypticClue("Search the boxes of Falador's general store.", CRATES_24088, new WorldPoint(2955, 3390, 0), "Falador general store."),
new CrypticClue("In a village made of bamboo, look for some crates under one of the houses.", CRATE_356, new WorldPoint(2800, 3074, 0), "Search the crate by the house at the northern point of the broken jungle fence in Tai Bwo Wannai."),
new CrypticClue("This crate is mine, all mine, even if it is in the middle of the desert.", CRATE_18889, new WorldPoint(3289, 3022, 0), "Center of desert Mining Camp. Search the crates. Requires the metal key from Tourist Trap to enter."),
new CrypticClue("Dig where 4 siblings and I all live with our evil overlord.", new WorldPoint(3195, 3357, 0), "Dig in the chicken pen inside the Champions' Guild"),
new CrypticClue("In a town where the guards are armed with maces, search the upstairs rooms of the Public House.", "Guard dog", 348, new WorldPoint(2574, 3326, 1), "Search the drawers upstairs in the pub north of Ardougne Castle. Kill a Guard dog at Handelmort Mansion to obtain the key."),
new CrypticClue("Four blades I have, yet draw no blood; Still I turn my prey to powder. If you are brave, come search my roof; It is there my blades are louder.", CRATE_12963, new WorldPoint(3166, 3309, 2), "Lumbridge windmill, search the crates on the top floor."),
new CrypticClue("Search through some drawers in the upstairs of a house in Rimmington.", DRAWERS_352, new WorldPoint(2970, 3214, 1), "On the first floor of the house north of Hetty the Witch's house in Rimmington."),
new CrypticClue("Probably filled with books on magic.", BOOKCASE_380, new WorldPoint(3096, 9572, 0), "Search the bookcase in the basement of Wizards' Tower. Fairy ring DIS."),
new CrypticClue("If you look closely enough, it seems that the archers have lost more than their needles.", HAYSTACK, new WorldPoint(2672, 3416, 0), "Search the haystack by the south corner of the Ranging Guild."),
new CrypticClue("Search the crate in the left-hand tower of Lumbridge Castle.", CRATE_357, new WorldPoint(3228, 3212, 1), "Located on the first floor of the southern tower at the Lumbridge Castle entrance."),
new CrypticClue("'Small shoe.' Often found with rod on mushroom.", "Gnome trainer", new WorldPoint(2476, 3428, 0), "Talk to any Gnome trainer in the agility area of the Tree Gnome Stronghold."),
new CrypticClue("I live in a deserted crack collecting soles.", "Genie", new WorldPoint(3371, 9320, 0), "Enter the crack west of Nardah Rug merchant, and talk to the Genie. You'll need a light source and a rope.", true),
new CrypticClue("46 is my number. My body is the colour of burnt orange and crawls among those with eight. Three mouths I have, yet I cannot eat. My blinking blue eye hides my grave.", new WorldPoint(3170, 3885, 0), "Sapphire respawn in the Spider's Nest, lvl 46 Wilderness. Dig under the sapphire spawn."),
new CrypticClue("Green is the colour of my death as the winter-guise, I swoop towards the ground.", new WorldPoint(2780, 3783, 0), "Slide down to where Trollweiss grows on Trollweiss Mountain. Bring a sled."),
new CrypticClue("Talk to a party-goer in Falador.", "Lucy", new WorldPoint(3046, 3382, 0), "Lucy is the bartender on the first floor of the Falador party room."),
new CrypticClue("He knows just how easy it is to lose track of time.", "Brother Kojo", new WorldPoint(2570, 3250, 0), "Speak to Brother Kojo in the Clock Tower. Answer: 22", "On a clock, how many times a day do the minute hand and the hour hand overlap?"),
new CrypticClue("A great view - watch the rapidly drying hides get splashed. Check the box you are sitting on.", BOXES, new WorldPoint(2523, 3493, 1), "Almera's House north of Baxtorian Falls, search boxes on the first floor."),
new CrypticClue("Search the Coffin in Edgeville.", COFFIN, new WorldPoint(3091, 3477, 0), "Search the coffin located by the Edgeville Wilderness teleport lever."),
new CrypticClue("When no weapons are at hand, then is the time to reflect. In Saradomin's name, redemption draws closer...", DRAWERS_350, new WorldPoint(2818, 3351, 0), "On Entrana, search the southern drawer in the house with the cooking range."),
new CrypticClue("Search the crates in a house in Yanille that has a piano.", CRATE_357, new WorldPoint(2598, 3105, 0), "The house is located northwest of the bank in Yanille."),
new CrypticClue("Speak to the staff of Sinclair mansion.", "Louisa", new WorldPoint(2736, 3578, 0), "Speak to Louisa, on the ground floor, found at the Sinclair Mansion. Fairy ring CJR"),
new CrypticClue("I am a token of the greatest love. I have no beginning or end. My eye is red, I can fit like a glove. Go to the place where it's money they lend, And dig by the gate to be my friend.", new WorldPoint(3191, 9825, 0), "Dig by the gate in the basement of the West Varrock bank."),
new CrypticClue("Speak to Kangai Mau.", "Kangai Mau", new WorldPoint(2791, 3183, 0), "Kangai Mau is found in the Shrimp and Parrot in Brimhaven."),
new CrypticClue("Speak to Hajedy.", "Hajedy", new WorldPoint(2779, 3211, 0), "Hajedy is found by the cart, located just south of the Brimhaven docks."),
new CrypticClue("Must be full of railings.", BOXES_6176, new WorldPoint(2576, 3464, 0), "Search the boxes around the hut where the broken Dwarf Cannon is, close to the start of the Dwarf Cannon quest."),
new CrypticClue("I wonder how many bronze swords he has handed out.", "Vannaka", new WorldPoint(3164, 9913, 0), "Talk to Vannaka. He can be found in Edgeville Dungeon."),
new CrypticClue("Read 'How to breed scorpions.' By O.W.Thathurt.", BOOKCASE_380, new WorldPoint(2703, 3409, 1), "Search the northern bookcase on the first floor of the Sorcerer's Tower."),
new CrypticClue("Search the crates in the Port Sarim Fishing shop.", CRATE_9534, new WorldPoint(3012, 3222, 0), "Search the crates, by the door, in Gerrant's Fishy Business in Port Sarim."),
new CrypticClue("Speak to The Lady of the Lake.", "The Lady of the Lake", new WorldPoint(2924, 3405, 0), "Talk to The Lady of the Lake in Taverley."),
new CrypticClue("Rotting next to a ditch. Dig next to the fish.", new WorldPoint(3547, 3183, 0), "Dig next to a fishing spot on the south-east side of Burgh de Rott."),
new CrypticClue("The King's magic won't be wasted by me.", "Guardian mummy", new WorldPoint(1934, 4427, 0), "Talk to the Guardian mummy inside the Pyramid Plunder minigame in Sophanem."),
new CrypticClue("Dig where the forces of Zamorak and Saradomin collide.", new WorldPoint(3049, 4839, 0), "Dig next to the law rift in the Abyss."),
new CrypticClue("Search the boxes in the goblin house near Lumbridge.", BOXES, new WorldPoint(3245, 3245, 0), "Goblin house on the eastern side of the river outside of Lumbridge."),
new CrypticClue("W marks the spot.", new WorldPoint(2867, 3546, 0), "Dig in the middle of the Warriors' Guild entrance hall."),
new CrypticClue("Surviving.", "Sir Vyvin", new WorldPoint(2983, 3338, 0), "Talk to Sir Vyvin on the second floor of Falador castle."),
new CrypticClue("My name is like a tree, yet it is spelt with a 'g'. Come see the fur which is right near me.", "Wilough", new WorldPoint(3221, 3435, 0), "Speak to Wilough, next to the Fur Merchant in Varrock Square."),
new CrypticClue("Speak to Jatix in Taverley.", "Jatix", new WorldPoint(2898, 3428, 0), "Jatix is found in the middle of Taverley."),
new CrypticClue("Speak to Gaius in Taverley.", "Gaius", new WorldPoint(2884, 3450, 0), "Gaius is found at the northwest corner in Taverley."),
new CrypticClue("If a man carried my burden, he would break his back. I am not rich, but leave silver in my track. Speak to the keeper of my trail.", "Gerrant", new WorldPoint(3014, 3222, 0), "Speak to Gerrant in the fish shop in Port Sarim."),
new CrypticClue("Search the drawers in Falador's chain mail shop.", DRAWERS, new WorldPoint(2969, 3311, 0), "Wayne's Chains - Chainmail Specialist store at the southern Falador walls."),
new CrypticClue("Talk to the barber in the Falador barber shop.", "Hairdresser", new WorldPoint(2945, 3379, 0), "The Hairdresser can be found in the barber shop, north of the west Falador bank."),
new CrypticClue("Often sought out by scholars of histories past, find me where words of wisdom speak volumes.", "Examiner", new WorldPoint(3362, 3341, 0), "Speak to an examiner at the Exam Centre."),
new CrypticClue("Generally speaking, his nose was very bent.", "General Bentnoze", new WorldPoint(2957, 3511, 0), "Talk to General Bentnoze in the Goblin Village north of Falador."),
new CrypticClue("Search the bush at the digsite centre.", BUSH_2357, new WorldPoint(3345, 3378, 0), "The bush is on the east side of the first pathway towards the digsite from the Exam Centre."),
new CrypticClue("Someone watching the fights in the Duel Arena is your next destination.", "Jeed", new WorldPoint(3360, 3242, 0), "Talk to Jeed, found on the upper floors, at the Duel Arena."),
new CrypticClue("It seems to have reached the end of the line, and it's still empty.", MINE_CART_6045, new WorldPoint(3041, 9820, 0), "Search the carts in the northern part of the Dwarven Mine."),
new CrypticClue("You'll have to plug your nose if you use this source of herbs.", null, "Kill an Aberrant or Deviant spectre."),
new CrypticClue("When you get tired of fighting, go deep, deep down until you need an antidote.", CRATE_357, new WorldPoint(2576, 9583, 0), "Go to Yanille Agility dungeon and fall into the place with the poison spiders by praying at the Chaos altar. Search the crate by the stairs leading up."),
new CrypticClue("Search the bookcase in the monastery.", BOOKCASE_380, new WorldPoint(3054, 3484, 0), "Search the southeastern bookcase at Edgeville Monastery."),
new CrypticClue("Surprising? I bet he is...", "Sir Prysin", new WorldPoint(3205, 3474, 0), "Talk to Sir Prysin in Varrock Palace."),
new CrypticClue("Search upstairs in the houses of Seers' Village for some drawers.", DRAWERS_25766, new WorldPoint(2716, 3471, 1), "Located in the house with the spinning wheel. South of the Seers' Village bank."),
new CrypticClue("Leader of the Yak City.", "Mawnis Burowgar", new WorldPoint(2336, 3799, 0), "Talk to Mawnis Burowgar in Neitiznot."),
new CrypticClue("Speak to Arhein in Catherby.", "Arhein", new WorldPoint(2803, 3430, 0), "Arhein is just south of the Catherby bank."),
new CrypticClue("Speak to Doric, who lives north of Falador.", "Doric", new WorldPoint(2951, 3451, 0), "Doric is found north of Falador and east of the Taverley gate."),
new CrypticClue("Where the best are commemorated, and a celebratory cup, not just for beer.", new WorldPoint(3388, 3152, 0), "Dig at the Clan Cup Trophy south-west of Citharede Abbey."),
new CrypticClue("'See you in your dreams' said the vegetable man.", "Dominic Onion", new WorldPoint(2608, 3116, 0), "Speak to Dominic Onion at the Nightmare Zone teleport spot."),
new CrypticClue("Try not to step on any aquatic nasties while searching this crate.", CRATE_18204, new WorldPoint(2764, 3273, 0), "Search the crate in Bailey's house on the Fishing Platform."),
new CrypticClue("The cheapest water for miles around, but they react badly to religious icons.", CRATE_354, new WorldPoint(3178, 2987, 0), "Search the crates in the General Store tent in the Desert Bandit Camp."),
new CrypticClue("This village has a problem with cartloads of the undead. Try checking the bookcase to find an answer.", BOOKCASE_394, new WorldPoint(2833, 2992, 0), "Search the bookcase by the doorway of the building just south east of the Shilo Village Gem Mine."),
new CrypticClue("Dobson is my last name, and with gardening I seek fame.", "Horacio", new WorldPoint(2635, 3310, 0), "Horacio, located in the garden of the Handelmort Mansion in East Ardougne."),
new CrypticClue("The magic of 4 colours, an early experience you could learn. The large beast caged up top, rages, as his demised kin's loot now returns.", "Wizard Mizgog", new WorldPoint(3103, 3163, 2), "Speak to Wizard Mizgog at the top of the Wizard's Tower south of Draynor."),
new CrypticClue("Aggie I see. Lonely and southern I feel. I am neither inside nor outside the house, yet no home would be complete without me. The treasure lies beneath me!", new WorldPoint(3085, 3255, 0), "Dig outside the window of Aggie's house in Draynor Village."),
new CrypticClue("Search the chest in Barbarian Village.", CLOSED_CHEST_375, new WorldPoint(3085, 3429, 0), "The chest located in the house with a spinning wheel in Barbarian Village."),
new CrypticClue("Search the crates in the outhouse of the long building in Taverley.", CRATE_357, new WorldPoint(2914, 3433, 0), "Located in the small building attached by a fence to the main building in Taverley. Climb over the stile."),
new CrypticClue("Talk to Ermin.", "Ermin", new WorldPoint(2488, 3409, 1), "Ermin can be found on the first floor of the tree house south-east of the Gnome Agility Course."),
new CrypticClue("Ghostly bones.", null, "Kill an Ankou."),
new CrypticClue("Search through chests found in the upstairs of houses in eastern Falador.", CLOSED_CHEST_375, new WorldPoint(3041, 3364, 1), "The house is located southwest of the Falador Party Room. There are two chests in the room, search the northern chest."),
new CrypticClue("Let's hope you don't meet a watery death when you encounter this fiend.", null, "Kill a waterfiend."),
new CrypticClue("Reflection is the weakness for these eyes of evil.", null, "Kill a basilisk."),
new CrypticClue("Search a bookcase in Lumbridge swamp.", BOOKCASE_9523, new WorldPoint(3146, 3177, 0), "Located in Father Urhney's house in Lumbridge Swamp."),
new CrypticClue("Surround my bones in fire, ontop the wooden pyre. Finally lay me to rest, before my one last test.", null, "Kill a confused/lost barbarian to receive mangled bones. Construct and burn a pyre ship. Kill the ferocious barbarian spirit that spawns to receive a clue casket."),
new CrypticClue("Fiendish cooks probably won't dig the dirty dishes.", new WorldPoint(3043, 4974, 1), "Dig by the fire in the Rogues' Den."),
new CrypticClue("My life was spared but these voices remain, now guarding these iron gates is my bane.", "Key Master", new WorldPoint(1310, 1251, 0), "Speak to the Key Master in Cerberus' Lair."),
new CrypticClue("Search the boxes in one of the tents in Al Kharid.", BOXES_361, new WorldPoint(3308, 3206, 0), "Search the boxes in the tent east of the Al Kharid Silk trader."),
new CrypticClue("One of several rhyming brothers, in business attire with an obsession for paper work.", "Piles", new WorldPoint(3186, 3936, 0), "Speak to Piles in the Wilderness Resource Area. An entry fee of 7,500 coins is required, or less if Wilderness Diaries have been completed."),
new CrypticClue("Search the drawers on the ground floor of a building facing Ardougne's Market.", DRAWERS_350, new WorldPoint(2653, 3320, 0), "Inside Noella's house north of the East Ardougne market."),
new CrypticClue("'A bag belt only?', he asked his balding brothers.", "Abbot Langley", new WorldPoint(3058, 3487, 0), "Talk-to Abbot Langley in Monastery west of Edgeville"),
new CrypticClue("Search the drawers upstairs in Falador's shield shop.", DRAWERS, new WorldPoint(2971, 3386, 1), "Cassie's Shield Shop at the northern Falador entrance."),
new CrypticClue("Go to this building to be illuminated, and check the drawers while you are there.", "Market Guard", DRAWERS_350 , new WorldPoint(2512, 3641, 1), "Search the drawers in the first floor of the Lighthouse. Kill a Rellekka marketplace guard to obtain the key."),
new CrypticClue("Dig near some giant mushrooms, behind the Grand Tree.", new WorldPoint(2458, 3504, 0), "Dig near the red mushrooms northwest of the Grand Tree."),
new CrypticClue("Pentagrams and demons, burnt bones and remains, I wonder what the blood contains.", new WorldPoint(3297, 3890, 0), "Dig under the blood rune spawn next to the Demonic Ruins."),
new CrypticClue("Search the drawers above Varrock's shops.", DRAWERS_7194, new WorldPoint(3206, 3419, 1), "Located upstairs in Thessalia's Fine Clothes shop in Varrock."),
new CrypticClue("Search the drawers in one of Gertrude's bedrooms.", DRAWERS_7194, new WorldPoint(3156, 3406, 0), "Kanel's bedroom (southeastern room), in Gertrude's house south of the Cooking Guild."),
new CrypticClue("Under a giant robotic bird that cannot fly.", new WorldPoint(1756, 4940, 0), "Dig next to the terrorbird display in the south exhibit of Varrock Museum's basement."),
new CrypticClue("Great demons, dragons and spiders protect this blue rock, beneath which, you may find what you seek.", new WorldPoint(3045, 10265, 0), "Dig by the runite rock in the Lava Maze Dungeon."),
new CrypticClue("My giant guardians below the market streets would be fans of rock and roll, if only they could grab hold of it. Dig near my green bubbles!", new WorldPoint(3161, 9904, 0), "Dig near the cauldron by Moss Giants under Varrock Sewers"),
new CrypticClue("Varrock is where I reside, not the land of the dead, but I am so old, I should be there instead. Let's hope your reward is as good as it says, just 1 gold one and you can have it read.", "Gypsy Aris", new WorldPoint(3203, 3424, 0), "Talk to Gypsy Aris, West of Varrock main square."),
new CrypticClue("Speak to a referee.", "Gnome ball referee", new WorldPoint(2386, 3487, 0), "Talk to a Gnome ball referee found on the Gnome ball field in the Gnome Stronghold. Answer: 5096", "What is 57 x 89 + 23?"),
new CrypticClue("This crate holds a better reward than a broken arrow.", CRATE_356, new WorldPoint(2671, 3437, 0), "Inside the Ranging Guild. Search the crate behind the northern most building."),
new CrypticClue("Search the drawers in the house next to the Port Sarim mage shop.", DRAWERS, new WorldPoint(3024, 3259, 0), "House east of Betty's Mage shop in Port Sarim. Contains a cooking sink."),
new CrypticClue("With a name like that, you'd expect a little more than just a few scimitars.", "Daga", new WorldPoint(2759, 2775, 0), "Speak to Daga on Ape Atoll."),
new CrypticClue("Strength potions with red spiders' eggs? He is quite a herbalist.", "Apothecary", new WorldPoint(3194, 3403, 0), "Talk to Apothecary in the South-western Varrock. (the) apothecary is just north-west of the Varrock Swordshop."),
new CrypticClue("Robin wishes to see your finest ranged equipment.", "Robin", new WorldPoint(3673, 3492, 0), "Robin at the inn in Port Phasmatys. Speak to him with +182 in ranged attack bonus. Bonus granted by the toxic blowpipe is ignored."),
new CrypticClue("You will need to under-cook to solve this one.", CRATE_357, new WorldPoint(3219, 9617, 0), "Search the crate in the Lumbridge basement."),
new CrypticClue("Search through some drawers found in Taverley's houses.", DRAWERS_350, new WorldPoint(2894, 3418, 0), "The south-eastern most house in Taverley, south of Jatix's Herblore Shop."),
new CrypticClue("Anger Abbot Langley.", "Abbot Langley", new WorldPoint(3058, 3487, 0), "Speak to Abbot Langley in the Edgeville Monastery while you have a negative prayer bonus (currently only possible with an Ancient staff)."),
new CrypticClue("Dig where only the skilled, the wealthy, or the brave can choose not to visit again.", new WorldPoint(3221, 3219, 0), "Dig at Lumbridge spawn"),
new CrypticClue("Scattered coins and gems fill the floor. The chest you seek is in the north east.", "King Black Dragon", CLOSED_CHEST_375, new WorldPoint(2288, 4702, 0), "Kill the King Black Dragon for a key (elite), and then open the closed chest in the NE corner of the lair."),
new CrypticClue("A ring of water surrounds 4 powerful rings, dig above the ladder located there.", new WorldPoint(1910, 4367, 0), "Dig by the ladder leading to the Dagannoth Kings room in the Waterbirth Island Dungeon. Bring a pet rock and rune thrownaxe."),
new CrypticClue("This place sure is a mess.", "Ewesey", new WorldPoint(1646, 3631, 0), "Ewesey is located in the mess hall in Hosidius."),
new CrypticClue("Here, there are tears, but nobody is crying. Speak to the guardian and show off your alignment to balance.", "Juna", JUNA, new WorldPoint(3252, 9517, 2), "Talk to Juna while wearing three Guthix related items."),
new CrypticClue("You might have to turn over a few stones to progress.", null, "Kill a rock crab."),
new CrypticClue("Dig under Razorlor's toad batta.", new WorldPoint(3139, 4554, 0), "Dig on the toad batta spawn in Tarn's Lair."),
new CrypticClue("Talk to Cassie in Falador.", "Cassie", new WorldPoint(2975, 3383, 0), "Cassie is found just south-east of the northern Falador gate."),
new CrypticClue("Faint sounds of 'Arr', fire giants found deep, the eastern tip of a lake, are the rewards you could reap.", new WorldPoint(3055, 10338, 0), "Dig south of the pillar in the Deep Wilderness Dungeon in the room with the fire giants."),
new CrypticClue("If you're feeling brave, dig beneath the dragon's eye.", new WorldPoint(2410, 4714, 0), "Dig below the mossy rock under the Viyeldi caves (Legend's Quest). Items needed: Pickaxe, unpowered orb, lockpick, spade, any charge orb spell, and either 79 agility or an axe and machete."),
new CrypticClue("Search the tents in the Imperial Guard camp in Burthorpe for some boxes.", BOXES_3686, new WorldPoint(2885, 3540, 0), "Search in the tents in the northwest corner of the soldiers' camp in Burthorpe."),
new CrypticClue("A dwarf, approaching death, but very much in the light.", "Thorgel", new WorldPoint(1863, 4639, 0), "Speak to Thorgel at the entrance to the Death altar."),
new CrypticClue("You must be 100 to play with me.", "Squire (Veteran)", new WorldPoint(2638, 2656, 0), "Speak to the Veteran boat squire at Pest Control."),
new CrypticClue("Three rule below and three sit at top. Come dig at my entrance.", new WorldPoint(2523, 3739, 0), "Dig in front of the entrance to the Waterbirth Island Dungeon."),
new CrypticClue("Search the drawers in the ground floor of a shop in Yanille.", DRAWERS_350, new WorldPoint(2570, 3085, 0), "Search the drawers in Yanille's hunting shop."),
new CrypticClue("Search the drawers of houses in Burthorpe.", DRAWERS, new WorldPoint(2929, 3570, 0), "Inside Hild's house in the northeast corner of Burthorpe."),
new CrypticClue("Where safe to speak, the man who offers the pouch of smallest size wishes to see your alignment.", "Mage of Zamorak", new WorldPoint(3260, 3385, 0), "Speak to the Mage of Zamorak south of the Rune Shop in Varrock while wearing three Zamorakian items."),
new CrypticClue("Search the crates in the guard house of the northern gate of East Ardougne.", CRATE_356, new WorldPoint(2645, 3338, 0), "The guard house northwest of the East Ardougne market."),
new CrypticClue("Go to the village being attacked by trolls, search the drawers in one of the houses.", "Penda", DRAWERS_350, new WorldPoint(2921, 3577, 0), "Go to Dunstan's house in the northeast corner of Burthorpe. Kill Penda in the Toad and Chicken to obtain the key."),
new CrypticClue("You'll get licked.", null, "Kill a Bloodveld."),
new CrypticClue("She's small but can build both literally and figuratively, as long as you have their favour.", "Lovada", new WorldPoint(1486, 3834, 0), "Speak to Lovada by the entrance to the blast mine in Lovakengj."),
new CrypticClue("Dig in front of the icy arena where 1 of 4 was fought.", new WorldPoint(2874, 3757, 0), "North of Trollheim, where you fought Kamil from Desert Treasure."),
new CrypticClue("Speak to Roavar.", "Roavar", new WorldPoint(3494, 3474, 0), "Talk to Roavar in the Canifis tavern."),
new CrypticClue("Search the drawers downstairs of houses in the eastern part of Falador.", DRAWERS_350, new WorldPoint(3039, 3342, 0), "House is located east of the eastern Falador bank and south of the fountain. The house is indicated by a cooking range icon on the minimap."),
new CrypticClue("Search the drawers found upstairs in East Ardougne's houses.", DRAWERS, new WorldPoint(2574, 3326, 1), "Upstairs of the pub north of the Ardougne Castle."),
new CrypticClue("The far north eastern corner where 1 of 4 was defeated, the shadows still linger.", new WorldPoint(2744, 5116, 0), "Dig on the northeastern-most corner of the Shadow Dungeon. Bring a ring of visibility."),
new CrypticClue("Search the drawers in a house in Draynor Village.", DRAWERS_350, new WorldPoint(3097, 3277, 0), "The drawer is located in the northernmost house in Draynor Village."),
new CrypticClue("Search the boxes in a shop in Taverley.", BOXES_360, new WorldPoint(2886, 3449, 0), "The box inside Gaius' Two Handed Shop in Taverley."),
new CrypticClue("I lie beneath the first descent to the holy encampment.", new WorldPoint(2914, 5300, 1), "Dig immediately after climbing down the first set of rocks towards Saradomin's encampment within the God Wars Dungeon."),
new CrypticClue("Search the upstairs drawers of a house in a village where pirates are known to have a good time.", "Pirate", 348, new WorldPoint(2809, 3165, 1), "The house in the southeast corner of Brimhaven, northeast of Davon's Amulet Store. Kill any Pirate located around Brimhaven to obtain the key."),
new CrypticClue("Search the chest in the Duke of Lumbridge's bedroom.", CLOSED_CHEST_375, new WorldPoint(3209, 3218, 1), "The Duke's room is on the first floor in Lumbridge Castle."),
new CrypticClue("Talk to the Doomsayer.", "Doomsayer", new WorldPoint(3232, 3228, 0), "Doomsayer can be found just north of Lumbridge Castle entrance."),
new CrypticClue("Search the chests upstairs in Al Kharid Palace.", CLOSED_CHEST_375, new WorldPoint(3301, 3169, 1), "The chest is located, in the northeast corner, on the first floor of the Al Kharid Palace."),
new CrypticClue("Search the boxes just outside the Armour shop in East Ardougne.", BOXES_361, new WorldPoint(2654, 3299, 0), "Outside Zenesha's Plate Mail Body Shop in East Ardougne."),
new CrypticClue("Surrounded by white walls and gems.", "Herquin", new WorldPoint(2945, 3335, 0), "Talk to Herquin, the gem store owner in Falador."),
new CrypticClue("Monk's residence in the far west. See robe storage device.", DRAWERS_350, new WorldPoint(1746, 3490, 0), "Search the drawers in the south tent of the monk's camp on the southern coast of Hosidius, directly south of the player-owned house portal."),
new CrypticClue("Search the drawers in Catherby's Archery shop.", DRAWERS_350, new WorldPoint(2825, 3442, 0), "Hickton's Archery Emporium in Catherby."),
new CrypticClue("The hand ain't listening.", "The Face", new WorldPoint(3019, 3232, 0), "Talk to The Face located by the manhole just north of the Port Sarim fishing shop."),
new CrypticClue("Search the chest in the left-hand tower of Camelot Castle.", CLOSED_CHEST_25592, new WorldPoint(2748, 3495, 2), "Located on the second floor of the western tower of Camelot."),
new CrypticClue("Anger those who adhere to Saradomin's edicts to prevent travel.", "Monk of Entrana", new WorldPoint(3042, 3236, 0), "Port Sarim Docks, try to charter a ship to Entrana with armour or weapons equipped."),
new CrypticClue("South of a river in a town surrounded by the undead, what lies beneath the furnace?", new WorldPoint(2857, 2966, 0), "Dig in front of the Shilo Village furnace."),
new CrypticClue("Talk to the Squire in the White Knights' castle in Falador.", "Squire", new WorldPoint(2977, 3343, 0), "The squire is located in the courtyard of the White Knights' Castle."),
new CrypticClue("Thanks, Grandma!", "Tynan", new WorldPoint(1836, 3786, 0), "Tynan can be found in the north-east corner of Port Piscarilius."),
new CrypticClue("In a town where everyone has perfect vision, seek some locked drawers in a house that sits opposite a workshop.", "Chicken", DRAWERS_25766, new WorldPoint(2709, 3478, 0), "The Seers' Village house south of the Elemental Workshop entrance. Kill any Chicken to obtain a key."),
new CrypticClue("Search the crates in East Ardougne's general store.", CRATE_357, new WorldPoint(2615, 3291, 0), "Located south of the Ardougne church."),
new CrypticClue("Come brave adventurer, your sense is on fire. If you talk to me, it's an old god you desire.", "Viggora", null, "Speak to Viggora while wearing a ring of visibility and a Ghostspeak amulet."),
new CrypticClue("2 musical birds. Dig in front of the spinning light.", new WorldPoint(2671, 10396, 0), "Dig in front of the spinning light in Ping and Pong's room inside the Iceberg"),
new CrypticClue("Search the wheelbarrow in Rimmington mine.", WHEELBARROW_9625, new WorldPoint(2978, 3239, 0), "The Rimmington mining site is located north of Rimmington."),
new CrypticClue("Belladonna, my dear. If only I had gloves, then I could hold you at last.", "Tool Leprechaun", new WorldPoint(3088, 3357, 0), "Talk to Tool Leprechaun at Draynor Manor."),
new CrypticClue("Search the crates in Horvik's armoury.", CRATE_5106, new WorldPoint(3228, 3433, 0), "Horvik's in Varrock."),
new CrypticClue("Ghommal wishes to be impressed by how strong your equipment is.", "Ghommal", new WorldPoint(2878, 3546, 0), "Speak to Ghommal at the Warriors' Guild with a total Melee Strength bonus of over 100."),
new CrypticClue("Shhhh!", "Logosia", new WorldPoint(1633, 3808, 0), "Speak to Logosia in the Arceuus Library's ground floor."),
new CrypticClue("Salty peter.", "Konoo", new WorldPoint(1703, 3524, 0), "Talk to Konoo who is digging saltpetre in Hosidius, north-east of the Woodcutting Guild."),
new CrypticClue("Talk to Zeke in Al Kharid.", "Zeke", new WorldPoint(3287, 3190, 0), "Zeke is the owner of the scimitar shop in Al Kharid."),
new CrypticClue("Guthix left his mark in a fiery lake, dig at the tip of it.", new WorldPoint(3069, 3935, 0), "Dig at the tip of the lava lake that is shaped like a Guthixian symbol, west of the Mage Arena."),
new CrypticClue("Search the drawers in the upstairs of a house in Catherby.", DRAWERS_350, new WorldPoint(2809, 3451, 1), "Perdu's house in Catherby."),
new CrypticClue("Search a crate in the Haymaker's arms.", CRATE_27532, new WorldPoint(1720, 3652, 1), "Search the crate in the north-east corner of The Haymaker's Arms tavern east of Kourend Castle."),
new CrypticClue("Desert insects is what I see. Taking care of them was my responsibility. Your solution is found by digging near me.", new WorldPoint(3307, 9505, 0), "Dig next to the Entomologist, Kalphite area, near Shantay Pass."),
new CrypticClue("Search the crates in the most north-western house in Al Kharid.", CRATE_358, new WorldPoint(3289, 3202, 0), "Search the crates in the house, marked with a cooking range icon, southeast of the gem stall in Al Kharid."),
new CrypticClue("You will have to fly high where a sword cannot help you.", null, "Kill an Aviansie."),
new CrypticClue("A massive battle rages beneath so be careful when you dig by the large broken crossbow.", new WorldPoint(2927, 3761, 0), "NE of the God Wars Dungeon entrance, climb the rocky handholds & dig by large crossbow."),
new CrypticClue("Mix yellow with blue and add heat, make sure you bring protection.", null, "Kill a green or brutal green dragon."),
new CrypticClue("Speak to Ellis in Al Kharid.", "Ellis", new WorldPoint(3276, 3191, 0), "Ellis is tanner just north of Al Kharid bank."),
new CrypticClue("Search the chests in the Dwarven Mine.", CLOSED_CHEST_375, new WorldPoint(3000, 9798, 0), "The chest is on the western wall, where Hura's Crossbow Shop is, in the Dwarven Mine."),
new CrypticClue("In a while...", null, "Kill a crocodile."),
new CrypticClue("A chisel and hammer reside in his home, strange for one of magic. Impress him with your magical equipment.", "Wizard Cromperty", new WorldPoint(2682, 3325, 0), "Wizard Cromperty, NE corner of East Ardougne. +100 magic attack bonus needed"),
new CrypticClue("You have all of the elements available to solve this clue. Fortunately you do not have to go as far as to stand in a draft.", CRATE_18506, new WorldPoint(2723, 9891, 0), "Search the crate, west of the Air Elementals, inside the Elemental Workshop."),
new CrypticClue("A demon's best friend holds the next step of this clue.", null, "Kill a hellhound."),
new CrypticClue("Dig in the centre of a great kingdom of 5 cities.", new WorldPoint(1639, 3673, 0), "Dig in front of the large statue in the centre of Great Kourend."),
new CrypticClue("Hopefully this set of armour will help you to keep surviving.", "Sir Vyvin", new WorldPoint(2982, 3336, 2), "Speak to Sir Vyvin, located in the White Knight's Castle, while wearing a white platebody and platelegs."),
new CrypticClue("The beasts retreat, for their Queen is gone; the song of this town still plays on. Dig near the birthplace of a blade, be careful not to melt your spade.", new WorldPoint(2342, 3677, 0), "Dig in front of the small furnace in the Piscatoris Fishing Colony."),
new CrypticClue("Darkness wanders around me, but fills my mind with knowledge.", "Biblia", new WorldPoint(1633, 3825, 2), "Speak to Biblia on the Arceuus Library's top floor."),
new CrypticClue("I would make a chemistry joke, but I'm afraid I wouldn't get a reaction.", "Chemist", new WorldPoint(2932, 3212, 0), "Talk to the Chemist in Rimmington"),
new CrypticClue("Show this to Hazelmere.", "Hazelmere", new WorldPoint(2677, 3088, 1), "Located upstairs in the house east of Yanille, north of fairy ring CLS."),
new CrypticClue("Does one really need a fire to stay warm here?", new WorldPoint(3816, 3810, 0), "Dig next to the fire near the Volcanic Mine entrance on Fossil Island."),
new CrypticClue("Search the open crate found in the Hosidius kitchens.", CRATES_27533, new WorldPoint(1683, 3616, 0), "The kitchens are north-west of the town in Hosidius."),
new CrypticClue("Dig under Ithoi's cabin.", new WorldPoint(2529, 2838, 0), "Dig under Ithoi's cabin in the Corsair Cove."),
new CrypticClue("Search the drawers, upstairs in the bank to the East of Varrock.", DRAWERS_7194, new WorldPoint(3250, 3420, 1), "Search the drawers upstairs in Varrock east bank."),
new CrypticClue("Speak to Hazelmere.", "Hazelmere", new WorldPoint(2677, 3088, 1), "Located upstairs in the house east of Yanille, north of fairy ring CLS. Answer: 6859", "What is 19 to the power of 3?"),
new CrypticClue("The effects of this fire are magnified.", new WorldPoint(1179, 3626, 0), "Dig by the fire beside Ket'sal K'uk in the westernmost part of the Kebos Swamp."),
new CrypticClue("Always walking around the castle grounds and somehow knows everyone's age.", "Hans", new WorldPoint(3221, 3218, 0), "Talk to Hans walking around Lumbridge Castle."),
new CrypticClue("In the place Duke Horacio calls home, talk to a man with a hat dropped by goblins.", "Cook", new WorldPoint(3208, 3213, 0), "Talk to the Cook in Lumbridge Castle."),
new CrypticClue("In a village of barbarians, I am the one who guards the village from up high.", "Hunding", new WorldPoint(3097, 3432, 2), "Talk to Hunding atop the tower on the east side of Barbarian Village."),
new CrypticClue("Talk to Charlie the Tramp in Varrock.", "Charlie the Tramp", new WorldPoint(3209, 3390, 0), "Talk to Charlie the Tramp by the southern entrance to Varrock. He will give you a task."),
new CrypticClue("Near the open desert I reside, to get past me you must abide. Go forward if you dare, for when you pass me, you'll be sweating by your hair.", "Shantay", new WorldPoint(3303, 3123, 0), "Talk to Shantay at the Shantay Pass south of Al Kharid."),
new CrypticClue("Search the chest in Fred the Farmer's bedroom.", CLOSED_CHEST_375, new WorldPoint(3185, 3274, 0), "Search the chest by Fred the Farmer's bed in his house north-west of Lumbridge."),
new CrypticClue("Search the eastern bookcase in Father Urhney's house.", BOOKCASE_9523, new WorldPoint(3149, 3177, 0), "Father Urhney's house is found in the western end of the Lumbridge Swamp."),
new CrypticClue("Talk to Morgan in his house at Draynor Village.", "Morgan", new WorldPoint(3098, 3268, 0), "Morgan can be found in the house with the quest start map icon in Northern Draynor Village."),
new CrypticClue("Talk to Charles at Port Piscarilius.", "Charles", new WorldPoint(1821, 3690, 0), "Charles is found by Veos' ship in Port Piscarilius."),
new CrypticClue("Search the crate in Rommiks crafting shop in Rimmington.", CRATE_9533, new WorldPoint(2946, 3207, 0), "The crates in Rommik's Crafty Supplies in Rimmington."),
new CrypticClue("Talk to Ali the Leaflet Dropper north of the Al Kharid mine.", "Ali the Leaflet Dropper", new WorldPoint(3283, 3329, 0), "Ali the Leaflet Dropper can be found roaming north of the Al Kharid mine."),
new CrypticClue("Talk to the cook in the Blue Moon Inn in Varrock.", "Cook", new WorldPoint(3230, 3401, 0), "The Blue Moon Inn can be found by the southern entrance to Varrock."),
new CrypticClue("Search the single crate in Horvik's smithy in Varrock.", CRATE_5106, new WorldPoint(3228, 3433, 0), "Horvik's Smithy is found north-east of of Varrock Square."),
new CrypticClue("Search the crates in Falador General store.", CRATES_24088, new WorldPoint(2955, 3390, 0), "The Falador General Store can be found by the northern entrance to the city."),
new CrypticClue("Talk to Wayne at Wayne's Chains in Falador.", "Wayne", new WorldPoint(2972, 3312, 0), "Wayne's shop is found directly south of the White Knights' Castle."),
new CrypticClue("Search the boxes next to a chest that needs a crystal key.", BOXES_360, new WorldPoint(2915, 3452, 0), "The Crystal chest can be found in the house directly south of the Witch's house in Taverley."),
new CrypticClue("Talk to Turael in Burthorpe.", "Turael", new WorldPoint(2930, 3536, 0), "Turael is located in the small house east of the Toad and Chicken inn in Burthorpe."),
new CrypticClue("More resources than I can handle, but in a very dangerous area. Can't wait to strike gold!", new WorldPoint(3183, 3941, 0), "Dig between the three gold ores in the Wilderness Resource Area."),
new CrypticClue("Observing someone in a swamp, under the telescope lies treasure.", new WorldPoint(2221, 3091, 0), "Dig next to the telescope on Broken Handz's island in the poison wastes. (Accessible only through fairy ring DLR)"),
new CrypticClue("A general who sets a 'shining' example.", "General Hining", new WorldPoint(2186, 3148, 0), "Talk to General Hining in Tyras Camp."),
new CrypticClue("Has no one told you it is rude to ask a lady her age?", "Mawrth", new WorldPoint(2333, 3165, 0), "Talk to Mawrth in Lletya."),
new CrypticClue("Elvish onions.", new WorldPoint(3303, 6092, 0), "Dig in the onion patch east of the Prifddinas allotments."),
new CrypticClue("Dig by the Giant's Den entrance, looking out over Lake Molch.", new WorldPoint(1418, 3591, 0), "South-east of Lake Molch in Zeah, outside the cave entrance."),
new CrypticClue("Search the crates in the fruit store just east of the Hosidius town centre.", CRATES_27533, new WorldPoint(1799, 3613, 0), "Search the crates in the back room of the Hosidius fruit store."),
new CrypticClue("A graceful man of many colours, his crates must be full of many delights.", "Hill Giant", CRATE_42067, new WorldPoint(1506, 3590, 2), "Kill any Hill Giant for a medium key. Then search the crate on the top floor of Osten's clothing shop in Shayzien."),
new CrypticClue("Search the basket of apples in an orchard, south of the unknown grave surrounded by white roses.", APPLE_BASKET, new WorldPoint(1718, 3626, 0), "Search the middle apple basket in the apple orchard north of Hosidius."),
new CrypticClue("Dig in the lair of red wings, within the temple of the Sun and Moon.", new WorldPoint(1820, 9935, 0), "Forthos Dungeon. In the center of the red dragons."),
new CrypticClue("Within the town of Lumbridge lives a man named Bob. He walks out of his door and takes 1 step east, 7 steps north, 5 steps west and 1 step south. Once he arrives, he digs a hole and buries his treasure.", new WorldPoint(3230, 3209, 0), "Just west of the bush outside Bob's axe shop in Lumbridge."),
new CrypticClue("Try not to let yourself be dazzled when you search these drawers.", DRAWERS_350, new WorldPoint(2561, 3323, 0), "Search the western drawers in Jimmy Dazzler's home near the East Ardougne Rat Pits."),
new CrypticClue("The Big High War God left his mark on this place.", new WorldPoint(3572, 4372, 0), "Dig anywhere in Yu'biusk. Fairy ring BLQ.")
);
private final String text;
private final String npc;
private final int objectId;
@Nullable
private final WorldPoint location;
private final String solution;
@Nullable
private final String questionText;
private CrypticClue(String text, WorldPoint location, String solution)
{
this(text, null, -1, location, solution);
}
private CrypticClue(String text, int objectId, WorldPoint location, String solution)
{
this(text, null, objectId, location, solution, null);
}
private CrypticClue(String text, String npc, WorldPoint location, String solution)
{
this(text, npc, -1, location, solution, null);
}
private CrypticClue(String text, String npc, WorldPoint location, String solution, boolean requiresLight)
{
this(text, npc, location, solution);
setRequiresLight(requiresLight);
}
private CrypticClue(String text, int objectId, WorldPoint location, String solution, String questionText)
{
this(text, null, objectId, location, solution, questionText);
}
private CrypticClue(String text, String npc, WorldPoint location, String solution, String questionText)
{
this(text, npc, -1, location, solution, questionText);
}
private CrypticClue(String text, String npc, int objectId, WorldPoint location, String solution)
{
this(text, npc, objectId, location, solution, null);
}
private CrypticClue(String text, String npc, int objectId, @Nullable WorldPoint location, String solution, @Nullable String questionText)
{
this.text = text;
this.npc = npc;
this.objectId = objectId;
this.location = location;
this.solution = solution;
this.questionText = questionText;
setRequiresSpade(getLocation() != null && getNpc() == null && objectId == -1);
}
@Override
public void makeOverlayHint(PanelComponent panelComponent, ClueScrollPlugin plugin)
{
panelComponent.getChildren().add(TitleComponent.builder().text("Cryptic Clue").build());
if (getNpc() != null)
{
panelComponent.getChildren().add(LineComponent.builder().left("NPC:").build());
panelComponent.getChildren().add(LineComponent.builder()
.left(getNpc())
.leftColor(TITLED_CONTENT_COLOR)
.build());
}
if (objectId != -1)
{
ObjectComposition object = plugin.getClient().getObjectDefinition(objectId);
if (object != null && object.getImpostorIds() != null)
{
object = object.getImpostor();
}
if (object != null)
{
panelComponent.getChildren().add(LineComponent.builder().left("Object:").build());
panelComponent.getChildren().add(LineComponent.builder()
.left(object.getName())
.leftColor(TITLED_CONTENT_COLOR)
.build());
}
}
panelComponent.getChildren().add(LineComponent.builder().left("Solution:").build());
panelComponent.getChildren().add(LineComponent.builder()
.left(getSolution())
.leftColor(TITLED_CONTENT_COLOR)
.build());
}
@Override
public void makeWorldOverlayHint(Graphics2D graphics, ClueScrollPlugin plugin)
{
// Mark dig location
if (getLocation() != null && getNpc() == null && objectId == -1)
{
LocalPoint localLocation = LocalPoint.fromWorld(plugin.getClient(), getLocation());
if (localLocation != null)
{
OverlayUtil.renderTileOverlay(plugin.getClient(), graphics, localLocation, plugin.getSpadeImage(), Color.ORANGE);
}
}
// Mark NPC
if (plugin.getNpcsToMark() != null)
{
for (NPC npc : plugin.getNpcsToMark())
{
OverlayUtil.renderActorOverlayImage(graphics, npc, plugin.getClueScrollImage(), Color.ORANGE, IMAGE_Z_OFFSET);
}
}
// Mark game object
if (objectId != -1)
{
net.runelite.api.Point mousePosition = plugin.getClient().getMouseCanvasPosition();
if (plugin.getObjectsToMark() != null)
{
for (TileObject gameObject : plugin.getObjectsToMark())
{
OverlayUtil.renderHoverableArea(graphics, gameObject.getClickbox(), mousePosition,
CLICKBOX_FILL_COLOR, CLICKBOX_BORDER_COLOR, CLICKBOX_HOVER_BORDER_COLOR);
OverlayUtil.renderImageLocation(plugin.getClient(), graphics, gameObject.getLocalLocation(), plugin.getClueScrollImage(), IMAGE_Z_OFFSET);
}
}
}
}
public static CrypticClue forText(String text)
{
for (CrypticClue clue : CLUES)
{
if (text.equalsIgnoreCase(clue.text) || text.equalsIgnoreCase(clue.questionText))
{
return clue;
}
}
return null;
}
@Override
public int[] getObjectIds()
{
return new int[] {objectId};
}
@Override
public String[] getNpcs()
{
return new String[] {npc};
}
}
| bsd-2-clause |
edgehosting/jira-dvcs-connector | jira-dvcs-connector-gitlab/src/main/java/org/gitlab/api/models/GitlabUser.java | 5255 | package org.gitlab.api.models;
import org.codehaus.jackson.annotate.JsonProperty;
import java.util.Date;
public class GitlabUser {
public static String URL = "/users";
public static String USERS_URL = "/users";
public static String USER_URL = "/user"; // for sudo based ops
private Integer _id;
private String _username;
private String _email;
private String _name;
private String _skype;
private String _linkedin;
private String _twitter;
private String _provider;
private String _state;
private boolean _blocked;
@JsonProperty("private_token")
private String _privateToken;
@JsonProperty("color_scheme_id")
private Integer _colorSchemeId;
@JsonProperty("provider")
private String _externProviderName;
@JsonProperty("website_url")
private String _websiteUrl;
@JsonProperty("created_at")
private Date _createdAt;
@JsonProperty("bio")
private String _bio;
@JsonProperty("dark_scheme")
private boolean _darkScheme;
@JsonProperty("theme_id")
private Integer _themeId;
@JsonProperty("extern_uid")
private String _externUid;
@JsonProperty("is_admin")
private boolean _isAdmin;
@JsonProperty("can_create_group")
private boolean _canCreateGroup;
@JsonProperty("can_create_project")
private boolean _canCreateProject;
@JsonProperty("can_create_team")
private boolean _canCreateTeam;
@JsonProperty("avatar_url")
private String _avatarUrl;
public Integer getId() {
return _id;
}
public void setId(Integer id) {
_id = id;
}
public String getUsername() {
return _username;
}
public void setUsername(String userName) {
_username = userName;
}
public String getEmail() {
return _email;
}
public void setEmail(String email) {
_email = email;
}
public String getName() {
return _name;
}
public void setName(String name) {
_name = name;
}
public boolean isBlocked() {
return _blocked;
}
public void setBlocked(boolean blocked) {
_blocked = blocked;
}
public Date getCreatedAt() {
return _createdAt;
}
public void setCreatedAt(Date createdAt) {
_createdAt = createdAt;
}
public String getBio() {
return _bio;
}
public void setBio(String bio) {
_bio = bio;
}
public String getSkype() {
return _skype;
}
public void setSkype(String skype) {
_skype = skype;
}
public String getLinkedin() {
return _linkedin;
}
public void setLinkedin(String linkedin) {
_linkedin = linkedin;
}
public String getTwitter() {
return _twitter;
}
public void setTwitter(String twitter) {
_twitter = twitter;
}
public boolean isDarkScheme() {
return _darkScheme;
}
public void setDarkScheme(boolean darkScheme) {
_darkScheme = darkScheme;
}
public Integer getThemeId() {
return _themeId;
}
public void setThemeId(Integer themeId) {
_themeId = themeId;
}
public String getExternUid() {
return _externUid;
}
public void setExternUid(String externUid) {
_externUid = externUid;
}
public String getProvider() {
return _provider;
}
public void setProvider(String provider) {
_provider = provider;
}
public String getState() {
return _state;
}
public void setState(String state) {
_state = state;
}
public String getExternProviderName() {
return _externProviderName;
}
public void setExternProviderName(String externProviderName) {
_externProviderName = externProviderName;
}
public String getWebsiteUrl() {
return _websiteUrl;
}
public void setWebsiteUrl(String websiteUrl) {
_websiteUrl = websiteUrl;
}
public boolean isAdmin() {
return _isAdmin;
}
public void setAdmin(boolean admin) {
_isAdmin = admin;
}
public boolean isCanCreateGroup() {
return _canCreateGroup;
}
public void setCanCreateGroup(boolean canCreateGroup) {
_canCreateGroup = canCreateGroup;
}
public boolean isCanCreateProject() {
return _canCreateProject;
}
public void setCanCreateProject(boolean canCreateProject) {
_canCreateProject = canCreateProject;
}
public boolean isCanCreateTeam() {
return _canCreateTeam;
}
public void setCanCreateTeam(boolean canCreateTeam) {
_canCreateTeam = canCreateTeam;
}
public String getAvatarUrl() {
return _avatarUrl;
}
public void setAvatarUrl(String avatarUrl) {
this._avatarUrl = avatarUrl;
}
public Integer getColorSchemeId() {
return _colorSchemeId;
}
public void setColorSchemeId(Integer colorSchemeId) {
this._colorSchemeId = colorSchemeId;
}
public String getPrivateToken() {
return _privateToken;
}
public void setPrivateToken(String privateToken) {
this._privateToken = privateToken;
}
}
| bsd-2-clause |
scifio/scifio | src/test/java/io/scif/img/cell/SCIFIOCellImgTest.java | 4140 | /*
* #%L
* SCIFIO library for reading and converting scientific file formats.
* %%
* Copyright (C) 2011 - 2021 SCIFIO developers.
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* #L%
*/
package io.scif.img.cell;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import io.scif.img.ImgOpener;
import io.scif.img.SCIFIOImgPlus;
import io.scif.io.location.TestImgLocation;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
/**
* Tests for the {@link SCIFIOCellImg} and related classes.
*
* @author Mark Hiner
*/
public class SCIFIOCellImgTest {
private static ImgOpener opener;
@BeforeClass
public static void createOpener() {
opener = new ImgOpener();
}
@AfterClass
public static void disposeOpener() {
opener.context().dispose();
}
/**
* Test that when a {@link SCIFIOCellImg} is opened and disposed, the
* associated reader is closed.
*/
@Test
public void testReaderCleanup() {
// Make an id that will trigger cell creation
TestImgLocation loc = TestImgLocation.builder().name("lotsofplanes").axes(
"X", "Y", "Z").lengths(256, 256, 100000).build();
final SCIFIOImgPlus<?> img = opener.openImgs(loc).get(0);
assertNotNull(((SCIFIOCellImg) img.getImg()).reader().getMetadata());
img.dispose();
assertNull(((SCIFIOCellImg) img.getImg()).reader().getMetadata());
}
// This test is currently disabled because it fails for unknown reasons.
// It passes from Eclipse, it passes from Maven on the command line, but it
// fails when run by Jenkins using Maven.
// We're testing the dispose behavior above, the purpose of this test is
// just
// to confirm that disposal occurs when an ImgPlus is garbage collected.
// Unfortunately, this will have to wait until we have a better
// understanding
// of how to test post-GC events.
// /**
// * Test that when a {@link SCIFIOCellImg} is opened and goes out of scope, the
// * associated reader is closed.
// */
// @Test
// public void testReaderOutOfScopeCleanup() {
// // Make an id that will trigger cell creation
// final String id = "lotsofplanes&axes=X,Y,Z&lengths=256,256,100000.fake";
// SCIFIOImgPlus<?> img = IO.open(id);
// assertNotNull(((SCIFIOCellImg) img.getImg()).reader().getMetadata());
// final WeakReference<Metadata> wr =
// new WeakReference<Metadata>(((SCIFIOCellImg) img.getImg()).reader()
// .getMetadata());
// img = null;
// long arraySize = MemoryTools.totalAvailableMemory();
// if (arraySize > Integer.MAX_VALUE) {
// arraySize = Integer.MAX_VALUE;
// }
// final long maxCounts =
// Math.round(Math.max(100,
// (2 * Math.ceil(((double)Runtime.getRuntime().maxMemory() / arraySize)))));
// for (int i = 0; i < maxCounts &&
// wr.get() != null; i++)
// {
// final byte[] tmp = new byte[(int) arraySize];
// }
// assertNull(wr.get());
// }
}
| bsd-2-clause |
gonzaca/projectgimy | src/Vista/LogAdmin.java | 12124 | package Vista;
import Controlador.Controlador;
import Modelo.Administrador;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class LogAdmin extends javax.swing.JFrame {
public LogAdmin() {
initComponents();
}
public LogAdmin(Controlador c) {
super("Login Administrador");
initComponents();
this.control = c;
Image icon = new ImageIcon(getClass().getResource("/Imagen/pgs-logo.png")).getImage();
setIconImage(icon);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
this.setExtendedState(JFrame.MAXIMIZED_BOTH);
this.setSize(screenSize);
this.setLocationRelativeTo(null);
this.setResizable(false);
admin = new Vista(control);
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jBlogin = new javax.swing.JButton();
jBCancel = new javax.swing.JButton();
jTFUser = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jPFContraseña = new javax.swing.JPasswordField();
jLabel5 = new javax.swing.JLabel();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenuItem1 = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagen/login_icon.png"))); // NOI18N
jLabel1.setToolTipText("");
jLabel2.setFont(new java.awt.Font("Tahoma", 3, 24)); // NOI18N
jLabel2.setText("Login Administrador");
jBlogin.setText("Login");
jBlogin.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jBloginActionPerformed(evt);
}
});
jBCancel.setText("Cancelar");
jBCancel.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jBCancelActionPerformed(evt);
}
});
jLabel3.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jLabel3.setText("Usuario:");
jLabel4.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
jLabel4.setText("Contraseña:");
jPFContraseña.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
jPFContraseñaKeyTyped(evt);
}
});
jLabel5.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagen/PGSBackgroundVista.PNG"))); // NOI18N
jMenu1.setText("Opciones");
jMenuItem1.setText("Crear Administrador");
jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem1ActionPerformed(evt);
}
});
jMenu1.add(jMenuItem1);
jMenuBar1.add(jMenu1);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addGap(33, 33, 33)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jTFUser, javax.swing.GroupLayout.PREFERRED_SIZE, 137, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jBlogin, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jBCancel, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jLabel4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jPFContraseña, javax.swing.GroupLayout.PREFERRED_SIZE, 137, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 253, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel5, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 792, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(72, 72, 72)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 104, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTFUser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(jPFContraseña, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(32, 32, 32)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jBCancel)
.addComponent(jBlogin)))
.addComponent(jLabel1))
.addContainerGap(120, Short.MAX_VALUE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel5, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jBloginActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBloginActionPerformed
java.awt.EventQueue.invokeLater(() -> {
try {
Administrador c = this.control.getDao().getAdmin(jTFUser.getText(), new String(jPFContraseña.getPassword()));
if (c != null) {
this.setVisible(false);
admin.setVisible(true);
control.setA(c);
} else {
JOptionPane.showMessageDialog(null, "Verifique que los datos esten correctos o que el usuario tenga permisos de acceso.");
}
} catch (Exception e) {
System.err.println("Error en LogCliente - Search cedula");
}
});
}//GEN-LAST:event_jBloginActionPerformed
private void jBCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBCancelActionPerformed
this.setVisible(false);;
SelectUser s = new SelectUser(control);
s.mostrar();
}//GEN-LAST:event_jBCancelActionPerformed
private void jPFContraseñaKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jPFContraseñaKeyTyped
if (evt.getKeyChar() == KeyEvent.VK_ENTER) {
jBlogin.doClick();
}
}//GEN-LAST:event_jPFContraseñaKeyTyped
private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
Registro r = new Registro(control);
}//GEN-LAST:event_jMenuItem1ActionPerformed
public void mostrar() {
this.setVisible(true);
}
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(LogAdmin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(LogAdmin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(LogAdmin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(LogAdmin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new LogAdmin().setVisible(true);
}
});
}
private Vista admin;
private Controlador control;
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jBCancel;
private javax.swing.JButton jBlogin;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem jMenuItem1;
private javax.swing.JPasswordField jPFContraseña;
private javax.swing.JTextField jTFUser;
// End of variables declaration//GEN-END:variables
}
| bsd-2-clause |
AndroidDeveloperLB/MultiTouchPlaceholderView | app/src/androidTest/java/lb/com/multi_touch_placeholder_view/ApplicationTest.java | 368 | package lb.com.multi_touch_placeholder_view;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application>
{
public ApplicationTest()
{
super(Application.class);
}
} | bsd-2-clause |
ianrenton/Gunboat | src/uk/co/marmablue/gunboat/bullets/Bullet.java | 1934 | package uk.co.marmablue.gunboat.bullets;
import java.util.ArrayList;
import uk.co.marmablue.gunboat.gui.GameRenderer;
import uk.co.marmablue.gunboat.miscobjects.RenderableGameObject;
import uk.co.marmablue.gunboat.model.Model;
import uk.co.marmablue.gunboat.ships.Ship;
public abstract class Bullet extends RenderableGameObject {
double damage = 0;
private boolean removable = false;
GameRenderer renderer;
private boolean allyControlled;
private boolean readyForCollisionCheck = false;
private double expiresAfter = 0;
public Bullet(Model model, double xPos, double yPos, double zPos, double heading, double speed, double damage, double range, GameRenderer renderer, boolean allyControlled) {
super(model, null, xPos, yPos, zPos, heading, speed);
this.damage = damage;
this.renderer = renderer;
this.allyControlled = allyControlled;
readyForCollisionCheck = true;
expiresAfter = range/speed*iterationRateHz;
}
@Override
public void iterate() {
super.iterate();
if (readyForCollisionCheck) {
if (allyControlled) {
removable = checkForCollisions(renderer.getEnemyShips());
} else {
removable = checkForCollisions(renderer.getAllyShips());
}
}
}
private boolean checkForCollisions(ArrayList<Ship> ships) {
for (Ship ship : ships) {
if (ship.checkForCollision(this)) {
ship.damage(damage);
return true;
}
}
return false;
}
public void setRemovable() {
removable = true;
}
public boolean hasExpired() {
if (removable || isOffScreen() || (iteration>expiresAfter)) {
this.stop();
return true;
} else return false;
}
public boolean isAllyControlled() {
return allyControlled;
}
}
| bsd-2-clause |
highsource/jaxb2-basics | tests/one/src/test/java/org/jvnet/jaxb2_commons/tests/one/HashCodeTest.java | 1013 | package org.jvnet.jaxb2_commons.tests.one;
import java.io.File;
import org.jvnet.jaxb2_commons.lang.JAXBCopyStrategy;
import org.jvnet.jaxb2_commons.lang.JAXBHashCodeStrategy;
import org.jvnet.jaxb2_commons.test.AbstractSamplesTest;
public class HashCodeTest extends AbstractSamplesTest {
@Override
protected void checkSample(File sample) throws Exception {
final Object lhs = createContext().createUnmarshaller().unmarshal(
sample);
final Object rhs = createContext().createUnmarshaller().unmarshal(
sample);
final Object chs = JAXBCopyStrategy.getInstance().copy(null, rhs);
final int leftHashCode = JAXBHashCodeStrategy.getInstance().hashCode(null,
0, lhs);
final int rightHashCode = JAXBHashCodeStrategy.getInstance().hashCode(null,
0, rhs);
final int copyHashCode = JAXBHashCodeStrategy.getInstance().hashCode(null,
0, chs);
assertEquals("Values must be equal.", leftHashCode, rightHashCode);
assertEquals("Values must be equal.", leftHashCode, copyHashCode);
}
}
| bsd-2-clause |
k-zen/Quary | src/net/apkc/quary/config/XMLBuilder.java | 5385 | /*
* Copyright (c) 2014, Andreas P. Koenzen <akc at apkc.net>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package net.apkc.quary.config;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import net.apkc.esxp.exceptions.AttributeNotFoundException;
import net.apkc.esxp.exceptions.ParserNotInitializedException;
import net.apkc.esxp.exceptions.TagNotFoundException;
import net.apkc.quary.definitions.index.IndexDefinition;
import net.apkc.quary.definitions.index.IndexDefinitionDB;
import net.apkc.quary.docs.QuaryDocument;
import net.apkc.quary.util.Constants;
import net.apkc.quary.util.Timer;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.log4j.Logger;
public final class XMLBuilder
{
private static final Logger LOG = Logger.getLogger(XMLBuilder.class.getName());
private static XMLProcessor processor = XMLProcessor.getInstance();
private XMLBuilder()
{
}
/**
* Creates a new Quary document based on information passed as an XML document.
* To index a document into Quary, it must be passed on as an XML file, and it
* must match a previously defined definition. If it's matched then it will be
* indexed where the definition says so, if not an exception is thrown and an
* error response is returned to the user.
*
* @param xml The XML file containing the data to be indexed.
*
* @return The XML message
*/
public static QuaryDocument parseExternalDocumentToQuaryDocument(String xml)
{
Timer timer = new Timer();
timer.starTimer();
// Re-start the parser and point to root node.
processor = processor.configure(new ByteArrayInputStream(xml.getBytes(StandardCharsets.UTF_8)), null, "root");
try {
// Look in the IndexDefinitionDB for a match. For now use the *definitionID* to look for a match.
IndexDefinition definition = IndexDefinitionDB.getInstance().getDefinition(processor.getTagAttribute("root", "root", "definitionID"));
// Match the XML file to the definition.
QuaryDocument doc = processor.buildQuaryDocument(definition).setSignature(DigestUtils.sha512Hex(xml)).setDefintionID(definition.getDefinitionID());
timer.endTimer();
if (LOG.isInfoEnabled()) {
LOG.info("Tiempo Unmarshall: " + timer.computeOperationTime(Timer.Time.MILLISECOND) + "ms");
}
return doc;
}
catch (ParserNotInitializedException | TagNotFoundException | AttributeNotFoundException e) {
LOG.fatal("Error procesando XML. Error: " + e.toString(), e);
return QuaryDocument.newBuild();
}
}
/**
* Creates a new definition object using data from an XML document.
*
* @param xml The XML document.
*
* @return A definition object.
*/
public static IndexDefinition parseDefinitionFile(InputStream xml)
{
Timer timer = new Timer();
timer.starTimer();
// Re-start the parser and point to root node.
processor = processor.configure(xml, XMLBuilder.class.getResourceAsStream(Constants.XSD_SCHEMA_FILE.getStringConstant()), "fields");
try {
IndexDefinition definition = IndexDefinition
.newBuild()
.setDefinitionID(processor.getTagAttribute("fields", "fields", "definitionID"))
.setScoreCoeficient(processor.getTagAttribute("fields", "fields", "scoreCoeficient"))
.setFields(processor.getFields());
timer.endTimer();
if (LOG.isInfoEnabled()) {
LOG.info("Tiempo Unmarshall: " + timer.computeOperationTime(Timer.Time.MILLISECOND) + "ms");
}
return definition;
}
catch (ParserNotInitializedException | TagNotFoundException | AttributeNotFoundException e) {
LOG.fatal("Error procesando XML. Error: " + e.toString(), e);
return IndexDefinition.newBuild();
}
}
}
| bsd-2-clause |
hyperfiction/HypFacebook | project/android/com/facebook/AuthorizationClient.java | 30883 | /**
* Copyright 2010-present Facebook.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook;
import android.Manifest;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.webkit.CookieSyncManager;
import ::APP_PACKAGE::.R;
import com.facebook.internal.ServerProtocol;
import com.facebook.internal.Utility;
import com.facebook.model.GraphMultiResult;
import com.facebook.model.GraphObject;
import com.facebook.model.GraphObjectList;
import com.facebook.model.GraphUser;
import com.facebook.widget.WebDialog;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
class AuthorizationClient implements Serializable {
private static final long serialVersionUID = 1L;
private static final String TAG = "Facebook-AuthorizationClient";
private static final String WEB_VIEW_AUTH_HANDLER_STORE =
"com.facebook.AuthorizationClient.WebViewAuthHandler.TOKEN_STORE_KEY";
private static final String WEB_VIEW_AUTH_HANDLER_TOKEN_KEY = "TOKEN";
List<AuthHandler> handlersToTry;
AuthHandler currentHandler;
transient Context context;
transient StartActivityDelegate startActivityDelegate;
transient OnCompletedListener onCompletedListener;
transient BackgroundProcessingListener backgroundProcessingListener;
transient boolean checkedInternetPermission;
AuthorizationRequest pendingRequest;
interface OnCompletedListener {
void onCompleted(Result result);
}
interface BackgroundProcessingListener {
void onBackgroundProcessingStarted();
void onBackgroundProcessingStopped();
}
interface StartActivityDelegate {
public void startActivityForResult(Intent intent, int requestCode);
public Activity getActivityContext();
}
void setContext(final Context context) {
this.context = context;
// We rely on individual requests to tell us how to start an activity.
startActivityDelegate = null;
}
void setContext(final Activity activity) {
this.context = activity;
// If we are used in the context of an activity, we will always use that activity to
// call startActivityForResult.
startActivityDelegate = new StartActivityDelegate() {
@Override
public void startActivityForResult(Intent intent, int requestCode) {
activity.startActivityForResult(intent, requestCode);
}
@Override
public Activity getActivityContext() {
return activity;
}
};
}
void startOrContinueAuth(AuthorizationRequest request) {
if (getInProgress()) {
continueAuth();
} else {
authorize(request);
}
}
void authorize(AuthorizationRequest request) {
if (request == null) {
return;
}
if (pendingRequest != null) {
throw new FacebookException("Attempted to authorize while a request is pending.");
}
if (request.needsNewTokenValidation() && !checkInternetPermission()) {
// We're going to need INTERNET permission later and don't have it, so fail early.
return;
}
pendingRequest = request;
handlersToTry = getHandlerTypes(request);
tryNextHandler();
}
void continueAuth() {
if (pendingRequest == null || currentHandler == null) {
throw new FacebookException("Attempted to continue authorization without a pending request.");
}
if (currentHandler.needsRestart()) {
currentHandler.cancel();
tryCurrentHandler();
}
}
boolean getInProgress() {
return pendingRequest != null && currentHandler != null;
}
void cancelCurrentHandler() {
if (currentHandler != null) {
currentHandler.cancel();
}
}
boolean onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == pendingRequest.getRequestCode()) {
return currentHandler.onActivityResult(requestCode, resultCode, data);
}
return false;
}
private List<AuthHandler> getHandlerTypes(AuthorizationRequest request) {
ArrayList<AuthHandler> handlers = new ArrayList<AuthHandler>();
final SessionLoginBehavior behavior = request.getLoginBehavior();
if (behavior.allowsKatanaAuth()) {
if (!request.isLegacy()) {
handlers.add(new GetTokenAuthHandler());
handlers.add(new KatanaLoginDialogAuthHandler());
}
handlers.add(new KatanaProxyAuthHandler());
}
if (behavior.allowsWebViewAuth()) {
handlers.add(new WebViewAuthHandler());
}
return handlers;
}
boolean checkInternetPermission() {
if (checkedInternetPermission) {
return true;
}
int permissionCheck = checkPermission(Manifest.permission.INTERNET);
if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
String errorType = context.getString(::APP_PACKAGE::.R.string.com_facebook_internet_permission_error_title);
String errorDescription = context.getString(::APP_PACKAGE::.R.string.com_facebook_internet_permission_error_message);
complete(Result.createErrorResult(errorType, errorDescription));
return false;
}
checkedInternetPermission = true;
return true;
}
void tryNextHandler() {
while (handlersToTry != null && !handlersToTry.isEmpty()) {
currentHandler = handlersToTry.remove(0);
boolean started = tryCurrentHandler();
if (started) {
return;
}
}
if (pendingRequest != null) {
// We went through all handlers without successfully attempting an auth.
completeWithFailure();
}
}
private void completeWithFailure() {
complete(Result.createErrorResult("Login attempt failed.", null));
}
boolean tryCurrentHandler() {
if (currentHandler.needsInternetPermission() && !checkInternetPermission()) {
return false;
}
return currentHandler.tryAuthorize(pendingRequest);
}
void completeAndValidate(Result outcome) {
// Do we need to validate a successful result (as in the case of a reauth)?
if (outcome.token != null && pendingRequest.needsNewTokenValidation()) {
validateSameFbidAndFinish(outcome);
} else {
// We're done, just notify the listener.
complete(outcome);
}
}
void complete(Result outcome) {
handlersToTry = null;
currentHandler = null;
pendingRequest = null;
notifyOnCompleteListener(outcome);
}
OnCompletedListener getOnCompletedListener() {
return onCompletedListener;
}
void setOnCompletedListener(OnCompletedListener onCompletedListener) {
this.onCompletedListener = onCompletedListener;
}
BackgroundProcessingListener getBackgroundProcessingListener() {
return backgroundProcessingListener;
}
void setBackgroundProcessingListener(BackgroundProcessingListener backgroundProcessingListener) {
this.backgroundProcessingListener = backgroundProcessingListener;
}
StartActivityDelegate getStartActivityDelegate() {
if (startActivityDelegate != null) {
return startActivityDelegate;
} else if (pendingRequest != null) {
// Wrap the request's delegate in our own.
return new StartActivityDelegate() {
@Override
public void startActivityForResult(Intent intent, int requestCode) {
pendingRequest.getStartActivityDelegate().startActivityForResult(intent, requestCode);
}
@Override
public Activity getActivityContext() {
return pendingRequest.getStartActivityDelegate().getActivityContext();
}
};
}
return null;
}
int checkPermission(String permission) {
return context.checkCallingOrSelfPermission(permission);
}
void validateSameFbidAndFinish(Result pendingResult) {
if (pendingResult.token == null) {
throw new FacebookException("Can't validate without a token");
}
RequestBatch batch = createReauthValidationBatch(pendingResult);
notifyBackgroundProcessingStart();
batch.executeAsync();
}
RequestBatch createReauthValidationBatch(final Result pendingResult) {
// We need to ensure that the token we got represents the same fbid as the old one. We issue
// a "me" request using the current token, a "me" request using the new token, and a "me/permissions"
// request using the current token to get the permissions of the user.
final ArrayList<String> fbids = new ArrayList<String>();
final ArrayList<String> tokenPermissions = new ArrayList<String>();
final String newToken = pendingResult.token.getToken();
Request.Callback meCallback = new Request.Callback() {
@Override
public void onCompleted(Response response) {
try {
GraphUser user = response.getGraphObjectAs(GraphUser.class);
if (user != null) {
fbids.add(user.getId());
}
} catch (Exception ex) {
}
}
};
String validateSameFbidAsToken = pendingRequest.getPreviousAccessToken();
Request requestCurrentTokenMe = createGetProfileIdRequest(validateSameFbidAsToken);
requestCurrentTokenMe.setCallback(meCallback);
Request requestNewTokenMe = createGetProfileIdRequest(newToken);
requestNewTokenMe.setCallback(meCallback);
Request requestCurrentTokenPermissions = createGetPermissionsRequest(validateSameFbidAsToken);
requestCurrentTokenPermissions.setCallback(new Request.Callback() {
@Override
public void onCompleted(Response response) {
try {
GraphMultiResult result = response.getGraphObjectAs(GraphMultiResult.class);
if (result != null) {
GraphObjectList<GraphObject> data = result.getData();
if (data != null && data.size() == 1) {
GraphObject permissions = data.get(0);
// The keys are the permission names.
tokenPermissions.addAll(permissions.asMap().keySet());
}
}
} catch (Exception ex) {
}
}
});
RequestBatch batch = new RequestBatch(requestCurrentTokenMe, requestNewTokenMe,
requestCurrentTokenPermissions);
batch.setBatchApplicationId(pendingRequest.getApplicationId());
batch.addCallback(new RequestBatch.Callback() {
@Override
public void onBatchCompleted(RequestBatch batch) {
try {
Result result = null;
if (fbids.size() == 2 && fbids.get(0) != null && fbids.get(1) != null &&
fbids.get(0).equals(fbids.get(1))) {
// Modify the token to have the right permission set.
AccessToken tokenWithPermissions = AccessToken
.createFromTokenWithRefreshedPermissions(pendingResult.token,
tokenPermissions);
result = Result.createTokenResult(tokenWithPermissions);
} else {
result = Result
.createErrorResult("User logged in as different Facebook user.", null);
}
complete(result);
} catch (Exception ex) {
complete(Result.createErrorResult("Caught exception", ex.getMessage()));
} finally {
notifyBackgroundProcessingStop();
}
}
});
return batch;
}
Request createGetPermissionsRequest(String accessToken) {
Bundle parameters = new Bundle();
parameters.putString("fields", "id");
parameters.putString("access_token", accessToken);
return new Request(null, "me/permissions", parameters, HttpMethod.GET, null);
}
Request createGetProfileIdRequest(String accessToken) {
Bundle parameters = new Bundle();
parameters.putString("fields", "id");
parameters.putString("access_token", accessToken);
return new Request(null, "me", parameters, HttpMethod.GET, null);
}
private void notifyOnCompleteListener(Result outcome) {
if (onCompletedListener != null) {
onCompletedListener.onCompleted(outcome);
}
}
private void notifyBackgroundProcessingStart() {
if (backgroundProcessingListener != null) {
backgroundProcessingListener.onBackgroundProcessingStarted();
}
}
private void notifyBackgroundProcessingStop() {
if (backgroundProcessingListener != null) {
backgroundProcessingListener.onBackgroundProcessingStopped();
}
}
abstract class AuthHandler implements Serializable {
private static final long serialVersionUID = 1L;
abstract boolean tryAuthorize(AuthorizationRequest request);
boolean onActivityResult(int requestCode, int resultCode, Intent data) {
return false;
}
boolean needsRestart() {
return false;
}
boolean needsInternetPermission() {
return false;
}
void cancel() {
}
}
class WebViewAuthHandler extends AuthHandler {
private static final long serialVersionUID = 1L;
private transient WebDialog loginDialog;
@Override
boolean needsRestart() {
// Because we are presenting WebView UI within the current context, we need to explicitly
// restart the process if the context goes away and is recreated.
return true;
}
@Override
boolean needsInternetPermission() {
return true;
}
@Override
void cancel() {
if (loginDialog != null) {
loginDialog.dismiss();
loginDialog = null;
}
}
@Override
boolean tryAuthorize(final AuthorizationRequest request) {
String applicationId = request.getApplicationId();
Bundle parameters = new Bundle();
if (!Utility.isNullOrEmpty(request.getPermissions())) {
parameters.putString(ServerProtocol.DIALOG_PARAM_SCOPE, TextUtils.join(",", request.getPermissions()));
}
String previousToken = request.getPreviousAccessToken();
if (!Utility.isNullOrEmpty(previousToken) && (previousToken.equals(loadCookieToken()))) {
parameters.putString(ServerProtocol.DIALOG_PARAM_ACCESS_TOKEN, previousToken);
} else {
// The call to clear cookies will create the first instance of CookieSyncManager if necessary
Utility.clearFacebookCookies(context);
}
WebDialog.OnCompleteListener listener = new WebDialog.OnCompleteListener() {
@Override
public void onComplete(Bundle values, FacebookException error) {
onWebDialogComplete(request, values, error);
}
};
WebDialog.Builder builder =
new AuthDialogBuilder(getStartActivityDelegate().getActivityContext(), applicationId, parameters)
.setOnCompleteListener(listener);
loginDialog = builder.build();
loginDialog.show();
return true;
}
void onWebDialogComplete(AuthorizationRequest request, Bundle values,
FacebookException error) {
Result outcome;
if (values != null) {
AccessToken token = AccessToken
.createFromWebBundle(request.getPermissions(), values, AccessTokenSource.WEB_VIEW);
outcome = Result.createTokenResult(token);
// Ensure any cookies set by the dialog are saved
// This is to work around a bug where CookieManager may fail to instantiate if CookieSyncManager
// has never been created.
CookieSyncManager syncManager = CookieSyncManager.createInstance(context);
syncManager.sync();
saveCookieToken(token.getToken());
} else {
if (error instanceof FacebookOperationCanceledException) {
outcome = Result.createCancelResult("User canceled log in.");
} else {
outcome = Result.createErrorResult(error.getMessage(), null);
}
}
completeAndValidate(outcome);
}
private void saveCookieToken(String token) {
Context context = getStartActivityDelegate().getActivityContext();
SharedPreferences sharedPreferences = context.getSharedPreferences(
WEB_VIEW_AUTH_HANDLER_STORE,
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(WEB_VIEW_AUTH_HANDLER_TOKEN_KEY, token);
if (!editor.commit()) {
Utility.logd(TAG, "Could not update saved web view auth handler token.");
}
}
private String loadCookieToken() {
Context context = getStartActivityDelegate().getActivityContext();
SharedPreferences sharedPreferences = context.getSharedPreferences(
WEB_VIEW_AUTH_HANDLER_STORE,
Context.MODE_PRIVATE);
return sharedPreferences.getString(WEB_VIEW_AUTH_HANDLER_TOKEN_KEY, "");
}
}
class GetTokenAuthHandler extends AuthHandler {
private static final long serialVersionUID = 1L;
private transient GetTokenClient getTokenClient;
@Override
void cancel() {
if (getTokenClient != null) {
getTokenClient.cancel();
getTokenClient = null;
}
}
boolean tryAuthorize(final AuthorizationRequest request) {
getTokenClient = new GetTokenClient(context, request.getApplicationId());
if (!getTokenClient.start()) {
return false;
}
notifyBackgroundProcessingStart();
GetTokenClient.CompletedListener callback = new GetTokenClient.CompletedListener() {
@Override
public void completed(Bundle result) {
getTokenCompleted(request, result);
}
};
getTokenClient.setCompletedListener(callback);
return true;
}
void getTokenCompleted(AuthorizationRequest request, Bundle result) {
getTokenClient = null;
notifyBackgroundProcessingStop();
if (result != null) {
ArrayList<String> currentPermissions = result.getStringArrayList(NativeProtocol.EXTRA_PERMISSIONS);
List<String> permissions = request.getPermissions();
if ((currentPermissions != null) &&
((permissions == null) || currentPermissions.containsAll(permissions))) {
// We got all the permissions we needed, so we can complete the auth now.
AccessToken token = AccessToken
.createFromNativeLogin(result, AccessTokenSource.FACEBOOK_APPLICATION_SERVICE);
Result outcome = Result.createTokenResult(token);
completeAndValidate(outcome);
return;
}
// We didn't get all the permissions we wanted, so update the request with just the permissions
// we still need.
ArrayList<String> newPermissions = new ArrayList<String>();
for (String permission : permissions) {
if (!currentPermissions.contains(permission)) {
newPermissions.add(permission);
}
}
request.setPermissions(newPermissions);
}
tryNextHandler();
}
}
abstract class KatanaAuthHandler extends AuthHandler {
private static final long serialVersionUID = 1L;
protected boolean tryIntent(Intent intent, int requestCode) {
if (intent == null) {
return false;
}
try {
getStartActivityDelegate().startActivityForResult(intent, requestCode);
} catch (ActivityNotFoundException e) {
return false;
}
return true;
}
}
class KatanaLoginDialogAuthHandler extends KatanaAuthHandler {
private static final long serialVersionUID = 1L;
@Override
boolean tryAuthorize(AuthorizationRequest request) {
Intent intent = NativeProtocol.createLoginDialog20121101Intent(context, request.getApplicationId(),
new ArrayList<String>(request.getPermissions()),
request.getDefaultAudience().getNativeProtocolAudience());
return tryIntent(intent, request.getRequestCode());
}
@Override
boolean onActivityResult(int requestCode, int resultCode, Intent data) {
Result outcome;
if (data == null) {
// This happens if the user presses 'Back'.
outcome = Result.createCancelResult("Operation canceled");
} else if (NativeProtocol.isServiceDisabledResult20121101(data)) {
outcome = null;
} else if (resultCode == Activity.RESULT_CANCELED) {
outcome = Result.createCancelResult(
data.getStringExtra(NativeProtocol.STATUS_ERROR_DESCRIPTION));
} else if (resultCode != Activity.RESULT_OK) {
outcome = Result.createErrorResult("Unexpected resultCode from authorization.", null);
} else {
outcome = handleResultOk(data);
}
if (outcome != null) {
completeAndValidate(outcome);
} else {
tryNextHandler();
}
return true;
}
private Result handleResultOk(Intent data) {
Bundle extras = data.getExtras();
String errorType = extras.getString(NativeProtocol.STATUS_ERROR_TYPE);
if (errorType == null) {
return Result.createTokenResult(
AccessToken.createFromNativeLogin(extras, AccessTokenSource.FACEBOOK_APPLICATION_NATIVE));
} else if (NativeProtocol.ERROR_SERVICE_DISABLED.equals(errorType)) {
return null;
} else if (NativeProtocol.ERROR_USER_CANCELED.equals(errorType)) {
return Result.createCancelResult(null);
} else {
return Result.createErrorResult(errorType, extras.getString("error_description"));
}
}
}
class KatanaProxyAuthHandler extends KatanaAuthHandler {
private static final long serialVersionUID = 1L;
@Override
boolean tryAuthorize(AuthorizationRequest request) {
Intent intent = NativeProtocol.createProxyAuthIntent(context,
request.getApplicationId(), request.getPermissions());
return tryIntent(intent, request.getRequestCode());
}
@Override
boolean onActivityResult(int requestCode, int resultCode, Intent data) {
// Handle stuff
Result outcome;
if (data == null) {
// This happens if the user presses 'Back'.
outcome = Result.createCancelResult("Operation canceled");
} else if (resultCode == Activity.RESULT_CANCELED) {
outcome = Result.createCancelResult(data.getStringExtra("error"));
} else if (resultCode != Activity.RESULT_OK) {
outcome = Result.createErrorResult("Unexpected resultCode from authorization.", null);
} else {
outcome = handleResultOk(data);
}
if (outcome != null) {
completeAndValidate(outcome);
} else {
tryNextHandler();
}
return true;
}
private Result handleResultOk(Intent data) {
Bundle extras = data.getExtras();
String error = extras.getString("error");
if (error == null) {
error = extras.getString("error_type");
}
if (error == null) {
AccessToken token = AccessToken.createFromWebBundle(pendingRequest.getPermissions(), extras,
AccessTokenSource.FACEBOOK_APPLICATION_WEB);
return Result.createTokenResult(token);
} else if (ServerProtocol.errorsProxyAuthDisabled.contains(error)) {
return null;
} else if (ServerProtocol.errorsUserCanceled.contains(error)) {
return Result.createCancelResult(null);
} else {
return Result.createErrorResult(error, extras.getString("error_description"));
}
}
}
static class AuthDialogBuilder extends WebDialog.Builder {
private static final String OAUTH_DIALOG = "oauth";
static final String REDIRECT_URI = "fbconnect://success";
public AuthDialogBuilder(Context context, String applicationId, Bundle parameters) {
super(context, applicationId, OAUTH_DIALOG, parameters);
}
@Override
public WebDialog build() {
Bundle parameters = getParameters();
parameters.putString(ServerProtocol.DIALOG_PARAM_REDIRECT_URI, REDIRECT_URI);
parameters.putString(ServerProtocol.DIALOG_PARAM_CLIENT_ID, getApplicationId());
return new WebDialog(getContext(), OAUTH_DIALOG, parameters, getTheme(), getListener());
}
}
static class AuthorizationRequest implements Serializable {
private static final long serialVersionUID = 1L;
private transient final StartActivityDelegate startActivityDelegate;
private SessionLoginBehavior loginBehavior;
private int requestCode;
private boolean isLegacy = false;
private List<String> permissions;
private SessionDefaultAudience defaultAudience;
private String applicationId;
private String previousAccessToken;
AuthorizationRequest(SessionLoginBehavior loginBehavior, int requestCode, boolean isLegacy,
List<String> permissions, SessionDefaultAudience defaultAudience, String applicationId,
String validateSameFbidAsToken, StartActivityDelegate startActivityDelegate) {
this.loginBehavior = loginBehavior;
this.requestCode = requestCode;
this.isLegacy = isLegacy;
this.permissions = permissions;
this.defaultAudience = defaultAudience;
this.applicationId = applicationId;
this.previousAccessToken = validateSameFbidAsToken;
this.startActivityDelegate = startActivityDelegate;
}
StartActivityDelegate getStartActivityDelegate() {
return startActivityDelegate;
}
List<String> getPermissions() {
return permissions;
}
void setPermissions(List<String> permissions) {
this.permissions = permissions;
}
SessionLoginBehavior getLoginBehavior() {
return loginBehavior;
}
int getRequestCode() {
return requestCode;
}
SessionDefaultAudience getDefaultAudience() {
return defaultAudience;
}
String getApplicationId() {
return applicationId;
}
boolean isLegacy() {
return isLegacy;
}
void setIsLegacy(boolean isLegacy) {
this.isLegacy = isLegacy;
}
String getPreviousAccessToken() {
return previousAccessToken;
}
boolean needsNewTokenValidation() {
return previousAccessToken != null && !isLegacy;
}
}
static class Result implements Serializable {
private static final long serialVersionUID = 1L;
enum Code {
SUCCESS,
CANCEL,
ERROR
}
final Code code;
final AccessToken token;
final String errorMessage;
private Result(Code code, AccessToken token, String errorMessage) {
this.token = token;
this.errorMessage = errorMessage;
this.code = code;
}
static Result createTokenResult(AccessToken token) {
return new Result(Code.SUCCESS, token, null);
}
static Result createCancelResult(String message) {
return new Result(Code.CANCEL, null, message);
}
static Result createErrorResult(String errorType, String errorDescription) {
String message = errorType;
if (errorDescription != null) {
message += ": " + errorDescription;
}
return new Result(Code.ERROR, null, message);
}
}
}
| bsd-2-clause |
opf-labs/jhove2 | src/main/java/org/jhove2/module/format/icc/profile/MonochromeDisplayProfile.java | 6477 | /* JHOVE2 - Next-generation architecture for format-aware characterization
*
* Copyright (c) 2009 by The Regents of the University of California,
* Ithaka Harbors, Inc., and The Board of Trustees of the Leland Stanford
* Junior University.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* o Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* o Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* o Neither the name of the University of California/California Digital
* Library, Ithaka Harbors/Portico, or Stanford University, nor the names of
* its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package org.jhove2.module.format.icc.profile;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.jhove2.annotation.ReportableProperty;
import org.jhove2.core.JHOVE2;
import org.jhove2.core.JHOVE2Exception;
import org.jhove2.core.Message;
import org.jhove2.core.Message.Context;
import org.jhove2.core.Message.Severity;
import org.jhove2.core.format.Format;
import org.jhove2.core.io.Input;
import org.jhove2.core.source.Source;
import org.jhove2.module.format.AbstractFormatProfile;
import org.jhove2.module.format.Validator;
import org.jhove2.module.format.icc.ICCModule;
import org.jhove2.module.format.icc.ICCTag;
import org.jhove2.module.format.icc.ICCTagTable;
import org.jhove2.persist.FormatProfileAccessor;
import com.sleepycat.persist.model.Persistent;
/** ICC monochrome display profile, as defined in ICC.1:2004-10, \u00a7 8.4.4.
*
* @author slabrams
*/
@Persistent
public class MonochromeDisplayProfile
extends AbstractFormatProfile
implements Validator
{
/** Profile version identifier. */
public static final String VERSION = "2.0.0";
/** Profile release date. */
public static final String RELEASE = "2010-09-10";
/** Profile rights statement. */
public static final String RIGHTS =
"Copyright 2010 by The Regents of the University of California. " +
"Available under the terms of the BSD license.";
/** Profile validation coverage. */
public static final Coverage COVERAGE = Coverage.Inclusive;
/** Validation status. */
protected Validity isValid;
/** Missing required tag messages. */
protected List<Message> missingRequiredTagMessages;
/** Instantiate a new <code>MonochromeDisplayProfile</code>
* @param format Profile format
* @param formatProfileAccessor persistence manager
*/
public MonochromeDisplayProfile(Format format, FormatProfileAccessor formatProfileAccessor)
{
super(VERSION, RELEASE, RIGHTS, format, formatProfileAccessor);
this.isValid = Validity.Undetermined;
this.missingRequiredTagMessages = new ArrayList<Message>();
}
@SuppressWarnings("unused")
private MonochromeDisplayProfile(){
this(null,null);
}
/** Validate the profile.
* @param jhove2 JHOVE2 framework
* @param source ICC source unit
* @param input ICC source input
* @return Validation status
* @see org.jhove2.module.format.Validator#validate(org.jhove2.core.JHOVE2, org.jhove2.core.source.Source, org.jhove2.core.io.Input)
*/
@Override
public Validity validate(JHOVE2 jhove2, Source source, Input input)
throws JHOVE2Exception
{
if (this.getFormatModule() != null) {
ICCTagTable table = ((ICCModule) this.getFormatModule()).getTagTable();
if (table != null) {
if (table.hasCommonRequirements()) {
this.isValid = Validity.True;
boolean hasGrayTRCTag = false;
List<ICCTag> tags = table.getTags();
Iterator<ICCTag> iter = tags.iterator();
while (iter.hasNext()) {
ICCTag tag = iter.next();
String signature = tag.getSignature_raw();
if (signature.equals("kTRC")) {
hasGrayTRCTag = true;
}
}
if (!hasGrayTRCTag) {
this.isValid = Validity.False;
Object [] args = new Object [] {"GrayTRC (\"kTRC\")"};
Message msg = new Message(Severity.WARNING, Context.OBJECT,
"org.jhove2.module.format.icc.ICCTagTable.MissingRequiredTag",
args, jhove2.getConfigInfo());
this.missingRequiredTagMessages.add(msg);
}
}
}
}
return this.isValid;
}
/** Get profile coverage.
* @return Profile coverage
* @see org.jhove2.module.format.Validator#getCoverage()
*/
@Override
public Coverage getCoverage()
{
return COVERAGE;
}
/** Get missing required tag messages.
* @return missing required messages
*/
@ReportableProperty(order=1, value="Missing required tags.",
ref="ICC.1:2004-10, \u00a7 8.4.4")
public List<Message> getMissingRequiredTagMessages() {
return this.missingRequiredTagMessages;
}
/** Get validation status.
* @return Validation status
* @see org.jhove2.module.format.Validator#isValid()
*/
@Override
public Validity isValid()
{
return this.isValid;
}
}
| bsd-2-clause |
intarsys/native-c | src/de/intarsys/nativec/api/INativeHandle.java | 8674 | /*
* Copyright (c) 2008, intarsys consulting GmbH
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* - Neither the name of intarsys nor the names of its contributors may be used
* to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package de.intarsys.nativec.api;
/**
* A "handle" to a piece of memory (in c space).
* <p>
* The handle combines an address and a memory chunk of a specified size.
*/
public interface INativeHandle {
/**
* The start address of the memory chunk
*
* @return The start address of the memory chunk
*/
public long getAddress();
/**
* Marshal the data at byte offset <code>index</code> from the start of the
* memory chunk to a byte.
*
* @param index
* The byte offset from the start of the memory chunk
* @return A byte marshaled from the memory chunk
*/
public byte getByte(int index);
/**
* Marshal the data at byte offset <code>index</code> from the start of the
* memory chunk to a byte array of length <code>count</code>.
*
* @param index
* The byte offset from the start of the memory chunk
* @param count
* The size of the byte array
* @return A byte array marshaled from the memory chunk
*/
public byte[] getByteArray(int index, int count);
/**
* Marshal the data at byte offset <code>index</code> from the start of the
* memory chunk to a long. Get only the "platform" number of bytes.
*
* @param index
* The byte offset from the start of the memory chunk
* @return A long marshaled from the memory chunk
*/
public long getCLong(int index);
/**
* Marshal the data at byte offset <code>index</code> from the start of the
* memory chunk to an int.
*
* @param index
* The byte offset from the start of the memory chunk
* @return An int marshaled from the memory chunk
*/
public int getInt(int index);
/**
* Marshal the data at byte offset <code>index</code> from the start of the
* memory chunk to a long value (which is always 8 byte).
*
* @param index
* The byte offset from the start of the memory chunk
* @return A long marshaled from the memory chunk
*/
public long getLong(int index);
/**
* Marshal the data at byte offset <code>index</code> from the start of the
* memory chunk to an {@link INativeHandle}.
*
* @param index
* The byte offset from the start of the memory chunk
* @return An {@link INativeHandle} marshaled from the memory chunk
*/
public INativeHandle getNativeHandle(int index);
/**
* Marshal the data at byte offset <code>index</code> from the start of the
* memory chunk to a short.
*
* @param index
* The byte offset from the start of the memory chunk
* @return A short marshaled from the memory chunk
*/
public short getShort(int index);
/**
* The size for the handle in bytes.
* <p>
* You can not access bytes from outside the range defined by getAdddress +
* size.
*
*/
public int getSize();
/**
* Marshal the data at byte offset <code>index</code> from the start of the
* memory chunk to a String.
*
* @param index
* The byte offset from the start of the memory chunk
* @return A String marshaled from the memory chunk
*/
public String getString(int index);
/**
* Marshal the data at byte offset <code>index</code> from the start of the
* memory chunk to a String using the platform wide character conversion.
*
* @param index
* The byte offset from the start of the memory chunk
* @return A String marshaled from the memory chunk
*/
public String getWideString(int index);
/**
* Create a new {@link INativeHandle}, offset from this by
* <code>offset</code> bytes.
*
* @param offset
* The byte offset from the start of the memory chunk
* @return A new {@link INativeHandle} pointing to "getAddress() + offset".
*/
public INativeHandle offset(int offset);
/**
* Write a byte to the memory at byte offset <code>index</code> from the
* start of the memory chunk.
*
* @param index
* The byte offset from the start of the memory chunk
* @param value
* The value to write.
*/
public void setByte(int index, byte value);
/**
* Write a byte array to the memory at byte offset <code>index</code> from
* the start of the memory chunk. The method will write
* <code>valueCount</code> bytes from <code>value</code> starting at
* <code>valueOffset</code>.
*
* @param index
* The byte offset from the start of the memory chunk
* @param value
* The value to write.
*/
public void setByteArray(int index, byte[] value, int valueOffset,
int valueCount);
/**
* Write a long to the memory at byte offset <code>index</code> from the
* start of the memory chunk. Write only the "platform" number of bytes. The
* caller is responsible for observing the value range.
*
* @param index
* The byte offset from the start of the memory chunk
* @param value
* The value to write.
*/
public void setCLong(int index, long value);
/**
* Write an int to the memory at byte offset <code>index</code> from the
* start of the memory chunk.
*
* @param index
* The byte offset from the start of the memory chunk
* @param value
* The value to write.
*/
public void setInt(int index, int value);
/**
* Write a long to the memory at byte offset <code>index</code> from the
* start of the memory chunk.
*
* @param index
* The byte offset from the start of the memory chunk
* @param value
* The value to write.
*/
public void setLong(int index, long value);
/**
* Write an {@link INativeHandle} to the memory at byte offset
* <code>index</code> from the start of the memory chunk.
*
* @param index
* The byte offset from the start of the memory chunk
* @param valueHandle
* The value to write.
*/
public void setNativeHandle(int index, INativeHandle valueHandle);
/**
* Write a short to the memory at byte offset <code>index</code> from the
* start of the memory chunk.
*
* @param index
* The byte offset from the start of the memory chunk
* @param value
* The value to write.
*/
public void setShort(int index, short value);
/**
* Set the valid size for the handle to <code>count</code> bytes.
* <p>
* You can not access bytes from outside the range defined by getAdddress +
* size.
*
* @param count
* The size of the memory managed by the {@link INativeHandle}
*/
public void setSize(int count);
/**
* Write a String to the memory at byte offset <code>index</code>from the
* start of the memory chunk.
*
* @param index
* The byte offset from the start of the memory chunk
* @param value
* The value to write.
*/
public void setString(int index, String value);
/**
* Write a String to the memory at byte offset <code>index</code>from the
* start of the memory chunk using the platform wide character conversion.
*
* @param index
* The byte offset from the start of the memory chunk
* @param value
* The value to write.
*/
public void setWideString(int index, String value);
}
| bsd-3-clause |
jdfekete/obvious | obvious-prefuse/src/main/java/obvious/prefuse/data/PrefuseObviousEdge.java | 2974 | /*
* Copyright (c) 2009, INRIA
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of INRIA nor the names of its contributors may
* be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package obvious.prefuse.data;
import obvious.data.Edge;
/**
* This class is in an implementation of the {@link obvious.data.Edge Edge}
* interface based on Prefuse Edge class. Since the Edge interface is
* only a tagging one, this class simply implements the Edge interface and
* extends {@link obvious.prefuse.data PrefuseObviousTuple PrefuseObviousTuple}
* class.
* @author Pierre-Luc Hemery
* @see obvious.data.Edge
* @see obvious.prefuse.data.PrefuseObviousTuple
*/
public class PrefuseObviousEdge extends PrefuseObviousTuple implements Edge {
/**
* Constructor for PrefuseObviousEdge.
* @param edge a prefuse Edge
*/
public PrefuseObviousEdge(prefuse.data.Edge edge) {
super(edge);
}
/*
* Indicates if the current edge is equals to this object.
* For a PrefuseObviousEdge its means that their node id/key are the same.
* @param obj test object
* @return true if the two nodes id/keys are equal
*/
@Override
public boolean equals(Object obj) {
try {
boolean rowEqual = this.getRow() == ((PrefuseObviousEdge) obj).getRow();
return rowEqual;
} catch (ClassCastException e) {
return false;
}
}
@Override
public int hashCode() {
final int startValue = 7;
int result = startValue;
final int multiplier = 11;
return result * multiplier + this.getRow();
}
}
| bsd-3-clause |
synergynet/synergynet2.5 | synergynet2.5/src/main/java/synergynetframework/appsystem/contentsystem/jme/items/JMERoundContentItem.java | 2539 | /*
* Copyright (c) 2008 University of Durham, England All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met: *
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer. * Redistributions in binary
* form must reproduce the above copyright notice, this list of conditions and
* the following disclaimer in the documentation and/or other materials provided
* with the distribution. * Neither the name of 'SynergyNet' nor the names of
* its contributors may be used to endorse or promote products derived from this
* software without specific prior written permission. THIS SOFTWARE IS PROVIDED
* BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package synergynetframework.appsystem.contentsystem.jme.items;
import synergynetframework.appsystem.contentsystem.items.ContentItem;
import synergynetframework.appsystem.contentsystem.items.implementation.interfaces.IRoundContentItemImplementation;
import com.jme.scene.Spatial;
/**
* The Class JMERoundContentItem.
*/
public class JMERoundContentItem extends JMEOrthoContentItem implements
IRoundContentItemImplementation {
/**
* Instantiates a new JME round content item.
*
* @param contentItem
* the content item
* @param spatial
* the spatial
*/
public JMERoundContentItem(ContentItem contentItem, Spatial spatial) {
super(contentItem, spatial);
}
/*
* (non-Javadoc)
* @see
* synergynetframework.appsystem.contentsystem.items.implementation.interfaces
* .IRoundContentItemImplementation#setRadius(float)
*/
@Override
public void setRadius(float radius) {
}
}
| bsd-3-clause |
sebastiencaille/sky-lib | testcase-writer/gui/src/main/java/ch/scaille/tcwriter/gui/editors/params/TestParameterModel.java | 2367 | package ch.scaille.tcwriter.gui.editors.params;
import ch.scaille.gui.mvc.GuiModel;
import ch.scaille.gui.mvc.properties.ListProperty;
import ch.scaille.gui.mvc.properties.ObjectProperty;
import ch.scaille.tcwriter.generators.model.testapi.TestParameterFactory;
import ch.scaille.tcwriter.generators.model.testcase.TestParameterValue;
import ch.scaille.tcwriter.generators.model.testcase.TestReference;
import ch.scaille.tcwriter.gui.frame.TCWriterController;
public class TestParameterModel extends GuiModel {
private final ObjectProperty<TestParameterFactory.ParameterNature> valueNature;
private final ObjectProperty<String> simpleValue;
private final ObjectProperty<TestReference> selectedReference;
private final ListProperty<TestReference> references;
private final ObjectProperty<TestParameterFactory> testApi;
private final ObjectProperty<TestParameterValue> editedParameterValue;
private final String prefix;
public TestParameterModel(final String prefix, final TCWriterController guiController,
final ObjectProperty<TestParameterFactory> testApi,
final ObjectProperty<TestParameterValue> editedParameterValue) {
super(with(guiController.getScopedChangeSupport().getMain().scoped(prefix + "-controller")));
this.prefix = prefix;
this.editedParameterValue = editedParameterValue;
this.testApi = testApi;
valueNature = new ObjectProperty<>(prefix + "-nature", this);
simpleValue = editedParameterValue.child(prefix + "-simpleValue", TestParameterValue::getSimpleValue,
TestParameterValue::setSimpleValue);
selectedReference = new ObjectProperty<>(prefix + "-reference", this);
references = new ListProperty<>(prefix + "-references", this);
editedParameterValue.addListener(getPropertySupport().detachWhenPropLoading());
}
public String getPrefix() {
return prefix;
}
public ObjectProperty<TestParameterFactory.ParameterNature> getValueNature() {
return valueNature;
}
public ObjectProperty<String> getSimpleValue() {
return simpleValue;
}
public ListProperty<TestReference> getReferences() {
return references;
}
public ObjectProperty<TestReference> getSelectedReference() {
return selectedReference;
}
public ObjectProperty<TestParameterFactory> getTestApi() {
return testApi;
}
public ObjectProperty<TestParameterValue> getEditedParameterValue() {
return editedParameterValue;
}
}
| bsd-3-clause |
xebialabs/vijava | src/com/vmware/vim25/HostIncompatibleForFaultToleranceReason.java | 1995 | /*================================================================================
Copyright (c) 2012 Steve Jin. All Rights Reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of VMware, Inc. nor the names of its contributors may be used
to endorse or promote products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL VMWARE, INC. OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
================================================================================*/
package com.vmware.vim25;
/**
* @author Steve Jin (http://www.doublecloud.org)
* @version 5.1
*/
public enum HostIncompatibleForFaultToleranceReason {
product ("product"),
processor ("processor");
@SuppressWarnings("unused")
private final String val;
private HostIncompatibleForFaultToleranceReason(String val)
{
this.val = val;
}
} | bsd-3-clause |
markles/GeoGit | src/web/api/src/main/java/org/geogit/rest/repository/RepositoryProvider.java | 599 | /* Copyright (c) 2014 OpenPlans. All rights reserved.
* This code is licensed under the GNU GPL 2.0 license, available at the root
* application directory.
*/
package org.geogit.rest.repository;
import org.geogit.api.GeoGIT;
import org.restlet.data.Request;
import com.google.common.base.Optional;
public interface RepositoryProvider {
/**
* Key used too lookup the {@link RepositoryProvider} instance in the
* {@link Request#getAttributes() request attributes}
*/
String KEY = "__REPOSITORY_PROVIDER_KEY__";
public Optional<GeoGIT> getGeogit(Request request);
} | bsd-3-clause |
janlugt/HipG | src/hipg/Config.java | 6657 | /**
* Copyright (c) 2009-2011 Vrije Universiteit Amsterdam.
* Written by Ela Krepska e.l.krepska@vu.nl.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package hipg;
import ibis.util.TypedProperties;
/**
* HipG config.
*
* @author ela, ekr@cs.vu.nl
*/
public final class Config {
static final TypedProperties properties = new TypedProperties();
static {
properties.loadFromClassPath("hipg.properties");
properties.addProperties(System.getProperties());
}
public static String REPORT_FILE_BASE_NAME = properties.getProperty("hipg.reportFileBaseName", null);
public static boolean CREATE_COMMUNICATION = properties.getBooleanProperty("hipg.createCommunication", true);;
/** Internal redundant checks (for debugging). */
public static final boolean ERRCHECK = properties.getBooleanProperty("hipg.errCheck", false);
/** Internal fine debug information (for debuggging). */
public static final boolean FINEDEBUG = properties.getBooleanProperty("hipg.fineDebug", false);
public static final boolean STATISTICS = properties.getBooleanProperty("hipg.statistics", false);
/** Internal fine timing information (for debugging). */
public static final boolean TIMING = properties.getBooleanProperty("hipg.timing", false);
/** Throughput printing (for debugging). */
public static final boolean THROUGHPUT = properties.getBooleanProperty("hipg.throughput", false);
/** Maximum number of synchronizers. */
public static final int MAXSYNCHRONIZERS = properties.getIntProperty("hipg.maxSynchronizers", 1024 * 1024);
/** Maximum number of graphs. */
public static final int MAXGRAPHS = properties.getIntProperty("hipg.maxGraphs", 10);
/** Maximum number of workers. */
public static final int POOLSIZE = properties.getIntProperty("hipg.poolSize", 0);
/** Message size (main buffer). */
public static final int MESSAGE_BUF_SIZE = properties.getIntProperty("hipg.messageBufSize", 4 * 8 * 1024 * 1024);
/**
* Preferred minimal message length, change if you know what you are doing. Message may still be shorter, when it is
* urgent to send them.
*/
public static final int PREFERRED_MINIMAL_MESSAGE_SIZE = properties.getIntProperty(
"hipg.preferredMinimalMessageSize", 1024);
public static final int SKIP_STEPS_BEFORE_SENDING_SMALL_MESSAGE = properties.getIntProperty(
"hipg.skipStepsBeforeSendingSmallMessage", 50);
public static final int YIELD_BEFORE_SENDING_SMALL_MESSAGE = properties.getIntProperty(
"hipg.yieldBeforeSendingSmallMessage", -1);
/** Number of preallocated send buffers. */
public static final int INIT_SEND_BUFFERS = properties.getIntProperty("hipg.initSendBuffers", 50);
/** Number of preallocated receive buffers. */
public static final int INIT_RECV_BUFFERS = properties.getIntProperty("hipg.initRecvBuffers", 50);
public static final int SYNCHRONIZER_QUEUE_CHUNK_SIZE = properties.getIntProperty(
"hipg.synchronizerQueueChunkSize", 16 * 1024);
public static final int SYNCHRONIZER_QUEUE_INITIAL_CHUNKS = properties.getIntProperty(
"hipg.synchronizerQueueInitialChunks", 1);
public static final int SYNCHRONIZER_QUEUE_MEM_CACHE_SIZE = properties.getIntProperty(
"hipg.synchronizerQueueMemCacheSize", 0);
public static final int MAX_METHODS_IMMEDIATE = properties.getIntProperty("hipg.maxMethodsImmediate", 100);
public static final boolean OBJECT_SERIALIZATION = properties.getBooleanProperty("hipg.objectSerialization", true);
public static final boolean FLUSH_BIGGEST = properties.getBooleanProperty("hipg.flushBiggest", false);
private static void checkConfiguration() {
if (POOLSIZE <= 0) {
printConfiguration();
throw new RuntimeException("Pool size not specified");
}
}
public static int getSendBufferSize() {
return Config.MESSAGE_BUF_SIZE / (Config.POOLSIZE - 1);
}
public static int getRecvBufferSize() {
return Config.MESSAGE_BUF_SIZE;
}
public static int getNumReceiveBuffers() {
return Config.INIT_RECV_BUFFERS;
}
public static int getNumSendBuffers() {
return Config.INIT_SEND_BUFFERS * (Config.POOLSIZE - 1);
}
public static void printConfiguration() {
System.err.println("Configuration:");
System.err.println(" POOLSIZE = " + POOLSIZE);
System.err.println(" ERRCHECK = " + ERRCHECK);
System.err.println(" FINEDEBUG = " + FINEDEBUG);
System.err.println(" FINE_TIMING = " + TIMING);
System.err.println(" STATISTICS = " + STATISTICS);
System.err.println(" THROUGHPUT = " + THROUGHPUT);
System.err.println(" MESSAGE_BUF_SIZE = " + (MESSAGE_BUF_SIZE / 1024) + " KB");
System.err.println(" INIT_SEND_BUFFERS = " + INIT_SEND_BUFFERS);
System.err.println(" INIT_RECV_BUFFERS = " + INIT_RECV_BUFFERS);
System.err.println(" SYNCHRONIZER_QUEUE_CHUNK_SIZE = " + SYNCHRONIZER_QUEUE_CHUNK_SIZE);
System.err.println(" SYNCHRONIZER_QUEUE_INITIAL_CHUNKS = " + SYNCHRONIZER_QUEUE_INITIAL_CHUNKS);
System.err.println(" SYNCHRONIZER_QUEUE_MEM_CACHE_SIZE = " + SYNCHRONIZER_QUEUE_MEM_CACHE_SIZE);
System.err.println(" MAX_METHODS_IMMEDIATE = " + MAX_METHODS_IMMEDIATE);
System.err.println(" OBJECT_SERIALIZATION = " + OBJECT_SERIALIZATION);
System.err.println(" PREFERRED_MINIMAL_MESSAGE_SIZE = " + PREFERRED_MINIMAL_MESSAGE_SIZE);
System.err.println(" SKIP_STEPS_BEFORE_SENDING_SMALL_MESSAGE = " + SKIP_STEPS_BEFORE_SENDING_SMALL_MESSAGE);
System.err.println(" YIELD_BEFORE_SENDING_SMALL_MESSAGE = " + YIELD_BEFORE_SENDING_SMALL_MESSAGE);
System.err.println(" FLUSH_BIGGEST = " + FLUSH_BIGGEST);
if (REPORT_FILE_BASE_NAME != null && !STATISTICS) {
throw new RuntimeException("To enable reporting, you must set hipg.statistics!");
}
}
static {
checkConfiguration();
}
}
| bsd-3-clause |
interdroid/swan-train-sensor | src/interdroid/swan/cuckoo_station_sensor/TrainSensor.java | 4331 | package interdroid.swan.cuckoo_station_sensor;
import interdroid.swan.cuckoo_station_sensor.R;
import interdroid.swan.sensors.AbstractConfigurationActivity;
import interdroid.swan.sensors.AbstractCuckooSensor;
import interdroid.vdb.content.avro.AvroContentProviderProxy; // link to android library: vdb-avro
import android.content.ContentValues;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import interdroid.swan.cuckoo_sensors.CuckooPoller;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import com.google.android.gms.gcm.GoogleCloudMessaging; // link to android library: google-play-services_lib
/**
* A sensor for departure times of trains in the Netherlands
*
* @author roelof <rkemp@cs.vu.nl>
*
*/
public class TrainSensor extends AbstractCuckooSensor {
/**
* The configuration activity for this sensor.
*/
public static class ConfigurationActivity extends
AbstractConfigurationActivity {
@Override
public final int getPreferencesXML() {
return R.xml.train_preferences;
}
}
/**
* The from configuration.
*/
public static final String FROM_CONFIG = "from";
/**
* The to configuration.
*/
public static final String TO_CONFIG = "to";
/**
* The type configuration.
*/
public static final String TYPE_CONFIG = "type";
/**
* The time configuration.
*/
public static final String TIME_CONFIG = "time";
/**
* The departure field.
*/
public static final String DEPARTURE_FIELD = "departure";
/**
* The schema for this sensor.
*/
public static final String SCHEME = getSchema();
/**
* The provider for this sensor.
*/
public static class Provider extends AvroContentProviderProxy {
/**
* Construct the provider for this sensor.
*/
public Provider() {
super(SCHEME);
}
}
/**
* @return the schema for this sensor.
*/
private static String getSchema() {
String scheme = "{'type': 'record', 'name': 'train', "
+ "'namespace': 'interdroid.swan.cuckoo_station_sensor.train',"
+ "\n'fields': [" + SCHEMA_TIMESTAMP_FIELDS + "\n{'name': '"
+ DEPARTURE_FIELD + "', 'type': 'long'}" + "\n]" + "}";
return scheme.replace('\'', '"');
}
@Override
public final String[] getValuePaths() {
return new String[] { DEPARTURE_FIELD };
}
@Override
public void initDefaultConfiguration(final Bundle defaults) {
defaults.putString(TYPE_CONFIG, "Intercity");
}
@Override
public final String getScheme() {
return SCHEME;
}
/**
* Data Storage Helper Method.
*
* @param departure
* value for departure
*/
private void storeReading(long departure) {
long now = System.currentTimeMillis();
ContentValues values = new ContentValues();
values.put(DEPARTURE_FIELD, departure);
putValues(values, now);
}
/**
* =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- Sensor Specific Implementation
* =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
*/
@Override
public final CuckooPoller getPoller() {
return new TrainPoller();
}
@Override
public String getGCMSenderId() {
throw new java.lang.RuntimeException("<put your gcm project id here>");
}
@Override
public String getGCMApiKey() {
throw new java.lang.RuntimeException("<put your gcm api key here>");
}
public void registerReceiver() {
IntentFilter filter = new IntentFilter(
"com.google.android.c2dm.intent.RECEIVE");
filter.addCategory(getPackageName());
registerReceiver(new BroadcastReceiver() {
private static final String TAG = "trainSensorReceiver";
@Override
public void onReceive(Context context, Intent intent) {
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(context);
String messageType = gcm.getMessageType(intent);
if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR
.equals(messageType)) {
Log.d(TAG, "Received update but encountered send error.");
} else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED
.equals(messageType)) {
Log.d(TAG, "Messages were deleted at the server.");
} else {
if (intent.hasExtra(DEPARTURE_FIELD)) {
storeReading(intent.getExtras().getLong("departure"));
}
}
setResultCode(Activity.RESULT_OK);
}
}, filter, "com.google.android.c2dm.permission.SEND", null);
}
} | bsd-3-clause |
michaxm/hdfs-thrift-bindings | src/main/java/org/apache/hadoop/fs/thriftfs/server/HdfsService.java | 16862 | package org.apache.hadoop.fs.thriftfs.server;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.io.IOUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.compress.CompressionCodec;
import org.apache.hadoop.io.compress.CompressionCodecFactory;
import org.apache.hadoop.io.compress.CompressionOutputStream;
import org.apache.hadoop.thriftfs.api.BlockLocation;
import org.apache.hadoop.thriftfs.api.FileStatus;
import org.apache.hadoop.thriftfs.api.Pathname;
import org.apache.hadoop.thriftfs.api.ThriftHadoopFileSystem;
import org.apache.hadoop.thriftfs.api.ThriftHandle;
import org.apache.hadoop.thriftfs.api.ThriftIOException;
import org.apache.thrift.TException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A thrift server implementing hdfs bindings.
*
* Disclaimer: I still feel this implementation is redundant, but I have not yet
* found an official variant nor an already used community addition.
*
* TODO: At the moment, this assumes it is run as a singleton and is not written
* with concurrency in mind.
*
* @author Axel Mannhardt
*/
final class HdfsService implements ThriftHadoopFileSystem.Iface {
private static final Logger LOG = LoggerFactory.getLogger( HdfsService.class );
private final HdfsConfig _config;
private final ResourceByIdStore<InputStream> _readStreamStore = new ResourceByIdStore<InputStream>();
private final ResourceByIdStore<OutputStream> _writeStreamStore = new ResourceByIdStore<OutputStream>();
public HdfsService( final HdfsConfig config ) {
_config = config;
}
@Override
public ThriftHandle append( final Pathname pathname ) throws ThriftIOException, TException {
throw new UnsupportedOperationException( "Not supported by thrift service." );
}
@Override
public void chmod( final Pathname pathname, final short mode ) throws ThriftIOException, TException {
throw new UnsupportedOperationException( "Not supported by thrift service." );
}
@Override
public void chown( final Pathname pathname, final String owner, final String group ) throws ThriftIOException, TException {
throw new UnsupportedOperationException( "Not supported by thrift service." );
}
@Override
public boolean closeReadHandle( final ThriftHandle out ) throws ThriftIOException, TException {
System.out.println( "releasing handle stream: " + out.getId() );
return _readStreamStore.release( out.getId() );
}
@Override
public boolean closeWriteHandle( final ThriftHandle in ) throws ThriftIOException, TException {
System.out.println( "releasing handle stream: " + in.getId() );
return _writeStreamStore.release( in.getId() );
}
@Override
public ThriftHandle create( final Pathname pathname ) throws ThriftIOException, TException {
final FileSystem fs = Utils.tryToGetFileSystem( _config );
final Path path = Utils.toPath( pathname );
try {
LOG.info( "creating new write handle on " + _config + " for: " + pathname.getPathname() );
final OutputStream stream = openOutputStream( pathname, fs, path );
return new ThriftHandle( _writeStreamStore.storeNew( stream ) );
} catch ( final IOException e ) {
throw Utils.wrapAsThriftException( e );
}
}
private OutputStream openOutputStream( final Pathname pathname, final FileSystem fs, final Path fullPath ) throws IOException {
final FSDataOutputStream stream = fs.create( fullPath );
final Configuration conf = new Configuration();
final CompressionCodecFactory factory = new CompressionCodecFactory( conf );
final CompressionCodec codec = factory.getCodec( fullPath );
if ( codec == null ) {
return stream;
}
final CompressionOutputStream compressedStream = codec.createOutputStream( stream );
return compressedStream;
}
@Override
public ThriftHandle createFile( final Pathname pathname, final short mode, final boolean overwrite, final int bufferSize,
final short block_replication, final long blocksize ) throws ThriftIOException, TException {
throw new UnsupportedOperationException( "Not supported by thrift service." );
}
@Override
public boolean exists( final Pathname pathname ) throws ThriftIOException, TException {
throw new UnsupportedOperationException( "Not supported by thrift service." );
}
@Override
public List<BlockLocation> getFileBlockLocations( final Pathname pathname, final long start, final long length )
throws ThriftIOException, TException {
final Path path = Utils.toPath( pathname );
final FileSystem fs = Utils.tryToGetFileSystem( _config );
final List<BlockLocation> result = new ArrayList<BlockLocation>();
try {
for ( final org.apache.hadoop.fs.BlockLocation bl : fs.getFileBlockLocations( path, start, length ) ) {
result.add( convertBlockLocation( bl ) );
}
} catch ( final IOException e ) {
throw Utils.wrapAsThriftException( e );
}
return result;
}
private static BlockLocation convertBlockLocation( final org.apache.hadoop.fs.BlockLocation bl ) throws IOException {
final BlockLocation blockLocation = new BlockLocation();
blockLocation.setHosts( Arrays.asList( bl.getHosts() ) );
blockLocation.setHostsIsSet( true );
blockLocation.setLength( bl.getLength() );
blockLocation.setNames( Arrays.asList( bl.getNames() ) );
blockLocation.setNamesIsSet( true );
blockLocation.setOffset( bl.getOffset() );
blockLocation.setOffsetIsSet( true );
return blockLocation;
}
@Override
public List<FileStatus> listStatus( final Pathname pathname ) throws ThriftIOException, TException {
final FileSystem fs = Utils.tryToGetFileSystem( _config );
final List<FileStatus> result = new ArrayList<FileStatus>();
try {
for ( final org.apache.hadoop.fs.FileStatus f : fs.listStatus( Utils.toPath( pathname ) ) ) {
result.add( convertFileStatus( f ) );
}
} catch ( final FileNotFoundException e ) {
e.printStackTrace();
return null;
} catch ( IllegalArgumentException | IOException e ) {
throw Utils.wrapAsThriftException( e );
}
return result;
}
private static FileStatus convertFileStatus( final org.apache.hadoop.fs.FileStatus f ) {
final String path = f.getPath().toString();
final long length = f.getLen();
final boolean isdir = f.isDirectory();
final short block_replication = f.getReplication();
final long blocksize = f.getBlockSize();
final long modification_time = f.getModificationTime();
final String permission = f.getPermission().toString();
final String owner = f.getOwner();
final String group = f.getGroup();
final FileStatus fileStatus =
new FileStatus( path, length, isdir, block_replication, blocksize, modification_time, permission, owner, group );
return fileStatus;
}
@Override
public boolean mkdirs( final Pathname pathname ) throws ThriftIOException, TException {
throw new UnsupportedOperationException( "Not supported by thrift service." );
}
/**
* See thrift definition: open for reading only.
*/
@Override
public ThriftHandle open( final Pathname pathname ) throws ThriftIOException, TException {
final FileSystem fs = Utils.tryToGetFileSystem( _config );
final Path path = Utils.toPath( pathname );
try {
final Path fullPath = fs.resolvePath( path ); // optional: check early (before doing it implicit while opening) that the path exists
LOG.info( "creating new read handle on " + _config + " for: " + pathname.getPathname() );
final InputStream stream = openInputStream( pathname, fs, fullPath );
return new ThriftHandle( _readStreamStore.storeNew( stream ) );
} catch ( final IOException e ) {
throw Utils.wrapAsThriftException( e );
}
}
private static InputStream openInputStream( final Pathname pathname, final FileSystem fs, final Path fullPath )
throws IOException {
final FSDataInputStream stream = fs.open( fullPath );
final Configuration conf = new Configuration();
final CompressionCodecFactory factory = new CompressionCodecFactory( conf );
final CompressionCodec codec = factory.getCodec( fullPath );
if ( codec == null ) {
return stream;
}
final InputStream uncompressedStream = codec.createInputStream( stream );
return uncompressedStream;
}
// FIXME: API: shouldn't this be of some binary return type (string encoding)???
@Override
public String read( final ThriftHandle handle, final long offset, final int size ) throws ThriftIOException, TException {
final InputStream stream = _readStreamStore.getResource( handle.getId() );
if ( stream == null ) {
throw new ThriftIOException( "unknown read handle: " + handle.getId() );
}
if ( offset > Integer.MAX_VALUE ) {
throw new IllegalArgumentException( "long offset not supported yet by thrift service" );
}
byte[] res;
try {
res = IOUtils.toByteArray( stream );
} catch ( final IOException e ) {
throw Utils.wrapAsThriftException( e );
}
final byte[] result = Arrays.copyOf( res, res.length );
return new String( result );
}
@Override
public boolean rename( final Pathname pathname, final Pathname dest ) throws ThriftIOException, TException {
throw new UnsupportedOperationException( "Not supported by thrift service." );
}
@Override
public boolean rm( final Pathname pathname, final boolean recursive ) throws ThriftIOException, TException {
throw new UnsupportedOperationException( "Not supported by thrift service." );
}
@Override
public void setInactivityTimeoutPeriod( final long periodInSeconds ) throws TException {
throw new UnsupportedOperationException( "Not supported by thrift service." );
}
@Override
public void setReplication( final Pathname pathname, final short replication ) throws ThriftIOException, TException {
throw new UnsupportedOperationException( "Not supported by thrift service." );
}
@Override
public void shutdown( final int status ) throws TException {
throw new UnsupportedOperationException( "Not supported by thrift service." );
}
@Override
public FileStatus stat( final Pathname pathname ) throws ThriftIOException, TException {
throw new UnsupportedOperationException( "Not supported by thrift service." );
}
/**
* As the common exceptions are handled as such, I am quite unsure, what the
* return value is meant for in that stolen API description. Returns false
* if the handle id is unknown.
*/
@Override
public boolean write( final ThriftHandle handle, final String data ) throws ThriftIOException, TException {
final OutputStream stream = _writeStreamStore.getResource( handle.getId() );
if ( stream == null ) {
return false;
}
try {
stream.write( data.getBytes() );
} catch ( final IOException e ) {
throw Utils.wrapAsThriftException( e );
}
return true;
}
static class HdfsConfig {
private final String _host;
private final int _port;
public HdfsConfig( final String host, final int port ) {
_host = host;
_port = port;
}
String hdfsPath() {
return "hdfs://" + _host + ":" + _port;
}
@Override
public String toString() {
return _host + ":" + _port;
}
}
private static final class Utils {
private Utils() {
// no instances for utils
}
static Path toPath( final Pathname pathname ) {
return new Path( pathname.getPathname() );
}
static FileSystem tryToGetFileSystem( final HdfsConfig config ) throws ThriftIOException {
FileSystem fs;
final Configuration configuration = new Configuration();
configuration.set( FileSystem.FS_DEFAULT_NAME_KEY, config.hdfsPath() );
try {
fs = FileSystem.get( configuration );
} catch ( final IOException e ) {
throw new ThriftIOException( printStacktraceToString( e ) );
}
return fs;
}
static ThriftIOException wrapAsThriftException( final Exception e ) {
return new ThriftIOException( Utils.printStacktraceToString( e ) );
}
private static String printStacktraceToString( final Exception e ) {
PrintStream printStream = null;
try {
final ByteArrayOutputStream out = new ByteArrayOutputStream();
printStream = new PrintStream( out, true );
e.printStackTrace( printStream );
printStream.flush();
final String msg = out.toString();
return msg;
} finally {
IOUtils.closeQuietly( printStream );
}
}
}
/**
* Simple resource store - not thread safe.
*
* @author Axel Mannhardt
*/
private static final class ResourceByIdStore<RESOURCE_TYPE extends Closeable> {
private static final long FIRST_ID = 1;
private final Map<Long, RESOURCE_TYPE> _store = new HashMap<Long, RESOURCE_TYPE>();
private long _lastAssignedId = FIRST_ID - 1;
ResourceByIdStore() {
Runtime.getRuntime().addShutdownHook( new Thread() {
@Override
public void run() {
cleanup();
}
} );
}
long storeNew( final RESOURCE_TYPE res ) {
final long nextId = nextId();
final Long nextKey = keyOf( nextId );
if ( _store.containsKey( nextKey ) ) {
throw new IllegalStateException( "tried to overwrite resource" );
}
final RESOURCE_TYPE previous = _store.put( nextKey, res );
if ( previous != null ) {
System.err.println( "destroyed other resource while creating new!" );
}
System.out.println( "Allocated resources: " + _store.size() );
return nextId;
}
RESOURCE_TYPE getResource( final long id ) {
return _store.get( keyOf( id ) );
}
boolean release( final long id ) {
final RESOURCE_TYPE res = _store.get( keyOf( id ) );
if ( res == null ) {
System.out.println( "Cannot close unknown resource: " + id );
return false;
}
IOUtils.closeQuietly( res );
_store.remove( keyOf( id ) );
System.out.println( "Remaining resources: " + _store.size() );
return true;
}
private long nextId() {
long nextId = _lastAssignedId + 1;
boolean overflow = false;
while ( _store.containsKey( keyOf( nextId ) ) ) {
if ( nextId < Long.MAX_VALUE ) {
nextId++;
} else {
if ( !overflow ) {
nextId = FIRST_ID;
overflow = true;
} else {
System.err.println( "FATAL: no free ids remaining" );
System.exit( 1 );
}
}
}
_lastAssignedId = nextId;
return nextId;
}
private static Long keyOf( final long l ) {
return Long.valueOf( l );
}
private void cleanup() {
for ( final Long id : _store.keySet() ) {
release( id.longValue() );
}
}
}
} | bsd-3-clause |
ZoltanTheHun/SkyHussars | src/main/java/skyhussars/TerrainEd.java | 2534 | /*
* Copyright (c) 2016, ZoltanTheHun
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package skyhussars;
import skyhussars.terrained.TerrainEdConfig;
import javafx.application.Application;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import skyhussars.terrained.FXMLSceneFactory;
/**
* Terrain Editor application for SkyHussars
*
*/
public class TerrainEd extends Application {
private Stage stage;
@Override
public void start(Stage stage) throws Exception {
this.stage = stage;
ApplicationContext context = new AnnotationConfigApplicationContext(TerrainEdConfig.class);
FXMLSceneFactory loaderFactory = context.getBean(FXMLSceneFactory.class);
loaderFactory.load("/terrained/terrained_main.fxml",this::prepareStage,stage);
}
private Parent prepareStage(Parent root) {
Scene scene = new Scene(root);
stage.setTitle("SkyHussars - TerrainEd");
stage.setScene(scene);
stage.show();
return root;
}
public static void main(String[] args) {
launch(args);
}
}
| bsd-3-clause |
NCIP/cab2b | software/dependencies/commonpackage/HEAD_TAG_10_Jan_2007_RELEASE_BRANCH_FOR_V11/src/edu/wustl/common/bizlogic/IActivityStatus.java | 530 | /*L
* Copyright Georgetown University, Washington University.
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/cab2b/LICENSE.txt for details.
*/
package edu.wustl.common.bizlogic;
public interface IActivityStatus
{
/**
* Returns the activityStatus.
* @return Returns the activityStatus.
*/
public String getActivityStatus();
/**
* @param activityStatus The activityStatus to set.
*/
public void setActivityStatus(String activityStatus);
}
| bsd-3-clause |
FuriKuri/aspgen | aspgen-generator/src/main/java/de/hbrs/aspgen/generator/container/FieldForMethodContainer.java | 1475 | package de.hbrs.aspgen.generator.container;
import de.hbrs.aspgen.api.ast.JavaMethod;
import de.hbrs.aspgen.api.generator.FieldForMethod;
public class FieldForMethodContainer extends FieldForClassContainer implements FieldForMethod {
private JavaMethod javaMethod;
public void setMethod(final JavaMethod javaMethod) {
this.javaMethod = javaMethod;
}
@Override
protected void setReplacedContent(final String content) {
final String firstReplaced;
if (fieldnameStartWithPlaceHolder(content, "classname")) {
firstReplaced = content.replaceFirst("\\$classname\\$", firstCharAsLowerCase(onType));
} else if (fieldnameStartWithPlaceHolder(content, "methodname")) {
firstReplaced = content.replaceFirst("\\$methodname\\$", firstCharAsLowerCase(javaMethod.getName()));
} else if (fieldnameStartWithPlaceHolder(content, "methodsignature")) {
firstReplaced = content.replaceFirst("\\$methodsignature\\$", firstCharAsLowerCase(removeMethodChars(javaMethod.getMethodSignature())));
} else {
firstReplaced = content;
}
this.contentLine = replacer.replaceWithFirstCharUpperCaseAndMethodChars(firstReplaced, onType, javaMethod);
}
private String removeMethodChars(final String string) {
return string.replaceAll("\\(|\\)|@|\\s|,", "");
}
@Override
public String getData() {
return getMethodData(javaMethod);
}
}
| bsd-3-clause |
ericdahl/project-euler | java/src/main/java/Runner.java | 697 | public class Runner {
public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
if (args.length < 1) {
System.err.println("Usage: Runner problem-number");
System.exit(1);
}
final String problem = args[0].toUpperCase();
Class<?> clazz = Runner.class.getClassLoader().loadClass(problem);
Puzzle p = (Puzzle) clazz.newInstance();
final long start = System.currentTimeMillis();
final String result = p.solve();
final long stop = System.currentTimeMillis();
System.out.println(String.format("%s (%d ms)", result, stop - start));
}
}
| bsd-3-clause |
jzy3d/jzy3d-api-0.8.4 | src/bridge/org/jzy3d/bridge/awt/FrameAWT.java | 805 | package org.jzy3d.bridge.awt;
import java.awt.Rectangle;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import org.jzy3d.chart.Chart;
public class FrameAWT extends java.awt.Frame{
public FrameAWT(Chart chart, Rectangle bounds, String title){
this.chart = chart;
this.setTitle(title + "[AWT]");
this.add((java.awt.Component)chart.getCanvas());
this.pack();
this.setBounds(bounds);
this.setVisible(true);
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
FrameAWT.this.remove((java.awt.Component)FrameAWT.this.chart.getCanvas());
FrameAWT.this.chart.dispose();
FrameAWT.this.chart = null;
FrameAWT.this.dispose();
}
});
}
private Chart chart;
private static final long serialVersionUID = 1L;
}
| bsd-3-clause |
OWASP/owasp-java-encoder | jsp/src/test/java/org/owasp/encoder/tag/ForCssStringTagTest.java | 2763 | // Copyright (c) 2012 Jeff Ichnowski
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above
// copyright notice, this list of conditions and the following
// disclaimer.
//
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials
// provided with the distribution.
//
// * Neither the name of the OWASP nor the names of its
// contributors may be used to endorse or promote products
// derived from this software without specific prior written
// permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.
package org.owasp.encoder.tag;
/**
* Simple tests for the ForCssStringTag.
*
* @author Jeremy Long (jeremy.long@gmail.com)
*/
public class ForCssStringTagTest extends EncodingTagTest {
public ForCssStringTagTest(String testName) {
super(testName);
}
@Override
protected void setUp() throws Exception {
super.setUp();
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
}
/**
* Test of doTag method, of class ForCssStringTag.
* This is a very simple test that doesn't fully
* exercise/test the encoder - only that the
* tag itself works.
* @throws Exception is thrown if the tag fails.
*/
public void testDoTag() throws Exception {
System.out.println("doTag");
ForCssStringTag instance = new ForCssStringTag();
String value = "<div>";
String expected = "\\3c div\\3e";
instance.setJspContext(_pageContext);
instance.setValue(value);
instance.doTag();
String results = _response.getContentAsString();
assertEquals(expected,results);
}
}
| bsd-3-clause |
haraldk/TwelveMonkeys | imageio/imageio-iff/src/main/java/com/twelvemonkeys/imageio/plugins/iff/IFFProviderInfo.java | 2665 | /*
* Copyright (c) 2015, Harald Kuhr
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.twelvemonkeys.imageio.plugins.iff;
import com.twelvemonkeys.imageio.spi.ReaderWriterProviderInfo;
/**
* IFFProviderInfo.
*
* @author <a href="mailto:harald.kuhr@gmail.com">Harald Kuhr</a>
* @author last modified by $Author: harald.kuhr$
* @version $Id: IFFProviderInfo.java,v 1.0 20/03/15 harald.kuhr Exp$
*/
final class IFFProviderInfo extends ReaderWriterProviderInfo {
IFFProviderInfo() {
super(
IFFProviderInfo.class,
new String[] {"iff", "IFF"},
new String[] {"iff", "lbm", "ham", "ham8", "ilbm", "rgb8", "deep"},
new String[] {"image/iff", "image/x-iff"},
"com.twelvemonkeys.imageio.plugins.iff.IFFImageReader",
new String[]{"com.twelvemonkeys.imageio.plugins.iff.IFFImageReaderSpi"},
"com.twelvemonkeys.imageio.plugins.iff.IFFImageWriter",
new String[] {"com.twelvemonkeys.imageio.plugins.iff.IFFImageWriterSpi"},
false, null, null, null, null,
true, null, null, null, null
);
}
}
| bsd-3-clause |
burtcorp/jmespath-java | jmespath-core/src/main/java/io/burt/jmespath/function/MapFunction.java | 796 | package io.burt.jmespath.function;
import java.util.List;
import java.util.ArrayList;
import io.burt.jmespath.Adapter;
import io.burt.jmespath.Expression;
public class MapFunction extends BaseFunction {
public MapFunction() {
super(
ArgumentConstraints.expression(),
ArgumentConstraints.arrayOf(ArgumentConstraints.anyValue())
);
}
@Override
protected <T> T callFunction(Adapter<T> runtime, List<FunctionArgument<T>> arguments) {
Expression<T> expression = arguments.get(0).expression();
T array = arguments.get(1).value();
List<T> elements = runtime.toList(array);
List<T> result = new ArrayList<>(elements.size());
for (T element : elements) {
result.add(expression.search(element));
}
return runtime.createArray(result);
}
}
| bsd-3-clause |
NCIP/cacis | cacisweb/src/main/java/gov/nih/nci/cacisweb/action/SecureXDSNAVAddAction.java | 7995 | /**
* Copyright 5AM Solutions Inc
* Copyright SemanticBits LLC
* Copyright AgileX Technologies, Inc
* Copyright Ekagra Software Technologies Ltd
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/cacis/LICENSE.txt for details.
*/
package gov.nih.nci.cacisweb.action;
import gov.nih.nci.cacisweb.CaCISWebConstants;
import gov.nih.nci.cacisweb.exception.CaCISWebException;
import gov.nih.nci.cacisweb.exception.KeystoreInstantiationException;
import gov.nih.nci.cacisweb.model.SecureXDSNAVModel;
import gov.nih.nci.cacisweb.util.CaCISUtil;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Properties;
import javax.mail.MessagingException;
import org.apache.log4j.Logger;
import com.opensymphony.xwork2.ActionSupport;
public class SecureXDSNAVAddAction extends ActionSupport {
private static final Logger log = Logger.getLogger(SecureXDSNAVAddAction.class);
private static final long serialVersionUID = 1L;
private SecureXDSNAVModel secureXDSNAVBean;
@Override
public String execute() throws Exception {
log.debug("execute() - START");
String secureXDSNAVKeystoreLocation = CaCISUtil
.getProperty(CaCISWebConstants.COM_PROPERTY_NAME_SECXDSNAV_RECEPIENT_TRUSTSTORE_LOCATION);
try {
CaCISUtil caCISUtil = new CaCISUtil();
KeyStore keystore = caCISUtil.getKeystore(secureXDSNAVKeystoreLocation,
CaCISWebConstants.COM_KEYSTORE_TYPE_JKS, CaCISUtil
.getProperty(CaCISWebConstants.COM_PROPERTY_NAME_SECXDSNAV_RECEPIENT_TRUSTSTORE_PASSWORD));
caCISUtil.releaseKeystore();
FileInputStream certificateStream = new FileInputStream(secureXDSNAVBean.getCertificate());
CertificateFactory cf = CertificateFactory.getInstance("X.509");
java.security.cert.X509Certificate cert = (X509Certificate) cf.generateCertificate(certificateStream);
// Add the certificate
keystore.setCertificateEntry(secureXDSNAVBean.getCertificateAlias(), cert);
// Save the new keystore contents
FileOutputStream out = new FileOutputStream(new File(secureXDSNAVKeystoreLocation));
keystore.store(out, CaCISUtil.getProperty(
CaCISWebConstants.COM_PROPERTY_NAME_SECXDSNAV_RECEPIENT_TRUSTSTORE_PASSWORD).toCharArray());
out.close();
// add the new entry to XDSNAV configuration properties file
// PropertiesConfiguration config = new PropertiesConfiguration(CaCISUtil
// .getProperty(CaCISWebConstants.COM_PROPERTY_NAME_SECXDSNAV_RECEPIENT_CONFIG_FILE_LOCATION));
// config.setProperty(secureXDSNAVBean.getCertificateAlias(), cert.getSubjectDN().getName());
// config.save();
Properties properties = new Properties();
properties.load(new FileInputStream(new File(CaCISUtil
.getProperty(CaCISWebConstants.COM_PROPERTY_NAME_SECXDSNAV_RECEPIENT_CONFIG_FILE_LOCATION))));
properties.setProperty(secureXDSNAVBean.getCertificateAlias(), cert.getSubjectDN().getName());
properties.store(new FileOutputStream(new File(CaCISUtil
.getProperty(CaCISWebConstants.COM_PROPERTY_NAME_SECXDSNAV_RECEPIENT_CONFIG_FILE_LOCATION))), "");
// send an email to the newly added recepient
// note that the same email properties files has xdsnav related properties also
String secureXDSNAVPropertyFileLocation = CaCISUtil
.getProperty(CaCISWebConstants.COM_PROPERTY_NAME_SECEMAIL_PROPERTIES_FILE_LOCATION);
String host = CaCISUtil.getPropertyFromPropertiesFile(secureXDSNAVPropertyFileLocation, CaCISUtil
.getProperty(CaCISWebConstants.COM_PROPERTY_NAME_SECXDSNAV_SENDER_HOST_PROP_NAME));
String port = CaCISUtil.getPropertyFromPropertiesFile(secureXDSNAVPropertyFileLocation, CaCISUtil
.getProperty(CaCISWebConstants.COM_PROPERTY_NAME_SECXDSNAV_SENDER_PORT_PROP_NAME));
String senderEmail = CaCISUtil.getPropertyFromPropertiesFile(secureXDSNAVPropertyFileLocation, CaCISUtil
.getProperty(CaCISWebConstants.COM_PROPERTY_NAME_SECXDSNAV_MESSAGE_FROM_PROP_NAME));
String senderUser = CaCISUtil.getPropertyFromPropertiesFile(secureXDSNAVPropertyFileLocation, CaCISUtil
.getProperty(CaCISWebConstants.COM_PROPERTY_NAME_SECXDSNAV_SENDER_USER_PROP_NAME));
String senderPassword = CaCISUtil.getPropertyFromPropertiesFile(secureXDSNAVPropertyFileLocation, CaCISUtil
.getProperty(CaCISWebConstants.COM_PROPERTY_NAME_SECXDSNAV_SENDER_PASSWORD_PROP_NAME));
String subject = CaCISUtil
.getProperty(CaCISWebConstants.COM_PROPERTY_NAME_SECXDSNAV_SETUP_NOTIFICATION_SUBJECT_PROP_NAME);
String message = CaCISUtil
.getProperty(CaCISWebConstants.COM_PROPERTY_NAME_SECXDSNAV_SETUP_NOTIFICATION_MESSAGE_PROP_NAME);
caCISUtil.sendEmail(host, port, senderEmail, senderUser, senderPassword, subject, message, secureXDSNAVBean
.getCertificateAlias());
} catch (KeystoreInstantiationException kie) {
log.error(kie.getMessage());
addActionError(getText("exception.keystoreInstantiation"));
return ERROR;
} catch (CertificateException ce) {
log.error(CaCISUtil.getStackTrace(ce));
addActionError(getText("exception.certification"));
return INPUT;
} catch (MessagingException e) {
log.error(CaCISUtil.getStackTrace(e));
addActionError(getText("secureXDSNAVBean.emailException"));
return INPUT;
}
addActionMessage(getText("secureXDSNAVBean.addCertificateSuccessful"));
log.debug("execute() - END");
return SUCCESS;
}
public void validate() {
try {
String secureXDSNAVKeystoreLocation = CaCISUtil
.getProperty(CaCISWebConstants.COM_PROPERTY_NAME_SECXDSNAV_RECEPIENT_TRUSTSTORE_LOCATION);
CaCISUtil caCISUtil = new CaCISUtil();
KeyStore keystore = caCISUtil.getKeystore(secureXDSNAVKeystoreLocation,
CaCISWebConstants.COM_KEYSTORE_TYPE_JKS, CaCISUtil
.getProperty(CaCISWebConstants.COM_PROPERTY_NAME_SECXDSNAV_RECEPIENT_TRUSTSTORE_PASSWORD));
if (keystore.containsAlias(secureXDSNAVBean.getCertificateAlias())) {
log.error(getText("secureXDSNAVBean.duplicateKey"));
addFieldError("secureXDSNAVBean.certificateAlias", getText("secureXDSNAVBean.duplicateKey"));
}
caCISUtil.releaseKeystore();
} catch (KeystoreInstantiationException kie) {
log.error(CaCISUtil.getStackTrace(kie));
addActionError(getText("exception.keystoreInstantiation"));
} catch (CaCISWebException e) {
log.error(CaCISUtil.getStackTrace(e));
addActionError(getText("exception.cacisweb"));
} catch (KeyStoreException e) {
log.error(CaCISUtil.getStackTrace(e));
addActionError(getText("exception.keystoreAccess"));
}
}
public SecureXDSNAVModel getSecureXDSNAVBean() {
return secureXDSNAVBean;
}
public void setSecureXDSNAVBean(SecureXDSNAVModel secureXDSNAVBean) {
this.secureXDSNAVBean = secureXDSNAVBean;
};
}
| bsd-3-clause |
pordonj/frc1675-2012 | src/org/frc1675/robot/system/SteppingShooter.java | 2423 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.frc1675.robot.system;
import edu.wpi.first.wpilibj.SpeedController;
import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
import org.frc1675.driver.XBoxController;
import org.frc1675.ups2012.SmartDashboardOutputProfiler;
/**
*
* @author Josh
*/
public class SteppingShooter implements Shooter{
private SpeedController shooterMotor;
private XBoxController controller;
private static final double COOLDOWN = 0.25;
private int currentStep;
private Timer timer;
private boolean stepAvailable;
public SteppingShooter(SpeedController shooterMotor, XBoxController controller){
this.shooterMotor = shooterMotor;
this.controller = controller;
currentStep = 0;
timer = new Timer();
stepAvailable = true;
}
public SteppingShooter(SpeedController shooterMotor) {
}
public boolean doShooter(){
handleStepping();
SmartDashboardOutputProfiler.getInstance().putDouble("Driver", "Shooter Speed: ", shooterMotor.get());
return controller.getXButton();
}
private void handleStepping() {
if(stepAvailable){
if(controller.getLeftBumperButton()){
addStep();
} else if(controller.getRightBumperButton()){
subtractStep();
}
} else {
checkCooldown();
}
shooterMotor.set(0.05 * (double)currentStep);
// SmartDashboard.putInt("Step", currentStep);
}
private void addStep() {
if(currentStep < 20){
currentStep++;
startCooldown();
}
}
private void subtractStep() {
if(currentStep > 0){
currentStep--;
startCooldown();
}
}
private void startCooldown() {
stepAvailable = false;
timer.reset();
timer.start();
}
private void checkCooldown() {
if(timer.get() > COOLDOWN){
stopCooldown();
}
}
private void stopCooldown() {
stepAvailable = true;
timer.stop();
}
public boolean setSpeed(double Speed) {
return true;
}
}
| bsd-3-clause |
n4ybn/yavijava | src/main/java/com/vmware/vim25/ws/SoapClient.java | 6795 | package com.vmware.vim25.ws;
import org.apache.log4j.Logger;
import javax.net.ssl.TrustManager;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
/**
* Created by Michael Rice on 8/10/14.
* <p>
* Copyright 2014 Michael Rice
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
public abstract class SoapClient implements Client {
private static Logger log = Logger.getLogger(SoapClient.class);
public String soapAction;
public URL baseUrl = null;
public String cookie = null;
public String vimNameSpace = null;
public int connectTimeout = 0;
public int readTimeout = 0;
protected TrustManager trustManager;
XmlGen xmlGen = new XmlGenDom();
/*===============================================
* API versions *
"2.0.0" VI 3.0
"2.5.0" VI 3.5 (and u1)
"2.5u2" VI 3.5u2 (and u3, u4)
"4.0" vSphere 4.0 (and u1)
"4.1" vSphere 4.1
"5.0" vSphere 5.0
"5.1" vSphere 5.1
===============================================
*/
public void setSoapActionOnApiVersion(String apiVersion) {
log.trace("API Version detected: " + apiVersion);
if ("4.0".equals(apiVersion)) {
soapAction = SoapAction.SOAP_ACTION_V40.toString();
}
else if ("4.1".equals(apiVersion)) {
soapAction = SoapAction.SOAP_ACTION_V41.toString();
}
else if ("5.0".equals(apiVersion)) {
soapAction = SoapAction.SOAP_ACTION_V50.toString();
}
else if ("5.1".equals(apiVersion)) {
soapAction = SoapAction.SOAP_ACTION_V51.toString();
}
else if ("5.5".equals(apiVersion)) {
soapAction = SoapAction.SOAP_ACTION_V55.toString();
}
else if ("6.0".equals(apiVersion)) {
soapAction = SoapAction.SOAP_ACTION_V60.toString();
}
else { //always defaults to latest version
soapAction = SoapAction.SOAP_ACTION_V60.toString();
}
log.trace("Set soapAction to: " + soapAction);
}
/**
* Returns the {@link java.net.URL} that will be used in the connection.
*
* @return <code>URL</code> of the vi server used by this Client
*/
public URL getBaseUrl() {
return this.baseUrl;
}
/**
* Set the baseUrl for use in this Client
*
* @param baseUrl
*/
public void setBaseUrl(URL baseUrl) {
this.baseUrl = baseUrl;
}
/**
* Returns the <code>String</code> of the Cookie from the Set-Cookie header
* unless it was manually set in which case it returns that.
*
* @return String from the Set-Cookie header
*/
public String getCookie() {
return cookie;
}
/**
* Primarily used to set the cookie from the Set-Cookie header
*
* @param cookie String from the Set-Cookie header
*/
public void setCookie(String cookie) {
this.cookie = cookie;
}
/**
* @return
*/
public String getVimNameSpace() {
return vimNameSpace;
}
/**
* @param vimNameSpace
*/
public void setVimNameSpace(String vimNameSpace) {
this.vimNameSpace = vimNameSpace;
}
public int getConnectTimeout() {
return this.connectTimeout;
}
/**
* @param timeoutMilliSec
*/
public void setConnectTimeout(int timeoutMilliSec) {
this.connectTimeout = timeoutMilliSec;
}
/**
* Returns the time in milliseconds that is set for the read timeout
* <p>
* This time may not be the same as what the underlying client uses. If
* for example the client does not support this and is for some reason
* hard coded to some value this value.
*
* @return int
*/
public int getReadTimeout() {
return this.readTimeout;
}
/**
* Set the read timeout.
* <p>
* Sets the read timeout to a specified timeout, in milliseconds.
* A non-zero value specifies the timeout when reading from Input
* stream when a connection is established to a resource. If the
* timeout expires before there is data available for read, a
* java.net.SocketTimeoutException is raised. A timeout of zero
* is interpreted as an infinite timeout.
* <p>
* This value will be used by the underlying http client used if
* it is supported. By default that is the WSClient which uses
* HTTPURLConnection which uses URLConnection
*
* @param timeoutMilliSec int
*/
public void setReadTimeout(int timeoutMilliSec) {
this.readTimeout = timeoutMilliSec;
}
public TrustManager getTrustManager() {
return trustManager;
}
/**
* Set a custom trust manager responsible for material used when making trust decisions.
*
* @param trustManager
*/
public void setTrustManager(TrustManager trustManager) {
this.trustManager = trustManager;
}
public StringBuffer readStream(InputStream is) throws IOException {
log.trace("Building StringBuffer from InputStream response.");
StringBuffer sb = new StringBuffer();
BufferedReader in = new BufferedReader(new InputStreamReader(is));
String lineStr;
while ((lineStr = in.readLine()) != null) {
sb.append(lineStr);
}
in.close();
return sb;
}
/**
* This method will marshall the java payload object in to xml payload.
*
* @param methodName
* @param paras
* @return String - XML SoapMessage
*/
public String marshall(String methodName, Argument[] paras) {
String soapMsg = XmlGen.toXML(methodName, paras, vimNameSpace);
log.trace("Marshalled Payload String xml: " + soapMsg);
return soapMsg;
}
/**
* This method will unmarshall the response inputstream to Java Object of
* returnType type.
*
* @param returnType
* @param is
* @return Object - Converted Response inputstream
*/
public Object unMarshall(String returnType, InputStream is) throws Exception {
return xmlGen.fromXML(returnType, is);
}
}
| bsd-3-clause |
marcin-k/Jcommunicator | src/view/MainWindow_TopLogo.java | 4565 | package view;
import controllers.Main_Controller;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
/**
* Created by marcin on 24/05/2016.
*
* Class returns a node used for top part of the main window
*/
public class MainWindow_TopLogo {
public Node getTopLogo(BorderPane rootNode){
//---------------------------Image View ------------------------------------------
/* LOGO REMOVED FROM THE FINAL VERSION
//Creates imageView node to return
ImageView imageView = new ImageView();
//Imports an logo file
Image image = new Image("file:logo.png");
//Sets the logo as the image view and returns it
imageView.setImage(image);
*/
//---------------------------Menu Bar ---------------------------------------------
MenuBar menuBar = new MenuBar();
Menu fileMenu = new Menu("File");
MenuItem settings = new MenuItem("Settings");
MenuItem login = new MenuItem("Log in");
MenuItem exit = new MenuItem("Exit");
fileMenu.getItems().addAll(login, settings, exit);
Menu aboutMenu = new Menu("About");
MenuItem aboutItem = new MenuItem("About");
aboutMenu.getItems().addAll(aboutItem);
menuBar.getMenus().addAll(fileMenu, aboutMenu);
menuBar.setStyle("-fx-font-size: 12px;-fx-font-weight:bold;"); //original color: #95c6f2
//---------------------------Contacts, Search Icons --------------------------------
HBox iconsPanel = new HBox();
ImageView contactIV = new ImageView(new Image("file:userM.png"));
ImageView searchIV = new ImageView(new Image("file:loop.png"));
searchIV.setFitWidth(40);
searchIV.setFitHeight(40);
contactIV.setFitHeight(40);
contactIV.setFitWidth(40);
Button search = new Button("", searchIV);
search.setOnAction(e-> {
rootNode.setCenter(new MainWindow_CenterPane_Search().getNode());
});
Button contacts = new Button("", contactIV);
contacts.setOnAction(e-> {
rootNode.setCenter(new MainWindow_CenterPane_Contacts().getCenterPane());
});
iconsPanel.getChildren().addAll(contacts, search);
//---------------------------Connections Status Indicator -------------------------
Label connectionStatus = Main_Controller.getInstance().getConnectionStatus();
//---------------------------Menu Event handler -----------------------------------
//One event handler will handle all menu events
EventHandler<ActionEvent> MEHandler = event -> {
String name = ((MenuItem) event.getTarget()).getText();
if (name.equals("Exit")) {
Platform.exit();
}
if (name.equals("Settings")) {
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("Settings");
alert.setContentText("This will be replace with settings window");
alert.showAndWait();
}
if (name.equals("Log in")) {
System.out.println("login window should appear now");
Stage loginWindow = new Stage();
LoginWindow node = new LoginWindow();
try {
Scene myScene = new Scene((Parent) node.getNode(rootNode), 320, 250);
loginWindow.setScene(myScene);
loginWindow.setResizable(false);
loginWindow.show();
} catch (Exception e) {
e.printStackTrace();
}
}
if (name.equals("About")) {
System.out.println("About window would be here");
}
};
aboutItem.setOnAction(MEHandler);
settings.setOnAction(MEHandler);
exit.setOnAction(MEHandler);
login.setOnAction(MEHandler);
//---------Creates parent Node that will store image view and menu bar and connection status------------
GridPane gridPane = new GridPane();
gridPane.add(menuBar,0,0);
gridPane.add(iconsPanel,0,2);
gridPane.add(connectionStatus,0,3);
return gridPane;
}
}
| bsd-3-clause |
oci-pronghorn/PronghornIoT-Examples | 110-gaspumpsimulator/src/main/java/com/ociweb/iot/examples/PumpState.java | 141 | package com.ociweb.iot.examples;
public enum PumpState {
Idle(), //will show tank values
Pump(),
Receipt(); //will show pump totals
}
| bsd-3-clause |
NCIP/visda | visda/VISDA-Developer/Month-8-yr1/visdaDev_V0.4/src/edu/vt/cbil/visda/view/DisplayParam.java | 1732 | package edu.vt.cbil.visda.view;
/**
* Created with Eclipse
* Date: Aug 21, 2005
*/
/**
* The class contains all the parameters for display
*
* @author Jiajing Wang
* @version visda_v0.1
*/
public class DisplayParam {
/**
* data display options:
* 0 -- plain, no labels;
* 1 -- with labels;
* 2 -- no labels, but with `depth coloring';
* 3 -- with labels, and `depth coloring';
* ('3' is valid in current version)
*/
int vl1;
/**
* data display options:
* 0 -- black background;
* 1 -- white background;
* ('1' is valid in current version)
*/
int vl2;
/**
* data display options:
* 0 -- no label# displayed;
* 1 -- with label# displayed;
* ('0' is valid in current version)
*/
int vl3;
/**
* for deep level display
*/
double R[];
/**
* 1: time course data without color;
* 0: phenotype data with color
*/
int flag_tc;
/**
* [1 1 1] There is no designated color, it is phenotype;
* Others, There is designated color, it is timecourse.
*/
float p_color[];
/**
* the threshold of posterior probability for display
*/
double thresholdZjk;
int blob_size;
public DisplayParam(double zjk, int vl1, int vl2, int vl3, int flag_tc, double[] r, int blobsize) {
super();
// TODO Auto-generated constructor stub
this.flag_tc = flag_tc;
R = r;
thresholdZjk = zjk;
this.vl1 = vl1;
this.vl2 = vl2;
this.vl3 = vl3;
this.blob_size = blobsize;
p_color = new float[3];
if (flag_tc == 0) {
p_color[0] = (float) 1.0;
p_color[1] = (float) 1.0;
p_color[2] = (float) 1.0;
} else {
p_color[0] = (float) 0.5;
p_color[1] = (float) 0.3;
p_color[2] = (float) 0.4;
}
}
}
| bsd-3-clause |
NCIP/caarray | qa/software/Legacy_API_Test_Suite/src/caarray/legacy/client/test/suite/AssayTypeTestSuite.java | 6409 | //======================================================================================
// Copyright 5AM Solutions Inc, Yale University
//
// Distributed under the OSI-approved BSD 3-Clause License.
// See http://ncip.github.com/caarray/LICENSE.txt for details.
//======================================================================================
package caarray.legacy.client.test.suite;
import gov.nih.nci.caarray.domain.AbstractCaArrayObject;
import gov.nih.nci.caarray.domain.project.AssayType;
import java.io.File;
import java.util.List;
import caarray.legacy.client.test.ApiFacade;
import caarray.legacy.client.test.TestProperties;
import caarray.legacy.client.test.TestResult;
import caarray.legacy.client.test.search.AssayTypeSearch;
import caarray.legacy.client.test.search.ExampleSearch;
/**
* @author vaughng
* Aug 12, 2009
*/
public class AssayTypeTestSuite extends SearchByExampleTestSuite
{
private static final String CONFIG_FILE = TestProperties.CONFIG_DIR
+ File.separator + "AssayType.csv";
private static final String NAME = "Name";
private static final String[] COLUMN_HEADERS = new String[] { TEST_CASE,
API, NAME, EXPECTED_RESULTS, MIN_RESULTS};
/**
* @param apiFacade
*/
public AssayTypeTestSuite(ApiFacade apiFacade)
{
super(apiFacade);
}
/* (non-Javadoc)
* @see caarray.legacy.client.test.suite.SearchByExampleTestSuite#evaluateResults(java.util.List, caarray.legacy.client.test.search.ExampleSearch, caarray.legacy.client.test.TestResult)
*/
@Override
protected void evaluateResults(
List<? extends AbstractCaArrayObject> resultsList,
ExampleSearch search, TestResult testResult)
{
AssayTypeSearch assaySearch = (AssayTypeSearch)search;
List<AssayType> assayResults = (List<AssayType>)resultsList;
int namedResults = 0;
for (AssayType assayType : assayResults)
{
if (assayType.getName() != null)
namedResults++;
}
if (assaySearch.getExpectedResults() != null)
{
if (namedResults != assaySearch.getExpectedResults())
{
testResult.setPassed(false);
String detail = "Failed with unexpected number of results, expected: "
+ assaySearch.getExpectedResults()
+ ", actual number of results: " + namedResults;
testResult.addDetail(detail);
}
else
{
String detail = "Found expected number of results: "
+ namedResults;
testResult.addDetail(detail);
}
}
if (assaySearch.getMinResults() != null)
{
if (namedResults < assaySearch.getMinResults())
{
testResult.setPassed(false);
String detail = "Failed with unexpected number of results, expected minimum: "
+ assaySearch.getMinResults()
+ ", actual number of results: " + namedResults;
testResult.addDetail(detail);
}
else
{
String detail = "Found expected number of results: "
+ namedResults;
testResult.addDetail(detail);
}
}
}
/* (non-Javadoc)
* @see caarray.legacy.client.test.suite.SearchByExampleTestSuite#getExampleSearch()
*/
@Override
protected ExampleSearch getExampleSearch()
{
return new AssayTypeSearch();
}
/* (non-Javadoc)
* @see caarray.legacy.client.test.suite.SearchByExampleTestSuite#populateAdditionalSearchValues(java.lang.String[], caarray.legacy.client.test.search.ExampleSearch)
*/
@Override
protected void populateAdditionalSearchValues(String[] input,
ExampleSearch exampleSearch)
{
//N/A
}
/* (non-Javadoc)
* @see caarray.legacy.client.test.suite.SearchByExampleTestSuite#populateSearch(java.lang.String[], caarray.legacy.client.test.search.ExampleSearch)
*/
@Override
protected void populateSearch(String[] input, ExampleSearch exampleSearch)
{
AssayTypeSearch search = (AssayTypeSearch)exampleSearch;
AssayType example = new AssayType();
if (headerIndexMap.get(API) < input.length
&& !input[headerIndexMap.get(API)].equals(""))
{
search.setApi(input[headerIndexMap.get(API)].trim());
}
if (headerIndexMap.get(NAME) < input.length && !input[headerIndexMap.get(NAME)].equals(""))
example.setName(input[headerIndexMap.get(NAME)].trim());
search.setAssayType(example);
if (headerIndexMap.get(TEST_CASE) < input.length
&& !input[headerIndexMap.get(TEST_CASE)].equals(""))
search.setTestCase(Float.parseFloat(input[headerIndexMap.get(TEST_CASE)]
.trim()));
if (headerIndexMap.get(EXPECTED_RESULTS) < input.length
&& !input[headerIndexMap.get(EXPECTED_RESULTS)].equals(""))
search.setExpectedResults(Integer
.parseInt(input[headerIndexMap.get(EXPECTED_RESULTS)].trim()));
if (headerIndexMap.get(MIN_RESULTS) < input.length
&& !input[headerIndexMap.get(MIN_RESULTS)].equals(""))
search.setMinResults(Integer
.parseInt(input[headerIndexMap.get(MIN_RESULTS)].trim()));
}
/* (non-Javadoc)
* @see caarray.legacy.client.test.suite.ConfigurableTestSuite#getColumnHeaders()
*/
@Override
protected String[] getColumnHeaders()
{
return COLUMN_HEADERS;
}
/* (non-Javadoc)
* @see caarray.legacy.client.test.suite.ConfigurableTestSuite#getConfigFilename()
*/
@Override
protected String getConfigFilename()
{
return CONFIG_FILE;
}
/* (non-Javadoc)
* @see caarray.legacy.client.test.suite.ConfigurableTestSuite#getType()
*/
@Override
protected String getType()
{
return "AssayType";
}
}
| bsd-3-clause |
jbehave/jbehave-core | examples/core/src/main/java/org/jbehave/examples/core/CoreStoriesWithCorrelation.java | 2534 | package org.jbehave.examples.core;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.jbehave.core.io.CodeLocations.codeLocationFromClass;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.jbehave.core.annotations.AfterScenario;
import org.jbehave.core.annotations.AfterScenario.Outcome;
import org.jbehave.core.annotations.AfterStories;
import org.jbehave.core.annotations.When;
import org.jbehave.core.configuration.Configuration;
import org.jbehave.core.embedder.StoryControls;
import org.jbehave.core.failures.UUIDExceptionWrapper;
import org.jbehave.core.io.StoryFinder;
import org.jbehave.core.junit.JUnit4StoryRunner;
import org.jbehave.core.steps.InjectableStepsFactory;
import org.jbehave.core.steps.InstanceStepsFactory;
import org.junit.runner.RunWith;
@RunWith(JUnit4StoryRunner.class)
public class CoreStoriesWithCorrelation extends CoreStories {
private List<String> failures = new ArrayList<>();
public CoreStoriesWithCorrelation() {
configuredEmbedder().embedderControls()
.doGenerateViewAfterStories(true)
.doIgnoreFailureInStories(true)
.doIgnoreFailureInView(true)
.useThreads(1).useStoryTimeouts("60");
}
@Override
public Configuration configuration() {
return super.configuration().useStoryControls(new StoryControls().doResetStateBeforeScenario(true));
}
@Override
public InjectableStepsFactory stepsFactory() {
return new InstanceStepsFactory(configuration(), this);
}
@Override
public List<String> storyPaths() {
return new StoryFinder().findPaths(codeLocationFromClass(this.getClass()), "**/failure_correlation*.story",
"");
}
@When("a failure occurs in story $count")
public void whenSomethingHappens(int count) {
throw new RuntimeException("BUM! in story " + count);
}
@AfterScenario(uponOutcome = Outcome.FAILURE)
public void afterScenarioFailure(UUIDExceptionWrapper failure) throws Exception {
System.out.println("After Failed Scenario ...");
File file = new File("target/failures/" + failure.getUUID().toString());
file.getParentFile().mkdirs();
file.createNewFile();
failures.add(file.toString());
System.out.println("Failure: " + file);
}
@AfterStories
public void afterStories() {
assertThat(failures.size(), equalTo(2));
}
}
| bsd-3-clause |
UrielCh/ovh-java-sdk | ovh-java-sdk-xdsl/src/main/java/net/minidev/ovh/api/xdsl/OvhMonitoringNotification.java | 1236 | package net.minidev.ovh.api.xdsl;
import net.minidev.ovh.api.xdsl.monitoringnotifications.OvhFrequencyEnum;
import net.minidev.ovh.api.xdsl.monitoringnotifications.OvhTypeEnum;
/**
* Defines where and how the notifications will be sent
*/
public class OvhMonitoringNotification {
/**
* The SMS account which will be debited for each sent SMS, if the type is sms
*
* canBeNull && readOnly
*/
public String smsAccount;
/**
* The phone number, if type is sms
*
* canBeNull && readOnly
*/
public String phone;
/**
* Whether or not to allow notifications for generic incidents
*
* canBeNull && readOnly
*/
public Boolean allowIncident;
/**
* canBeNull && readOnly
*/
public Long id;
/**
* canBeNull && readOnly
*/
public OvhTypeEnum type;
/**
* canBeNull && readOnly
*/
public Boolean enabled;
/**
* The e-mail address, if type is mail
*
* canBeNull && readOnly
*/
public String email;
/**
* The frenquency to send reminders when the access is still down
*
* canBeNull && readOnly
*/
public OvhFrequencyEnum frequency;
/**
* The number of seconds the access has to be down to trigger an alert
*
* canBeNull && readOnly
*/
public Long downThreshold;
}
| bsd-3-clause |
krishagni/openspecimen | WEB-INF/src/com/krishagni/catissueplus/core/common/service/LabelPrinter.java | 480 | package com.krishagni.catissueplus.core.common.service;
import java.util.List;
import com.krishagni.catissueplus.core.common.domain.LabelPrintJob;
import com.krishagni.catissueplus.core.common.domain.LabelTmplToken;
import com.krishagni.catissueplus.core.common.domain.PrintItem;
import com.krishagni.catissueplus.core.common.events.LabelTokenDetail;
public interface LabelPrinter<T> {
List<LabelTmplToken> getTokens();
LabelPrintJob print(List<PrintItem<T>> printItems);
}
| bsd-3-clause |
salesforce/grpc-java-contrib | contrib/grpc-spring/src/main/java/com/salesforce/grpc/contrib/spring/GuavaLFReturnValueHandler.java | 5318 | /*
* Copyright (c) 2019, Salesforce.com, Inc.
* All rights reserved.
* Licensed under the BSD 3-Clause license.
* For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
package com.salesforce.grpc.contrib.spring;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.MoreExecutors;
import org.springframework.core.MethodParameter;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.async.DeferredResult;
import org.springframework.web.context.request.async.WebAsyncUtils;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.servlet.mvc.method.annotation.DeferredResultMethodReturnValueHandler;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
/**
* GuavaLFReturnValueHandler teaches Spring Web how to deal with Controller methods that return {@link ListenableFuture}.
* This allows you to use `ListenableFuture`-based logic end-to-end to build non-blocking asynchronous mvc services on
* top of gRPC.
*
* To enable GuavaLFReturnValueHandler, wire it up as a spring {@code {@literal @}Bean}.
*
* <blockquote><pre><code>
* {@literal @}Bean
* public GuavaLFReturnValueHandler GuavaLFReturnValueHandler(RequestMappingHandlerAdapter requestMappingHandlerAdapter) {
* return new GuavaLFReturnValueHandler().install(requestMappingHandlerAdapter);
* }
* </code></pre></blockquote>
*
* Once installed, Spring {@code {@literal @}Controller} operations can return a {@link ListenableFuture}s
* directly.
*
* <blockquote><pre><code>
* {@literal @}Controller
* public class MyController {
* {@literal @}RequestMapping(method = RequestMethod.GET, value = "/home")
* ListenableFuture<ModelAndView> home(HttpServletRequest request, Model model) {
* // work that returns a ListenableFuture...
* }
* }
* </code></pre></blockquote>
*
* Heavily inspired by https://github.com/AndreasKl/spring-boot-mvc-completablefuture
*/
public class GuavaLFReturnValueHandler implements HandlerMethodReturnValueHandler {
@Override
public boolean supportsReturnType(MethodParameter returnType) {
return ListenableFuture.class.isAssignableFrom(returnType.getParameterType());
}
@Override
public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer,
NativeWebRequest webRequest) throws Exception {
if (returnValue == null) {
mavContainer.setRequestHandled(true);
return;
}
final DeferredResult<Object> deferredResult = new DeferredResult<>();
@SuppressWarnings("unchecked")
ListenableFuture<Object> futureValue = (ListenableFuture<Object>) returnValue;
Futures.addCallback(futureValue,
new FutureCallback<Object>() {
@Override
public void onSuccess(@Nullable Object result) {
deferredResult.setResult(result);
}
@Override
public void onFailure(Throwable ex) {
deferredResult.setErrorResult(ex);
}
},
MoreExecutors.directExecutor());
startDeferredResultProcessing(mavContainer, webRequest, deferredResult);
}
@VisibleForTesting
protected void startDeferredResultProcessing(ModelAndViewContainer mavContainer, NativeWebRequest webRequest,
final DeferredResult<Object> deferredResult) throws Exception {
WebAsyncUtils.getAsyncManager(webRequest).startDeferredResultProcessing(deferredResult, mavContainer);
}
// ===========================
// INSTALLATION
// ===========================
public GuavaLFReturnValueHandler install(RequestMappingHandlerAdapter requestMappingHandlerAdapter) {
final List<HandlerMethodReturnValueHandler> originalHandlers = new ArrayList<>(
requestMappingHandlerAdapter.getReturnValueHandlers());
final int deferredPos = indexOfType(originalHandlers, DeferredResultMethodReturnValueHandler.class);
// Add our handler directly after the deferred handler.
originalHandlers.add(deferredPos + 1, this);
requestMappingHandlerAdapter.setReturnValueHandlers(originalHandlers);
return this;
}
private int indexOfType(final List<HandlerMethodReturnValueHandler> originalHandlers, Class<?> handlerClass) {
for (int i = 0; i < originalHandlers.size(); i++) {
final HandlerMethodReturnValueHandler valueHandler = originalHandlers.get(i);
if (handlerClass.isAssignableFrom(valueHandler.getClass())) {
return i;
}
}
return -1;
}
}
| bsd-3-clause |
datagr4m/org.datagr4m | datagr4m-drawing/src/main/java/org/datagr4m/drawing/layout/hierarchical/matrix/HierarchicalMatrixLayout.java | 6753 | package org.datagr4m.drawing.layout.hierarchical.matrix;
import org.apache.log4j.Logger;
import org.datagr4m.drawing.layout.hierarchical.AbstractHierarchicalLayout;
import org.datagr4m.drawing.layout.hierarchical.IHierarchicalNodeLayout;
import org.datagr4m.drawing.model.bounds.RectangleBounds;
import org.datagr4m.drawing.model.items.IBoundedItem;
import org.datagr4m.drawing.model.items.hierarchical.IHierarchicalNodeModel;
import org.datagr4m.monitors.ITimeMonitor;
import org.datagr4m.monitors.TimeMonitor;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
/**
* La position de la matrice est la position du mod�le associ� � ce layout La position des cellules est donc relative �
* la position du mod�le
*/
public class HierarchicalMatrixLayout extends AbstractHierarchicalLayout implements IHierarchicalMatrixLayout {
private static final long serialVersionUID = 2988838649895956485L;
protected int nLine;
protected int nColumn;
protected float[] lineHeight;
protected float[] columnWidth;
protected float allLineHeight;
protected float allColumnWidth;
protected IHierarchicalNodeModel model;
protected BiMap<IBoundedItem, CellIndex> mapIndex;
private ITimeMonitor timeMonitor;
public HierarchicalMatrixLayout() {
this(null);
}
public HierarchicalMatrixLayout(IHierarchicalNodeLayout parent) {
super(parent);
initMonitor();
init();
}
private void initMonitor() {
timeMonitor = new TimeMonitor(this);
}
@Override
public ITimeMonitor getTimeMonitor() {
return timeMonitor;
}
@Override
public void setModel(IHierarchicalNodeModel model) {
this.model = model;
}
@Override
public IHierarchicalNodeModel getModel() {
return model;
}
@Override
public void setItemCell(IBoundedItem item, int lineIndex, int columnIndex) throws IllegalArgumentException {
if (!model.hasChild(item))
Logger.getLogger(HierarchicalMatrixLayout.class).error("Item " + item + " is not an IMMEDIATE child of current model " + model);
// throw new IllegalArgumentException("Item " + item + " is not child of current model " + model);
else
mapIndex.put(item, new CellIndex(lineIndex, columnIndex));
}
protected void autoColumnGrid() {
int k = 0;
for (IBoundedItem i : getModel().getChildren()) {
setItemCell(i, k, 0);
k++;
}
}
protected void autoLineGrid() {
int k = 0;
for (IBoundedItem i : getModel().getChildren()) {
setItemCell(i, 0, k);
k++;
}
}
/********* DIMENSIONS **********/
@Override
public void setSize(int nLine, int nColumn) throws IllegalArgumentException {
this.nLine = nLine;
this.nColumn = nColumn;
this.lineHeight = new float[nLine];
this.columnWidth = new float[nColumn];
}
@Override
public void setLineHeight(float height) {
if (!isReady())
throw new RuntimeException("Algorithm not ready. Missing some parameters. Maybe Size?");
for (int i = 0; i < lineHeight.length; i++)
setLineHeight(i, height);
allLineHeight = height;
}
@Override
public void setColumnWidth(float width) {
for (int i = 0; i < columnWidth.length; i++)
setColumnWidth(i, width);
allColumnWidth = width;
}
// @Override
protected void setLineHeight(int line, float height) {
lineHeight[line] = height;
}
// @Override
protected void setColumnWidth(int column, float width) {
columnWidth[column] = width;
}
@Override
public float getLineHeight(int line) {
return lineHeight[line];
}
@Override
public float getColumnWidth(int column) {
return columnWidth[column];
}
/******************/
@Override
public void initAlgo() {
if (isReady()) {
super.initAlgo(); // handle children first
computeLayout();
} else
throw new RuntimeException("Layout has not been completely set!");
}
@Override
public void goAlgo() {
if (isReady()) {
super.goAlgo();
computeLayout();
} else
throw new RuntimeException("Layout has not been completely set!");
timeMonitor.stopMonitor();
}
/********* ACTUAL MATRIX LAYOUT ********/
protected void computeLayout() {
for (IBoundedItem item : mapIndex.keySet()) {
CellIndex index = mapIndex.get(item);
// System.out.println(item + " " + index);
item.changePosition(getXPosition(index), getYPosition(index));
}
}
protected float getXPosition(CellIndex index) {
if (isEven(nColumn)) {
// float middle = nColumn/2f;
// return (index.getColumnIndex()-middle+0.5f) * allColumnWidth;
float start = -(allColumnWidth / 2 + nColumn / 2);
return index.getColumnIndex() * allColumnWidth + start;
} else {
int middle = (nColumn - 1) / 2;
return (index.getColumnIndex() - middle) * allColumnWidth;
}
}
protected float getYPosition(CellIndex index) {
if (isEven(nLine)) {
float start = -(allLineHeight / 2 + nLine / 2);
return index.getLineIndex() * allLineHeight + start;
// float middle = nLine/2f;
// //(index.getLineIndex()-middle+0.5f) * allLineHeight;
} else {
int middle = (nLine - 1) / 2;
return (index.getLineIndex() - middle) * allLineHeight;
}
}
protected boolean isEven(int value) {
return value % 2 == 0;
}
protected void autoRowSize() {
float max = 0;
for (IBoundedItem i : getModel().getChildren()) {
RectangleBounds b = i.getRawCorridorRectangleBounds();
float h = b.getHeight();
if (h > max)
max = h;
}
allLineHeight = max;
}
protected void autoColSize() {
float max = 0;
for (IBoundedItem i : getModel().getChildren()) {
RectangleBounds b = i.getRawCorridorRectangleBounds();
float w = b.getWidth();
if (w > max)
max = w;
}
allColumnWidth = max;
}
public boolean isReady() {
return (nLine != -1 && nColumn != -1);
}
protected void init() {
nLine = -1;
nColumn = -1;
lineHeight = null;
columnWidth = null;
mapIndex = HashBiMap.create();
}
}
| bsd-3-clause |
lockss/lockss-daemon | plugins/test/src/org/lockss/plugin/blackquotidianrdf/TestBlackQuotidianRDFXPath.java | 7793 | package org.lockss.plugin.blackquotidianrdf;
import org.apache.commons.lang.StringUtils;
import org.lockss.test.LockssTestCase;
import org.springframework.util.xml.SimpleNamespaceContext;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.*;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TestBlackQuotidianRDFXPath extends LockssTestCase {
public void testAPIXmlXPathAlone() throws Exception {
String fname = "sample_rdf.xml";
Document document = getDocument(getResourceAsStream(fname));
String xpathArticleTitleExpression = "//rdf:RDF/rdf:Description/scalar:isLive[text() = \"1\"]/../@rdf:about";
//String xpathArticleTitleExpression = "//rdf:Description";
String xpathPaginationExpression = "/PubmedArticleSet/PubmedArticle/MedlineCitation/Article/Pagination/MedlinePgn";
String xpathDoiExpression = "/PubmedArticleSet/PubmedArticle/MedlineCitation/Article/ELocationID[@EIdType=\"doi\"]";
String xpathAuthorExpression = "/PubmedArticleSet/PubmedArticle/MedlineCitation/Article/AuthorList/Author";
String xpathPubTitleExpression = "/PubmedArticleSet/PubmedArticle/MedlineCitation/Article/Journal/Title";
String xpathPubDateExpression = "/PubmedArticleSet/PubmedArticle/MedlineCitation/Article/Journal/JournalIssue/PubDate";
String xpathEISSNExpression = "/PubmedArticleSet/PubmedArticle/MedlineCitation/Article/Journal/ISSN[@IssnType=\"Electronic\"]";
evaluateXPath(document, xpathArticleTitleExpression);
//evaluatePaginationXPath(document, xpathPaginationExpression);
//evaluateXPath(document, xpathDoiExpression);
//evaluateXPath(document, xpathPubTitleExpression );
//evaluateXPath(document, xpathPubDateExpression );
//evaluateXPath(document, xpathEISSNExpression );
//evaluatePaginationXPath(document, xpathPaginationExpression);
//evaluateAuthoNameXPath(document, xpathAuthorExpression );
}
private void evaluateXPath(Document document, String xpathExpression) throws Exception
{
XPathFactory xpathFactory = XPathFactory.newInstance();
XPath xpath = xpathFactory.newXPath();
SimpleNamespaceContext nsCtx = new SimpleNamespaceContext();
xpath.setNamespaceContext(nsCtx);
nsCtx.bindNamespaceUri("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#");
nsCtx.bindNamespaceUri("scalar", "http://scalar.usc.edu/2012/01/scalar-ns#");
List<String> values = new ArrayList<>();
int count = 0;
try
{
XPathExpression expr = xpath.compile(xpathExpression);
NodeList nodes = (NodeList) expr.evaluate(document, XPathConstants.NODESET);
count = nodes.getLength();
log.info("count ======" + count);
//assertNotEquals(nodes.getLength(), 0);
for (int i = 0; i < count ; i++) {
String value = nodes.item(i).getTextContent();
//assertNotNull(value);
}
} catch (XPathExpressionException e) {
log.error(e.getMessage(), e);
}
}
private void evaluateAuthoNameXPath(Document document, String xpathExpression) throws Exception
{
XPathFactory xpathFactory = XPathFactory.newInstance();
XPath xpath = xpathFactory.newXPath();
List<String> values = new ArrayList<>();
int count = 0;
try
{
XPathExpression expr = xpath.compile(xpathExpression);
NodeList nodes = (NodeList) expr.evaluate(document, XPathConstants.NODESET);
count = nodes.getLength();
assertNotEquals(nodes.getLength(), 0);
for (int i = 0; i < count ; i++) {
NodeList nameChildren = nodes.item(i).getChildNodes();
String surname = null;
String firstname = null;
for (int p = 0; p < nameChildren.getLength(); p++) {
Node partNode = nameChildren.item(p);
String partName = partNode.getNodeName();
if ("LastName".equals(partName)) {
surname = partNode.getTextContent();
log.info("surname is " + surname);
} else if ("ForeName".equals(partName)) {
firstname = partNode.getTextContent();
log.info("firstname is " + firstname);
}
}
StringBuilder valbuilder = new StringBuilder();
if (!StringUtils.isBlank(firstname)) {
valbuilder.append(firstname);
if (!StringUtils.isBlank(surname)) {
valbuilder.append(" " + surname);
}
log.info("author name is " + valbuilder.toString());
}
assertNotNull(valbuilder.toString());
}
} catch (XPathExpressionException e) {
log.error(e.getMessage(), e);
}
}
private void evaluatePaginationXPath(Document document, String xpathExpression) throws Exception
{
XPathFactory xpathFactory = XPathFactory.newInstance();
XPath xpath = xpathFactory.newXPath();
List<String> values = new ArrayList<>();
int count = 0;
String PAGINATION_PATTERN_STRING = "(\\d+)\\s*(-)?\\s*(\\d+)";
Pattern PAGINATION_PATTER_PATTERN = Pattern.compile("^\\s*" + PAGINATION_PATTERN_STRING, Pattern.CASE_INSENSITIVE);
try
{
XPathExpression expr = xpath.compile(xpathExpression);
NodeList nodes = (NodeList) expr.evaluate(document, XPathConstants.NODESET);
count = nodes.getLength();
assertNotEquals(nodes.getLength(), 0);
log.info("Expression is " + xpathExpression + ", count ====== " + count);
for (int i = 0; i < count ; i++) {
String value = nodes.item(i).getTextContent();
Matcher iMat = PAGINATION_PATTER_PATTERN .matcher(value);
if(!iMat.find()){ //use find not match to ignore trailing stuff
log.info("Acta DerMato Venereologica pagination no match");
} else {
log.info("start_page = " + iMat.group(1) + ", end_page = " + iMat.group(3));
}
assertNotNull(value);
}
} catch (XPathExpressionException e) {
log.error(e.getMessage(), e);
}
}
private void doSomething(Node node) {
// do something with the current node instead of System.out
log.info("Fei - node: " + node.getNodeName());
NodeList nodeList = node.getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++) {
Node currentNode = nodeList.item(i);
if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
//calls this method for all the children which is Element
log.info("Fei - node -------- Element_Node: " + node.getNodeName());
doSomething(currentNode);
}
}
}
private Document getDocument(InputStream ins) throws Exception
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(ins);
doSomething(doc.getDocumentElement());
return doc;
}
}
| bsd-3-clause |
krishagni/openspecimen | WEB-INF/src/com/krishagni/catissueplus/core/biospecimen/domain/SpecimenSavedEvent.java | 282 | package com.krishagni.catissueplus.core.biospecimen.domain;
import com.krishagni.catissueplus.core.common.events.OpenSpecimenEvent;
public class SpecimenSavedEvent extends OpenSpecimenEvent<Specimen> {
public SpecimenSavedEvent(Specimen specimen) {
super(null, specimen);
}
}
| bsd-3-clause |
PeterMitrano/allwpilib | wpilibj/src/sim/java/edu/wpi/first/wpilibj/SpeedController.java | 1058 | /*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2016. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj;
/**
* Interface for speed controlling devices.
*/
public interface SpeedController extends PIDOutput {
/**
* Common interface for getting the current set speed of a speed controller.
*
* @return The current set speed. Value is between -1.0 and 1.0.
*/
double get();
/**
* Common interface for setting the speed of a speed controller.
*
* @param speed The speed to set. Value should be between -1.0 and 1.0.
*/
void set(double speed);
/**
* Disable the speed controller
*/
void disable();
}
| bsd-3-clause |
sirixdb/sirix | bundles/sirix-core/src/main/java/org/sirix/diff/algorithm/fmse/utils/SubCost01.java | 3125 | package org.sirix.diff.algorithm.fmse.utils;
/**
* SimMetrics - SimMetrics is a java library of Similarity or Distance Metrics, e.g. Levenshtein
* Distance, that provide float based similarity measures between String Data. All metrics return
* consistant measures rather than unbounded similarity scores.
*
* Copyright (C) 2005 Sam Chapman - Open Source Release v1.1
*
* Please Feel free to contact me about this library, I would appreciate knowing quickly what you
* wish to use it for and any criticisms/comments upon the SimMetric library.
*
* email: s.chapman@dcs.shef.ac.uk www: http://www.dcs.shef.ac.uk/~sam/ www:
* http://www.dcs.shef.ac.uk/~sam/stringmetrics.html
*
* address: Sam Chapman, Department of Computer Science, University of Sheffield, Sheffield, S.
* Yorks, S1 4DP United Kingdom,
*
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
* 02111-1307 USA
*/
/**
* Package: costfunctions Description: SubCost01 implements a substitution cost function where
* d(i,j) = 1 if idoes not equal j, 0 if i equals j.
*
* Date: 24-Mar-2004 Time: 13:38:12
*
* @author Sam Chapman <a href="http://www.dcs.shef.ac.uk/~sam/">Website</a>,
* <a href="mailto:sam@dcs.shef.ac.uk">Email</a>.
* @version 1.1
*/
public final class SubCost01 implements SubstitutionCost {
/**
* Get the name of the cost function.
*
* @return the name of the cost function
*/
@Override
public String getShortDescriptionString() {
return "SubCost01";
}
/**
* Cost between characters where d(i,j) = 1 if i does not equals j, 0 if i equals j.
*
* @param str1 the string1 to evaluate the cost
* @param string1Index the index within the string1 to test
* @param str2 the string2 to evaluate the cost
* @param string2Index the index within the string2 to test
* @return the cost of a given subsitution d(i,j) where d(i,j) = 1 if i!=j, 0 if i==j
*/
@Override
public float getCost(final String str1, final int string1Index, final String str2,
final int string2Index) {
if (str1.charAt(string1Index) == str2.charAt(string2Index)) {
return 0.0f;
} else {
return 1.0f;
}
}
/**
* Get the maximum possible cost.
*
* @return the maximum possible cost
*/
@Override
public float getMaxCost() {
return 1.0f;
}
/**
* Get the minimum possible cost.
*
* @return the minimum possible cost
*/
@Override
public float getMinCost() {
return 0.0f;
}
}
| bsd-3-clause |
messagebird/java-rest-api | api/src/test/java/com/messagebird/SpyService.java | 5256 | package com.messagebird;
import com.messagebird.exceptions.GeneralException;
import java.util.HashMap;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.spy;
/**
* Builder for effortlessly constructing spy services of MessageBirdServiceImpl.
* <p>
* The following example configures a mock to return an OK response with a
* response of your choice whenever doRequest() is called:
*
* <pre>
* MessageBirdService messageBirdService = SpyService
* .expects("GET", "conversatons/convid")
* .withConversationsAPIBaseURL()
* .andReturns(new ApiResponse("YOUR_RESPONSE_BODY"));
* </pre>
*
* @param <P> Type of the payload being (optionally) returned.
*/
class SpyService<P> {
private static final String CONVERSATIONS_API_BASE_URL = "https://conversations.messagebird.com/v1";
private static final String REST_API_BASE_URL = "https://rest.messagebird.com";
private static final String VOICE_CALLS_BASE_URL = "https://voice.messagebird.com";
private String method;
private String url;
private P payload;
private String baseURL;
SpyService() {
//
}
/**
* Gets the access key for the MessageBirdService. Can be overridden, but
* if a use case requires this, the mock is likely not used properly.
* <p>
* It is strongly advisable to NOT make this a valid access key for several
* reasons, but also because Mockito uses loose mocks. This means that if a
* mocked method is invoked without any matching expectations (for example,
* with the wrong parameters), it does not throw exceptions. It instead
* calls the real implementation. Leaving the access key blank ensures an
* exception is thrown ("not authorized"), causing the test to fail.
*
* @return Access key for MessageBirdService.
*/
protected String getAccessKey() {
return "";
}
/**
* Sets up a spy and configures its expectations for doRequest().
*
* @param method Method that doRequest() expects.
* @param url URL that doRequest() expects.
* @param payload Payload that doRequest() expects.
* @param <P> Type of the payload.
* @return Intermediate SpyService that can be finalized through
* andReturns().
*/
static <P> SpyService expects(final String method, final String url, final P payload) {
SpyService service = new SpyService<P>();
service.method = method;
service.url = url;
service.payload = payload;
return service;
}
/**
* Sets up a spy and configures its expectations for doRequest(). This sets
* the expected payload to null - useful for requests without bodies, like
* GETs and DELETEs. To provide an expected payload, use the overload.
*
* @param method Method that doRequest() expects.
* @param url URL that doRequest() expects.
* @return Intermediate SpyService that can be finalized through
* andReturns().
*/
static SpyService expects(final String method, final String url) {
return SpyService.expects(method, url, null);
}
/**
* Sets a base URL to prefix the URL provided to expects() with when
* building the spy.
*
* @param baseURL String to prefix the URL with when building the spy.
* @return Intermediate SpyService that can be finalized through
* andReturns().
*/
SpyService withBaseURL(final String baseURL) {
this.baseURL = baseURL;
return this;
}
/**
* Sets the base URL to match the Conversations API's.
*
* @return Intermediate SpyService that can be finalized through
* andReturns().
*/
SpyService withConversationsAPIBaseURL() {
return withBaseURL(CONVERSATIONS_API_BASE_URL);
}
/**
* Prefixes all URLs provided to expects() with the REST API's base URL
* when building the spy.
*
* @return Intermediate SpyService that can be finalized through
* andReturns().
*/
SpyService withRestAPIBaseURL() {
return withBaseURL(REST_API_BASE_URL);
}
/**
* Sets the base URL to match the Voice Call API's.
*
* @return Intermediate SpyService that can be finalized through
* andReturns().
*/
SpyService withVoiceCallAPIBaseURL() {
return withBaseURL(VOICE_CALLS_BASE_URL);
}
/**
* Finalizes the SpyService by configuring its return value for
* doRequest() and builds the spy.
*
* @param apiResponse APIResponse to return from the spy when doRequest()
* is invoked with the configured expectation.
* @return MessageBirdServiceImpl with a spy on doRequest().
* @throws GeneralException
*/
MessageBirdService andReturns(final APIResponse apiResponse) throws GeneralException {
if (baseURL != null && !baseURL.isEmpty()) {
url = String.format("%s/%s", baseURL, url);
}
MessageBirdServiceImpl messageBirdService = spy(new MessageBirdServiceImpl(getAccessKey()));
doReturn(apiResponse).when(messageBirdService).doRequest(method, url, new HashMap<>(), payload);
return messageBirdService;
}
}
| bsd-3-clause |
wieden-kennedy/composite-framework | src/test/java/com/wk/lodge/composite/web/support/TestChannelInterceptor.java | 2541 |
package com.wk.lodge.composite.web.support;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptorAdapter;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
/**
* A ChannelInterceptor that caches mesages.
*/
public class TestChannelInterceptor extends ChannelInterceptorAdapter {
private final BlockingQueue<Message<?>> messages = new ArrayBlockingQueue<>(100);
private final List<String> destinationPatterns = new ArrayList<>();
private final PathMatcher matcher = new AntPathMatcher();
private volatile boolean isRecording;
/**
* @param autoStart whether to start recording messages removing the need to
* call {@link #startRecording()} explicitly
*/
public TestChannelInterceptor(boolean autoStart) {
this.isRecording = autoStart;
}
public void setIncludedDestinations(String... patterns) {
this.destinationPatterns.addAll(Arrays.asList(patterns));
}
public void startRecording() {
this.isRecording = true;
}
public void stopRecording() {
this.isRecording = false;
}
/**
* @return the next received message or {@code null} if the specified time elapses
*/
public Message<?> awaitMessage(long timeoutInSeconds) throws InterruptedException {
return this.messages.poll(timeoutInSeconds, TimeUnit.SECONDS);
}
@Override
public Message<?> preSend(Message<?> message, MessageChannel channel) {
if (this.isRecording) {
if (this.destinationPatterns.isEmpty()) {
this.messages.add(message);
}
else {
StompHeaderAccessor headers = StompHeaderAccessor.wrap(message);
if (headers.getDestination() != null) {
for (String pattern : this.destinationPatterns) {
if (this.matcher.match(pattern, headers.getDestination())) {
this.messages.add(message);
break;
}
}
}
}
}
return message;
}
} | bsd-3-clause |
threerings/jiggl | webgl/src/main/java/com/threerings/jiggl/view/ModelViewShader.java | 2264 | //
// Jiggl WebGL - GWT + WebGL backend for 2D game framework
// http://github.com/threerings/jiggl/blob/master/LICENSE
package com.threerings.jiggl.view;
import com.googlecode.gwtgl.binding.WebGLUniformLocation;
/**
* Provides a basic shader with a model view transform (no texture, no color).
*/
public class ModelViewShader extends Shader
{
/** The vertex position attribute (used by the geometry when rendering). */
public int vposAttr;
/** The uniform variable containing our model view matrix. */
public WebGLUniformLocation mviewMatrix;
@Override // from Shader
public void bind (WGLRenderer r)
{
super.bind(r);
r.wctx.uniformMatrix4fv(_projMatrix, false, r.projMatrix);
}
@Override // from Shader
public boolean init (WGLRenderer r)
{
if (!super.init(r)) return false; // already initted
this.vposAttr = r.wctx.getAttribLocation(_program, VPOS_ATTR);
r.wctx.enableVertexAttribArray(this.vposAttr);
_projMatrix = r.wctx.getUniformLocation(_program, PMTX_VAR);
this.mviewMatrix = r.wctx.getUniformLocation(_program, MVMTX_VAR);
return true;
}
@Override // from Shader
protected String getVertexSource ()
{
String program =
"attribute vec3 VPOS_ATTR;\n" +
"uniform mat4 PMTX_VAR;\n" +
"uniform mat4 MVMTX_VAR;\n" +
"void main (void) {\n" +
" gl_Position = PMTX_VAR * MVMTX_VAR * vec4(VPOS_ATTR, 1.0);\n" +
"}";
return program.
replace("VPOS_ATTR", VPOS_ATTR).
replace("PMTX_VAR", PMTX_VAR).
replace("MVMTX_VAR", MVMTX_VAR);
}
@Override // from Shader
protected String getFragmentSource ()
{
String program = "#ifdef GL_ES\n" +
" precision highp float;\n" +
"#endif\n" +
"void main (void) {\n" +
" gl_FragColor = vec4(1, 1, 1, 1);\n" +
"}";
return program;
}
protected WebGLUniformLocation _projMatrix;
protected static final String VPOS_ATTR = "vertexPos";
protected static final String PMTX_VAR = "projectionMatrix";
protected static final String MVMTX_VAR = "modelViewMatrix";
}
| bsd-3-clause |
NCIEVS/evsrestapi | src/main/java/gov/nih/nci/evs/api/service/ElasticSearchService.java | 784 |
package gov.nih.nci.evs.api.service;
import java.util.List;
import org.springframework.web.client.HttpClientErrorException;
import gov.nih.nci.evs.api.model.ConceptResultList;
import gov.nih.nci.evs.api.model.SearchCriteria;
import gov.nih.nci.evs.api.model.Terminology;
/**
* Represents a service that performs a search against an elasticsearch
* endpoint.
*/
public interface ElasticSearchService {
/**
* Search.
*
* @param terminologies the terminologies
* @param searchCriteria the search criteria
* @return the string
* @throws Exception the exception
* @throws HttpClientErrorException the http client error exception
*/
public ConceptResultList search(List<Terminology> terminologies, SearchCriteria searchCriteria)
throws Exception;
}
| bsd-3-clause |
tomwhite/hellbender | src/main/java/org/broadinstitute/hellbender/tools/walkers/rnaseq/OverhangFixingManager.java | 13678 | package org.broadinstitute.hellbender.tools.walkers.rnaseq;
import htsjdk.samtools.SAMFileWriter;
import htsjdk.samtools.SAMRecord;
import htsjdk.samtools.SAMRecordCoordinateComparator;
import htsjdk.samtools.reference.IndexedFastaSequenceFile;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.broadinstitute.hellbender.utils.GenomeLoc;
import org.broadinstitute.hellbender.utils.GenomeLocParser;
import org.broadinstitute.hellbender.utils.clipping.ReadClipper;
import org.broadinstitute.hellbender.utils.read.ReadUtils;
import java.util.*;
/**
* The class manages reads and splices and tries to apply overhang clipping when appropriate.
* Important note: although for efficiency the manager does try to send reads to the underlying writer in coordinate
* sorted order, it does NOT guarantee that it will do so in every case! So unless there's a good reason not to,
* methods that instantiate this manager should pass in a writer that does not assume the reads are pre-sorted.
*/
public class OverhangFixingManager {
protected static final Logger logger = LogManager.getLogger(OverhangFixingManager.class);
private static final boolean DEBUG = false;
// how many reads should we store in memory before flushing the queue?
private final int MAX_RECORDS_IN_MEMORY;
// how many mismatches do we tolerate in the overhangs?
private final int MAX_MISMATCHES_IN_OVERHANG;
// how many bases do we tolerate in the overhang before deciding not to clip?
private final int MAX_BASES_IN_OVERHANG;
// should we not bother fixing overhangs?
private final boolean doNotFixOverhangs;
// where we ultimately write out our records
private final SAMFileWriter writer;
// fasta reference reader to check overhanging edges in the exome reference sequence
private final IndexedFastaSequenceFile referenceReader;
// the genome loc parser
private final GenomeLocParser genomeLocParser;
// the read cache
private final static int initialCapacity = 5000;
private PriorityQueue<SplitRead> waitingReads = new PriorityQueue<>(initialCapacity, new SplitReadComparator());
// the set of current splices to use
private final Set<Splice> splices = new TreeSet<>(new SpliceComparator());
protected static final int MAX_SPLICES_TO_KEEP = 1000;
/**
*
* @param writer actual writer
* @param genomeLocParser the GenomeLocParser object
* @param referenceReader the reference reader
* @param maxRecordsInMemory max records to keep in memory
* @param maxMismatchesInOverhangs max number of mismatches permitted in the overhangs before requiring clipping
* @param maxBasesInOverhangs max number of bases permitted in the overhangs before deciding not to clip
* @param doNotFixOverhangs if true, don't clip overhangs at all
*/
public OverhangFixingManager(final SAMFileWriter writer,
final GenomeLocParser genomeLocParser,
final IndexedFastaSequenceFile referenceReader,
final int maxRecordsInMemory,
final int maxMismatchesInOverhangs,
final int maxBasesInOverhangs,
final boolean doNotFixOverhangs) {
this.writer = writer;
this.genomeLocParser = genomeLocParser;
this.referenceReader = referenceReader;
this.MAX_RECORDS_IN_MEMORY = maxRecordsInMemory;
this.MAX_MISMATCHES_IN_OVERHANG = maxMismatchesInOverhangs;
this.MAX_BASES_IN_OVERHANG = maxBasesInOverhangs;
this.doNotFixOverhangs = doNotFixOverhangs;
}
public final int getNReadsInQueue() { return waitingReads.size(); }
/**
* For testing purposes only
*
* @return the list of reads currently in the queue
*/
public List<SplitRead> getReadsInQueueForTesting() {
return new ArrayList<>(waitingReads);
}
/**
* For testing purposes only
*
* @return the list of splices currently in the queue
*/
public List<Splice> getSplicesForTesting() {
return new ArrayList<>(splices);
}
/**
* Add a new observed split to the list to use
*
* @param contig the contig
* @param start the start of the split, inclusive
* @param end the end of the split, inclusive
*/
public void addSplicePosition(final String contig, final int start, final int end) {
if ( doNotFixOverhangs )
return;
// is this a new splice? if not, we are done
final Splice splice = new Splice(contig, start, end);
if ( splices.contains(splice) )
return;
// initialize it with the reference context
// we don't want to do this until we know for sure that it's a new splice position
splice.initialize(referenceReader);
// clear the set of old split positions seen if we hit a new contig
final boolean sameContig = splices.isEmpty() || splices.iterator().next().loc.getContig().equals(contig);
if ( !sameContig )
splices.clear();
// run this position against the existing reads
for ( final SplitRead read : waitingReads )
fixSplit(read, splice);
splices.add(splice);
if ( splices.size() > MAX_SPLICES_TO_KEEP )
cleanSplices();
}
/**
* Add a read to the manager
*
* @param read the read to add
*/
public void addRead(final SAMRecord read) {
if ( read == null ) throw new IllegalArgumentException("read added to manager is null, which is not allowed");
// if the new read is on a different contig or we have too many reads, then we need to flush the queue and clear the map
final boolean tooManyReads = getNReadsInQueue() >= MAX_RECORDS_IN_MEMORY;
final boolean encounteredNewContig = getNReadsInQueue() > 0 && !waitingReads.peek().read.getReferenceIndex().equals(read.getReferenceIndex());
if ( tooManyReads || encounteredNewContig ) {
if ( DEBUG ) logger.warn("Flushing queue on " + (tooManyReads ? "too many reads" : ("move to new contig: " + read.getReferenceName() + " from " + waitingReads.peek().read.getReferenceName())) + " at " + read.getAlignmentStart());
final int targetQueueSize = encounteredNewContig ? 0 : MAX_RECORDS_IN_MEMORY / 2;
// write the required number of waiting reads to disk
while ( getNReadsInQueue() > targetQueueSize )
writer.addAlignment(waitingReads.poll().read);
}
final SplitRead splitRead = new SplitRead(read);
// fix overhangs, as needed
for ( final Splice splice : splices)
fixSplit(splitRead, splice);
// add the new read to the queue
waitingReads.add(splitRead);
}
/**
* Clean up the list of splices
*/
private void cleanSplices() {
final int targetQueueSize = splices.size() / 2;
final Iterator<Splice> iter = splices.iterator();
for ( int i = 0; i < targetQueueSize; i++ ) {
iter.next();
iter.remove();
}
}
/**
* Try to fix the given read using the given split
*
* @param read the read to fix
* @param splice the split (bad region to clip out)
*/
private void fixSplit(final SplitRead read, final Splice splice) {
// if the read doesn't even overlap the split position then we can just exit
if ( read.loc == null || !splice.loc.overlapsP(read.loc) )
return;
if ( isLeftOverhang(read.loc, splice.loc) ) {
final int overhang = splice.loc.getStop() - read.loc.getStart() + 1;
if ( overhangingBasesMismatch(read.read.getReadBases(), 0, splice.reference, splice.reference.length - overhang, overhang) ) {
final SAMRecord clippedRead = ReadClipper.hardClipByReadCoordinates(read.read, 0, overhang - 1);
read.setRead(clippedRead);
}
}
else if ( isRightOverhang(read.loc, splice.loc) ) {
final int overhang = read.loc.getStop() - splice.loc.getStart() + 1;
if ( overhangingBasesMismatch(read.read.getReadBases(), read.read.getReadLength() - overhang, splice.reference, 0, overhang) ) {
final SAMRecord clippedRead = ReadClipper.hardClipByReadCoordinates(read.read, read.read.getReadLength() - overhang, read.read.getReadLength() - 1);
read.setRead(clippedRead);
}
}
}
/**
* Is this a proper overhang on the left side of the read?
*
* @param readLoc the read's loc
* @param spliceLoc the split's loc
* @return true if it's a left side overhang
*/
protected static boolean isLeftOverhang(final GenomeLoc readLoc, final GenomeLoc spliceLoc) {
return readLoc.getStart() <= spliceLoc.getStop() && readLoc.getStart() > spliceLoc.getStart() && readLoc.getStop() > spliceLoc.getStop();
}
/**
* Is this a proper overhang on the right side of the read?
*
* @param readLoc the read's loc
* @param spliceLoc the split's loc
* @return true if it's a right side overhang
*/
protected static boolean isRightOverhang(final GenomeLoc readLoc, final GenomeLoc spliceLoc) {
return readLoc.getStop() >= spliceLoc.getStart() && readLoc.getStop() < spliceLoc.getStop() && readLoc.getStart() < spliceLoc.getStart();
}
/**
* Are there too many mismatches to the reference among the overhanging bases?
*
* @param read the read bases
* @param readStartIndex where to start on the read
* @param reference the reference bases
* @param referenceStartIndex where to start on the reference
* @param spanToTest how many bases to test
* @return true if too many overhanging bases mismatch, false otherwise
*/
protected boolean overhangingBasesMismatch(final byte[] read,
final int readStartIndex,
final byte[] reference,
final int referenceStartIndex,
final int spanToTest) {
// don't process too small a span, too large a span, or a span that is most of a read
if ( spanToTest < 1 || spanToTest > MAX_BASES_IN_OVERHANG || spanToTest > read.length / 2 )
return false;
int numMismatchesSeen = 0;
for ( int i = 0; i < spanToTest; i++ ) {
if ( read[readStartIndex + i] != reference[referenceStartIndex + i] ) {
if ( ++numMismatchesSeen > MAX_MISMATCHES_IN_OVERHANG )
return true;
}
}
// we can still mismatch overall if at least half of the bases mismatch
return numMismatchesSeen >= ((spanToTest+1)/2);
}
/**
* Close out the manager stream by clearing the read cache
*/
public void close() {
// write out all of the remaining reads
while ( ! waitingReads.isEmpty() )
writer.addAlignment(waitingReads.poll().read);
}
// class to represent the reads with their soft-clip-included GenomeLocs
public final class SplitRead {
public SAMRecord read;
public GenomeLoc loc;
public SplitRead(final SAMRecord read) {
setRead(read);
}
public void setRead(final SAMRecord read) {
boolean readIsEmpty = ReadUtils.isEmpty(read);
if ( !readIsEmpty ) {
this.read = read;
if ( ! read.getReadUnmappedFlag() )
loc = genomeLocParser.createGenomeLoc(read.getReferenceName(), ReadUtils.getSoftStart(read), ReadUtils.getSoftEnd(read));
}
}
}
// class to represent the comparator for the split reads
private final class SplitReadComparator implements Comparator<SplitRead> {
private final SAMRecordCoordinateComparator readComparator;
public SplitReadComparator() {
readComparator = new SAMRecordCoordinateComparator();
}
public int compare(final SplitRead read1, final SplitRead read2) {
return readComparator.compare(read1.read, read2.read);
}
}
// class to represent the split positions
protected final class Splice {
public final GenomeLoc loc;
public byte[] reference;
public Splice(final String contig, final int start, final int end) {
loc = genomeLocParser.createGenomeLoc(contig, start, end);
}
public void initialize(final IndexedFastaSequenceFile referenceReader) {
reference = referenceReader.getSubsequenceAt(loc.getContig(), loc.getStart(), loc.getStop()).getBases();
}
@Override
public boolean equals(final Object other) {
return other != null && (other instanceof Splice) && this.loc.equals(((Splice)other).loc);
}
@Override
public int hashCode() {
return loc.hashCode();
}
}
// class to represent the comparator for the split reads
private final class SpliceComparator implements Comparator<Splice> {
public int compare(final Splice position1, final Splice position2) {
return position1.loc.compareTo(position2.loc);
}
}
}
| bsd-3-clause |
al3xandru/testng-jmock | core/acceptance-tests/atest/jmock/DynamicMockExample.java | 3169 | /* Copyright (c) 2000-2004 jMock.org
*/
package atest.jmock;
import org.jmock.Mock;
import org.jmock.MockObjectTestCase;
public class DynamicMockExample extends MockObjectTestCase
{
public interface Market {
String[] listStocks();
int getPrice( String ticker );
void buyStock( String ticker, int quantity );
}
public class Agent
{
Market market;
public Agent( Market market ) {
this.market = market;
}
public void buyLowestPriceStock( int cost ) {
String[] stocks = market.listStocks();
int cheapestPrice = Integer.MAX_VALUE;
String cheapestStock = null;
for (int i = 0; i < stocks.length; ++i) {
int price = market.getPrice(stocks[i]);
if (price < cheapestPrice) {
cheapestPrice = price;
cheapestStock = stocks[i];
}
}
market.buyStock(cheapestStock, cost / cheapestPrice);
}
}
public void testBuilderExample() {
Mock market = mock(Market.class);
Agent agent = new Agent((Market)market.proxy());
market.stubs().method("listStocks").withNoArguments()
.will(returnValue(new String[]{"IBM", "ORCL"}));
market.expects(atLeastOnce()).method("getPrice").with(eq("IBM"))
.will(returnValue(10));
market.expects(atLeastOnce()).method("getPrice").with(eq("ORCL"))
.will(returnValue(25));
market.expects(once()).method("buyStock").with(eq("IBM"), eq(2));
agent.buyLowestPriceStock(20);
}
public void xtestDynaMockExample() {
Mock mockMarket = mock(Market.class);
Agent agent = new Agent((Market)mockMarket.proxy());
//
//
// mockMarket.invokedMethod("buyStock", "MSFT", new Integer(10)).void();
//
// mockMarket.invokedMethod("buyStock", "MSFT", new Integer(10)).returns(true)
// .expectOnce();
// //.expectNever();
// //.addMatcher(new MyExpectation());
//
// mockMarket.invokedMethod("listStocks").alwaysReturns(new Vector("MSFT", "ORCL"));
// mockMarket.invokedMethod("getPrice", "MSFT").alwaysReturns(10);
// mockMarket.invokedMethod("getPrice", "ORCL").alwaysReturns(50);
//
// mockMarket.invokedMethod(C.equal("buyStock"), C.eq(1)).
//
// mockMarket.methodName("listStocks").noParams()
// .alwaysReturns("MSFT");
//
// InvocationHandler listInvocation = mockMarket.methodName("listStocks").noParams()
// .returns("MSFT")
// .returns("ORCL")
// .throwsException(new ....);
//
// mockMarket.methodName("buyStock").params("MSFT", 10).returns(900)
// .calledOnce()
// .before(listInvocation);
// mockMarket.methodName("buyStock").params("ORCL", 2).returns(100)
// .calledOnce()
// .before(listInvocation);
//
// mockMarket.newInvocationHandler().addMatcher( new NameMatcher(new IsEqual("buyStock"))
// .addMatcher( new ActualParameterMatcher( new Constraint[] { new IsEqual("MSFT"), new IsEqual(new Integer(10)})))
// .addStub( new ReturnStub( new Integer(900) )));
//
//
agent.buyLowestPriceStock(1000);
}
}
| bsd-3-clause |
MjAbuz/carrot2 | core/carrot2-util-text/src-test/org/carrot2/text/vsm/TermDocumentMatrixBuilderTest.java | 7308 |
/*
* Carrot2 project.
*
* Copyright (C) 2002-2015, Dawid Weiss, Stanisław Osiński.
* All rights reserved.
*
* Refer to the full license file "carrot2.LICENSE"
* in the root folder of the repository checkout or at:
* http://www.carrot2.org/carrot2.LICENSE
*/
package org.carrot2.text.vsm;
import org.carrot2.matrix.MatrixAssertions;
import org.carrot2.text.preprocessing.PreprocessingContext;
import org.junit.Test;
import com.carrotsearch.hppc.IntIntHashMap;
/**
* Test cases for {@link TermDocumentMatrixBuilder}.
*/
@SuppressWarnings("deprecation")
public class TermDocumentMatrixBuilderTest extends TermDocumentMatrixBuilderTestBase
{
@Test
public void testEmpty()
{
int [] expectedTdMatrixStemIndices = new int [] {};
double [][] expectedTdMatrixElements = new double [] [] {};
check(expectedTdMatrixElements, expectedTdMatrixStemIndices);
}
@Test
public void testSingleWords()
{
createDocuments("", "aa . bb", "", "bb . cc", "", "aa . cc . cc");
int [] expectedTdMatrixStemIndices = new int []
{
2, 0, 1
};
double [][] expectedTdMatrixElements = new double [] []
{
{
0, 1, 2
},
{
1, 0, 1
},
{
1, 1, 0
}
};
check(expectedTdMatrixElements, expectedTdMatrixStemIndices);
}
@Test
public void testSinglePhrase()
{
createDocuments("", "aa bb cc", "", "aa bb cc", "", "aa bb cc");
int [] expectedTdMatrixStemIndices = new int []
{
0, 1, 2
};
double [][] expectedTdMatrixElements = new double [] []
{
{
1, 1, 1
},
{
1, 1, 1
},
{
1, 1, 1
},
};
check(expectedTdMatrixElements, expectedTdMatrixStemIndices);
}
@Test
public void testSinglePhraseWithSingleWords()
{
createDocuments("", "aa bb cc", "", "aa bb cc", "", "aa bb cc", "",
"ff . gg . ff . gg");
preprocessingPipeline.documentAssigner.minClusterSize = 1;
int [] expectedTdMatrixStemIndices = new int []
{
0, 1, 2, 3, 4
};
double [][] expectedTdMatrixElements = new double [] []
{
{
1, 1, 1, 0
},
{
1, 1, 1, 0
},
{
1, 1, 1, 0
},
{
0, 0, 0, 2
},
{
0, 0, 0, 2
},
};
check(expectedTdMatrixElements, expectedTdMatrixStemIndices);
}
@Test
public void testSinglePhraseWithStopWord()
{
createDocuments("", "aa stop cc", "", "aa stop cc", "", "aa stop cc");
int [] expectedTdMatrixStemIndices = new int []
{
0, 1
};
double [][] expectedTdMatrixElements = new double [] []
{
{
1, 1, 1
},
{
1, 1, 1
}
};
System.out.println(context);
check(expectedTdMatrixElements, expectedTdMatrixStemIndices);
}
@Test
public void testMatrixSizeLimit()
{
createDocuments("", "aa . aa", "", "bb . bb . bb", "", "cc . cc . cc . cc");
preprocessingPipeline.documentAssigner.minClusterSize = 1;
int [] expectedTdMatrixStemIndices = new int []
{
2, 1
};
double [][] expectedTdMatrixElements = new double [] []
{
{
0, 0, 4
},
{
0, 3, 0
}
};
matrixBuilder.maximumMatrixSize = 3 * 2;
check(expectedTdMatrixElements, expectedTdMatrixStemIndices);
}
@Test
public void testTitleWordBoost()
{
createDocuments("aa", "bb", "", "bb . cc", "", "aa . cc . cc");
int [] expectedTdMatrixStemIndices = new int []
{
0, 2, 1
};
double [][] expectedTdMatrixElements = new double [] []
{
{
2, 0, 2
},
{
0, 1, 2
},
{
1, 1, 0
}
};
check(expectedTdMatrixElements, expectedTdMatrixStemIndices);
}
@Test
public void testCarrot905()
{
createDocuments("", "aa . bb", "", "bb . cc", "", "aa . cc . cc");
PreprocessingContext context = preprocessingPipeline.preprocess(
this.context.documents,
this.context.query,
this.context.language.getLanguageCode());
// The preprocessing pipeline will produce increasing indices in tfByDocument,
// so to reproduce the bug, we need to perturb them, e.g. reverse.
final int [][] tfByDocument = context.allStems.tfByDocument;
for (int s = 0; s < tfByDocument.length; s++)
{
final int [] stemTfByDocument = tfByDocument[s];
for (int i = 0; i < stemTfByDocument.length / 4; i++)
{
int t = stemTfByDocument[i * 2];
stemTfByDocument[i * 2] = stemTfByDocument[(stemTfByDocument.length / 2 - i - 1) * 2];
stemTfByDocument[(stemTfByDocument.length / 2 - i - 1) * 2] = t;
t = stemTfByDocument[i * 2 + 1];
stemTfByDocument[i * 2 + 1] = stemTfByDocument[(stemTfByDocument.length / 2 - i - 1) * 2 + 1];
stemTfByDocument[(stemTfByDocument.length / 2 - i - 1) * 2 + 1] = t;
}
}
vsmContext = new VectorSpaceModelContext(context);
matrixBuilder.buildTermDocumentMatrix(vsmContext);
matrixBuilder.buildTermPhraseMatrix(vsmContext);
int [] expectedTdMatrixStemIndices = new int []
{
2, 0, 1
};
double [][] expectedTdMatrixElements = new double [] []
{
{
0, 1, 2
},
{
1, 0, 1
},
{
1, 1, 0
}
};
checkOnly(expectedTdMatrixElements, expectedTdMatrixStemIndices);
}
private void check(double [][] expectedTdMatrixElements,
int [] expectedTdMatrixStemIndices)
{
buildTermDocumentMatrix();
checkOnly(expectedTdMatrixElements, expectedTdMatrixStemIndices);
}
void checkOnly(double [][] expectedTdMatrixElements,
int [] expectedTdMatrixStemIndices)
{
assertThat(vsmContext.termDocumentMatrix.rows()).as("tdMatrix.rowCount")
.isEqualTo(expectedTdMatrixStemIndices.length);
MatrixAssertions.assertThat(vsmContext.termDocumentMatrix).isEquivalentTo(
expectedTdMatrixElements);
final IntIntHashMap expectedStemToRowIndex = new IntIntHashMap();
for (int i = 0; i < expectedTdMatrixStemIndices.length; i++)
{
expectedStemToRowIndex.put(expectedTdMatrixStemIndices[i], i);
}
assertThat((Object) vsmContext.stemToRowIndex).isEqualTo(expectedStemToRowIndex);
}
}
| bsd-3-clause |
DevilTech/Robotics2014 | src/edu/wpi/first/wpilibj/templates/Wiring.java | 347 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package edu.wpi.first.wpilibj.templates;
public class Wiring {
public static final int SAMPLE_RATE = 0;
public static final double SENSOR_SCALE = 1;
}
| bsd-3-clause |
synergynet/synergynet3.1 | synergynet3.1-parent/synergynet3-appsystem-core/src/main/java/synergynet3/mediadetection/mediasearch/comparators/FileNameComparator.java | 578 | package synergynet3.mediadetection.mediasearch.comparators;
import java.io.File;
import java.util.Comparator;
/**
* The Class FileNameComparator.
*/
public class FileNameComparator implements Comparator<File>
{
/*
* (non-Javadoc)
* @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
*/
@Override
public int compare(File a, File b)
{
if (a.isDirectory() && !a.isDirectory())
{
return -1;
}
else if (!a.isDirectory() && a.isDirectory())
{
return 1;
}
else
{
return a.getName().compareToIgnoreCase(b.getName());
}
}
}
| bsd-3-clause |
gurkerl83/millipede-xtreemfs | java/servers/src/org/xtreemfs/mrc/operations/GetXAttrsOperation.java | 4235 | /*
* Copyright (c) 2008-2011 by Jan Stender,
* Zuse Institute Berlin
*
* Licensed under the BSD License, see LICENSE file for details.
*
*/
package org.xtreemfs.mrc.operations;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.xtreemfs.mrc.MRCRequest;
import org.xtreemfs.mrc.MRCRequestDispatcher;
import org.xtreemfs.mrc.ac.FileAccessManager;
import org.xtreemfs.mrc.database.DatabaseResultSet;
import org.xtreemfs.mrc.database.StorageManager;
import org.xtreemfs.mrc.database.VolumeManager;
import org.xtreemfs.mrc.metadata.FileMetadata;
import org.xtreemfs.mrc.metadata.XAttr;
import org.xtreemfs.mrc.utils.MRCHelper;
import org.xtreemfs.mrc.utils.Path;
import org.xtreemfs.mrc.utils.PathResolver;
import org.xtreemfs.mrc.utils.MRCHelper.SysAttrs;
import org.xtreemfs.pbrpc.generatedinterfaces.MRC.listxattrRequest;
import org.xtreemfs.pbrpc.generatedinterfaces.MRC.listxattrResponse;
/**
*
* @author stender
*/
public class GetXAttrsOperation extends MRCOperation {
public GetXAttrsOperation(MRCRequestDispatcher master) {
super(master);
}
@Override
public void startRequest(MRCRequest rq) throws Throwable {
final listxattrRequest rqArgs = (listxattrRequest) rq.getRequestArgs();
final VolumeManager vMan = master.getVolumeManager();
final FileAccessManager faMan = master.getFileAccessManager();
validateContext(rq);
Path p = new Path(rqArgs.getVolumeName(), rqArgs.getPath());
StorageManager sMan = vMan.getStorageManagerByName(p.getComp(0));
PathResolver res = new PathResolver(sMan, p);
// check whether the path prefix is searchable
faMan.checkSearchPermission(sMan, res, rq.getDetails().userId, rq.getDetails().superUser, rq
.getDetails().groupIds);
// check whether file exists
res.checkIfFileDoesNotExist();
// retrieve and prepare the metadata to return
FileMetadata file = res.getFile();
Map<String, String> attrs = new HashMap<String, String>();
DatabaseResultSet<XAttr> myAttrs = sMan.getXAttrs(file.getId(), rq.getDetails().userId);
DatabaseResultSet<XAttr> globalAttrs = sMan.getXAttrs(file.getId(), StorageManager.GLOBAL_ID);
// include global attributes
while (globalAttrs.hasNext()) {
XAttr attr = globalAttrs.next();
attrs.put(attr.getKey(), attr.getValue());
}
globalAttrs.destroy();
// include individual user attributes
while (myAttrs.hasNext()) {
XAttr attr = myAttrs.next();
attrs.put(attr.getKey(), attr.getValue());
}
myAttrs.destroy();
// include system attributes
for (SysAttrs attr : SysAttrs.values()) {
String key = "xtreemfs." + attr.toString();
String value = MRCHelper.getSysAttrValue(master.getConfig(), sMan, master.getOSDStatusManager(),
faMan, res.toString(), file, attr.toString());
if (!value.equals(""))
attrs.put(key, value);
}
// include policy attributes
List<String> policyAttrNames = MRCHelper.getPolicyAttrNames(sMan, file.getId());
for (String attr : policyAttrNames)
attrs.put(attr, "");
listxattrResponse.Builder result = listxattrResponse.newBuilder();
Iterator<Entry<String, String>> it = attrs.entrySet().iterator();
while (it.hasNext()) {
Entry<String, String> attr = it.next();
org.xtreemfs.pbrpc.generatedinterfaces.MRC.XAttr.Builder builder = org.xtreemfs.pbrpc.generatedinterfaces.MRC.XAttr
.newBuilder().setName(attr.getKey());
if (!rqArgs.getNamesOnly())
builder.setValue(attr.getValue());
result.addXattrs(builder.build());
}
// set the response
rq.setResponse(result.build());
finishRequest(rq);
}
}
| bsd-3-clause |
OurMap/OurMap | OurMapWeb/src/com/bnmi/ourmap/web/actions/SaveIconCategories.java | 5271 | /*******************************************************************************
com.bnmi.ourmap.web.actions.SaveIconCategories.java
Version: 1.0
********************************************************************************
Original Authors:
Manuel Cuesta, lead programmer <camilocuesta@hotmail.com>
Angus Leech, lead designer <alpinefabulist@yahoo.com>
Full credits at: <http://www.ourmapmaker.ca/content/about-ourmap/credits>
For questions or comments please contact us at: [ourmap@ourmapmaker.ca]
********************************************************************************
OurMap is Copyright (c) 2010, The Banff Centre <ourmap@ourmapmaker.ca>
All rights reserved.
Published under the terms of the new BSD license.
See <www.ourmapmaker.ca/content/about-ourmap> for more information about the
OurMap software and the license.
Full sourcecode, documentation and license info is also available here:
http://github.com/OurMap/OurMap
LICENSE:
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
Neither the name of The Banff Centre nor the names of its contributors may be
used to endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
********************************************************************************
Revision History / Change Log:
Version 1.0 released Oct.2010
********************************************************************************
Notes:
*******************************************************************************/
package com.bnmi.ourmap.web.actions;
import com.bnmi.ourmap.control.EasyDelegate;
import com.bnmi.ourmap.model.Category;
import com.bnmi.ourmap.model.CriteriosCategory;
import com.bnmi.ourmap.model.Map;
import com.bnmi.ourmap.model.Project;
import com.bnmi.ourmap.web.Constantes;
import com.inga.utils.SigarUtils;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
/**
*
* @author Manuel Camilo Cuesta
*/
public class SaveIconCategories extends Action {
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
HttpSession session = request.getSession();
EasyDelegate del = (EasyDelegate) session.getAttribute(Constantes.DELEGATE);
Integer mapid = SigarUtils.parseInt( request.getParameter("mapid"));
if ( mapid == null )
mapid = (Integer) request.getAttribute("mapid");
Map m = del.getMap(mapid);
Project p = del.getProject( m.getProjectId() );
Integer iconsMode = m.getIconsMode();
if ( iconsMode != null && iconsMode.intValue() == 2 )
{
CriteriosCategory findKeys = new CriteriosCategory();
findKeys.setMapId(mapid);
List<Category> cats = del.findCategorys(findKeys);
boolean allCatsHaveIcon = true;
for( Category k : cats )
{
if ( k.getIconId() == null )
{
allCatsHaveIcon = false;
break;
}
}
if ( ! allCatsHaveIcon )
{
response.sendRedirect( "editicons.do?mapid=" + mapid );
session.setAttribute("category_icon_missing", "true" );
return null;
}
else
{
session.removeAttribute("category_icon_missing");
}
}
Object newcategory = session.getAttribute("newcategory");
session.removeAttribute("newcategory");
if ( newcategory != null )
{
response.sendRedirect( "orgcats.do?mapid=" + mapid );
return null;
}
response.sendRedirect( "mapconfiguration.do?mapid=" + mapid );
return null;
}
}
| bsd-3-clause |
fmapfmapfmap/onionoo-dev | src/main/java/org/torproject/onionoo/docs/DetailsDocument.java | 10910 | /* Copyright 2013--2014 The Tor Project
* See LICENSE for licensing information */
package org.torproject.onionoo.docs;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;
import org.apache.commons.lang3.StringEscapeUtils;
public class DetailsDocument extends Document {
/* We must ensure that details files only contain ASCII characters
* and no UTF-8 characters. While UTF-8 characters are perfectly
* valid in JSON, this would break compatibility with existing files
* pretty badly. We do this by escaping non-ASCII characters, e.g.,
* \u00F2. Gson won't treat this as UTF-8, but will think that we want
* to write six characters '\', 'u', '0', '0', 'F', '2'. The only thing
* we'll have to do is to change back the '\\' that Gson writes for the
* '\'. */
private static String escapeJSON(String s) {
return StringEscapeUtils.escapeJava(s);
}
private static String unescapeJSON(String s) {
return StringEscapeUtils.unescapeJava(s);
}
private String nickname;
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getNickname() {
return this.nickname;
}
private String fingerprint;
public void setFingerprint(String fingerprint) {
this.fingerprint = fingerprint;
}
public String getFingerprint() {
return this.fingerprint;
}
private String hashed_fingerprint;
public void setHashedFingerprint(String hashedFingerprint) {
this.hashed_fingerprint = hashedFingerprint;
}
public String getHashedFingerprint() {
return this.hashed_fingerprint;
}
private List<String> or_addresses;
public void setOrAddresses(List<String> orAddresses) {
this.or_addresses = orAddresses;
}
public List<String> getOrAddresses() {
return this.or_addresses;
}
private List<String> exit_addresses;
public void setExitAddresses(List<String> exitAddresses) {
this.exit_addresses = !exitAddresses.isEmpty() ? exitAddresses : null;
}
public List<String> getExitAddresses() {
return this.exit_addresses == null ? new ArrayList<String>()
: this.exit_addresses;
}
private String dir_address;
public void setDirAddress(String dirAddress) {
this.dir_address = dirAddress;
}
public String getDirAddress() {
return this.dir_address;
}
private String last_seen;
public void setLastSeen(long lastSeen) {
this.last_seen = DateTimeHelper.format(lastSeen);
}
public long getLastSeen() {
return DateTimeHelper.parse(this.last_seen);
}
private String last_changed_address_or_port;
public void setLastChangedAddressOrPort(
long lastChangedAddressOrPort) {
this.last_changed_address_or_port = DateTimeHelper.format(
lastChangedAddressOrPort);
}
public long getLastChangedAddressOrPort() {
return DateTimeHelper.parse(this.last_changed_address_or_port);
}
private String first_seen;
public void setFirstSeen(long firstSeen) {
this.first_seen = DateTimeHelper.format(firstSeen);
}
public long getFirstSeen() {
return DateTimeHelper.parse(this.first_seen);
}
private Boolean running;
public void setRunning(Boolean running) {
this.running = running;
}
public Boolean getRunning() {
return this.running;
}
private SortedSet<String> flags;
public void setFlags(SortedSet<String> flags) {
this.flags = flags;
}
public SortedSet<String> getFlags() {
return this.flags;
}
private String country;
public void setCountry(String country) {
this.country = country;
}
public String getCountry() {
return this.country;
}
private String country_name;
public void setCountryName(String countryName) {
this.country_name = escapeJSON(countryName);
}
public String getCountryName() {
return unescapeJSON(this.country_name);
}
private String region_name;
public void setRegionName(String regionName) {
this.region_name = escapeJSON(regionName);
}
public String getRegionName() {
return unescapeJSON(this.region_name);
}
private String city_name;
public void setCityName(String cityName) {
this.city_name = escapeJSON(cityName);
}
public String getCityName() {
return unescapeJSON(this.city_name);
}
private Float latitude;
public void setLatitude(Float latitude) {
this.latitude = latitude;
}
public Float getLatitude() {
return this.latitude;
}
private Float longitude;
public void setLongitude(Float longitude) {
this.longitude = longitude;
}
public Float getLongitude() {
return this.longitude;
}
private String as_number;
public void setAsNumber(String asNumber) {
this.as_number = escapeJSON(asNumber);
}
public String getAsNumber() {
return unescapeJSON(this.as_number);
}
private String as_name;
public void setAsName(String asName) {
this.as_name = escapeJSON(asName);
}
public String getAsName() {
return unescapeJSON(this.as_name);
}
private Long consensus_weight;
public void setConsensusWeight(Long consensusWeight) {
this.consensus_weight = consensusWeight;
}
public Long getConsensusWeight() {
return this.consensus_weight;
}
private String host_name;
public void setHostName(String hostName) {
this.host_name = escapeJSON(hostName);
}
public String getHostName() {
return unescapeJSON(this.host_name);
}
private String last_restarted;
public void setLastRestarted(Long lastRestarted) {
this.last_restarted = (lastRestarted == null ? null :
DateTimeHelper.format(lastRestarted));
}
public Long getLastRestarted() {
return this.last_restarted == null ? null :
DateTimeHelper.parse(this.last_restarted);
}
private Integer bandwidth_rate;
public void setBandwidthRate(Integer bandwidthRate) {
this.bandwidth_rate = bandwidthRate;
}
public Integer getBandwidthRate() {
return this.bandwidth_rate;
}
private Integer bandwidth_burst;
public void setBandwidthBurst(Integer bandwidthBurst) {
this.bandwidth_burst = bandwidthBurst;
}
public Integer getBandwidthBurst() {
return this.bandwidth_burst;
}
private Integer observed_bandwidth;
public void setObservedBandwidth(Integer observedBandwidth) {
this.observed_bandwidth = observedBandwidth;
}
public Integer getObservedBandwidth() {
return this.observed_bandwidth;
}
private Integer advertised_bandwidth;
public void setAdvertisedBandwidth(Integer advertisedBandwidth) {
this.advertised_bandwidth = advertisedBandwidth;
}
public Integer getAdvertisedBandwidth() {
return this.advertised_bandwidth;
}
private List<String> exit_policy;
public void setExitPolicy(List<String> exitPolicy) {
this.exit_policy = exitPolicy;
}
public List<String> getExitPolicy() {
return this.exit_policy;
}
private Map<String, List<String>> exit_policy_summary;
public void setExitPolicySummary(
Map<String, List<String>> exitPolicySummary) {
this.exit_policy_summary = exitPolicySummary;
}
public Map<String, List<String>> getExitPolicySummary() {
return this.exit_policy_summary;
}
private Map<String, List<String>> exit_policy_v6_summary;
public void setExitPolicyV6Summary(
Map<String, List<String>> exitPolicyV6Summary) {
this.exit_policy_v6_summary = exitPolicyV6Summary;
}
public Map<String, List<String>> getExitPolicyV6Summary() {
return this.exit_policy_v6_summary;
}
private String contact;
public void setContact(String contact) {
this.contact = escapeJSON(contact);
}
public String getContact() {
return unescapeJSON(this.contact);
}
private String platform;
public void setPlatform(String platform) {
this.platform = escapeJSON(platform);
}
public String getPlatform() {
return unescapeJSON(this.platform);
}
private List<String> family;
public void setFamily(List<String> family) {
this.family = family;
}
public List<String> getFamily() {
return this.family;
}
private SortedSet<String> alleged_family;
public void setAllegedFamily(SortedSet<String> allegedFamily) {
this.alleged_family = allegedFamily;
}
public SortedSet<String> getAllegedFamily() {
return this.alleged_family;
}
private SortedSet<String> effective_family;
public void setEffectiveFamily(SortedSet<String> effectiveFamily) {
this.effective_family = effectiveFamily;
}
public SortedSet<String> getEffectiveFamily() {
return this.effective_family;
}
private SortedSet<String> indirect_family;
public void setIndirectFamily(SortedSet<String> indirectFamily) {
this.indirect_family = indirectFamily;
}
public SortedSet<String> getIndirectFamily() {
return this.indirect_family;
}
private Float consensus_weight_fraction;
public void setConsensusWeightFraction(Float consensusWeightFraction) {
if (consensusWeightFraction == null ||
consensusWeightFraction >= 0.0) {
this.consensus_weight_fraction = consensusWeightFraction;
}
}
public Float getConsensusWeightFraction() {
return this.consensus_weight_fraction;
}
private Float guard_probability;
public void setGuardProbability(Float guardProbability) {
if (guardProbability == null || guardProbability >= 0.0) {
this.guard_probability = guardProbability;
}
}
public Float getGuardProbability() {
return this.guard_probability;
}
private Float middle_probability;
public void setMiddleProbability(Float middleProbability) {
if (middleProbability == null || middleProbability >= 0.0) {
this.middle_probability = middleProbability;
}
}
public Float getMiddleProbability() {
return this.middle_probability;
}
private Float exit_probability;
public void setExitProbability(Float exitProbability) {
if (exitProbability == null || exitProbability >= 0.0) {
this.exit_probability = exitProbability;
}
}
public Float getExitProbability() {
return this.exit_probability;
}
private Boolean recommended_version;
public void setRecommendedVersion(Boolean recommendedVersion) {
this.recommended_version = recommendedVersion;
}
public Boolean getRecommendedVersion() {
return this.recommended_version;
}
private Boolean hibernating;
public void setHibernating(Boolean hibernating) {
this.hibernating = hibernating;
}
public Boolean getHibernating() {
return this.hibernating;
}
private List<String> transports;
public void setTransports(List<String> transports) {
this.transports = (transports != null && !transports.isEmpty()) ?
transports : null;
}
public List<String> getTransports() {
return this.transports;
}
private Boolean measured;
public void setMeasured(Boolean measured) {
this.measured = measured;
}
public Boolean getMeasured() {
return this.measured;
}
}
| bsd-3-clause |
y-usuzumi/survive-the-course | random_questions/找出和为给定值的所有路径/java/ratina/src/test/java/ratina/AppTest.java | 278 | package ratina;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
/**
* Unit test for simple App.
*/
public class AppTest
{
/**
* Rigorous Test :-)
*/
@Test
public void shouldAnswerWithTrue()
{
assertTrue( true );
}
}
| bsd-3-clause |
exponent/exponent | packages/expo-updates/android/src/androidTest/java/expo/modules/updates/launcher/SelectionPolicyFilterAwareTest.java | 10467 | package expo.modules.updates.launcher;
import android.net.Uri;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import androidx.test.internal.runner.junit4.AndroidJUnit4ClassRunner;
import expo.modules.updates.UpdatesConfiguration;
import expo.modules.updates.db.entity.UpdateEntity;
import expo.modules.updates.manifest.NewManifest;
@RunWith(AndroidJUnit4ClassRunner.class)
public class SelectionPolicyFilterAwareTest {
JSONObject manifestFilters;
SelectionPolicyFilterAware selectionPolicy;
UpdateEntity updateDefault1;
UpdateEntity updateDefault2;
UpdateEntity updateRollout0;
UpdateEntity updateRollout1;
UpdateEntity updateRollout2;
UpdateEntity updateMultipleFilters;
UpdateEntity updateNoMetadata;
@Before
public void setup() throws JSONException {
manifestFilters = new JSONObject("{\"branchname\": \"rollout\"}");
selectionPolicy = new SelectionPolicyFilterAware("1.0");
HashMap<String, Object> configMap = new HashMap<>();
configMap.put("updateUrl", Uri.parse("https://exp.host/@test/test"));
UpdatesConfiguration config = new UpdatesConfiguration().loadValuesFromMap(configMap);
JSONObject manifestJsonRollout0 = new JSONObject("{\"id\":\"079cde35-8433-4c17-81c8-7117c1513e71\",\"createdAt\":\"2021-01-10T19:39:22.480Z\",\"runtimeVersion\":\"1.0\",\"launchAsset\":{\"hash\":\"DW5MBgKq155wnX8rCP1lnsW6BsTbfKLXxGXRQx1RcOA\",\"key\":\"0436e5821bff7b95a84c21f22a43cb96.bundle\",\"contentType\":\"application/javascript\",\"url\":\"https://url.to/bundle\"},\"assets\":[{\"hash\":\"JSeRsPNKzhVdHP1OEsDVsLH500Zfe4j1O7xWfa14oBo\",\"key\":\"3261e570d51777be1e99116562280926.png\",\"contentType\":\"image/png\",\"url\":\"https://url.to/asset\"}],\"updateMetadata\":{\"branchName\":\"rollout\"}}");
updateRollout0 = NewManifest.fromManifestJson(manifestJsonRollout0, null, config).getUpdateEntity();
JSONObject manifestJsonDefault1 = new JSONObject("{\"id\":\"079cde35-8433-4c17-81c8-7117c1513e72\",\"createdAt\":\"2021-01-11T19:39:22.480Z\",\"runtimeVersion\":\"1.0\",\"launchAsset\":{\"hash\":\"DW5MBgKq155wnX8rCP1lnsW6BsTbfKLXxGXRQx1RcOA\",\"key\":\"0436e5821bff7b95a84c21f22a43cb96.bundle\",\"contentType\":\"application/javascript\",\"url\":\"https://url.to/bundle\"},\"assets\":[{\"hash\":\"JSeRsPNKzhVdHP1OEsDVsLH500Zfe4j1O7xWfa14oBo\",\"key\":\"3261e570d51777be1e99116562280926.png\",\"contentType\":\"image/png\",\"url\":\"https://url.to/asset\"}],\"updateMetadata\":{\"branchName\":\"default\"}}");
updateDefault1 = NewManifest.fromManifestJson(manifestJsonDefault1, null, config).getUpdateEntity();
JSONObject manifestJsonRollout1 = new JSONObject("{\"id\":\"079cde35-8433-4c17-81c8-7117c1513e73\",\"createdAt\":\"2021-01-12T19:39:22.480Z\",\"runtimeVersion\":\"1.0\",\"launchAsset\":{\"hash\":\"DW5MBgKq155wnX8rCP1lnsW6BsTbfKLXxGXRQx1RcOA\",\"key\":\"0436e5821bff7b95a84c21f22a43cb96.bundle\",\"contentType\":\"application/javascript\",\"url\":\"https://url.to/bundle\"},\"assets\":[{\"hash\":\"JSeRsPNKzhVdHP1OEsDVsLH500Zfe4j1O7xWfa14oBo\",\"key\":\"3261e570d51777be1e99116562280926.png\",\"contentType\":\"image/png\",\"url\":\"https://url.to/asset\"}],\"updateMetadata\":{\"branchName\":\"rollout\"}}");
updateRollout1 = NewManifest.fromManifestJson(manifestJsonRollout1, null, config).getUpdateEntity();
JSONObject manifestJsonDefault2 = new JSONObject("{\"id\":\"079cde35-8433-4c17-81c8-7117c1513e74\",\"createdAt\":\"2021-01-13T19:39:22.480Z\",\"runtimeVersion\":\"1.0\",\"launchAsset\":{\"hash\":\"DW5MBgKq155wnX8rCP1lnsW6BsTbfKLXxGXRQx1RcOA\",\"key\":\"0436e5821bff7b95a84c21f22a43cb96.bundle\",\"contentType\":\"application/javascript\",\"url\":\"https://url.to/bundle\"},\"assets\":[{\"hash\":\"JSeRsPNKzhVdHP1OEsDVsLH500Zfe4j1O7xWfa14oBo\",\"key\":\"3261e570d51777be1e99116562280926.png\",\"contentType\":\"image/png\",\"url\":\"https://url.to/asset\"}],\"updateMetadata\":{\"branchName\":\"default\"}}");
updateDefault2 = NewManifest.fromManifestJson(manifestJsonDefault2, null, config).getUpdateEntity();
JSONObject manifestJsonRollout2 = new JSONObject("{\"id\":\"079cde35-8433-4c17-81c8-7117c1513e75\",\"createdAt\":\"2021-01-14T19:39:22.480Z\",\"runtimeVersion\":\"1.0\",\"launchAsset\":{\"hash\":\"DW5MBgKq155wnX8rCP1lnsW6BsTbfKLXxGXRQx1RcOA\",\"key\":\"0436e5821bff7b95a84c21f22a43cb96.bundle\",\"contentType\":\"application/javascript\",\"url\":\"https://url.to/bundle\"},\"assets\":[{\"hash\":\"JSeRsPNKzhVdHP1OEsDVsLH500Zfe4j1O7xWfa14oBo\",\"key\":\"3261e570d51777be1e99116562280926.png\",\"contentType\":\"image/png\",\"url\":\"https://url.to/asset\"}],\"updateMetadata\":{\"branchName\":\"rollout\"}}");
updateRollout2 = NewManifest.fromManifestJson(manifestJsonRollout2, null, config).getUpdateEntity();
JSONObject manifestJsonMultipleFilters = new JSONObject("{\"id\":\"079cde35-8433-4c17-81c8-7117c1513e72\",\"createdAt\":\"2021-01-11T19:39:22.480Z\",\"runtimeVersion\":\"1.0\",\"launchAsset\":{\"hash\":\"DW5MBgKq155wnX8rCP1lnsW6BsTbfKLXxGXRQx1RcOA\",\"key\":\"0436e5821bff7b95a84c21f22a43cb96.bundle\",\"contentType\":\"application/javascript\",\"url\":\"https://url.to/bundle\"},\"assets\":[{\"hash\":\"JSeRsPNKzhVdHP1OEsDVsLH500Zfe4j1O7xWfa14oBo\",\"key\":\"3261e570d51777be1e99116562280926.png\",\"contentType\":\"image/png\",\"url\":\"https://url.to/asset\"}],\"updateMetadata\":{\"firstKey\": \"value1\", \"secondKey\": \"value2\"}}");
updateMultipleFilters = NewManifest.fromManifestJson(manifestJsonMultipleFilters, null, config).getUpdateEntity();
JSONObject manifestJsonNoMetadata = new JSONObject("{\"id\":\"079cde35-8433-4c17-81c8-7117c1513e72\",\"createdAt\":\"2021-01-11T19:39:22.480Z\",\"runtimeVersion\":\"1.0\",\"launchAsset\":{\"hash\":\"DW5MBgKq155wnX8rCP1lnsW6BsTbfKLXxGXRQx1RcOA\",\"key\":\"0436e5821bff7b95a84c21f22a43cb96.bundle\",\"contentType\":\"application/javascript\",\"url\":\"https://url.to/bundle\"},\"assets\":[{\"hash\":\"JSeRsPNKzhVdHP1OEsDVsLH500Zfe4j1O7xWfa14oBo\",\"key\":\"3261e570d51777be1e99116562280926.png\",\"contentType\":\"image/png\",\"url\":\"https://url.to/asset\"}]}");
updateNoMetadata = NewManifest.fromManifestJson(manifestJsonNoMetadata, null, config).getUpdateEntity();
}
@Test
public void testSelectUpdateToLaunch() {
// should pick the newest update that matches the manifest filters
UpdateEntity expected = updateRollout1;
UpdateEntity actual = selectionPolicy.selectUpdateToLaunch(Arrays.asList(updateDefault1, expected, updateDefault2), manifestFilters);
Assert.assertEquals(expected, actual);
}
@Test
public void testSelectUpdatesToDelete_SecondNewestMatching() {
// if there is an older update that matches the manifest filters, keep that one over any newer ones that don't match
List<UpdateEntity> updatesToDelete = selectionPolicy.selectUpdatesToDelete(Arrays.asList(updateRollout0, updateDefault1, updateRollout1, updateDefault2, updateRollout2), updateRollout2, manifestFilters);
Assert.assertEquals(3, updatesToDelete.size());
Assert.assertTrue(updatesToDelete.contains(updateRollout0));
Assert.assertTrue(updatesToDelete.contains(updateDefault1));
Assert.assertFalse(updatesToDelete.contains(updateRollout1));
Assert.assertTrue(updatesToDelete.contains(updateDefault2));
Assert.assertFalse(updatesToDelete.contains(updateRollout2));
}
@Test
public void testSelectUpdatesToDelete_NoneOlderMatching() {
// if there is no older update that matches the manifest filters, just keep the next newest one
List<UpdateEntity> updatesToDelete = selectionPolicy.selectUpdatesToDelete(Arrays.asList(updateDefault1, updateDefault2, updateRollout2), updateRollout2, manifestFilters);
Assert.assertEquals(1, updatesToDelete.size());
Assert.assertTrue(updatesToDelete.contains(updateDefault1));
Assert.assertFalse(updatesToDelete.contains(updateDefault2));
Assert.assertFalse(updatesToDelete.contains(updateRollout2));
}
@Test
public void testShouldLoadNewUpdate_NormalCase_NewUpdate() {
boolean actual = selectionPolicy.shouldLoadNewUpdate(updateRollout2, updateRollout1, manifestFilters);
Assert.assertTrue(actual);
}
@Test
public void testShouldLoadNewUpdate_NormalCase_NoUpdate() {
boolean actual = selectionPolicy.shouldLoadNewUpdate(updateRollout1, updateRollout1, manifestFilters);
Assert.assertFalse(actual);
}
@Test
public void testShouldLoadNewUpdate_NoneMatchingFilters() {
// should choose to load an older update if the current update doesn't match the manifest filters
boolean actual = selectionPolicy.shouldLoadNewUpdate(updateRollout1, updateDefault2, manifestFilters);
Assert.assertTrue(actual);
}
@Test
public void testShouldLoadNewUpdate_NewerExists() {
boolean actual = selectionPolicy.shouldLoadNewUpdate(updateRollout1, updateRollout2, manifestFilters);
Assert.assertFalse(actual);
}
@Test
public void testShouldLoadNewUpdate_DoesntMatch() {
// should never choose to load an update that doesn't match its own filters
boolean actual = selectionPolicy.shouldLoadNewUpdate(updateDefault2, null, manifestFilters);
Assert.assertFalse(actual);
}
@Test
public void testMatchesFilters_MultipleFilters() throws JSONException {
// if there are multiple filters, a manifest must match them all to pass
Assert.assertFalse(SelectionPolicyFilterAware.matchesFilters(updateMultipleFilters, new JSONObject("{\"firstkey\": \"value1\", \"secondkey\": \"wrong-value\"}")));
Assert.assertTrue(SelectionPolicyFilterAware.matchesFilters(updateMultipleFilters, new JSONObject("{\"firstkey\": \"value1\", \"secondkey\": \"value2\"}")));
}
@Test
public void testMatchesFilters_EmptyMatchesAll() throws JSONException {
// no field is counted as a match
Assert.assertTrue(SelectionPolicyFilterAware.matchesFilters(updateDefault1, new JSONObject("{\"field-that-update-doesnt-have\": \"value\"}")));
}
@Test
public void testMatchesFilters_Null() throws JSONException {
// null filters or null updateMetadata (i.e. bare or legacy manifests) is counted as a match
Assert.assertTrue(SelectionPolicyFilterAware.matchesFilters(updateDefault1, null));
Assert.assertTrue(SelectionPolicyFilterAware.matchesFilters(updateNoMetadata, manifestFilters));
}
}
| bsd-3-clause |
wsldl123292/jodd | jodd-db/src/main/java/jodd/db/oom/mapper/ResultSetMapper.java | 1538 | // Copyright (c) 2003-present, Jodd Team (jodd.org). All Rights Reserved.
package jodd.db.oom.mapper;
import java.sql.ResultSet;
/**
* ResultSet mapper which implementations parse objects from one result set row.
* There are two ways of mapping. The basic way is mapping against provided
* entity types. The second, extended, way is auto-mapping, where no types
* are provided. Instead, they are mapped by {@link jodd.db.oom.DbOomManager} or
* similar external class.
* <p>
* There should be only one instance of <code>ResultSetMapper</code> per <code>ResultSet</code>.
*/
public interface ResultSetMapper {
// ---------------------------------------------------------------- moving
/**
* Moves the cursor down one row from its current position.
*/
boolean next();
/**
* Releases this ResultSet object's database and JDBC resources immediately instead of
* waiting for this to happen when it is automatically closed.
*/
void close();
/**
* Return JDBC result set.
*/
ResultSet getResultSet();
// ---------------------------------------------------------------- parse types
/**
* Resolves table names into the list of entity types.
* Resolving is used when query is executed without specified types.
*/
Class[] resolveTables();
/**
* Parse objects from one result set row to specified types.
*/
Object[] parseObjects(Class... types);
/**
* Parse single object from result set row to specified type.
* @see #parseObjects(Class[])
*/
Object parseOneObject(Class... types);
}
| bsd-3-clause |
lang010/acit | leetcode/1118.number-of-days-in-a-month.336157828.ac.java | 996 | /*
* @lc app=leetcode id=1118 lang=java
*
* [1118] Number of Days in a Month
*
* https://leetcode.com/problems/number-of-days-in-a-month/description/
*
* algorithms
* Easy (57.34%)
* Total Accepted: 4.7K
* Total Submissions: 8.1K
* Testcase Example: '1992\n7'
*
* Given a year Y and a month M, return how many days there are in that
* month.
*
*
*
* Example 1:
*
*
* Input: Y = 1992, M = 7
* Output: 31
*
*
* Example 2:
*
*
* Input: Y = 2000, M = 2
* Output: 29
*
*
* Example 3:
*
*
* Input: Y = 1900, M = 2
* Output: 28
*
*
*
*
* Note:
*
*
* 1583 <= Y <= 2100
* 1 <= M <= 12
*
*
*/
class Solution {
public int numberOfDays(int Y, int M) {
if (M == 2) {
if (Y%4 != 0)
return 28;
if (Y%100 == 0 && Y%400 != 0)
return 28;
return 29;
}
if (M%2 == 1 && M < 8 || M > 7 && M%2 == 0)
return 31;
return 30;
}
}
| bsd-3-clause |
resource4j/resource4j | integration/spring/src/main/java/com/github/resource4j/spring/context/EmptyResolutionContextProvider.java | 396 | package com.github.resource4j.spring.context;
import com.github.resource4j.resources.context.ResourceResolutionContext;
import static com.github.resource4j.resources.context.ResourceResolutionContext.withoutContext;
public class EmptyResolutionContextProvider implements ResolutionContextProvider {
@Override
public ResourceResolutionContext getContext() {
return withoutContext();
}
}
| bsd-3-clause |
liry/gooddata-java | src/test/java/com/gooddata/md/AttributeTest.java | 4965 | /**
* Copyright (C) 2004-2016, GoodData(R) Corporation. All rights reserved.
* This source code is licensed under the BSD-style license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
package com.gooddata.md;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.hamcrest.Matchers;
import org.testng.annotations.Test;
import java.io.InputStream;
import java.util.Collection;
import static com.gooddata.JsonMatchers.serializesToJson;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.MatcherAssert.assertThat;
public class AttributeTest {
public static final String TITLE = "Person ID";
@SuppressWarnings("deprecation")
@Test
public void shouldDeserialize() throws Exception {
final InputStream stream = getClass().getResourceAsStream("/md/attribute.json");
final Attribute attribute = new ObjectMapper().readValue(stream, Attribute.class);
assertThat(attribute, is(notNullValue()));
final Collection<DisplayForm> displayForms = attribute.getDisplayForms();
assertThat(displayForms, is(notNullValue()));
assertThat(displayForms, hasSize(1));
final DisplayForm displayForm = displayForms.iterator().next();
assertThat(displayForm, is(notNullValue()));
assertThat(displayForm.getFormOf(), is("/gdc/md/PROJECT_ID/obj/DF_FORM_OF_ID"));
assertThat(displayForm.getExpression(), is("[/gdc/md/PROJECT_ID/obj/DF_EXPRESSION_ID]"));
assertThat(displayForm.getLdmExpression(), is("[/gdc/md/PROJECT_ID/obj/DF_LDM_EXPRESSION_ID]"));
final DisplayForm defaultDisplayForm = attribute.getDefaultDisplayForm();
assertThat(defaultDisplayForm, is(notNullValue()));
assertThat(defaultDisplayForm.getFormOf(), is("/gdc/md/PROJECT_ID/obj/DF_FORM_OF_ID"));
assertThat(defaultDisplayForm.getExpression(), is("[/gdc/md/PROJECT_ID/obj/DF_EXPRESSION_ID]"));
assertThat(defaultDisplayForm.getLdmExpression(), is("[/gdc/md/PROJECT_ID/obj/DF_LDM_EXPRESSION_ID]"));
final Collection<Key> primaryKeys = attribute.getPrimaryKeys();
assertThat(primaryKeys, is(Matchers.notNullValue()));
assertThat(primaryKeys, hasSize(1));
assertThat(primaryKeys.iterator().next(), is(Matchers.notNullValue()));
final Collection<Key> foreignKeys = attribute.getForeignKeys();
assertThat(foreignKeys, is(Matchers.notNullValue()));
assertThat(foreignKeys, hasSize(1));
assertThat(foreignKeys.iterator().next(), is(Matchers.notNullValue()));
assertThat(attribute.hasDimension(), is(true));
assertThat(attribute.getDimensionLink(), is("/gdc/md/PROJECT_ID/obj/DIM_ID"));
assertThat(attribute.getDimensionUri(), is("/gdc/md/PROJECT_ID/obj/DIM_ID"));
assertThat(attribute.getDirection(), is("asc"));
assertThat(attribute.getSort(), is("pk"));
assertThat(attribute.isSortedByPk(), is(true));
assertThat(attribute.isSortedByUsedDf(), is(false));
assertThat(attribute.isSortedByLinkedDf(), is(false));
assertThat(attribute.getType(), is("GDC.time.date"));
assertThat(attribute.getLinkedDisplayFormLink(), is("/gdc/md/PROJECT_ID/obj/DF_LINK"));
assertThat(attribute.getLinkedDisplayFormUri(), is("/gdc/md/PROJECT_ID/obj/DF_LINK"));
assertThat(attribute.getCompositeAttribute(), hasSize(0));
assertThat(attribute.getCompositeAttributePk(), hasSize(0));
assertThat(attribute.getFolders(), hasSize(0));
assertThat(attribute.getGrain(), hasSize(0));
assertThat(attribute.getRelations(), hasSize(0));
}
@Test
public void testSerialization() throws Exception {
final Attribute attribute = new Attribute(TITLE, new Key("/gdc/md/PROJECT_ID/obj/PK_ID", "col"),
new Key("/gdc/md/PROJECT_ID/obj/FK_ID", "col"));
assertThat(attribute, serializesToJson("/md/attribute-input.json"));
}
@Test
public void shouldSerializeSameAsDeserializationInput() throws Exception {
final InputStream stream = getClass().getResourceAsStream("/md/attribute.json");
final Attribute attribute = new ObjectMapper().readValue(stream, Attribute.class);
assertThat(attribute, serializesToJson("/md/attribute-inputOrig.json"));
}
@Test
public void shouldDeserializeAttributeWithSort() throws Exception {
final InputStream stream = getClass().getResourceAsStream("/md/attribute-sortDf.json");
final Attribute attribute = new ObjectMapper().readValue(stream, Attribute.class);
assertThat(attribute.getSort(), is("/gdc/md/PROJECT_ID/obj/1806"));
assertThat(attribute.isSortedByLinkedDf(), is(true));
assertThat(attribute.isSortedByUsedDf(), is(false));
assertThat(attribute.isSortedByPk(), is(false));
}
}
| bsd-3-clause |
zakki/openhsp | plugins/hsplet/hspda/QuickSort/Container/DoubleContainer.java | 229 | package QuickSort.Container;
final public class DoubleContainer extends Container {
public double
value;
public DoubleContainer(final double value, final int index) {
this.value = value;
this.index = index;
}
} | bsd-3-clause |
TeamCohen/MinorThird | src/main/java/LBJ2/nlp/seg/PlainToTokenParser.java | 2100 | package LBJ2.nlp.seg;
import LBJ2.nlp.Word;
import LBJ2.parse.LinkedVector;
import LBJ2.parse.Parser;
/**
* This parser takes the {@link LBJ2.nlp.Word}s in the representation created
* by another {@link LBJ2.parse.Parser} and creates a new representation
* consisting of {@link Token}s. The input parser is actually expected to
* return a {@link LBJ2.parse.LinkedVector} populated by
* {@link LBJ2.nlp.Word}s with each call to {@link LBJ2.parse.Parser#next()}.
* The {@link Token}s returned by calls to this class's {@link #next()}
* method are also contained in {@link LBJ2.parse.LinkedVector}s representing
* sentences which are accessible via the
* {@link LBJ2.parse.LinkedVector#parent} field.
*
* @author Nick Rizzolo
**/
public class PlainToTokenParser implements Parser
{
/**
* A parser creating a representation consisting of {@link LBJ2.nlp.Word}s.
**/
protected Parser parser;
/** The next token to return. */
protected Token next;
/**
* The only constructor.
*
* @param p A parser creating a representation consisting of
* {@link LBJ2.nlp.Word}s.
**/
public PlainToTokenParser(Parser p) { parser = p; }
/**
* This method returns {@link Token}s until the input is exhausted, at
* which point it returns <code>null</code>.
**/
public Object next() {
while (next == null) {
LinkedVector words = (LinkedVector) parser.next();
if (words == null) return null;
Word w = (Word) words.get(0);
Token t = new Token(w, null, null);
for (w = (Word) w.next; w != null; w = (Word) w.next) {
t.next = new Token(w, t, null);
t = (Token) t.next;
}
LinkedVector tokens = new LinkedVector(t);
next = (Token) tokens.get(0);
}
Token result = next;
next = (Token) next.next;
return result;
}
/** Sets this parser back to the beginning of the raw data. */
public void reset() {
parser.reset();
next = null;
}
/** Frees any resources this parser may be holding. */
public void close() { parser.close(); }
}
| bsd-3-clause |
mtCarto/geogig | src/core/src/main/java/org/locationtech/geogig/repository/impl/SpatialOps.java | 5190 | /* Copyright (c) 2012-2016 Boundless and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Distribution License v1.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/org/documents/edl-v10.html
*
* Contributors:
* Gabriel Roldan (Boundless) - initial implementation
*/
package org.locationtech.geogig.repository.impl;
import java.util.List;
import org.eclipse.jdt.annotation.Nullable;
import org.geotools.geometry.jts.JTS;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.geotools.referencing.CRS;
import org.locationtech.geogig.model.Node;
import org.locationtech.geogig.model.RevFeature;
import org.locationtech.geogig.model.RevTree;
import org.opengis.geometry.BoundingBox;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import com.google.common.base.Splitter;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Envelope;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.GeometryFactory;
/**
* Utility methods to deal with various spatial operations
*
*/
public class SpatialOps {
private static final GeometryFactory gfac = new GeometryFactory();
/**
* @param oldObject
* @param newObject
* @return the aggregated bounding box
*/
public static com.vividsolutions.jts.geom.Envelope aggregatedBounds(Node oldObject,
Node newObject) {
Envelope env = new Envelope();
if (oldObject != null) {
oldObject.expand(env);
}
if (newObject != null) {
newObject.expand(env);
}
return env;
}
/**
* Creates and returns a geometry out of bounds (a point if bounds.getSpan(0) ==
* bounds.getSpan(1) == 0D, a polygon otherwise), setting the bounds
* {@link BoundingBox#getCoordinateReferenceSystem() CRS} as the geometry's
* {@link Geometry#getUserData() user data}.
*
* @param bounds the bounding box to build from
* @return the newly constructed geometry
*/
public static Geometry toGeometry(final BoundingBox bounds) {
if (bounds == null) {
return null;
}
Geometry geom;
if (bounds.getSpan(0) == 0D && bounds.getSpan(1) == 0D) {
geom = gfac.createPoint(new Coordinate(bounds.getMinX(), bounds.getMinY()));
} else {
geom = JTS.toGeometry(bounds, gfac);
}
geom.setUserData(bounds.getCoordinateReferenceSystem());
return geom;
}
public static Envelope boundsOf(RevTree tree) {
Envelope env = new Envelope();
tree.buckets().values().forEach((b) -> b.expand(env));
tree.trees().forEach((t) -> t.expand(env));
tree.features().forEach((f) -> f.expand(env));
return env;
}
@Nullable
public static Envelope boundsOf(RevFeature feat) {
Envelope env = new Envelope();
feat.forEach((o) -> {
if (o instanceof Geometry) {
env.expandToInclude(((Geometry) o).getEnvelopeInternal());
}
});
return env.isNull() ? null : env;
}
/**
* Parses a bounding box in the format {@code <minx,miny,maxx,maxy,SRS>} where SRS is an EPSG
* code like {@code EPSG:4325} etc.
* <p>
* The oridinates must be given in "longitude first" format, and the SRS will be decoded the
* same way.
*
* @throws IllegalArgumentException if the argument doesn't match the expected format, or the
* SRS can't be parsed.
*/
@Nullable
public static ReferencedEnvelope parseBBOX(final @Nullable String bboxArg) {
if (bboxArg == null) {
return null;
}
List<String> split = Splitter.on(',').omitEmptyStrings().splitToList(bboxArg);
if (split.size() != 5) {
throw new IllegalArgumentException(String.format(
"Invalid bbox parameter: '%s'. Expected format: <minx,miny,maxx,maxy,CRS>",
bboxArg));
}
double minx;
double miny;
double maxx;
double maxy;
try {
minx = Double.parseDouble(split.get(0));
miny = Double.parseDouble(split.get(1));
maxx = Double.parseDouble(split.get(2));
maxy = Double.parseDouble(split.get(3));
} catch (NumberFormatException nfe) {
throw new IllegalArgumentException(String.format(
"Invalid bbox parameter: '%s'. Expected format: <minx,miny,maxx,maxy,CRS>",
bboxArg));
}
final String srs = split.get(4);
final CoordinateReferenceSystem crs;
try {
crs = CRS.decode(srs, true);
} catch (FactoryException e) {
throw new IllegalArgumentException(String
.format("Invalid bbox parameter: '%s'. Can't parse CRS '%s'", bboxArg, srs));
}
ReferencedEnvelope env = new ReferencedEnvelope(minx, maxx, miny, maxy, crs);
return env;
}
}
| bsd-3-clause |
vtkio/vtk | src/main/java/vtk/text/html/HtmlDigester.java | 7642 | /* Copyright (c) 2012, University of Oslo, Norway
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of the University of Oslo nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package vtk.text.html;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;
import org.w3c.tidy.Tidy;
import com.googlecode.htmlcompressor.compressor.HtmlCompressor;
import vtk.util.io.NullOutputStream;
/**
* XXX Should also handle inputstreams and doms
*/
public class HtmlDigester {
private static final Pattern TAG_PATTERN = Pattern.compile("<.*?>");
private static final int DEFAULT_TRUNCATE_LIMIT = 1000;
private static final String DEFAULT_TAIL = "...";
/**
* Compress the html
*/
public String compress(String html) {
HtmlCompressor compressor = new HtmlCompressor();
compressor.setRemoveIntertagSpaces(true);
return compressor.compress(html);
}
public String truncateHtml(String html) {
return this.truncateHtml(html, DEFAULT_TRUNCATE_LIMIT);
}
/**
* Truncate supplied html to within the given limit. Append tail to
* truncated result and use JTidy to close removed tags.
*/
public String truncateHtml(String html, int limit) {
if (html == null) {
throw new IllegalArgumentException("Must supply html to truncate");
}
if (limit < 0 || limit < DEFAULT_TAIL.length()) {
throw new IllegalArgumentException("Limit is too small");
}
if (html.length() < limit) {
return html;
}
// Compress before truncating. If within limits, no need to remove
// content and truncate
String compressed = this.compress(html);
if (compressed.length() < limit) {
return compressed;
}
int processedLimit = limit;
int tryCount = 0;
// Worst case, make 3 attempts
while (tryCount <= 3) {
// Be greedy. Assume that half of the tags removed will be added
// back during sanitization (tags are closed and made valid) ->
// leave room for them by further reducing limit
String removed = compressed.substring(processedLimit, compressed.length());
int removedTagsLength = this.getRemoveTagsLength(removed);
int truncationLimit = processedLimit - (removedTagsLength / 2);
// Leave room for the tail
truncationLimit -= DEFAULT_TAIL.length();
// We were too greedy, we ended up removing everything. Go with half
// the original limit and hope
if (truncationLimit < 0) {
truncationLimit = processedLimit / 2;
}
String truncated = compressed.substring(0, truncationLimit);
// If html was truncated in the middle of a tag, remove what remains
// of that tag
if (truncated.lastIndexOf("<") > truncated.lastIndexOf(">")) {
truncated = truncated.substring(0, truncated.lastIndexOf("<"));
}
// Add the tail
truncated = this.addTail(truncated, DEFAULT_TAIL);
String sanitizedTruncated = this.sanitizeTruncated(truncated);
if (sanitizedTruncated.length() <= limit) {
return sanitizedTruncated;
}
// Try again with a ~5% shorter limit
processedLimit -= (limit / 20);
}
return null;
}
private int getRemoveTagsLength(String removed) {
Matcher m = TAG_PATTERN.matcher(removed);
int removedTagsLength = 0;
while (m.find()) {
removedTagsLength += m.group().length();
}
return removedTagsLength;
}
private String addTail(String truncated, String tail) {
if (truncated.endsWith(">")) {
List<String> endTags = new ArrayList<String>();
while (truncated.endsWith(">")) {
String endTag = truncated.substring(truncated.lastIndexOf("<"), truncated.length());
endTags.add(endTag);
truncated = truncated.substring(0, truncated.lastIndexOf("<"));
}
truncated = truncated.trim();
if (!truncated.equals("")) {
truncated = truncated.concat(tail);
Collections.reverse(endTags);
truncated = truncated.concat(StringUtils.join(endTags, ""));
} else {
truncated = truncated.concat(StringUtils.join(endTags, ""));
truncated = truncated.concat(tail);
}
return truncated;
}
return truncated.trim().concat(tail);
}
private String sanitizeTruncated(String truncated) {
// XXX Setup/configuration? Add tags without attributes... e.g. <li
// style...>? Print body only?
Tidy tidy = new Tidy();
tidy.setPrintBodyOnly(true);
tidy.setQuiet(true);
tidy.setOnlyErrors(false);
tidy.setShowWarnings(false);
tidy.setErrout(new PrintWriter(NullOutputStream.INSTANCE));
tidy.setMakeClean(true);
tidy.setDropFontTags(true);
tidy.setDropProprietaryAttributes(true);
tidy.setInputEncoding("utf-8");
tidy.setOutputEncoding("utf-8");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ByteArrayInputStream bais = new ByteArrayInputStream(truncated.getBytes());
tidy.parseDOM(new BufferedInputStream(bais), baos);
String sanitized = null;
try {
sanitized = new String(baos.toByteArray(), "utf-8");
} catch (UnsupportedEncodingException e) {
// XXX log?
sanitized = new String(baos.toByteArray());
}
// Compress result
sanitized = this.compress(sanitized);
return sanitized;
}
}
| bsd-3-clause |
wizjany/Plume | src/main/java/com/skcraft/plume/module/perf/profiler/SpecificProfiler.java | 5412 | package com.skcraft.plume.module.perf.profiler;
import au.com.bytecode.opencsv.CSVWriter;
import com.google.common.collect.Lists;
import com.google.common.io.CharSource;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.inject.Inject;
import com.sk89q.intake.Command;
import com.sk89q.intake.Require;
import com.sk89q.intake.parametric.annotation.Optional;
import com.skcraft.plume.command.At;
import com.skcraft.plume.command.Group;
import com.skcraft.plume.command.Sender;
import com.skcraft.plume.common.event.ReportGenerationEvent;
import com.skcraft.plume.common.util.concurrent.Deferreds;
import com.skcraft.plume.common.util.config.Config;
import com.skcraft.plume.common.util.config.InjectConfig;
import com.skcraft.plume.common.util.event.EventBus;
import com.skcraft.plume.common.util.module.Module;
import com.skcraft.plume.util.Broadcaster;
import com.skcraft.plume.util.Messages;
import com.skcraft.plume.util.concurrent.TickExecutorService;
import com.skcraft.plume.util.profiling.AlreadyProfilingException;
import com.skcraft.plume.util.profiling.NotProfilingException;
import com.skcraft.plume.util.profiling.ProfilerExecutor;
import lombok.extern.java.Log;
import net.minecraft.command.ICommandSender;
import ninja.leaping.configurate.objectmapping.Setting;
import java.io.IOException;
import java.io.StringWriter;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static com.skcraft.plume.common.util.SharedLocale.tr;
@Module(name = "specific-profiler", desc = "Provides a tick profiler")
@Log
public class SpecificProfiler {
public static final String PERMISSION = "plume.specificprofiler";
@Inject private EventBus eventBus;
@Inject private Broadcaster broadcaster;
@Inject private ProfilerExecutor<TickProfiler> profilerExecutor;
@Inject private TickExecutorService tickExecutor;
@InjectConfig("specific_profiler") private Config<SpecificProfilerConfig> config;
@Command(aliases = "start", desc = "Start profiling")
@Group({@At("sprofiler")})
@Require(PERMISSION)
public void start(@Sender ICommandSender sender, @Optional Integer delay) {
try {
delay = config.get().clampDelay(delay);
ListenableFuture<TickProfiler> future = profilerExecutor.submit(new TickProfiler(), delay, TimeUnit.SECONDS);
broadcaster.broadcast(Messages.info(tr("specificProfiler.started", delay, sender.getCommandSenderName())), PERMISSION);
Deferreds.makeDeferred(future)
.tap(() -> {
broadcaster.broadcast(Messages.info(tr("specificProfiler.completed")), PERMISSION);
}, tickExecutor)
.filter(profiler -> {
ReportGenerationEvent event = new ReportGenerationEvent("specificprofiler", "csv", CharSource.wrap(generateReport(profiler)));
eventBus.post(event);
return event.getMessages();
})
.done(messages -> {
for (String message : messages) {
broadcaster.broadcast(Messages.info(message), PERMISSION);
}
});
} catch (AlreadyProfilingException e) {
sender.addChatMessage(Messages.error(tr("specificProfiler.alreadyProfiling")));
}
}
@Command(aliases = "stop", desc = "Stop profiling")
@Group({@At("sprofiler")})
@Require(PERMISSION)
public void stop(@Sender ICommandSender sender) {
try {
profilerExecutor.stop();
} catch (NotProfilingException e) {
sender.addChatMessage(Messages.error(tr("specificProfile.noOngoing")));
}
}
private String generateReport(TickProfiler profiler) throws IOException {
StringWriter writer = new StringWriter();
CollectAppendersEvent event = new CollectAppendersEvent(profiler.getTimings());
eventBus.post(event);
List<Appender> appenders = Lists.newArrayList(new TimingAppender());
appenders.addAll(event.getAppenders());
try (CSVWriter csv = new CSVWriter(writer)) {
List<String> columns = Lists.newArrayList();
for (Appender appender : appenders) {
columns.addAll(appender.getColumns());
}
csv.writeNext(columns.toArray(new String[columns.size()]));
for (Timing timing : profiler.getTimings()) {
List<String> values = Lists.newArrayList();
for (Appender appender : appenders) {
values.addAll(appender.getValues(timing));
}
csv.writeNext(values.toArray(new String[values.size()]));
}
}
return writer.toString();
}
private static class SpecificProfilerConfig {
@Setting(comment = "The number of seconds to profile for by default (if not specified)")
private int defaultProfileDuration = 30;
@Setting(comment = "The maximum number of seconds to profile for")
private int maxProfileDuration = 60 * 5;
public int clampDelay(Integer delay) {
if (delay == null) {
delay = defaultProfileDuration;
}
delay = Math.min(maxProfileDuration, Math.max(5, delay));
return delay;
}
}
}
| bsd-3-clause |
lutece-platform/lutece-core | src/test/java/fr/paris/lutece/portal/service/user/menu/TestAdminUserMenuItemProvider.java | 2944 | /*
* Copyright (c) 2002-2022, City of Paris
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright notice
* and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice
* and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* 3. Neither the name of 'Mairie de Paris' nor 'Lutece' nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* License 1.0
*/
package fr.paris.lutece.portal.service.user.menu;
import javax.servlet.http.HttpServletRequest;
import fr.paris.lutece.portal.business.user.menu.AdminUserMenuItem;
import fr.paris.lutece.portal.business.user.menu.IAdminUserMenuItemProvider;
public class TestAdminUserMenuItemProvider implements IAdminUserMenuItemProvider
{
protected static final AdminUserMenuItem ITEM = new AdminUserMenuItem( "junit", "junit" );
protected static final String INVOKED_NAME = "INVOKED_NAME";
private final AdminUserMenuItem _item;
private String _strName;
protected TestAdminUserMenuItemProvider( String strClass )
{
_item = new AdminUserMenuItem( "junit", strClass );
}
protected TestAdminUserMenuItemProvider( )
{
_item = ITEM;
}
@Override
public boolean isInvoked( HttpServletRequest request )
{
final Object invokedAttr = request.getAttribute( INVOKED_NAME );
if ( invokedAttr != null )
{
return invokedAttr.equals( getName( ) );
}
return true;
}
@Override
public AdminUserMenuItem getItem( HttpServletRequest request )
{
return _item;
}
@Override
public String getName( )
{
return _strName;
}
@Override
public void setName( String strName )
{
_strName = strName;
}
}
| bsd-3-clause |
fabricebouye/gw2-sab | gw2-sab-tests/src/com/bouye/gw2/sab/scene/characters/TestCharacterTrainingPane.java | 3818 | /*
* Copyright (C) 2016-2017 Fabrice Bouyé
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the BSD license. See the LICENSE file for details.
*/
package com.bouye.gw2.sab.scene.characters;
import api.web.gw2.mapping.core.JsonpContext;
import api.web.gw2.mapping.v2.professions.Profession;
import com.bouye.gw2.sab.SABConstants;
import com.bouye.gw2.sab.query.WebQuery;
import com.bouye.gw2.sab.scene.characters.professions.SimpleProfessionListCell;
import java.io.IOException;
import java.net.URL;
import java.util.Collection;
import java.util.Collections;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.control.ToolBar;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
/**
* Test.
* @author Fabrice Bouyé
*/
public final class TestCharacterTrainingPane extends Application {
@Override
public void start(Stage primaryStage) {
final CharacterTrainingPane trainingPane = new CharacterTrainingPane();
final ComboBox<Profession> professionCombo = new ComboBox<>();
professionCombo.setButtonCell(new SimpleProfessionListCell());
professionCombo.setCellFactory(listView -> new SimpleProfessionListCell());
professionCombo.valueProperty().addListener((observable, oldValue, newValue) -> trainingPane.setProfession(newValue));
final ToolBar toolBar = new ToolBar();
toolBar.getItems().add(professionCombo);
final BorderPane root = new BorderPane();
root.setTop(toolBar);
root.setCenter(trainingPane);
final Scene scene = new Scene(root, 700, 600);
primaryStage.setTitle("TestCharacterTrainingPane"); // NOI18N.
primaryStage.setScene(scene);
primaryStage.show();
// ScenicView.show(scene);
loadTestAsync(professionCombo);
}
private void loadTestAsync(final ComboBox<Profession> professionCombo) {
Service<Collection<Profession>> service = new Service<Collection<Profession>>() {
@Override
protected Task<Collection<Profession>> createTask() {
return new Task<Collection<Profession>>() {
@Override
protected Collection<Profession> call() throws Exception {
final Collection<Profession> professions = SABConstants.INSTANCE.isOffline() ? loadLocalTest() : loadRemoteTest();
return professions;
}
};
}
};
service.setOnSucceeded(workerStateEvent -> {
final Collection<Profession> profession = (Collection<Profession>) workerStateEvent.getSource().getValue();
professionCombo.getItems().setAll(profession);
});
service.setOnFailed(workerStateEvent -> {
final Throwable ex = workerStateEvent.getSource().getException();
Logger.getGlobal().log(Level.SEVERE, ex.getMessage(), ex);
});
service.start();
}
private Collection<Profession> loadRemoteTest() {
return WebQuery.INSTANCE.queryProfessions();
}
private Collection<Profession> loadLocalTest() throws IOException {
final URL url = getClass().getResource("professions/professions.json");
Collection<Profession> result = Collections.EMPTY_LIST;
if (url != null) {
result = JsonpContext.SAX.loadObjectArray(Profession.class, url);
}
return result;
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
| bsd-3-clause |
treejames/StarAppSquare | src/com/nd/android/u/square/ui/view/VoiceLayout.java | 8791 | package com.nd.android.u.square.ui.view;
import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.product.android.business.ApplicationVariable;
import com.common.utils.StarAppUtils;
import com.nd.android.u.filestoragesystem.externalInterface.FileUtilFactory;
import com.nd.android.u.square.R;
import com.nd.android.u.square.dataStructure.MultimediaInfo;
import com.nd.android.u.square.dataStructure.PostEntity;
import com.nd.android.u.square.dataStructure.VoiceEventBusBean;
import com.nd.android.u.square.interf.IMultimediaInfo;
import com.nd.android.u.square.interf.IMultimediaInfo.MultiTypy;
import com.nd.android.u.square.service.MusicUtils;
import com.nd.android.u.square.service.VoicePlayerService;
import com.nd.android.u.square.service.VoicePlayerService.STATE;
import de.greenrobot.event.EventBus;
/**
* 声音播放控件
*
* <br>
* Created 2014-9-3 下午9:06:28
*
* @version
* @author chenpeng
*
* @see
*/
public class VoiceLayout extends RelativeLayout {
private Context mContext;
private ImageView ivVoice;
private TextView tvVoice;
private IMultimediaInfo mItem;
private boolean isPlaying;
// 背景图片id
private int tvStopColorID = R.color.gray_voice_text;
private int tvPlayingColorID = R.color.white;
private int tvStopBgResID = R.drawable.forum_post_voice_white;
private int tvPlayingBgResID = R.drawable.forum_post_voice_pink;
private int ivStopBgResID = R.drawable.post_voice_stop;
private int ivPlayingBgResID = R.drawable.post_voice_playing;
public void setTvStopBgResID(int tvStopBgResID) {
this.tvStopBgResID = tvStopBgResID;
}
public void setTvPlayingBgResID(int tvPlayingBgResID) {
this.tvPlayingBgResID = tvPlayingBgResID;
}
public void setIvStopBgResID(int ivStopBgResID) {
this.ivStopBgResID = ivStopBgResID;
}
public void setIvPlayingBgResID(int ivPlayingBgResID) {
this.ivPlayingBgResID = ivPlayingBgResID;
}
// public VoiceLayout(Context context) {
// super(context);
// init(context);
// }
public VoiceLayout(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
public VoiceLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context, attrs);
}
private void init(Context context, AttributeSet attrs) {
mContext = context;
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.VoiceLayout);
boolean forHotTopic = ta.getBoolean(R.styleable.VoiceLayout_forHotTopic, false);
ta.recycle();
if(forHotTopic){
LayoutInflater.from(mContext).inflate(R.layout.hot_topic_voice_layout, this, true);
tvStopColorID = R.color.square_hot_topic_voice_stop_text;
tvPlayingColorID = R.color.white;
tvStopBgResID = R.drawable.translu;
tvPlayingBgResID = R.drawable.translu;
ivStopBgResID = R.drawable.jay_voice_normal;
ivPlayingBgResID = R.drawable.jay_voice_playing;
}else{
LayoutInflater.from(mContext).inflate(R.layout.common_voice_layout, this, true);
}
ivVoice = (ImageView) findViewById(R.id.iv_post_voice);
tvVoice = (TextView) findViewById(R.id.tv_post_voice);
setOnClickListener(listener);
EventBus.getDefault().register(this);
initTypeface();
}
/**
* 设置字体
*
* <br>Created 2014-11-30 下午5:42:08
* @author : HuangYK
*/
private void initTypeface() {
// TODO Auto-generated method stub
StarAppUtils.setViewTypeFace(tvVoice, false);
}
public void onDestory() {
if (isPlaying) {
isPlaying = false;
MusicUtils.stopVoice();
}
EventBus.getDefault().unregister(this);
}
private MultimediaInfo changeData(PostEntity item) {
if (item.audio == null) {
return null;
} else {
return new MultimediaInfo(MultiTypy.audio, item.tid, item.audio.fid, item.audio.path,
item.audio.time);
}
}
public void setData(PostEntity item) {
setData(changeData(item));
}
public void setData(IMultimediaInfo item) {
mItem = item;
if (item == null) {
setVisibility(View.GONE);
} else {
if(TextUtils.isEmpty(item.getExtra())){
tvVoice.setVisibility(View.GONE);
}else{
tvVoice.setVisibility(View.VISIBLE);
tvVoice.setText(item.getExtra());
}
setVisibility(View.VISIBLE);
if (VoicePlayerService.voice_state == STATE.PLAYING
&& item.getFid() == VoicePlayerService.mCurPlayAudioId
&& item.getId() == VoicePlayerService.mCurPostID) {
// if (fid == voiceFid) {
playingState();
} else {
stopState();
}
}
}
public void onEventMainThread(VoiceEventBusBean bean) {
if (bean == null)
return;
// // try fix BUG #53241 【Android】【广场】有网络情况下,多次快速从广场进入论坛再返回,系统崩溃退出
// if (VoiceEventBusBean.BeanConst.EVENT_DESTROY.equals(bean.getStrAction())) {
// if (mContext.hashCode() == bean.getIntKey()) {
// onDestory();
// return;
// }
// }
if (mItem == null || !VoicePlayerService.VOICE_SERVICE.equals(bean.getStrAction()))
return;
if (bean.hasValue(VoicePlayerService.MUSIC_CHANGE)) {
// 更换音频时,voiceFid =
VoicePlayerService.mCurPlayAudioId = (Long) bean
.getValue(VoicePlayerService.MUSIC_CHANGE);
if (mItem.getFid() == VoicePlayerService.mCurPlayAudioId
&& mItem.getId() == VoicePlayerService.mCurPostID) {
playingState();
} else {
stopState();
}
} else if (bean.hasValue(VoicePlayerService.MUSIC_COMPLETE)) {
stopState();
} else if (bean.hasValue(VoicePlayerService.PLAYER_ACTION)) {
int value = (Integer) bean.getValue(VoicePlayerService.PLAYER_ACTION);
if (value == VoicePlayerService.ACTION_STOP || value == VoicePlayerService.ACTION_PAUSE) {
// voiceFid = -1;
stopState();
}
}
}
private OnClickListener listener = new OnClickListener() {
@Override
public void onClick(View v) {
if (mItem == null)
return;
Log.e(VIEW_LOG_TAG, "voice_state:" + VoicePlayerService.voice_state
+ " mCurPlayAudioId:" + VoicePlayerService.mCurPlayAudioId + " mCurPostID:"
+ VoicePlayerService.mCurPostID + "" + mItem.getId() + "" + mItem.getFid());
if (VoicePlayerService.voice_state == STATE.PLAYING
&& mItem.getFid() == VoicePlayerService.mCurPlayAudioId
&& mItem.getId() == VoicePlayerService.mCurPostID) {
MusicUtils.pause(mContext);
stopState();
} else {
if (mItem != null && !TextUtils.isEmpty(mItem.getPath())) {
MusicUtils.playVoice(mContext, mItem.getPath(), mItem.getFid(),
mItem.getId(), "voice");
} else {
MusicUtils.playVoice(
mContext,
FileUtilFactory.getInstance().getDownUrlByFid(mItem.getFid(),
null, 0), mItem.getFid(),
mItem.getId(), "voice");
}
playingState();
}
}
};
private void stopState() {
isPlaying = false;
tvVoice.setTextColor(getResources().getColor(tvStopColorID));
tvVoice.setBackgroundResource(tvStopBgResID);
ivVoice.setImageResource(ivStopBgResID);
}
private void playingState() {
isPlaying = true;
tvVoice.setTextColor(getResources().getColor(tvPlayingColorID));
tvVoice.setBackgroundResource(tvPlayingBgResID);
ivVoice.setImageResource(ivPlayingBgResID);
}
}
| bsd-3-clause |
lutece-platform/lutece-core | src/test/java/fr/paris/lutece/util/sql/TransactionTest.java | 3500 | /*
* Copyright (c) 2002-2022, City of Paris
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright notice
* and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice
* and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* 3. Neither the name of 'Mairie de Paris' nor 'Lutece' nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* License 1.0
*/
package fr.paris.lutece.util.sql;
import fr.paris.lutece.test.LuteceTestCase;
import java.sql.SQLException;
/**
* Transaction Test
*/
public class TransactionTest extends LuteceTestCase
{
private static final String SQL_DROP_TABLE = "DROP TABLE IF EXISTS test_transaction";
private static final String SQL_CREATE_TABLE = "CREATE TABLE test_transaction ( id integer )";
private static final String SQL_INSERT = "INSERT INTO test_transaction VALUES ( ? )";
public void testCommit( )
{
System.out.println( "commit" );
Transaction transaction = new Transaction( );
try
{
transaction.prepareStatement( SQL_DROP_TABLE );
transaction.executeStatement( );
transaction.prepareStatement( SQL_CREATE_TABLE );
transaction.executeStatement( );
for ( int i = 0; i < 3; i++ )
{
transaction.prepareStatement( SQL_INSERT );
transaction.getStatement( ).setInt( 1, i );
transaction.executeStatement( );
}
transaction.commit( );
}
catch( SQLException ex )
{
transaction.rollback( ex );
}
assertTrue( transaction.getStatus( ) == Transaction.COMMITTED );
}
public void testRollback( )
{
System.out.println( "rollback" );
Transaction transaction = new Transaction( );
try
{
for ( int i = 3; i < 6; i++ )
{
transaction.prepareStatement( SQL_INSERT );
transaction.getStatement( ).setInt( 1, i );
transaction.executeStatement( );
}
transaction.rollback( );
}
catch( SQLException ex )
{
transaction.rollback( ex );
}
assertTrue( transaction.getStatus( ) == Transaction.ROLLEDBACK );
}
}
| bsd-3-clause |
lamerman/ros_android_bag | app/src/main/java/org/lamerman/rosandroidbag/RecordLauncher.java | 7364 | package org.lamerman.rosandroidbag;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.ArrayUtils;
import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.MessageFormat;
import java.util.Arrays;
public class RecordLauncher {
public interface RecordStateListener {
void onRecordExit();
}
private volatile boolean mIsRecordProcessLaunched = false;
private volatile boolean mIsStopRequested = false;
private Thread mRunProcessThread;
private RecordStateListener mListener;
private StringBuffer mApplicationLogs = new StringBuffer();
private final Context mContext;
RecordLauncher(Context context, RecordStateListener listener) {
if (listener == null) throw new NullPointerException("Listener must not be null");
this.mContext = context;
this.mListener = listener;
}
synchronized public void startRecord(final Intent intent) {
if (mIsRecordProcessLaunched) {
throw new IllegalStateException("Record already launched");
} else {
mIsRecordProcessLaunched = true;
mRunProcessThread = new Thread() {
@Override
public void run() {
runRecordProcess(mContext, intent);
}
};
mRunProcessThread.start();
}
}
synchronized public void stopRecord() {
if (!mIsRecordProcessLaunched) {
throw new IllegalStateException("Record has not been launched yet");
} else {
mIsStopRequested = true;
mRunProcessThread.interrupt();
while (mIsRecordProcessLaunched) {
try {
Thread.sleep(50);
} catch (InterruptedException ex) {
// normal workflow
}
}
}
}
public String getLogs() {
return mApplicationLogs.toString();
}
private void runRecordProcess(Context context, Intent intent) {
InputStream recordResource = context.getResources().openRawResource(R.raw.record);
try {
File recordFile = copyRecordExecutableToFs(context, recordResource);
String myExec = recordFile.toString();
String command = MessageFormat.format("{0} {1}", myExec, intent.getStringExtra(Common.KEY_ARGUMENTS));
File pwd = context.getExternalCacheDir();
String logMessage = "The bags will be available at this path (selectable text): " + pwd;
Log.i(Common.LOG_TAG, logMessage);
mApplicationLogs.append(logMessage).append("\n\n");
String[] defaultEnv = new String[] {
"ROS_MASTER_URI=" + intent.getStringExtra(Common.KEY_MASTER_URL),
"HOME=" + pwd.toString()
};
String[] env = (String[]) ArrayUtils.addAll(defaultEnv,
extractEnvironmentVariables(intent.getStringExtra(Common.KEY_ENVIRONMENT_VARIABLES)));
logMessage = MessageFormat.format("Running the command\n{0}\nwith the following environment " +
"variables set\n{1}", command, Arrays.toString(env));
mApplicationLogs.append(logMessage).append("\n\n");
Log.i(Common.LOG_TAG, logMessage);
Process process = Runtime.getRuntime().exec(command, env, pwd);
DataInputStream stderr = new DataInputStream(process.getErrorStream());
DataInputStream stdout = new DataInputStream(process.getInputStream());
Integer returnCode = null;
while (mIsStopRequested == false && returnCode == null) {
try {
returnCode = process.exitValue();
logStream(stdout, "stdout");
logStream(stderr, "stderr");
break;
} catch (IllegalThreadStateException ex) {
// this exception will be thrown if the process is running, so it's not an error
}
logStream(stdout, "stdout");
logStream(stderr, "stderr");
try {
Thread.sleep(200);
} catch (InterruptedException ex) {
// normal workflow
}
}
if (returnCode == null) {
int pid = Common.getPid(process);
boolean killed = Common.killWithSigint(pid);
if (killed) {
try {
returnCode = process.waitFor();
} catch (InterruptedException e) {
process.destroy();
// normal workflow
}
} else {
Log.w(Common.LOG_TAG, "Could not shut down the record process gracefully, killing forcibly");
process.destroy();
}
}
SharedPreferences sharedPref = context.getSharedPreferences(Common.STORAGE_KEY, Context.MODE_PRIVATE);
sharedPref.edit().putString(Common.LOGS_STORAGE_KEY, getLogs()).commit();
mListener.onRecordExit();
stderr.close();
stdout.close(); // TODO: close streams even on exception
Log.w(Common.LOG_TAG, "Return code: " + String.valueOf(returnCode));
} catch (IOException e) {
Log.e(Common.LOG_TAG, "Could not run executable", e);
}
mIsRecordProcessLaunched = false;
mIsStopRequested = false;
}
private File copyRecordExecutableToFs(Context context, InputStream recordResource) throws IOException {
byte[] recordBytes = IOUtils.toByteArray(recordResource);
File recordFile = new File(context.getCacheDir(), "ros_android_bag_record");
if (recordFile.exists()) recordFile.delete();
FileUtils.writeByteArrayToFile(recordFile, recordBytes);
boolean result = recordFile.setExecutable(true);
if (result == false) {
String errorText = "Could not set executable flag to " + recordFile.toString();
Log.e(Common.LOG_TAG, errorText);
throw new IllegalStateException(errorText);
}
return recordFile;
}
private void logStream(DataInputStream stream, String streamName) throws IOException {
if (stream.available() > 0) {
String logLine = streamName + ": " + new String(IOUtils.readFully(stream, stream.available()), "UTF-8");
mApplicationLogs.append(logLine).append("\n\n");
Log.w(Common.LOG_TAG, logLine);
}
}
static String[] extractEnvironmentVariables(String environmentVariablesStr) {
String environmentVariablesStrEscaped = environmentVariablesStr.replace("\\,", Common.ESCAPED_COMMA_REPLACEMENT);
String[] keyValuePairs = environmentVariablesStrEscaped.split(",");
for (int i = 0; i < keyValuePairs.length; i++) {
keyValuePairs[i] = keyValuePairs[i].replace(Common.ESCAPED_COMMA_REPLACEMENT, ",");
}
return keyValuePairs;
}
}
| bsd-3-clause |
NCIP/cananolab | software/cananolab-webapp/src/gov/nih/nci/cananolab/restful/core/InitSetup.java | 12555 | /*L
* Copyright SAIC
* Copyright SAIC-Frederick
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/cananolab/LICENSE.txt for details.
*/
package gov.nih.nci.cananolab.restful.core;
import gov.nih.nci.cananolab.dto.common.PublicDataCountBean;
import gov.nih.nci.cananolab.exception.BaseException;
import gov.nih.nci.cananolab.restful.bean.LabelValueBean;
import gov.nih.nci.cananolab.service.PublicDataCountJob;
import gov.nih.nci.cananolab.service.common.LookupService;
import gov.nih.nci.cananolab.util.ClassUtils;
import gov.nih.nci.cananolab.util.StringUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
/**
* This class sets up information required for all forms.
*
* @author pansu, cais
*
*/
public class InitSetup {
private InitSetup() {
}
public static InitSetup getInstance() {
return new InitSetup();
}
/**
* Queries and common_lookup table and creates a map in application context
*
* @param appContext
* @return
* @throws BaseException
*/
public Map<String, Map<String, SortedSet<String>>> getDefaultLookupTable(ServletContext appContext) throws BaseException {
Map<String, Map<String, SortedSet<String>>> defaultLookupTable = null;
if (appContext.getAttribute("defaultLookupTable") == null) {
defaultLookupTable = LookupService.findAllLookups();
appContext.setAttribute("defaultLookupTable", defaultLookupTable);
} else {
defaultLookupTable = new HashMap<String, Map<String, SortedSet<String>>>(
(Map<? extends String, Map<String, SortedSet<String>>>) appContext.getAttribute("defaultLookupTable"));
}
return defaultLookupTable;
}
/**
* Retrieve lookup Map from lookup table and store in the application
* context
*
* @param appContext
* @param contextAttribute
* @param name
* @return
* @throws BaseException
*/
public Map<String, String> getLookupByName(ServletContext appContext,
String contextAttribute, String name) throws BaseException {
Map<String, Map<String, SortedSet<String>>> defaultLookupTable = getDefaultLookupTable(appContext);
Map<String, SortedSet<String>> lookupByNameMap = defaultLookupTable.get(name);
Map<String, String> lookupMap = new HashMap<String, String>();
Set<String> keySet = lookupByNameMap.keySet();
for (String key : keySet) {
lookupMap.put(key, (String) lookupByNameMap.get(key).first());
}
appContext.setAttribute(contextAttribute, lookupMap);
return lookupMap;
}
/**
* Retrieve default lookup values from lookup table in the database and
* store in the application context
*
* @param appContext
* @param contextAttribute
* @param lookupName
* @param lookupAttribute
* @return
* @throws BaseException
*/
public SortedSet<String> getDefaultTypesByLookup(ServletContext appContext,
String contextAttribute, String lookupName, String lookupAttribute)
throws BaseException {
Map<String, Map<String, SortedSet<String>>> defaultLookupTable = getDefaultLookupTable(appContext);
SortedSet<String> types = new TreeSet<String>();
if (defaultLookupTable.get(lookupName) != null) {
types = defaultLookupTable.get(lookupName).get(lookupAttribute);
appContext.setAttribute(contextAttribute, types);
return types;
} else {
return types;
}
}
/**
* Retrieve default lookup and other values from lookup table in the
* database and store in the session
*
* @param request
* @param sessionAttribute
* @param lookupName
* @param lookupAttribute
* @param otherTypeAttribute
* @aparam updateSession
* @return
* @throws BaseException
*/
public SortedSet<String> getDefaultAndOtherTypesByLookup(HttpServletRequest request, String sessionAttribute,
String lookupName, String lookupAttribute,
String otherTypeAttribute, boolean updateSession)
throws BaseException {
SortedSet<String> types = null;
if (updateSession) {
types = LookupService.getDefaultAndOtherLookupTypes(lookupName,
lookupAttribute, otherTypeAttribute);
request.getSession().setAttribute(sessionAttribute, types);
} else {
types = new TreeSet<String>((SortedSet<? extends String>) (request
.getSession().getAttribute(sessionAttribute)));
}
return types;
}
/**
* Retrieve other values from lookup table in the database and store in the
* session
*
* @param request
* @param sessionAttribute
* @param lookupName
* @param lookupAttribute
* @param otherTypeAttribute
* @aparam updateSession
* @return
* @throws BaseException
*/
public SortedSet<String> getOtherTypesByLookup(HttpServletRequest request,
String sessionAttribute, String lookupName,
String otherTypeAttribute, boolean updateSession)
throws BaseException
{
SortedSet<String> types = null;
if (updateSession) {
types = LookupService.findLookupValues(lookupName, otherTypeAttribute);
request.getSession().setAttribute(sessionAttribute, types);
} else {
types = new TreeSet<String>((SortedSet<? extends String>) (request
.getSession().getAttribute(sessionAttribute)));
}
return types;
}
/**
* Retrieve default lookup values by reflection and store in the app context
*
* @param appContext
* @param contextAttribute
* @param lookupName
* @param fullParentClassName
* @return
* @throws Exception
*/
public SortedSet<String> getDefaultTypesByReflection(
ServletContext appContext, String contextAttribute,
String fullParentClassName) throws Exception
{
SortedSet<String> types = new TreeSet<String>();
List<String> classNames = ClassUtils.getChildClassNames(fullParentClassName);
for (String name : classNames) {
if (!name.contains("Other")) {
String shortClassName = ClassUtils.getShortClassName(name);
String displayName = ClassUtils.getDisplayName(shortClassName);
types.add(displayName);
}
}
appContext.setAttribute(contextAttribute, types);
return types;
}
/**
* Retrieve default lookup and other values by reflection and store in the
* session
*
* @param request
* @param contextAttributeForDefaults
* @param sessionAttribute
* @param fullParentClassName
* @param otherFullParentClassName
* @param updateSession
* @return
* @throws Exception
*/
public SortedSet<String> getDefaultAndOtherTypesByReflection(
HttpServletRequest request, String contextAttributeForDefaults,
String sessionAttribute, String fullParentClassName,
String otherFullParentClassName, boolean updateSession)
throws Exception
{
ServletContext appContext = request.getSession().getServletContext();
SortedSet<String> defaultTypes = getDefaultTypesByReflection(
appContext, contextAttributeForDefaults, fullParentClassName);
SortedSet<String> types = null;
if (updateSession) {
types = new TreeSet<String>(defaultTypes);
if (contextAttributeForDefaults.equals("defaultFunctionalizingEntityTypes")) {
Iterator<String> ite = types.iterator();
while (ite.hasNext())
System.out.println("DefaultType: " + ite.next());
}
SortedSet<String> otherTypes = LookupService.getAllOtherObjectTypes(otherFullParentClassName);
if (otherTypes != null && contextAttributeForDefaults.equals("defaultFunctionalizingEntityTypes")) {
Iterator<String> ite = otherTypes.iterator();
while (ite.hasNext())
System.out.println("otherTypes: " + ite.next());
}
if (otherTypes != null)
types.addAll(otherTypes);
if (contextAttributeForDefaults.equals("defaultFunctionalizingEntityTypes")) {
Iterator<String> ite = types.iterator();
while (ite.hasNext())
System.out.println("Combined types: " + ite.next());
}
request.getSession().setAttribute(sessionAttribute, types);
} else {
types = new TreeSet<String>((SortedSet<? extends String>) (request
.getSession().getAttribute(sessionAttribute)));
}
return types;
}
// check whether the value is already stored in context
private Boolean isLookupInContext(HttpServletRequest request,
String lookupName, String attribute, String otherAttribute,
String value) throws BaseException {
Map<String, Map<String, SortedSet<String>>> defaultLookupTable = getDefaultLookupTable(request
.getSession().getServletContext());
SortedSet<String> defaultValues = null;
if (defaultLookupTable.get(lookupName) != null) {
defaultValues = defaultLookupTable.get(lookupName).get(attribute);
}
if (defaultValues != null && defaultValues.contains(value)) {
return true;
} else {
SortedSet<String> otherValues = null;
if (defaultLookupTable.get(lookupName) != null) {
otherValues = defaultLookupTable.get(lookupName).get(otherAttribute);
}
if (otherValues != null && otherValues.contains(value)) {
return true;
}
}
return false;
}
public void persistLookup(HttpServletRequest request, String lookupName,
String attribute, String otherAttribute, String value)
throws BaseException {
if (value == null || value.length() == 0) {
return;
}
// if value contains special characters, do not save
if (!StringUtils.xssValidate(value)) {
return;
}
if (isLookupInContext(request, lookupName, attribute, otherAttribute,
value)) {
return;
} else {
LookupService.saveOtherType(lookupName, otherAttribute, value);
}
}
public List<LabelValueBean> getDefaultAndOtherTypesByLookupAsOptions(
String lookupName, String lookupAttribute, String otherTypeAttribute)
throws Exception {
List<LabelValueBean> lvBeans = new ArrayList<LabelValueBean>();
SortedSet<String> defaultValues = LookupService.findLookupValues(lookupName, lookupAttribute);
// annotate the label of the default ones with *s.
for (String name : defaultValues) {
LabelValueBean lv = new LabelValueBean(name, name);
lvBeans.add(lv);
}
SortedSet<String> otherValues = LookupService.findLookupValues(lookupName, otherTypeAttribute);
for (String name : otherValues) {
LabelValueBean lv = new LabelValueBean("[" + name + "]", name);
lvBeans.add(lv);
}
return lvBeans;
}
//public List<LabelValueBean> getDefaultAndOtherTypesByReflectionAsOptions(
public List<LabelValueBean> getDefaultAndOtherTypesByReflectionAsOptions(
ServletContext appContext, String contextAttributeForDefaults,
String fullParentClassName, String otherFullParentClassName)
throws Exception {
List<LabelValueBean> lvBeans = new ArrayList<LabelValueBean>();
SortedSet<String> defaultTypes = getDefaultTypesByReflection(
appContext, contextAttributeForDefaults, fullParentClassName);
for (String type : defaultTypes) {
LabelValueBean lv = new LabelValueBean(type, type);
lvBeans.add(lv);
}
SortedSet<String> otherTypes = LookupService.getAllOtherObjectTypes(otherFullParentClassName);
if (otherTypes != null) {
for (String type : otherTypes) {
LabelValueBean lv = new LabelValueBean("[" + type + "]", type);
lvBeans.add(lv);
}
}
return lvBeans;
}
public void setStaticOptions(ServletContext appContext) {
LabelValueBean[] booleanOptions = new LabelValueBean[] {
new LabelValueBean("true", "1"),
new LabelValueBean("false", "0") };
appContext.setAttribute("booleanOptions", booleanOptions);
LabelValueBean[] booleanOperands = new LabelValueBean[] { new LabelValueBean("equals", "is") };
appContext.setAttribute("booleanOperands", booleanOperands);
List<LabelValueBean> numberOperands = new ArrayList<LabelValueBean>();
numberOperands.add(new LabelValueBean("=", "="));
numberOperands.add( new LabelValueBean(">", ">"));
numberOperands.add(new LabelValueBean(">=", ">="));
numberOperands.add(new LabelValueBean("<=", "<="));
appContext.setAttribute("numberOperands", numberOperands);
// register page
LabelValueBean[] titleOperands = new LabelValueBean[] {
new LabelValueBean(" ", " "), new LabelValueBean("Dr.", "Dr."),
new LabelValueBean("Mr.", "Mr."),
new LabelValueBean("Mrs.", "Mrs."),
new LabelValueBean("Miss", "Miss"),
new LabelValueBean("Ms.", "Ms.") };
appContext.setAttribute("titleOperands", titleOperands);
}
public void setPublicCountInContext(ServletContext appContext) {
PublicDataCountJob job=new PublicDataCountJob();
//job.queryPublicDataCounts();
PublicDataCountBean dataCounts=job.getPublicDataCounts();
appContext.setAttribute("publicCounts", dataCounts);
}
}
| bsd-3-clause |
knopflerfish/knopflerfish.org | osgi/bundles/xml/kxml/src/org/kxml2/kdom/Element.java | 8860 | /* Copyright (c) 2002,2003, Stefan Haustein, Oberhausen, Rhld., Germany
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE. */
package org.kxml2.kdom;
import java.io.*;
import java.util.*;
import org.xmlpull.v1.*;
/**
* In order to create an element, please use the createElement method
* instead of invoking the constructor directly. The right place to
* add user defined initialization code is the init method. */
public class Element extends Node {
protected String namespace;
protected String name;
protected Vector<String[]> attributes;
protected Node parent;
protected Vector<String[]> prefixes;
public Element() {
}
/**
* called when all properties are set, but before children
* are parsed. Please do not use setParent for initialization
* code any longer. */
public void init() {
}
/**
* removes all children and attributes */
public void clear() {
attributes = null;
children = null;
}
/**
* Forwards creation request to parent if any, otherwise
* calls super.createElement. */
public Element createElement(
String namespace,
String name) {
return (this.parent == null)
? super.createElement(namespace, name)
: this.parent.createElement(namespace, name);
}
/**
* Returns the number of attributes of this element. */
public int getAttributeCount() {
return attributes == null ? 0 : attributes.size ();
}
public String getAttributeNamespace (int index) {
return attributes.elementAt (index) [0];
}
/* public String getAttributePrefix (int index) {
return ((String []) attributes.elementAt (index)) [1];
}*/
public String getAttributeName (int index) {
return attributes.elementAt (index) [1];
}
public String getAttributeValue (int index) {
return attributes.elementAt (index) [2];
}
public String getAttributeValue (String namespace, String name) {
for (int i = 0; i < getAttributeCount (); i++) {
if (name.equals (getAttributeName (i))
&& (namespace == null || namespace.equals (getAttributeNamespace(i)))) {
return getAttributeValue (i);
}
}
return null;
}
/**
* Returns the root node, determined by ascending to the
* all parents un of the root element. */
public Node getRoot() {
Element current = this;
while (current.parent != null) {
if (!(current.parent instanceof Element)) return current.parent;
current = (Element) current.parent;
}
return current;
}
/**
* returns the (local) name of the element */
public String getName() {
return name;
}
/**
* returns the namespace of the element */
public String getNamespace() {
return namespace;
}
/**
* returns the namespace for the given prefix */
public String getNamespaceUri (String prefix) {
int cnt = getNamespaceCount ();
for (int i = 0; i < cnt; i++) {
if (prefix == getNamespacePrefix (i) ||
(prefix != null && prefix.equals (getNamespacePrefix (i))))
return getNamespaceUri (i);
}
return parent instanceof Element ? ((Element) parent).getNamespaceUri (prefix) : null;
}
/**
* returns the number of declared namespaces, NOT including
* parent elements */
public int getNamespaceCount () {
return (prefixes == null ? 0 : prefixes.size ());
}
public String getNamespacePrefix (int i) {
return prefixes.elementAt (i) [0];
}
public String getNamespaceUri (int i) {
return prefixes.elementAt (i) [1];
}
/**
* Returns the parent node of this element */
public Node getParent() {
return parent;
}
/*
* Returns the parent element if available, null otherwise
public Element getParentElement() {
return (parent instanceof Element)
? ((Element) parent)
: null;
}
*/
/**
* Builds the child elements from the given Parser. By overwriting
* parse, an element can take complete control over parsing its
* subtree. */
public void parse(XmlPullParser parser)
throws IOException, XmlPullParserException {
for (int i = parser.getNamespaceCount (parser.getDepth () - 1);
i < parser.getNamespaceCount (parser.getDepth ()); i++) {
setPrefix (parser.getNamespacePrefix (i), parser.getNamespaceUri(i));
}
for (int i = 0; i < parser.getAttributeCount (); i++)
setAttribute (parser.getAttributeNamespace (i),
// parser.getAttributePrefix (i),
parser.getAttributeName (i),
parser.getAttributeValue (i));
// if (prefixMap == null) throw new RuntimeException ("!!");
init();
if (parser.isEmptyElementTag())
parser.nextToken ();
else {
parser.nextToken ();
super.parse(parser);
if (getChildCount() == 0)
addChild(IGNORABLE_WHITESPACE, "");
}
parser.require(
XmlPullParser.END_TAG,
getNamespace(),
getName());
parser.nextToken ();
}
/**
* Sets the given attribute; a value of null removes the attribute */
public void setAttribute (String namespace, String name, String value) {
if (attributes == null)
attributes = new Vector<String[]> ();
if (namespace == null)
namespace = "";
for (int i = attributes.size()-1; i >=0; i--){
String[] attribut = attributes.elementAt(i);
if (attribut[0].equals(namespace) &&
attribut[1].equals(name)){
if (value == null) {
attributes.removeElementAt(i);
}
else {
attribut[2] = value;
}
return;
}
}
attributes.addElement
(new String [] {namespace, name, value});
}
/**
* Sets the given prefix; a namespace value of null removess the
* prefix */
public void setPrefix (String prefix, String namespace) {
if (prefixes == null) prefixes = new Vector<String[]> ();
prefixes.addElement (new String [] {prefix, namespace});
}
/**
* sets the name of the element */
public void setName(String name) {
this.name = name;
}
/**
* sets the namespace of the element. Please note: For no
* namespace, please use Xml.NO_NAMESPACE, null is not a legal
* value. Currently, null is converted to Xml.NO_NAMESPACE, but
* future versions may throw an exception. */
public void setNamespace(String namespace) {
if (namespace == null)
throw new NullPointerException ("Use \"\" for empty namespace");
this.namespace = namespace;
}
/**
* Sets the Parent of this element. Automatically called from the
* add method. Please use with care, you can simply
* create inconsitencies in the document tree structure using
* this method! */
protected void setParent(Node parent) {
this.parent = parent;
}
/**
* Writes this element and all children to the given XmlWriter. */
public void write(XmlSerializer writer)
throws IOException {
if (prefixes != null) {
for (int i = 0; i < prefixes.size (); i++) {
writer.setPrefix (getNamespacePrefix (i), getNamespaceUri (i));
}
}
writer.startTag(
getNamespace(),
getName());
int len = getAttributeCount();
for (int i = 0; i < len; i++) {
writer.attribute(
getAttributeNamespace(i),
getAttributeName(i),
getAttributeValue(i));
}
writeChildren(writer);
writer.endTag(getNamespace (), getName ());
}
}
| bsd-3-clause |
Pluto-tv/chromium-crosswalk | chrome/android/java/src/org/chromium/chrome/browser/ntp/NewTabPage.java | 24086 | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.ntp;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View;
import org.chromium.base.ApiCompatibilityUtils;
import org.chromium.base.VisibleForTesting;
import org.chromium.base.metrics.RecordHistogram;
import org.chromium.base.metrics.RecordUserAction;
import org.chromium.chrome.R;
import org.chromium.chrome.browser.NativePage;
import org.chromium.chrome.browser.UrlConstants;
import org.chromium.chrome.browser.compositor.layouts.content.InvalidationAwareThumbnailProvider;
import org.chromium.chrome.browser.document.DocumentMetricIds;
import org.chromium.chrome.browser.enhancedbookmarks.EnhancedBookmarkUtils;
import org.chromium.chrome.browser.favicon.FaviconHelper;
import org.chromium.chrome.browser.favicon.FaviconHelper.FaviconAvailabilityCallback;
import org.chromium.chrome.browser.favicon.FaviconHelper.FaviconImageCallback;
import org.chromium.chrome.browser.favicon.LargeIconBridge;
import org.chromium.chrome.browser.favicon.LargeIconBridge.LargeIconCallback;
import org.chromium.chrome.browser.ntp.BookmarksPage.BookmarkSelectedListener;
import org.chromium.chrome.browser.ntp.LogoBridge.Logo;
import org.chromium.chrome.browser.ntp.LogoBridge.LogoObserver;
import org.chromium.chrome.browser.ntp.NewTabPageView.NewTabPageManager;
import org.chromium.chrome.browser.preferences.DocumentModeManager;
import org.chromium.chrome.browser.preferences.DocumentModePreference;
import org.chromium.chrome.browser.preferences.PrefServiceBridge;
import org.chromium.chrome.browser.preferences.PreferencesLauncher;
import org.chromium.chrome.browser.profiles.MostVisitedSites;
import org.chromium.chrome.browser.profiles.MostVisitedSites.MostVisitedURLsObserver;
import org.chromium.chrome.browser.profiles.MostVisitedSites.ThumbnailCallback;
import org.chromium.chrome.browser.profiles.Profile;
import org.chromium.chrome.browser.search_engines.TemplateUrlService;
import org.chromium.chrome.browser.search_engines.TemplateUrlService.TemplateUrlServiceObserver;
import org.chromium.chrome.browser.tab.Tab;
import org.chromium.chrome.browser.tabmodel.TabModel.TabLaunchType;
import org.chromium.chrome.browser.tabmodel.TabModelSelector;
import org.chromium.chrome.browser.util.FeatureUtilities;
import org.chromium.content_public.browser.LoadUrlParams;
import org.chromium.ui.base.DeviceFormFactor;
import org.chromium.ui.base.PageTransition;
import java.util.concurrent.TimeUnit;
/**
* Provides functionality when the user interacts with the NTP.
*/
public class NewTabPage
implements NativePage, InvalidationAwareThumbnailProvider, TemplateUrlServiceObserver {
// The number of times that an opt-out promo will be shown.
private static final int MAX_OPT_OUT_PROMO_COUNT = 10;
// MostVisitedItem Context menu item IDs.
static final int ID_OPEN_IN_NEW_TAB = 0;
static final int ID_OPEN_IN_INCOGNITO_TAB = 1;
static final int ID_REMOVE = 2;
private static MostVisitedSites sMostVisitedSitesForTests;
private final Tab mTab;
private final TabModelSelector mTabModelSelector;
private final Activity mActivity;
private final Profile mProfile;
private final String mTitle;
private final int mBackgroundColor;
private final NewTabPageView mNewTabPageView;
private MostVisitedSites mMostVisitedSites;
private FaviconHelper mFaviconHelper;
private LargeIconBridge mLargeIconBridge;
private LogoBridge mLogoBridge;
private boolean mSearchProviderHasLogo;
private final boolean mOptOutPromoShown;
private String mOnLogoClickUrl;
private FakeboxDelegate mFakeboxDelegate;
// The timestamp at which the constructor was called.
private final long mConstructedTimeNs;
private boolean mIsLoaded;
// Whether destroy() has been called.
private boolean mIsDestroyed;
/**
* Allows clients to listen for updates to the scroll changes of the search box on the
* NTP.
*/
public interface OnSearchBoxScrollListener {
/**
* Callback to be notified when the scroll position of the search box on the NTP has
* changed. A scroll percentage of 0, means the search box has no scroll applied and
* is in it's natural resting position. A value of 1 means the search box is scrolled
* entirely to the top of the screen viewport.
*
* @param scrollPercentage The percentage the search box has been scrolled off the page.
*/
void onScrollChanged(float scrollPercentage);
}
/**
* Handles user interaction with the fakebox (the URL bar in the NTP).
*/
public interface FakeboxDelegate {
/**
* Shows the voice recognition dialog. Called when the user taps the microphone icon.
*/
void startVoiceRecognition();
/**
* @return Whether voice search is currently enabled.
*/
boolean isVoiceSearchEnabled();
/**
* Focuses the URL bar when the user taps the fakebox, types in the fakebox, or pastes text
* into the fakebox.
*
* @param pastedText The text that was pasted or typed into the fakebox, or null if the user
* just tapped the fakebox.
*/
void requestUrlFocusFromFakebox(String pastedText);
}
/**
* @param url The URL to check whether it is for the NTP.
* @return Whether the passed in URL is used to render the NTP.
*/
public static boolean isNTPUrl(String url) {
return url != null && url.startsWith(UrlConstants.NTP_URL);
}
public static void launchBookmarksDialog(Activity activity, Tab tab,
TabModelSelector tabModelSelector) {
if (!EnhancedBookmarkUtils.showEnhancedBookmarkIfEnabled(activity)) {
BookmarkDialogSelectedListener listener = new BookmarkDialogSelectedListener(tab);
NativePage page = BookmarksPage.buildPageInDocumentMode(
activity, tab, tabModelSelector, Profile.getLastUsedProfile(),
listener);
page.updateForUrl(UrlConstants.BOOKMARKS_URL);
Dialog dialog = new NativePageDialog(activity, page);
listener.setDialog(dialog);
dialog.show();
}
}
public static void launchRecentTabsDialog(Activity activity, Tab tab) {
DocumentRecentTabsManager manager = new DocumentRecentTabsManager(tab, activity);
NativePage page = new RecentTabsPage(activity, manager);
page.updateForUrl(UrlConstants.RECENT_TABS_URL);
Dialog dialog = new NativePageDialog(activity, page);
manager.setDialog(dialog);
dialog.show();
}
@VisibleForTesting
static void setMostVisitedSitesForTests(MostVisitedSites mostVisitedSitesForTests) {
sMostVisitedSitesForTests = mostVisitedSitesForTests;
}
private final NewTabPageManager mNewTabPageManager = new NewTabPageManager() {
@Override
public boolean isLocationBarShownInNTP() {
if (mIsDestroyed) return false;
Context context = mNewTabPageView.getContext();
return isInSingleUrlBarMode(context)
&& !mNewTabPageView.urlFocusAnimationsDisabled();
}
@Override
public boolean isVoiceSearchEnabled() {
return mFakeboxDelegate != null && mFakeboxDelegate.isVoiceSearchEnabled();
}
private void recordOpenedMostVisitedItem(MostVisitedItem item) {
if (mIsDestroyed) return;
NewTabPageUma.recordAction(NewTabPageUma.ACTION_OPENED_MOST_VISITED_ENTRY);
NewTabPageUma.recordExplicitUserNavigation(
item.getUrl(), NewTabPageUma.RAPPOR_ACTION_VISITED_SUGGESTED_TILE);
RecordHistogram.recordEnumeratedHistogram("NewTabPage.MostVisited", item.getIndex(),
NewTabPageView.MAX_MOST_VISITED_SITES);
mMostVisitedSites.recordOpenedMostVisitedItem(item.getIndex());
}
private void recordDocumentOptOutPromoClick(int which) {
RecordHistogram.recordEnumeratedHistogram("DocumentActivity.OptOutClick", which,
DocumentMetricIds.OPT_OUT_CLICK_COUNT);
}
@Override
public boolean shouldShowOptOutPromo() {
if (!FeatureUtilities.isDocumentMode(mActivity)) return false;
DocumentModeManager documentModeManager = DocumentModeManager.getInstance(mActivity);
return !documentModeManager.isOptOutPromoDismissed()
&& (documentModeManager.getOptOutShownCount() < MAX_OPT_OUT_PROMO_COUNT);
}
@Override
public void optOutPromoShown() {
assert FeatureUtilities.isDocumentMode(mActivity);
DocumentModeManager.getInstance(mActivity).incrementOptOutShownCount();
RecordUserAction.record("DocumentActivity_OptOutShownOnHome");
}
@Override
public void optOutPromoClicked(boolean settingsClicked) {
assert FeatureUtilities.isDocumentMode(mActivity);
if (settingsClicked) {
recordDocumentOptOutPromoClick(DocumentMetricIds.OPT_OUT_CLICK_SETTINGS);
PreferencesLauncher.launchSettingsPage(mActivity,
DocumentModePreference.class.getName());
} else {
recordDocumentOptOutPromoClick(DocumentMetricIds.OPT_OUT_CLICK_GOT_IT);
DocumentModeManager documentModeManager = DocumentModeManager.getInstance(
mActivity);
documentModeManager.setOptedOutState(DocumentModeManager.OPT_OUT_PROMO_DISMISSED);
}
}
@Override
public void open(MostVisitedItem item) {
if (mIsDestroyed) return;
recordOpenedMostVisitedItem(item);
mTab.loadUrl(new LoadUrlParams(item.getUrl()));
}
@Override
public void onCreateContextMenu(ContextMenu menu, OnMenuItemClickListener listener) {
if (mIsDestroyed) return;
menu.add(Menu.NONE, ID_OPEN_IN_NEW_TAB, Menu.NONE, R.string.contextmenu_open_in_new_tab)
.setOnMenuItemClickListener(listener);
if (PrefServiceBridge.getInstance().isIncognitoModeEnabled()) {
menu.add(Menu.NONE, ID_OPEN_IN_INCOGNITO_TAB, Menu.NONE,
R.string.contextmenu_open_in_incognito_tab).setOnMenuItemClickListener(
listener);
}
menu.add(Menu.NONE, ID_REMOVE, Menu.NONE, R.string.remove)
.setOnMenuItemClickListener(listener);
}
@Override
public boolean onMenuItemClick(int menuId, MostVisitedItem item) {
if (mIsDestroyed) return false;
switch (menuId) {
case ID_OPEN_IN_NEW_TAB:
recordOpenedMostVisitedItem(item);
mTabModelSelector.openNewTab(new LoadUrlParams(item.getUrl()),
TabLaunchType.FROM_LONGPRESS_BACKGROUND, mTab, false);
return true;
case ID_OPEN_IN_INCOGNITO_TAB:
recordOpenedMostVisitedItem(item);
if (FeatureUtilities.isDocumentMode(mActivity)) {
ApiCompatibilityUtils.finishAndRemoveTask(mActivity);
}
mTabModelSelector.openNewTab(new LoadUrlParams(item.getUrl()),
TabLaunchType.FROM_LONGPRESS_FOREGROUND, mTab, true);
return true;
case ID_REMOVE:
mMostVisitedSites.blacklistUrl(item.getUrl());
return true;
default:
return false;
}
}
@Override
public void navigateToBookmarks() {
if (mIsDestroyed) return;
RecordUserAction.record("MobileNTPSwitchToBookmarks");
if (FeatureUtilities.isDocumentMode(mActivity)) {
launchBookmarksDialog(mActivity, mTab, mTabModelSelector);
} else if (!EnhancedBookmarkUtils.showEnhancedBookmarkIfEnabled(mActivity)) {
mTab.loadUrl(new LoadUrlParams(UrlConstants.BOOKMARKS_URL));
}
}
@Override
public void navigateToRecentTabs() {
if (mIsDestroyed) return;
RecordUserAction.record("MobileNTPSwitchToOpenTabs");
if (FeatureUtilities.isDocumentMode(mActivity)) {
launchRecentTabsDialog(mActivity, mTab);
} else {
mTab.loadUrl(new LoadUrlParams(UrlConstants.RECENT_TABS_URL));
}
}
@Override
public void focusSearchBox(boolean beginVoiceSearch, String pastedText) {
if (mIsDestroyed) return;
if (mFakeboxDelegate != null) {
if (beginVoiceSearch) {
mFakeboxDelegate.startVoiceRecognition();
} else {
mFakeboxDelegate.requestUrlFocusFromFakebox(pastedText);
}
}
}
@Override
public void setMostVisitedURLsObserver(MostVisitedURLsObserver observer, int numResults) {
if (mIsDestroyed) return;
mMostVisitedSites.setMostVisitedURLsObserver(observer, numResults);
}
@Override
public void getURLThumbnail(String url, ThumbnailCallback thumbnailCallback) {
if (mIsDestroyed) return;
mMostVisitedSites.getURLThumbnail(url, thumbnailCallback);
}
@Override
public void getLocalFaviconImageForURL(
String url, int size, FaviconImageCallback faviconCallback) {
if (mIsDestroyed) return;
if (mFaviconHelper == null) mFaviconHelper = new FaviconHelper();
mFaviconHelper.getLocalFaviconImageForURL(mProfile, url, FaviconHelper.FAVICON
| FaviconHelper.TOUCH_ICON | FaviconHelper.TOUCH_PRECOMPOSED_ICON, size,
faviconCallback);
}
@Override
public void getLargeIconForUrl(String url, int size, LargeIconCallback callback) {
if (mIsDestroyed) return;
if (mLargeIconBridge == null) mLargeIconBridge = new LargeIconBridge(mProfile);
mLargeIconBridge.getLargeIconForUrl(url, size, callback);
}
@Override
public void ensureFaviconIsAvailable(String pageUrl, String faviconUrl,
FaviconAvailabilityCallback callback) {
if (mIsDestroyed) return;
if (mFaviconHelper == null) mFaviconHelper = new FaviconHelper();
mFaviconHelper.ensureFaviconIsAvailable(mProfile, mTab.getWebContents(), pageUrl,
faviconUrl, callback);
}
@Override
public void openLogoLink() {
if (mIsDestroyed) return;
if (mOnLogoClickUrl == null) return;
mTab.loadUrl(new LoadUrlParams(mOnLogoClickUrl, PageTransition.LINK));
}
@Override
public void getSearchProviderLogo(final LogoObserver logoObserver) {
if (mIsDestroyed) return;
LogoObserver wrapperCallback = new LogoObserver() {
@Override
public void onLogoAvailable(Logo logo, boolean fromCache) {
if (mIsDestroyed) return;
mOnLogoClickUrl = logo != null ? logo.onClickUrl : null;
logoObserver.onLogoAvailable(logo, fromCache);
}
};
mLogoBridge.getCurrentLogo(wrapperCallback);
}
@Override
public void onLoadingComplete() {
long loadTimeMs = (System.nanoTime() - mConstructedTimeNs) / 1000000;
RecordHistogram.recordTimesHistogram(
"Tab.NewTabOnload", loadTimeMs, TimeUnit.MILLISECONDS);
mIsLoaded = true;
if (mIsDestroyed) return;
mMostVisitedSites.onLoadingComplete();
}
};
/**
* Constructs a NewTabPage.
* @param activity The activity used for context to create the new tab page's View.
* @param tab The Tab that is showing this new tab page.
* @param tabModelSelector The TabModelSelector used to open tabs.
*/
public NewTabPage(Activity activity, Tab tab, TabModelSelector tabModelSelector) {
mConstructedTimeNs = System.nanoTime();
mTab = tab;
mActivity = activity;
mTabModelSelector = tabModelSelector;
mProfile = tab.getProfile();
mTitle = activity.getResources().getString(R.string.button_new_tab);
mBackgroundColor = activity.getResources().getColor(R.color.ntp_bg);
TemplateUrlService.getInstance().addObserver(this);
// Whether to show the promo can change within the lifetime of a single NTP instance
// because the user can dismiss the promo. To ensure the UI is consistent, cache the
// value initially and ignore further updates.
mOptOutPromoShown = mNewTabPageManager.shouldShowOptOutPromo();
mMostVisitedSites = buildMostVisitedSites(mProfile);
mLogoBridge = new LogoBridge(mProfile);
updateSearchProviderHasLogo();
LayoutInflater inflater = LayoutInflater.from(activity);
mNewTabPageView = (NewTabPageView) inflater.inflate(R.layout.new_tab_page, null);
mNewTabPageView.initialize(mNewTabPageManager, isInSingleUrlBarMode(activity),
mSearchProviderHasLogo);
}
private static MostVisitedSites buildMostVisitedSites(Profile profile) {
if (sMostVisitedSitesForTests != null) {
return sMostVisitedSitesForTests;
} else {
return new MostVisitedSites(profile);
}
}
/** @return The view container for the new tab page. */
@VisibleForTesting
NewTabPageView getNewTabPageView() {
return mNewTabPageView;
}
/**
* Updates whether the NewTabPage should animate on URL focus changes.
* @param disable Whether to disable the animations.
*/
public void setUrlFocusAnimationsDisabled(boolean disable) {
mNewTabPageView.setUrlFocusAnimationsDisabled(disable);
}
private boolean isInSingleUrlBarMode(Context context) {
if (DeviceFormFactor.isTablet(context)) return false;
if (mOptOutPromoShown) return false;
return mSearchProviderHasLogo;
}
private void updateSearchProviderHasLogo() {
mSearchProviderHasLogo = !mOptOutPromoShown
&& TemplateUrlService.getInstance().isDefaultSearchEngineGoogle();
}
private void onSearchEngineUpdated() {
// TODO(newt): update this if other search providers provide logos.
updateSearchProviderHasLogo();
mNewTabPageView.setSearchProviderHasLogo(mSearchProviderHasLogo);
}
/**
* Specifies the percentage the URL is focused during an animation. 1.0 specifies that the URL
* bar has focus and has completed the focus animation. 0 is when the URL bar is does not have
* any focus.
*
* @param percent The percentage of the URL bar focus animation.
*/
public void setUrlFocusChangeAnimationPercent(float percent) {
mNewTabPageView.setUrlFocusChangeAnimationPercent(percent);
}
/**
* Get the bounds of the search box in relation to the top level NewTabPage view.
*
* @param originalBounds The bounding region of the search box without external transforms
* applied. The delta between this and the transformed bounds determines
* the amount of scroll applied to this view.
* @param transformedBounds The bounding region of the search box including any transforms
* applied by the parent view hierarchy up to the NewTabPage view.
* This more accurately reflects the current drawing location of the
* search box.
*/
public void getSearchBoxBounds(Rect originalBounds, Rect transformedBounds) {
mNewTabPageView.getSearchBoxBounds(originalBounds, transformedBounds);
}
/**
* @return Whether the location bar is shown in the NTP.
*/
public boolean isLocationBarShownInNTP() {
return mNewTabPageManager.isLocationBarShownInNTP();
}
/**
* Sets the listener for search box scroll changes.
* @param listener The listener to be notified on changes.
*/
public void setSearchBoxScrollListener(OnSearchBoxScrollListener listener) {
mNewTabPageView.setSearchBoxScrollListener(listener);
}
/**
* Sets the FakeboxDelegate that this pages interacts with.
*/
public void setFakeboxDelegate(FakeboxDelegate fakeboxDelegate) {
mFakeboxDelegate = fakeboxDelegate;
if (mFakeboxDelegate != null) {
mNewTabPageView.updateVoiceSearchButtonVisibility();
}
}
/**
* @return Whether the NTP has finished loaded.
*/
@VisibleForTesting
public boolean isLoadedForTests() {
return mIsLoaded;
}
// TemplateUrlServiceObserver overrides
@Override
public void onTemplateURLServiceChanged() {
onSearchEngineUpdated();
}
// NativePage overrides
@Override
public void destroy() {
assert !mIsDestroyed;
assert getView().getParent() == null : "Destroy called before removed from window";
if (mFaviconHelper != null) {
mFaviconHelper.destroy();
mFaviconHelper = null;
}
if (mLargeIconBridge != null) {
mLargeIconBridge.destroy();
mLargeIconBridge = null;
}
if (mMostVisitedSites != null) {
mMostVisitedSites.destroy();
mMostVisitedSites = null;
}
if (mLogoBridge != null) {
mLogoBridge.destroy();
mLogoBridge = null;
}
TemplateUrlService.getInstance().removeObserver(this);
mIsDestroyed = true;
}
@Override
public String getUrl() {
return UrlConstants.NTP_URL;
}
@Override
public String getTitle() {
return mTitle;
}
@Override
public int getBackgroundColor() {
return mBackgroundColor;
}
@Override
public View getView() {
return mNewTabPageView;
}
@Override
public String getHost() {
return UrlConstants.NTP_HOST;
}
@Override
public void updateForUrl(String url) {
}
// InvalidationAwareThumbnailProvider
@Override
public boolean shouldCaptureThumbnail() {
return mNewTabPageView.shouldCaptureThumbnail();
}
@Override
public void captureThumbnail(Canvas canvas) {
mNewTabPageView.captureThumbnail(canvas);
}
private static class BookmarkDialogSelectedListener implements BookmarkSelectedListener {
private Dialog mDialog;
private final Tab mTab;
public BookmarkDialogSelectedListener(Tab tab) {
mTab = tab;
}
@Override
public void onNewTabOpened() {
if (mDialog != null) mDialog.dismiss();
}
@Override
public void onBookmarkSelected(String url, String title, Bitmap favicon) {
if (mDialog != null) mDialog.dismiss();
mTab.loadUrl(new LoadUrlParams(url));
}
public void setDialog(Dialog dialog) {
mDialog = dialog;
}
}
}
| bsd-3-clause |
dom4j/visdom | src/java/org/dom4j/visdom/editor/EditorFrame.java | 5949 | /*
* Copyright 2001 (C) MetaStuff, Ltd. All Rights Reserved.
*
* This software is open source.
* See the bottom of this file for the licence.
*
* $Id: EditorFrame.java,v 1.1.1.1 2001/05/22 08:12:41 jstrachan Exp $
*/
package org.dom4j.visdom.editor;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
/**
* Base class for a simple editor
*
*/
public class EditorFrame extends JFrame
{
public EditorFrame(ResourceBundle resources)
{
setTitle(resources.getString("Title"));
editorPanel = createEditorPanel( resources );
// add window closer!
addWindowListener( editorPanel.createApplicationCloser() );
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.add( createToolBar(), BorderLayout.NORTH );
panel.add( editorPanel, BorderLayout.CENTER );
getContentPane().setLayout(new BorderLayout());
getContentPane().add( createMenuBar(), BorderLayout.NORTH );
getContentPane().add( panel, BorderLayout.CENTER );
getContentPane().add( createStatusBar(), BorderLayout.SOUTH );
pack();
}
//-------------------------------------------------------------------------
// Factory methods
//-------------------------------------------------------------------------
/**
* Factory method to create the editor panel to use
*
*/
protected EditorPanel createEditorPanel(ResourceBundle resources)
{
return new EditorPanel(resources);
}
protected JMenuBar createMenuBar()
{
return editorPanel.createMenuBar();
}
protected Component createToolBar()
{
return editorPanel.createToolBar();
}
protected Component createStatusBar()
{
return editorPanel.createStatusBar();
}
//-------------------------------------------------------------------------
// Main
//-------------------------------------------------------------------------
public static void main(String[] args)
{
try
{
// try setting the locale
Locale locale = Locale.getDefault();
if ( args.length > 0 )
{
String country = args[0];
if ( country.equals( "france" ) )
{
System.out.println( "Using French" );
locale = new Locale( Locale.FRENCH.getLanguage(), Locale.FRANCE.getCountry() );
}
else if ( country.equals( "germany" ) )
{
System.out.println( "Using German" );
locale = new Locale( Locale.GERMAN.getLanguage(), Locale.GERMANY.getCountry() );
}
}
ResourceBundle resources;
try
{
resources = ResourceBundle.getBundle( "Editor", locale );
EditorFrame frame = new EditorFrame(resources);
frame.setSize(500, 600);
frame.show();
}
catch (MissingResourceException mre)
{
System.err.println("Editor.properties not found");
System.exit(0);
}
}
catch (Throwable t)
{
System.out.println("uncaught exception: " + t);
t.printStackTrace();
}
}
//-------------------------------------------------------------------------
// Attributes
//-------------------------------------------------------------------------
protected EditorPanel editorPanel;
}
/*
* Redistribution and use of this software and associated documentation
* ("Software"), with or without modification, are permitted provided
* that the following conditions are met:
*
* 1. Redistributions of source code must retain copyright
* statements and notices. Redistributions must also contain a
* copy of this document.
*
* 2. Redistributions in binary form must reproduce the
* above copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. The name "DOM4J" must not be used to endorse or promote
* products derived from this Software without prior written
* permission of MetaStuff, Ltd. For written permission,
* please contact dom4j-info@metastuff.com.
*
* 4. Products derived from this Software may not be called "DOM4J"
* nor may "DOM4J" appear in their names without prior written
* permission of MetaStuff, Ltd. DOM4J is a registered
* trademark of MetaStuff, Ltd.
*
* 5. Due credit should be given to the DOM4J Project
* (http://dom4j.org/).
*
* THIS SOFTWARE IS PROVIDED BY METASTUFF, LTD. AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT
* NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* METASTUFF, LTD. OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Copyright 2001 (C) MetaStuff, Ltd. All Rights Reserved.
*
* $Id: EditorFrame.java,v 1.1.1.1 2001/05/22 08:12:41 jstrachan Exp $
*/
| bsd-3-clause |
lutece-platform/lutece-core | src/java/fr/paris/lutece/portal/service/database/LuteceTransactionManager.java | 4063 | /*
* Copyright (c) 2002-2022, City of Paris
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright notice
* and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice
* and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* 3. Neither the name of 'Mairie de Paris' nor 'Lutece' nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* License 1.0
*/
package fr.paris.lutece.portal.service.database;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionStatus;
import fr.paris.lutece.portal.service.plugin.Plugin;
import fr.paris.lutece.portal.service.plugin.PluginService;
import fr.paris.lutece.util.sql.TransactionManager;
/**
* Lutece transaction manager. This TM use Lutece's specific pool transaction manager with the class {@link TransactionManager}. It allow plugins to use multi
* plugin transactions, and nested transactions. Note that nested transactions does not create savepoints : if a nested transaction is roll backed, then the
* whole transaction is roll backed.
*/
public class LuteceTransactionManager implements PlatformTransactionManager
{
private String _strPluginName;
private Plugin _plugin;
/**
* Gets the plugin name
*
* @return the plugin name
*/
public String getPluginName( )
{
return _strPluginName;
}
/**
* Sets the plugin name
*
* @param strPluginName
* the plugin name
*/
public void setPluginName( String strPluginName )
{
_strPluginName = strPluginName;
}
/**
* {@inheritDoc}
*/
@Override
public TransactionStatus getTransaction( TransactionDefinition definition )
{
TransactionStatus trStatus = new DefaultTransactionStatus( null, true, false, false, false, null );
TransactionManager.beginTransaction( getPlugin( ) );
return trStatus;
}
/**
* {@inheritDoc}
*/
@Override
public void commit( TransactionStatus status )
{
TransactionManager.commitTransaction( getPlugin( ) );
}
/**
* {@inheritDoc}
*/
@Override
public void rollback( TransactionStatus status )
{
TransactionManager.rollBack( getPlugin( ) );
}
private synchronized Plugin getPlugin( )
{
if ( _plugin == null )
{
if ( StringUtils.isNotBlank( _strPluginName ) )
{
_plugin = PluginService.getPlugin( _strPluginName );
}
else
{
_plugin = PluginService.getCore( );
}
}
return _plugin;
}
}
| bsd-3-clause |
AllTheDucks/remotegenerator | example-data/src/main/java/com/alltheducks/remotegenerator/example/mixedannotations/NotAnnotatedOne.java | 100 | package com.alltheducks.remotegenerator.example.mixedannotations;
public class NotAnnotatedOne {
}
| bsd-3-clause |
att/AAF | inno/rosetta/src/test/java/com/data/test/JU_Stream2Obj.java | 2891 | /*******************************************************************************
* Copyright (c) 2016 AT&T Intellectual Property. All rights reserved.
*******************************************************************************/
package com.data.test;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import org.junit.Test;
import com.att.inno.env.APIException;
import com.att.inno.env.Data;
import com.att.inno.env.DataFactory;
import com.att.inno.env.EnvJAXB;
import com.att.inno.env.impl.BasicEnv;
import com.att.rosetta.InJson;
import com.att.rosetta.InXML;
import com.att.rosetta.Out;
import com.att.rosetta.OutJson;
import com.att.rosetta.OutRaw;
import com.att.rosetta.OutXML;
import com.att.rosetta.Parse;
import com.att.rosetta.ParseException;
import inherit.DerivedA;
import inherit.Root;
public class JU_Stream2Obj {
/*
<?xml version="1.0" encoding=Config.UTF-8 standalone="yes"?>
<root xmlns="urn:inherit">
<base xsi:type="derivedA" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<name>myDerivedA_1</name>
<num>1432</num>
<shortName>mda_1</shortName>
<value>value_1</value>
<value>value_2</value>
</base>
</root>
{"base":[{"__extension":"derivedA","name":"myDerivedA_1","num":1432,"shortName":"mda_1","value":["value_1","value_2"]}]}
*/
@Test
public void json2Obj() throws APIException, SecurityException, NoSuchFieldException, ClassNotFoundException, ParseException, IOException {
DerivedA da = new DerivedA();
da.setName("myDerivedA_1");
da.setNum((short)1432);
da.setShortName("mda_1");
da.getValue().add("value_1");
da.getValue().add("value_2");
Root root = new Root();
root.getBase().add(da);
da = new DerivedA();
da.setName("myDerivedA_2");
da.setNum((short)1432);
da.setShortName("mda_2");
da.getValue().add("value_2.1");
da.getValue().add("value_2.2");
root.getBase().add(da);
EnvJAXB env = new BasicEnv();
DataFactory<Root> rootDF = env.newDataFactory(Root.class);
String xml = rootDF.newData(env).out(Data.TYPE.XML).load(root).option(Data.PRETTY).asString();
System.out.println(xml);
InXML inXML;
Parse<Reader,?> in = inXML = new InXML(Root.class);
Out out = new OutRaw();
StringWriter sw = new StringWriter();
out.extract(new StringReader(xml), sw, in);
System.out.println(sw.toString());
out = new OutJson();
sw = new StringWriter();
out.extract(new StringReader(xml), sw, in);
String json;
System.out.println(json = sw.toString());
in = new InJson();
out = new OutRaw();
sw = new StringWriter();
out.extract(new StringReader(json), sw, in);
System.out.println(sw.toString());
out = new OutXML(inXML);
sw = new StringWriter();
out.extract(new StringReader(json), sw, in, true);
System.out.println(sw.toString());
System.out.flush();
}
}
| bsd-3-clause |
datalogistics/dlt-java-client | src/edu/crest/dlt/exnode/function/FunctionXorEncrypt.java | 1467 | /*******************************************************************************
* Copyright (c) : See the COPYRIGHT file in top-level/project directory
*******************************************************************************/
/* $Id: XorEncryptFunction.java,v 1.4 2008/05/24 22:25:52 linuxguy79 Exp $ */
package edu.crest.dlt.exnode.function;
import java.util.logging.Logger;
public class FunctionXorEncrypt extends Function
{
private static final Logger log = Logger.getLogger(FunctionXorEncrypt.class.getName());
private String key = null;
public FunctionXorEncrypt()
{
super("xor_encrypt");
}
public void key(String key)
{
this.key = key;
log.info("key : " + key);
}
public String key()
{ // FIX: key length string must equal 7
// for compatibility w/ LoRS tools.
key = "1234567"; // TODO
return key;
}
/*
* XOR encrypt function
*
* input: rawbuf contains the clear/crypted data output: rawbuf contains the
* crypted/clear data (No memory allocation is done)
*/
public byte[] execute(byte[] rawBuf)
{
if (key == null) { // TODO
log.severe("a key must be set.");
return null;
}
byte[] bk = key.getBytes();
int keylen = bk.length;
int rawlen = rawBuf.length;
for (int b = 0; b < rawlen; b = b + keylen) {
for (int k = 0; k < keylen && ((b + k) < rawlen); k++) {
int p = (b + k) % 2; // alternatively 0 or 1
rawBuf[b + k] ^= (p == 0) ? bk[6] : 0;
}
}
return (rawBuf);
}
}
| bsd-3-clause |
Demannu/hackwars-classic | src/classes/GUI/PortScanTableModel.java | 1528 | package GUI;
/**
PortScanTableModel.java
*/
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;
import Assignments.*;
import View.*;
public class PortScanTableModel extends AbstractTableModel{
private Object[][] rowData;
private String[] columnNames;
public PortScanTableModel(Object[][] rowData,String[] columnNames){
this.rowData=rowData;
this.columnNames=columnNames;
}
public boolean isCellEditable(int row,int column){
if(column==4)
return(true);
return(false);
}
public String getColumnName(int col) {
return columnNames[col];
}
public int getRowCount() { return rowData.length; }
public int getColumnCount() { return columnNames.length; }
public Object getValueAt(int row, int col) {
return rowData[row][col];
}
public void setValueAt(Object value, int row, int col) {
rowData[row][col] = value;
fireTableCellUpdated(row, col);
}
public void addRow(Object[] data){
//System.out.println(rowData.length+" "+columnNames.length);
Object[][] temp = new Object[rowData.length+1][columnNames.length];
//System.out.println(temp.length);
for(int i=0;i<rowData.length;i++){
for(int j=0;j<columnNames.length;j++){
temp[i][j]=rowData[i][j];
}
}
for(int i=0;i<columnNames.length;i++){
temp[rowData.length][i]=data[i];
}
rowData = temp;
fireTableDataChanged();
}
public void resetData(){
rowData = new Object[0][0];
fireTableDataChanged();
}
}
| isc |
coingecko/XChange | xchange-cryptsy/src/main/java/com/xeiam/xchange/cryptsy/dto/trade/CryptsyTradeHistory.java | 2816 | package com.xeiam.xchange.cryptsy.dto.trade;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.xeiam.xchange.cryptsy.CryptsyUtils;
import com.xeiam.xchange.cryptsy.dto.CryptsyOrder.CryptsyOrderType;
/**
* @author ObsessiveOrange
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public class CryptsyTradeHistory {
private final int marketId;
private final int tradeId;
private final CryptsyOrderType type;
private final Date timeStamp;
private final BigDecimal price;
private final BigDecimal quantity;
private final BigDecimal total;
private final BigDecimal fee;
private final CryptsyOrderType init_type;
private final int orderId;
/**
* Constructor
*
* @param timestamp
* @param isYourOrder
* @param orderId
* @param rate
* @param amount
* @param type
* @param pair
* @throws ParseException
*/
public CryptsyTradeHistory(@JsonProperty("marketid") int marketId, @JsonProperty("tradeid") int tradeId, @JsonProperty("tradetype") CryptsyOrderType type,
@JsonProperty("datetime") String timeStamp, @JsonProperty("tradeprice") BigDecimal price, @JsonProperty("quantity") BigDecimal quantity, @JsonProperty("total") BigDecimal total,
@JsonProperty("fee") BigDecimal fee, @JsonProperty("initiate_ordertype") CryptsyOrderType init_type, @JsonProperty("order_id") int orderId) throws ParseException {
this.marketId = marketId;
this.tradeId = tradeId;
this.type = type;
this.timeStamp = timeStamp == null ? null : CryptsyUtils.convertDateTime(timeStamp);
this.price = price;
this.quantity = quantity;
this.total = total;
this.fee = fee;
this.init_type = init_type;
this.orderId = orderId;
}
public int getMarketId() {
return marketId;
}
public int getTradeId() {
return tradeId;
}
public CryptsyOrderType getTradeType() {
return type;
}
public Date getTimestamp() {
return timeStamp;
}
public BigDecimal getPrice() {
return price;
}
public BigDecimal getQuantity() {
return quantity;
}
public BigDecimal getTotal() {
return total;
}
public BigDecimal getFee() {
return fee;
}
public CryptsyOrderType getInitiatingOrderType() {
return init_type;
}
public int getOrderId() {
return orderId;
}
@Override
public String toString() {
return "CryptsyTrade[" + "Market ID='" + marketId + "',Trade ID='" + tradeId + "',Type='" + type + "',Timestamp='" + timeStamp + "',Price='" + price + "',Quantity='" + quantity + "',Total='"
+ total + "',Fee='" + fee + "',InitiatingOrderType='" + init_type + "',Order ID='" + orderId + "']";
}
}
| mit |
AugurSystems/TACACS | src/com/augur/tacacs/Header.java | 4814 | package com.augur.tacacs;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import static com.augur.tacacs.Packet.toInt;
/**
*
* @author Chris.Janicki@augur.com
* Copyright 2016 Augur Systems, Inc. All rights reserved.
*/
public class Header
{
static final int FF = 0xFF;
/** Unique serial number within a session; must reset session if wrap. */
final byte seqNum;
final byte flags;
final TAC_PLUS.PACKET.VERSION version;
final TAC_PLUS.PACKET.TYPE type;
/** Cryptographically random four bytes */
final byte[] sessionID;
/**
* This is only set when decoding an incoming packet;
* not used (set to -1) when a new header is constructed programmatically.
* In the latter case, the body's length will be calculated as needed when
* writePacket() is called.
*/
final int bodyLength;
@Override public String toString()
{
return "[session:"+Packet.toHex(sessionID)+", seqNum:"+seqNum+", type:"+type+", flags:0x"+Integer.toHexString(flags&FF)+"]";
}
private Header(byte seqNum, byte flags, TAC_PLUS.PACKET.VERSION version, TAC_PLUS.PACKET.TYPE type, byte[] sessionID) {
this.seqNum = seqNum;
this.flags = flags;
this.version = version;
this.type = type;
this.sessionID = sessionID;
this.bodyLength = -1;
}
Header(byte flags, TAC_PLUS.PACKET.VERSION version, TAC_PLUS.PACKET.TYPE type, byte[] sessionID) {
this(
(byte)1,
flags,
version,
type,
sessionID
);
}
/** Used internally when receiving packets. */
Header(byte[] bytes)
{
version = TAC_PLUS.PACKET.VERSION.forCode(bytes[0]);
type = TAC_PLUS.PACKET.TYPE.forCode(bytes[1]);
seqNum = bytes[2];
flags = bytes[3];
sessionID = Arrays.copyOfRange(bytes, 4, 8);
bodyLength = toInt(bytes[8],bytes[9],bytes[10],bytes[11]);
}
/**
* Used by both SessionClient and SessionServer to create response packets.
* Implicitly allows SINGLE_CONNECT mode, since it returns the same header flags received last
* (i.e. encrypted and/or SINGLE_CONNECT).
* So if client supports SINGLE_CONNECT (via initial request packet) then the server allows it.
*
* @param version
* @return
* @throws IOException
*/
Header next(TAC_PLUS.PACKET.VERSION version) throws IOException
{
if ((FF&seqNum)>=FF) { throw new IOException("Session's sequence numbers exhausted; try new session."); }
return new Header((byte)((Packet.FF&seqNum)+1), flags, version, type, sessionID);
}
boolean hasFlag(TAC_PLUS.PACKET.FLAG flag)
{
return (flags & flag.code()) != 0;
}
/**
* Toggles the encryption of the given packet body byte[] returning the result.
* The calculation depends on the given key, and these header fields:
* sessionID, version, and seqNum.
* @param body
* @param key
* @param md
* @throws NoSuchAlgorithmException if the MD5 message digest can't be found; shouldn't happen.
* @return A new byte[] containing the ciphered/deciphered body; or just
* the unchanged body itself if TAC_PLUS.PACKET.FLAG.UNENCRYPTED is set.
*/
byte[] toggleCipher(byte[] body, byte[] key) throws NoSuchAlgorithmException
{
if (hasFlag(TAC_PLUS.PACKET.FLAG.UNENCRYPTED)) { return body; }
MessageDigest md = MessageDigest.getInstance("MD5");
int length = body.length;
byte[] pad = new byte[length];
md.update(sessionID); // reset() not necessary since each digest() resets
md.update(key);
md.update(version.code());
md.update(seqNum);
byte[] digest=md.digest(); // first digest applies only header info
System.arraycopy(digest, 0, pad, 0, Math.min(digest.length,length));
length -= digest.length;
int pos = digest.length;
while (length>0)
{
md.update(sessionID);
md.update(key);
md.update(version.code());
md.update(seqNum);
md.update(Arrays.copyOfRange(pad, pos-digest.length, pos)); // apply previous digest too
digest=md.digest();
System.arraycopy(digest, 0, pad, pos, Math.min(digest.length,length));
pos += digest.length;
length -= digest.length;
}
byte[] toggled = new byte[body.length];
for (int i=body.length-1; i>=0; i--)
{
toggled[i] = (byte)((body[i] & 0xff) ^ (pad[i] & 0xff));
}
return toggled;
}
void writePacket(OutputStream out, byte[] body, byte[] key) throws IOException
{
int len = body.length;
ByteArrayOutputStream bout = new ByteArrayOutputStream(12+len);
bout.write(version.code());
bout.write(type.code());
bout.write(seqNum);
bout.write(flags);
bout.write(sessionID);
bout.write(Packet.toBytes4(len));
try { bout.write(toggleCipher(body, key)); } catch (NoSuchAlgorithmException e) { throw new IOException(e.getMessage()); }
out.write(bout.toByteArray());
out.flush();
}
}
| mit |
vistaprint/octopus-jenkins-plugin | src/main/java/hudson/plugins/octopusdeploy/Log.java | 1111 | package hudson.plugins.octopusdeploy;
import hudson.model.BuildListener;
import java.io.PrintStream;
/**
* Logs messages to the Jenkins build console.
* @author cwetherby
*/
public class Log {
private final BuildListener listener;
private final PrintStream logger;
/**
* Generate a log that adds lines to the given BuildListener's console output.
* @param listener The BuildListener responsible for adding lines to the job's console.
*/
public Log(BuildListener listener) {
this.listener = listener;
this.logger = listener.getLogger();
}
/**
* Print an info message.
* @param msg The info message.
*/
public void info(String msg) {
logger.append("INFO: " + msg + "\n");
}
/**
* Print an error message.
* @param msg The error message.
*/
public void error(String msg) {
listener.error(msg);
}
/**
* Print a fatal error message.
* @param msg The fatal error message.
*/
public void fatal(String msg) {
listener.fatalError(msg);
}
}
| mit |
hpe-idol/haven-search-components | idol/src/test/java/com/hp/autonomy/searchcomponents/idol/requests/IdolDatabasesRequestTest.java | 1225 | /*
* (c) Copyright 2015 Micro Focus or one of its affiliates.
*
* Licensed under the MIT License (the "License"); you may not use this file
* except in compliance with the License.
*
* The only warranties for products and services of Micro Focus and its affiliates
* and licensors ("Micro Focus") are as may be set forth in the express warranty
* statements accompanying such products and services. Nothing herein should be
* construed as constituting an additional warranty. Micro Focus shall not be
* liable for technical or editorial errors or omissions contained herein. The
* information contained herein is subject to change without notice.
*/
package com.hp.autonomy.searchcomponents.idol.requests;
import com.hp.autonomy.searchcomponents.core.databases.DatabasesRequest;
import com.hp.autonomy.searchcomponents.core.databases.DatabasesRequestTest;
public class IdolDatabasesRequestTest extends DatabasesRequestTest {
@Override
protected DatabasesRequest constructObject() {
return IdolDatabasesRequestImpl.builder().build();
}
@Override
protected String json() {
return "{}";
}
@Override
protected String toStringContent() {
return "";
}
}
| mit |
GDGAllahabad/EffervescenceMMXIV | src/com/example/effervescencemmxiv/Konqueror.java | 7586 | package com.example.effervescencemmxiv;
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
@SuppressLint("DefaultLocale")
public class Konqueror extends Activity implements OnClickListener, OnCheckedChangeListener {
String[] phone,phone1,phone2,phone3;
TextView tv3, tv4, tv5, tv6, tv7, tv8,tv9,tv10,tv11;
Button b, b1;
CheckBox cb;
ImageView iv1, iv2;
boolean diditwork = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_konqueror);
TextView tv1, tv2;
Typeface tf1 = Typeface.createFromAsset(getAssets(),
"MYRIADPROREGULAR.ttf");
Typeface tf = Typeface.createFromAsset(getAssets(),
"MyriadPro-Light.ttf");
tv2 = (TextView) findViewById(R.id.textView2);
tv1 = (TextView) findViewById(R.id.textView1);
tv1.setTypeface(tf1);
tv2.setTypeface(tf);
// new addition
tv4 = (TextView) findViewById(R.id.textView5);
tv5 = (TextView) findViewById(R.id.textView3);
tv6 = (TextView) findViewById(R.id.textView6);
tv7 = (TextView) findViewById(R.id.textView8);
tv3 = (TextView) findViewById(R.id.textView9);
tv9 = (TextView) findViewById(R.id.textView10);
tv10 = (TextView) findViewById(R.id.textView11);
tv11 = (TextView) findViewById(R.id.textView12);
tv4.setTypeface(tf);
tv3.setTypeface(tf);
tv9.setTypeface(tf);
tv10.setTypeface(tf);
tv11.setTypeface(tf);
tv5.setTypeface(tf1);
tv6.setTypeface(tf1);
tv7.setTypeface(tf1);
String organiser = tv3.getText().toString();
phone = organiser.split(":");
tv3.setOnClickListener(this);
String organiser1 = tv9.getText().toString();
phone1 = organiser1.split(":");
tv9.setOnClickListener(this);
String organiser2 = tv10.getText().toString();
phone2 = organiser2.split(":");
tv10.setOnClickListener(this);
String organiser3 = tv11.getText().toString();
phone3 = organiser3.split(":");
tv11.setOnClickListener(this);
//over
iv1 = (ImageView)findViewById(R.id.imageView3);
iv2 = (ImageView)findViewById(R.id.imageView1);
//ActionBar actionBar = getActionBar();
//actionBar.setDisplayHomeAsUpEnabled(true);
cb = (CheckBox) findViewById(R.id.checkBox1);
iv1.setOnClickListener(this);
iv2.setOnClickListener(this);
cb.setOnClickListener(this);
cb.setChecked(getFromSP("kon"));
cb.setOnCheckedChangeListener(this);
}
private boolean getFromSP(String key){
SharedPreferences preferences = getApplicationContext().getSharedPreferences("effervescencemmxiv", android.content.Context.MODE_PRIVATE);
return preferences.getBoolean(key, false);
}
private void saveInSp(String key,boolean value){
SharedPreferences preferences = getApplicationContext().getSharedPreferences("effervescencemmxiv", android.content.Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean(key, value);
editor.commit();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.konqueror, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item){
Intent myIntent = new Intent(getApplicationContext(), Eventsbyday.class);
startActivityForResult(myIntent, 0);
finish();
return true;
}
@SuppressLint("DefaultLocale")
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.checkBox1:
if(cb.isChecked()){
try{
Favourites entry = new Favourites(Konqueror.this);
entry.openandwrite();
entry.createEntry("Konqueror", "com.example.effervescencemmxiv.KON");
entry.close();
}catch(Exception e){
diditwork = false;
String error = e.toString();
Toast.makeText(getApplicationContext(), error, Toast.LENGTH_SHORT).show();
}finally{
if(diditwork) {
//Toast.makeText(getApplicationContext(), "Success", Toast.LENGTH_SHORT).show();
}
}
break;
}
else {
try{
Favourites entry = new Favourites(Konqueror.this);
entry.openandwrite();
entry.deleteTitleGivenName("Konqueror");
entry.close();
}catch(Exception e){
String error = e.toString();
Toast.makeText(getApplicationContext(), error, Toast.LENGTH_SHORT).show();
}
break;
}
case R.id.imageView1:
String str = "Konqueror";
Intent it = new Intent("com.example.effervescencemmxiv.SN");
it.putExtra("event", str);
it.putExtra("address", "com.example.effervescencemmxiv.KON");
startActivity(it);
break;
case R.id.imageView3:
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Getting Current Location
Location location = locationManager.getLastKnownLocation(provider);
String s = "25.43123,81.77114,17";
if(location!=null){
double lat = location.getLatitude();
double lon = location.getLongitude();
s = "";
s = String.format("%f,%f", lat, lon);
}
Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
Uri.parse("http://maps.google.com/maps?saddr=" + s + "&daddr=25.429050, 81.771413"));
intent.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity");
startActivity(intent);
break;
//new
case R.id.textView9:
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:+91" + phone[1].trim()));
startActivity(callIntent);
break;
case R.id.textView10:
Intent callIntent1 = new Intent(Intent.ACTION_CALL);
callIntent1.setData(Uri.parse("tel:+91" + phone1[1].trim()));
startActivity(callIntent1);
break;
case R.id.textView11:
Intent callIntent2 = new Intent(Intent.ACTION_CALL);
callIntent2.setData(Uri.parse("tel:+91" + phone2[1].trim()));
startActivity(callIntent2);
break;
case R.id.textView12:
Intent callIntent3 = new Intent(Intent.ACTION_CALL);
callIntent3.setData(Uri.parse("tel:+91" + phone3[1].trim()));
startActivity(callIntent3);
break;
//over
}
}
@Override
public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
// TODO Auto-generated method stub
saveInSp("kon",arg1);
}
}
| mit |
1fish2/the-blue-alliance-android | android/src/main/java/com/thebluealliance/androidclient/listitems/AllianceListElement.java | 5602 | package com.thebluealliance.androidclient.listitems;
import com.thebluealliance.androidclient.R;
import com.thebluealliance.androidclient.helpers.EventTeamHelper;
import com.thebluealliance.androidclient.interfaces.RenderableModel;
import com.thebluealliance.androidclient.listeners.EventTeamClickListener;
import com.thebluealliance.androidclient.listeners.PlayoffAdvancementClickListener;
import com.thebluealliance.androidclient.renderers.ModelRendererSupplier;
import com.thebluealliance.androidclient.types.PlayoffAdvancement;
import android.content.Context;
import android.text.SpannableString;
import android.text.style.UnderlineSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import java.util.List;
public class AllianceListElement extends ListElement implements RenderableModel {
public final int number;
public final PlayoffAdvancement advancement;
public final List<String> teams;
public final String eventKey;
public final String allianceName;
public AllianceListElement(String eventKey, String name, int number, List<String> teams,
PlayoffAdvancement advancement) {
if (teams.size() < 2) throw new IllegalArgumentException("Alliances have >= 2 members");
this.number = number;
this.advancement = advancement;
this.teams = teams;
this.eventKey = eventKey;
this.allianceName = name;
}
@Override
public View getView(Context c, LayoutInflater inflater, View convertView) {
ViewHolder holder;
if (convertView == null || !(convertView.getTag() instanceof ViewHolder)) {
convertView = inflater.inflate(R.layout.list_item_alliance, null, false);
holder = new ViewHolder();
holder.allianceName = (TextView) convertView.findViewById(R.id.alliance_name);
holder.advancement = (TextView) convertView.findViewById(R.id.alliance_advancement);
holder.memberOne = (TextView) convertView.findViewById(R.id.member_one);
holder.memberTwo = (TextView) convertView.findViewById(R.id.member_two);
holder.memberThree = (TextView) convertView.findViewById(R.id.member_three);
holder.memberFour = (TextView) convertView.findViewById(R.id.member_four);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.allianceName.setText(allianceName != null
? allianceName
: String.format(c.getString(R.string.alliance_title), number));
if (advancement != PlayoffAdvancement.NONE) {
holder.advancement.setVisibility(View.VISIBLE);
holder.advancement.setText(advancement.getAbbreviation());
holder.advancement.setClickable(true);
holder.advancement.setOnClickListener(new PlayoffAdvancementClickListener(c, advancement));
} else {
holder.advancement.setVisibility(View.VISIBLE);
holder.advancement.setText("");
holder.advancement.setOnClickListener(null);
holder.advancement.setClickable(false);
}
EventTeamClickListener listener = new EventTeamClickListener(c);
String team1Key = teams.get(0);
SpannableString underLine = new SpannableString(team1Key.substring(3));
underLine.setSpan(new UnderlineSpan(), 0, underLine.length(), 0);
holder.memberOne.setText(underLine);
holder.memberOne.setTag(EventTeamHelper.generateKey(eventKey, team1Key));
holder.memberOne.setOnClickListener(listener);
holder.memberOne.setOnLongClickListener(listener);
String team2Key = teams.get(1);
holder.memberTwo.setText(team2Key.substring(3));
holder.memberTwo.setTag(EventTeamHelper.generateKey(eventKey, team2Key));
holder.memberTwo.setOnClickListener(listener);
holder.memberTwo.setOnLongClickListener(listener);
if (teams.size() >= 3) {
String team3Key = teams.get(2);
holder.memberThree.setText(team3Key.substring(3));
holder.memberThree.setTag(EventTeamHelper.generateKey(eventKey, team3Key));
holder.memberThree.setVisibility(View.VISIBLE);
holder.memberThree.setOnClickListener(listener);
holder.memberThree.setOnLongClickListener(listener);
}
if (teams.size() >= 4) {
String team4Key = teams.get(3);
holder.memberFour.setText(team4Key.substring(3));
holder.memberFour.setTag(EventTeamHelper.generateKey(eventKey, team4Key));
holder.memberFour.setVisibility(View.VISIBLE);
holder.memberFour.setOnClickListener(listener);
holder.memberFour.setOnLongClickListener(listener);
}
return convertView;
}
private static class ViewHolder {
TextView allianceName;
TextView advancement;
TextView memberOne;
TextView memberTwo;
TextView memberThree;
TextView memberFour;
}
@Override
public ListElement render(ModelRendererSupplier supplier) {
return this;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof AllianceListElement)) {
return false;
}
AllianceListElement other = (AllianceListElement) o;
return number == other.number
&& teams.equals(other.teams)
&& eventKey.equals(other.eventKey);
}
}
| mit |
navalev/azure-sdk-for-java | sdk/network/mgmt-v2019_06_01/src/main/java/com/microsoft/azure/management/network/v2019_06_01/implementation/PrivateLinkServicesInner.java | 134068 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.network.v2019_06_01.implementation;
import com.microsoft.azure.arm.collection.InnerSupportsGet;
import com.microsoft.azure.arm.collection.InnerSupportsDelete;
import com.microsoft.azure.arm.collection.InnerSupportsListing;
import retrofit2.Retrofit;
import com.google.common.reflect.TypeToken;
import com.microsoft.azure.AzureServiceFuture;
import com.microsoft.azure.CloudException;
import com.microsoft.azure.ListOperationCallback;
import com.microsoft.azure.management.network.v2019_06_01.CheckPrivateLinkServiceVisibilityRequest;
import com.microsoft.azure.management.network.v2019_06_01.ErrorException;
import com.microsoft.azure.Page;
import com.microsoft.azure.PagedList;
import com.microsoft.rest.ServiceCallback;
import com.microsoft.rest.ServiceFuture;
import com.microsoft.rest.ServiceResponse;
import com.microsoft.rest.Validator;
import java.io.IOException;
import java.util.List;
import okhttp3.ResponseBody;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.Header;
import retrofit2.http.Headers;
import retrofit2.http.HTTP;
import retrofit2.http.Path;
import retrofit2.http.POST;
import retrofit2.http.PUT;
import retrofit2.http.Query;
import retrofit2.http.Url;
import retrofit2.Response;
import rx.functions.Func1;
import rx.Observable;
/**
* An instance of this class provides access to all the operations defined
* in PrivateLinkServices.
*/
public class PrivateLinkServicesInner implements InnerSupportsGet<PrivateLinkServiceInner>, InnerSupportsDelete<Void>, InnerSupportsListing<PrivateLinkServiceInner> {
/** The Retrofit service to perform REST calls. */
private PrivateLinkServicesService service;
/** The service client containing this operation class. */
private NetworkManagementClientImpl client;
/**
* Initializes an instance of PrivateLinkServicesInner.
*
* @param retrofit the Retrofit instance built from a Retrofit Builder.
* @param client the instance of the service client containing this operation class.
*/
public PrivateLinkServicesInner(Retrofit retrofit, NetworkManagementClientImpl client) {
this.service = retrofit.create(PrivateLinkServicesService.class);
this.client = client;
}
/**
* The interface defining all the services for PrivateLinkServices to be
* used by Retrofit to perform actually REST calls.
*/
interface PrivateLinkServicesService {
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2019_06_01.PrivateLinkServices delete" })
@HTTP(path = "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/privateLinkServices/{serviceName}", method = "DELETE", hasBody = true)
Observable<Response<ResponseBody>> delete(@Path("resourceGroupName") String resourceGroupName, @Path("serviceName") String serviceName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2019_06_01.PrivateLinkServices beginDelete" })
@HTTP(path = "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/privateLinkServices/{serviceName}", method = "DELETE", hasBody = true)
Observable<Response<ResponseBody>> beginDelete(@Path("resourceGroupName") String resourceGroupName, @Path("serviceName") String serviceName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2019_06_01.PrivateLinkServices getByResourceGroup" })
@GET("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/privateLinkServices/{serviceName}")
Observable<Response<ResponseBody>> getByResourceGroup(@Path("resourceGroupName") String resourceGroupName, @Path("serviceName") String serviceName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Query("$expand") String expand, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2019_06_01.PrivateLinkServices createOrUpdate" })
@PUT("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/privateLinkServices/{serviceName}")
Observable<Response<ResponseBody>> createOrUpdate(@Path("resourceGroupName") String resourceGroupName, @Path("serviceName") String serviceName, @Path("subscriptionId") String subscriptionId, @Body PrivateLinkServiceInner parameters, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2019_06_01.PrivateLinkServices beginCreateOrUpdate" })
@PUT("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/privateLinkServices/{serviceName}")
Observable<Response<ResponseBody>> beginCreateOrUpdate(@Path("resourceGroupName") String resourceGroupName, @Path("serviceName") String serviceName, @Path("subscriptionId") String subscriptionId, @Body PrivateLinkServiceInner parameters, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2019_06_01.PrivateLinkServices listByResourceGroup" })
@GET("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/privateLinkServices")
Observable<Response<ResponseBody>> listByResourceGroup(@Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2019_06_01.PrivateLinkServices list" })
@GET("subscriptions/{subscriptionId}/providers/Microsoft.Network/privateLinkServices")
Observable<Response<ResponseBody>> list(@Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2019_06_01.PrivateLinkServices updatePrivateEndpointConnection" })
@PUT("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/privateLinkServices/{serviceName}/privateEndpointConnections/{peConnectionName}")
Observable<Response<ResponseBody>> updatePrivateEndpointConnection(@Path("resourceGroupName") String resourceGroupName, @Path("serviceName") String serviceName, @Path("peConnectionName") String peConnectionName, @Path("subscriptionId") String subscriptionId, @Body PrivateEndpointConnectionInner parameters, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2019_06_01.PrivateLinkServices deletePrivateEndpointConnection" })
@HTTP(path = "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/privateLinkServices/{serviceName}/privateEndpointConnections/{peConnectionName}", method = "DELETE", hasBody = true)
Observable<Response<ResponseBody>> deletePrivateEndpointConnection(@Path("resourceGroupName") String resourceGroupName, @Path("serviceName") String serviceName, @Path("peConnectionName") String peConnectionName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2019_06_01.PrivateLinkServices beginDeletePrivateEndpointConnection" })
@HTTP(path = "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/privateLinkServices/{serviceName}/privateEndpointConnections/{peConnectionName}", method = "DELETE", hasBody = true)
Observable<Response<ResponseBody>> beginDeletePrivateEndpointConnection(@Path("resourceGroupName") String resourceGroupName, @Path("serviceName") String serviceName, @Path("peConnectionName") String peConnectionName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2019_06_01.PrivateLinkServices checkPrivateLinkServiceVisibility" })
@POST("subscriptions/{subscriptionId}/providers/Microsoft.Network/locations/{location}/checkPrivateLinkServiceVisibility")
Observable<Response<ResponseBody>> checkPrivateLinkServiceVisibility(@Path("location") String location, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body CheckPrivateLinkServiceVisibilityRequest parameters, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2019_06_01.PrivateLinkServices checkPrivateLinkServiceVisibilityByResourceGroup" })
@POST("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/locations/{location}/checkPrivateLinkServiceVisibility")
Observable<Response<ResponseBody>> checkPrivateLinkServiceVisibilityByResourceGroup(@Path("location") String location, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body CheckPrivateLinkServiceVisibilityRequest parameters, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2019_06_01.PrivateLinkServices listAutoApprovedPrivateLinkServices" })
@GET("subscriptions/{subscriptionId}/providers/Microsoft.Network/locations/{location}/autoApprovedPrivateLinkServices")
Observable<Response<ResponseBody>> listAutoApprovedPrivateLinkServices(@Path("location") String location, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2019_06_01.PrivateLinkServices listAutoApprovedPrivateLinkServicesByResourceGroup" })
@GET("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/locations/{location}/autoApprovedPrivateLinkServices")
Observable<Response<ResponseBody>> listAutoApprovedPrivateLinkServicesByResourceGroup(@Path("location") String location, @Path("resourceGroupName") String resourceGroupName, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2019_06_01.PrivateLinkServices listByResourceGroupNext" })
@GET
Observable<Response<ResponseBody>> listByResourceGroupNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2019_06_01.PrivateLinkServices listNext" })
@GET
Observable<Response<ResponseBody>> listNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2019_06_01.PrivateLinkServices listAutoApprovedPrivateLinkServicesNext" })
@GET
Observable<Response<ResponseBody>> listAutoApprovedPrivateLinkServicesNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.network.v2019_06_01.PrivateLinkServices listAutoApprovedPrivateLinkServicesByResourceGroupNext" })
@GET
Observable<Response<ResponseBody>> listAutoApprovedPrivateLinkServicesByResourceGroupNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
}
/**
* Deletes the specified private link service.
*
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the private link service.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws ErrorException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
*/
public void delete(String resourceGroupName, String serviceName) {
deleteWithServiceResponseAsync(resourceGroupName, serviceName).toBlocking().last().body();
}
/**
* Deletes the specified private link service.
*
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the private link service.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<Void> deleteAsync(String resourceGroupName, String serviceName, final ServiceCallback<Void> serviceCallback) {
return ServiceFuture.fromResponse(deleteWithServiceResponseAsync(resourceGroupName, serviceName), serviceCallback);
}
/**
* Deletes the specified private link service.
*
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the private link service.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable for the request
*/
public Observable<Void> deleteAsync(String resourceGroupName, String serviceName) {
return deleteWithServiceResponseAsync(resourceGroupName, serviceName).map(new Func1<ServiceResponse<Void>, Void>() {
@Override
public Void call(ServiceResponse<Void> response) {
return response.body();
}
});
}
/**
* Deletes the specified private link service.
*
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the private link service.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable for the request
*/
public Observable<ServiceResponse<Void>> deleteWithServiceResponseAsync(String resourceGroupName, String serviceName) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (serviceName == null) {
throw new IllegalArgumentException("Parameter serviceName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
final String apiVersion = "2019-06-01";
Observable<Response<ResponseBody>> observable = service.delete(resourceGroupName, serviceName, this.client.subscriptionId(), apiVersion, this.client.acceptLanguage(), this.client.userAgent());
return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken<Void>() { }.getType());
}
/**
* Deletes the specified private link service.
*
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the private link service.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws ErrorException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
*/
public void beginDelete(String resourceGroupName, String serviceName) {
beginDeleteWithServiceResponseAsync(resourceGroupName, serviceName).toBlocking().single().body();
}
/**
* Deletes the specified private link service.
*
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the private link service.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<Void> beginDeleteAsync(String resourceGroupName, String serviceName, final ServiceCallback<Void> serviceCallback) {
return ServiceFuture.fromResponse(beginDeleteWithServiceResponseAsync(resourceGroupName, serviceName), serviceCallback);
}
/**
* Deletes the specified private link service.
*
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the private link service.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceResponse} object if successful.
*/
public Observable<Void> beginDeleteAsync(String resourceGroupName, String serviceName) {
return beginDeleteWithServiceResponseAsync(resourceGroupName, serviceName).map(new Func1<ServiceResponse<Void>, Void>() {
@Override
public Void call(ServiceResponse<Void> response) {
return response.body();
}
});
}
/**
* Deletes the specified private link service.
*
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the private link service.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceResponse} object if successful.
*/
public Observable<ServiceResponse<Void>> beginDeleteWithServiceResponseAsync(String resourceGroupName, String serviceName) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (serviceName == null) {
throw new IllegalArgumentException("Parameter serviceName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
final String apiVersion = "2019-06-01";
return service.beginDelete(resourceGroupName, serviceName, this.client.subscriptionId(), apiVersion, this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Void>>>() {
@Override
public Observable<ServiceResponse<Void>> call(Response<ResponseBody> response) {
try {
ServiceResponse<Void> clientResponse = beginDeleteDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<Void> beginDeleteDelegate(Response<ResponseBody> response) throws ErrorException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<Void, ErrorException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<Void>() { }.getType())
.register(202, new TypeToken<Void>() { }.getType())
.register(204, new TypeToken<Void>() { }.getType())
.registerError(ErrorException.class)
.build(response);
}
/**
* Gets the specified private link service by resource group.
*
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the private link service.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws ErrorException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the PrivateLinkServiceInner object if successful.
*/
public PrivateLinkServiceInner getByResourceGroup(String resourceGroupName, String serviceName) {
return getByResourceGroupWithServiceResponseAsync(resourceGroupName, serviceName).toBlocking().single().body();
}
/**
* Gets the specified private link service by resource group.
*
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the private link service.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<PrivateLinkServiceInner> getByResourceGroupAsync(String resourceGroupName, String serviceName, final ServiceCallback<PrivateLinkServiceInner> serviceCallback) {
return ServiceFuture.fromResponse(getByResourceGroupWithServiceResponseAsync(resourceGroupName, serviceName), serviceCallback);
}
/**
* Gets the specified private link service by resource group.
*
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the private link service.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PrivateLinkServiceInner object
*/
public Observable<PrivateLinkServiceInner> getByResourceGroupAsync(String resourceGroupName, String serviceName) {
return getByResourceGroupWithServiceResponseAsync(resourceGroupName, serviceName).map(new Func1<ServiceResponse<PrivateLinkServiceInner>, PrivateLinkServiceInner>() {
@Override
public PrivateLinkServiceInner call(ServiceResponse<PrivateLinkServiceInner> response) {
return response.body();
}
});
}
/**
* Gets the specified private link service by resource group.
*
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the private link service.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PrivateLinkServiceInner object
*/
public Observable<ServiceResponse<PrivateLinkServiceInner>> getByResourceGroupWithServiceResponseAsync(String resourceGroupName, String serviceName) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (serviceName == null) {
throw new IllegalArgumentException("Parameter serviceName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
final String apiVersion = "2019-06-01";
final String expand = null;
return service.getByResourceGroup(resourceGroupName, serviceName, this.client.subscriptionId(), apiVersion, expand, this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<PrivateLinkServiceInner>>>() {
@Override
public Observable<ServiceResponse<PrivateLinkServiceInner>> call(Response<ResponseBody> response) {
try {
ServiceResponse<PrivateLinkServiceInner> clientResponse = getByResourceGroupDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
/**
* Gets the specified private link service by resource group.
*
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the private link service.
* @param expand Expands referenced resources.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws ErrorException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the PrivateLinkServiceInner object if successful.
*/
public PrivateLinkServiceInner getByResourceGroup(String resourceGroupName, String serviceName, String expand) {
return getByResourceGroupWithServiceResponseAsync(resourceGroupName, serviceName, expand).toBlocking().single().body();
}
/**
* Gets the specified private link service by resource group.
*
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the private link service.
* @param expand Expands referenced resources.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<PrivateLinkServiceInner> getByResourceGroupAsync(String resourceGroupName, String serviceName, String expand, final ServiceCallback<PrivateLinkServiceInner> serviceCallback) {
return ServiceFuture.fromResponse(getByResourceGroupWithServiceResponseAsync(resourceGroupName, serviceName, expand), serviceCallback);
}
/**
* Gets the specified private link service by resource group.
*
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the private link service.
* @param expand Expands referenced resources.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PrivateLinkServiceInner object
*/
public Observable<PrivateLinkServiceInner> getByResourceGroupAsync(String resourceGroupName, String serviceName, String expand) {
return getByResourceGroupWithServiceResponseAsync(resourceGroupName, serviceName, expand).map(new Func1<ServiceResponse<PrivateLinkServiceInner>, PrivateLinkServiceInner>() {
@Override
public PrivateLinkServiceInner call(ServiceResponse<PrivateLinkServiceInner> response) {
return response.body();
}
});
}
/**
* Gets the specified private link service by resource group.
*
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the private link service.
* @param expand Expands referenced resources.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PrivateLinkServiceInner object
*/
public Observable<ServiceResponse<PrivateLinkServiceInner>> getByResourceGroupWithServiceResponseAsync(String resourceGroupName, String serviceName, String expand) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (serviceName == null) {
throw new IllegalArgumentException("Parameter serviceName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
final String apiVersion = "2019-06-01";
return service.getByResourceGroup(resourceGroupName, serviceName, this.client.subscriptionId(), apiVersion, expand, this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<PrivateLinkServiceInner>>>() {
@Override
public Observable<ServiceResponse<PrivateLinkServiceInner>> call(Response<ResponseBody> response) {
try {
ServiceResponse<PrivateLinkServiceInner> clientResponse = getByResourceGroupDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<PrivateLinkServiceInner> getByResourceGroupDelegate(Response<ResponseBody> response) throws ErrorException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<PrivateLinkServiceInner, ErrorException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<PrivateLinkServiceInner>() { }.getType())
.registerError(ErrorException.class)
.build(response);
}
/**
* Creates or updates an private link service in the specified resource group.
*
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the private link service.
* @param parameters Parameters supplied to the create or update private link service operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws ErrorException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the PrivateLinkServiceInner object if successful.
*/
public PrivateLinkServiceInner createOrUpdate(String resourceGroupName, String serviceName, PrivateLinkServiceInner parameters) {
return createOrUpdateWithServiceResponseAsync(resourceGroupName, serviceName, parameters).toBlocking().last().body();
}
/**
* Creates or updates an private link service in the specified resource group.
*
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the private link service.
* @param parameters Parameters supplied to the create or update private link service operation.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<PrivateLinkServiceInner> createOrUpdateAsync(String resourceGroupName, String serviceName, PrivateLinkServiceInner parameters, final ServiceCallback<PrivateLinkServiceInner> serviceCallback) {
return ServiceFuture.fromResponse(createOrUpdateWithServiceResponseAsync(resourceGroupName, serviceName, parameters), serviceCallback);
}
/**
* Creates or updates an private link service in the specified resource group.
*
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the private link service.
* @param parameters Parameters supplied to the create or update private link service operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable for the request
*/
public Observable<PrivateLinkServiceInner> createOrUpdateAsync(String resourceGroupName, String serviceName, PrivateLinkServiceInner parameters) {
return createOrUpdateWithServiceResponseAsync(resourceGroupName, serviceName, parameters).map(new Func1<ServiceResponse<PrivateLinkServiceInner>, PrivateLinkServiceInner>() {
@Override
public PrivateLinkServiceInner call(ServiceResponse<PrivateLinkServiceInner> response) {
return response.body();
}
});
}
/**
* Creates or updates an private link service in the specified resource group.
*
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the private link service.
* @param parameters Parameters supplied to the create or update private link service operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable for the request
*/
public Observable<ServiceResponse<PrivateLinkServiceInner>> createOrUpdateWithServiceResponseAsync(String resourceGroupName, String serviceName, PrivateLinkServiceInner parameters) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (serviceName == null) {
throw new IllegalArgumentException("Parameter serviceName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
if (parameters == null) {
throw new IllegalArgumentException("Parameter parameters is required and cannot be null.");
}
Validator.validate(parameters);
final String apiVersion = "2019-06-01";
Observable<Response<ResponseBody>> observable = service.createOrUpdate(resourceGroupName, serviceName, this.client.subscriptionId(), parameters, apiVersion, this.client.acceptLanguage(), this.client.userAgent());
return client.getAzureClient().getPutOrPatchResultAsync(observable, new TypeToken<PrivateLinkServiceInner>() { }.getType());
}
/**
* Creates or updates an private link service in the specified resource group.
*
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the private link service.
* @param parameters Parameters supplied to the create or update private link service operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws ErrorException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the PrivateLinkServiceInner object if successful.
*/
public PrivateLinkServiceInner beginCreateOrUpdate(String resourceGroupName, String serviceName, PrivateLinkServiceInner parameters) {
return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, serviceName, parameters).toBlocking().single().body();
}
/**
* Creates or updates an private link service in the specified resource group.
*
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the private link service.
* @param parameters Parameters supplied to the create or update private link service operation.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<PrivateLinkServiceInner> beginCreateOrUpdateAsync(String resourceGroupName, String serviceName, PrivateLinkServiceInner parameters, final ServiceCallback<PrivateLinkServiceInner> serviceCallback) {
return ServiceFuture.fromResponse(beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, serviceName, parameters), serviceCallback);
}
/**
* Creates or updates an private link service in the specified resource group.
*
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the private link service.
* @param parameters Parameters supplied to the create or update private link service operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PrivateLinkServiceInner object
*/
public Observable<PrivateLinkServiceInner> beginCreateOrUpdateAsync(String resourceGroupName, String serviceName, PrivateLinkServiceInner parameters) {
return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, serviceName, parameters).map(new Func1<ServiceResponse<PrivateLinkServiceInner>, PrivateLinkServiceInner>() {
@Override
public PrivateLinkServiceInner call(ServiceResponse<PrivateLinkServiceInner> response) {
return response.body();
}
});
}
/**
* Creates or updates an private link service in the specified resource group.
*
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the private link service.
* @param parameters Parameters supplied to the create or update private link service operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PrivateLinkServiceInner object
*/
public Observable<ServiceResponse<PrivateLinkServiceInner>> beginCreateOrUpdateWithServiceResponseAsync(String resourceGroupName, String serviceName, PrivateLinkServiceInner parameters) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (serviceName == null) {
throw new IllegalArgumentException("Parameter serviceName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
if (parameters == null) {
throw new IllegalArgumentException("Parameter parameters is required and cannot be null.");
}
Validator.validate(parameters);
final String apiVersion = "2019-06-01";
return service.beginCreateOrUpdate(resourceGroupName, serviceName, this.client.subscriptionId(), parameters, apiVersion, this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<PrivateLinkServiceInner>>>() {
@Override
public Observable<ServiceResponse<PrivateLinkServiceInner>> call(Response<ResponseBody> response) {
try {
ServiceResponse<PrivateLinkServiceInner> clientResponse = beginCreateOrUpdateDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<PrivateLinkServiceInner> beginCreateOrUpdateDelegate(Response<ResponseBody> response) throws ErrorException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<PrivateLinkServiceInner, ErrorException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<PrivateLinkServiceInner>() { }.getType())
.register(201, new TypeToken<PrivateLinkServiceInner>() { }.getType())
.registerError(ErrorException.class)
.build(response);
}
/**
* Gets all private link services in a resource group.
*
* @param resourceGroupName The name of the resource group.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws ErrorException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the PagedList<PrivateLinkServiceInner> object if successful.
*/
public PagedList<PrivateLinkServiceInner> listByResourceGroup(final String resourceGroupName) {
ServiceResponse<Page<PrivateLinkServiceInner>> response = listByResourceGroupSinglePageAsync(resourceGroupName).toBlocking().single();
return new PagedList<PrivateLinkServiceInner>(response.body()) {
@Override
public Page<PrivateLinkServiceInner> nextPage(String nextPageLink) {
return listByResourceGroupNextSinglePageAsync(nextPageLink).toBlocking().single().body();
}
};
}
/**
* Gets all private link services in a resource group.
*
* @param resourceGroupName The name of the resource group.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<List<PrivateLinkServiceInner>> listByResourceGroupAsync(final String resourceGroupName, final ListOperationCallback<PrivateLinkServiceInner> serviceCallback) {
return AzureServiceFuture.fromPageResponse(
listByResourceGroupSinglePageAsync(resourceGroupName),
new Func1<String, Observable<ServiceResponse<Page<PrivateLinkServiceInner>>>>() {
@Override
public Observable<ServiceResponse<Page<PrivateLinkServiceInner>>> call(String nextPageLink) {
return listByResourceGroupNextSinglePageAsync(nextPageLink);
}
},
serviceCallback);
}
/**
* Gets all private link services in a resource group.
*
* @param resourceGroupName The name of the resource group.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PagedList<PrivateLinkServiceInner> object
*/
public Observable<Page<PrivateLinkServiceInner>> listByResourceGroupAsync(final String resourceGroupName) {
return listByResourceGroupWithServiceResponseAsync(resourceGroupName)
.map(new Func1<ServiceResponse<Page<PrivateLinkServiceInner>>, Page<PrivateLinkServiceInner>>() {
@Override
public Page<PrivateLinkServiceInner> call(ServiceResponse<Page<PrivateLinkServiceInner>> response) {
return response.body();
}
});
}
/**
* Gets all private link services in a resource group.
*
* @param resourceGroupName The name of the resource group.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PagedList<PrivateLinkServiceInner> object
*/
public Observable<ServiceResponse<Page<PrivateLinkServiceInner>>> listByResourceGroupWithServiceResponseAsync(final String resourceGroupName) {
return listByResourceGroupSinglePageAsync(resourceGroupName)
.concatMap(new Func1<ServiceResponse<Page<PrivateLinkServiceInner>>, Observable<ServiceResponse<Page<PrivateLinkServiceInner>>>>() {
@Override
public Observable<ServiceResponse<Page<PrivateLinkServiceInner>>> call(ServiceResponse<Page<PrivateLinkServiceInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(listByResourceGroupNextWithServiceResponseAsync(nextPageLink));
}
});
}
/**
* Gets all private link services in a resource group.
*
ServiceResponse<PageImpl<PrivateLinkServiceInner>> * @param resourceGroupName The name of the resource group.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the PagedList<PrivateLinkServiceInner> object wrapped in {@link ServiceResponse} if successful.
*/
public Observable<ServiceResponse<Page<PrivateLinkServiceInner>>> listByResourceGroupSinglePageAsync(final String resourceGroupName) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
final String apiVersion = "2019-06-01";
return service.listByResourceGroup(resourceGroupName, this.client.subscriptionId(), apiVersion, this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<PrivateLinkServiceInner>>>>() {
@Override
public Observable<ServiceResponse<Page<PrivateLinkServiceInner>>> call(Response<ResponseBody> response) {
try {
ServiceResponse<PageImpl<PrivateLinkServiceInner>> result = listByResourceGroupDelegate(response);
return Observable.just(new ServiceResponse<Page<PrivateLinkServiceInner>>(result.body(), result.response()));
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<PageImpl<PrivateLinkServiceInner>> listByResourceGroupDelegate(Response<ResponseBody> response) throws ErrorException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<PageImpl<PrivateLinkServiceInner>, ErrorException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<PageImpl<PrivateLinkServiceInner>>() { }.getType())
.registerError(ErrorException.class)
.build(response);
}
/**
* Gets all private link service in a subscription.
*
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws ErrorException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the PagedList<PrivateLinkServiceInner> object if successful.
*/
public PagedList<PrivateLinkServiceInner> list() {
ServiceResponse<Page<PrivateLinkServiceInner>> response = listSinglePageAsync().toBlocking().single();
return new PagedList<PrivateLinkServiceInner>(response.body()) {
@Override
public Page<PrivateLinkServiceInner> nextPage(String nextPageLink) {
return listNextSinglePageAsync(nextPageLink).toBlocking().single().body();
}
};
}
/**
* Gets all private link service in a subscription.
*
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<List<PrivateLinkServiceInner>> listAsync(final ListOperationCallback<PrivateLinkServiceInner> serviceCallback) {
return AzureServiceFuture.fromPageResponse(
listSinglePageAsync(),
new Func1<String, Observable<ServiceResponse<Page<PrivateLinkServiceInner>>>>() {
@Override
public Observable<ServiceResponse<Page<PrivateLinkServiceInner>>> call(String nextPageLink) {
return listNextSinglePageAsync(nextPageLink);
}
},
serviceCallback);
}
/**
* Gets all private link service in a subscription.
*
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PagedList<PrivateLinkServiceInner> object
*/
public Observable<Page<PrivateLinkServiceInner>> listAsync() {
return listWithServiceResponseAsync()
.map(new Func1<ServiceResponse<Page<PrivateLinkServiceInner>>, Page<PrivateLinkServiceInner>>() {
@Override
public Page<PrivateLinkServiceInner> call(ServiceResponse<Page<PrivateLinkServiceInner>> response) {
return response.body();
}
});
}
/**
* Gets all private link service in a subscription.
*
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PagedList<PrivateLinkServiceInner> object
*/
public Observable<ServiceResponse<Page<PrivateLinkServiceInner>>> listWithServiceResponseAsync() {
return listSinglePageAsync()
.concatMap(new Func1<ServiceResponse<Page<PrivateLinkServiceInner>>, Observable<ServiceResponse<Page<PrivateLinkServiceInner>>>>() {
@Override
public Observable<ServiceResponse<Page<PrivateLinkServiceInner>>> call(ServiceResponse<Page<PrivateLinkServiceInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink));
}
});
}
/**
* Gets all private link service in a subscription.
*
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the PagedList<PrivateLinkServiceInner> object wrapped in {@link ServiceResponse} if successful.
*/
public Observable<ServiceResponse<Page<PrivateLinkServiceInner>>> listSinglePageAsync() {
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
final String apiVersion = "2019-06-01";
return service.list(this.client.subscriptionId(), apiVersion, this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<PrivateLinkServiceInner>>>>() {
@Override
public Observable<ServiceResponse<Page<PrivateLinkServiceInner>>> call(Response<ResponseBody> response) {
try {
ServiceResponse<PageImpl<PrivateLinkServiceInner>> result = listDelegate(response);
return Observable.just(new ServiceResponse<Page<PrivateLinkServiceInner>>(result.body(), result.response()));
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<PageImpl<PrivateLinkServiceInner>> listDelegate(Response<ResponseBody> response) throws ErrorException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<PageImpl<PrivateLinkServiceInner>, ErrorException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<PageImpl<PrivateLinkServiceInner>>() { }.getType())
.registerError(ErrorException.class)
.build(response);
}
/**
* Approve or reject private end point connection for a private link service in a subscription.
*
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the private link service.
* @param peConnectionName The name of the private end point connection.
* @param parameters Parameters supplied to approve or reject the private end point connection.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws ErrorException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the PrivateEndpointConnectionInner object if successful.
*/
public PrivateEndpointConnectionInner updatePrivateEndpointConnection(String resourceGroupName, String serviceName, String peConnectionName, PrivateEndpointConnectionInner parameters) {
return updatePrivateEndpointConnectionWithServiceResponseAsync(resourceGroupName, serviceName, peConnectionName, parameters).toBlocking().single().body();
}
/**
* Approve or reject private end point connection for a private link service in a subscription.
*
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the private link service.
* @param peConnectionName The name of the private end point connection.
* @param parameters Parameters supplied to approve or reject the private end point connection.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<PrivateEndpointConnectionInner> updatePrivateEndpointConnectionAsync(String resourceGroupName, String serviceName, String peConnectionName, PrivateEndpointConnectionInner parameters, final ServiceCallback<PrivateEndpointConnectionInner> serviceCallback) {
return ServiceFuture.fromResponse(updatePrivateEndpointConnectionWithServiceResponseAsync(resourceGroupName, serviceName, peConnectionName, parameters), serviceCallback);
}
/**
* Approve or reject private end point connection for a private link service in a subscription.
*
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the private link service.
* @param peConnectionName The name of the private end point connection.
* @param parameters Parameters supplied to approve or reject the private end point connection.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PrivateEndpointConnectionInner object
*/
public Observable<PrivateEndpointConnectionInner> updatePrivateEndpointConnectionAsync(String resourceGroupName, String serviceName, String peConnectionName, PrivateEndpointConnectionInner parameters) {
return updatePrivateEndpointConnectionWithServiceResponseAsync(resourceGroupName, serviceName, peConnectionName, parameters).map(new Func1<ServiceResponse<PrivateEndpointConnectionInner>, PrivateEndpointConnectionInner>() {
@Override
public PrivateEndpointConnectionInner call(ServiceResponse<PrivateEndpointConnectionInner> response) {
return response.body();
}
});
}
/**
* Approve or reject private end point connection for a private link service in a subscription.
*
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the private link service.
* @param peConnectionName The name of the private end point connection.
* @param parameters Parameters supplied to approve or reject the private end point connection.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PrivateEndpointConnectionInner object
*/
public Observable<ServiceResponse<PrivateEndpointConnectionInner>> updatePrivateEndpointConnectionWithServiceResponseAsync(String resourceGroupName, String serviceName, String peConnectionName, PrivateEndpointConnectionInner parameters) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (serviceName == null) {
throw new IllegalArgumentException("Parameter serviceName is required and cannot be null.");
}
if (peConnectionName == null) {
throw new IllegalArgumentException("Parameter peConnectionName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
if (parameters == null) {
throw new IllegalArgumentException("Parameter parameters is required and cannot be null.");
}
Validator.validate(parameters);
final String apiVersion = "2019-06-01";
return service.updatePrivateEndpointConnection(resourceGroupName, serviceName, peConnectionName, this.client.subscriptionId(), parameters, apiVersion, this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<PrivateEndpointConnectionInner>>>() {
@Override
public Observable<ServiceResponse<PrivateEndpointConnectionInner>> call(Response<ResponseBody> response) {
try {
ServiceResponse<PrivateEndpointConnectionInner> clientResponse = updatePrivateEndpointConnectionDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<PrivateEndpointConnectionInner> updatePrivateEndpointConnectionDelegate(Response<ResponseBody> response) throws ErrorException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<PrivateEndpointConnectionInner, ErrorException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<PrivateEndpointConnectionInner>() { }.getType())
.registerError(ErrorException.class)
.build(response);
}
/**
* Delete private end point connection for a private link service in a subscription.
*
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the private link service.
* @param peConnectionName The name of the private end point connection.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws ErrorException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
*/
public void deletePrivateEndpointConnection(String resourceGroupName, String serviceName, String peConnectionName) {
deletePrivateEndpointConnectionWithServiceResponseAsync(resourceGroupName, serviceName, peConnectionName).toBlocking().last().body();
}
/**
* Delete private end point connection for a private link service in a subscription.
*
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the private link service.
* @param peConnectionName The name of the private end point connection.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<Void> deletePrivateEndpointConnectionAsync(String resourceGroupName, String serviceName, String peConnectionName, final ServiceCallback<Void> serviceCallback) {
return ServiceFuture.fromResponse(deletePrivateEndpointConnectionWithServiceResponseAsync(resourceGroupName, serviceName, peConnectionName), serviceCallback);
}
/**
* Delete private end point connection for a private link service in a subscription.
*
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the private link service.
* @param peConnectionName The name of the private end point connection.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable for the request
*/
public Observable<Void> deletePrivateEndpointConnectionAsync(String resourceGroupName, String serviceName, String peConnectionName) {
return deletePrivateEndpointConnectionWithServiceResponseAsync(resourceGroupName, serviceName, peConnectionName).map(new Func1<ServiceResponse<Void>, Void>() {
@Override
public Void call(ServiceResponse<Void> response) {
return response.body();
}
});
}
/**
* Delete private end point connection for a private link service in a subscription.
*
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the private link service.
* @param peConnectionName The name of the private end point connection.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable for the request
*/
public Observable<ServiceResponse<Void>> deletePrivateEndpointConnectionWithServiceResponseAsync(String resourceGroupName, String serviceName, String peConnectionName) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (serviceName == null) {
throw new IllegalArgumentException("Parameter serviceName is required and cannot be null.");
}
if (peConnectionName == null) {
throw new IllegalArgumentException("Parameter peConnectionName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
final String apiVersion = "2019-06-01";
Observable<Response<ResponseBody>> observable = service.deletePrivateEndpointConnection(resourceGroupName, serviceName, peConnectionName, this.client.subscriptionId(), apiVersion, this.client.acceptLanguage(), this.client.userAgent());
return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken<Void>() { }.getType());
}
/**
* Delete private end point connection for a private link service in a subscription.
*
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the private link service.
* @param peConnectionName The name of the private end point connection.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws ErrorException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
*/
public void beginDeletePrivateEndpointConnection(String resourceGroupName, String serviceName, String peConnectionName) {
beginDeletePrivateEndpointConnectionWithServiceResponseAsync(resourceGroupName, serviceName, peConnectionName).toBlocking().single().body();
}
/**
* Delete private end point connection for a private link service in a subscription.
*
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the private link service.
* @param peConnectionName The name of the private end point connection.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<Void> beginDeletePrivateEndpointConnectionAsync(String resourceGroupName, String serviceName, String peConnectionName, final ServiceCallback<Void> serviceCallback) {
return ServiceFuture.fromResponse(beginDeletePrivateEndpointConnectionWithServiceResponseAsync(resourceGroupName, serviceName, peConnectionName), serviceCallback);
}
/**
* Delete private end point connection for a private link service in a subscription.
*
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the private link service.
* @param peConnectionName The name of the private end point connection.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceResponse} object if successful.
*/
public Observable<Void> beginDeletePrivateEndpointConnectionAsync(String resourceGroupName, String serviceName, String peConnectionName) {
return beginDeletePrivateEndpointConnectionWithServiceResponseAsync(resourceGroupName, serviceName, peConnectionName).map(new Func1<ServiceResponse<Void>, Void>() {
@Override
public Void call(ServiceResponse<Void> response) {
return response.body();
}
});
}
/**
* Delete private end point connection for a private link service in a subscription.
*
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the private link service.
* @param peConnectionName The name of the private end point connection.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceResponse} object if successful.
*/
public Observable<ServiceResponse<Void>> beginDeletePrivateEndpointConnectionWithServiceResponseAsync(String resourceGroupName, String serviceName, String peConnectionName) {
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (serviceName == null) {
throw new IllegalArgumentException("Parameter serviceName is required and cannot be null.");
}
if (peConnectionName == null) {
throw new IllegalArgumentException("Parameter peConnectionName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
final String apiVersion = "2019-06-01";
return service.beginDeletePrivateEndpointConnection(resourceGroupName, serviceName, peConnectionName, this.client.subscriptionId(), apiVersion, this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Void>>>() {
@Override
public Observable<ServiceResponse<Void>> call(Response<ResponseBody> response) {
try {
ServiceResponse<Void> clientResponse = beginDeletePrivateEndpointConnectionDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<Void> beginDeletePrivateEndpointConnectionDelegate(Response<ResponseBody> response) throws ErrorException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<Void, ErrorException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<Void>() { }.getType())
.register(202, new TypeToken<Void>() { }.getType())
.register(204, new TypeToken<Void>() { }.getType())
.registerError(ErrorException.class)
.build(response);
}
/**
* Checks the subscription is visible to private link service.
*
* @param location The location of the domain name.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the PrivateLinkServiceVisibilityInner object if successful.
*/
public PrivateLinkServiceVisibilityInner checkPrivateLinkServiceVisibility(String location) {
return checkPrivateLinkServiceVisibilityWithServiceResponseAsync(location).toBlocking().single().body();
}
/**
* Checks the subscription is visible to private link service.
*
* @param location The location of the domain name.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<PrivateLinkServiceVisibilityInner> checkPrivateLinkServiceVisibilityAsync(String location, final ServiceCallback<PrivateLinkServiceVisibilityInner> serviceCallback) {
return ServiceFuture.fromResponse(checkPrivateLinkServiceVisibilityWithServiceResponseAsync(location), serviceCallback);
}
/**
* Checks the subscription is visible to private link service.
*
* @param location The location of the domain name.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PrivateLinkServiceVisibilityInner object
*/
public Observable<PrivateLinkServiceVisibilityInner> checkPrivateLinkServiceVisibilityAsync(String location) {
return checkPrivateLinkServiceVisibilityWithServiceResponseAsync(location).map(new Func1<ServiceResponse<PrivateLinkServiceVisibilityInner>, PrivateLinkServiceVisibilityInner>() {
@Override
public PrivateLinkServiceVisibilityInner call(ServiceResponse<PrivateLinkServiceVisibilityInner> response) {
return response.body();
}
});
}
/**
* Checks the subscription is visible to private link service.
*
* @param location The location of the domain name.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PrivateLinkServiceVisibilityInner object
*/
public Observable<ServiceResponse<PrivateLinkServiceVisibilityInner>> checkPrivateLinkServiceVisibilityWithServiceResponseAsync(String location) {
if (location == null) {
throw new IllegalArgumentException("Parameter location is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
final String apiVersion = "2019-06-01";
final String privateLinkServiceAlias = null;
CheckPrivateLinkServiceVisibilityRequest parameters = new CheckPrivateLinkServiceVisibilityRequest();
parameters.withPrivateLinkServiceAlias(null);
return service.checkPrivateLinkServiceVisibility(location, this.client.subscriptionId(), apiVersion, this.client.acceptLanguage(), parameters, this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<PrivateLinkServiceVisibilityInner>>>() {
@Override
public Observable<ServiceResponse<PrivateLinkServiceVisibilityInner>> call(Response<ResponseBody> response) {
try {
ServiceResponse<PrivateLinkServiceVisibilityInner> clientResponse = checkPrivateLinkServiceVisibilityDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
/**
* Checks the subscription is visible to private link service.
*
* @param location The location of the domain name.
* @param privateLinkServiceAlias The alias of the private link service.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the PrivateLinkServiceVisibilityInner object if successful.
*/
public PrivateLinkServiceVisibilityInner checkPrivateLinkServiceVisibility(String location, String privateLinkServiceAlias) {
return checkPrivateLinkServiceVisibilityWithServiceResponseAsync(location, privateLinkServiceAlias).toBlocking().single().body();
}
/**
* Checks the subscription is visible to private link service.
*
* @param location The location of the domain name.
* @param privateLinkServiceAlias The alias of the private link service.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<PrivateLinkServiceVisibilityInner> checkPrivateLinkServiceVisibilityAsync(String location, String privateLinkServiceAlias, final ServiceCallback<PrivateLinkServiceVisibilityInner> serviceCallback) {
return ServiceFuture.fromResponse(checkPrivateLinkServiceVisibilityWithServiceResponseAsync(location, privateLinkServiceAlias), serviceCallback);
}
/**
* Checks the subscription is visible to private link service.
*
* @param location The location of the domain name.
* @param privateLinkServiceAlias The alias of the private link service.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PrivateLinkServiceVisibilityInner object
*/
public Observable<PrivateLinkServiceVisibilityInner> checkPrivateLinkServiceVisibilityAsync(String location, String privateLinkServiceAlias) {
return checkPrivateLinkServiceVisibilityWithServiceResponseAsync(location, privateLinkServiceAlias).map(new Func1<ServiceResponse<PrivateLinkServiceVisibilityInner>, PrivateLinkServiceVisibilityInner>() {
@Override
public PrivateLinkServiceVisibilityInner call(ServiceResponse<PrivateLinkServiceVisibilityInner> response) {
return response.body();
}
});
}
/**
* Checks the subscription is visible to private link service.
*
* @param location The location of the domain name.
* @param privateLinkServiceAlias The alias of the private link service.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PrivateLinkServiceVisibilityInner object
*/
public Observable<ServiceResponse<PrivateLinkServiceVisibilityInner>> checkPrivateLinkServiceVisibilityWithServiceResponseAsync(String location, String privateLinkServiceAlias) {
if (location == null) {
throw new IllegalArgumentException("Parameter location is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
final String apiVersion = "2019-06-01";
CheckPrivateLinkServiceVisibilityRequest parameters = new CheckPrivateLinkServiceVisibilityRequest();
parameters.withPrivateLinkServiceAlias(privateLinkServiceAlias);
return service.checkPrivateLinkServiceVisibility(location, this.client.subscriptionId(), apiVersion, this.client.acceptLanguage(), parameters, this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<PrivateLinkServiceVisibilityInner>>>() {
@Override
public Observable<ServiceResponse<PrivateLinkServiceVisibilityInner>> call(Response<ResponseBody> response) {
try {
ServiceResponse<PrivateLinkServiceVisibilityInner> clientResponse = checkPrivateLinkServiceVisibilityDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<PrivateLinkServiceVisibilityInner> checkPrivateLinkServiceVisibilityDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<PrivateLinkServiceVisibilityInner, CloudException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<PrivateLinkServiceVisibilityInner>() { }.getType())
.registerError(CloudException.class)
.build(response);
}
/**
* Checks the subscription is visible to private link service.
*
* @param location The location of the domain name.
* @param resourceGroupName The name of the resource group.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the PrivateLinkServiceVisibilityInner object if successful.
*/
public PrivateLinkServiceVisibilityInner checkPrivateLinkServiceVisibilityByResourceGroup(String location, String resourceGroupName) {
return checkPrivateLinkServiceVisibilityByResourceGroupWithServiceResponseAsync(location, resourceGroupName).toBlocking().single().body();
}
/**
* Checks the subscription is visible to private link service.
*
* @param location The location of the domain name.
* @param resourceGroupName The name of the resource group.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<PrivateLinkServiceVisibilityInner> checkPrivateLinkServiceVisibilityByResourceGroupAsync(String location, String resourceGroupName, final ServiceCallback<PrivateLinkServiceVisibilityInner> serviceCallback) {
return ServiceFuture.fromResponse(checkPrivateLinkServiceVisibilityByResourceGroupWithServiceResponseAsync(location, resourceGroupName), serviceCallback);
}
/**
* Checks the subscription is visible to private link service.
*
* @param location The location of the domain name.
* @param resourceGroupName The name of the resource group.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PrivateLinkServiceVisibilityInner object
*/
public Observable<PrivateLinkServiceVisibilityInner> checkPrivateLinkServiceVisibilityByResourceGroupAsync(String location, String resourceGroupName) {
return checkPrivateLinkServiceVisibilityByResourceGroupWithServiceResponseAsync(location, resourceGroupName).map(new Func1<ServiceResponse<PrivateLinkServiceVisibilityInner>, PrivateLinkServiceVisibilityInner>() {
@Override
public PrivateLinkServiceVisibilityInner call(ServiceResponse<PrivateLinkServiceVisibilityInner> response) {
return response.body();
}
});
}
/**
* Checks the subscription is visible to private link service.
*
* @param location The location of the domain name.
* @param resourceGroupName The name of the resource group.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PrivateLinkServiceVisibilityInner object
*/
public Observable<ServiceResponse<PrivateLinkServiceVisibilityInner>> checkPrivateLinkServiceVisibilityByResourceGroupWithServiceResponseAsync(String location, String resourceGroupName) {
if (location == null) {
throw new IllegalArgumentException("Parameter location is required and cannot be null.");
}
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
final String apiVersion = "2019-06-01";
final String privateLinkServiceAlias = null;
CheckPrivateLinkServiceVisibilityRequest parameters = new CheckPrivateLinkServiceVisibilityRequest();
parameters.withPrivateLinkServiceAlias(null);
return service.checkPrivateLinkServiceVisibilityByResourceGroup(location, resourceGroupName, this.client.subscriptionId(), apiVersion, this.client.acceptLanguage(), parameters, this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<PrivateLinkServiceVisibilityInner>>>() {
@Override
public Observable<ServiceResponse<PrivateLinkServiceVisibilityInner>> call(Response<ResponseBody> response) {
try {
ServiceResponse<PrivateLinkServiceVisibilityInner> clientResponse = checkPrivateLinkServiceVisibilityByResourceGroupDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
/**
* Checks the subscription is visible to private link service.
*
* @param location The location of the domain name.
* @param resourceGroupName The name of the resource group.
* @param privateLinkServiceAlias The alias of the private link service.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the PrivateLinkServiceVisibilityInner object if successful.
*/
public PrivateLinkServiceVisibilityInner checkPrivateLinkServiceVisibilityByResourceGroup(String location, String resourceGroupName, String privateLinkServiceAlias) {
return checkPrivateLinkServiceVisibilityByResourceGroupWithServiceResponseAsync(location, resourceGroupName, privateLinkServiceAlias).toBlocking().single().body();
}
/**
* Checks the subscription is visible to private link service.
*
* @param location The location of the domain name.
* @param resourceGroupName The name of the resource group.
* @param privateLinkServiceAlias The alias of the private link service.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<PrivateLinkServiceVisibilityInner> checkPrivateLinkServiceVisibilityByResourceGroupAsync(String location, String resourceGroupName, String privateLinkServiceAlias, final ServiceCallback<PrivateLinkServiceVisibilityInner> serviceCallback) {
return ServiceFuture.fromResponse(checkPrivateLinkServiceVisibilityByResourceGroupWithServiceResponseAsync(location, resourceGroupName, privateLinkServiceAlias), serviceCallback);
}
/**
* Checks the subscription is visible to private link service.
*
* @param location The location of the domain name.
* @param resourceGroupName The name of the resource group.
* @param privateLinkServiceAlias The alias of the private link service.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PrivateLinkServiceVisibilityInner object
*/
public Observable<PrivateLinkServiceVisibilityInner> checkPrivateLinkServiceVisibilityByResourceGroupAsync(String location, String resourceGroupName, String privateLinkServiceAlias) {
return checkPrivateLinkServiceVisibilityByResourceGroupWithServiceResponseAsync(location, resourceGroupName, privateLinkServiceAlias).map(new Func1<ServiceResponse<PrivateLinkServiceVisibilityInner>, PrivateLinkServiceVisibilityInner>() {
@Override
public PrivateLinkServiceVisibilityInner call(ServiceResponse<PrivateLinkServiceVisibilityInner> response) {
return response.body();
}
});
}
/**
* Checks the subscription is visible to private link service.
*
* @param location The location of the domain name.
* @param resourceGroupName The name of the resource group.
* @param privateLinkServiceAlias The alias of the private link service.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PrivateLinkServiceVisibilityInner object
*/
public Observable<ServiceResponse<PrivateLinkServiceVisibilityInner>> checkPrivateLinkServiceVisibilityByResourceGroupWithServiceResponseAsync(String location, String resourceGroupName, String privateLinkServiceAlias) {
if (location == null) {
throw new IllegalArgumentException("Parameter location is required and cannot be null.");
}
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
final String apiVersion = "2019-06-01";
CheckPrivateLinkServiceVisibilityRequest parameters = new CheckPrivateLinkServiceVisibilityRequest();
parameters.withPrivateLinkServiceAlias(privateLinkServiceAlias);
return service.checkPrivateLinkServiceVisibilityByResourceGroup(location, resourceGroupName, this.client.subscriptionId(), apiVersion, this.client.acceptLanguage(), parameters, this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<PrivateLinkServiceVisibilityInner>>>() {
@Override
public Observable<ServiceResponse<PrivateLinkServiceVisibilityInner>> call(Response<ResponseBody> response) {
try {
ServiceResponse<PrivateLinkServiceVisibilityInner> clientResponse = checkPrivateLinkServiceVisibilityByResourceGroupDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<PrivateLinkServiceVisibilityInner> checkPrivateLinkServiceVisibilityByResourceGroupDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<PrivateLinkServiceVisibilityInner, CloudException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<PrivateLinkServiceVisibilityInner>() { }.getType())
.registerError(CloudException.class)
.build(response);
}
/**
* Returns all of the private link service ids that can be linked to a Private Endpoint with auto approved in this subscription in this region.
*
* @param location The location of the domain name.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the PagedList<AutoApprovedPrivateLinkServiceInner> object if successful.
*/
public PagedList<AutoApprovedPrivateLinkServiceInner> listAutoApprovedPrivateLinkServices(final String location) {
ServiceResponse<Page<AutoApprovedPrivateLinkServiceInner>> response = listAutoApprovedPrivateLinkServicesSinglePageAsync(location).toBlocking().single();
return new PagedList<AutoApprovedPrivateLinkServiceInner>(response.body()) {
@Override
public Page<AutoApprovedPrivateLinkServiceInner> nextPage(String nextPageLink) {
return listAutoApprovedPrivateLinkServicesNextSinglePageAsync(nextPageLink).toBlocking().single().body();
}
};
}
/**
* Returns all of the private link service ids that can be linked to a Private Endpoint with auto approved in this subscription in this region.
*
* @param location The location of the domain name.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<List<AutoApprovedPrivateLinkServiceInner>> listAutoApprovedPrivateLinkServicesAsync(final String location, final ListOperationCallback<AutoApprovedPrivateLinkServiceInner> serviceCallback) {
return AzureServiceFuture.fromPageResponse(
listAutoApprovedPrivateLinkServicesSinglePageAsync(location),
new Func1<String, Observable<ServiceResponse<Page<AutoApprovedPrivateLinkServiceInner>>>>() {
@Override
public Observable<ServiceResponse<Page<AutoApprovedPrivateLinkServiceInner>>> call(String nextPageLink) {
return listAutoApprovedPrivateLinkServicesNextSinglePageAsync(nextPageLink);
}
},
serviceCallback);
}
/**
* Returns all of the private link service ids that can be linked to a Private Endpoint with auto approved in this subscription in this region.
*
* @param location The location of the domain name.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PagedList<AutoApprovedPrivateLinkServiceInner> object
*/
public Observable<Page<AutoApprovedPrivateLinkServiceInner>> listAutoApprovedPrivateLinkServicesAsync(final String location) {
return listAutoApprovedPrivateLinkServicesWithServiceResponseAsync(location)
.map(new Func1<ServiceResponse<Page<AutoApprovedPrivateLinkServiceInner>>, Page<AutoApprovedPrivateLinkServiceInner>>() {
@Override
public Page<AutoApprovedPrivateLinkServiceInner> call(ServiceResponse<Page<AutoApprovedPrivateLinkServiceInner>> response) {
return response.body();
}
});
}
/**
* Returns all of the private link service ids that can be linked to a Private Endpoint with auto approved in this subscription in this region.
*
* @param location The location of the domain name.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PagedList<AutoApprovedPrivateLinkServiceInner> object
*/
public Observable<ServiceResponse<Page<AutoApprovedPrivateLinkServiceInner>>> listAutoApprovedPrivateLinkServicesWithServiceResponseAsync(final String location) {
return listAutoApprovedPrivateLinkServicesSinglePageAsync(location)
.concatMap(new Func1<ServiceResponse<Page<AutoApprovedPrivateLinkServiceInner>>, Observable<ServiceResponse<Page<AutoApprovedPrivateLinkServiceInner>>>>() {
@Override
public Observable<ServiceResponse<Page<AutoApprovedPrivateLinkServiceInner>>> call(ServiceResponse<Page<AutoApprovedPrivateLinkServiceInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(listAutoApprovedPrivateLinkServicesNextWithServiceResponseAsync(nextPageLink));
}
});
}
/**
* Returns all of the private link service ids that can be linked to a Private Endpoint with auto approved in this subscription in this region.
*
ServiceResponse<PageImpl<AutoApprovedPrivateLinkServiceInner>> * @param location The location of the domain name.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the PagedList<AutoApprovedPrivateLinkServiceInner> object wrapped in {@link ServiceResponse} if successful.
*/
public Observable<ServiceResponse<Page<AutoApprovedPrivateLinkServiceInner>>> listAutoApprovedPrivateLinkServicesSinglePageAsync(final String location) {
if (location == null) {
throw new IllegalArgumentException("Parameter location is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
final String apiVersion = "2019-06-01";
return service.listAutoApprovedPrivateLinkServices(location, this.client.subscriptionId(), apiVersion, this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<AutoApprovedPrivateLinkServiceInner>>>>() {
@Override
public Observable<ServiceResponse<Page<AutoApprovedPrivateLinkServiceInner>>> call(Response<ResponseBody> response) {
try {
ServiceResponse<PageImpl<AutoApprovedPrivateLinkServiceInner>> result = listAutoApprovedPrivateLinkServicesDelegate(response);
return Observable.just(new ServiceResponse<Page<AutoApprovedPrivateLinkServiceInner>>(result.body(), result.response()));
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<PageImpl<AutoApprovedPrivateLinkServiceInner>> listAutoApprovedPrivateLinkServicesDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<PageImpl<AutoApprovedPrivateLinkServiceInner>, CloudException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<PageImpl<AutoApprovedPrivateLinkServiceInner>>() { }.getType())
.registerError(CloudException.class)
.build(response);
}
/**
* Returns all of the private link service ids that can be linked to a Private Endpoint with auto approved in this subscription in this region.
*
* @param location The location of the domain name.
* @param resourceGroupName The name of the resource group.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the PagedList<AutoApprovedPrivateLinkServiceInner> object if successful.
*/
public PagedList<AutoApprovedPrivateLinkServiceInner> listAutoApprovedPrivateLinkServicesByResourceGroup(final String location, final String resourceGroupName) {
ServiceResponse<Page<AutoApprovedPrivateLinkServiceInner>> response = listAutoApprovedPrivateLinkServicesByResourceGroupSinglePageAsync(location, resourceGroupName).toBlocking().single();
return new PagedList<AutoApprovedPrivateLinkServiceInner>(response.body()) {
@Override
public Page<AutoApprovedPrivateLinkServiceInner> nextPage(String nextPageLink) {
return listAutoApprovedPrivateLinkServicesByResourceGroupNextSinglePageAsync(nextPageLink).toBlocking().single().body();
}
};
}
/**
* Returns all of the private link service ids that can be linked to a Private Endpoint with auto approved in this subscription in this region.
*
* @param location The location of the domain name.
* @param resourceGroupName The name of the resource group.
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<List<AutoApprovedPrivateLinkServiceInner>> listAutoApprovedPrivateLinkServicesByResourceGroupAsync(final String location, final String resourceGroupName, final ListOperationCallback<AutoApprovedPrivateLinkServiceInner> serviceCallback) {
return AzureServiceFuture.fromPageResponse(
listAutoApprovedPrivateLinkServicesByResourceGroupSinglePageAsync(location, resourceGroupName),
new Func1<String, Observable<ServiceResponse<Page<AutoApprovedPrivateLinkServiceInner>>>>() {
@Override
public Observable<ServiceResponse<Page<AutoApprovedPrivateLinkServiceInner>>> call(String nextPageLink) {
return listAutoApprovedPrivateLinkServicesByResourceGroupNextSinglePageAsync(nextPageLink);
}
},
serviceCallback);
}
/**
* Returns all of the private link service ids that can be linked to a Private Endpoint with auto approved in this subscription in this region.
*
* @param location The location of the domain name.
* @param resourceGroupName The name of the resource group.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PagedList<AutoApprovedPrivateLinkServiceInner> object
*/
public Observable<Page<AutoApprovedPrivateLinkServiceInner>> listAutoApprovedPrivateLinkServicesByResourceGroupAsync(final String location, final String resourceGroupName) {
return listAutoApprovedPrivateLinkServicesByResourceGroupWithServiceResponseAsync(location, resourceGroupName)
.map(new Func1<ServiceResponse<Page<AutoApprovedPrivateLinkServiceInner>>, Page<AutoApprovedPrivateLinkServiceInner>>() {
@Override
public Page<AutoApprovedPrivateLinkServiceInner> call(ServiceResponse<Page<AutoApprovedPrivateLinkServiceInner>> response) {
return response.body();
}
});
}
/**
* Returns all of the private link service ids that can be linked to a Private Endpoint with auto approved in this subscription in this region.
*
* @param location The location of the domain name.
* @param resourceGroupName The name of the resource group.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PagedList<AutoApprovedPrivateLinkServiceInner> object
*/
public Observable<ServiceResponse<Page<AutoApprovedPrivateLinkServiceInner>>> listAutoApprovedPrivateLinkServicesByResourceGroupWithServiceResponseAsync(final String location, final String resourceGroupName) {
return listAutoApprovedPrivateLinkServicesByResourceGroupSinglePageAsync(location, resourceGroupName)
.concatMap(new Func1<ServiceResponse<Page<AutoApprovedPrivateLinkServiceInner>>, Observable<ServiceResponse<Page<AutoApprovedPrivateLinkServiceInner>>>>() {
@Override
public Observable<ServiceResponse<Page<AutoApprovedPrivateLinkServiceInner>>> call(ServiceResponse<Page<AutoApprovedPrivateLinkServiceInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(listAutoApprovedPrivateLinkServicesByResourceGroupNextWithServiceResponseAsync(nextPageLink));
}
});
}
/**
* Returns all of the private link service ids that can be linked to a Private Endpoint with auto approved in this subscription in this region.
*
ServiceResponse<PageImpl<AutoApprovedPrivateLinkServiceInner>> * @param location The location of the domain name.
ServiceResponse<PageImpl<AutoApprovedPrivateLinkServiceInner>> * @param resourceGroupName The name of the resource group.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the PagedList<AutoApprovedPrivateLinkServiceInner> object wrapped in {@link ServiceResponse} if successful.
*/
public Observable<ServiceResponse<Page<AutoApprovedPrivateLinkServiceInner>>> listAutoApprovedPrivateLinkServicesByResourceGroupSinglePageAsync(final String location, final String resourceGroupName) {
if (location == null) {
throw new IllegalArgumentException("Parameter location is required and cannot be null.");
}
if (resourceGroupName == null) {
throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null.");
}
if (this.client.subscriptionId() == null) {
throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
}
final String apiVersion = "2019-06-01";
return service.listAutoApprovedPrivateLinkServicesByResourceGroup(location, resourceGroupName, this.client.subscriptionId(), apiVersion, this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<AutoApprovedPrivateLinkServiceInner>>>>() {
@Override
public Observable<ServiceResponse<Page<AutoApprovedPrivateLinkServiceInner>>> call(Response<ResponseBody> response) {
try {
ServiceResponse<PageImpl<AutoApprovedPrivateLinkServiceInner>> result = listAutoApprovedPrivateLinkServicesByResourceGroupDelegate(response);
return Observable.just(new ServiceResponse<Page<AutoApprovedPrivateLinkServiceInner>>(result.body(), result.response()));
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<PageImpl<AutoApprovedPrivateLinkServiceInner>> listAutoApprovedPrivateLinkServicesByResourceGroupDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<PageImpl<AutoApprovedPrivateLinkServiceInner>, CloudException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<PageImpl<AutoApprovedPrivateLinkServiceInner>>() { }.getType())
.registerError(CloudException.class)
.build(response);
}
/**
* Gets all private link services in a resource group.
*
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws ErrorException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the PagedList<PrivateLinkServiceInner> object if successful.
*/
public PagedList<PrivateLinkServiceInner> listByResourceGroupNext(final String nextPageLink) {
ServiceResponse<Page<PrivateLinkServiceInner>> response = listByResourceGroupNextSinglePageAsync(nextPageLink).toBlocking().single();
return new PagedList<PrivateLinkServiceInner>(response.body()) {
@Override
public Page<PrivateLinkServiceInner> nextPage(String nextPageLink) {
return listByResourceGroupNextSinglePageAsync(nextPageLink).toBlocking().single().body();
}
};
}
/**
* Gets all private link services in a resource group.
*
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param serviceFuture the ServiceFuture object tracking the Retrofit calls
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<List<PrivateLinkServiceInner>> listByResourceGroupNextAsync(final String nextPageLink, final ServiceFuture<List<PrivateLinkServiceInner>> serviceFuture, final ListOperationCallback<PrivateLinkServiceInner> serviceCallback) {
return AzureServiceFuture.fromPageResponse(
listByResourceGroupNextSinglePageAsync(nextPageLink),
new Func1<String, Observable<ServiceResponse<Page<PrivateLinkServiceInner>>>>() {
@Override
public Observable<ServiceResponse<Page<PrivateLinkServiceInner>>> call(String nextPageLink) {
return listByResourceGroupNextSinglePageAsync(nextPageLink);
}
},
serviceCallback);
}
/**
* Gets all private link services in a resource group.
*
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PagedList<PrivateLinkServiceInner> object
*/
public Observable<Page<PrivateLinkServiceInner>> listByResourceGroupNextAsync(final String nextPageLink) {
return listByResourceGroupNextWithServiceResponseAsync(nextPageLink)
.map(new Func1<ServiceResponse<Page<PrivateLinkServiceInner>>, Page<PrivateLinkServiceInner>>() {
@Override
public Page<PrivateLinkServiceInner> call(ServiceResponse<Page<PrivateLinkServiceInner>> response) {
return response.body();
}
});
}
/**
* Gets all private link services in a resource group.
*
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PagedList<PrivateLinkServiceInner> object
*/
public Observable<ServiceResponse<Page<PrivateLinkServiceInner>>> listByResourceGroupNextWithServiceResponseAsync(final String nextPageLink) {
return listByResourceGroupNextSinglePageAsync(nextPageLink)
.concatMap(new Func1<ServiceResponse<Page<PrivateLinkServiceInner>>, Observable<ServiceResponse<Page<PrivateLinkServiceInner>>>>() {
@Override
public Observable<ServiceResponse<Page<PrivateLinkServiceInner>>> call(ServiceResponse<Page<PrivateLinkServiceInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(listByResourceGroupNextWithServiceResponseAsync(nextPageLink));
}
});
}
/**
* Gets all private link services in a resource group.
*
ServiceResponse<PageImpl<PrivateLinkServiceInner>> * @param nextPageLink The NextLink from the previous successful call to List operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the PagedList<PrivateLinkServiceInner> object wrapped in {@link ServiceResponse} if successful.
*/
public Observable<ServiceResponse<Page<PrivateLinkServiceInner>>> listByResourceGroupNextSinglePageAsync(final String nextPageLink) {
if (nextPageLink == null) {
throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null.");
}
String nextUrl = String.format("%s", nextPageLink);
return service.listByResourceGroupNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<PrivateLinkServiceInner>>>>() {
@Override
public Observable<ServiceResponse<Page<PrivateLinkServiceInner>>> call(Response<ResponseBody> response) {
try {
ServiceResponse<PageImpl<PrivateLinkServiceInner>> result = listByResourceGroupNextDelegate(response);
return Observable.just(new ServiceResponse<Page<PrivateLinkServiceInner>>(result.body(), result.response()));
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<PageImpl<PrivateLinkServiceInner>> listByResourceGroupNextDelegate(Response<ResponseBody> response) throws ErrorException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<PageImpl<PrivateLinkServiceInner>, ErrorException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<PageImpl<PrivateLinkServiceInner>>() { }.getType())
.registerError(ErrorException.class)
.build(response);
}
/**
* Gets all private link service in a subscription.
*
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws ErrorException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the PagedList<PrivateLinkServiceInner> object if successful.
*/
public PagedList<PrivateLinkServiceInner> listNext(final String nextPageLink) {
ServiceResponse<Page<PrivateLinkServiceInner>> response = listNextSinglePageAsync(nextPageLink).toBlocking().single();
return new PagedList<PrivateLinkServiceInner>(response.body()) {
@Override
public Page<PrivateLinkServiceInner> nextPage(String nextPageLink) {
return listNextSinglePageAsync(nextPageLink).toBlocking().single().body();
}
};
}
/**
* Gets all private link service in a subscription.
*
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param serviceFuture the ServiceFuture object tracking the Retrofit calls
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<List<PrivateLinkServiceInner>> listNextAsync(final String nextPageLink, final ServiceFuture<List<PrivateLinkServiceInner>> serviceFuture, final ListOperationCallback<PrivateLinkServiceInner> serviceCallback) {
return AzureServiceFuture.fromPageResponse(
listNextSinglePageAsync(nextPageLink),
new Func1<String, Observable<ServiceResponse<Page<PrivateLinkServiceInner>>>>() {
@Override
public Observable<ServiceResponse<Page<PrivateLinkServiceInner>>> call(String nextPageLink) {
return listNextSinglePageAsync(nextPageLink);
}
},
serviceCallback);
}
/**
* Gets all private link service in a subscription.
*
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PagedList<PrivateLinkServiceInner> object
*/
public Observable<Page<PrivateLinkServiceInner>> listNextAsync(final String nextPageLink) {
return listNextWithServiceResponseAsync(nextPageLink)
.map(new Func1<ServiceResponse<Page<PrivateLinkServiceInner>>, Page<PrivateLinkServiceInner>>() {
@Override
public Page<PrivateLinkServiceInner> call(ServiceResponse<Page<PrivateLinkServiceInner>> response) {
return response.body();
}
});
}
/**
* Gets all private link service in a subscription.
*
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PagedList<PrivateLinkServiceInner> object
*/
public Observable<ServiceResponse<Page<PrivateLinkServiceInner>>> listNextWithServiceResponseAsync(final String nextPageLink) {
return listNextSinglePageAsync(nextPageLink)
.concatMap(new Func1<ServiceResponse<Page<PrivateLinkServiceInner>>, Observable<ServiceResponse<Page<PrivateLinkServiceInner>>>>() {
@Override
public Observable<ServiceResponse<Page<PrivateLinkServiceInner>>> call(ServiceResponse<Page<PrivateLinkServiceInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink));
}
});
}
/**
* Gets all private link service in a subscription.
*
ServiceResponse<PageImpl<PrivateLinkServiceInner>> * @param nextPageLink The NextLink from the previous successful call to List operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the PagedList<PrivateLinkServiceInner> object wrapped in {@link ServiceResponse} if successful.
*/
public Observable<ServiceResponse<Page<PrivateLinkServiceInner>>> listNextSinglePageAsync(final String nextPageLink) {
if (nextPageLink == null) {
throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null.");
}
String nextUrl = String.format("%s", nextPageLink);
return service.listNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<PrivateLinkServiceInner>>>>() {
@Override
public Observable<ServiceResponse<Page<PrivateLinkServiceInner>>> call(Response<ResponseBody> response) {
try {
ServiceResponse<PageImpl<PrivateLinkServiceInner>> result = listNextDelegate(response);
return Observable.just(new ServiceResponse<Page<PrivateLinkServiceInner>>(result.body(), result.response()));
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<PageImpl<PrivateLinkServiceInner>> listNextDelegate(Response<ResponseBody> response) throws ErrorException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<PageImpl<PrivateLinkServiceInner>, ErrorException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<PageImpl<PrivateLinkServiceInner>>() { }.getType())
.registerError(ErrorException.class)
.build(response);
}
/**
* Returns all of the private link service ids that can be linked to a Private Endpoint with auto approved in this subscription in this region.
*
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the PagedList<AutoApprovedPrivateLinkServiceInner> object if successful.
*/
public PagedList<AutoApprovedPrivateLinkServiceInner> listAutoApprovedPrivateLinkServicesNext(final String nextPageLink) {
ServiceResponse<Page<AutoApprovedPrivateLinkServiceInner>> response = listAutoApprovedPrivateLinkServicesNextSinglePageAsync(nextPageLink).toBlocking().single();
return new PagedList<AutoApprovedPrivateLinkServiceInner>(response.body()) {
@Override
public Page<AutoApprovedPrivateLinkServiceInner> nextPage(String nextPageLink) {
return listAutoApprovedPrivateLinkServicesNextSinglePageAsync(nextPageLink).toBlocking().single().body();
}
};
}
/**
* Returns all of the private link service ids that can be linked to a Private Endpoint with auto approved in this subscription in this region.
*
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param serviceFuture the ServiceFuture object tracking the Retrofit calls
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<List<AutoApprovedPrivateLinkServiceInner>> listAutoApprovedPrivateLinkServicesNextAsync(final String nextPageLink, final ServiceFuture<List<AutoApprovedPrivateLinkServiceInner>> serviceFuture, final ListOperationCallback<AutoApprovedPrivateLinkServiceInner> serviceCallback) {
return AzureServiceFuture.fromPageResponse(
listAutoApprovedPrivateLinkServicesNextSinglePageAsync(nextPageLink),
new Func1<String, Observable<ServiceResponse<Page<AutoApprovedPrivateLinkServiceInner>>>>() {
@Override
public Observable<ServiceResponse<Page<AutoApprovedPrivateLinkServiceInner>>> call(String nextPageLink) {
return listAutoApprovedPrivateLinkServicesNextSinglePageAsync(nextPageLink);
}
},
serviceCallback);
}
/**
* Returns all of the private link service ids that can be linked to a Private Endpoint with auto approved in this subscription in this region.
*
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PagedList<AutoApprovedPrivateLinkServiceInner> object
*/
public Observable<Page<AutoApprovedPrivateLinkServiceInner>> listAutoApprovedPrivateLinkServicesNextAsync(final String nextPageLink) {
return listAutoApprovedPrivateLinkServicesNextWithServiceResponseAsync(nextPageLink)
.map(new Func1<ServiceResponse<Page<AutoApprovedPrivateLinkServiceInner>>, Page<AutoApprovedPrivateLinkServiceInner>>() {
@Override
public Page<AutoApprovedPrivateLinkServiceInner> call(ServiceResponse<Page<AutoApprovedPrivateLinkServiceInner>> response) {
return response.body();
}
});
}
/**
* Returns all of the private link service ids that can be linked to a Private Endpoint with auto approved in this subscription in this region.
*
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PagedList<AutoApprovedPrivateLinkServiceInner> object
*/
public Observable<ServiceResponse<Page<AutoApprovedPrivateLinkServiceInner>>> listAutoApprovedPrivateLinkServicesNextWithServiceResponseAsync(final String nextPageLink) {
return listAutoApprovedPrivateLinkServicesNextSinglePageAsync(nextPageLink)
.concatMap(new Func1<ServiceResponse<Page<AutoApprovedPrivateLinkServiceInner>>, Observable<ServiceResponse<Page<AutoApprovedPrivateLinkServiceInner>>>>() {
@Override
public Observable<ServiceResponse<Page<AutoApprovedPrivateLinkServiceInner>>> call(ServiceResponse<Page<AutoApprovedPrivateLinkServiceInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(listAutoApprovedPrivateLinkServicesNextWithServiceResponseAsync(nextPageLink));
}
});
}
/**
* Returns all of the private link service ids that can be linked to a Private Endpoint with auto approved in this subscription in this region.
*
ServiceResponse<PageImpl<AutoApprovedPrivateLinkServiceInner>> * @param nextPageLink The NextLink from the previous successful call to List operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the PagedList<AutoApprovedPrivateLinkServiceInner> object wrapped in {@link ServiceResponse} if successful.
*/
public Observable<ServiceResponse<Page<AutoApprovedPrivateLinkServiceInner>>> listAutoApprovedPrivateLinkServicesNextSinglePageAsync(final String nextPageLink) {
if (nextPageLink == null) {
throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null.");
}
String nextUrl = String.format("%s", nextPageLink);
return service.listAutoApprovedPrivateLinkServicesNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<AutoApprovedPrivateLinkServiceInner>>>>() {
@Override
public Observable<ServiceResponse<Page<AutoApprovedPrivateLinkServiceInner>>> call(Response<ResponseBody> response) {
try {
ServiceResponse<PageImpl<AutoApprovedPrivateLinkServiceInner>> result = listAutoApprovedPrivateLinkServicesNextDelegate(response);
return Observable.just(new ServiceResponse<Page<AutoApprovedPrivateLinkServiceInner>>(result.body(), result.response()));
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<PageImpl<AutoApprovedPrivateLinkServiceInner>> listAutoApprovedPrivateLinkServicesNextDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<PageImpl<AutoApprovedPrivateLinkServiceInner>, CloudException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<PageImpl<AutoApprovedPrivateLinkServiceInner>>() { }.getType())
.registerError(CloudException.class)
.build(response);
}
/**
* Returns all of the private link service ids that can be linked to a Private Endpoint with auto approved in this subscription in this region.
*
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws CloudException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the PagedList<AutoApprovedPrivateLinkServiceInner> object if successful.
*/
public PagedList<AutoApprovedPrivateLinkServiceInner> listAutoApprovedPrivateLinkServicesByResourceGroupNext(final String nextPageLink) {
ServiceResponse<Page<AutoApprovedPrivateLinkServiceInner>> response = listAutoApprovedPrivateLinkServicesByResourceGroupNextSinglePageAsync(nextPageLink).toBlocking().single();
return new PagedList<AutoApprovedPrivateLinkServiceInner>(response.body()) {
@Override
public Page<AutoApprovedPrivateLinkServiceInner> nextPage(String nextPageLink) {
return listAutoApprovedPrivateLinkServicesByResourceGroupNextSinglePageAsync(nextPageLink).toBlocking().single().body();
}
};
}
/**
* Returns all of the private link service ids that can be linked to a Private Endpoint with auto approved in this subscription in this region.
*
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param serviceFuture the ServiceFuture object tracking the Retrofit calls
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<List<AutoApprovedPrivateLinkServiceInner>> listAutoApprovedPrivateLinkServicesByResourceGroupNextAsync(final String nextPageLink, final ServiceFuture<List<AutoApprovedPrivateLinkServiceInner>> serviceFuture, final ListOperationCallback<AutoApprovedPrivateLinkServiceInner> serviceCallback) {
return AzureServiceFuture.fromPageResponse(
listAutoApprovedPrivateLinkServicesByResourceGroupNextSinglePageAsync(nextPageLink),
new Func1<String, Observable<ServiceResponse<Page<AutoApprovedPrivateLinkServiceInner>>>>() {
@Override
public Observable<ServiceResponse<Page<AutoApprovedPrivateLinkServiceInner>>> call(String nextPageLink) {
return listAutoApprovedPrivateLinkServicesByResourceGroupNextSinglePageAsync(nextPageLink);
}
},
serviceCallback);
}
/**
* Returns all of the private link service ids that can be linked to a Private Endpoint with auto approved in this subscription in this region.
*
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PagedList<AutoApprovedPrivateLinkServiceInner> object
*/
public Observable<Page<AutoApprovedPrivateLinkServiceInner>> listAutoApprovedPrivateLinkServicesByResourceGroupNextAsync(final String nextPageLink) {
return listAutoApprovedPrivateLinkServicesByResourceGroupNextWithServiceResponseAsync(nextPageLink)
.map(new Func1<ServiceResponse<Page<AutoApprovedPrivateLinkServiceInner>>, Page<AutoApprovedPrivateLinkServiceInner>>() {
@Override
public Page<AutoApprovedPrivateLinkServiceInner> call(ServiceResponse<Page<AutoApprovedPrivateLinkServiceInner>> response) {
return response.body();
}
});
}
/**
* Returns all of the private link service ids that can be linked to a Private Endpoint with auto approved in this subscription in this region.
*
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the PagedList<AutoApprovedPrivateLinkServiceInner> object
*/
public Observable<ServiceResponse<Page<AutoApprovedPrivateLinkServiceInner>>> listAutoApprovedPrivateLinkServicesByResourceGroupNextWithServiceResponseAsync(final String nextPageLink) {
return listAutoApprovedPrivateLinkServicesByResourceGroupNextSinglePageAsync(nextPageLink)
.concatMap(new Func1<ServiceResponse<Page<AutoApprovedPrivateLinkServiceInner>>, Observable<ServiceResponse<Page<AutoApprovedPrivateLinkServiceInner>>>>() {
@Override
public Observable<ServiceResponse<Page<AutoApprovedPrivateLinkServiceInner>>> call(ServiceResponse<Page<AutoApprovedPrivateLinkServiceInner>> page) {
String nextPageLink = page.body().nextPageLink();
if (nextPageLink == null) {
return Observable.just(page);
}
return Observable.just(page).concatWith(listAutoApprovedPrivateLinkServicesByResourceGroupNextWithServiceResponseAsync(nextPageLink));
}
});
}
/**
* Returns all of the private link service ids that can be linked to a Private Endpoint with auto approved in this subscription in this region.
*
ServiceResponse<PageImpl<AutoApprovedPrivateLinkServiceInner>> * @param nextPageLink The NextLink from the previous successful call to List operation.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the PagedList<AutoApprovedPrivateLinkServiceInner> object wrapped in {@link ServiceResponse} if successful.
*/
public Observable<ServiceResponse<Page<AutoApprovedPrivateLinkServiceInner>>> listAutoApprovedPrivateLinkServicesByResourceGroupNextSinglePageAsync(final String nextPageLink) {
if (nextPageLink == null) {
throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null.");
}
String nextUrl = String.format("%s", nextPageLink);
return service.listAutoApprovedPrivateLinkServicesByResourceGroupNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<AutoApprovedPrivateLinkServiceInner>>>>() {
@Override
public Observable<ServiceResponse<Page<AutoApprovedPrivateLinkServiceInner>>> call(Response<ResponseBody> response) {
try {
ServiceResponse<PageImpl<AutoApprovedPrivateLinkServiceInner>> result = listAutoApprovedPrivateLinkServicesByResourceGroupNextDelegate(response);
return Observable.just(new ServiceResponse<Page<AutoApprovedPrivateLinkServiceInner>>(result.body(), result.response()));
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponse<PageImpl<AutoApprovedPrivateLinkServiceInner>> listAutoApprovedPrivateLinkServicesByResourceGroupNextDelegate(Response<ResponseBody> response) throws CloudException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<PageImpl<AutoApprovedPrivateLinkServiceInner>, CloudException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<PageImpl<AutoApprovedPrivateLinkServiceInner>>() { }.getType())
.registerError(CloudException.class)
.build(response);
}
}
| mit |
tariq1890/tacoco | src/main/java/org/spideruci/tacoco/analysis/InstrumenterConfig.java | 1489 | package org.spideruci.tacoco.analysis;
public class InstrumenterConfig {
private final String location;
private final String arguments;
private final String memory;
private final String classPath;
private final String xbootpath;
private final boolean prependBootpath;
private final static String JAVAAGENT = "-javaagent:";
private final static String XBOOTCLASSPATH_P = "-Xbootclasspath/p:";
private final static String XBOOTCLASSPATH_A = "-Xbootclasspath/a:";
public static InstrumenterConfig get(String location, String arguments) {
return get(location, arguments, null);
}
public static InstrumenterConfig get(String location, String arguments, String xbootpath) {
return new InstrumenterConfig(location, arguments, null, xbootpath);
}
private InstrumenterConfig(String location, String arguments, String classPath, String xbootpath) {
this.location = location;
this.arguments = arguments;
this.classPath = classPath;
this.xbootpath = xbootpath;
this.memory = "-Xms2048M";
this.prependBootpath = true;
}
public String buildJavaagentArg() {
String agentOpt = JAVAAGENT;
agentOpt += location;
agentOpt += "=" + arguments;
return agentOpt;
}
public String xbootclassPathArg() {
String xbootpathOpt =
this.prependBootpath ? XBOOTCLASSPATH_P : XBOOTCLASSPATH_A;
xbootpathOpt += xbootpath;
return xbootpathOpt;
}
public String getClassPath() {
return this.classPath;
}
public String getMemory() {
return this.memory;
}
}
| mit |
HurtMePlenty/spotifyImporter | src/main/java/com/wrapper/spotify/exceptions/WebApiException.java | 208 | package com.wrapper.spotify.exceptions;
public class WebApiException extends Exception {
public WebApiException(String message) {
super(message);
}
public WebApiException() {
super();
}
}
| mit |
plattformbrandenburg/ldadmin | src/main/java/de/piratenpartei/berlin/ldadmin/dbaccess/generated/tables/daos/SessionDao.java | 4672 | /**
* This class is generated by jOOQ
*/
package de.piratenpartei.berlin.ldadmin.dbaccess.generated.tables.daos;
/**
* This class is generated by jOOQ.
*/
@javax.annotation.Generated(value = { "http://www.jooq.org", "3.4.4" },
comments = "This class is generated by jOOQ")
@java.lang.SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class SessionDao extends org.jooq.impl.DAOImpl<de.piratenpartei.berlin.ldadmin.dbaccess.generated.tables.records.SessionRecord, de.piratenpartei.berlin.ldadmin.dbaccess.generated.tables.pojos.Session, java.lang.String> {
/**
* Create a new SessionDao without any configuration
*/
public SessionDao() {
super(de.piratenpartei.berlin.ldadmin.dbaccess.generated.tables.Session.SESSION, de.piratenpartei.berlin.ldadmin.dbaccess.generated.tables.pojos.Session.class);
}
/**
* Create a new SessionDao with an attached configuration
*/
public SessionDao(org.jooq.Configuration configuration) {
super(de.piratenpartei.berlin.ldadmin.dbaccess.generated.tables.Session.SESSION, de.piratenpartei.berlin.ldadmin.dbaccess.generated.tables.pojos.Session.class, configuration);
}
/**
* {@inheritDoc}
*/
@Override
protected java.lang.String getId(de.piratenpartei.berlin.ldadmin.dbaccess.generated.tables.pojos.Session object) {
return object.getIdent();
}
/**
* Fetch records that have <code>ident IN (values)</code>
*/
public java.util.List<de.piratenpartei.berlin.ldadmin.dbaccess.generated.tables.pojos.Session> fetchByIdent(java.lang.String... values) {
return fetch(de.piratenpartei.berlin.ldadmin.dbaccess.generated.tables.Session.SESSION.IDENT, values);
}
/**
* Fetch a unique record that has <code>ident = value</code>
*/
public de.piratenpartei.berlin.ldadmin.dbaccess.generated.tables.pojos.Session fetchOneByIdent(java.lang.String value) {
return fetchOne(de.piratenpartei.berlin.ldadmin.dbaccess.generated.tables.Session.SESSION.IDENT, value);
}
/**
* Fetch records that have <code>additional_secret IN (values)</code>
*/
public java.util.List<de.piratenpartei.berlin.ldadmin.dbaccess.generated.tables.pojos.Session> fetchByAdditionalSecret(java.lang.String... values) {
return fetch(de.piratenpartei.berlin.ldadmin.dbaccess.generated.tables.Session.SESSION.ADDITIONAL_SECRET, values);
}
/**
* Fetch records that have <code>expiry IN (values)</code>
*/
public java.util.List<de.piratenpartei.berlin.ldadmin.dbaccess.generated.tables.pojos.Session> fetchByExpiry(java.sql.Timestamp... values) {
return fetch(de.piratenpartei.berlin.ldadmin.dbaccess.generated.tables.Session.SESSION.EXPIRY, values);
}
/**
* Fetch records that have <code>member_id IN (values)</code>
*/
public java.util.List<de.piratenpartei.berlin.ldadmin.dbaccess.generated.tables.pojos.Session> fetchByMemberId(java.lang.Long... values) {
return fetch(de.piratenpartei.berlin.ldadmin.dbaccess.generated.tables.Session.SESSION.MEMBER_ID, values);
}
/**
* Fetch records that have <code>authority IN (values)</code>
*/
public java.util.List<de.piratenpartei.berlin.ldadmin.dbaccess.generated.tables.pojos.Session> fetchByAuthority(java.lang.String... values) {
return fetch(de.piratenpartei.berlin.ldadmin.dbaccess.generated.tables.Session.SESSION.AUTHORITY, values);
}
/**
* Fetch records that have <code>authority_uid IN (values)</code>
*/
public java.util.List<de.piratenpartei.berlin.ldadmin.dbaccess.generated.tables.pojos.Session> fetchByAuthorityUid(java.lang.String... values) {
return fetch(de.piratenpartei.berlin.ldadmin.dbaccess.generated.tables.Session.SESSION.AUTHORITY_UID, values);
}
/**
* Fetch records that have <code>authority_login IN (values)</code>
*/
public java.util.List<de.piratenpartei.berlin.ldadmin.dbaccess.generated.tables.pojos.Session> fetchByAuthorityLogin(java.lang.String... values) {
return fetch(de.piratenpartei.berlin.ldadmin.dbaccess.generated.tables.Session.SESSION.AUTHORITY_LOGIN, values);
}
/**
* Fetch records that have <code>needs_delegation_check IN (values)</code>
*/
public java.util.List<de.piratenpartei.berlin.ldadmin.dbaccess.generated.tables.pojos.Session> fetchByNeedsDelegationCheck(java.lang.Boolean... values) {
return fetch(de.piratenpartei.berlin.ldadmin.dbaccess.generated.tables.Session.SESSION.NEEDS_DELEGATION_CHECK, values);
}
/**
* Fetch records that have <code>lang IN (values)</code>
*/
public java.util.List<de.piratenpartei.berlin.ldadmin.dbaccess.generated.tables.pojos.Session> fetchByLang(java.lang.String... values) {
return fetch(de.piratenpartei.berlin.ldadmin.dbaccess.generated.tables.Session.SESSION.LANG, values);
}
}
| mit |
paoloambrosio/cucumber-jvm | core/src/test/java/cucumber/runtime/formatter/JUnitFormatterTest.java | 31989 | package cucumber.runtime.formatter;
import cucumber.api.Result;
import cucumber.runner.TimeServiceStub;
import cucumber.runtime.Backend;
import cucumber.runtime.Runtime;
import cucumber.runtime.RuntimeOptions;
import cucumber.runtime.TestHelper;
import cucumber.runtime.Utils;
import cucumber.runtime.io.ClasspathResourceLoader;
import cucumber.runtime.model.CucumberFeature;
import cucumber.runtime.snippets.FunctionNameGenerator;
import gherkin.pickles.PickleStep;
import org.custommonkey.xmlunit.Diff;
import org.custommonkey.xmlunit.XMLUnit;
import org.junit.AssumptionViolatedException;
import org.junit.Test;
import org.xml.sax.SAXException;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.AbstractMap.SimpleEntry;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import static cucumber.runtime.TestHelper.result;
import static java.util.Arrays.asList;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class JUnitFormatterTest {
@Test
public void featureSimpleTest() throws Exception {
File report = runFeaturesWithJunitFormatter(asList("cucumber/runtime/formatter/JUnitFormatterTest_1.feature"));
assertXmlEqual("cucumber/runtime/formatter/JUnitFormatterTest_1.report.xml", report);
}
@Test
public void featureWithBackgroundTest() throws Exception {
File report = runFeaturesWithJunitFormatter(asList("cucumber/runtime/formatter/JUnitFormatterTest_2.feature"));
assertXmlEqual("cucumber/runtime/formatter/JUnitFormatterTest_2.report.xml", report);
}
@Test
public void featureWithOutlineTest() throws Exception {
File report = runFeaturesWithJunitFormatter(asList("cucumber/runtime/formatter/JUnitFormatterTest_3.feature"));
assertXmlEqual("cucumber/runtime/formatter/JUnitFormatterTest_3.report.xml", report);
}
@Test
public void featureSimpleStrictTest() throws Exception {
boolean strict = true;
File report = runFeaturesWithJunitFormatter(asList("cucumber/runtime/formatter/JUnitFormatterTest_1.feature"), strict);
assertXmlEqual("cucumber/runtime/formatter/JUnitFormatterTest_1_strict.report.xml", report);
}
@Test
public void should_format_passed_scenario() throws Throwable {
CucumberFeature feature = TestHelper.feature("path/test.feature",
"Feature: feature name\n" +
" Scenario: scenario name\n" +
" Given first step\n" +
" When second step\n" +
" Then third step\n");
Map<String, Result> stepsToResult = new HashMap<String, Result>();
stepsToResult.put("first step", result("passed"));
stepsToResult.put("second step", result("passed"));
stepsToResult.put("third step", result("passed"));
long stepDuration = milliSeconds(1);
String formatterOutput = runFeatureWithJUnitFormatter(feature, stepsToResult, stepDuration);
String expected = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n" +
"<testsuite failures=\"0\" name=\"cucumber.runtime.formatter.JUnitFormatter\" skipped=\"0\" tests=\"1\" time=\"0.003\">\n" +
" <testcase classname=\"feature name\" name=\"scenario name\" time=\"0.003\">\n" +
" <system-out><![CDATA[" +
"Given first step............................................................passed\n" +
"When second step............................................................passed\n" +
"Then third step.............................................................passed\n" +
"]]></system-out>\n" +
" </testcase>\n" +
"</testsuite>\n";
assertXmlEqual(expected, formatterOutput);
}
@Test
public void should_format_skipped_scenario() throws Throwable {
CucumberFeature feature = TestHelper.feature("path/test.feature",
"Feature: feature name\n" +
" Scenario: scenario name\n" +
" Given first step\n" +
" When second step\n" +
" Then third step\n");
Map<String, Result> stepsToResult = new HashMap<String, Result>();
Throwable exception = new AssumptionViolatedException("message");
stepsToResult.put("first step", result("skipped", exception));
stepsToResult.put("second step", result("skipped"));
stepsToResult.put("third step", result("skipped"));
long stepDuration = milliSeconds(1);
String formatterOutput = runFeatureWithJUnitFormatter(feature, stepsToResult, stepDuration);
String stackTrace = getStackTrace(exception);
String expected = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n" +
"<testsuite failures=\"0\" name=\"cucumber.runtime.formatter.JUnitFormatter\" skipped=\"1\" tests=\"1\" time=\"0.003\">\n" +
" <testcase classname=\"feature name\" name=\"scenario name\" time=\"0.003\">\n" +
" <skipped message=\"" + stackTrace.replace("\n\t", " 	").replaceAll("\r", " ") + "\"><![CDATA[" +
"Given first step............................................................skipped\n" +
"When second step............................................................skipped\n" +
"Then third step.............................................................skipped\n" +
"\n" +
"StackTrace:\n" +
stackTrace +
"]]></skipped>\n" +
" </testcase>\n" +
"</testsuite>\n";
assertXmlEqual(expected, formatterOutput);
}
@Test
public void should_format_pending_scenario() throws Throwable {
CucumberFeature feature = TestHelper.feature("path/test.feature",
"Feature: feature name\n" +
" Scenario: scenario name\n" +
" Given first step\n" +
" When second step\n" +
" Then third step\n");
Map<String, Result> stepsToResult = new HashMap<String, Result>();
stepsToResult.put("first step", result("pending"));
stepsToResult.put("second step", result("skipped"));
stepsToResult.put("third step", result("undefined"));
long stepDuration = milliSeconds(1);
String formatterOutput = runFeatureWithJUnitFormatter(feature, stepsToResult, stepDuration);
String expected = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n" +
"<testsuite failures=\"0\" name=\"cucumber.runtime.formatter.JUnitFormatter\" skipped=\"1\" tests=\"1\" time=\"0.003\">\n" +
" <testcase classname=\"feature name\" name=\"scenario name\" time=\"0.003\">\n" +
" <skipped><![CDATA[" +
"Given first step............................................................pending\n" +
"When second step............................................................skipped\n" +
"Then third step.............................................................undefined\n" +
"]]></skipped>\n" +
" </testcase>\n" +
"</testsuite>\n";
assertXmlEqual(expected, formatterOutput);
}
@Test
public void should_format_failed_scenario() throws Throwable {
CucumberFeature feature = TestHelper.feature("path/test.feature",
"Feature: feature name\n" +
" Scenario: scenario name\n" +
" Given first step\n" +
" When second step\n" +
" Then third step\n");
Map<String, Result> stepsToResult = new HashMap<String, Result>();
stepsToResult.put("first step", result("passed"));
stepsToResult.put("second step", result("passed"));
stepsToResult.put("third step", result("failed"));
long stepDuration = milliSeconds(1);
String formatterOutput = runFeatureWithJUnitFormatter(feature, stepsToResult, stepDuration);
String expected = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n" +
"<testsuite failures=\"1\" name=\"cucumber.runtime.formatter.JUnitFormatter\" skipped=\"0\" tests=\"1\" time=\"0.003\">\n" +
" <testcase classname=\"feature name\" name=\"scenario name\" time=\"0.003\">\n" +
" <failure message=\"the stack trace\"><![CDATA[" +
"Given first step............................................................passed\n" +
"When second step............................................................passed\n" +
"Then third step.............................................................failed\n" +
"\n" +
"StackTrace:\n" +
"the stack trace" +
"]]></failure>\n" +
" </testcase>\n" +
"</testsuite>\n";
assertXmlEqual(expected, formatterOutput);
}
@Test
public void should_handle_failure_in_before_hook() throws Throwable {
CucumberFeature feature = TestHelper.feature("path/test.feature",
"Feature: feature name\n" +
" Scenario: scenario name\n" +
" Given first step\n" +
" When second step\n" +
" Then third step\n");
Map<String, Result> stepsToResult = new HashMap<String, Result>();
stepsToResult.put("first step", result("passed"));
stepsToResult.put("second step", result("passed"));
stepsToResult.put("third step", result("passed"));
List<SimpleEntry<String, Result>> hooks = new ArrayList<SimpleEntry<String, Result>>();
hooks.add(TestHelper.hookEntry("before", result("failed")));
long stepHookDuration = milliSeconds(1);
String formatterOutput = runFeatureWithJUnitFormatter(feature, stepsToResult, hooks, stepHookDuration);
String expected = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n" +
"<testsuite failures=\"1\" name=\"cucumber.runtime.formatter.JUnitFormatter\" skipped=\"0\" tests=\"1\" time=\"0.004\">\n" +
" <testcase classname=\"feature name\" name=\"scenario name\" time=\"0.004\">\n" +
" <failure message=\"the stack trace\"><![CDATA[" +
"Given first step............................................................skipped\n" +
"When second step............................................................skipped\n" +
"Then third step.............................................................skipped\n" +
"\n" +
"StackTrace:\n" +
"the stack trace" +
"]]></failure>\n" +
" </testcase>\n" +
"</testsuite>\n";
assertXmlEqual(expected, formatterOutput);
}
@Test
public void should_handle_pending_in_before_hook() throws Throwable {
CucumberFeature feature = TestHelper.feature("path/test.feature",
"Feature: feature name\n" +
" Scenario: scenario name\n" +
" Given first step\n" +
" When second step\n" +
" Then third step\n");
Map<String, Result> stepsToResult = new HashMap<String, Result>();
stepsToResult.put("first step", result("skipped"));
stepsToResult.put("second step", result("skipped"));
stepsToResult.put("third step", result("skipped"));
List<SimpleEntry<String, Result>> hooks = new ArrayList<SimpleEntry<String, Result>>();
hooks.add(TestHelper.hookEntry("before", result("pending")));
long stepHookDuration = milliSeconds(1);
String formatterOutput = runFeatureWithJUnitFormatter(feature, stepsToResult, hooks, stepHookDuration);
String expected = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n" +
"<testsuite failures=\"0\" name=\"cucumber.runtime.formatter.JUnitFormatter\" skipped=\"1\" tests=\"1\" time=\"0.004\">\n" +
" <testcase classname=\"feature name\" name=\"scenario name\" time=\"0.004\">\n" +
" <skipped><![CDATA[" +
"Given first step............................................................skipped\n" +
"When second step............................................................skipped\n" +
"Then third step.............................................................skipped\n" +
"]]></skipped>\n" +
" </testcase>\n" +
"</testsuite>\n";
assertXmlEqual(expected, formatterOutput);
}
@Test
public void should_handle_failure_in_before_hook_with_background() throws Throwable {
CucumberFeature feature = TestHelper.feature("path/test.feature",
"Feature: feature name\n" +
" Background: background name\n" +
" Given first step\n" +
" Scenario: scenario name\n" +
" When second step\n" +
" Then third step\n");
Map<String, Result> stepsToResult = new HashMap<String, Result>();
stepsToResult.put("first step", result("passed"));
stepsToResult.put("second step", result("passed"));
stepsToResult.put("third step", result("passed"));
List<SimpleEntry<String, Result>> hooks = new ArrayList<SimpleEntry<String, Result>>();
hooks.add(TestHelper.hookEntry("before", result("failed")));
long stepHookDuration = milliSeconds(1);
String formatterOutput = runFeatureWithJUnitFormatter(feature, stepsToResult, hooks, stepHookDuration);
String expected = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n" +
"<testsuite failures=\"1\" name=\"cucumber.runtime.formatter.JUnitFormatter\" skipped=\"0\" tests=\"1\" time=\"0.004\">\n" +
" <testcase classname=\"feature name\" name=\"scenario name\" time=\"0.004\">\n" +
" <failure message=\"the stack trace\"><![CDATA[" +
"Given first step............................................................skipped\n" +
"When second step............................................................skipped\n" +
"Then third step.............................................................skipped\n" +
"\n" +
"StackTrace:\n" +
"the stack trace" +
"]]></failure>\n" +
" </testcase>\n" +
"</testsuite>\n";
assertXmlEqual(expected, formatterOutput);
}
@Test
public void should_handle_failure_in_after_hook() throws Throwable {
CucumberFeature feature = TestHelper.feature("path/test.feature",
"Feature: feature name\n" +
" Scenario: scenario name\n" +
" Given first step\n" +
" When second step\n" +
" Then third step\n");
Map<String, Result> stepsToResult = new HashMap<String, Result>();
stepsToResult.put("first step", result("passed"));
stepsToResult.put("second step", result("passed"));
stepsToResult.put("third step", result("passed"));
List<SimpleEntry<String, Result>> hooks = new ArrayList<SimpleEntry<String, Result>>();
hooks.add(TestHelper.hookEntry("after", result("failed")));
long stepHookDuration = milliSeconds(1);
String formatterOutput = runFeatureWithJUnitFormatter(feature, stepsToResult, hooks, stepHookDuration);
String expected = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n" +
"<testsuite failures=\"1\" name=\"cucumber.runtime.formatter.JUnitFormatter\" skipped=\"0\" tests=\"1\" time=\"0.004\">\n" +
" <testcase classname=\"feature name\" name=\"scenario name\" time=\"0.004\">\n" +
" <failure message=\"the stack trace\"><![CDATA[" +
"Given first step............................................................passed\n" +
"When second step............................................................passed\n" +
"Then third step.............................................................passed\n" +
"\n" +
"StackTrace:\n" +
"the stack trace" +
"]]></failure>\n" +
" </testcase>\n" +
"</testsuite>\n";
assertXmlEqual(expected, formatterOutput);
}
@Test
public void should_accumulate_time_from_steps_and_hooks() throws Throwable {
CucumberFeature feature = TestHelper.feature("path/test.feature",
"Feature: feature name\n" +
" Scenario: scenario name\n" +
" * first step\n" +
" * second step\n");
Map<String, Result> stepsToResult = new HashMap<String, Result>();
stepsToResult.put("first step", result("passed"));
stepsToResult.put("second step", result("passed"));
List<SimpleEntry<String, Result>> hooks = new ArrayList<SimpleEntry<String, Result>>();
hooks.add(TestHelper.hookEntry("before", result("passed")));
hooks.add(TestHelper.hookEntry("after", result("passed")));
long stepHookDuration = milliSeconds(1);
String formatterOutput = runFeatureWithJUnitFormatter(feature, stepsToResult, hooks, stepHookDuration);
String expected = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n" +
"<testsuite failures=\"0\" name=\"cucumber.runtime.formatter.JUnitFormatter\" skipped=\"0\" tests=\"1\" time=\"0.004\">\n" +
" <testcase classname=\"feature name\" name=\"scenario name\" time=\"0.004\">\n" +
" <system-out><![CDATA[" +
"* first step................................................................passed\n" +
"* second step...............................................................passed\n" +
"]]></system-out>\n" +
" </testcase>\n" +
"</testsuite>\n";
assertXmlEqual(expected, formatterOutput);
}
@Test
public void should_format_scenario_outlines() throws Throwable {
CucumberFeature feature = TestHelper.feature("path/test.feature",
"Feature: feature name\n" +
" Scenario Outline: outline_name\n" +
" Given first step \"<arg>\"\n" +
" When second step\n" +
" Then third step\n\n" +
" Examples: examples\n" +
" | arg |\n" +
" | a |\n" +
" | b |\n");
Map<String, Result> stepsToResult = new HashMap<String, Result>();
stepsToResult.put("first step \"a\"", result("passed"));
stepsToResult.put("first step \"b\"", result("passed"));
stepsToResult.put("second step", result("passed"));
stepsToResult.put("third step", result("passed"));
long stepDuration = milliSeconds(1);
String formatterOutput = runFeatureWithJUnitFormatter(feature, stepsToResult, stepDuration);
String expected = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n" +
"<testsuite failures=\"0\" name=\"cucumber.runtime.formatter.JUnitFormatter\" skipped=\"0\" tests=\"2\" time=\"0.006\">\n" +
" <testcase classname=\"feature name\" name=\"outline_name\" time=\"0.003\">\n" +
" <system-out><![CDATA[" +
"Given first step \"a\"........................................................passed\n" +
"When second step............................................................passed\n" +
"Then third step.............................................................passed\n" +
"]]></system-out>\n" +
" </testcase>\n" +
" <testcase classname=\"feature name\" name=\"outline_name_2\" time=\"0.003\">\n" +
" <system-out><![CDATA[" +
"Given first step \"b\"........................................................passed\n" +
"When second step............................................................passed\n" +
"Then third step.............................................................passed\n" +
"]]></system-out>\n" +
" </testcase>\n" +
"</testsuite>\n";
assertXmlEqual(expected, formatterOutput);
}
@Test
public void should_format_scenario_outlines_with_multiple_examples() throws Throwable {
CucumberFeature feature = TestHelper.feature("path/test.feature",
"Feature: feature name\n" +
" Scenario Outline: outline name\n" +
" Given first step \"<arg>\"\n" +
" When second step\n" +
" Then third step\n\n" +
" Examples: examples 1\n" +
" | arg |\n" +
" | a |\n" +
" | b |\n\n" +
" Examples: examples 2\n" +
" | arg |\n" +
" | c |\n" +
" | d |\n");
Map<String, Result> stepsToResult = new HashMap<String, Result>();
stepsToResult.put("first step \"a\"", result("passed"));
stepsToResult.put("first step \"b\"", result("passed"));
stepsToResult.put("first step \"c\"", result("passed"));
stepsToResult.put("first step \"d\"", result("passed"));
stepsToResult.put("second step", result("passed"));
stepsToResult.put("third step", result("passed"));
long stepDuration = milliSeconds(1);
String formatterOutput = runFeatureWithJUnitFormatter(feature, stepsToResult, stepDuration);
String expected = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n" +
"<testsuite failures=\"0\" name=\"cucumber.runtime.formatter.JUnitFormatter\" skipped=\"0\" tests=\"4\" time=\"0.012\">\n" +
" <testcase classname=\"feature name\" name=\"outline name\" time=\"0.003\">\n" +
" <system-out><![CDATA[" +
"Given first step \"a\"........................................................passed\n" +
"When second step............................................................passed\n" +
"Then third step.............................................................passed\n" +
"]]></system-out>\n" +
" </testcase>\n" +
" <testcase classname=\"feature name\" name=\"outline name 2\" time=\"0.003\">\n" +
" <system-out><![CDATA[" +
"Given first step \"b\"........................................................passed\n" +
"When second step............................................................passed\n" +
"Then third step.............................................................passed\n" +
"]]></system-out>\n" +
" </testcase>\n" +
" <testcase classname=\"feature name\" name=\"outline name 3\" time=\"0.003\">\n" +
" <system-out><![CDATA[" +
"Given first step \"c\"........................................................passed\n" +
"When second step............................................................passed\n" +
"Then third step.............................................................passed\n" +
"]]></system-out>\n" +
" </testcase>\n" +
" <testcase classname=\"feature name\" name=\"outline name 4\" time=\"0.003\">\n" +
" <system-out><![CDATA[" +
"Given first step \"d\"........................................................passed\n" +
"When second step............................................................passed\n" +
"Then third step.............................................................passed\n" +
"]]></system-out>\n" +
" </testcase>\n" +
"</testsuite>\n";
assertXmlEqual(expected, formatterOutput);
}
@Test
public void should_format_scenario_outlines_with_arguments_in_name() throws Throwable {
CucumberFeature feature = TestHelper.feature("path/test.feature",
"Feature: feature name\n" +
" Scenario Outline: outline name <arg>\n" +
" Given first step \"<arg>\"\n" +
" When second step\n" +
" Then third step\n\n" +
" Examples: examples 1\n" +
" | arg |\n" +
" | a |\n" +
" | b |\n");
Map<String, Result> stepsToResult = new HashMap<String, Result>();
stepsToResult.put("first step \"a\"", result("passed"));
stepsToResult.put("first step \"b\"", result("passed"));
stepsToResult.put("second step", result("passed"));
stepsToResult.put("third step", result("passed"));
long stepDuration = milliSeconds(1);
String formatterOutput = runFeatureWithJUnitFormatter(feature, stepsToResult, stepDuration);
String expected = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n" +
"<testsuite failures=\"0\" name=\"cucumber.runtime.formatter.JUnitFormatter\" skipped=\"0\" tests=\"2\" time=\"0.006\">\n" +
" <testcase classname=\"feature name\" name=\"outline name a\" time=\"0.003\">\n" +
" <system-out><![CDATA[" +
"Given first step \"a\"........................................................passed\n" +
"When second step............................................................passed\n" +
"Then third step.............................................................passed\n" +
"]]></system-out>\n" +
" </testcase>\n" +
" <testcase classname=\"feature name\" name=\"outline name b\" time=\"0.003\">\n" +
" <system-out><![CDATA[" +
"Given first step \"b\"........................................................passed\n" +
"When second step............................................................passed\n" +
"Then third step.............................................................passed\n" +
"]]></system-out>\n" +
" </testcase>\n" +
"</testsuite>\n";
assertXmlEqual(expected, formatterOutput);
}
private File runFeaturesWithJunitFormatter(final List<String> featurePaths) throws IOException {
return runFeaturesWithJunitFormatter(featurePaths, false);
}
private File runFeaturesWithJunitFormatter(final List<String> featurePaths, boolean strict) throws IOException {
File report = File.createTempFile("cucumber-jvm-junit", "xml");
final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
final ClasspathResourceLoader resourceLoader = new ClasspathResourceLoader(classLoader);
List<String> args = new ArrayList<String>();
if (strict) {
args.add("--strict");
}
args.add("--plugin");
args.add("junit:" + report.getAbsolutePath());
args.addAll(featurePaths);
RuntimeOptions runtimeOptions = new RuntimeOptions(args);
Backend backend = mock(Backend.class);
when(backend.getSnippet(any(PickleStep.class), anyString(), any(FunctionNameGenerator.class))).thenReturn("TEST SNIPPET");
final cucumber.runtime.Runtime runtime = new Runtime(resourceLoader, classLoader, asList(backend), runtimeOptions, new TimeServiceStub(0L), null);
runtime.run();
return report;
}
private String runFeatureWithJUnitFormatter(final CucumberFeature feature) throws Throwable {
return runFeatureWithJUnitFormatter(feature, new HashMap<String, Result>(), 0L);
}
private String runFeatureWithJUnitFormatter(final CucumberFeature feature, final Map<String, Result> stepsToResult, final long stepHookDuration)
throws Throwable {
return runFeatureWithJUnitFormatter(feature, stepsToResult, Collections.<SimpleEntry<String, Result>>emptyList(), stepHookDuration);
}
private String runFeatureWithJUnitFormatter(final CucumberFeature feature, final Map<String, Result> stepsToResult,
final List<SimpleEntry<String, Result>> hooks, final long stepHookDuration) throws Throwable {
final File report = File.createTempFile("cucumber-jvm-junit", ".xml");
final JUnitFormatter junitFormatter = createJUnitFormatter(report);
TestHelper.runFeatureWithFormatter(feature, stepsToResult, hooks, stepHookDuration, junitFormatter);
Scanner scanner = new Scanner(new FileInputStream(report), "UTF-8");
String formatterOutput = scanner.useDelimiter("\\A").next();
scanner.close();
return formatterOutput;
}
private void assertXmlEqual(String expectedPath, File actual) throws IOException, ParserConfigurationException, SAXException {
XMLUnit.setIgnoreWhitespace(true);
InputStreamReader control = new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream(expectedPath), "UTF-8");
Diff diff = new Diff(control, new FileReader(actual));
assertTrue("XML files are similar " + diff, diff.identical());
}
private void assertXmlEqual(String expected, String actual) throws SAXException, IOException {
XMLUnit.setIgnoreWhitespace(true);
Diff diff = new Diff(expected, actual);
assertTrue("XML files are similar " + diff + "\nFormatterOutput = " + actual, diff.identical());
}
private JUnitFormatter createJUnitFormatter(final File report) throws IOException {
return new JUnitFormatter(Utils.toURL(report.getAbsolutePath()));
}
private Long milliSeconds(int milliSeconds) {
return milliSeconds * 1000000L;
}
private String getStackTrace(Throwable exception) {
StringWriter sw = new StringWriter();
exception.printStackTrace(new PrintWriter(sw));
return sw.toString();
}
}
| mit |
eamonfoy/trello-to-markdown | src/main/java/de/neuland/jade4j/util/CharacterParser.java | 22976 | package de.neuland.jade4j.util;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CharacterParser {
private Pattern pattern = Pattern.compile("^\\w+\\b");
// function parse(src, state, options) {
// options = options || {};
// state = state || exports.defaultState();
// var start = options.start || 0;
// var end = options.end || src.length;
// var index = start;
// while (index < end) {
// if (state.roundDepth < 0 || state.curlyDepth < 0 || state.squareDepth < 0) {
// throw new SyntaxError('Mismatched Bracket: ' + src[index - 1]);
// }
// exports.parseChar(src[index++], state);
// }
// return state;
// }
public static class SyntaxError extends Exception{
/**
* Constructs a new exception with the specified detail message. The
* cause is not initialized, and may subsequently be initialized by
* a call to {@link #initCause}.
*
* @param message the detail message. The detail message is saved for
* later retrieval by the {@link #getMessage()} method.
*/
public SyntaxError(String message) {
super(message);
}
}
public State parse(String src) throws SyntaxError {
Options options = new Options();
options.setEnd(src.length());
return this.parse(src,this.defaultState(),options);
}
public State parse(String src,State state) throws SyntaxError {
Options options = new Options();
options.setEnd(src.length());
return this.parse(src,state,options);
}
public State parse(String src,State state,Options options) throws SyntaxError {
if(options == null) {
options = new Options();
options.setEnd(src.length());
}
if(state == null)
state = this.defaultState();
int start = options.getStart();
int end = options.getEnd();
int index = start;
while (index < end) {
if (state.getRoundDepth() < 0 || state.getCurlyDepth() < 0 || state.getSquareDepth() < 0) {
throw new SyntaxError("Mismatched Bracket: " + src.charAt(index - 1));
}
this.parseChar(src.charAt(index++), state);
}
return state;
}
// function parseMax(src, options) {
// options = options || {};
// var start = options.start || 0;
// var index = start;
// var state = exports.defaultState();
// while (state.roundDepth >= 0 && state.curlyDepth >= 0 && state.squareDepth >= 0) {
// if (index >= src.length) {
// throw new Error('The end of the string was reached with no closing bracket found.');
// }
// exports.parseChar(src[index++], state);
// }
// var end = index - 1;
// return {
// start: start,
// end: end,
// src: src.substring(start, end)
// };
// }
public Match parseMax(String src) throws SyntaxError {
Options options = new Options();
return this.parseMax(src, options);
}
public Match parseMax(String src,Options options) throws SyntaxError {
if(options == null)
options = new Options();
int start = options.getStart();
int index = start;
State state = this.defaultState();
while (state.getRoundDepth() >= 0 && state.getCurlyDepth() >= 0 && state.getSquareDepth() >= 0) {
if (index >= src.length()) {
throw new SyntaxError("The end of the string was reached with no closing bracket found.");
}
this.parseChar(src.charAt(index++), state);
}
int end = index - 1;
return new Match(start,end,src.substring(start,end));
}
// var bracketToProp = {
// ')': 'roundDepth',
// '}': 'curlyDepth',
// ']': 'squareDepth'
// };
//
// function parseMaxBracket(src, bracket, options) {
// options = options || {};
// var start = options.start || 0;
// var index = start;
// var state = exports.defaultState();
// var prop = bracketToProp[bracket];
// if (prop === undefined) {
// throw new Error('Bracket specified (' + JSON.stringify(bracket) + ') is not one of ")", "]", or "}";');
// }
// while (state[prop] >= 0) {
// if (index >= src.length) {
// throw new Error('The end of the string was reached with no closing bracket "' + bracket + '" found.');
// }
// exports.parseChar(src[index++], state);
// }
// var end = index - 1;
// return {
// start: start,
// end: end,
// src: src.substring(start, end)
// };
// }
private int getStateProp(State state, char bracket){
if(')' == bracket)
return state.getRoundDepth();
if('}' == bracket)
return state.getCurlyDepth();
if(']' == bracket)
return state.getSquareDepth();
return -1;
}
public Match parseMaxBracket(String src,char bracket) throws SyntaxError {
return this.parseMaxBracket(src,bracket,new Options());
}
public Match parseMaxBracket(String src,char bracket,Options options) throws SyntaxError {
if (options == null)
options = new Options();
int start = options.getStart();
int index = start;
State state = this.defaultState();
if (bracket != ')' && bracket != '}' && bracket != ']') {
throw new SyntaxError("Bracket specified (" + String.valueOf(bracket) + ") is not one of \")\", \"]\", or \"}\"");
}
while (getStateProp(state,bracket) >= 0) {
if (index >= src.length()) {
throw new SyntaxError("The end of the string was reached with no closing bracket \"" + bracket + "\" found.");
}
this.parseChar(src.charAt(index++), state);
}
int end = index - 1;
return new Match(start, end, src.substring(start, end));
}
// function parseUntil(src, delimiter, options) {
// options = options || {};
// var includeLineComment = options.includeLineComment || false;
// var start = options.start || 0;
// var index = start;
// var state = exports.defaultState();
// while (state.isString() || state.regexp || state.blockComment ||
// (!includeLineComment && state.lineComment) || !startsWith(src, delimiter, index)) {
// exports.parseChar(src[index++], state);
// }
// var end = index;
// return {
// start: start,
// end: end,
// src: src.substring(start, end)
// };
// }
public Match parseUntil(String src,String delimiter) {
return this.parseUntil(src,delimiter,new Options());
}
public Match parseUntil(String src,String delimiter,Options options){
if (options == null)
options = new Options();
boolean includeLineComment = options.isIncludeLineComment();
int start = options.getStart();
int index = start;
State state = this.defaultState();
while (state.isString() || state.isRegexp() || state.isBlockComment() ||
(!includeLineComment && state.isLineComment()) || !startsWith(src, delimiter, index)) {
this.parseChar(src.charAt(index++), state);
}
int end = index;
return new Match(start, end, src.substring(start, end));
}
// function parseChar(character, state) {
// if (character.length !== 1) throw new Error('Character must be a string of length 1');
// state = state || exports.defaultState();
// state.src = state.src || '';
// state.src += character;
// var wasComment = state.blockComment || state.lineComment;
// var lastChar = state.history ? state.history[0] : '';
//
// if (state.regexpStart) {
// if (character === '/' || character == '*') {
// state.regexp = false;
// }
// state.regexpStart = false;
// }
// if (state.lineComment) {
// if (character === '\n') {
// state.lineComment = false;
// }
// } else if (state.blockComment) {
// if (state.lastChar === '*' && character === '/') {
// state.blockComment = false;
// }
// } else if (state.singleQuote) {
// if (character === '\'' && !state.escaped) {
// state.singleQuote = false;
// } else if (character === '\\' && !state.escaped) {
// state.escaped = true;
// } else {
// state.escaped = false;
// }
// } else if (state.doubleQuote) {
// if (character === '"' && !state.escaped) {
// state.doubleQuote = false;
// } else if (character === '\\' && !state.escaped) {
// state.escaped = true;
// } else {
// state.escaped = false;
// }
// } else if (state.regexp) {
// if (character === '/' && !state.escaped) {
// state.regexp = false;
// } else if (character === '\\' && !state.escaped) {
// state.escaped = true;
// } else {
// state.escaped = false;
// }
// } else if (lastChar === '/' && character === '/') {
// state.history = state.history.substr(1);
// state.lineComment = true;
// } else if (lastChar === '/' && character === '*') {
// state.history = state.history.substr(1);
// state.blockComment = true;
// } else if (character === '/' && isRegexp(state.history)) {
// state.regexp = true;
// state.regexpStart = true;
// } else if (character === '\'') {
// state.singleQuote = true;
// } else if (character === '"') {
// state.doubleQuote = true;
// } else if (character === '(') {
// state.roundDepth++;
// } else if (character === ')') {
// state.roundDepth--;
// } else if (character === '{') {
// state.curlyDepth++;
// } else if (character === '}') {
// state.curlyDepth--;
// } else if (character === '[') {
// state.squareDepth++;
// } else if (character === ']') {
// state.squareDepth--;
// }
// if (!state.blockComment && !state.lineComment && !wasComment) state.history = character + state.history;
// state.lastChar = character; // store last character for ending block comments
// return state;
// }
public State parseChar(char character,State state){
// if (character.length !== 1) throw new Error('Character must be a string of length 1');
if(state == null)
state = this.defaultState();
state.setSrc(state.getSrc() + character);
boolean wasComment = state.isBlockComment() || state.isLineComment();
Character lastChar = !state.getHistory().isEmpty() ? state.getHistory().charAt(0) : null;
if (state.isRegexpStart()) {
if ('/' == character || '*'==character) {
state.setRegexp(false);
}
state.setRegexpStart(false);
}
if (state.isLineComment()) {
if ('\n' == character) {
state.setLineComment(false);
}
} else if (state.isBlockComment()) {
if ('*' == state.getLastChar() && '/'==character) {
state.setBlockComment(false);
}
} else if (state.isSingleQuote()) {
if ('\''==character && !state.isEscaped()) {
state.setSingleQuote(false);
} else if ('\\'==character && !state.isEscaped()) {
state.setEscaped(true);
} else {
state.setEscaped(false);
}
} else if (state.isDoubleQuote()) {
if ('"'==character && !state.isEscaped()) {
state.setDoubleQuote(false);
} else if ('\\'==character && !state.isEscaped()) {
state.setEscaped(true);
} else {
state.setEscaped(false);
}
} else if (state.isRegexp()) {
if ('/'==character && !state.isEscaped()) {
state.setRegexp(false);
} else if ('\\'==character && !state.isEscaped()) {
state.setRegexp(true);
} else {
state.setEscaped(false);
}
} else if (lastChar!=null && '/' == lastChar && '/'==character) {
state.setHistory(state.getHistory().substring(1));
state.setLineComment(true);
} else if (lastChar!=null && '/'==lastChar && '*'==character) {
state.setHistory(state.getHistory().substring(1));
state.setBlockComment(true);
} else if ('/'==character && !state.getHistory().isEmpty() &&isRegexp(state.getHistory())) {
state.setRegexp(true);
state.setRegexpStart(true);
} else if ('\''==character) {
state.setSingleQuote(true);
} else if (character == '"') {
state.setDoubleQuote(true);
} else if (character == '(') {
state.setRoundDepth(state.getRoundDepth()+1);
} else if (character == ')') {
state.setRoundDepth(state.getRoundDepth()-1);
} else if (character == '{') {
state.setCurlyDepth(state.getCurlyDepth()+1);
} else if (character == '}') {
state.setCurlyDepth(state.getCurlyDepth()-1);
} else if (character == '[') {
state.setSquareDepth(state.getSquareDepth()+1);
} else if (character == ']') {
state.setSquareDepth(state.getSquareDepth()-1);
}
if (!state.isBlockComment() && !state.isLineComment() && !wasComment) state.setHistory(character + state.getHistory());
state.setLastChar(character); // store last character for ending block comments
return state;
}
// exports.defaultState = function () { return new State() };
public State defaultState(){
return new State();
}
public static class State{
private boolean lineComment = false;
private boolean blockComment = false;
private boolean singleQuote = false;
private boolean doubleQuote = false;
private boolean regexp = false;
private boolean regexpStart = false;
private boolean escaped = false;
private int roundDepth = 0;
private int curlyDepth = 0;
private int squareDepth = 0;
private String history = "";
private Character lastChar = null;
private String src = "";
public boolean isString(){
return this.singleQuote || this.doubleQuote;
}
public boolean isComment(){
return this.lineComment || this.blockComment;
}
public boolean isNesting(){
return this.isString() || this.isComment() || this.regexp || this.roundDepth > 0 || this.curlyDepth > 0 || this.squareDepth > 0;
}
public String getSrc() {
return src;
}
public boolean isLineComment() {
return lineComment;
}
public void setLineComment(boolean lineComment) {
this.lineComment = lineComment;
}
public boolean isBlockComment() {
return blockComment;
}
public void setBlockComment(boolean blockComment) {
this.blockComment = blockComment;
}
public boolean isSingleQuote() {
return singleQuote;
}
public void setSingleQuote(boolean singleQuote) {
this.singleQuote = singleQuote;
}
public boolean isDoubleQuote() {
return doubleQuote;
}
public void setDoubleQuote(boolean doubleQuote) {
this.doubleQuote = doubleQuote;
}
public boolean isRegexp() {
return regexp;
}
public void setRegexp(boolean regexp) {
this.regexp = regexp;
}
public boolean isRegexpStart() {
return regexpStart;
}
public void setRegexpStart(boolean regexpStart) {
this.regexpStart = regexpStart;
}
public boolean isEscaped() {
return escaped;
}
public void setEscaped(boolean escaped) {
this.escaped = escaped;
}
public int getRoundDepth() {
return roundDepth;
}
public void setRoundDepth(int roundDepth) {
this.roundDepth = roundDepth;
}
public int getCurlyDepth() {
return curlyDepth;
}
public void setCurlyDepth(int curlyDepth) {
this.curlyDepth = curlyDepth;
}
public int getSquareDepth() {
return squareDepth;
}
public void setSquareDepth(int squareDepth) {
this.squareDepth = squareDepth;
}
public String getHistory() {
return history;
}
public void setHistory(String history) {
this.history = history;
}
public Character getLastChar() {
return lastChar;
}
public void setLastChar(Character lastChar) {
this.lastChar = lastChar;
}
public void setSrc(String src) {
this.src = src;
}
}
private boolean startsWith(String str, String start, int i){
return start.equals(str.substring(i,i+start.length()));
}
// exports.isPunctuator = isPunctuator
// function isPunctuator(c) {
// if (!c) return true; // the start of a string is a punctuator
// var code = c.charCodeAt(0)
//
// switch (code) {
// case 46: // . dot
// case 40: // ( open bracket
// case 41: // ) close bracket
// case 59: // ; semicolon
// case 44: // , comma
// case 123: // { open curly brace
// case 125: // } close curly brace
// case 91: // [
// case 93: // ]
// case 58: // :
// case 63: // ?
// case 126: // ~
// case 37: // %
// case 38: // &
// case 42: // *:
// case 43: // +
// case 45: // -
// case 47: // /
// case 60: // <
// case 62: // >
// case 94: // ^
// case 124: // |
// case 33: // !
// case 61: // =
// return true;
// default:
// return false;
// }
// }
public boolean isPunctuator(Character character){
Integer code = Character.codePointAt(character.toString(),0);
switch (code) {
case 46: // . dot
case 40: // ( open bracket
case 41: // ) close bracket
case 59: // ; semicolon
case 44: // , comma
case 123: // { open curly brace
case 125: // } close curly brace
case 91: // [
case 93: // ]
case 58: // :
case 63: // ?
case 126: // ~
case 37: // %
case 38: // &
case 42: // *:
case 43: // +
case 45: // -
case 47: // /
case 60: // <
case 62: // >
case 94: // ^
case 124: // |
case 33: // !
case 61: // =
return true;
default:
return false;
}
}
public boolean isKeyword(String id) {
return ("if".equals(id)) || ("in".equals(id)) || ("do".equals(id)) || ("var".equals(id)) || ("for".equals(id)) || ("new".equals(id)) ||
("try".equals(id)) || ("let".equals(id)) || ("this".equals(id)) || ("else".equals(id)) || ("case".equals(id)) ||
("void".equals(id)) || ("with".equals(id)) || ("enum".equals(id)) || ("while".equals(id)) || ("break".equals(id)) || ("catch".equals(id)) ||
("throw".equals(id)) || ("const".equals(id)) || ("yield".equals(id)) || ("class".equals(id)) || ("super".equals(id)) ||
("return".equals(id)) || ("typeof".equals(id)) || ("delete".equals(id)) || ("switch".equals(id)) || ("export".equals(id)) ||
("import".equals(id)) || ("default".equals(id)) || ("finally".equals(id)) || ("extends".equals(id)) || ("function".equals(id)) ||
("continue".equals(id)) || ("debugger".equals(id)) || ("package".equals(id)) || ("private".equals(id)) || ("interface".equals(id)) ||
("instanceof".equals(id)) || ("implements".equals(id)) || ("protected".equals(id)) || ("public".equals(id)) || ("static".equals(id));
}
// function isRegexp(history) {
// //could be start of regexp or divide sign
//
// history = history.replace(/^\s*/, '');
//
// //unless its an `if`, `while`, `for` or `with` it's a divide, so we assume it's a divide
// if (history[0] === ')') return false;
// //unless it's a function expression, it's a regexp, so we assume it's a regexp
// if (history[0] === '}') return true;
// //any punctuation means it's a regexp
// if (isPunctuator(history[0])) return true;
// //if the last thing was a keyword then it must be a regexp (e.g. `typeof /foo/`)
// if (/^\w+\b/.test(history) && isKeyword(/^\w+\b/.exec(history)[0].split('').reverse().join(''))) return true;
//
// return false;
// }
public boolean isRegexp(String history){
//could be start of regexp or divide sign
history = history.replace("^\\s*", "");
//unless its an `if`, `while`, `for` or `with` it's a divide, so we assume it's a divide
if (history.charAt(0) == ')') return false;
//unless it's a function expression, it's a regexp, so we assume it's a regexp
if (history.charAt(0) == '}') return true;
//any punctuation means it's a regexp
if (isPunctuator(history.charAt(0))) return true;
//if the last thing was a keyword then it must be a regexp (e.g. `typeof /foo/`)
Matcher matcher = pattern.matcher(history);
if (matcher.matches() && isKeyword(new StringBuilder(matcher.group(0)).reverse().toString())){
return true;
}
return false;
}
public class Match {
private int start;
private int end;
private String src;
public Match(int start, int end, String src) {
this.start = start;
this.end = end;
this.src = src;
}
public int getStart() {
return start;
}
public int getEnd() {
return end;
}
public String getSrc() {
return src;
}
}
}
| mit |
andreasb242/settlers-remake | jsettlers.graphics.swing/src/main/java/jsettlers/graphics/swing/utils/ImageUtils.java | 975 | package jsettlers.graphics.swing.utils;
import java.awt.image.BufferedImage;
import java.nio.ShortBuffer;
import jsettlers.common.Color;
import jsettlers.graphics.image.SingleImage;
public class ImageUtils {
/**
* Converts a single image to a buffered image.
*
* @param image
* The image to convert, needs to be loaded.
* @return
*/
public static BufferedImage convertToBufferedImage(SingleImage image) {
int width = image.getWidth();
int height = image.getHeight();
if (width <= 0 || height <= 0) {
return null;
}
BufferedImage rendered = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
ShortBuffer data = image.getData().duplicate();
data.rewind();
int[] rgbArray = new int[data.remaining()];
for (int i = 0; i < rgbArray.length; i++) {
short myColor = data.get();
rgbArray[i] = Color.convertTo32Bit(myColor);
}
rendered.setRGB(0, 0, width, height, rgbArray, 0, width);
return rendered;
}
}
| mit |
d3alek/TheHunt---Interactive-graphical-platform-for-AI-Experiments | TheHunt/src/d3kod/graphics/shader/programs/TextureProgram.java | 2210 | package d3kod.graphics.shader.programs;
public class TextureProgram extends Program {
private static final AttribVariable[] programVariables = {
AttribVariable.A_Position, AttribVariable.A_TexCoordinate
};
private static final String vertexShaderCode =
"uniform mat4 u_MVPMatrix; \n" // A constant representing the combined model/view/projection matrix.
+ "attribute vec4 a_Position; \n" // Per-vertex position information we will pass in.
+ "attribute vec2 a_TexCoordinate;\n" // Per-vertex texture coordinate information we will pass in
+ "varying vec2 v_TexCoordinate; \n" // This will be passed into the fragment shader.
+ "void main() \n" // The entry point for our vertex shader.
+ "{ \n"
+ " v_TexCoordinate = a_TexCoordinate; \n"
+ " gl_Position = u_MVPMatrix \n" // gl_Position is a special variable used to store the final position.
+ " * a_Position; \n" // Multiply the vertex by the matrix to get the final point in
// normalized screen coordinates.
+ "} \n";
private static final String fragmentShaderCode =
"uniform sampler2D u_Texture; \n" // The input texture.
+ "precision mediump float; \n" // Set the default precision to medium. We don't need as high of a
// precision in the fragment shader.
+ "uniform vec4 u_Color; \n"
// triangle per fragment.
+ "varying vec2 v_TexCoordinate; \n" // Interpolated texture coordinate per fragment.
+ "void main() \n" // The entry point for our fragment shader.
+ "{ \n"
+ " gl_FragColor = texture2D(u_Texture, v_TexCoordinate);\n" // Pass the color directly through the pipeline.
+ " gl_FragColor.a *= u_Color.a;\n"
+ "} \n";
public TextureProgram() {
// super(vertexShaderCode, fragmentShaderCode, programVariables);
// TODO Auto-generated constructor stub
}
@Override
public void init() {
super.init(vertexShaderCode, fragmentShaderCode, programVariables);
}
}
| mit |
amallem/simpledb | src/simpledb/StringAggregator.java | 1469 | package simpledb;
/**
* Knows how to compute some aggregate over a set of StringFields.
*/
public class StringAggregator implements Aggregator {
/**
* Aggregate constructor
* @param gbfield the 0-based index of the group-by field in the tuple, or NO_GROUPING if there is no grouping
* @param gbfieldtype the type of the group by field (e.g., Type.INT_TYPE), or null if there is no grouping
* @param afield the 0-based index of the aggregate field in the tuple
* @param what aggregation operator to use -- only supports COUNT
* @throws IllegalArgumentException if what != COUNT
*/
public StringAggregator(int gbfield, Type gbfieldtype, int afield, Op what) {
// some code goes here
}
/**
* Merge a new tuple into the aggregate, grouping as indicated in the constructor
* @param tup the Tuple containing an aggregate field and a group-by field
*/
public void merge(Tuple tup) {
// some code goes here
}
/**
* Create a DbIterator over group aggregate results.
*
* @return a DbIterator whose tuples are the pair (groupVal,
* aggregateVal) if using group, or a single (aggregateVal) if no
* grouping. The aggregateVal is determined by the type of
* aggregate specified in the constructor.
*/
public DbIterator iterator() {
// some code goes here
throw new UnsupportedOperationException("implement me");
}
}
| mit |
LaunchKey/launchkey-java | sdk/src/main/java/com/iovation/launchkey/sdk/transport/domain/OrganizationV3DirectorySdkKeysPostRequest.java | 920 | /**
* Copyright 2017 iovation, Inc.
* <p>
* Licensed under the MIT License.
* You may not use this file except in compliance with the License.
* A copy of the License is located in the "LICENSE.txt" file accompanying
* this file. This file is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.iovation.launchkey.sdk.transport.domain;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.UUID;
public class OrganizationV3DirectorySdkKeysPostRequest {
private final UUID directoryId;
public OrganizationV3DirectorySdkKeysPostRequest(UUID directoryId) {
this.directoryId = directoryId;
}
@JsonProperty("directory_id")
public UUID getDirectoryId() {
return directoryId;
}
}
| mit |