repo_name
stringlengths 7
104
| file_path
stringlengths 11
238
| context
list | import_statement
stringlengths 103
6.85k
| code
stringlengths 60
38.4k
| next_line
stringlengths 10
824
| gold_snippet_index
int32 0
8
|
---|---|---|---|---|---|---|
palominolabs/benchpress | worker-core/src/main/java/com/palominolabs/benchpress/worker/SliceRunner.java | [
"@Immutable\npublic final class JobSlice {\n private final UUID jobId;\n private final int sliceId;\n private final Task task;\n private final String progressUrl;\n private final String finishedUrl;\n\n @JsonCreator\n public JobSlice(@JsonProperty(\"jobId\") UUID jobId, @JsonProperty(\"sliceId\") int sliceId,\n @JsonProperty(\"task\") Task task, @JsonProperty(\"progressUrl\") String progressUrl,\n @JsonProperty(\"finishedUrl\") String finishedUrl) {\n this.jobId = jobId;\n this.sliceId = sliceId;\n this.task = task;\n this.progressUrl = progressUrl;\n this.finishedUrl = finishedUrl;\n }\n\n @JsonProperty(\"jobId\")\n public UUID getJobId() {\n return jobId;\n }\n\n @JsonProperty(\"sliceId\")\n public int getSliceId() {\n return sliceId;\n }\n\n @JsonProperty(\"task\")\n public Task getTask() {\n return task;\n }\n\n @JsonProperty(\"progressUrl\")\n public String getProgressUrl() {\n return progressUrl;\n }\n\n @JsonProperty(\"finishedUrl\")\n public String getFinishedUrl() {\n return finishedUrl;\n }\n}",
"public interface ComponentFactory {\n /**\n * Read config data out of the config node using the supplied ObjectReader and create a TaskFactory.\n *\n * @return a configured task factory\n */\n @Nonnull\n TaskFactory getTaskFactory();\n}",
"@ThreadSafe\npublic final class JobTypePluginRegistry extends IdRegistry<JobTypePlugin> {\n @Inject\n JobTypePluginRegistry(Set<JobTypePlugin> componentFactories) {\n super(componentFactories);\n }\n}",
"@NotThreadSafe\npublic interface TaskFactory {\n\n /**\n * @param jobId job id\n * @param sliceId the slice of the overall job that these tasks are part of\n * @param workerId the worker that these tasks are running in\n * @param progressClient client the workers can use to hand any notable data back to the controller\n * @return runnables\n * @throws IOException if task creation fails\n */\n @Nonnull\n Collection<Runnable> getRunnables(@Nonnull UUID jobId, int sliceId, @Nonnull UUID workerId,\n @Nonnull ScopedProgressClient progressClient) throws\n IOException;\n\n // TODO actually call this somewhere\n void shutdown();\n}",
"public class ScopedProgressClient {\n\n private final UUID jobId;\n\n private final int sliceId;\n\n private final String jobFinishedUrl;\n private final String jobProgressUrl;\n private final TaskProgressClient client;\n\n public ScopedProgressClient(UUID jobId, int sliceId, String jobFinishedUrl, String jobProgressUrl, TaskProgressClient client) {\n this.jobId = jobId;\n this.sliceId = sliceId;\n this.jobFinishedUrl = jobFinishedUrl;\n this.jobProgressUrl = jobProgressUrl;\n this.client = client;\n }\n\n public void reportFinished(Duration duration) {\n client.reportFinished(jobId, sliceId, duration, jobFinishedUrl);\n }\n\n public void reportProgress(JsonNode data) {\n client.reportProgress(jobId, sliceId, data, jobProgressUrl);\n }\n}",
"@ThreadSafe\npublic interface TaskProgressClient {\n /**\n * Indicates that all threads for the task have completed\n */\n void reportFinished(UUID jobId, int sliceId, Duration duration, String url);\n\n void reportProgress(UUID jobId, int sliceId, JsonNode data, String url);\n}",
"public static final String JOB_ID = \"jobId\";"
] | import com.fasterxml.jackson.databind.ObjectReader;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.palominolabs.benchpress.ipc.Ipc;
import com.palominolabs.benchpress.job.json.JobSlice;
import com.palominolabs.benchpress.job.task.ComponentFactory;
import com.palominolabs.benchpress.job.task.JobTypePluginRegistry;
import com.palominolabs.benchpress.job.task.TaskFactory;
import com.palominolabs.benchpress.task.reporting.ScopedProgressClient;
import com.palominolabs.benchpress.task.reporting.TaskProgressClient;
import java.time.Duration;
import java.time.Instant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import javax.annotation.concurrent.ThreadSafe;
import java.io.IOException;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import static com.palominolabs.benchpress.logging.MdcKeys.JOB_ID; | package com.palominolabs.benchpress.worker;
@Singleton
@ThreadSafe
public final class SliceRunner {
private static final Logger logger = LoggerFactory.getLogger(SliceRunner.class);
private final ExecutorService executorService = Executors.newCachedThreadPool();
private final CompletionService<Void> completionService = new ExecutorCompletionService<>(executorService);
/**
* TODO figure out a good way to worker-scope a random uuid -- @WorkerId binding annotation perhaps? Wrapper class?
*/
private final UUID workerId = UUID.randomUUID();
| private final TaskProgressClient taskProgressClient; | 5 |
jurihock/voicesmith | voicesmith/src/de/jurihock/voicesmith/threads/DetuneThread.java | [
"public enum FrameType\n{\n\tLarge(2),\n\tDefault(1),\n\tMedium(1 / 2D),\n\tSmall(1 / 4D);\n\n\tpublic final double\tratio;\n\n\tprivate FrameType(double ratio)\n\t{\n\t\tthis.ratio = ratio;\n\t}\n}",
"public final class Preferences\n{\n\t// TODO: Try different audio sources\n\t// public static final int PCM_IN_SOURCE = MediaRecorder.AudioSource.MIC;\n\t// public static final int PCM_IN_SOURCE =\n\t// MediaRecorder.AudioSource.VOICE_CALL;\n\t// public static final int PCM_IN_SOURCE =\n\t// MediaRecorder.AudioSource.VOICE_DOWNLINK;\n\t// public static final int PCM_IN_SOURCE =\n\t// MediaRecorder.AudioSource.VOICE_UPLINK;\n\t// public static final int PCM_OUT_SOURCE = AudioManager.STREAM_MUSIC;\n\t// public static final int PCM_OUT_SOURCE = AudioManager.STREAM_VOICE_CALL;\n\n\t// public static final String\t\tDATASTORE_DIR\t= \"Android/data/de.jurihock.voicesmith\";\n\t// public static final String\t\tVOICEBANK_DIR\t= DATASTORE_DIR\t+ \"/voicebank\";\n\t// public static final String\t\tRECORDS_FILE\t= VOICEBANK_DIR + \"/records.xml\";\n\n\tprivate final SharedPreferences\tpreferences;\n\n\tpublic Preferences(Context context)\n\t{\n\t\tpreferences = PreferenceManager\n\t\t\t.getDefaultSharedPreferences(context);\n\n\t\tPreferenceManager.setDefaultValues(\n\t\t\tcontext, R.xml.preferences, false);\n\t}\n\n\tpublic void registerOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener listener)\n\t{\n\t\tpreferences.registerOnSharedPreferenceChangeListener(listener);\n\t}\n\n\tpublic void unregisterOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener listener)\n\t{\n\t\tpreferences.unregisterOnSharedPreferenceChangeListener(listener);\n\t}\n\n\tpublic void reset()\n\t{\n\t\tpreferences.edit().clear().commit();\n\n // There are no needs to show the Change Log again after reset\n this.setChangeLogShowed(true);\n\t}\n\n public boolean isChangeLogShowed()\n {\n return preferences.getBoolean(\"ChangeLog\", false);\n }\n\n public boolean setChangeLogShowed(boolean value)\n {\n return preferences.edit().putBoolean(\"ChangeLog\", value).commit();\n }\n\n public boolean isForceVolumeLevelOn()\n {\n return preferences.getBoolean(\"ForceVolumeLevel\", true);\n }\n\n\tpublic int getVolumeLevel(HeadsetMode mode)\n\t{\n if(mode == HeadsetMode.BLUETOOTH_HEADSET)\n {\n return Integer.parseInt(\n preferences.getString(\"BluetoothVolumeLevel\", \"100\"));\n }\n else\n {\n return Integer.parseInt(\n preferences.getString(\"WireVolumeLevel\", \"30\"));\n }\n\t}\n\n\tpublic boolean setVolumeLevel(HeadsetMode mode, int value)\n\t{\n\t\tif ((0 <= value) && (value <= 100))\n\t\t{\n if(mode == HeadsetMode.BLUETOOTH_HEADSET)\n {\n return preferences.edit()\n .putString(\"BluetoothVolumeLevel\",\n Integer.toString(value))\n .commit();\n }\n else\n {\n return preferences.edit()\n .putString(\"WireVolumeLevel\",\n Integer.toString(value))\n .commit();\n }\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tpublic int getSignalAmplificationFactor()\n\t{\n\t\treturn Integer.parseInt(\n\t\t\tpreferences.getString(\"SignalAmplification\", \"6\"));\n\t}\n\n\tpublic int getSampleRate()\n\t{\n\t\treturn Integer.parseInt(\n\t\t\tpreferences.getString(\"SampleRate\", \"44100\"));\n\t}\n\n public boolean isCorrectOffsetOn()\n {\n return preferences.getBoolean(\"CorrectOffset\", true);\n }\n\n\tpublic boolean isSpectralNoiseGateOn()\n\t{\n\t\treturn preferences.getBoolean(\"SpectralNoiseGate\", true);\n\t}\n\n public int getNoiseGateCoeffExponent()\n {\n return Integer.parseInt(\n preferences.getString(\"NoiseGateCoeffExponent\", \"3\"));\n }\n\n public boolean isBandpassFilterOn()\n {\n return preferences.getBoolean(\"BandpassFilter\", false);\n }\n\n public int getBandpassLowerFreq()\n {\n return Integer.parseInt(\n preferences.getString(\"BandpassLowerFreq\", \"100\"));\n }\n\n public int getBandpassUpperFreq()\n {\n return Integer.parseInt(\n preferences.getString(\"BandpassUpperFreq\", \"8000\"));\n }\n\n public boolean isAutoMuteOn()\n {\n return preferences.getBoolean(\"AutoMute\", false);\n }\n\n public int getAutoMuteHighThreshold()\n {\n int high = Integer.parseInt(preferences.getString(\"AutoMuteHighThreshold\", \"-20\"));\n int low = Integer.parseInt(preferences.getString(\"AutoMuteLowThreshold\", \"-25\"));\n\n return Math.min(0, Math.max(high, low));\n }\n\n public int getAutoMuteLowThreshold()\n {\n int high = Integer.parseInt(preferences.getString(\"AutoMuteHighThreshold\", \"-20\"));\n int low = Integer.parseInt(preferences.getString(\"AutoMuteLowThreshold\", \"-25\"));\n\n return Math.min(0, Math.min(high, low));\n }\n\n public int getAutoMuteHangover()\n {\n return Integer.parseInt(\n preferences.getString(\"AutoMuteHangover\", \"5\"));\n }\n\n\tpublic boolean isLoggingOn()\n\t{\n\t\treturn preferences.getBoolean(\"Logging\", false);\n\t}\n\n public boolean isInternalMicSupportOn()\n {\n return preferences.getBoolean(\"InternalMicSupport\", false);\n }\n\n public boolean setInternalMicSupport(boolean internalMicSupport)\n {\n return preferences.edit().putBoolean(\"InternalMicSupport\", internalMicSupport).commit();\n }\n\n public boolean isBluetoothHeadsetSupportOn()\n {\n return preferences.getBoolean(\"BluetoothHeadsetSupport\", false);\n }\n\n public boolean setBluetoothHeadsetSupport(boolean bluetoothHeadsetSupport)\n {\n return preferences.edit().putBoolean(\"BluetoothHeadsetSupport\", bluetoothHeadsetSupport).commit();\n }\n\n\tpublic DAFX getDafx()\n\t{\n\t\treturn DAFX.valueOf(\n\t\t\tpreferences.getInt(\"DAFX\", 0));\n\t}\n\n\tpublic boolean setDafx(DAFX value)\n\t{\n\t\treturn preferences.edit()\n\t\t\t.putInt(\"DAFX\", value.ordinal())\n\t\t\t.commit();\n\t}\n\t\n\tpublic AAF getAaf()\n\t{\n\t\treturn AAF.valueOf(\n\t\t\tpreferences.getInt(\"AAF\", 0));\n\t}\n\n\tpublic boolean setAaf(AAF value)\n\t{\n\t\treturn preferences.edit()\n\t\t\t.putInt(\"AAF\", value.ordinal())\n\t\t\t.commit();\n\t}\n\n public String getAudioThreadPreferences(String threadName)\n {\n return preferences.getString(threadName, null);\n }\n\n public boolean setAudioThreadPreferences(String threadName, String value)\n {\n return preferences.edit().putString(threadName, value).commit();\n }\n\n\t/**\n\t * Returns the optimal PCM buffer size in bytes. Because of output buffer\n\t * stuffing, the input buffer should be bigger, to prevent the overflow.\n\t * */\n\tpublic int getPcmBufferSize(int sampleRate)\n\t{\n\t\tint pcmInBufferSize = AudioRecord.getMinBufferSize(\n\t\t\tsampleRate,\n\t\t\tAudioFormat.CHANNEL_IN_MONO, // DON'T CHANGE!\n\t\t\tAudioFormat.ENCODING_PCM_16BIT); // DON'T CHANGE!\n\n\t\tint pcmOutBufferSize = AudioTrack.getMinBufferSize(\n\t\t\tsampleRate,\n\t\t\tAudioFormat.CHANNEL_OUT_MONO, // DON'T CHANGE!\n\t\t\tAudioFormat.ENCODING_PCM_16BIT); // DON'T CHANGE!\n\n\t\treturn Math.max(pcmInBufferSize, pcmOutBufferSize);\n\t}\n\n\tpublic int getFrameSize(FrameType frameType, int sampleRate)\n\t{\n\t\t// An example for the 44,1 kHz sample rate:\n\t\t// - Large frame size = 4096\n\t\t// - Default frame size = 2048\n\t\t// - Medium frame size = 1024\n\t\t// - Small frame size = 512\n\n\t\tfinal double frameSizeRatio = 1D / (44100D / 2048D); // default ratio\n\t\tfinal double frameTypeRatio = frameType.ratio;\n\n\t\t// Only even frame sizes are required\n\t\tint frameSize = (int) (sampleRate * frameSizeRatio * frameTypeRatio);\n\t\tif (frameSize % 2 != 0) frameSize++;\n\n\t\treturn frameSize;\n\t}\n\n\tpublic int getHopSize(FrameType frameType, int sampleRate)\n\t{\n\t\t// The hop size for a Hann window is 1/4 of the frame size:\n\t\treturn getFrameSize(frameType, sampleRate) / 4;\n\t}\n}",
"public final class Utils\n{\n\tprivate static final String\t\t\t\tNATIVELIB_NAME\t= \"Voicesmith\";\n\tprivate static final String\t\t\t\tLOGCAT_TAG\t\t= \"Voicesmith\";\n\tprivate static final int\t\t\t\tTOAST_LENGTH\t= Toast.LENGTH_LONG;\n\n\tprivate final Context\t\t\t\t\tcontext;\n\tprivate final Preferences\t\t\t\tpreferences;\n\n\t/**\n\t * Stopwatch timestamps.\n\t * */\n\tprivate static final Map<String, Long>\ttics\t\t\t= new HashMap<String, Long>();\n\n\tpublic Utils(Context context)\n\t{\n\t\tthis.context = context;\n\t\tthis.preferences = new Preferences(context);\n\t}\n\n\t/**\n\t * Loads the native library.\n\t * */\n\tpublic static void loadNativeLibrary()\n\t{\n\t\ttry\n\t\t{\n\t\t\tSystem.loadLibrary(NATIVELIB_NAME);\n\t\t}\n\t\tcatch (UnsatisfiedLinkError exception)\n\t\t{\n Log.d(LOGCAT_TAG, String.format(\n \"Native library %s could not be loaded!\",\n NATIVELIB_NAME));\n\t\t}\n\t}\n\n public String getVersionString(int formatResId)\n {\n return getVersionString(context.getString(formatResId));\n }\n\n public String getVersionString(String format)\n {\n try\n {\n PackageInfo info = context.getPackageManager()\n .getPackageInfo(context.getPackageName(), 0);\n\n return String.format(\n format,\n info.versionName,\n info.versionCode);\n }\n catch (PackageManager.NameNotFoundException exception)\n {\n new Utils(context).log(exception);\n }\n\n return null;\n }\n\n\t/**\n\t * Checks if a local service is just running.\n\t * */\n\tpublic boolean isServiceRunning(Class<?> serviceClass)\n\t{\n\t\tActivityManager manager = (ActivityManager)\n\t\t\tcontext.getSystemService(Context.ACTIVITY_SERVICE);\n\n\t\tList<RunningServiceInfo> services =\n\t\t\tmanager.getRunningServices(Integer.MAX_VALUE);\n\n\t\tfor (RunningServiceInfo service : services)\n\t\t{\n\t\t\tif (service.service.getClassName().equals(\n\t\t\t\tserviceClass.getName()))\n\t\t\t{\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t * Tries to mount the external storage, makes necessary dirs and finally\n\t * returns a File instance for assigned file path.\n\t * */\n\tpublic File mountFile(String path) throws IOException\n\t{\n\t\tif (!Environment.MEDIA_MOUNTED.equals(\n\t\t\tEnvironment.getExternalStorageState()))\n\t\t{\n\t\t\tthrow new IOException(\"Unable to mount external storage!\");\n\t\t}\n\n\t\tFile file = new File(\n\t\t\tEnvironment.getExternalStorageDirectory(),\n\t\t\tpath);\n\n\t\tFile dir = file.getParentFile();\n\t\tif (!dir.exists() && !dir.mkdirs())\n\t\t{\n\t\t\tthrow new IOException(String.format(\n\t\t\t\t\"Unable to make directory '%s'!\",\n\t\t\t\tdir.getAbsolutePath()));\n\t\t}\n\n\t\treturn file;\n\t}\n\n\tpublic void postNotification(int iconID, String tickerText, String contentTitle, String contentText, Class<?> activityClass)\n\t{\n\t\tNotificationManager service = (NotificationManager)\n\t\t\tcontext.getSystemService(Context.NOTIFICATION_SERVICE);\n\n\t\tNotification notification = new Notification(\n\t\t\ticonID, tickerText, System.currentTimeMillis());\n\t\tnotification.flags |= Notification.FLAG_AUTO_CANCEL\n\t\t\t| Notification.FLAG_NO_CLEAR;\n\n\t\tIntent intent = new Intent(context, activityClass);\n\t\tintent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);\n\n\t\tPendingIntent pendingIntent = PendingIntent\n\t\t\t.getActivity(context, 0, intent, 0);\n\n\t\tnotification.setLatestEventInfo(context,\n\t\t\tcontentTitle, contentText, pendingIntent);\n\n\t\tservice.cancel(0);\n\t\tservice.notify(0, notification);\n\t}\n\n\tpublic void cancelAllNotifications()\n\t{\n\t\tNotificationManager service = (NotificationManager)\n\t\t\tcontext.getSystemService(Context.NOTIFICATION_SERVICE);\n\n\t\tservice.cancelAll();\n\t}\n\n\t/**\n\t * Writes a LogCat log entry.\n\t * */\n\tpublic void log(String message)\n\t{\n\t\tif (preferences.isLoggingOn())\n\t\t{\n\t\t\tLog.d(LOGCAT_TAG, message);\n\t\t}\n\t}\n\n\t/**\n\t * Writes a formatted LogCat log entry.\n\t * */\n\tpublic void log(String message, Object... args)\n\t{\n\t\tlog(String.format(message, args));\n\t}\n\n\t/**\n\t * Writes a LogCat log entry.\n\t * */\n\tpublic void log(Throwable exception)\n\t{\n\t\tlog(\"[EXCEPTION] \" + Log.getStackTraceString(exception));\n\t}\n\n\t/**\n\t * Shows a Toast message.\n\t * */\n\tpublic void toast(String message)\n\t{\n\t\tToast.makeText(context, message, TOAST_LENGTH).show();\n\t}\n\n\t/**\n\t * Shows a formatted Toast message.\n\t * */\n\tpublic void toast(String message, Object... args)\n\t{\n\t\ttoast(String.format(message, args));\n\t}\n\n\t/**\n\t * Writes a LogCat log entry if condition is FALSE.\n\t * */\n\tpublic void assertTrue(boolean condition, String message)\n\t{\n\t\tif (!condition) log(\"[ASSERT] \" + message);\n\t}\n\n\t/**\n\t * Writes a formatted LogCat log entry if condition is FALSE.\n\t * */\n\tpublic void assertTrue(boolean condition, String message, Object... args)\n\t{\n\t\tassertTrue(condition, String.format(message, args));\n\t}\n\n\t/**\n\t * Starts a stopwatch.\n\t * */\n\tpublic synchronized void tic(String tag)\n\t{\n\t\tif (tics.containsKey(tag))\n\t\t{\n\t\t\ttics.remove(tag);\n\t\t}\n\n\t\tlong tic = SystemClock.elapsedRealtime(); // ms\n\t\t// long tic = System.nanoTime(); // ns\n\n\t\ttics.put(tag, tic);\n\t}\n\n\t/**\n\t * Stops a stopwatch and prints out the time difference.\n\t * */\n\tpublic synchronized void toc(String tag)\n\t{\n\t\tlong toc = SystemClock.elapsedRealtime(); // ms\n\t\t// long toc = System.nanoTime(); // ns\n\n\t\tif (tics.containsKey(tag))\n\t\t{\n\t\t\tlong tic = tics.remove(tag);\n\n\t\t\tlog(\"%s: %d ms\", tag, (toc - tic)); // ms\n\t\t\t// log(\"%s: %f ms\", tag, (toc - tic) / 1000D); // ns/1000\n\t\t}\n\t}\n}",
"public final class DetuneProcessor\n{\n\tpublic static void processFrame(float[] frame)\n\t{\n\t\tfinal int fftSize = frame.length / 2;\n\t\tfloat re, im;\n\n\t\tfor (int i = 1; i < fftSize; i++)\n\t\t{\n\t\t\t// Get source Re and Im parts\n\t\t\tre = frame[2 * i];\n\t\t\tim = frame[2 * i + 1];\n\n\t\t\t// Invert phase value\n\t\t\tim = -im;\n\n\t\t\t// Store destination Re and Im parts\n\t\t\tframe[2 * i] = re;\n\t\t\tframe[2 * i + 1] = im;\n\t\t}\n\t}\n}",
"public final class StftPostprocessor implements Disposable\n{\n\tprivate final AudioDevice\toutput;\n\tprivate final int\t\t\tframeSize;\n\tprivate final int\t\t\thopSize;\n\tprivate final boolean\t\tdoInverseFFT;\n\n\tprivate KissFFT\t\t\t\tfft\t= null;\n\tprivate final float[]\t\twindow;\n\n\tprivate final short[]\t\tprevFrame, nextFrame;\n\tprivate int\t\t\t\t\tframeCursor;\n\n\tpublic StftPostprocessor(AudioDevice output, int frameSize, int hopSize, boolean doInverseFFT)\n\t{\n\t\tthis.output = output;\n\t\tthis.frameSize = frameSize;\n\t\tthis.hopSize = hopSize;\n\t\tthis.doInverseFFT = doInverseFFT;\n\n\t\tfft = new KissFFT(frameSize);\n\t\twindow = new Window(frameSize, true).hann();\n\n\t\tprevFrame = new short[frameSize];\n\t\tnextFrame = new short[frameSize];\n\t\tframeCursor = 0;\n\t}\n\n\tpublic void dispose()\n\t{\n\t\tif (fft != null)\n\t\t{\n\t\t\tfft.dispose();\n\t\t\tfft = null;\n\t\t}\n\t}\n\n\tpublic void processFrame(float[] frame)\n\t{\n\t\tif (doInverseFFT) fft.ifft(frame);\n\n\t\t// Prepare left frame part\n\t\tsynthesizeFrame(\n\t\t\tframe, 0,\n\t\t\tprevFrame, frameCursor,\n\t\t\tframeSize - frameCursor,\n\t\t\twindow);\n\n\t\t// Prepare right frame part\n\t\tsynthesizeFrame(\n\t\t\tframe, frameSize - frameCursor,\n\t\t\tnextFrame, 0,\n\t\t\tframeCursor,\n\t\t\twindow);\n\n\t\t// Increment and handle frame cursor\n\t\tframeCursor += hopSize;\n\t\tif (frameCursor >= frameSize)\n\t\t{\n\t\t\t// Reset frame cursor\n\t\t\tframeCursor -= frameSize;\n\n\t\t\t// Write ready frame to output\n\t\t\toutput.write(prevFrame);\n\n\t\t\t// Prepare frame buffers\n\t\t\tSystem.arraycopy(nextFrame, 0, prevFrame, 0, frameSize);\n\t\t\tArrays.fill(nextFrame, (short) 0);\n\t\t}\n\t}\n\n\t/**\n\t * Performs the synthesis step with weighting.\n\t * */\n\tprivate static void synthesizeFrame(float[] src, int offsetSrc, short[] dst, int offsetDst, int count, float[] window)\n\t{\n\t\tif (count == 0) return;\n\n\t\tfor (int i = 0; i < count; i++)\n\t\t{\n\t\t\t// Get the source value\n\t\t\tfloat value = src[i + offsetSrc];\n\n\t\t\t// Multiply with window coefficient\n\t\t\tvalue *= window[i + offsetSrc];\n\n\t\t\t// Expand and add it to destination value\n\t\t\tvalue = min(1F, max(-1F, value));\n\t\t\tdst[i + offsetDst] += (short) round(value * 32767F);\n\t\t}\n\t}\n}",
"public final class StftPreprocessor implements Disposable\n{\n\tprivate final AudioDevice\t\tinput;\n\tprivate final int\t\t\t\tframeSize;\n\tprivate final int\t\t\t\thopSize;\n\tprivate final boolean\t\t\tdoForwardFFT;\n\n private final OffsetProcessor deoffset;\n\tprivate final VadProcessor \t\tvad;\n private final AmplifyProcessor\tamplifier;\n private final DenoiseProcessor denoiser;\n\n\tprivate KissFFT\t\t\t\t\tfft\t= null;\n\tprivate final float[]\t\t\twindow;\n\n\tprivate final short[]\t\t\tprevFrame, nextFrame;\n\tprivate int\t\t\t\t\t\tframeCursor;\n\n\tpublic StftPreprocessor(AudioDevice input, int frameSize, int hopSize, boolean doForwardFFT)\n\t{\n\t\tthis.input = input;\n\t\tthis.frameSize = frameSize;\n\t\tthis.hopSize = hopSize;\n\t\tthis.doForwardFFT = doForwardFFT;\n\n deoffset = new OffsetProcessor(input.getContext());\n\t\tvad = new VadProcessor(input.getSampleRate(), input.getContext());\n\t\tamplifier = new AmplifyProcessor(input.getContext());\n denoiser = new DenoiseProcessor(input.getSampleRate(), input.getContext());\n\n\t\tfft = new KissFFT(frameSize);\n\t\twindow = new Window(frameSize, true).hann();\n\n\t\tprevFrame = new short[frameSize];\n\t\tnextFrame = new short[frameSize];\n\t\tframeCursor = -1;\n\t}\n\n\tpublic void dispose()\n\t{\n\t\tif (fft != null)\n\t\t{\n\t\t\tfft.dispose();\n\t\t\tfft = null;\n\t\t}\n\t}\n\n\tpublic void processFrame(float[] frame)\n\t{\n\t\t// Handle the first frame\n\t\tif (frameCursor == -1)\n\t\t{\n\t\t\tframeCursor = frameSize;\n\t\t\tinput.read(nextFrame);\n\n\t\t\t// Pre-preprocess frame\n deoffset.processFrame(nextFrame);\n vad.processFrame(nextFrame);\n\t\t\tamplifier.processFrame(nextFrame);\n\t\t}\n\t\t// Handle frame cursor\n\t\telse if (frameCursor >= frameSize)\n\t\t{\n\t\t\t// Reset frame cursor\n\t\t\tframeCursor -= frameSize;\n\n\t\t\t// Prepare frame buffers\n\t\t\tSystem.arraycopy(nextFrame, 0, prevFrame, 0, frameSize);\n\n\t\t\t// Read next frame\n\t\t\tinput.read(nextFrame);\n\n // Pre-preprocess frame\n deoffset.processFrame(nextFrame);\n vad.processFrame(nextFrame);\n amplifier.processFrame(nextFrame);\n\t\t}\n\n\t\t// Prepare left frame part\n\t\tanalyzeFrame(\n\t\t\tprevFrame, frameCursor,\n\t\t\tframe, 0,\n\t\t\tframeSize - frameCursor,\n\t\t\twindow);\n\n\t\t// Prepare right frame part\n\t\tanalyzeFrame(\n\t\t\tnextFrame, 0,\n\t\t\tframe, frameSize - frameCursor,\n\t\t\tframeCursor,\n\t\t\twindow);\n\n\t\tif (doForwardFFT)\n {\n fft.fft(frame);\n denoiser.processFrame(frame);\n }\n\n\t\t// Increment frame cursor\n\t\tframeCursor += hopSize;\n\t}\n\n\t/**\n\t * Performs the analysis step with weighting.\n\t * */\n\tprivate static void analyzeFrame(short[] src, int offsetSrc, float[] dst, int offsetDst, int count, float[] window)\n\t{\n\t\tif (count == 0) return;\n\n\t\tfor (int i = 0; i < count; i++)\n\t\t{\n\t\t\t// Get and normalize source value\n\t\t\tfloat value = (float) src[i + offsetSrc] / 32767F;\n\t\t\tvalue = min(1F, max(-1F, value));\n\n\t\t\t// Multiply with window coefficient\n\t\t\tvalue *= window[i + offsetDst];\n\n\t\t\t// Copy it to destination array\n\t\t\tdst[i + offsetDst] = value;\n\t\t}\n\t}\n}",
"public abstract class AudioDevice implements Disposable\n{\n\tprotected final Context\tcontext;\n\n\tpublic Context getContext()\n\t{\n\t\treturn context;\n\t}\n\n\tprivate int\tsampleRate;\n\n\tpublic int getSampleRate()\n\t{\n\t\treturn sampleRate;\n\t}\n\t\n\tprotected void setSampleRate(int sampleRate)\n\t{\n\t\tthis.sampleRate = sampleRate;\n\t}\n\t\n\tpublic AudioDevice(Context context)\n\t{\n\t\tthis(context, new Preferences(context).getSampleRate());\n\t}\n\n\tpublic AudioDevice(Context context, int\tsampleRate)\n\t{\n\t\tthis.context = context;\n\t\tthis.sampleRate = sampleRate;\n\t\tnew Utils(context).log(\"Current sample rate is %s Hz.\", sampleRate);\n\t}\n\n\tpublic int read(short[] buffer, int offset, int count)\n\t{\n\t\treturn -1;\n\t}\n\n\tpublic final boolean read(short[] buffer)\n\t{\n if (buffer == null) return false;\n if (buffer.length == 0) return false;\n\n\t\tint count = 0;\n\n\t\tdo\n\t\t{\n int result = read(buffer, count, buffer.length - count);\n if (result < 0) return false; // error on reading data\n\t\t\tcount += result;\n\t\t}\n\t\twhile (count < buffer.length);\n\n\t\treturn true;\n\t}\n\n\tpublic int write(short[] buffer, int offset, int count)\n\t{\n\t\treturn -1;\n\t}\n\n\tpublic final boolean write(short[] buffer)\n\t{\n if (buffer == null) return false;\n if (buffer.length == 0) return false;\n\n\t\tint count = 0;\n\n\t\tdo\n\t\t{\n int result = write(buffer, count, buffer.length - count);\n if (result < 0) return false; // error on writing data\n count += result;\n\t\t}\n\t\twhile (count < buffer.length);\n\n return true;\n\t}\n\n\tpublic void flush()\n\t{\n\t}\n\n\tpublic void start()\n\t{\n\t}\n\n\tpublic void stop()\n\t{\n\t}\n\n\tpublic void dispose()\n\t{\n\t}\n}"
] | import android.content.Context;
import de.jurihock.voicesmith.FrameType;
import de.jurihock.voicesmith.Preferences;
import de.jurihock.voicesmith.Utils;
import de.jurihock.voicesmith.dsp.processors.DetuneProcessor;
import de.jurihock.voicesmith.dsp.stft.StftPostprocessor;
import de.jurihock.voicesmith.dsp.stft.StftPreprocessor;
import de.jurihock.voicesmith.io.AudioDevice; | /*
* Voicesmith <http://voicesmith.jurihock.de/>
*
* Copyright (c) 2011-2014 Juergen Hock
*
* 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 de.jurihock.voicesmith.threads;
public class DetuneThread extends AudioThread
{
private final float[] buffer;
private StftPreprocessor preprocessor = null;
private StftPostprocessor postprocessor = null;
public DetuneThread(Context context, AudioDevice input, AudioDevice output)
{
super(context, input, output);
Preferences preferences = new Preferences(context);
| FrameType frameType = FrameType.Medium; | 0 |
ZSCNetSupportDept/WechatTicketSystem | src/main/java/love/sola/netsupport/wechat/handler/SubscribeHandler.java | [
"public class Attribute {\n\n public static final String AUTHORIZED = \"authorized\";\n public static final String WECHAT = \"wechat\";\n public static final String OPERATOR = \"operator\";\n public static final String USER = \"user\";\n\n}",
"@Entity\n@Table(name = \"operators\")\npublic class Operator {\n\n public static final String PROPERTY_WECHAT = \"wechat\";\n\n //System Accounts\n public static Operator USER_SELF;\n public static Operator ADMIN;\n\n @Id\n @Column(name = \"id\", nullable = false, insertable = false, updatable = false)\n private Integer id;\n @Column(name = \"name\", nullable = false, insertable = false, updatable = false)\n private String name;\n @Column(name = \"access\", nullable = false, insertable = false, updatable = false)\n private Integer access;\n @Column(name = \"wechat\", insertable = false, updatable = false)\n @Expose(serialize = false)\n private String wechat;\n private Integer block;\n private Integer week;\n @Expose(serialize = false)\n private String password;\n\n public Operator(Integer id, String name, Integer access, String wechat, Integer block, Integer week, String password) {\n this.id = id;\n this.name = name;\n this.access = access;\n this.wechat = wechat;\n this.block = block;\n this.week = week;\n this.password = password;\n }\n\n public Operator() {\n }\n\n public Integer getId() {\n return id;\n }\n\n public void setId(Integer id) {\n this.id = id;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public Integer getAccess() {\n return access;\n }\n\n public void setAccess(Integer access) {\n this.access = access;\n }\n\n public String getWechat() {\n return wechat;\n }\n\n public void setWechat(String wechat) {\n this.wechat = wechat;\n }\n\n public Integer getBlock() {\n return block;\n }\n\n public void setBlock(Integer block) {\n this.block = block;\n }\n\n public Integer getWeek() {\n return week;\n }\n\n public void setWeek(Integer week) {\n this.week = week;\n }\n\n public String getPassword() {\n return password;\n }\n\n public void setPassword(String password) {\n this.password = password;\n }\n\n @Override\n public String toString() {\n return \"Operator{\" +\n \"id=\" + id +\n \", name='\" + name + '\\'' +\n \", access=\" + access +\n \", wechat='\" + wechat + '\\'' +\n \", block=\" + block +\n \", week=\" + week +\n '}';\n }\n}",
"@Entity\n@Table(name = \"users\")\npublic class User {\n\n //System Accounts\n public static User OFFICIAL_CHINA_UNICOM_XH;\n public static User OFFICIAL_CHINA_MOBILE_XH;\n public static User OFFICIAL_CHINA_MOBILE_FX;\n\n public static final String PROPERTY_NAME = \"name\";\n public static final String PROPERTY_WECHAT = \"wechatId\";\n public static final String PROPERTY_BLOCK = \"block\";\n\n @Id\n @Column(name = \"id\", updatable = false, nullable = false)\n private Long id;\n @Column(name = \"name\", updatable = false, nullable = false)\n private String name;\n @Convert(converter = ISPConverter.class)\n private ISP isp;\n @Column(name = \"netaccount\")\n private String netAccount;\n @Expose(serialize = false)\n @Column(name = \"wechat\")\n private String wechatId;\n private Integer block;\n private Integer room;\n private Long phone;\n\n public User() {\n }\n\n public User(Long id, String name, ISP isp, String netAccount, String wechatId, Integer block, Integer room, Long phone) {\n this.id = id;\n this.name = name;\n this.isp = isp;\n this.netAccount = netAccount;\n this.wechatId = wechatId;\n this.block = block;\n this.room = room;\n this.phone = phone;\n }\n\n public Long getId() {\n return id;\n }\n\n public void setId(Long id) {\n this.id = id;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public ISP getIsp() {\n return isp;\n }\n\n public void setIsp(ISP isp) {\n this.isp = isp;\n }\n\n public String getNetAccount() {\n return netAccount;\n }\n\n public void setNetAccount(String netAccount) {\n this.netAccount = netAccount;\n }\n\n public String getWechatId() {\n return wechatId;\n }\n\n public void setWechatId(String wechatId) {\n this.wechatId = wechatId;\n }\n\n public Integer getBlock() {\n return block;\n }\n\n public void setBlock(Integer block) {\n this.block = block;\n }\n\n public Integer getRoom() {\n return room;\n }\n\n public void setRoom(Integer room) {\n this.room = room;\n }\n\n public Long getPhone() {\n return phone;\n }\n\n public void setPhone(Long phone) {\n this.phone = phone;\n }\n\n @Override\n public String toString() {\n return \"User{\" +\n \"id=\" + id +\n \", name='\" + name + '\\'' +\n \", isp=\" + isp +\n \", netAccount='\" + netAccount + '\\'' +\n \", wechatId='\" + wechatId + '\\'' +\n \", block=\" + block +\n \", room=\" + room +\n \", phone=\" + phone +\n '}';\n }\n}",
"public class WechatSession {\n\n private static MapSessionRepository repository;\n\n static {\n repository = new MapSessionRepository();\n }\n\n public static WxSession get(String id) {\n return repository.getSession(id);\n }\n\n public static WxSession create() {\n return repository.createSession();\n }\n\n public static Collection<? extends WxSession> list() {\n return repository.asMap().values();\n }\n\n}",
"public interface WxSession {\n\n String getId();\n\n <T> T getAttribute(String name);\n\n Set<String> getAttributeNames();\n\n void setAttribute(String name, Object value);\n\n void removeAttribute(String name);\n\n void invalidate();\n\n}",
"public class TableOperator extends SQLCore {\n\n public static boolean has(String wechat) {\n try (Session s = SQLCore.sf.openSession()) {\n return (long) s.createCriteria(Operator.class)\n .add(Restrictions.eq(Operator.PROPERTY_WECHAT, wechat))\n .setProjection(Projections.rowCount())\n .uniqueResult() > 0;\n }\n }\n\n\n public static Operator get(String wechat) {\n try (Session s = SQLCore.sf.openSession()) {\n return (Operator) s.createCriteria(Operator.class)\n .add(Restrictions.eq(Operator.PROPERTY_WECHAT, wechat))\n .uniqueResult();\n }\n }\n\n public static Operator get(int id) {\n try (Session s = SQLCore.sf.openSession()) {\n return s.get(Operator.class, id);\n }\n }\n\n protected static void init() {\n try (Session s = SQLCore.sf.openSession()) {\n Operator.USER_SELF = s.get(Operator.class, -1);\n Operator.ADMIN = s.get(Operator.class, 0);\n }\n }\n\n}",
"@SuppressWarnings(\"Duplicates\")\npublic class TableUser extends SQLCore {\n\n public static final String COLUMN_ID = \"id\";\n public static final String COLUMN_NAME = \"name\";\n public static final String COLUMN_ISP = \"isp\";\n public static final String COLUMN_NET_ACCOUNT = \"netaccount\";\n public static final String COLUMN_WECHAT = \"wechat\";\n public static final String COLUMN_BLOCK = \"block\";\n public static final String COLUMN_ROOM = \"room\";\n public static final String COLUMN_PHONE = \"phone\";\n\n public static User getById(long id) {\n try (Session s = sf.openSession()) {\n return s.get(User.class, id);\n }\n }\n\n public static User getByName(String name) {\n try (Session s = sf.openSession()) {\n return (User) s.createCriteria(User.class).add(Restrictions.eq(User.PROPERTY_NAME, name)).uniqueResult();\n }\n }\n\n public static User getByWechat(String wechat) {\n try {\n User u = cache.get(wechat);\n return u == NULL_USER ? null : u;\n } catch (ExecutionException e) {\n e.printStackTrace();\n return null;\n }\n }\n\n public static int update(User user) {\n try (Session s = sf.openSession()) {\n s.beginTransaction();\n s.update(user);\n s.getTransaction().commit();\n cache.put(user.getWechatId(), user);\n return 1;\n }\n }\n\n protected static void init() {\n try (Session s = SQLCore.sf.openSession()) {\n User.OFFICIAL_CHINA_UNICOM_XH = s.get(User.class, 100104L);\n User.OFFICIAL_CHINA_MOBILE_XH = s.get(User.class, 100864L);\n User.OFFICIAL_CHINA_MOBILE_FX = s.get(User.class, 100865L);\n }\n }\n\n private static LoadingCache<String, User> cache = CacheBuilder.newBuilder()\n .concurrencyLevel(4)\n .maximumSize(4096)\n .expireAfterAccess(Settings.I.User_Wechat_Cache_Expire_Time, TimeUnit.SECONDS)\n .build(new ValueLoader());\n\n private static class ValueLoader extends CacheLoader<String, User> {\n @Override\n public User load(String key) throws Exception {\n User u = TableUser.getByWechat0(key);\n return u == null ? NULL_USER : u;\n }\n }\n\n private static final User NULL_USER = new User();\n\n public static void flushCache() {\n cache.invalidateAll();\n }\n\n private static User getByWechat0(String wechat) {\n try (Session s = sf.openSession()) {\n return (User) s.createCriteria(User.class).add(Restrictions.eq(User.PROPERTY_WECHAT, wechat)).uniqueResult();\n }\n }\n\n}",
"public enum Command {\n\n REGISTER(0, RegisterHandler.class),\n QUERY(1, QueryHandler.class),\n SUBMIT(2, SubmitHandler.class),\n CANCEL(3, CancelHandler.class),\n PROFILE(4, ProfileHandler.class),\n LOGIN(10, LoginHandler.class),\n OPERATOR_INFO(11, OperatorInfoHandler.class),\n SIGN(12, SignHandler.class), //FIXME\n ;\n\n private static final Map<Integer, Command> ID_MAP = new HashMap<>();\n\n static {\n for (Command type : values()) {\n if (type.id >= 0) {\n ID_MAP.put(type.id, type);\n }\n }\n }\n\n public final String regex;\n public final Class<? extends WxMpMessageHandler> handler;\n public final int id;\n\n Command(int id, Class<? extends WxMpMessageHandler> handler) {\n this.id = id;\n this.regex = lang(\"REGEX_\" + name());\n this.handler = handler;\n }\n\n public static Command fromId(int id) {\n return ID_MAP.get(id);\n }\n\n @Override\n public String toString() {\n return name();\n }\n\n}",
"public static String format(String key, Object... args) {\n MessageFormat cache = format_cache.get(key);\n if (cache != null) {\n return cache.format(args);\n } else {\n cache = new MessageFormat(lang(key));\n format_cache.put(key, cache);\n return cache.format(args);\n }\n}"
] | import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.outxmlbuilder.TextBuilder;
import static love.sola.netsupport.config.Lang.format;
import java.util.Map;
import love.sola.netsupport.enums.Attribute;
import love.sola.netsupport.pojo.Operator;
import love.sola.netsupport.pojo.User;
import love.sola.netsupport.session.WechatSession;
import love.sola.netsupport.session.WxSession;
import love.sola.netsupport.sql.TableOperator;
import love.sola.netsupport.sql.TableUser;
import love.sola.netsupport.wechat.Command;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpMessageHandler; | /*
* This file is part of WechatTicketSystem.
*
* WechatTicketSystem is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* WechatTicketSystem 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with WechatTicketSystem. If not, see <http://www.gnu.org/licenses/>.
*/
package love.sola.netsupport.wechat.handler;
/**
* @author Sola {@literal <[email protected]>}
*/
public class SubscribeHandler implements WxMpMessageHandler {
@Override
public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService wxMpService, WxSessionManager sessionManager) throws WxErrorException {
TextBuilder out = WxMpXmlOutMessage.TEXT().fromUser(wxMessage.getToUserName()).toUser(wxMessage.getFromUserName());
String fromUser = wxMessage.getFromUserName(); | User u = TableUser.getByWechat(fromUser); | 2 |
NudgeApm/nudge-elasticstack-connector | src/main/java/org/nudge/elasticstack/context/elasticsearch/builder/TransactionSerializer.java | [
"public class Configuration {\n\n\tprivate static final Logger LOG = Logger.getLogger(Configuration.class);\n\n\t// Configuration files\n\tprivate static final String CONF_FILE = \"nudge-elastic.properties\";\n\tprivate static final String NUDGE_URL = \"nudge.url\";\n\tprivate static final String NUDGE_API_TOKEN = \"nudge.api.token\";\n\tprivate static final String NUDGE_APP_IDS = \"nudge.app.ids\";\n\tprivate static final String ELASTIC_INDEX = \"elastic.index\";\n\tprivate static final String OUTUPUT_ELASTIC_HOSTS = \"output.elastic.hosts\";\n\tprivate static final String DRY_RUN = \"plugin.dryrun\";\n\tprivate static final String RAWDATA_HISTORY = \"rawdata.history\";\n\n\t// Attributs\n\tprivate Properties properties = new Properties();\n\tprivate String nudgeUrl;\n\tprivate String nudgeApiToken;\n\tprivate String[] apps;\n\tprivate String elasticIndex;\n\tprivate String elasticHostURL;\n\tprivate boolean dryRun;\n\tprivate String rawdataHistory;\n\n\tprivate Configuration() {\n\t\tsearchPropertiesFile();\n\t}\n\n\tConfiguration(boolean initWithoutLoad) {\n\t\tif (!initWithoutLoad) {\n\t\t\tsearchPropertiesFile();\n\t\t}\n\t}\n\n\tConfiguration(Properties props) {\n\t\tthis.properties = props;\n\t\tloadProperties();\n\t}\n\n\tConfiguration(String pathFile) {\n\t\tloadPropertiesFile(pathFile);\n\t}\n\n\tprivate static class ConfigurationHolder {\n\t\tprivate static final Configuration instance = new Configuration();\n\t}\n\n\tpublic static Configuration getInstance() {\n\t\treturn ConfigurationHolder.instance;\n\t}\n\n\t/**\n\t * Load properties with the default conf file, must be placed next to the jar program.\n\t */\n\tprivate void searchPropertiesFile() {\n\t\ttry {\n\t\t\tPath folderJarPath = Paths\n\t\t\t\t\t.get(this.getClass().getProtectionDomain().getCodeSource().getLocation().toURI()).getParent();\n\t\t\tString confFile = folderJarPath.toString() + \"/\" + CONF_FILE;\n\t\t\tif (Files.exists(Paths.get(confFile))) {\n\t\t\t\tloadPropertiesFile(confFile);\n\t\t\t} else {\n\t\t\t\tURL confURL = ClassLoader.getSystemResource(CONF_FILE);\n\t\t\t\tif (confURL != null) {\n\t\t\t\t\tLOG.info(CONF_FILE + \" found at the classloader root path\");\n\t\t\t\t\tloadPropertiesFile(confURL.getPath());\n\t\t\t\t} else {\n\t\t\t\t\tLOG.warn(CONF_FILE + \" doesn't found at the classloader root path\");\n\t\t\t\t}\n\t\t\t}\n\t\t} catch (URISyntaxException e) {\n\t\t\tLOG.error(\"Incorrect path for configuration file\", e);\n\t\t}\n\t}\n\n\tprivate void loadPropertiesFile(String pathFile) {\n\t\tFile propsFile = new File(pathFile);\n\t\tboolean propsFileExists = propsFile.exists();\n\t\tif (propsFileExists) {\n\t\t\ttry (InputStream propsIS = new FileInputStream(propsFile)) {\n\t\t\t\tproperties.load(propsIS);\n\t\t\t} catch (IOException e) {\n\t\t\t\tthrow new IllegalStateException(e.getMessage(), e);\n\t\t\t}\n\t\t}\n\t\tloadProperties();\n\t}\n\n\tprivate void loadProperties() {\n\t\tnudgeUrl = getProperty(NUDGE_URL, \"https://monitor.nudge-apm.com\");\n\t\tif (!nudgeUrl.endsWith(\"/\"))\n\t\t\tnudgeUrl += \"/\";\n\t\tnudgeApiToken = checkNotNull(NUDGE_API_TOKEN);\n\t\tapps = split(checkNotNull(NUDGE_APP_IDS));\n\t\telasticHostURL = getProperty(OUTUPUT_ELASTIC_HOSTS, \"http://localhost:9200/\");\n\t\trawdataHistory = getProperty(RAWDATA_HISTORY, \"-10m\");\n\t\tif (!elasticHostURL.endsWith(\"/\"))\n\t\t\telasticHostURL += \"/\";\n\t\telasticIndex = getProperty(ELASTIC_INDEX, \"nudge\");\n\t\tdryRun = Boolean.valueOf(getProperty(DRY_RUN, \"false\"));\n\t}\n\n\tprivate String[] split(String composite) {\n\t\treturn composite.contains(\",\") ? composite.split(\",\") : composite.split(\";\");\n\t}\n\n\tString checkNotNull(String key) {\n\t\tString value = getProperty(key, null);\n\t\tif (value == null) {\n\t\t\tthrow new IllegalArgumentException(\"You must set the \\\"\" + key + \"\\\" parameter in your properties file.\");\n\t\t}\n\t\treturn value;\n\t}\n\n\tString getProperty(String key, String defaultValue) {\n\t\tString value = System.getProperty(\"nes.\" + key);\n\t\tif (value != null) {\n\t\t\treturn value;\n\t\t}\n\t\tvalue = properties.getProperty(key);\n\t\tif (value != null) {\n\t\t\treturn value.trim();\n\t\t}\n\t\treturn defaultValue;\n\t}\n\n\tpublic static void displayOptions() {\n\t\tSystem.out.println(NUDGE_URL + \" URL that should be used to connect to NudgeAPM\");\n\t\tSystem.out.println(NUDGE_API_TOKEN + \" Nudge authentication API token\");\n\t\tSystem.out.println(NUDGE_APP_IDS + \" App id to grab data from NudgeAPM\");\n\t\tSystem.out.println(ELASTIC_INDEX + \" Name of the elasticSearch index which will be create\");\n\t\tSystem.out.println(OUTUPUT_ELASTIC_HOSTS + \" Adress of the elasticSearch which will be use to index\");\n\t\tSystem.out.println(DRY_RUN + \" Collect and log, dont push to elasticsearch\");\n\t\tSystem.out.println(RAWDATA_HISTORY + \" Period of the Nudge Rawdata to push into Elasticsearch\");\n\t}\n\n\t// ======================\n\t// Getters and Setters\n\t// ======================\n\tpublic String getNudgeUrl() {\n\t\treturn nudgeUrl;\n\t}\n\n\tpublic String[] getAppIds() {\n\t\treturn apps;\n\t}\n\n\tpublic String getElasticIndex() {\n\t\treturn elasticIndex;\n\t}\n\n\tpublic String getElasticHostURL() {\n\t\treturn elasticHostURL;\n\t}\n\n\tpublic boolean getDryRun() {\n\t\treturn dryRun;\n\t}\n\n\tpublic String getRawdataHistory() {\n\t\treturn rawdataHistory;\n\t}\n\n\tpublic String getNudgeApiToken() {\n\t\treturn nudgeApiToken;\n\t}\n}",
"public class BulkFormat {\n\n\t@JsonProperty(\"index\")\n\tprivate Index indexElement;\n\n\tpublic BulkFormat() {\n\t\tthis.indexElement = new Index();\n\t}\n\n\tpublic Index getIndexElement() {\n\t\treturn indexElement;\n\t}\n\n\tpublic void setIndexElement(Index indexElement) {\n\t\tthis.indexElement = indexElement;\n\t}\n\n\t// -- Inner class Index\n\tpublic class Index {\n\t\tprivate String index;\n\t\tprivate String type;\n\t\tprivate String id;\n\n\t\t@JsonProperty(\"_index\")\n\t\tpublic String getIndex() {\n\t\t\tString format = \"yyyy-MM-dd\";\n\t\t\tjava.text.SimpleDateFormat formater = new java.text.SimpleDateFormat(format);\n\t\t\tjava.util.Date date = new java.util.Date();\n\t\t\tString dateFormater = formater.format(date);\n\t\t\treturn index + \"-\" + dateFormater;\n\t\t\t\n\t\t}\n\n\t\tpublic void setIndex(String index) {\n\t\t\tthis.index = index;\n\t\t}\n\n\t\t@JsonProperty(\"_type\")\n\t\tpublic String getType() {\n\t\t\treturn type;\n\t\t}\n\n\t\tpublic void setType(String type) {\n\t\t\tthis.type = type;\n\t\t}\n\n\t\t@JsonProperty(\"_id\")\n\t\tpublic String getId() {\n\t\t\treturn id;\n\t\t}\n\n\t\tpublic void setId(String id) {\n\t\t\tthis.id = id;\n\t\t}\n\t}\n}",
"public enum EventType {\n\n\t// TODO FMA add JAX-WS layer here\n\n\tGEO_LOC(\"geolocation\"),\n\tJAVA(\"layer_java\"),\n\tJAX_WS(\"layer_jax-ws\"),\n\tJMS(\"layer_jms\"),\n\tMBEAN(\"mbean\"),\n\tSQL(\"layer_sql\"),\n\tTRANSACTION(\"transaction\");\n\n\tprivate final String type;\n\n\tEventType(String type) {\n\t\tthis.type = type;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn type;\n\t}\n}",
"public class LayerEvent extends NudgeEvent {\n\n\tpublic LayerEvent(EventType type) {\n\t\tsuper.setType(type);\n\t}\n\n\t// ===========================\n\t// Getters and Setters\n\t// ===========================\n\n\t@Override\n\t@JsonProperty(\"layer_code\")\n\tpublic String getName() {\n\t\treturn super.getName();\n\t}\n\n\tpublic String getTransactionId() {\n\t\treturn super.getTransactionId();\n\t}\n\n\t@JsonProperty(\"layer_count\")\n\tpublic long getCount() {\n\t\treturn super.getCount();\n\t}\n\n\t@JsonProperty(\"layer_responseTime\")\n\tpublic long getResponseTime() {\n\t\treturn super.getResponseTime();\n\t}\n\n}",
"public abstract class NudgeEvent {\n\n\tprivate String appId;\n\tprivate String appName;\n\tprivate String host;\n\tprivate String hostname;\n\tprivate String date;\n\tprivate String name;\n\tprivate long responseTime;\n\tprivate long count;\n\tprivate EventType type;\n\tprivate String transactionId;\n\n\tNudgeEvent() {\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"NudgeEvent{\" +\n\t\t\t\t\"appId='\" + appId + '\\'' +\n\t\t\t\t\", appName='\" + appName + '\\'' +\n\t\t\t\t\", host='\" + host + '\\'' +\n\t\t\t\t\", hostname='\" + hostname + '\\'' +\n\t\t\t\t\", date='\" + date + '\\'' +\n\t\t\t\t\", name='\" + name + '\\'' +\n\t\t\t\t\", responseTime=\" + responseTime +\n\t\t\t\t\", count=\" + count +\n\t\t\t\t\", type='\" + type + '\\'' +\n\t\t\t\t\", transactionId='\" + transactionId + '\\'' +\n\t\t\t\t'}';\n\t}\n\n\t// =========================\n\t// Getters and Setters\n\t// =========================\n\n\n\tpublic void setAppId(String appId) {\n\t\tthis.appId = appId;\n\t}\n\n\tpublic String getAppName() {\n\t\treturn appName;\n\t}\n\n\tpublic void setAppName(String appName) {\n\t\tthis.appName = appName;\n\t}\n\n\tpublic String getHost() {\n\t\treturn host;\n\t}\n\n\tpublic void setHost(String host) {\n\t\tthis.host = host;\n\t}\n\n\tpublic String getHostname() {\n\t\treturn hostname;\n\t}\n\n\tpublic void setHostname(String hostname) {\n\t\tthis.hostname = hostname;\n\t}\n\n\t@JsonProperty(\"@timestamp\")\n\tpublic String getDate() {\n\t\treturn date;\n\t}\n\n\tpublic void setDate(String date) {\n\t\tthis.date = date;\n\t}\n\n\t@JsonProperty(\"transaction_name\")\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic String getAppId() {\n\t\treturn appId;\n\t}\n\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\n\tpublic EventType getType() {\n\t\treturn type;\n\t}\n\n\tpublic void setType(EventType type) {\n\t\tthis.type = type;\n\t}\n\n\t@JsonProperty(\"transaction_responseTime\")\n\tpublic long getResponseTime() {\n\t\treturn responseTime;\n\t}\n\n\tpublic void setResponseTime(long responseTime) {\n\t\tthis.responseTime = responseTime;\n\t}\n\n\t@JsonProperty(\"transaction_count\")\n\tpublic long getCount() {\n\t\treturn count;\n\t}\n\n\tpublic void setCount(long count) {\n\t\tthis.count = count;\n\t}\n\t\n\tpublic void setTransactionId(String transactionId) {\n\t\tthis.transactionId = transactionId;\n\t}\n\n\tpublic String getTransactionId() {\n\t\treturn transactionId;\n\t}\n\n}",
"@JsonInclude(value = JsonInclude.Include.NON_NULL)\npublic class TransactionEvent extends NudgeEvent {\n\n\t// WS attributs\n\tprivate Long responseTimeLayerJaxws;\n\tprivate String layerNameJaxws;\n\tprivate Long layerCountJaxws;\n\t// SQL attributs\n\tprivate Long responseTimeLayerSql;\n\tprivate String layerNameSql;\n\tprivate Long layerCountSql;\n\t// JMS attributs\n\tprivate Long responseTimeLayerJms;\n\tprivate String layerNameJms;\n\tprivate Long layerCountJms;\n\t// JAVA attributs\n\tprivate Long responseTimeLayerJava;\n\tprivate String layerNameJava;\n\tprivate Long layerCountJava;\n\n\tpublic TransactionEvent() {\n\t\tsuper.setType(EventType.TRANSACTION);\n\t}\n\n\t// ========================\n\t// Getters and Setters\n\t// =========================\n\t\n\t// ******** Layer Jaxws ***********\n\n\t@JsonProperty(\"layer_jaxws_responsetime\")\n\tpublic Long getResponseTimeLayerJaxws() {\n\t\treturn responseTimeLayerJaxws;\n\t}\n\t\n\tpublic void setResponseTimeLayerJaxws(Long responseTimeLayerJaxws) {\n\t\tthis.responseTimeLayerJaxws = responseTimeLayerJaxws;\n\t}\n\n\t@JsonProperty(\"layer_jaws_name\")\n\tpublic String getLayerNameJaxws() {\n\t\treturn layerNameJaxws;\n\t}\n\t\n\tpublic void setLayerNameJaxws(String layerNameJaxws) {\n\t\tthis.layerNameJaxws = layerNameJaxws;\n\t}\n\n\t@JsonProperty(\"layer_jaxws_count\")\n\tpublic Long getLayerCountJaxws() {\n\t\treturn layerCountJaxws;\n\t}\n\n\tpublic void setLayerCountJaxws(Long layerCountJaxws) {\n\t\tthis.layerCountJaxws = layerCountJaxws;\n\t}\n\n\t// ********* Layer sql *************\n\t\n\t@JsonProperty(\"layer_sql_responsetime\")\n\tpublic Long getResponseTimeLayerSql() {\n\t\treturn responseTimeLayerSql;\n\t}\n\n\tpublic void setResponseTimeLayerSql(Long responseTimeLayerSql) {\n\t\tthis.responseTimeLayerSql = responseTimeLayerSql;\n\t}\n\n\t@JsonProperty(\"layer_sql_name\")\n\tpublic String getLayerNameSql() {\n\t\treturn layerNameSql;\n\t}\n\n\tpublic void setLayerNameSql(String layerNameSql) {\n\t\tthis.layerNameSql = layerNameSql;\n\t}\n\n\t@JsonProperty(\"layer_sql_count\")\n\tpublic Long getLayerCountSql() {\n\t\treturn layerCountSql;\n\t}\n\n\tpublic void setLayerCountSql(Long layerCountSql) {\n\t\tthis.layerCountSql = layerCountSql;\n\t}\n\n\t// ******** Layer jms **************\n\t\n\t@JsonProperty(\"layer_jms_responsetime\")\n\tpublic Long getResponseTimeLayerJms() {\n\t\treturn responseTimeLayerJms;\n\t}\n\n\tpublic void setResponseTimeLayerJms(Long responseTimeLayerJms) {\n\t\tthis.responseTimeLayerJms = responseTimeLayerJms;\n\t}\n\n\t@JsonProperty(\"layer_jms_name\")\n\tpublic String getLayerNameJms() {\n\t\treturn layerNameJms;\n\t}\n\n\tpublic void setLayerNameJms(String layerNameJms) {\n\t\tthis.layerNameJms = layerNameJms;\n\t}\n\n\t@JsonProperty(\"layer_jms_count\")\n\tpublic Long getLayerCountJms() {\n\t\treturn layerCountJms;\n\t}\n\n\tpublic void setLayerCountJms(Long layerCountJms) {\n\t\tthis.layerCountJms = layerCountJms;\n\t}\n\n\t// ********** Layer java **************\n\t\n\t@JsonProperty(\"layer_java_responsetime\")\n\tpublic long getResponseTimeLayerJava() {\n\t\treturn responseTimeLayerJava;\n\t}\n\n\tpublic void setResponseTimeLayerJava(long responseTimeLayerJava) {\n\t\tthis.responseTimeLayerJava = responseTimeLayerJava;\n\t} \n\n\t@JsonProperty(\"layer_java_name\")\n\tpublic String getLayerNameJava() {\n\t\treturn layerNameJava;\n\t}\n\n\tpublic void setLayerNameJava(String layerNameJava) {\n\t\tthis.layerNameJava = layerNameJava;\n\t}\n\n\t@JsonProperty(\"layer_java_count\")\n\tpublic Long getLayerCountJava() {\n\t\treturn layerCountJava;\n\t}\n\n\tpublic void setLayerCountJava(Long layerCountJava) {\n\t\tthis.layerCountJava = layerCountJava;\n\t}\n\t\n} //end of class",
"public class LayerCallDTO {\n\tprivate String code;\n\tprivate long count;\n\tprivate long responseTime;\n\tprivate long timestamp;\n\n\tpublic String getCode() {\n\t\treturn code;\n\t}\n\n\tpublic void setCode(String code) {\n\t\tthis.code = code;\n\t}\n\n\tpublic long getCount() {\n\t\treturn count;\n\t}\n\n\tpublic void setCount(long count) {\n\t\tthis.count = count;\n\t}\n\n\tpublic long getResponseTime() {\n\t\treturn responseTime;\n\t}\n\n\tpublic void setResponseTime(long responseTime) {\n\t\tthis.responseTime = responseTime;\n\t}\n\n\tpublic long getTimestamp() {\n\t\treturn timestamp;\n\t}\n\n\tpublic void setTimestamp(long timestamp) {\n\t\tthis.timestamp = timestamp;\n\t}\n\n}",
"public class LayerDTO {\n\n private String layerName;\n private long time;\n private long count;\n private List<LayerCallDTO> calls;\n\n /*** Getters and Setters ***/\n\n public String getLayerName() {\n return layerName;\n }\n\n public void setLayerName(String layerName) {\n this.layerName = layerName;\n }\n\n public long getTime() {\n return time;\n }\n\n public void setTime(long time) {\n this.time = time;\n }\n\n public long getCount() {\n return count;\n }\n\n public void setCount(long count) {\n this.count = count;\n }\n\n public List<LayerCallDTO> getCalls() {\n return calls;\n }\n\n public void setCalls(List<LayerCallDTO> calls) {\n this.calls = calls;\n }\n\n /*** Utility methods ***/\n public LayerCallDTO createAddLayerDetail() {\n checkLayerDetailList();\n LayerCallDTO layerCall = new LayerCallDTO();\n getCalls().add(layerCall);\n return layerCall;\n }\n\n public LayerCallDTO addLayerDetail(LayerCallDTO layerCall) {\n if (layerCall == null) {\n throw new IllegalArgumentException(\"The layerCall is invalid, must not be null\");\n }\n checkLayerDetailList();\n\n getCalls().add(layerCall);\n return layerCall;\n }\n\n private void checkLayerDetailList() {\n if (getCalls() == null) {\n setCalls(new ArrayList<LayerCallDTO>());\n }\n }\n\n}",
"public class TransactionDTO {\n\n private String id;\n private String code;\n private long startTime;\n private long endTime;\n private String userIp;\n private List<LayerDTO> layers;\n\n public TransactionDTO() {\n this.id = UUID.randomUUID().toString();\n }\n\n public LayerDTO addNewLayerDTO() {\n if (getLayers() == null) {\n setLayers(new ArrayList<LayerDTO>());\n }\n LayerDTO layerDTO = new LayerDTO();\n getLayers().add(layerDTO);\n return layerDTO;\n }\n\n /*** Getters and Setters ***/\n\n public String getId() {\n return id;\n }\n\n public void setId(String id) {\n this.id = id;\n }\n\n public String getCode() {\n return code;\n }\n\n public void setCode(String code) {\n this.code = code;\n }\n\n public long getStartTime() {\n return startTime;\n }\n\n public void setStartTime(long startTime) {\n this.startTime = startTime;\n }\n\n public long getEndTime() {\n return endTime;\n }\n\n public void setEndTime(long endTime) {\n this.endTime = endTime;\n }\n\n public String getUserIp() {\n return userIp;\n }\n\n public void setUserIp(String userIp) {\n this.userIp = userIp;\n }\n\n public List<LayerDTO> getLayers() {\n return layers;\n }\n\n public void setLayers(List<LayerDTO> layers) {\n this.layers = layers;\n }\n \n}"
] | import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.apache.log4j.Logger;
import org.nudge.elasticstack.Configuration;
import org.nudge.elasticstack.context.elasticsearch.bean.BulkFormat;
import org.nudge.elasticstack.context.elasticsearch.bean.EventType;
import org.nudge.elasticstack.context.elasticsearch.bean.LayerEvent;
import org.nudge.elasticstack.context.elasticsearch.bean.NudgeEvent;
import org.nudge.elasticstack.context.elasticsearch.bean.TransactionEvent;
import org.nudge.elasticstack.context.nudge.dto.LayerCallDTO;
import org.nudge.elasticstack.context.nudge.dto.LayerDTO;
import org.nudge.elasticstack.context.nudge.dto.TransactionDTO;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID; | package org.nudge.elasticstack.context.elasticsearch.builder;
/**
* Serialize Nudge transaction into JSON object.
*/
public class TransactionSerializer {
private static final Logger LOG = Logger.getLogger(TransactionSerializer.class.getName());
private static final String lineBreak = "\n";
private Configuration config = Configuration.getInstance();
/**
* Retrieve transaction data from rawdata and add it to parse.
* @param appId
* @param transactionList
* @return
* @throws ParseException
* @throws JsonProcessingException
*/
public List<NudgeEvent> serialize(String appId, String appName, String host, String hostname, List<TransactionDTO> transactionList)
throws ParseException, JsonProcessingException {
List<NudgeEvent> events = new ArrayList<>();
for (TransactionDTO trans : transactionList) {
TransactionEvent transactionEvent = new TransactionEvent();
// build the transaction JSON object
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
String date = sdf.format(trans.getStartTime());
transactionEvent.setAppId(appId);
transactionEvent.setAppName(appName);
transactionEvent.setHost(host);
transactionEvent.setHostname(hostname);
transactionEvent.setName(trans.getCode());
transactionEvent.setResponseTime(trans.getEndTime() - trans.getStartTime());
transactionEvent.setDate(date);
transactionEvent.setCount(1L);
transactionEvent.setTransactionId(trans.getId());
events.add(transactionEvent);
// handle layers - build for each layers a JSON object
events.addAll(buildLayerEvents(trans.getLayers(), transactionEvent));
}
return events;
}
/**
* Retrieve layer from transaction
*
* @param eventTrans
* @return
*/
public TransactionEvent nullLayer(TransactionEvent eventTrans) {
if (eventTrans.getLayerNameSql() == null) {
eventTrans.setResponseTimeLayerSql(0L);
eventTrans.setLayerCountSql(0L);
eventTrans.setLayerNameSql("null layer");
}
if (eventTrans.getLayerNameJaxws() == null) {
eventTrans.setResponseTimeLayerJaxws(0L);
eventTrans.setLayerCountJaxws(0L);
eventTrans.setLayerNameJaxws("null layer");
}
if (eventTrans.getLayerNameJms() == null) {
eventTrans.setLayerCountJms(0L);
eventTrans.setResponseTimeLayerJms(0L);
eventTrans.setLayerNameJms("null layer");
}
return eventTrans;
}
protected LayerEvent createLayerEvent(EventType type, LayerCallDTO layerCallDTO, TransactionEvent transaction) {
SimpleDateFormat sdfr = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
String sqlTimestamp = sdfr.format(layerCallDTO.getTimestamp());
LayerEvent layerEvent = new LayerEvent(type);
layerEvent.setAppId(transaction.getAppId());
layerEvent.setAppName(transaction.getAppName());
layerEvent.setHost(transaction.getHost());
layerEvent.setHostname(transaction.getHostname());
layerEvent.setDate(sqlTimestamp);
layerEvent.setName(layerCallDTO.getCode());
layerEvent.setCount(layerCallDTO.getCount());
layerEvent.setResponseTime(layerCallDTO.getResponseTime());
layerEvent.setTransactionId(transaction.getTransactionId());
return layerEvent;
}
protected LayerEvent createJavaLayerEvent(TransactionEvent transaction, long responseTime) {
LayerEvent javaLayer = new LayerEvent(EventType.JAVA);
javaLayer.setAppId(transaction.getAppId());
javaLayer.setAppName(transaction.getAppName());
javaLayer.setHost(transaction.getHost());
javaLayer.setHostname(transaction.getHostname());
javaLayer.setDate(transaction.getDate());
javaLayer.setName(transaction.getName());
javaLayer.setCount(transaction.getCount());
javaLayer.setResponseTime(responseTime);
javaLayer.setTransactionId(transaction.getTransactionId());
return javaLayer;
}
/**
* Build layer events
*
* @param rawdataLayers
* @param transactionEvent
* @throws ParseException
* @throws JsonProcessingException
*/ | public List<LayerEvent> buildLayerEvents(List<LayerDTO> rawdataLayers, TransactionEvent transactionEvent) | 7 |
jmcampanini/gexf4j-core | src/test/java/com/ojn/gexf4j/core/impl/data/AttributeValueImplTest.java | [
"public interface Attribute {\n\n\tString getId();\n\t\n\tString getTitle();\n\tAttribute setTitle(String title);\n\t\n\tAttributeType getAttributeType();\n\t\n\tboolean hasDefaultValue();\n\tAttribute clearDefaultValue();\n\tString getDefaultValue();\n\tAttribute setDefaultValue(String defaultValue);\n\t\n\tList<String> getOptions();\n\t\n\tAttributeValue createValue(String value);\n}",
"public enum AttributeClass {\n\n\tNODE,\n\tEDGE,\n}",
"public enum AttributeType {\n\n\tINTEGER,\n\tLONG,\n\tDOUBLE,\n\tFLOAT,\n\tBOOLEAN,\n\tSTRING,\n\tLISTSTRING,\n\tANYURI,\n}",
"public interface AttributeValue extends Dynamic<AttributeValue> {\n\n\tAttribute getAttribute();\n\t\n\tString getValue();\n\tAttributeValue setValue(String value);\n}",
"public abstract class AttributeValueTest {\n\n\tprotected abstract Attribute newAttribute();\n\tprotected abstract AttributeValue newAttributeValue(Attribute attrib, String value);\n\t\n\tprivate String value = null;\n\tprivate Attribute attrib = null;\n\tprivate AttributeValue av = null;\n\t\n\t@Before\n\tpublic void before() {\n\t\tvalue = UUID.randomUUID().toString();\n\t\tattrib = newAttribute();\n\t\tav = newAttributeValue(attrib, value);\n\t}\n\t\n\t@Test\n\tpublic void valueFor() {\n\t\tassertThat(av.getAttribute(), is(equalTo(attrib)));\n\t}\n\t\n\t@Test\n\tpublic void setValueValid() {\n\t\tString newValue = UUID.randomUUID().toString();\n\t\tav.setValue(newValue);\n\t\t\n\t\tassertThat(av.getValue(), is(equalTo(newValue)));\n\t}\n\t\n\t@Test(expected=IllegalArgumentException.class)\n\tpublic void setValueNull() {\n\t\tav.setValue(null);\n\t}\n}"
] | import java.util.UUID;
import com.ojn.gexf4j.core.data.Attribute;
import com.ojn.gexf4j.core.data.AttributeClass;
import com.ojn.gexf4j.core.data.AttributeType;
import com.ojn.gexf4j.core.data.AttributeValue;
import com.ojn.gexf4j.core.data.AttributeValueTest; | package com.ojn.gexf4j.core.impl.data;
public class AttributeValueImplTest extends AttributeValueTest {
@Override | protected Attribute newAttribute() { | 0 |
wrey75/WaveCleaner | src/main/java/com/oxande/xmlswing/components/JTreeUI.java | [
"public class AttributeDefinition {\r\n\t\r\n\tpublic final static Map<String, String> ALIGNS = new HashMap<String, String>();\r\n\tpublic final static Map<String, String> CLOSE_OPERATIONS = new HashMap<String, String>();\r\n\tpublic final static Map<String, String> CURSORS = new HashMap<String, String>();\r\n\tpublic final static Map<String, String> LIST_SEL_MODE = new HashMap<String, String>();\r\n\t\r\n\tstatic {\r\n\t\t\r\n\t\tCURSORS.put( \"crosshair\", \"CROSSHAIR_CURSOR\" );\r\n\t\tCURSORS.put( \"default\", \"DEFAULT_CURSOR\" );\r\n\t\tCURSORS.put( \"hand\", \"HAND_CURSOR\" );\r\n\t\tCURSORS.put( \"move\", \"MOVE_CURSOR\" );\r\n\t\t\r\n//\t\tpublic static final int \tCUSTOM_CURSOR \t-1\r\n//\t\tpublic static final int \tN_RESIZE_CURSOR \t8\r\n//\t\tpublic static final int \tNE_RESIZE_CURSOR \t7\r\n//\t\tpublic static final int \tNW_RESIZE_CURSOR \t6\r\n//\t\tpublic static final int \tS_RESIZE_CURSOR \t9\r\n//\t\tpublic static final int \tSE_RESIZE_CURSOR \t5\r\n//\t\tpublic static final int \tSW_RESIZE_CURSOR \t4\r\n//\t\tCURSORS.put( \"\", \"W_RESIZE_CURSOR\" );\r\n\t\t\r\n\t\tCURSORS.put( \"text\", \"TEXT_CURSOR\" );\r\n\t\tCURSORS.put( \"wait\", \"WAIT_CURSOR\" );\r\n\t\t\r\n\t\tCLOSE_OPERATIONS.put( \"nothing\", \"DO_NOTHING_ON_CLOSE\" );\r\n\t\tCLOSE_OPERATIONS.put( \"hide\", \"HIDE_ON_CLOSE\" );\r\n\t\tCLOSE_OPERATIONS.put( \"dispose\", \"DISPOSE_ON_CLOSE\" );\r\n\t\tCLOSE_OPERATIONS.put( \"exit\", \"EXIT_ON_CLOSE\" );\r\n\r\n\t\tString scName = SwingConstants.class.getName();\r\n\t\tALIGNS.put( \"bottom\", scName + \".BOTTOM\" );\r\n\t\tALIGNS.put( \"center\", scName + \".CENTER\" );\r\n\t\tALIGNS.put( \"east\", scName + \".EAST\" );\r\n\t\tALIGNS.put( \"leading\", scName + \".LEADING\" );\r\n\t\tALIGNS.put( \"left\", scName + \".LEFT\" );\r\n\t\tALIGNS.put( \"next\", scName + \".NEXT\" );\r\n\t\tALIGNS.put( \"north\", scName + \".NORTH\" );\r\n\t\tALIGNS.put( \"right\", scName + \".RIGHT\" );\r\n\t\tALIGNS.put( \"top\", scName + \".TOP\" );\r\n\t\tALIGNS.put( \"trailing\", scName + \".TRAILING\" );\r\n\t\tALIGNS.put( \"west\", scName + \".WEST\" );\r\n\t\t\r\n\t\t\r\n\t\tLIST_SEL_MODE.put(\"single\", \"javax.swing.ListSelectionModel.SINGLE_SELECTION\" ); \r\n\t\tLIST_SEL_MODE.put(\"interval\", \"javax.swing.ListSelectionModel.SINGLE_INTERVAL_SELECTION\" );\r\n\t\tLIST_SEL_MODE.put(\"any\", \"javax.swing.ListSelectionModel.MULTIPLE_INTERVAL_SELECTION\" );\r\n\t}\r\n\t\r\n\t/**\r\n\t * Values for automatic affectation of the correct\r\n\t * parameters for the methods. \r\n\t *\r\n\t */\r\n\tpublic enum ClassType {\r\n\t\tTEXT,\r\n\t\tSTRING,\r\n\t\tCHAR,\r\n\t\tINTEGER,\r\n\t\tBOOLEAN,\r\n\t\tPERCENT,\r\n\t\tCOLOR,\r\n\t\tALIGNMENT,\r\n\t\tDIMENSION,\r\n\t\tINSETS,\r\n\t\tKEYSTROKE,\r\n\t\tVERTICAL_OR_HORIZONTAL, // Not yet implemented\r\n\t\tJSPLITPANE_ORIENTATION,\r\n\t\tJLIST_ORIENTATION,\r\n\t\tICON,\r\n\t\tCURSOR,\r\n\t\tCOMPONENT,\r\n\t\tJTABLE_AUTO_RESIZE, // For JTable implementation\r\n\t\tJLIST_SELECT_MODE,\r\n\t};\r\n\t\r\n\tprivate String attrName;\r\n\tprivate String methodName;\r\n\tprivate String defaultValue = null;\r\n\tprivate ClassType type;\r\n\t\r\n\t/**\r\n\t * Create the attribute.\r\n\t * \r\n\t * @param attributeName the attribute name.\r\n\t * @param methodName the method name (if <code>null</code> then\r\n\t * \t\t\tthe method name is created implicitly based on\r\n\t * \t\t\tthe attribute name with the first character capitalized\r\n\t * \t\t\tand prefixed by \"set\".\r\n\t * @param type the type of the expected variable.\r\n\t * @param defaultValue the default value if exists (usually not provided).\r\n\t * \t\t\tThis default value is used only for some attribute types.\r\n\t */\r\n\tpublic AttributeDefinition( String attributeName, String methodName, ClassType type, String defaultValue ){\r\n\t\tthis.attrName = attributeName;\r\n\t\tif( methodName == null ){\r\n\t\t\tthis.methodName = \"set\" + UIParser.capitalizeFirst(attributeName);\r\n\t\t}\r\n\t\telse {\r\n\t\t\tthis.methodName = methodName;\r\n\t\t}\r\n\t\tthis.type = type;\r\n\t\tthis.defaultValue = defaultValue;\r\n\t}\r\n\r\n\tpublic AttributeDefinition( String attributeName, String methodName, ClassType type ){\r\n\t\tthis( attributeName, methodName, type, null );\r\n\t}\r\n\r\n\tpublic String getParameterIfExist( Element e ) throws UnexpectedTag{\r\n\t\tString[] params = getParameters(e);\r\n\t\treturn( params == null ? null : params[0]);\r\n\t}\r\n\t\r\n\t/**\r\n\t * Get the parameters for this element.\r\n\t * \r\n\t * @param e the element.\r\n\t * @return the list of the arguments or <code>null</code>\r\n\t * \t\tif there is no attribute for this definition.\r\n\t * @throws UnexpectedTag \r\n\t */\r\n\tpublic String[] getParameters( Element e ) throws UnexpectedTag{\r\n\t\tString[] params = null;\r\n\t\t\r\n\t\tswitch( type ){\r\n\t\tcase TEXT :\r\n\t\t\tString txt = Parser.getTextContents(e).trim();\r\n\t\t\tif( txt.trim().length() == 0 ){\r\n\t\t\t\ttxt = Parser.getAttribute(e, \"text\");\r\n\t\t\t}\r\n\t\t\tif( txt != null ){\r\n\t\t\t\tparams = new String[] { JavaCode.toParam(txt) };\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\t\t\t\r\n\t\tcase BOOLEAN :\r\n\t\t\tBoolean b = Parser.getBooleanAttribute(e, attrName);\r\n\t\t\tif( b != null ){\r\n\t\t\t\tparams = new String[] { JavaCode.toParam(b) };\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\r\n\t\tcase INTEGER :\r\n\t\t\tInteger i = Parser.getIntegerAttribute(e, attrName);\r\n\t\t\tif( i != null ){\r\n\t\t\t\tparams = new String[] { JavaCode.toParam( i ) };\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\r\n\t\tcase PERCENT :\r\n\t\t\tDouble percent = Parser.getPercentageAttribute(e, attrName);\r\n\t\t\tif( percent != null ){\r\n\t\t\t\tparams = new String[] { JavaCode.toParam( percent.doubleValue() ) };\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\r\n\t\tcase STRING :\r\n\t\t\tString s = Parser.getStringAttribute(e, attrName, defaultValue );\r\n\t\t\tif( s != null ){\r\n\t\t\t\tparams = new String[] { JavaCode.toParam( s ) };\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\r\n\t\tcase CHAR :\r\n\t\t\tString chars = Parser.getAttribute(e, attrName);\r\n\t\t\tif( chars != null ){\r\n\t\t\t\tparams = new String[] { JavaCode.toParam( chars.charAt(0) ) };\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\r\n\t\tcase COLOR :\r\n\t\t\tColor color = Parser.getColorAttribute(e, attrName);\r\n\t\t\tif( color != null ){\r\n\t\t\t\tparams = new String[] { JavaCode.toParam( color ) };\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\r\n\t\tcase ALIGNMENT :\r\n\t\t\tString align = Parser.getAttribute(e, attrName);\r\n\t\t\tif( align != null ){\r\n\t\t\t\tString constant = null;\r\n\t\t\t\tconstant = ALIGNS.get( align.trim().toLowerCase() );\r\n\t\t\t\tif( constant != null ){\r\n\t\t\t\t\tparams = new String[] { constant };\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\r\n\t\tcase ICON :\r\n\t\t\tString iconName = Parser.getAttribute(e, attrName);\r\n\t\t\tif( iconName != null ){\r\n\t\t\t\tString icon;\r\n\t\t\t\tif( iconName.startsWith(\"http:\" ) || iconName.startsWith(\"ftp:\" ) ){\r\n\t\t\t\t\ticon = \"new \" + ImageIcon.class.getName() + \"( new \" + URL.class.getName() + \"( \" + iconName + \") )\";\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\ticon = \"(new javax.swing.ImageIcon(getClass().getResource(\" + JavaClass.toParam(iconName) + \")))\";\r\n\t\t\t\t}\r\n\t\t\t\tparams = new String[] { icon };\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\r\n\t\tcase CURSOR :\r\n\t\t\tString cursorName = Parser.getAttribute(e, attrName);\r\n\t\t\tif( cursorName != null ){\r\n\t\t\t\tString cursor = Cursor.class.getName() + \"getPredefinedCursor( \" + Cursor.class.getName() + cursorName + \") )\";\r\n\t\t\t\tparams = new String[] { cursor };\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\r\n\t\tcase JSPLITPANE_ORIENTATION :\r\n\t\t\tString orientation = Parser.getAttribute(e, attrName);\r\n\t\t\tif( orientation != null ){\r\n\t\t\t\tif( orientation.equalsIgnoreCase(\"horizontal\") ){\r\n\t\t\t\t\tparams = new String[] { \"JSplitPane.HORIZONTAL_SPLIT\" };\r\n\t\t\t\t}\r\n\t\t\t\telse if( orientation.equalsIgnoreCase(\"vertical\") ){\r\n\t\t\t\t\tparams = new String[] { \"JSplitPane.VERTICAL_SPLIT\" };\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\tthrow new IllegalArgumentException(\"horizontal or vertical expected for this tag.\" );\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\r\n\t\tcase JLIST_ORIENTATION :\r\n\t\t\torientation = Parser.getAttribute(e, attrName);\r\n\t\t\tif( orientation != null ){\r\n\t\t\t\tif( orientation.equalsIgnoreCase(\"hwrap\") ){\r\n\t\t\t\t\tparams = new String[] { \"JList.HORIZONTAL_WRAP\" };\r\n\t\t\t\t}\r\n\t\t\t\telse if( orientation.equalsIgnoreCase(\"vwrap\") ){\r\n\t\t\t\t\tparams = new String[] { \"JSplitPane.VERTICAL_WRAP\" };\r\n\t\t\t\t}\r\n\t\t\t\telse if( orientation.equalsIgnoreCase(\"vertical\") ){\r\n\t\t\t\t\tparams = new String[] { \"JSplitPane.VERTICAL\" };\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\tthrow new IllegalArgumentException(\"hwrap, vwrap or vertical expected for this tag.\" );\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\r\n\t\tcase DIMENSION :\r\n\t\t\tString dim = Parser.getAttribute(e, attrName);\r\n\t\t\tif( dim != null ){\r\n\t\t\t\tString[] vector = dim.split(\",\");\r\n\t\t\t\tif( vector.length < 2 ){\r\n\t\t\t\t\tthrow new UnexpectedTag(\"attribute \\\"\" + attrName + \"\\\" expects 2 comma separated values.\" );\r\n\t\t\t\t}\r\n\t\t\t\ttry {\r\n\t\t\t\t\tint width = Integer.parseInt( vector[0].trim() );\r\n\t\t\t\t\tint height = Integer.parseInt( vector[1].trim() );\r\n\t\t\t\t\tparams = new String[] { \"new java.awt.Dimension(\" + width + \",\" + height +\")\" };\r\n\t\t\t\t}\r\n\t\t\t\tcatch( NumberFormatException ex ){\r\n\t\t\t\t\tthrow new UnexpectedTag(\"attribute \\\"\" + attrName + \"\\\" expects numeric values.\" );\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\r\n\t\tcase INSETS :\r\n\t\t\tString insets = Parser.getAttribute(e, attrName);\r\n\t\t\tif( insets != null ){\r\n\t\t\t\tString[] vector = insets.split(\",\");\r\n\t\t\t\ttry {\r\n\t\t\t\t\tint top = 0, left = 0, bottom = 0, right = 0;\r\n\t\t\t\t\t// if only one value, the inset is assumed for others.\r\n\t\t\t\t\tswitch( vector.length ){\r\n\t\t\t\t\tcase 1 :\r\n\t\t\t\t\t\ttop = Integer.parseInt( vector[0].trim() );\r\n\t\t\t\t\t\tleft = bottom = right = top;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tcase 2 :\r\n\t\t\t\t\t\tbottom = top = Integer.parseInt( vector[0].trim() );\r\n\t\t\t\t\t\tright = left = Integer.parseInt( vector[1].trim() );\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tcase 4 :\r\n\t\t\t\t\t\ttop = Integer.parseInt( vector[0].trim() );\r\n\t\t\t\t\t\tleft = Integer.parseInt( vector[1].trim() );\r\n\t\t\t\t\t\tbottom = Integer.parseInt( vector[2].trim() );\r\n\t\t\t\t\t\tright = Integer.parseInt( vector[3].trim() );\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\tdefault :\r\n\t\t\t\t\t\tthrow new UnexpectedTag(\"attribute \\\"\" + attrName + \"\\\" expects only 1, 2 or 4 numeric values.\" );\t\t\t\t\t\r\n\t\t\t\t\t}\r\n\t\t\t\t\tparams = new String[] { \"new java.awt.Insets(\" + top + \",\" + left + \",\" + bottom + \",\" + right + \")\" };\r\n\t\t\t\t}\r\n\t\t\t\tcatch( NumberFormatException ex ){\r\n\t\t\t\t\tthrow new UnexpectedTag(\"attribute \\\"\" + attrName + \"\\\" expects numeric values.\" );\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\r\n\t\tcase KEYSTROKE :\r\n\t\t\tString keystroke = Parser.getAttribute(e, attrName);\r\n\t\t\tif( keystroke != null ){\r\n\t\t\t\tKeyStroke ks = KeyStroke.getKeyStroke(keystroke);\r\n\t\t\t\tif( ks == null ){\r\n\t\t\t\t\tthrow new UnexpectedTag(\"Keystroke \\\"\" + keystroke + \"\\\" invalid\" );\r\n\t\t\t\t}\r\n\t\t\t\tparams = new String[] { \"javax.swing.KeyStroke.getKeyStroke(\" + JavaClass.toParam(keystroke) + \")\" };\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\t\t\t\r\n\t\tcase JTABLE_AUTO_RESIZE :\r\n\t\t\tString autoResizeMode = Parser.getStringAttribute(e, attrName, defaultValue);\r\n\t\t\tif( autoResizeMode != null ){\r\n\t\t\t\tif( autoResizeMode.equalsIgnoreCase(\"off\")){\r\n\t\t\t\t\tparams = new String[] { \"JTable.AUTO_RESIZE_OFF\" };\r\n\t\t\t\t}\r\n\t\t\t\telse if( autoResizeMode.equalsIgnoreCase(\"next\")){\r\n\t\t\t\t\tparams = new String[] { \"JTable.AUTO_RESIZE_NEXT_COLUMN\" };\r\n\t\t\t\t}\r\n\t\t\t\telse if( autoResizeMode.equalsIgnoreCase(\"subsequent\")){\r\n\t\t\t\t\tparams = new String[] { \"JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS\" };\r\n\t\t\t\t}\r\n\t\t\t\telse if( autoResizeMode.equalsIgnoreCase(\"last\")){\r\n\t\t\t\t\tparams = new String[] { \"JTable.AUTO_RESIZE_LAST_COLUMN\" };\r\n\t\t\t\t}\r\n\t\t\t\telse if( autoResizeMode.equalsIgnoreCase(\"all\")){\r\n\t\t\t\t\tparams = new String[] { \"JTable.AUTO_RESIZE_ALL_COLUMNS\" };\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\tthrow new UnexpectedTag(\"JTable \\\"autoResizeMode\\\" attribute not valid.\");\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\t\t\r\n\t\tcase JLIST_SELECT_MODE :\r\n\t\t\tString selectMode = Parser.getStringAttribute(e, attrName, defaultValue);\r\n\t\t\tif( selectMode != null ){\r\n\t\t\t\tString constant = null;\r\n\t\t\t\tconstant = LIST_SEL_MODE.get( selectMode.toLowerCase() );\r\n\t\t\t\tif( constant != null ){\r\n\t\t\t\t\tparams = new String[] { constant };\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\tthrow new UnexpectedTag(\"value \\\"\" + selectMode + \"\\\" for attribute \" + attrName + \" is not valid.\");\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\t\t\t\r\n\t\tcase VERTICAL_OR_HORIZONTAL :\r\n\t\t\torientation = Parser.getAttribute(e, attrName);\r\n\t\t\tif( orientation != null ){\r\n\t\t\t\tif( orientation.equalsIgnoreCase(\"horizontal\") ){\r\n\t\t\t\t\tparams = new String[] { \"JSlider.HORIZONTAL\" };\r\n\t\t\t\t}\r\n\t\t\t\telse if( orientation.equalsIgnoreCase(\"vertical\") ){\r\n\t\t\t\t\tparams = new String[] { \"JSlider.VERTICAL\" };\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\tthrow new IllegalArgumentException(\"horizontal or vertical expected for this tag ('\" + orientation + \"') provided.\" );\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\r\n\t\tdefault :\r\n\t\t\tif( Parser.getAttribute(e, attrName) != null ){\r\n\t\t\t\tthrow new IllegalArgumentException(\"Type \" + type + \" not yet supported.\" );\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn params;\r\n\t}\r\n\t\r\n\tpublic void addToMethod( JavaMethod jmethod, Element e, String varName ) throws UnexpectedTag{\r\n\t\tString[] params = getParameters(e);\r\n\t\tif( params != null ){\r\n\t\t\tjmethod.addCall( varName + \".\" + methodName, params );\r\n\t\t}\r\n\t}\r\n\t\r\n\r\n}\r",
"public class AttributesController {\r\n\tList<AttributeDefinition> list = new ArrayList<AttributeDefinition>();\r\n\tAttributesController parent = null;\r\n\r\n\tpublic AttributesController( AttributesController parent, AttributeDefinition[] arr ){\r\n\t\tthis.parent = parent;\r\n\t\tthis.list.addAll( Arrays.asList(arr) );\r\n\t}\r\n\r\n\tpublic AttributesController( AttributeDefinition[] arr ){\r\n\t\tthis(null,arr);\r\n\t}\r\n\r\n\t/**\r\n\t * @return the parent\r\n\t */\r\n\tpublic AttributesController getParent() {\r\n\t\treturn parent;\r\n\t}\r\n\r\n\t/**\r\n\t * @param parent the parent to set\r\n\t */\r\n\tpublic void setParent(AttributesController parent) {\r\n\t\tthis.parent = parent;\r\n\t}\r\n\r\n\tpublic void addToMethod( JavaMethod jmethod, Element e, String varName ) throws UnexpectedTag{\r\n\t\tif( parent != null ){\r\n\t\t\tparent.addToMethod(jmethod, e, varName);\r\n\t\t}\r\n\t\tfor( AttributeDefinition def : list ){\r\n\t\t\tdef.addToMethod(jmethod, e, varName);\r\n\t\t}\r\n\t}\r\n\t\r\n}\r",
"public final class Parser {\r\n\tpublic static final Map<String, Color> COLORS = new HashMap<String, Color>();\r\n\t\r\n\tstatic {\r\n\t\tCOLORS.put( \"black\", Color.BLACK );\r\n\t\tCOLORS.put( \"blue\", Color.BLUE );\r\n\t\tCOLORS.put( \"cyan\", Color.CYAN );\r\n\t\tCOLORS.put( \"darkgray\", Color.DARK_GRAY );\r\n\t\tCOLORS.put( \"gray\", Color.GRAY );\r\n\t\tCOLORS.put( \"green\", Color.GREEN );\r\n\t\tCOLORS.put( \"lightgray\", Color.LIGHT_GRAY );\r\n\t\tCOLORS.put( \"magenta\", Color.MAGENTA );\r\n\t\tCOLORS.put( \"orange\", Color.ORANGE );\r\n\t\tCOLORS.put( \"pink\", Color.PINK );\r\n\t\tCOLORS.put( \"red\", Color.RED );\r\n\t\tCOLORS.put( \"white\", Color.WHITE );\r\n\t\tCOLORS.put( \"yellow\", Color.YELLOW );\r\n\t}\r\n\t\r\n\t/**\r\n\t * The attribute for the variable name of the component.\r\n\t */\r\n\tpublic static final String ID_ATTRIBUTE = \"id\";\r\n\t\r\n\t/**\r\n\t * The attribute for the class name of the component. Usually,\r\n\t * the class name is a predefined class, but if the developper\r\n\t * wants to used an extended class rather than the normal class,\r\n\t * he can do it by changing this attribute. This attribute is available\r\n\t * for any component.\r\n\t * \r\n\t */\r\n\tpublic static final String CLASS_ATTRIBUTE = \"class\";\r\n\t\r\n\tprivate static Map<String, Integer> ids = new HashMap<String, Integer>();\r\n\r\n\t/**\r\n\t * Clear the IDs created before.\r\n\t */\r\n\tpublic static void clearIds(){\r\n\t\tids.clear();\r\n\t}\r\n\t\r\n\tpublic static synchronized String getUniqueId( String root ){\r\n\t\tInteger id = null;\r\n\t\tsynchronized( ids ){\r\n\t\t\tid = ids.get(root);\r\n\t\t\tif( id == null ){\r\n\t\t\t\tid = new Integer(1);\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\tid = new Integer( id.intValue() + 1 );\r\n\t\t\t}\r\n\t\t\tids.put(root, id); // Store the new value\r\n\t\t}\r\n\t\treturn root + id.toString();\r\n\t}\r\n\r\n\tpublic static Element getChildElement( Element root, String tagName ) {\r\n\t\tList<Element> list = getChildElements(root,tagName);\r\n\t\tswitch( list.size() ){\r\n\t\t\tcase 0:\r\n\t\t\t\treturn null;\r\n\t\t\t\t\r\n\t\t\tcase 1: \r\n\t\t\t\treturn list.get(0);\r\n\t\t\t\t\r\n\t\t\tdefault :\r\n\t\t\t\tthrow new IllegalArgumentException( \"Multiple <\" + tagName + \"> found. Only one expected.\" ); \r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic static List<Element> getChildElements( Element root, String tagName ){\r\n\t\tList<Element> selected = new LinkedList<Element>();\r\n\t\tList<Element> childs = getChildElements(root);\r\n\t\tfor( Element e : childs ){\r\n\t\t\tif( e.getTagName().equals(tagName) ){\r\n\t\t\t\tselected.add(e);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn selected;\r\n\t}\r\n\r\n\t/**\r\n\t * Retrieve the elements contained in the parent element.\r\n\t * \r\n\t * @param e the parent element\r\n\t * @return the child elements.\r\n\t */\r\n\tpublic static List<Element> getChildElements( Element e ){\r\n\t\tNodeList nodes = e.getChildNodes();\r\n\t\tint len = nodes.getLength();\r\n\t\tList<Element> elements = new ArrayList<Element>( len );\r\n\t\tfor(int i = 0; i < len; i++ ){\r\n\t\t\tNode node = nodes.item(i);\r\n\t\t\tif( node.getNodeType() == Node.ELEMENT_NODE ){\r\n\t\t\t\telements.add( (Element)node );\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn elements;\r\n\t}\r\n\t\r\n\tpublic static List<Element> getChildElementsExcept( Element e, String ... list ){\r\n\t\tNodeList nodes = e.getChildNodes();\r\n\t\tint len = nodes.getLength();\r\n\t\tList<Element> elements = new ArrayList<Element>( len );\r\n\t\tfor(int i = 0; i < len; i++ ){\r\n\t\t\tNode node = nodes.item(i);\r\n\t\t\tif( node.getNodeType() == Node.ELEMENT_NODE ){\r\n\t\t\t\tString nodeName = node.getNodeName();\r\n\t\t\t\tboolean toBeAdded = true;\r\n\t\t\t\tfor(int j = 0; j < list.length; j++){\r\n\t\t\t\t\tif( nodeName.equalsIgnoreCase(list[j]) ){\r\n\t\t\t\t\t\ttoBeAdded = false;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tif( toBeAdded ) elements.add( (Element)node );\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn elements;\r\n\t}\r\n\r\n\t/**\r\n\t * The attribute as a string.\r\n\t * \r\n\t * @param e the XML element.\r\n\t * @param attributeName the attribute.\r\n\t * @param mandatory if the attribute is mandatory (if the attribute is\r\n\t * \t\tmandatory and not found or is empty, a {@link NullPointerException}\r\n\t * \t\tis thrown).\r\n\t * @return the string value or <code>null</code> if not exists or is\r\n\t * \t\tempty.\r\n\t */\r\n\tpublic static String getAttribute( Element e, String attributeName, boolean mandatory ){\r\n\t\tString value = normalized( e.getAttribute(attributeName) );\r\n\t\tif( mandatory && value == null ){\r\n\t\t\tthrow new NullPointerException( \"<\" + e.getNodeName() + \">: attribute \\\"\" + attributeName + \"\\\" expected.\");\r\n\t\t}\r\n\t\treturn value;\r\n\t}\r\n\r\n\tpublic static String getStringAttribute( Element e, String attributeName, String defaultValue ){\r\n\t\tString value = normalized( e.getAttribute(attributeName) );\r\n\t\treturn (value == null ? defaultValue : value );\r\n\t}\r\n\r\n\tpublic static String getAttribute( Element e, String attributeName ){\r\n\t\treturn getAttribute(e, attributeName, false);\r\n\t}\r\n\r\n\t/**\r\n\t * Get the color attribute. The attribute returned is a \r\n\t * {@link Color} instance (or <code>null</code> if it is not\r\n\t * possible to decode).\r\n\t * \r\n\t * <p>\r\n\t * A color is analysed based on the color's name (yellow, cyan,\r\n\t * dark, etc.) or by the \"<code>#</code>\" character followed\r\n\t * by the color expressed in hexadecimal using the form RRGGBB.\r\n\t * For example, \"<code>#00ff00</code>\" is used for the green color.\r\n\t * </p>\r\n\t * \r\n\t * @param e the XML element.\r\n\t * @param attributeName the attribute name for the color.\r\n\t * @return <code>null</code> is the attribute is empty or\r\n\t * \t\tdoes not exist or we are not able to decode the color,\r\n\t * \t\tthe color value.\r\n\t */\r\n\tpublic static Color getColorAttribute( Element e, String attributeName ){\r\n\t\tColor color = null;\r\n\t\tString s = getAttribute(e, attributeName, false);\r\n\t\tif( s != null && s.length() > 0 ){\r\n\t\t\tif( s.charAt(0) == '#' ){\r\n\t\t\t\t// RVB color...\r\n\t\t\t\ttry {\r\n\t\t\t\t\tint rgb = Integer.parseInt( s.substring(1).trim(), 16 );\r\n\t\t\t\t\tcolor = new Color(rgb);\r\n\t\t\t\t}\r\n\t\t\t\tcatch( NumberFormatException ex ){\r\n\t\t\t\t\t// Error displayed below.\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\t// Use the color array.\r\n\t\t\t\tcolor = COLORS.get(s.toLowerCase());\r\n\t\t\t\tif( color == null ){\r\n\t\t\t\t\t// Last hope before we cancel!\r\n\t\t\t\t\tcolor = Color.getColor(s);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif( color == null ){\r\n\t\t\t\tSystem.err.println(\"<\" + e.getTagName() + \" \" + attributeName + \"= \" + JavaCode.toParam(s) + \">: can not convert to a color.\");\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn color;\r\n\t}\r\n\r\n\t\r\n\t/**\r\n\t * Retrieve the class name for the tag or the defaulted one.\r\n\t * When an object is instantied, we use a default class \r\n\t * (a <label> will create a <code>JLabel</code> obejct)\r\n\t * but you can override the class with the \"class\" attribute\r\n\t * in the tag. This is a solution to provide more power\r\n\t * to an object.\r\n\t * \r\n\t * @param e the tag.\r\n\t * @param clazz the default class to use.\r\n\t * @return the class to be declared in the JAVA code.\r\n\t * \r\n\t */\r\n\tpublic static String getClassName( Element e, Class<?> clazz ){\r\n\t\tString className = getAttribute(e, CLASS_ATTRIBUTE);\r\n\t\treturn( className == null ? clazz.getName() : className );\t\t\r\n\t}\r\n\r\n\t/**\r\n\t * Get the name of the the object. When a tag declares a\r\n\t * new object, this object can have a name (in this case, it\r\n\t * can be accessed by a derived class) or anonymous (the name\r\n\t * is created based on the <i>rootName</> parameter). In many\r\n\t * case, it is not necessary to declare a name except you have\r\n\t * to access the object in the derived class.\r\n\t * \r\n\t * @param e the tag.\r\n\t * @param rootName the default root naming in case the name is\r\n\t * \t\tcreated as an anomymous.\r\n\t * @return the name of the object.\r\n\t * @deprecated do not use anymore because you do not know if \r\n\t * \t\tthe variable is anonymous or not!\r\n\t * @see #addDeclaration(JavaClass, Element, Class) as replacement.\r\n\t */\r\n\tpublic static String getVariableName( Element e, String rootName ){\r\n\t\tString varName = getAttribute(e, ID_ATTRIBUTE);\r\n\t\tif( varName == null ){\r\n\t\t\tvarName = Parser.getUniqueId(rootName);\r\n\t\t}\r\n\t\treturn varName;\t\t\r\n\t}\r\n\r\n\tpublic static String normalized( String s ){\r\n\t\tif( s == null ) return null;\r\n\t\ts = s.trim();\r\n\t\treturn ( s.length() == 0 ? null : s );\r\n\t}\r\n\t\r\n\tprivate static String cleanOf( String source ){\r\n\t\tint len = source.length();\r\n\t\tStringBuilder buf = new StringBuilder(len);\r\n\t\tboolean lastCharIsSpace = true;\r\n\t\tfor( int i = 0; i < len; i++ ){\r\n\t\t\tchar c = source.charAt(i);\r\n\t\t\tboolean isSpace = Character.isWhitespace(c);\r\n\t\t\tif( !isSpace ){\r\n\t\t\t\tlastCharIsSpace = false;\r\n\t\t\t\tbuf.append(c);\r\n\t\t\t}\r\n\t\t\telse if(!lastCharIsSpace){\r\n\t\t\t\tbuf.append(' ');\r\n\t\t\t\tlastCharIsSpace = true;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn buf.toString().trim();\r\n\t}\r\n\r\n\t/**\r\n\t * Get the text contents for a tag. Retrieve the text\r\n\t * enclosed between the beginning and the end of the\r\n\t * tag <i>excluding</i> the text of inner tags.\r\n\t * \r\n\t * <p>\r\n\t * <p>This is an <emph>emphazed</p> text.</code>\r\n\t * will return \"This is an text.\"\r\n\t * </p>\r\n\t * \r\n\t * @param e the tag.\r\n\t * @return the text stored in the tag.\r\n\t */\r\n\tpublic static String getTextContents( Element e){\r\n\t\tif(e.hasAttribute(\"_text\")){\r\n\t\t\treturn e.getAttribute(\"_text\");\r\n\t\t}\r\n\r\n\t\t// Look in children\r\n\t\tStringBuilder buf = new StringBuilder();\r\n\t\tNodeList list = e.getChildNodes();\r\n\t\tfor( int i = 0; i < list.getLength(); i++ ){\r\n\t\t\tNode node = list.item(i);\r\n\t\t\tswitch( node.getNodeType() ){\r\n\t\t\t\tcase Node.TEXT_NODE :\r\n\t\t\t\t\tbuf.append( cleanOf( node.getNodeValue() ) );\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tcase Node.CDATA_SECTION_NODE :\r\n\t\t\t\t\tbuf.append( node.getNodeValue() );\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tcase Node.ELEMENT_NODE :\r\n\t\t\t\t\tElement elem = (Element)node;\r\n\t\t\t\t\tif( elem.getNodeName().equalsIgnoreCase(\"br\") ){\r\n\t\t\t\t\t\tbuf.append(\"\\n\");\r\n\t\t\t\t\t}\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tdefault:\r\n\t\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn buf.toString();\r\n\t}\r\n\r\n\t/**\r\n\t * Get the boolean attribute.\r\n\t * \r\n\t * @param e the XML element.\r\n\t * @param attributeName the attribute name.\r\n\t * @param defaultValue the default value returned if the attribute does not\r\n\t * \t\texists or is not set to <code>true</code> or <code>false</code>.\r\n\t * @return the value of the attribute or the default value.\r\n\t */\r\n\tpublic static boolean getBooleanAttribute( Element e, String attributeName, boolean defaultValue ){\r\n\t\tBoolean b = getBooleanAttribute(e, attributeName);\r\n\t\tif( b == null ){\r\n\t\t\treturn defaultValue;\r\n\t\t}\r\n\t\treturn b.booleanValue();\r\n\t}\r\n\r\n\tpublic static Boolean getBooleanAttribute( Element e, String attributeName ){\r\n\t\tString s = Parser.getAttribute(e, attributeName);\r\n\t\tif( s == null ) return null;\r\n\t\tif( s.equalsIgnoreCase(Boolean.toString(true)) ) return true;\r\n\t\tif( s.equalsIgnoreCase(Boolean.toString(false)) ) return false;\r\n\t\tSystem.out.println( \"<\" + e.getNodeName() + \"> is expected to have true/false for the attribute \\\"\" + attributeName + \"\\\" instead of \\\"\" + s + \"\\\"\" );\r\n\t\treturn null;\r\n\t}\r\n\t\r\n\tpublic static Integer getIntegerAttribute( Element e, String attributeName ){\r\n\t\tInteger ret = null;\r\n\t\tString s = Parser.getAttribute(e, attributeName);\r\n\t\tif( s == null ) return null;\r\n\t\ttry {\r\n\t\t\tret = Integer.parseInt(s);\r\n\t\t}\r\n\t\tcatch( NumberFormatException ex ){\r\n\t\t\tSystem.out.println(\"<\" + e.getTagName() + \" \" + attributeName + \"= \" + JavaCode.toParam(s) + \">: can not convert to an integer.\");\r\n\t\t}\r\n\t\treturn ret;\r\n\t}\r\n\r\n\tpublic static int getIntegerAttribute( Element e, String attributeName, int defaultValue ){\r\n\t\tInteger ret = getIntegerAttribute(e,attributeName);\r\n\t\treturn( ret == null ? defaultValue : ret.intValue() );\r\n\t}\r\n\r\n\t/**\r\n\t * Get the percentage value. The percentage value can be expressed\r\n\t * directly (with 0.250 for example) or with the percentage\r\n\t * character (25%) at your convenience.\r\n\t * \r\n\t * @param e the XML element.\r\n\t * @param attributeName the attribute to extract.\r\n\t * @return the value expressed as a double (a range from\r\n\t * \t\t0.0 to 1.0� or <code>null</code> if no data available.\r\n\t * \r\n\t */\r\n\tpublic static Double getPercentageAttribute( Element e, String attributeName ){\r\n\t\tdouble factor = 1;\r\n\t\tDouble ret = null;\r\n\t\tString s = Parser.getAttribute(e, attributeName);\r\n\t\tif( s == null ) return null;\r\n\t\ttry {\r\n\t\t\tif( s.endsWith(\"%\") ){\r\n\t\t\t\tfactor = 0.01;\r\n\t\t\t\ts = s.substring(0, s.indexOf(\"%\") ).trim();\r\n\t\t\t}\r\n\t\t\tret = new Double( Double.parseDouble(s) * factor);\r\n\t\t}\r\n\t\tcatch( NumberFormatException ex ){\r\n\t\t\tSystem.out.println(\"<\" + e.getTagName() + \" \" + attributeName + \"= \" + JavaCode.toParam(s) + \">: can not convert to an integer.\");\r\n\t\t}\r\n\t\treturn ret;\r\n\t}\r\n\r\n\tpublic static String addDeclaration( JavaClass jclass, Element e, Class<?> clazz ){\r\n\t\tString className = getClassName( e, clazz, jclass );\r\n\t\treturn addDeclaration(jclass, e, className, ID_ATTRIBUTE );\r\n\t}\r\n\t\r\n\tpublic static String getSimpleName( String fullName ){\r\n\t\tint pos = fullName.lastIndexOf(\".\");\r\n\t\tif( pos > 0 ){\r\n\t\t\treturn fullName.substring(pos+1);\r\n\t\t}\r\n\t\treturn fullName;\r\n\t}\r\n\r\n\tpublic static String addDeclaration( JavaClass jclass, Element e, String className, String attributeName ){\r\n\t\tString modifier = \"protected\";\r\n\t\t\r\n\t\tString varName = (e == null ? null : getAttribute(e, attributeName));\r\n\t\tif( varName == null ){\r\n\t\t\tvarName = Parser.getUniqueId( getSimpleName(className).toLowerCase() );\r\n\t\t\tmodifier = \"private\";\r\n\t\t}\r\n\r\n\t\tjclass.addAnonymousDeclaration( modifier + \" \" + className + \" \" + varName + \" = new \" + className + \"();\" );\r\n\t\tjclass.register( varName, className );\r\n\t\treturn varName;\r\n\t}\r\n\r\n\t/**\r\n\t * Get the class name.\r\n\t * \r\n\t * @param e the element.\r\n\t * @param clazz the default class, this value is overrided if\r\n\t * a attribute {@link #CLASS_ATTRIBUTE} is found.\r\n\t * @param jclass the class on which we declare the import. \r\n\t * @return the name of the class to use to initialize the variables\r\n\t * \t\tin the sepcified class.\r\n\t */\r\n\tpublic static String getClassName( Element e, Class<?> clazz, JavaClass jclass ){\r\n\t\tString className = (e == null ? null : Parser.getAttribute(e, CLASS_ATTRIBUTE));\r\n\t\tif( className == null ){\r\n\t\t\t// Only import standard classes. For classes defined by the user,\r\n\t\t\t// we must avoid use the import process to avoid issues on names.\r\n\t\t\tjclass.addImport(clazz);\r\n\t\t\tclassName = clazz.getSimpleName();\t\t\r\n\t\t}\r\n\t\treturn className;\r\n\t}\r\n\r\n\tpublic static void setDefaultAttributeValue( Element e, String attributeName, String defaultValue ){\r\n\t\tString value = getAttribute(e, attributeName);\r\n\t\tif( value == null ){\r\n\t\t\te.setAttribute(attributeName, defaultValue);\r\n\t\t}\r\n\t}\r\n}\r",
"public enum ClassType {\r\n\tTEXT,\r\n\tSTRING,\r\n\tCHAR,\r\n\tINTEGER,\r\n\tBOOLEAN,\r\n\tPERCENT,\r\n\tCOLOR,\r\n\tALIGNMENT,\r\n\tDIMENSION,\r\n\tINSETS,\r\n\tKEYSTROKE,\r\n\tVERTICAL_OR_HORIZONTAL, // Not yet implemented\r\n\tJSPLITPANE_ORIENTATION,\r\n\tJLIST_ORIENTATION,\r\n\tICON,\r\n\tCURSOR,\r\n\tCOMPONENT,\r\n\tJTABLE_AUTO_RESIZE, // For JTable implementation\r\n\tJLIST_SELECT_MODE,\r\n};\r",
"@SuppressWarnings(\"serial\")\r\npublic class UnexpectedTag extends SAXException {\r\n\tpublic UnexpectedTag( Element e ){\r\n\t\tsuper(\"Tag <\" + e.getTagName() + \"> unexpected. XPath = \" + xpath(e) );\r\n\t}\r\n\r\n\tpublic UnexpectedTag( String text ){\r\n\t\tsuper(text);\r\n\t}\r\n\t\r\n\tpublic UnexpectedTag( Element e, String text ){\r\n\t\tsuper(\"XPath = \" + xpath(e) + \": \" + text );\r\n\t}\r\n\r\n\tpublic static String xpath(Element root ){\r\n\t\tString ret = \"\";\r\n\t\tNode e = root;\r\n\t\twhile( e != null ) {\r\n\t\t\tret = \"/\" + e.getNodeName() + ret;\r\n\t\t\te = e.getParentNode();\r\n\t\t}\r\n\t\treturn ret;\r\n\t}\r\n}\r",
"public class JavaClass extends JavaCode {\r\n\tprivate String fullClassName = null;\r\n\tprivate String extClassName = null;\r\n\tprivate Set<String> implementInterfaces = new HashSet<String>(); \r\n\tprivate JavaType javaType = new JavaType();\r\n\tprivate JavaComments comments = null;\r\n\tprivate LinesOfCode declarations = new LinesOfCode();\r\n\tprivate Set<String> importSet = new HashSet<String>(); \r\n\tprivate Map<String, JavaMethod> methods = new HashMap<String, JavaMethod>();\r\n\tprivate LinesOfCode staticCode = new LinesOfCode();\r\n\tprivate Map<String,JavaClass> innerClasses = new HashMap<String, JavaClass>();\r\n\tprivate Properties props = new Properties();\r\n\tprivate Map<String,String> registered = new HashMap<String, String>();\r\n\r\n\tpublic void addStatic( JavaCode code ){\r\n\t\tstaticCode.addCode(code);\r\n\t}\r\n\r\n\tpublic void addStatic( String line ){\r\n\t\tstaticCode.addCode( new LineOfCode(line) );\r\n\t}\r\n\r\n\t/**\r\n\t * Add the interface. Note once the class implements\r\n\t * an interface, this interface is imported.\r\n\t * \r\n\t * @param iClass the interface class. \r\n\t */\r\n\tpublic void addInterface( Class<?> iClass ){\r\n\t\taddImport(iClass);\r\n\t\timplementInterfaces.add(iClass.getSimpleName());\r\n\t}\r\n\r\n\tpublic void addInterface( String iClass ){\r\n\t\timplementInterfaces.add(iClass);\r\n\t}\r\n\r\n\t/**\r\n\t * @return the comments\r\n\t */\r\n\tpublic JavaComments getComments() {\r\n\t\treturn comments;\r\n\t}\r\n\r\n\t/**\r\n\t * @param comments the comments to set\r\n\t */\r\n\tpublic void setComments(JavaComments comments) {\r\n\t\tthis.comments = comments;\r\n\t}\r\n\r\n\t/**\r\n\t * Retrieve a method based on its name. Note if\r\n\t * several methods having the same name\r\n\t * have been added to this class,\r\n\t * only the first one is returned.\r\n\t * \r\n\t * @param name the method name.\r\n\t * @return the method if one exists with the specified\r\n\t * \t\tname, if not return <code>null</code>.\r\n\t */\r\n\tpublic JavaMethod getMethod( String name ){\r\n\t\treturn methods.get(name);\r\n\t}\r\n\r\n\tpublic String addMethodIfNotExists( JavaMethod m ){\r\n\t\tif( getMethod( m.getName()) == null ){\r\n\t\t\treturn addMethod(m);\r\n\t\t}\r\n\t\treturn m.getName();\r\n\t}\r\n\r\n\tpublic String addMethod( JavaMethod m ){\r\n\t\tString root = m.getName();\r\n\t\tif( methods.containsKey(root) ){\r\n\t\t\tint i = 1;\r\n\t\t\twhile( methods.containsKey(m.getName()+\".\"+i) ){\r\n\t\t\t\ti++;\r\n\t\t\t}\r\n\t\t\troot = m.getName() + \".\" + i;\r\n\t\t}\r\n\t\tmethods.put( root, m);\r\n\t\treturn root;\r\n\t}\r\n\r\n\r\n\t/**\r\n\t * Add an anonymous declaration. It means you have to\r\n\t * give all the declaration but the variable is not registred.\r\n\t * \r\n\t * @param lineOfCode the line of code to add in the \r\n\t * \t\tdeclaration part of the class.\r\n\t * @see #register(String, Class) for registring the\r\n\t * \t\tvariable (if necessary).\r\n\t */\r\n\tpublic void addAnonymousDeclaration( CharSequence lineOfCode ) {\r\n\t\tdeclarations.addCode(lineOfCode);\r\n\t}\r\n\r\n\t/**\r\n\t * Add a declaration. \r\n\t * \r\n\t * @param varName the variable name;\r\n\t * @param type the Java type.\r\n\t * @param params the parameters for the initialization. If\r\n\t * \t\t<code>null</code>, there is no initialisation. A\r\n\t * \t\t<code>null</code> array (or no parameter) means\r\n\t * \t\tthe variable is created empty.\r\n\t */\r\n\tpublic void addDeclaration( String varName, JavaType type, String[] params ) {\r\n\t\t// jclass.addDeclaration( modifier + \" \" + className + \" \" + varName + \" = new \" + className + \"();\" );\r\n\t\tStringBuilder buf = new StringBuilder();\r\n\t\tbuf.append( type ).append(\" \").append(varName);\r\n\t\tif( params != null ){\r\n\t\t\tbuf.append( \" = new \" ).append( type.getClassName() ).append(\"(\");\r\n\t\t\tfor( int i = 0; i < params.length; i++ ){\r\n\t\t\t\tif( i > 1 ) buf.append(\", \");\r\n\t\t\t\tbuf.append( params[i] );\r\n\t\t\t}\r\n\t\t\tbuf.append(\")\");\r\n\t\t}\r\n\t\tbuf.append(\";\");\r\n\t\tdeclarations.addCode(buf.toString());\r\n\t}\r\n\t\r\n\t/**\r\n\t * Add the class specified as an import of\r\n\t * the current class. It simplifies the code\r\n\t * created.\r\n\t * \r\n\t * @param className the class name.\r\n\t * @see #addImport(Class)\r\n\t */\r\n\tpublic void addImport( String className ){\r\n\t\timportSet.add(className);\r\n\t}\r\n\r\n\t/**\r\n\t * Import a new class in the class. The class can\r\n\t * be referenced with its simple name. For example,\r\n\t * if you import the <code>java.util.List</code> class,\r\n\t * you will be able to refer to it with <code>List</code>\r\n\t * only.\r\n\t * \r\n\t * <p>You can import the same class multiple times:\r\n\t * the class name imported is registred to avoid\r\n\t * duplicate lines in the final code.\r\n\t * </p>\r\n\t * \r\n\t * @param clazz the class to import.\r\n\t */\r\n\tpublic void addImport( Class<?> clazz ){\r\n\t\taddImport( clazz.getName() );\r\n\t}\r\n\r\n\t/**\r\n\t * Creates the class.\r\n\t * \r\n\t * @param name the class name (a full name including\r\n\t * \t\tthe package; if not the class will be created\r\n\t * \t\tin the default package).\r\n\t */\r\n\tpublic JavaClass( String name ){\r\n\t\tthis.fullClassName = name;\r\n\t}\r\n\t\r\n\tpublic JavaMethod getConstructor( JavaParam ... params ){\r\n\t\tJavaMethod constructor = new JavaMethod( this.getClassName() );\r\n\t\tconstructor.setReturnType(new JavaType(\"\"));\r\n\t\tconstructor.setParams(params);\r\n\t\taddMethod(constructor);\r\n\t\treturn constructor;\r\n\t}\r\n\t\r\n\tpublic String getClassName(){\r\n\t\tint pos = fullClassName.lastIndexOf(\".\");\r\n\t\treturn (pos < 0 ? fullClassName : fullClassName.substring(pos+1) );\r\n\t}\r\n\r\n\t/**\r\n\t * Checks if a class has been imported.\r\n\t * \r\n\t * @param clazz the class to import.\r\n\t * @return <code>true</code> if the class already\r\n\t * \t\texists in the import list, <code>false</code>\r\n\t * \t\tin the other cases.\r\n\t */\r\n\tpublic boolean isImported( Class<?> clazz ){\r\n\t\treturn importSet.contains(clazz.getName());\r\n\t}\r\n\t\r\n\tpublic void setExtend( Class<?> clazz ){\r\n\t\textClassName = (isImported( clazz ) ? clazz.getSimpleName() : clazz.getName());\r\n\t}\r\n\r\n\tpublic void setExtend( String clazzName ){\r\n\t\textClassName = clazzName;\r\n\t}\r\n\t\r\n\tpublic static String name2file( String s ){\r\n\t\tStringBuilder buf = new StringBuilder();\r\n\t\tfor(int i = 0; i < s.length(); i++ ){\r\n\t\t\tchar c = s.charAt(i);\r\n\t\t\tswitch( c ){\r\n\t\t\tcase '.' : buf.append( File.separator ); break;\r\n\t\t\tdefault : buf.append(c); break;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn buf.toString();\r\n\t}\r\n\r\n\t/**\r\n\t * Get the package name for this class.\r\n\t * \r\n\t * @return the package name\r\n\t */\r\n\tpublic String getPackageName(){\r\n\t\tint pos = fullClassName.lastIndexOf(\".\");\r\n\t\treturn (pos < 0 ? null : fullClassName.substring(0,pos) );\r\n\t}\r\n\r\n\tpublic void newAnonymousClass( String className, JavaClass clazz, String params ) throws IOException {\r\n\t\t\r\n\t}\r\n\r\n\t/**\r\n\t * Write the class on the disk.\r\n\t * \r\n\t * @param rootDir the root directory for the JAVA source\r\n\t * \t\tcode.\r\n\t * @return the path of the JAVA class. \r\n\t * @throws IOException if an i/O error occurred.\r\n\t */\r\n\tpublic String writeClass( String rootDir ) throws IOException {\r\n\t\tString packageName = getPackageName();\r\n\t\tString className = getClassName();\r\n\t\t\r\n\t\tString packageDir = \"\";\r\n\t\tif( packageName != null ){\r\n\t\t\tpackageDir = File.separator + name2file( packageName );\r\n\t\t}\r\n\t\tString fileName = rootDir + packageDir + File.separator + className + \".java\";\r\n\t\t\r\n\t\tWriter w = new OutputStreamWriter( new FileOutputStream(fileName) );\r\n\t\tif( packageName != null ){\r\n\t\t\tprintln( w, \"package \" + packageName + \";\" );\r\n\t\t}\r\n\t\t\r\n\t\t// Import classes\r\n\t\tString[] importArray = importSet.toArray(new String[0]);\r\n\t\tArrays.sort(importArray);\r\n\t\tString rootName = \"\";\r\n\t\tfor( String importLibraryName : importArray ){\r\n\t\t\tString[] subNames = importLibraryName.split(\"\\\\.\");\r\n\t\t\tif( !subNames[0].equals(rootName) ){\r\n\t\t\t\tprintln(w);\r\n\t\t\t\trootName = subNames[0];\r\n\t\t\t}\r\n\t\t\tprintln( w, \"import \" + importLibraryName + \";\" );\r\n\t\t}\r\n\t\tprintln(w);\r\n\r\n\t\twriteCode(w, 0,false);\r\n\t\tw.close();\r\n\t\treturn fileName;\r\n\t}\r\n\r\n\t@Override\r\n\tprotected void writeCode(Writer w, int tabs) throws IOException {\r\n\t\twriteCode(w, tabs,false);\r\n\t}\r\n\r\n\tpublic void writeAnonymous(Writer w, int tabs) throws IOException {\r\n\t\twriteCode(w, tabs, true);\r\n\t}\r\n\r\n\tpublic String toParam() {\r\n\t\ttry {\r\n\t\t\tStringWriter w = new StringWriter(); \r\n\t\t\twriteCode(w, 0, true);\r\n\t\t\tw.close();\r\n\t\t\treturn w.getBuffer().toString();\r\n\t\t}\r\n\t\tcatch(IOException ex ){\r\n\t\t\tthrow new OutOfMemoryError(\"I/O Error:\" + ex.getMessage());\r\n\t\t}\r\n\t}\r\n\r\n\tprotected void writeCode(Writer w, int tabs, boolean anonymous) throws IOException {\r\n\t\t\r\n\t\tif( anonymous ){\r\n\t\t\tw.write(\"new \" + getClassName() + \"() \" );\r\n\t\t}\r\n\t\telse {\r\n\t\t\t// Comments\r\n\t\t\tif( comments != null ) comments.writeCode(w, tabs);\r\n\t\t\r\n\t\t\t// Class declaration\r\n\t\t\tjavaType.setClassName(\"class\");\r\n\t\t\tw.write( javaType + \" \" + getClassName() );\r\n\t\t\tif( extClassName != null ) {\r\n\t\t\t\tString extend = \"extends\";\r\n\t\t\t\ttry {\r\n\t\t\t\t\tClass<?> clazz = Class.forName(extClassName);\r\n\t\t\t\t\tif( clazz.isInterface() ){\r\n\t\t\t\t\t\textend = \"implements\";\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tcatch(ClassNotFoundException ex){\r\n\t\t\t\t\t// Simply ignore in case we not found the class\r\n\t\t\t\t}\r\n\t\t\t\tw.write( \" \" + extend + \" \" + extClassName );\r\n\t\t\t}\r\n\r\n\t\t\tif( this.implementInterfaces.size() > 0 ){\r\n\t\t\t\t// Interfaces implemented.\r\n\t\t\t\tboolean first = true;\r\n\t\t\t\tfor(String className : this.implementInterfaces){\r\n\t\t\t\t\tw.write( first ? \" implements \" : \", \" );\r\n\t\t\t\t\tw.write(className);\r\n\t\t\t\t\tfirst = false;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tw.write( \" {\" + JavaCode.CRLF );\r\n\t\t\r\n\t\tdeclarations.writeCode(w, tabs + 1);\r\n\t\t\r\n\t\tif( staticCode.size() > 0 ){\r\n\t\t\tString prefix = (anonymous ? \"\" : \"static \");\r\n\t\t\tw.write( getTabulations(tabs+1) + prefix + \"{\" + JavaCode.CRLF );\r\n\t\t\tstaticCode.writeCode(w, tabs+2);\r\n\t\t\tw.write( getTabulations(tabs+1) + \"}\" + JavaCode.CRLF );\r\n\t\t}\r\n\r\n\t\tfor( JavaClass c : innerClasses.values() ){\r\n\t\t\tc.writeCode(w, tabs+1, false);\r\n\t\t}\r\n\r\n\t\t// Methods...\r\n\t\tfor( JavaMethod m : methods.values() ){\r\n\t\t\tprintln(w);\r\n\t\t\tm.writeCode(w, tabs+1);\r\n\t\t}\r\n\t\t\r\n\t\t// Class ending\r\n\t\tw.write( \"}\" + JavaCode.CRLF + JavaCode.CRLF );\r\n\t}\r\n\t\r\n\t/**\r\n\t * Register an object. The registration of an object\r\n\t * is a simple way to mark the object to be owned\r\n\t * by the class. It is just a flag (no code is\r\n\t * associated). The registration is used to\r\n\t * register a group or some similar stuff.\r\n\t * \r\n\t * @param obj the name of the object to register.\r\n\t * @param clazz the class of the object.\r\n\t */\r\n\tpublic void register( String obj, Class<?> clazz ){\r\n\t\tregistered.put(obj, clazz.getName());\r\n\t}\r\n\r\n\tpublic void register( String obj, String className ){\r\n\t\tregistered.put(obj, className );\r\n\t}\r\n\r\n\tpublic boolean isRegistered( String obj ){\r\n\t\tString className = registered.get(obj);\r\n\t\treturn (className != null);\r\n\t}\r\n\t\r\n\tpublic void addInnerClass( JavaClass jclass ){\r\n\t\tinnerClasses.put( jclass.getClassName(), jclass );\r\n\t\t\r\n\t}\r\n\t\r\n\t/**\r\n\t * Dummy method: returns 0x0104 for the release\r\n\t * 1.5 of the JAVA classes.\r\n\t * \r\n\t * @return the version of the java classes.\r\n\t * \r\n\t */\r\n\tpublic int getVersion() {\r\n\t\treturn 0x0105;\r\n\t}\r\n\r\n /**\r\n * Set a property to this class. A proprty has no meaning and is\r\n * not used to construct the class. Nevertheless, it can be helpful\r\n * to store some global information during the construction of the\r\n * class. \r\n *\r\n * @param key the key to be placed into this property list.\r\n * @param value the value corresponding to <tt>key</tt>.\r\n * @see #getProperty\r\n */\r\n\tpublic void setProperty(String key, String value){\r\n\t\tprops.setProperty(key, value);\r\n\t}\r\n\r\n /**\r\n * Searches for the property with the specified key in this property list.\r\n * If the key is not found in this property list, the method returns\r\n * <code>null</code>.\r\n *\r\n * @param key the property key.\r\n * @return the value in this property list with the specified key value.\r\n * @see #setProperty\r\n */\r\n\tpublic String getProperty(String key){\r\n\t\treturn props.getProperty(key);\r\n\t}\r\n\t\r\n\tpublic void setModifiers( int modifiers ){\r\n\t\tjavaType.setAccess(modifiers);\r\n\t}\r\n}\r",
"public class JavaMethod extends JavaBlock {\r\n\t// JavaBlock contents = new JavaBlock();\r\n\tJavaComments comments = new JavaComments();\r\n\tString name;\r\n\tJavaType returnType = new JavaType( \"void\" );\r\n\t\r\n\t/**\r\n\t * @return the returnType\r\n\t */\r\n\tpublic JavaType getReturnType() {\r\n\t\treturn returnType;\r\n\t}\r\n\r\n\t/**\r\n\t * @param returnType the returnType to set\r\n\t */\r\n\tpublic void setReturnType(JavaType returnType) {\r\n\t\tthis.returnType = returnType;\r\n\t}\r\n\r\n\tList<JavaParam> params = new ArrayList<JavaParam>();\r\n\t/**\r\n\t * @return the params\r\n\t */\r\n\tpublic JavaParam[] getParams() {\r\n\t\treturn params.toArray(new JavaParam[0]);\r\n\t}\r\n\r\n\tpublic JavaComments getComments(){\r\n\t\treturn this.comments;\r\n\t}\r\n\r\n\tpublic void setComments( JavaComments comments ){\r\n\t\tthis.comments = comments;\r\n\t}\r\n\r\n\tpublic void setComments( String comments ){\r\n\t\tthis.comments = new JavaComments(comments);\r\n\t}\r\n\r\n\t/**\r\n\t * @param params the params to set\r\n\t */\r\n\tpublic void setParams(JavaParam ... params) {\r\n\t\tthis.params = Arrays.asList( params );\r\n\t}\r\n\r\n\t\r\n\tpublic JavaMethod(){\r\n\t}\r\n\r\n\tpublic JavaMethod( String name ){\r\n\t\tthis();\r\n\t\tthis.name = name;\r\n\t}\r\n\r\n\tpublic JavaMethod( String name, JavaParam ... params ){\r\n\t\tthis(name);\r\n\t\tsetParams(params);\r\n\t}\r\n\r\n\r\n\r\n//\tpublic void addCode( JavaCode code ){\r\n//\t\tcontents.addCode(code);\r\n//\t}\r\n\r\n\t/**\r\n\t * @return the name\r\n\t */\r\n\tpublic String getName() {\r\n\t\treturn name;\r\n\t}\r\n\r\n\t/**\r\n\t * @param name the name to set\r\n\t */\r\n\tpublic void setName(String name) {\r\n\t\tthis.name = name;\r\n\t}\r\n\r\n\r\n\t@Override\r\n\tprotected void writeCode(Writer writer, int tabs) throws IOException {\r\n\t\tString tab = getTabulations(tabs);\r\n\t\tif( comments != null) comments.writeCode(writer, tabs);\r\n\t\twriter.write( tab + returnType + \" \" + getName() + \"(\" );\r\n\t\tboolean firstParam = true;\r\n\t\tfor( JavaParam param : params ){\r\n\t\t\tif( !firstParam ){\r\n\t\t\t\twriter.write(\", \");\r\n\t\t\t}\r\n\t\t\twriter.write( param.toString() );\r\n\t\t\tfirstParam = false;\r\n\t\t}\r\n\t\twriter.write( \")\" + CRLF );\r\n\t\tsuper.writeCode(writer, tabs);\r\n\t}\r\n\r\n\t/**\r\n\t * Add a line comment in the method. The\r\n\t * comment starts with \"//\" and it is added\r\n\t * at the end of the current code. \r\n\t * \r\n\t * @param comment the comment line to add.\r\n\t * @see #setComments(JavaComments) to set\r\n\t * \t\tthe comments of the method. \r\n\t */\r\n\tpublic void addLineComment( String comment ){\r\n\t\tJavaComments cmt = new JavaComments();\r\n\t\tcmt.setJavaDoc(false);\r\n\t\tcmt.add(comment);\r\n\t\taddCode(cmt);\r\n\t}\r\n\r\n}\r"
] | import javax.swing.JTree;
import org.w3c.dom.Element;
import com.oxande.xmlswing.AttributeDefinition;
import com.oxande.xmlswing.AttributesController;
import com.oxande.xmlswing.Parser;
import com.oxande.xmlswing.AttributeDefinition.ClassType;
import com.oxande.xmlswing.UnexpectedTag;
import com.oxande.xmlswing.jcode.JavaClass;
import com.oxande.xmlswing.jcode.JavaMethod;
| package com.oxande.xmlswing.components;
public class JTreeUI extends JComponentUI {
public static final String TAGNAME = "tree";
public static final AttributeDefinition[] PROPERTIES = {
DRAGGABLE_ATTRIBUTE_DEF,
new AttributeDefinition( "editable", "setEditable", ClassType.BOOLEAN ),
new AttributeDefinition( "expandsSelectedPaths", "setExpandsSelectedPaths", ClassType.BOOLEAN ),
new AttributeDefinition( "invokeStopCellEditing", "setInvokesStopCellEditing", ClassType.BOOLEAN ),
new AttributeDefinition( "largeModel", "setLargeModel", ClassType.BOOLEAN ),
new AttributeDefinition( "rootVisible", "setRootVisible", ClassType.BOOLEAN ),
new AttributeDefinition( "rowHeight", "setRowHeight", ClassType.INTEGER ),
new AttributeDefinition( "scrollOnExpand", "setScrollOnExpand", ClassType.BOOLEAN ),
new AttributeDefinition( "showRootHandles", "setShowRootHandles", ClassType.BOOLEAN ),
new AttributeDefinition( "toogleClickCount", "setToogleClickCount", ClassType.INTEGER ),
new AttributeDefinition( "visibleRowCount", "setVisibleRowCount", ClassType.INTEGER ),
};
public static final AttributesController CONTROLLER = new AttributesController( JComponentUI.CONTROLLER, PROPERTIES );
public JTreeUI(){
}
| public String parse(JavaClass jclass, JavaMethod initMethod, Element root ) throws UnexpectedTag{
| 6 |
javaBin/AndroiditoJZ12 | android/src/main/java/com/google/android/apps/iosched/ui/VendorsFragment.java | [
"public class ScheduleContract {\n\n /**\n * Special value for {@link SyncColumns#UPDATED} indicating that an entry\n * has never been updated, or doesn't exist yet.\n */\n public static final long UPDATED_NEVER = -2;\n\n /**\n * Special value for {@link SyncColumns#UPDATED} indicating that the last\n * update time is unknown, usually when inserted from a local file source.\n */\n public static final long UPDATED_UNKNOWN = -1;\n\n public interface SyncColumns {\n /** Last time this entry was updated or synchronized. */\n String UPDATED = \"updated\";\n }\n\n interface BlocksColumns {\n /** Unique string identifying this block of time. */\n String BLOCK_ID = \"block_id\";\n /** Title describing this block of time. */\n String BLOCK_TITLE = \"block_title\";\n /** Time when this block starts. */\n String BLOCK_START = \"block_start\";\n /** Time when this block ends. */\n String BLOCK_END = \"block_end\";\n /** Type describing this block. */\n String BLOCK_TYPE = \"block_type\";\n /** Extra string metadata for the block. */\n String BLOCK_META = \"block_meta\";\n }\n\n interface TracksColumns {\n /** Unique string identifying this track. */\n String TRACK_ID = \"track_id\";\n /** Name describing this track. */\n String TRACK_NAME = \"track_name\";\n /** Color used to identify this track, in {@link Color#argb} format. */\n String TRACK_COLOR = \"track_color\";\n /** Body of text explaining this track in detail. */\n String TRACK_ABSTRACT = \"track_abstract\";\n }\n\n interface RoomsColumns {\n /** Unique string identifying this room. */\n String ROOM_ID = \"room_id\";\n /** Name describing this room. */\n String ROOM_NAME = \"room_name\";\n /** Building floor this room exists on. */\n String ROOM_FLOOR = \"room_floor\";\n }\n\n interface SessionsColumns {\n /** Unique string identifying this session. */\n String SESSION_ID = \"session_id\";\n /** The type of session (session, keynote, codelab, etc). */\n String SESSION_TYPE = \"session_type\";\n /** Difficulty level of the session. */\n String SESSION_LEVEL = \"session_level\";\n /** Title describing this track. */\n String SESSION_TITLE = \"session_title\";\n /** Body of text explaining this session in detail. */\n String SESSION_ABSTRACT = \"session_abstract\";\n /** Requirements that attendees should meet. */\n String SESSION_REQUIREMENTS = \"session_requirements\";\n /** Keywords/tags for this session. */\n String SESSION_TAGS = \"session_keywords\";\n /** Hashtag for this session. */\n String SESSION_HASHTAGS = \"session_hashtag\";\n /** Full URL to session online. */\n String SESSION_URL = \"session_url\";\n /** Full URL to YouTube. */\n String SESSION_YOUTUBE_URL = \"session_youtube_url\";\n /** Full URL to PDF. */\n String SESSION_PDF_URL = \"session_pdf_url\";\n /** Full URL to official session notes. */\n String SESSION_NOTES_URL = \"session_notes_url\";\n /** User-specific flag indicating starred status. */\n String SESSION_STARRED = \"session_starred\";\n /** Key for session Calendar event. (Used in ICS or above) */\n String SESSION_CAL_EVENT_ID = \"session_cal_event_id\";\n /** The YouTube live stream URL. */\n String SESSION_LIVESTREAM_URL = \"session_livestream_url\";\n String SESSION_START = \"session_start\";\n String SESSION_END = \"session_end\";\n }\n\n interface SpeakersColumns {\n /** Unique string identifying this speaker. */\n String SPEAKER_ID = \"speaker_id\";\n /** Name of this speaker. */\n String SPEAKER_NAME = \"speaker_name\";\n /** Profile photo of this speaker. */\n String SPEAKER_IMAGE_URL = \"speaker_image_url\";\n /** Company this speaker works for. */\n String SPEAKER_COMPANY = \"speaker_company\";\n /** Body of text describing this speaker in detail. */\n String SPEAKER_ABSTRACT = \"speaker_abstract\";\n /** Full URL to the speaker's profile. */\n String SPEAKER_URL = \"speaker_url\";\n }\n\n interface VendorsColumns {\n /** Unique string identifying this vendor. */\n String VENDOR_ID = \"vendor_id\";\n /** Name of this vendor. */\n String VENDOR_NAME = \"vendor_name\";\n /** Location or city this vendor is based in. */\n String VENDOR_LOCATION = \"vendor_location\";\n /** Body of text describing this vendor. */\n String VENDOR_DESC = \"vendor_desc\";\n /** Link to vendor online. */\n String VENDOR_URL = \"vendor_url\";\n /** Body of text describing the product of this vendor. */\n String VENDOR_PRODUCT_DESC = \"vendor_product_desc\";\n /** Link to vendor logo. */\n String VENDOR_LOGO_URL = \"vendor_logo_url\";\n /** User-specific flag indicating starred status. */\n String VENDOR_STARRED = \"vendor_starred\";\n }\n\n interface AnnouncementsColumns {\n /** Unique string identifying this announcment. */\n String ANNOUNCEMENT_ID = \"announcement_id\";\n /** Title of the announcement. */\n String ANNOUNCEMENT_TITLE = \"announcement_title\";\n /** Summary of the announcement. */\n String ANNOUNCEMENT_SUMMARY = \"announcement_summary\";\n /** Track announcement belongs to. */\n String ANNOUNCEMENT_TRACKS = \"announcement_tracks\";\n /** Full URL for the announcement. */\n String ANNOUNCEMENT_URL = \"announcement_url\";\n /** Date of the announcement. */\n String ANNOUNCEMENT_DATE = \"announcement_date\";\n }\n\n public static final String CONTENT_AUTHORITY = \"no.java.schedule\";\n\n public static final Uri BASE_CONTENT_URI = Uri.parse(\"content://\" + CONTENT_AUTHORITY);\n\n private static final String PATH_BLOCKS = \"blocks\";\n private static final String PATH_AT = \"at\";\n private static final String PATH_BETWEEN = \"between\";\n private static final String PATH_TRACKS = \"tracks\";\n private static final String PATH_ROOMS = \"rooms\";\n private static final String PATH_SESSIONS = \"sessions\";\n private static final String PATH_WITH_TRACK = \"with_track\";\n private static final String PATH_STARRED = \"starred\";\n private static final String PATH_SPEAKERS = \"speakers\";\n private static final String PATH_VENDORS = \"vendors\";\n private static final String PATH_ANNOUNCEMENTS = \"announcements\";\n private static final String PATH_SEARCH = \"search\";\n private static final String PATH_SEARCH_SUGGEST = \"search_suggest_query\";\n\n /**\n * Blocks are generic timeslots that {@link Sessions} and other related\n * events fall into.\n */\n public static class Blocks implements BlocksColumns, BaseColumns {\n public static final Uri CONTENT_URI =\n BASE_CONTENT_URI.buildUpon().appendPath(PATH_BLOCKS).build();\n\n public static final String CONTENT_TYPE =\n \"vnd.android.cursor.dir/vnd.androidito-iosched.block\";\n public static final String CONTENT_ITEM_TYPE =\n \"vnd.android.cursor.item/vnd.androidito-iosched.block\";\n\n /** Count of {@link Sessions} inside given block. */\n public static final String SESSIONS_COUNT = \"sessions_count\";\n\n /**\n * Flag indicating the number of sessions inside this block that have\n * {@link Sessions#SESSION_STARRED} set.\n */\n public static final String NUM_STARRED_SESSIONS = \"num_starred_sessions\";\n\n /**\n * The {@link Sessions#SESSION_ID} of the first starred session in this\n * block.\n */\n public static final String STARRED_SESSION_ID = \"starred_session_id\";\n\n /**\n * The {@link Sessions#SESSION_TITLE} of the first starred session in\n * this block.\n */\n public static final String STARRED_SESSION_TITLE = \"starred_session_title\";\n\n /**\n * The {@link Sessions#SESSION_LIVESTREAM_URL} of the first starred\n * session in this block.\n */\n public static final String STARRED_SESSION_LIVESTREAM_URL =\n \"starred_session_livestream_url\";\n\n /**\n * The {@link Rooms#ROOM_NAME} of the first starred session in this\n * block.\n */\n public static final String STARRED_SESSION_ROOM_NAME = \"starred_session_room_name\";\n\n /**\n * The {@link Rooms#ROOM_ID} of the first starred session in this block.\n */\n public static final String STARRED_SESSION_ROOM_ID = \"starred_session_room_id\";\n\n /**\n * The {@link Sessions#SESSION_HASHTAGS} of the first starred session in\n * this block.\n */\n public static final String STARRED_SESSION_HASHTAGS = \"starred_session_hashtags\";\n\n /**\n * The {@link Sessions#SESSION_URL} of the first starred session in this\n * block.\n */\n public static final String STARRED_SESSION_URL = \"starred_session_url\";\n\n /** Default \"ORDER BY\" clause. */\n public static final String DEFAULT_SORT = BlocksColumns.BLOCK_START + \" ASC, \"\n + BlocksColumns.BLOCK_END + \" ASC\";\n\n public static final String EMPTY_SESSIONS_SELECTION = \"(\" + BLOCK_TYPE\n + \" = '\" + ParserUtils.BLOCK_TYPE_SESSION + \"' OR \" + BLOCK_TYPE\n + \" = '\" + ParserUtils.BLOCK_TYPE_CODE_LAB + \"') AND \"\n + SESSIONS_COUNT + \" = 0\";\n\n /** Build {@link Uri} for requested {@link #BLOCK_ID}. */\n public static Uri buildBlockUri(String blockId) {\n return CONTENT_URI.buildUpon().appendPath(blockId).build();\n }\n\n /**\n * Build {@link Uri} that references any {@link Sessions} associated\n * with the requested {@link #BLOCK_ID}.\n */\n public static Uri buildSessionsUri(String blockId) {\n return CONTENT_URI.buildUpon().appendPath(blockId).appendPath(PATH_SESSIONS).build();\n }\n\n /**\n * Build {@link Uri} that references starred {@link Sessions} associated\n * with the requested {@link #BLOCK_ID}.\n */\n public static Uri buildStarredSessionsUri(String blockId) {\n return CONTENT_URI.buildUpon().appendPath(blockId).appendPath(PATH_SESSIONS)\n .appendPath(PATH_STARRED).build();\n }\n\n /**\n * Build {@link Uri} that references any {@link Blocks} that occur\n * between the requested time boundaries.\n */\n public static Uri buildBlocksBetweenDirUri(long startTime, long endTime) {\n return CONTENT_URI.buildUpon().appendPath(PATH_BETWEEN).appendPath(\n String.valueOf(startTime)).appendPath(String.valueOf(endTime)).build();\n }\n\n /** Read {@link #BLOCK_ID} from {@link Blocks} {@link Uri}. */\n public static String getBlockId(Uri uri) {\n return uri.getPathSegments().get(1);\n }\n\n /**\n * Generate a {@link #BLOCK_ID} that will always match the requested\n * {@link Blocks} details.\n */\n public static String generateBlockId(long startTime, long endTime) {\n startTime /= DateUtils.SECOND_IN_MILLIS;\n endTime /= DateUtils.SECOND_IN_MILLIS;\n return ParserUtils.sanitizeId(startTime + \"-\" + endTime);\n }\n }\n\n /**\n * Tracks are overall categories for {@link Sessions} and {@link Vendors},\n * such as \"Android\" or \"Enterprise.\"\n */\n public static class Tracks implements TracksColumns, BaseColumns {\n public static final Uri CONTENT_URI =\n BASE_CONTENT_URI.buildUpon().appendPath(PATH_TRACKS).build();\n\n public static final String CONTENT_TYPE =\n \"vnd.android.cursor.dir/vnd.androidito-iosched.track\";\n public static final String CONTENT_ITEM_TYPE =\n \"vnd.android.cursor.item/vnd.androidito-iosched.track\";\n\n /** \"All tracks\" ID. */\n public static final String ALL_TRACK_ID = \"all\";\n public static final String CODELABS_TRACK_ID = generateTrackId(\"Code Labs\");\n public static final String TECH_TALK_TRACK_ID = generateTrackId(\"Tech Talk\");\n\n /** Count of {@link Sessions} inside given track. */\n public static final String SESSIONS_COUNT = \"sessions_count\";\n /** Count of {@link Vendors} inside given track. */\n public static final String VENDORS_COUNT = \"vendors_count\";\n\n /** Default \"ORDER BY\" clause. */\n public static final String DEFAULT_SORT = TracksColumns.TRACK_NAME + \" ASC\";\n\n /** Build {@link Uri} for requested {@link #TRACK_ID}. */\n public static Uri buildTrackUri(String trackId) {\n return CONTENT_URI.buildUpon().appendPath(trackId).build();\n }\n\n /**\n * Build {@link Uri} that references any {@link Sessions} associated\n * with the requested {@link #TRACK_ID}.\n */\n public static Uri buildSessionsUri(String trackId) {\n return CONTENT_URI.buildUpon().appendPath(trackId).appendPath(PATH_SESSIONS).build();\n }\n\n /**\n * Build {@link Uri} that references any {@link Vendors} associated with\n * the requested {@link #TRACK_ID}.\n */\n public static Uri buildVendorsUri(String trackId) {\n return CONTENT_URI.buildUpon().appendPath(trackId).appendPath(PATH_VENDORS).build();\n }\n\n /** Read {@link #TRACK_ID} from {@link Tracks} {@link Uri}. */\n public static String getTrackId(Uri uri) {\n return uri.getPathSegments().get(1);\n }\n\n /**\n * Generate a {@link #TRACK_ID} that will always match the requested\n * {@link Tracks} details.\n */\n public static String generateTrackId(String name) {\n return ParserUtils.sanitizeId(name);\n }\n }\n\n /**\n * Rooms are physical locations at the conference venue.\n */\n public static class Rooms implements RoomsColumns, BaseColumns {\n public static final Uri CONTENT_URI =\n BASE_CONTENT_URI.buildUpon().appendPath(PATH_ROOMS).build();\n\n public static final String CONTENT_TYPE =\n \"vnd.android.cursor.dir/vnd.androidito-iosched.room\";\n public static final String CONTENT_ITEM_TYPE =\n \"vnd.android.cursor.item/vnd.androidito-iosched.room\";\n\n /** Default \"ORDER BY\" clause. */\n public static final String DEFAULT_SORT = RoomsColumns.ROOM_FLOOR + \" ASC, \"\n + RoomsColumns.ROOM_NAME + \" COLLATE NOCASE ASC\";\n\n /** Build {@link Uri} for requested {@link #ROOM_ID}. */\n public static Uri buildRoomUri(String roomId) {\n return CONTENT_URI.buildUpon().appendPath(roomId).build();\n }\n\n /**\n * Build {@link Uri} that references any {@link Sessions} associated\n * with the requested {@link #ROOM_ID}.\n */\n public static Uri buildSessionsDirUri(String roomId) {\n return CONTENT_URI.buildUpon().appendPath(roomId).appendPath(PATH_SESSIONS).build();\n }\n\n /** Read {@link #ROOM_ID} from {@link Rooms} {@link Uri}. */\n public static String getRoomId(Uri uri) {\n return uri.getPathSegments().get(1);\n }\n }\n\n /**\n * Each session is a block of time that has a {@link Tracks}, a\n * {@link Rooms}, and zero or more {@link Speakers}.\n */\n public static class Sessions implements SessionsColumns, BlocksColumns, RoomsColumns,\n SyncColumns, BaseColumns {\n public static final Uri CONTENT_URI =\n BASE_CONTENT_URI.buildUpon().appendPath(PATH_SESSIONS).build();\n public static final Uri CONTENT_STARRED_URI =\n CONTENT_URI.buildUpon().appendPath(PATH_STARRED).build();\n\n public static final String CONTENT_TYPE =\n \"vnd.android.cursor.dir/vnd.androidito-iosched.session\";\n public static final String CONTENT_ITEM_TYPE =\n \"vnd.android.cursor.item/vnd.androidito-iosched.session\";\n\n public static final String BLOCK_ID = \"block_id\";\n public static final String ROOM_ID = \"room_id\";\n public static final String START = \"session_start\";\n public static final String END = \"session_end\";\n\n\n public static final String SEARCH_SNIPPET = \"search_snippet\";\n\n // TODO: shortcut primary track to offer sub-sorting here\n /** Default \"ORDER BY\" clause. */\n public static final String DEFAULT_SORT = BlocksColumns.BLOCK_START + \" ASC,\"\n + SessionsColumns.SESSION_TITLE + \" COLLATE NOCASE ASC\";\n\n public static final String BLOCK_SESSION_SORT =\n ROOM_NAME + \" ASC,\"+\n SessionsColumns.SESSION_START + \" ASC\";\n\n public static final String LIVESTREAM_SELECTION =\n SESSION_LIVESTREAM_URL + \" is not null AND \" + SESSION_LIVESTREAM_URL + \"!=''\";\n\n // Used to fetch sessions for a particular time\n public static final String AT_TIME_SELECTION =\n BLOCK_START + \" < ? and \" + BLOCK_END + \" \" + \"> ?\";\n\n // Builds selectionArgs for {@link AT_TIME_SELECTION}\n public static String[] buildAtTimeSelectionArgs(long time) {\n final String timeString = String.valueOf(time);\n return new String[] { timeString, timeString };\n }\n\n // Used to fetch upcoming sessions\n public static final String UPCOMING_SELECTION =\n BLOCK_START + \" = (select min(\" + BLOCK_START + \") from \" +\n ScheduleDatabase.Tables.BLOCKS_JOIN_SESSIONS + \" where \" + LIVESTREAM_SELECTION +\n \" and \" + BLOCK_START + \" >\" + \" ?)\";\n\n // Builds selectionArgs for {@link UPCOMING_SELECTION}\n public static String[] buildUpcomingSelectionArgs(long minTime) {\n return new String[] { String.valueOf(minTime) };\n }\n\n /** Build {@link Uri} for requested {@link #SESSION_ID}. */\n public static Uri buildSessionUri(String sessionId) {\n return CONTENT_URI.buildUpon().appendPath(sessionId).build();\n }\n\n /**\n * Build {@link Uri} that references any {@link Speakers} associated\n * with the requested {@link #SESSION_ID}.\n */\n public static Uri buildSpeakersDirUri(String sessionId) {\n return CONTENT_URI.buildUpon().appendPath(sessionId).appendPath(PATH_SPEAKERS).build();\n }\n\n /**\n * Build {@link Uri} that includes track detail with list of sessions.\n */\n public static Uri buildWithTracksUri() {\n return CONTENT_URI.buildUpon().appendPath(PATH_WITH_TRACK).build();\n }\n\n /**\n * Build {@link Uri} that includes track detail for a specific session.\n */\n public static Uri buildWithTracksUri(String sessionId) {\n return CONTENT_URI.buildUpon().appendPath(sessionId)\n .appendPath(PATH_WITH_TRACK).build();\n }\n\n /**\n * Build {@link Uri} that references any {@link Tracks} associated with\n * the requested {@link #SESSION_ID}.\n */\n public static Uri buildTracksDirUri(String sessionId) {\n return CONTENT_URI.buildUpon().appendPath(sessionId).appendPath(PATH_TRACKS).build();\n }\n\n public static Uri buildSessionsAtDirUri(long time) {\n return CONTENT_URI.buildUpon().appendPath(PATH_AT).appendPath(String.valueOf(time))\n .build();\n }\n\n public static Uri buildSearchUri(String query) {\n return CONTENT_URI.buildUpon().appendPath(PATH_SEARCH).appendPath(query).build();\n }\n\n public static boolean isSearchUri(Uri uri) {\n List<String> pathSegments = uri.getPathSegments();\n return pathSegments.size() >= 2 && PATH_SEARCH.equals(pathSegments.get(1));\n }\n\n /** Read {@link #SESSION_ID} from {@link Sessions} {@link Uri}. */\n public static String getSessionId(Uri uri) {\n return uri.getPathSegments().get(1);\n }\n\n public static String getSearchQuery(Uri uri) {\n return uri.getPathSegments().get(2);\n }\n }\n\n /**\n * Speakers are individual people that lead {@link Sessions}.\n */\n public static class Speakers implements SpeakersColumns, SyncColumns, BaseColumns {\n public static final Uri CONTENT_URI =\n BASE_CONTENT_URI.buildUpon().appendPath(PATH_SPEAKERS).build();\n\n public static final String CONTENT_TYPE =\n \"vnd.android.cursor.dir/vnd.androidito-iosched.speaker\";\n public static final String CONTENT_ITEM_TYPE =\n \"vnd.android.cursor.item/vnd.androidito-iosched.speaker\";\n\n /** Default \"ORDER BY\" clause. */\n public static final String DEFAULT_SORT = SpeakersColumns.SPEAKER_NAME\n + \" COLLATE NOCASE ASC\";\n\n /** Build {@link Uri} for requested {@link #SPEAKER_ID}. */\n public static Uri buildSpeakerUri(String speakerId) {\n return CONTENT_URI.buildUpon().appendPath(speakerId).build();\n }\n\n /**\n * Build {@link Uri} that references any {@link Sessions} associated\n * with the requested {@link #SPEAKER_ID}.\n */\n public static Uri buildSessionsDirUri(String speakerId) {\n return CONTENT_URI.buildUpon().appendPath(speakerId).appendPath(PATH_SESSIONS).build();\n }\n\n /** Read {@link #SPEAKER_ID} from {@link Speakers} {@link Uri}. */\n public static String getSpeakerId(Uri uri) {\n return uri.getPathSegments().get(1);\n }\n }\n\n /**\n * Each vendor is a company appearing at the conference that may be\n * associated with a specific {@link Tracks}.\n */\n public static class Vendors implements VendorsColumns, SyncColumns, BaseColumns {\n public static final Uri CONTENT_URI =\n BASE_CONTENT_URI.buildUpon().appendPath(PATH_VENDORS).build();\n\n public static final String CONTENT_TYPE =\n \"vnd.android.cursor.dir/vnd.androidito-iosched.vendor\";\n public static final String CONTENT_ITEM_TYPE =\n \"vnd.android.cursor.item/vnd.androidito-iosched.vendor\";\n\n /** {@link Tracks#TRACK_ID} that this vendor belongs to. */\n public static final String TRACK_ID = \"track_id\";\n\n public static final String SEARCH_SNIPPET = \"search_snippet\";\n\n /** Default \"ORDER BY\" clause. */\n public static final String DEFAULT_SORT = VendorsColumns.VENDOR_NAME\n + \" COLLATE NOCASE ASC\";\n\n /** Build {@link Uri} for requested {@link #VENDOR_ID}. */\n public static Uri buildVendorUri(String vendorId) {\n return CONTENT_URI.buildUpon().appendPath(vendorId).build();\n }\n\n public static Uri buildSearchUri(String query) {\n return CONTENT_URI.buildUpon().appendPath(PATH_SEARCH).appendPath(query).build();\n }\n\n public static boolean isSearchUri(Uri uri) {\n List<String> pathSegments = uri.getPathSegments();\n return pathSegments.size() >= 2 && PATH_SEARCH.equals(pathSegments.get(1));\n }\n\n /** Read {@link #VENDOR_ID} from {@link Vendors} {@link Uri}. */\n public static String getVendorId(Uri uri) {\n return uri.getPathSegments().get(1);\n }\n\n public static String getSearchQuery(Uri uri) {\n return uri.getPathSegments().get(2);\n }\n\n /**\n * Generate a {@link #VENDOR_ID} that will always match the requested\n * {@link Vendors} details.\n */\n public static String generateVendorId(String companyName) {\n return ParserUtils.sanitizeId(companyName);\n }\n }\n\n /**\n * Announcements of breaking news\n */\n public static class Announcements implements AnnouncementsColumns, BaseColumns {\n public static final Uri CONTENT_URI =\n BASE_CONTENT_URI.buildUpon().appendPath(PATH_ANNOUNCEMENTS).build();\n\n public static final String CONTENT_TYPE =\n \"vnd.android.cursor.dir/vnd.androidito-iosched.announcement\";\n public static final String CONTENT_ITEM_TYPE =\n \"vnd.android.cursor.item/vnd.androidito-iosched.announcement\";\n\n /** Default \"ORDER BY\" clause. */\n public static final String DEFAULT_SORT = AnnouncementsColumns.ANNOUNCEMENT_DATE\n + \" COLLATE NOCASE ASC\";\n\n /** Build {@link Uri} for requested {@link #ANNOUNCEMENT_ID}. */\n public static Uri buildAnnouncementUri(String announcementId) {\n return CONTENT_URI.buildUpon().appendPath(announcementId).build();\n }\n\n /**\n * Build {@link Uri} that references any {@link Announcements}\n * associated with the requested {@link #ANNOUNCEMENT_ID}.\n */\n public static Uri buildAnnouncementsDirUri(String announcementId) {\n return CONTENT_URI.buildUpon().appendPath(announcementId)\n .appendPath(PATH_ANNOUNCEMENTS).build();\n }\n\n /**\n * Read {@link #ANNOUNCEMENT_ID} from {@link Announcements} {@link Uri}.\n */\n public static String getAnnouncementId(Uri uri) {\n return uri.getPathSegments().get(1);\n }\n }\n\n public static class SearchSuggest {\n public static final Uri CONTENT_URI =\n BASE_CONTENT_URI.buildUpon().appendPath(PATH_SEARCH_SUGGEST).build();\n\n public static final String DEFAULT_SORT = SearchManager.SUGGEST_COLUMN_TEXT_1\n + \" COLLATE NOCASE ASC\";\n }\n\n public static Uri addCallerIsSyncAdapterParameter(Uri uri) {\n return uri.buildUpon().appendQueryParameter(\n ContactsContract.CALLER_IS_SYNCADAPTER, \"true\").build();\n }\n\n public static boolean hasCallerIsSyncAdapterParameter(Uri uri) {\n return TextUtils.equals(\"true\",\n uri.getQueryParameter(ContactsContract.CALLER_IS_SYNCADAPTER));\n }\n\n private ScheduleContract() {\n }\n}",
"public class UIUtils {\n /**\n * Time zone to use when formatting all session times. To always use the\n * phone local time, use {@link TimeZone#getDefault()}.\n */\n public static final TimeZone CONFERENCE_TIME_ZONE = TimeZone.getTimeZone(\"Europe/Oslo\");\n\n public static final long CONFERENCE_START_MILLIS = ParserUtils.parseTime(\n \"2016-09-07T08:00:00.000+01:00\");\n public static final long CONFERENCE_END_MILLIS = ParserUtils.parseTime(\n \"2016-09-08T18:00:00.000+01:00\");\n\n public static final String CONFERENCE_HASHTAG = \"#javazone\";\n\n private static final int SECOND_MILLIS = 1000;\n private static final int MINUTE_MILLIS = 60 * SECOND_MILLIS;\n private static final int HOUR_MILLIS = 60 * MINUTE_MILLIS;\n private static final int DAY_MILLIS = 24 * HOUR_MILLIS;\n\n /**\n * Flags used with {@link DateUtils#formatDateRange}.\n */\n private static final int TIME_FLAGS = DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_WEEKDAY | DateUtils.FORMAT_ABBREV_WEEKDAY | DateUtils.FORMAT_24HOUR;\n private static final int LIGHTNING_TALK_TIME_FLAGS = DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_24HOUR;\n\n /**\n * {@link StringBuilder} used for formatting time block.\n */\n private static StringBuilder sBuilder = new StringBuilder(50);\n /**\n * {@link Formatter} used for formatting time block.\n */\n private static Formatter sFormatter = new Formatter(sBuilder, Locale.getDefault());\n\n private static StyleSpan sBoldSpan = new StyleSpan(Typeface.BOLD);\n\n private static CharSequence sEmptyRoomText;\n private static CharSequence sCodeLabRoomText;\n\n private static CharSequence sNowPlayingText;\n private static CharSequence sLivestreamNowText;\n private static CharSequence sLivestreamAvailableText;\n\n public static final String GOOGLE_PLUS_PACKAGE_NAME = \"com.google.android.apps.plus\";\n\n /**\n * Format and return the given {@link Blocks} and {@link Rooms} values using\n * {@link #CONFERENCE_TIME_ZONE}.\n */\n public static String formatSessionSubtitle(String sessionTitle,\n long blockStart, long blockEnd, long sessionStart, long sessionEnd, String roomName, String type, Context context) {\n if (sEmptyRoomText == null || sCodeLabRoomText == null) {\n sEmptyRoomText = context.getText(R.string.unknown_room);\n\n }\n\n //TODO JavaZone room name handling\n if (roomName == null) {\n roomName = \"TBD\";\n //return context.getString(R.string.session_subtitle,\n // formatBlockTimeString(blockStart, blockEnd, context), sEmptyRoomText,type);\n }\n\n\n if (Constants.LIGHTNINGTALK.equals(type)) {\n //if (sessionStart != 0) {\n // type = \"(Lightning talk starts \" + formatLightningTalkTimeString(sessionStart, context) + \")\";\n //} else {\n type = \"(Lightning talk)\";\n //}\n } else {\n type = \"\";\n }\n\n return context.getString(\n R.string.session_subtitle,\n formatBlockTimeString(sessionStart, sessionEnd, context),\n roomName, type\n );\n }\n\n private static String formatLightningTalkTimeString(long sessionStart, Context context) {\n TimeZone.setDefault(CONFERENCE_TIME_ZONE);\n\n if (sessionStart == 0) {\n return \"TBD\";\n }\n\n return DateUtils.formatDateTime(context, sessionStart, LIGHTNING_TALK_TIME_FLAGS);\n }\n\n /**\n * Format and return the given {@link Blocks} values using\n * {@link #CONFERENCE_TIME_ZONE}.\n */\n public static String formatBlockTimeString(long blockStart, long blockEnd, Context context) {\n TimeZone.setDefault(CONFERENCE_TIME_ZONE);\n\n if (blockStart == 0) {\n return \"TBD\";\n }\n\n // NOTE: There is an efficient version of formatDateRange in Eclair and\n // beyond that allows you to recycle a StringBuilder.\n return DateUtils.formatDateRange(context, blockStart, blockEnd, TIME_FLAGS);\n }\n\n public static boolean isSameDay(long time1, long time2) {\n TimeZone.setDefault(CONFERENCE_TIME_ZONE);\n\n Calendar cal1 = Calendar.getInstance();\n Calendar cal2 = Calendar.getInstance();\n cal1.setTimeInMillis(time1);\n cal2.setTimeInMillis(time2);\n return cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) &&\n cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR);\n }\n\n public static String getTimeAgo(long time, Context ctx) {\n if (time < 1000000000000L) {\n // if timestamp given in seconds, convert to millis\n time *= 1000;\n }\n\n long now = getCurrentTime(ctx);\n if (time > now || time <= 0) {\n return null;\n }\n\n // TODO: localize\n final long diff = now - time;\n if (diff < MINUTE_MILLIS) {\n return \"just now\";\n } else if (diff < 2 * MINUTE_MILLIS) {\n return \"a minute ago\";\n } else if (diff < 50 * MINUTE_MILLIS) {\n return diff / MINUTE_MILLIS + \" minutes ago\";\n } else if (diff < 90 * MINUTE_MILLIS) {\n return \"an hour ago\";\n } else if (diff < 24 * HOUR_MILLIS) {\n return diff / HOUR_MILLIS + \" hours ago\";\n } else if (diff < 48 * HOUR_MILLIS) {\n return \"yesterday\";\n } else {\n return diff / DAY_MILLIS + \" days ago\";\n }\n }\n\n /**\n * Populate the given {@link TextView} with the requested text, formatting\n * through {@link Html#fromHtml(String)} when applicable. Also sets\n * {@link TextView#setMovementMethod} so inline links are handled.\n */\n public static void setTextMaybeHtml(TextView view, String text) {\n if (TextUtils.isEmpty(text)) {\n view.setText(\"\");\n return;\n }\n if (text.contains(\"<\") && text.contains(\">\")) {\n view.setText(Html.fromHtml(text));\n view.setMovementMethod(LinkMovementMethod.getInstance());\n } else {\n view.setText(text);\n }\n }\n\n public static void updateTimeAndLivestreamBlockUI(final Context context,\n long blockStart, long blockEnd, boolean hasLivestream,\n View backgroundView, TextView titleView, TextView subtitleView,\n CharSequence subtitle) {\n long currentTimeMillis = getCurrentTime(context);\n\n boolean past = (currentTimeMillis > blockEnd && currentTimeMillis < CONFERENCE_END_MILLIS);\n boolean present = (blockStart <= currentTimeMillis && currentTimeMillis <= blockEnd);\n\n final Resources res = context.getResources();\n if (backgroundView != null) {\n backgroundView.setBackgroundColor(past\n ? res.getColor(R.color.past_background_color)\n : 0);\n }\n\n if (titleView != null) {\n titleView.setTypeface(Typeface.SANS_SERIF, past ? Typeface.NORMAL : Typeface.BOLD);\n }\n\n if (subtitleView != null) {\n boolean empty = true;\n SpannableStringBuilder sb = new SpannableStringBuilder(); // TODO: recycle\n if (subtitle != null) {\n sb.append(subtitle);\n empty = false;\n }\n\n if (present) {\n if (sNowPlayingText == null) {\n sNowPlayingText = Html.fromHtml(context.getString(R.string.now_playing_badge));\n }\n if (!empty) {\n sb.append(\" \");\n }\n sb.append(sNowPlayingText);\n\n if (hasLivestream) {\n if (sLivestreamNowText == null) {\n sLivestreamNowText = Html.fromHtml(\" \" +\n context.getString(R.string.live_now_badge));\n }\n sb.append(sLivestreamNowText);\n }\n } else if (hasLivestream) {\n if (sLivestreamAvailableText == null) {\n sLivestreamAvailableText = Html.fromHtml(\n context.getString(R.string.live_available_badge));\n }\n if (!empty) {\n sb.append(\" \");\n }\n sb.append(sLivestreamAvailableText);\n }\n\n subtitleView.setText(sb);\n }\n }\n\n /**\n * Given a snippet string with matching segments surrounded by curly\n * braces, turn those areas into bold spans, removing the curly braces.\n */\n public static Spannable buildStyledSnippet(String snippet) {\n final SpannableStringBuilder builder = new SpannableStringBuilder(snippet);\n\n // Walk through string, inserting bold snippet spans\n int startIndex = -1, endIndex = -1, delta = 0;\n while ((startIndex = snippet.indexOf('{', endIndex)) != -1) {\n endIndex = snippet.indexOf('}', startIndex);\n\n // Remove braces from both sides\n builder.delete(startIndex - delta, startIndex - delta + 1);\n builder.delete(endIndex - delta - 1, endIndex - delta);\n\n // Insert bold style\n builder.setSpan(sBoldSpan, startIndex - delta, endIndex - delta - 1,\n Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);\n\n delta += 2;\n }\n\n return builder;\n }\n\n public static void preferPackageForIntent(Context context, Intent intent, String packageName) {\n PackageManager pm = context.getPackageManager();\n for (ResolveInfo resolveInfo : pm.queryIntentActivities(intent, 0)) {\n if (resolveInfo.activityInfo.packageName.equals(packageName)) {\n intent.setPackage(packageName);\n break;\n }\n }\n }\n\n public static ImageFetcher getImageFetcher(final FragmentActivity activity) {\n // The ImageFetcher takes care of loading remote images into our ImageView\n ImageFetcher fetcher = new ImageFetcher(activity);\n fetcher.setImageCache(ImageCache.findOrCreateCache(activity, \"imageFetcher\"));\n return fetcher;\n }\n\n public static String getSessionHashtagsString(String hashtags) {\n if (!TextUtils.isEmpty(hashtags)) {\n if (!hashtags.startsWith(\"#\")) {\n hashtags = \"#\" + hashtags;\n }\n\n if (hashtags.contains(CONFERENCE_HASHTAG)) {\n return hashtags;\n }\n return CONFERENCE_HASHTAG + \" \" + hashtags;\n } else {\n return CONFERENCE_HASHTAG;\n }\n }\n\n private static final int BRIGHTNESS_THRESHOLD = 130;\n\n /**\n * Calculate whether a color is light or dark, based on a commonly known\n * brightness formula.\n *\n * @see {@literal http://en.wikipedia.org/wiki/HSV_color_space%23Lightness}\n */\n public static boolean isColorDark(int color) {\n return Color.alpha(color) != 0 && (((30 * Color.red(color) +\n 59 * Color.green(color) +\n 11 * Color.blue(color)) / 100) <= BRIGHTNESS_THRESHOLD);\n }\n\n // Shows whether a notification was fired for a particular session time block. In the\n // event that notification has not been fired yet, return false and set the bit.\n public static boolean isNotificationFiredForBlock(Context context, String blockId) {\n SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);\n final String key = String.format(\"notification_fired_%s\", blockId);\n boolean fired = sp.getBoolean(key, false);\n sp.edit().putBoolean(key, true).commit();\n return fired;\n }\n\n private static final long sAppLoadTime = System.currentTimeMillis();\n\n public static long getCurrentTime(final Context context) {\n if (BuildConfig.DEBUG) {\n return context.getSharedPreferences(\"mock_data\", Context.MODE_PRIVATE)\n .getLong(\"mock_current_time\", System.currentTimeMillis())\n + System.currentTimeMillis() - sAppLoadTime;\n } else {\n return System.currentTimeMillis();\n }\n }\n\n public static void safeOpenLink(Context context, Intent linkIntent) {\n try {\n context.startActivity(linkIntent);\n } catch (ActivityNotFoundException e) {\n Toast.makeText(context, \"Couldn't open link\", Toast.LENGTH_SHORT).show();\n }\n }\n\n // TODO: use <meta-data> element instead\n private static final Class[] sPhoneActivities = new Class[]{\n MapActivity.class,\n SessionDetailActivity.class,\n SessionsActivity.class,\n TrackDetailActivity.class,\n VendorDetailActivity.class,\n };\n\n // TODO: use <meta-data> element instead\n private static final Class[] sTabletActivities = new Class[]{\n MapMultiPaneActivity.class,\n SessionsVendorsMultiPaneActivity.class,\n };\n\n public static void enableDisableActivities(final Context context) {\n boolean isHoneycombTablet = isHoneycombTablet(context);\n PackageManager pm = context.getPackageManager();\n\n // Enable/disable phone activities\n for (Class a : sPhoneActivities) {\n pm.setComponentEnabledSetting(new ComponentName(context, a),\n isHoneycombTablet\n ? PackageManager.COMPONENT_ENABLED_STATE_DISABLED\n : PackageManager.COMPONENT_ENABLED_STATE_ENABLED,\n PackageManager.DONT_KILL_APP);\n }\n\n // Enable/disable tablet activities\n for (Class a : sTabletActivities) {\n pm.setComponentEnabledSetting(new ComponentName(context, a),\n isHoneycombTablet\n ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED\n : PackageManager.COMPONENT_ENABLED_STATE_DISABLED,\n PackageManager.DONT_KILL_APP);\n }\n }\n\n public static Class getMapActivityClass(Context context) {\n if (UIUtils.isHoneycombTablet(context)) {\n return MapMultiPaneActivity.class;\n }\n\n return MapActivity.class;\n }\n\n @TargetApi(Build.VERSION_CODES.HONEYCOMB)\n public static void setActivatedCompat(View view, boolean activated) {\n if (hasHoneycomb()) {\n view.setActivated(activated);\n }\n }\n\n public static boolean isGoogleTV(Context context) {\n return context.getPackageManager().hasSystemFeature(\"com.google.android.tv\");\n }\n\n public static boolean hasFroyo() {\n // Can use static final constants like FROYO, declared in later versions\n // of the OS since they are inlined at compile time. This is guaranteed behavior.\n return Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO;\n }\n\n public static boolean hasGingerbread() {\n return Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD;\n }\n\n public static boolean hasHoneycomb() {\n return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB;\n }\n\n public static boolean hasHoneycombMR1() {\n return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1;\n }\n\n public static boolean hasICS() {\n return Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH;\n }\n\n public static boolean hasJellyBean() {\n return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN;\n }\n\n public static boolean hasLollipop() {\n return Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP;\n }\n\n public static boolean isTablet(Context context) {\n return (context.getResources().getConfiguration().screenLayout\n & Configuration.SCREENLAYOUT_SIZE_MASK)\n >= Configuration.SCREENLAYOUT_SIZE_LARGE;\n }\n\n public static boolean isHoneycombTablet(Context context) {\n return hasHoneycomb() && isTablet(context);\n }\n\n public static void colorImageViewArray(ImageView[] imageViews, int colorId) {\n for(ImageView imageView : imageViews) {\n imageView.setColorFilter(colorId, PorterDuff.Mode.SRC_IN);\n }\n }\n}",
"public static void LOGD(final String tag, String message) {\n if (Log.isLoggable(tag, Log.DEBUG)) {\n Log.d(tag, message);\n }\n}",
"public static String makeLogTag(String str) {\n if (str.length() > MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH) {\n return LOG_PREFIX + str.substring(0, MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 1);\n }\n\n return LOG_PREFIX + str;\n}",
"public static Spannable buildStyledSnippet(String snippet) {\n final SpannableStringBuilder builder = new SpannableStringBuilder(snippet);\n\n // Walk through string, inserting bold snippet spans\n int startIndex = -1, endIndex = -1, delta = 0;\n while ((startIndex = snippet.indexOf('{', endIndex)) != -1) {\n endIndex = snippet.indexOf('}', startIndex);\n\n // Remove braces from both sides\n builder.delete(startIndex - delta, startIndex - delta + 1);\n builder.delete(endIndex - delta - 1, endIndex - delta);\n\n // Insert bold style\n builder.setSpan(sBoldSpan, startIndex - delta, endIndex - delta - 1,\n Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);\n\n delta += 2;\n }\n\n return builder;\n}"
] | import no.java.schedule.R;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.util.UIUtils;
import com.actionbarsherlock.app.SherlockListFragment;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.text.Spannable;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.TextView;
import static com.google.android.apps.iosched.util.LogUtils.LOGD;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
import static com.google.android.apps.iosched.util.UIUtils.buildStyledSnippet; | /*
* Copyright 2012 Google Inc.
*
* 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.android.apps.iosched.ui;
/**
* A {@link ListFragment} showing a list of developer sandbox companies.
*/
public class VendorsFragment extends SherlockListFragment implements
LoaderManager.LoaderCallbacks<Cursor> {
| private static final String TAG = makeLogTag(VendorsFragment.class); | 3 |
aw20/MongoWorkBench | src/org/aw20/mongoworkbench/eclipse/view/MSystemJavaScript.java | [
"public class EventWorkBenchManager extends Object {\n\tprivate static EventWorkBenchManager thisInst;\n\t\n\tpublic static synchronized EventWorkBenchManager getInst(){\n\t\tif ( thisInst == null )\n\t\t\tthisInst = new EventWorkBenchManager();\n\n\t\treturn thisInst;\n\t}\n\n\tprivate Set<EventWorkBenchListener>\tlisteners;\n\t\n\tprivate EventWorkBenchManager(){\n\t\tlisteners\t= new HashSet<EventWorkBenchListener>();\n\t}\n\t\n\tpublic void registerListener(EventWorkBenchListener listener){\n\t\tlisteners.add(listener);\n\t}\n\t\n\tpublic void deregisterListener(EventWorkBenchListener listener){\n\t\tlisteners.remove(listener);\n\t}\n\n\tpublic void onEvent( final Event event, final Object data ){\n\t\t\n\t\tnew Thread(\"EventWorkBenchEventFire\"){ \n\t\t\tpublic void run(){\n\t\t\t\tIterator<EventWorkBenchListener>\tit\t= listeners.iterator();\n\t\t\t\twhile ( it.hasNext() ){\n\t\t\t\t\ttry{\n\t\t\t\t\t\tit.next().onEventWorkBench(event, data);\n\t\t\t\t\t}catch(Exception e){\n\t\t\t\t\t\tSystem.out.println(e);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}.start();\n\n\t}\n\t\n}",
"public interface MongoCommandListener {\n\n\tpublic void onMongoCommandStart( MongoCommand mcmd );\n\tpublic void onMongoCommandFinished( MongoCommand mcmd );\n\t\n}",
"public class MongoFactory extends Thread {\n\n\tprivate static MongoFactory\tthisInst = null;\n\t\n\tpublic static synchronized MongoFactory getInst(){\n\t\tif ( thisInst == null )\n\t\t\tthisInst = new MongoFactory();\n\n\t\treturn thisInst;\n\t}\n\t\n\tprivate Map<String,MongoClient>\tmongoMap;\n\t\n\tprivate Set<MongoCommandListener>\tmongoListeners;\n\tprivate Set<MDocumentView>\tdocumentViewListeners;\n\t\n\tprivate List<MongoCommand>\tcommandQueue;\n\tprivate Map<String, Class>\tcommandMap;\n\tprivate boolean bRun = true;\n\n\t\n\tprivate String activeServer = null, activeDB = null, activeCollection = null;\n\t\n\tpublic MongoFactory(){\n\t\tmongoMap\t\t\t\t\t\t\t= new HashMap<String,MongoClient>();\n\t\tcommandQueue\t\t\t\t\t=\tnew ArrayList<MongoCommand>(); \n\t\tmongoListeners\t\t\t\t= new HashSet<MongoCommandListener>();\n\t\tdocumentViewListeners\t= new HashSet<MDocumentView>();\n\t\tcommandMap\t\t\t\t\t\t= new HashMap<String,Class>();\n\n\t\t// Register the Commands\n\t\tcommandMap.put(\"^db\\\\.[^\\\\(]+\\\\.find\\\\(.*\", FindMongoCommand.class);\n\t\tcommandMap.put(\"^db\\\\.[^\\\\(]+\\\\.findOne\\\\(.*\", FindOneMongoCommand.class);\n\t\tcommandMap.put(\"^db\\\\.[^\\\\(]+\\\\.save\\\\(.*\", SaveMongoCommand.class);\n\t\tcommandMap.put(\"^db\\\\.[^\\\\(]+\\\\.update\\\\(.*\", UpdateMongoCommand.class);\n\t\tcommandMap.put(\"^db\\\\.[^\\\\(]+\\\\.remove\\\\(.*\", RemoveMongoCommand.class);\n\t\tcommandMap.put(\"^db\\\\.[^\\\\(]+\\\\.group\\\\(.*\", GroupMongoCommand.class);\n\t\tcommandMap.put(\"^db\\\\.[^\\\\(]+\\\\.aggregate\\\\(.*\", AggregateMongoCommand.class);\n\t\tcommandMap.put(\"^db\\\\.[^\\\\(]+\\\\.mapReduce\\\\(.*\", MapReduceMongoCommand.class);\n\t\tcommandMap.put(\"^use\\\\s+.*\", UseMongoCommand.class);\n\t\tcommandMap.put(\"^show dbs\", ShowDbsMongoCommand.class);\n\t\tcommandMap.put(\"^show collections\", ShowCollectionsMongoCommand.class);\n\t\tcommandMap.put(\"^db\\\\.serverStatus\\\\(.*\", DBserverStatsMongoCommand.class);\n\t\tcommandMap.put(\"^db\\\\.getStats\\\\(.*\", DBStatsMongoCommand.class);\n\n\t\tsetName( \"MongoFactory\" );\n\t\tstart();\n\t}\n\t\n\tpublic void registerListener(MongoCommandListener listener){\n\t\tif ( listener instanceof MDocumentView )\n\t\t\tdocumentViewListeners.add( (MDocumentView)listener );\n\t\telse\n\t\t\tmongoListeners.add(listener);\n\t}\n\t\n\tpublic void deregisterListener(MongoCommandListener listener){\n\t\tif ( listener instanceof MDocumentView )\n\t\t\tdocumentViewListeners.remove( (MDocumentView)listener );\n\t\telse\n\t\t\tmongoListeners.remove(listener);\n\t}\n\t\t\n\tpublic void removeMongo(String sName){\n\t\tMongoClient\tmclient\t= mongoMap.remove(sName);\n\t\tif ( mclient != null )\n\t\t\tmclient.close();\n\t}\n\t\n\t\n\tpublic MongoClient getMongo(String sName) {\n\t\tactiveServer = sName;\n\t\t\n\t\tif ( mongoMap.containsKey(sName) )\n\t\t\treturn mongoMap.get(sName);\n\t\telse{\n\t\t\ttry {\n\t\t\t\tMongoClient mc\t= Activator.getDefault().getMongoClient(sName);\n\t\t\t\tmongoMap.put( sName, mc );\n\t\t\t\treturn mc;\n\t\t\t} catch (UnknownHostException e) {\n\t\t\t\tEventWorkBenchManager.getInst().onEvent( org.aw20.mongoworkbench.Event.EXCEPTION, e);\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic void destroy(){\n\t\tbRun = false;\n\t}\n\t\n\tpublic String getActiveServer(){\n\t\treturn activeServer;\n\t}\n\t\n\tpublic String getActiveDB(){\n\t\treturn activeDB;\n\t}\n\t\n\tpublic void setActiveDB(String db){\n\t\tthis.activeDB = db;\n\t}\n\t\n\tpublic MongoCommand\tcreateCommand( String cmd ) throws Exception {\n\t\t\n\t\t// remove line breaks\n\t\tcmd = cmd.replaceAll(\"(\\\\r|\\\\n)\", \"\");\n\t\tcmd = cmd.replaceAll(\"\\\\t+\", \" \");\n\t\tcmd\t= cmd.trim();\n\n\t\tIterator p = commandMap.keySet().iterator();\n\t\twhile (p.hasNext()) {\n\t\t\tString patternStr = (String) p.next();\n\t\t\tif (cmd.matches(patternStr)) {\n\t\t\t\tClass clazz = (Class) commandMap.get(patternStr);\n\t\t\t\ttry {\n\t\t\t\t\tMongoCommand mcmd = (MongoCommand)clazz.newInstance();\n\t\t\t\t\tmcmd.setConnection(activeServer, activeDB);\n\t\t\t\t\tmcmd.setCommandStr( cmd );\n\t\t\t\t\tmcmd.parseCommandStr();\n\t\t\t\t\treturn mcmd;\n\t\t\t\t} catch (Exception e) {\n\t\t\t\t\tEventWorkBenchManager.getInst().onEvent( Event.EXCEPTION, e);\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\t// Determine if this is a command\n\t\tif ( cmd.startsWith(\"db.\") || cmd.startsWith(\"sh.\") || cmd.startsWith(\"rs.\") ){\n\t\t\tMongoCommand mcmd = new PassThruMongoCommand();\n\t\t\tmcmd.setConnection(activeServer, activeDB);\n\t\t\tmcmd.setCommandStr(cmd);\n\t\t\treturn mcmd;\n\t\t}\n\t\t\t\n\t\t\n\t\treturn null;\n\t}\n\t\n\tpublic void submitExecution( MongoCommand mcmd ){\n\t\tsynchronized(commandQueue){\n\t\t\tcommandQueue.add(mcmd);\n\t\t\tcommandQueue.notify();\n\t\t}\n\t}\n\n\tpublic MongoClient getMongoActive() {\n\t\treturn mongoMap.get(activeServer);\n\t}\n\n\tpublic DB getMongoActiveDB() {\n\t\treturn mongoMap.get(activeServer).getDB(activeDB);\n\t}\n\t\n\tpublic void run(){\n\t\tMongoCommand\tcmd;\n\t\t\n\t\twhile (bRun){\n\t\t\t\n\t\t\twhile ( commandQueue.size() == 0 ){\n\t\t\t\tsynchronized (commandQueue) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tcommandQueue.wait();\n\t\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t\t\tbRun = false;\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tsynchronized(commandQueue){\n\t\t\t\tcmd\t= commandQueue.remove(0);\n\t\t\t\tif ( cmd == null )\n\t\t\t\t\tcontinue;\n\t\t\t}\n\n\n\t\t\t// Now let the listeners know we are about to start\n\t\t\talertDocumentViewsOnMongoCommandStart(cmd);\n\t\t\talertListenersOnMongoCommandStart(cmd);\n\t\t\t\n\t\t\t// Execute the command\n\t\t\tlong startTime\t= System.currentTimeMillis();\n\t\t\ttry{\n\t\t\t\tcmd.execute();\n\t\t\t}catch(Throwable t){\n\t\t\t\tt.printStackTrace();\n\t\t\t}finally{\n\t\t\t\tcmd.setExecTime( System.currentTimeMillis() - startTime );\n\t\t\t\tcmd.hasRun();\n\t\t\t}\n\n\t\t\tif ( cmd.getCollection() != null )\n\t\t\t\tactiveCollection = cmd.getCollection();\n\t\t\t\n\n\t\t\t// Now let the listeners know we have finished\n\t\t\talertDocumentViewsOnMongoCommandFinished(cmd);\n\t\t\talertListenersOnMongoCommandFinished(cmd);\n\t\t}\n\t}\n\n\tpublic void setActiveServerDB(String name, String db) {\n\t\tactiveServer = name;\n\t\tactiveDB = db;\n\t}\n\n\tpublic String getActiveCollection() {\n\t\treturn activeCollection;\n\t}\n\t\n\t\n\tprivate void alertListenersOnMongoCommandStart( MongoCommand cmd ){\n\t\tIterator<MongoCommandListener>\tit\t= mongoListeners.iterator();\n\t\twhile ( it.hasNext() ){\n\t\t\ttry{\n\t\t\t\tit.next().onMongoCommandStart(cmd);\n\t\t\t}catch(Exception e){\n\t\t\t\tEventWorkBenchManager.getInst().onEvent( Event.EXCEPTION, e);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprivate void alertListenersOnMongoCommandFinished( MongoCommand cmd ){\n\t\tIterator<MongoCommandListener>\tit\t= mongoListeners.iterator();\n\t\twhile ( it.hasNext() ){\n\t\t\ttry{\n\t\t\t\tit.next().onMongoCommandFinished(cmd);\n\t\t\t}catch(Exception e){\n\t\t\t\tEventWorkBenchManager.getInst().onEvent( Event.EXCEPTION, e);\n\t\t\t}\n\t\t}\n\t}\n\t\n\t\n\tprivate void alertDocumentViewsOnMongoCommandStart( MongoCommand cmd ){}\n\t\n\tprivate void alertDocumentViewsOnMongoCommandFinished( MongoCommand cmd ){\n\t\tif ( !cmd.hasQueryData() )\n\t\t\treturn;\n\t\t\n\t\tfindDocumentView(cmd);\n\t}\n\t\n\tprivate void findDocumentView(final MongoCommand cmd){\n\t\tIterator<MDocumentView>\tit\t= documentViewListeners.iterator();\n\t\t\n\t\tfinal String id\t= ( cmd.getDB() != null ? cmd.getDB() : \"DB\" ) + \"-\" + ( cmd.getCollection() != null ? cmd.getCollection() : \"Output\" );\n\t\t\n\t\twhile ( it.hasNext() ){\n\t\t\tMDocumentView view = it.next();\n\t\t\t\n\t\t\tif ( view.getViewTitle().equals(id) ){\n\t\t\t\tfinal MDocumentView finalView = view;\n\t\t\t\tActivator.getDefault().getShell().getDisplay().asyncExec(new Runnable() {\n\t\t\t\t\tpublic void run() {\n\t\t\t\t\t\tActivator.getDefault().showView(\"org.aw20.mongoworkbench.eclipse.view.MDocumentView\", id );\n\t\t\t\t\t\t((MDocumentView)finalView).onMongoCommandFinished(cmd);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\t\n\t\t\n\t\t/* Need to create a new one */\n\t\tActivator.getDefault().getShell().getDisplay().asyncExec(new Runnable() {\n\t\t\tpublic void run() {\n\t\t\t\tObject view = Activator.getDefault().showView(\"org.aw20.mongoworkbench.eclipse.view.MDocumentView\", id );\n\t\t\t\tif ( view != null && view instanceof MDocumentView )\n\t\t\t\t\t((MDocumentView)view).onMongoCommandFinished(cmd);\n\t\t\t}\n\t\t});\n\t\t\n\t}\n}",
"public abstract class MongoCommand extends Object {\n\n\tpublic static String KEY_NAME = \"_name\";\n\n\tpublic static String KEY_COUNT = \"_count\";\n\n\tprotected String sName = null, sDb = null, sColl = null, rteMessage = \"\", cmd = null;\n\n\tprotected Exception lastException = null;\n\n\tprotected boolean hasRun = false;\n\n\tprivate long execTime = -1;\n\n\t/**\n\t * Sets the connection details to which this command pertains to\n\t * \n\t * @param mongoName\n\t * @param database\n\t * @param collection\n\t */\n\tpublic MongoCommand setConnection(String mongoName, String database, String collection) {\n\t\tthis.sName = mongoName;\n\t\tthis.sDb = database;\n\t\tthis.sColl = collection;\n\t\treturn this;\n\t}\n\n\tpublic MongoCommand setConnection(String mongoName, String database) {\n\t\tthis.sName = mongoName;\n\t\tthis.sDb = database;\n\t\treturn this;\n\t}\n\n\tpublic MongoCommand setConnection(String mongoName) {\n\t\tthis.sName = mongoName;\n\t\treturn this;\n\t}\n\n\tpublic MongoCommand setConnection(MongoCommand mcmd) {\n\t\tthis.sName = mcmd.sName;\n\t\tthis.sDb = mcmd.sDb;\n\t\tthis.sColl = mcmd.sColl;\n\t\treturn this;\n\t}\n\n\tpublic boolean isSuccess() {\n\t\treturn lastException == null;\n\t}\n\t\n\tpublic boolean hasQueryData(){\n\t\treturn false;\n\t}\n\n\tpublic boolean hasRun() {\n\t\treturn hasRun;\n\t}\n\n\tpublic void markAsRun() {\n\t\thasRun = true;\n\t}\n\n\tpublic Exception getException() {\n\t\treturn lastException;\n\t}\n\n\tpublic void setException(Exception e) {\n\t\tlastException = e;\n\t}\n\n\tpublic String getExceptionMessage() {\n\t\tif (lastException == null)\n\t\t\treturn \"\";\n\n\t\tif (lastException instanceof MongoException) {\n\t\t\tString e = lastException.getMessage();\n\t\t\tif (e.startsWith(\"command failed [$eval]: {\") && e.endsWith(\"}\")) {\n\t\t\t\ttry {\n\t\t\t\t\tMap m = (Map) JSON.parse(e.substring(e.indexOf(\"{\")));\n\t\t\t\t\treturn (String) m.get(\"errmsg\");\n\t\t\t\t} catch (Exception ee) {\n\t\t\t\t\treturn lastException.getMessage();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn lastException.getMessage();\n\t}\n\n\tpublic long getExecTime() {\n\t\treturn execTime;\n\t}\n\n\tprotected void setMessage(String string) {\n\t\trteMessage = string;\n\t}\n\n\tpublic String getMessage() {\n\t\treturn rteMessage;\n\t}\n\n\tpublic String getName() {\n\t\treturn sName;\n\t}\n\n\tpublic String getDB() {\n\t\treturn sDb;\n\t}\n\n\tpublic String getCollection() {\n\t\treturn sColl;\n\t}\n\n\t/**\n\t * Override this function to provide the body of the command\n\t */\n\tpublic abstract void execute() throws Exception;\n\n\tpublic String getCommandString() {\n\t\treturn this.cmd;\n\t}\n\n\tpublic void setExecTime(long l) {\n\t\texecTime = l;\n\t}\n\n\tpublic void setCommandStr(String cmd) {\n\t\tthis.cmd = cmd;\n\t}\n\n\tpublic void parseCommandStr() throws Exception {}\n\n\tpublic String getMatchIgnoreCase(String patternStr, String target) {\n\t\tPattern pattern = Pattern.compile(patternStr, Pattern.CASE_INSENSITIVE | Pattern.DOTALL);\n\t\tMatcher matcher = pattern.matcher(target);\n\t\tif (matcher.find()) {\n\t\t\tif (matcher.groupCount() > 0) {\n\t\t\t\treturn matcher.group(1);\n\t\t\t} else {\n\t\t\t\treturn target.substring(matcher.start(), matcher.end());\n\t\t\t}\n\t\t} else {\n\t\t\treturn \"\";\n\t\t}\n\t}\n\t\n\t\n\tpublic BasicDBObject parse() throws Exception{\n\t\tMongoClient mdb = MongoFactory.getInst().getMongo( sName );\n\t\t\n\t\tif ( mdb == null )\n\t\t\tthrow new Exception(\"no server selected\");\n\t\t\n\t\tif ( sDb == null )\n\t\t\tthrow new Exception(\"no database selected\");\n\t\t\n\t\tMongoFactory.getInst().setActiveDB(sDb);\n\t\t\n\t\tDB db\t= mdb.getDB(sDb);\n\t\treturn parseMongoCommandString(db, cmd);\n\t}\n\t\n\t\n\tprotected BasicDBObject parseMongoCommandString(DB db, String cmd) throws Exception {\n\t\t\n\t\tString newCmd = cmd.replaceFirst(\"db.\" + sColl, \"a\");\n\t\tString jsStr = StreamUtil.readToString( this.getClass().getResourceAsStream(\"parseCommand.txt\") ); \n\t\tjsStr = StringUtil.tokenReplace(jsStr, new String[]{\"//_QUERY_\"}, new String[]{newCmd} );\n\n\t\tBasicDBObject cmdMap = (BasicDBObject)db.eval(jsStr, (Object[])null);\n\t\t\n\t\t/*\n\t\t * Using JavaScript Engine\n\t\tContext cx = Context.enter();\n\t\tcx.setLanguageVersion(Context.VERSION_1_7);\n\t\tScriptable scope = cx.initStandardObjects();\n\t\tObject returnObj = cx.evaluateString(scope, jsStr, \"CustomJS\", 1, null);\n\t\t\n\t\tMap cmdMap = (Map) jsConvert2cfData( (IdScriptableObject)returnObj );\n\t\t*/\n\t\t\n\t\t// Remove the helper methods\n\t\tcmdMap.remove(\"find\");\n\t\tcmdMap.remove(\"findOne\");\n\t\tcmdMap.remove(\"group\");\n\t\tcmdMap.remove(\"aggregate\");\n\t\tcmdMap.remove(\"save\");\n\t\tcmdMap.remove(\"mapReduce\");\n\t\tcmdMap.remove(\"update\");\n\t\tcmdMap.remove(\"remove\");\n\t\tcmdMap.remove(\"limit\");\n\t\tcmdMap.remove(\"skip\");\n\t\tcmdMap.remove(\"sort\");\n\t\t\n\t\treturn new BasicDBObject( cmdMap );\n\t}\n\n\t\n\tpublic static Object jsConvert2cfData(IdScriptableObject obj) throws Exception {\n\n\t\tif (obj instanceof NativeObject) {\n\t\t\tMap struct = new HashMap();\n\n\t\t\tNativeObject nobj = (NativeObject) obj;\n\t\t\tObject[] elements = nobj.getAllIds();\n\n\t\t\tObject cfdata;\n\t\t\t\n\t\t\tfor (int x = 0; x < elements.length; x++) {\n\t\t\t\tObject jsObj = nobj.get(elements[x]);\n\n\t\t\t\tif (jsObj == null)\n\t\t\t\t\tcfdata = null;\n\t\t\t\telse if (jsObj instanceof NativeObject || jsObj instanceof NativeArray)\n\t\t\t\t\tcfdata = jsConvert2cfData((IdScriptableObject) jsObj);\n\t\t\t\telse\n\t\t\t\t\tcfdata = jsObj;\n\n\t\t\t\tstruct.put((String) elements[x], cfdata);\n\t\t\t}\n\n\t\t\treturn struct;\n\t\t} else if (obj instanceof NativeArray) {\n\t\t\tList array = new ArrayList();\n\n\t\t\tNativeArray nobj = (NativeArray) obj;\n\t\t\tObject cfdata;\n\t\t\tint len = (int) nobj.getLength();\n\n\t\t\tfor (int x = 0; x < len; x++) {\n\t\t\t\tObject jsObj = nobj.get(x);\n\n\t\t\t\tif (jsObj == null)\n\t\t\t\t\tcfdata = null;\n\t\t\t\telse if (jsObj instanceof NativeObject || jsObj instanceof NativeArray)\n\t\t\t\t\tcfdata = jsConvert2cfData((IdScriptableObject) jsObj);\n\t\t\t\telse\n\t\t\t\t\tcfdata = jsObj;\n\t\t\t\t\n\t\t\t\tarray.add(cfdata);\n\t\t\t}\n\n\t\t\treturn array;\n\t\t} else {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t\n\tprotected BasicDBObject\tfixNumbers( BasicDBObject dbo ){\n\t\tIterator<String> it\t= dbo.keySet().iterator();\n\t\twhile (it.hasNext()){\n\t\t\tString field\t= it.next();\n\t\t\tObject o\t= dbo.get(field);\n\t\t\tif ( o instanceof Double ){\n\t\t\t\tdbo.put(field, NumberUtil.fixDouble( (Double)o) );\n\t\t\t}else if ( o instanceof BasicDBObject ){\n\t\t\t\tdbo.put(field, fixNumbers((BasicDBObject)o) );\n\t\t\t}else if ( o instanceof BasicDBList ){\n\t\t\t\tdbo.put(field, fixNumbers((BasicDBList)o) );\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn dbo;\n\t}\n\t\n\t\n\tprotected BasicDBList\tfixNumbers( BasicDBList dbo ){\n\t\tfor ( int x=0; x < dbo.size(); x++ ){\n\t\t\tObject o =\tdbo.get(x);\n\t\t\t\n\t\t\tif ( o instanceof Double ){\n\t\t\t\tdbo.set(x, NumberUtil.fixDouble( (Double)o) );\n\t\t\t}else if ( o instanceof BasicDBObject ){\n\t\t\t\tdbo.set(x, fixNumbers((BasicDBObject)o) );\n\t\t\t}else if ( o instanceof BasicDBList ){\n\t\t\t\tdbo.set(x, fixNumbers((BasicDBList)o) );\n\t\t\t}\n\t\t}\n\n\t\treturn dbo;\n\t}\n}",
"public class SystemJavaScriptReadCommand extends MongoCommand {\n\n\tprivate String jsName = null, jsCode = null;\n\t\n\tpublic SystemJavaScriptReadCommand(String jsName) {\n\t\tthis.jsName = jsName;\n\t}\n\n\t@Override\n\tpublic void execute() throws Exception {\n\n\t\tMongoClient mdb = MongoFactory.getInst().getMongo( sName );\n\t\t\n\t\tif ( mdb == null )\n\t\t\tthrow new Exception(\"no server selected\");\n\t\t\n\t\tif ( sDb == null )\n\t\t\tthrow new Exception(\"no database selected\");\n\t\t\n\t\tMongoFactory.getInst().setActiveDB(sDb);\n\t\tDB db\t= mdb.getDB(sDb);\n\n\t\tDBCollection coll\t= db.getCollection(\"system.js\");\n\t\tDBObject dbo = coll.findOne( new BasicDBObject(\"_id\", jsName) );\n\t\t\n\t\tif ( dbo.containsField(\"value\") ){\n\t\t\tjsCode\t= ((Code)dbo.get(\"value\")).getCode();\n\t\t}\n\t\t\n\t\tsetMessage(\"System JavaScript loaded=\" + jsName);\n\t}\n\n\tpublic String getCode(){\n\t\treturn jsCode;\n\t}\n\t\n\tpublic String getJSName(){\n\t\treturn jsName;\n\t}\n\t\n\tpublic String getCommandString() {\n\t\treturn \"aw20.systemjs.read(\\\"\" + jsName + \"\\\")\";\n\t}\n}",
"public class SystemJavaScriptValidateCommand extends MongoCommand {\n\n\tprivate String jsName = null, jsCode = null;\n\t\n\tpublic SystemJavaScriptValidateCommand(String jsName, String jsCode) {\n\t\tthis.jsName = jsName;\n\t\tthis.jsCode\t= jsCode;\n\t}\n\n\t@Override\n\tpublic void execute() throws Exception {\n\n\t\tMongoClient mdb = MongoFactory.getInst().getMongo( sName );\n\t\t\n\t\tif ( mdb == null )\n\t\t\tthrow new Exception(\"no server selected\");\n\t\t\n\t\tif ( sDb == null )\n\t\t\tthrow new Exception(\"no database selected\");\n\t\t\n\t\tMongoFactory.getInst().setActiveDB(sDb);\n\t\tDB db\t= mdb.getDB(sDb);\n\n\t\ttry{\n\t\t\tdb.eval( jsCode, (Object[])null );\n\t\t}catch(Exception e){\n\t\t\tif ( e.getMessage().indexOf(\"SyntaxError\") != -1 )\n\t\t\t\tthrow e;\n\t\t}\n\n\t\tsetMessage(\"Valid JavaScript=\" + jsName);\n\t}\n\n\tpublic String getCommandString() {\n\t\treturn \"aw20.systemjs.validate(\\\"\" + jsName + \"\\\")\";\n\t}\n}",
"public class SystemJavaScriptWriteCommand extends MongoCommand {\n\n\tprivate String jsName = null, jsCode = null;\n\t\n\tpublic SystemJavaScriptWriteCommand(String jsName, String jsCode) {\n\t\tthis.jsName = jsName;\n\t\tthis.jsCode\t= jsCode;\n\t}\n\n\t@Override\n\tpublic void execute() throws Exception {\n\n\t\tMongoClient mdb = MongoFactory.getInst().getMongo( sName );\n\t\t\n\t\tif ( mdb == null )\n\t\t\tthrow new Exception(\"no server selected\");\n\t\t\n\t\tif ( sDb == null )\n\t\t\tthrow new Exception(\"no database selected\");\n\t\t\n\t\tMongoFactory.getInst().setActiveDB(sDb);\n\t\tDB db\t= mdb.getDB(sDb);\n\n\t\tDBCollection coll\t= db.getCollection(\"system.js\");\n\t\t\n\t\tBasicDBObject dbo = new BasicDBObject(\"_id\", jsName).append(\"value\", new Code(jsCode) );\n\t\tcoll.save(dbo, WriteConcern.JOURNAL_SAFE);\n\t\t\n\t\tsetMessage(\"System JavaScript Written=\" + jsName);\n\t}\n\t\n\tpublic String getCommandString() {\n\t\treturn \"aw20.systemjs.write(\\\"\" + jsName + \"\\\")\";\n\t}\n}",
"public class MSwtUtil extends Object {\n\n\tpublic static Text createText( Composite comp ){\n\t\tText txt = new Text(comp, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.CANCEL | SWT.MULTI);\n\t\ttxt.setFont(SWTResourceManager.getFont(\"Courier New\", 9, SWT.NORMAL));\n\t\ttxt.setTabs(2);\n\t\treturn txt;\n\t}\n\t\n\tpublic static void addListenerToMenuItems(Menu menu, Listener listener) {\n\t\tMenuItem[] itemArray = menu.getItems();\n\t\tfor (int i = 0; i < itemArray.length; ++i) {\n\t\t\titemArray[i].addListener(SWT.Selection, listener);\n\t\t}\n\t}\n\n\tpublic static void copyToClipboard(String s) {\n\t\tDisplay display = Display.findDisplay(Thread.currentThread());\n\t\tClipboard clipboard = new Clipboard(display);\n\t\tTextTransfer textTransfer = TextTransfer.getInstance();\n\t\tclipboard.setContents(new Object[] { s }, new Transfer[] { textTransfer });\n\t\tclipboard.dispose();\n\t}\n\n\tpublic static Image getImage(Device device, String imageFileName) {\n\t\tInputStream in = null;\n\t\ttry {\n\t\t\tin = StreamUtil.getResourceStream(\"org/aw20/mongoworkbench/eclipse/resources/\" + imageFileName);\n\t\t\tImageData imageData = new ImageData(in);\n\t\t\treturn new Image(device, imageData);\n\t\t} catch (Exception e) {\n\t\t\treturn null;\n\t\t} finally {\n\t\t\tStreamUtil.closeStream(in);\n\t\t}\n\t}\n\t\n}"
] | import java.io.IOException;
import org.aw20.mongoworkbench.EventWorkBenchManager;
import org.aw20.mongoworkbench.MongoCommandListener;
import org.aw20.mongoworkbench.MongoFactory;
import org.aw20.mongoworkbench.command.MongoCommand;
import org.aw20.mongoworkbench.command.SystemJavaScriptReadCommand;
import org.aw20.mongoworkbench.command.SystemJavaScriptValidateCommand;
import org.aw20.mongoworkbench.command.SystemJavaScriptWriteCommand;
import org.aw20.util.MSwtUtil;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text; | /*
* MongoWorkBench is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* Free Software Foundation,version 3.
*
* MongoWorkBench 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
* If not, see http://www.gnu.org/licenses/
*
* Additional permission under GNU GPL version 3 section 7
*
* If you modify this Program, or any covered work, by linking or combining
* it with any of the JARS listed in the README.txt (or a modified version of
* (that library), containing parts covered by the terms of that JAR, the
* licensors of this Program grant you additional permission to convey the
* resulting work.
*
* https://github.com/aw20/MongoWorkBench
*
* April 2013
*/
package org.aw20.mongoworkbench.eclipse.view;
public class MSystemJavaScript extends MAbstractView implements MongoCommandListener {
private Text textBox;
private String HELPURL = "http://docs.mongodb.org/manual/tutorial/store-javascript-function-on-server/";
private Button btnValidate, btnSave; | private SystemJavaScriptReadCommand readCommand; | 4 |
Samistine/BloodMoon | src/main/java/uk/co/jacekk/bukkit/bloodmoon/feature/world/ExtendedNightListener.java | [
"public final class BloodMoon extends BasePlugin {\n\n public static boolean DEBUG = false;\n\n private ArrayList<String> activeWorlds;\n private HashMap<String, PluginConfig> worldConfig;\n protected ArrayList<String> forceWorlds;\n\n @Override\n public void onEnable() {\n super.onEnable(true);\n\n activeWorlds = new ArrayList<>();\n forceWorlds = new ArrayList<>();\n worldConfig = new HashMap<>();\n\n try {\n BloodMoonEntityType.registerEntities();\n } catch (EntityRegistrationException e) {\n e.printStackTrace();//\n }\n\n for (World world : getServer().getWorlds()) {\n createConfig(world);\n }\n\n getCommandManager().registerCommandExecutor(new BloodMoonExecuter(this));\n getServer().getPluginManager().registerEvents(new WorldInitListener(this), this);\n getServer().getPluginManager().registerEvents(new SpawnReasonListener(this), this);\n getServer().getScheduler().scheduleSyncRepeatingTask(this, new TimeMonitorTask(this), 100L, 100L);\n\n for (Feature feature : Feature.values()) {\n try {\n Class<? extends Listener> listener = feature.getListenerClass();\n\n if (listener != null) {\n getServer().getPluginManager().registerEvents(listener.getConstructor(BloodMoon.class).newInstance(this), this);\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n }\n\n @Override\n public void onDisable() {\n for (World world : getServer().getWorlds()) {\n if (isActive(world)) {\n deactivate(world);\n }\n }\n }\n\n /**\n * Starts a bloodmoon in a specific world\n *\n * @param world The world\n */\n public void activate(World world) {\n Validate.notNull(world);\n\n if (isActive(world)) {\n return;\n }\n\n BloodMoonStartEvent event = new BloodMoonStartEvent(world);\n\n getServer().getPluginManager().callEvent(event);\n\n if (!event.isCancelled()) {\n activeWorlds.add(world.getName());\n }\n }\n\n /**\n * Starts a bloodmoon the next time night is reached in a specific world\n *\n * @param world The world\n */\n public void forceNextNight(World world) {\n Validate.notNull(world);\n forceWorlds.add(world.getName());\n }\n\n /**\n * Stops an existing bloodmoon in a world\n *\n * @param world The world\n */\n public void deactivate(World world) {\n Validate.notNull(world);\n if (isActive(world)) {\n\n BloodMoonEndEvent event = new BloodMoonEndEvent(world);\n\n getServer().getPluginManager().callEvent(event);\n\n if (!event.isCancelled()) {\n activeWorlds.remove(world.getName());\n }\n }\n }\n\n /**\n * Checks if a bloodmoon is currently active in a world\n *\n * @param world The world\n * @return true if a bloodmoon is active false if not\n */\n public boolean isActive(World world) {\n Validate.notNull(world);\n return activeWorlds.contains(world.getName());\n }\n\n /**\n * Checks if the bloodmoon is enabled for a world\n *\n * @param world The world\n * @return true if the bloodmoon is enabled false if not\n */\n public boolean isEnabled(World world) {\n Validate.notNull(world);\n if (!worldConfig.containsKey(world.getName())) {\n return false;\n }\n\n return worldConfig.get(world.getName()).getBoolean(Config.ENABLED);\n }\n\n /**\n * Checks if a specific feature is enabled in a world.\n *\n * @param world The world\n * @param feature The {@link Feature} to check\n * @return true if the feature is enabled false if not\n */\n public boolean isFeatureEnabled(World world, Feature feature) {\n Validate.notNull(world);\n if (!worldConfig.containsKey(world.getName())) {\n return false;\n }\n\n return worldConfig.get(world.getName()).getBoolean(feature.getEnabledConfigKey());\n }\n\n /**\n * Sets up the config for a world. This should only be used by other plugins\n * if a world is being loaded that would not call a WorldInitEvent.\n *\n * @param world The {@link World} being loaded\n * @return The config object that was created for the world or null if it\n * already existed.\n */\n public PluginConfig createConfig(World world) {\n Validate.notNull(world);\n String worldName = world.getName();\n\n if (!worldConfig.containsKey(worldName)) {\n PluginConfig newConfig = new PluginConfig(new File(getBaseDirPath() + File.separator + worldName + \".yml\"), Config.class, getLogger());\n\n worldConfig.put(worldName, newConfig);\n\n if (newConfig.getBoolean(Config.ALWAYS_ON)) {\n activate(world);\n }\n\n return newConfig;\n }\n\n return null;\n }\n\n /**\n * Gets the config for a world\n *\n * @param world The world\n * @return the {@link PluginConfig} for this world\n */\n public PluginConfig getConfig(World world) {\n Validate.notNull(world);\n if (!worldConfig.containsKey(world.getName())) {\n return createConfig(world);\n }\n\n return worldConfig.get(world.getName());\n }\n\n /**\n * Reloads all config files.\n */\n public void reloadWorldConfig() {\n for (PluginConfig config : worldConfig.values()) {\n config.reload();\n }\n }\n\n /**\n * Gets the reason that an entity spawned. Note that these reasons are reset\n * when the server restarts.\n *\n * @param entity The entity\n * @return The {@link SpawnReason}\n */\n public SpawnReason getSpawnReason(Entity entity) {\n for (MetadataValue value : entity.getMetadata(\"spawn-reason\")) {\n if (value.getOwningPlugin() instanceof BloodMoon) {\n return (SpawnReason) value.value();\n }\n }\n\n return SpawnReason.DEFAULT;\n }\n\n}",
"public class Config {\n\n public static final PluginConfigKey ENABLED = new PluginConfigKey(\"enabled\", false);\n public static final PluginConfigKey ALWAYS_ON = new PluginConfigKey(\"always-on\", false);\n public static final PluginConfigKey CHANCE = new PluginConfigKey(\"chance\", 14);\n\n public static final PluginConfigKey FEATURE_CHAT_MESSAGE_ENABLED = new PluginConfigKey(\"features.chat-message.enabled\", true);\n public static final PluginConfigKey FEATURE_CHAT_MESSAGE_START_MESSAGE = new PluginConfigKey(\"features.chat-message.start-message\", \"&cThe bloodmoon is rising !\");\n public static final PluginConfigKey FEATURE_CHAT_MESSAGE_END_MESSAGE = new PluginConfigKey(\"features.chat-message.end-message\", \"&cThe bloodmoon is over !\");\n\n public static final PluginConfigKey FEATURE_SERVER_COMMANDS_ENABLED = new PluginConfigKey(\"features.server-commands.enabled\", false);\n public static final PluginConfigKey FEATURE_SERVER_COMMANDS_START_COMMANDS = new PluginConfigKey(\"features.server-commands.commands.start\", Arrays.asList(\"toggledownfall\", \"time set 0\", \"op Notch\"));\n public static final PluginConfigKey FEATURE_SERVER_COMMANDS_END_COMMANDS = new PluginConfigKey(\"features.server-commands.commands.end\", Arrays.asList(\"toggledownfall\", \"time set 12000\", \"deop Notch\"));\n\n public static final PluginConfigKey FEATURE_DISABLED_COMMANDS_ENABLED = new PluginConfigKey(\"features.disabled-commands.enabled\", true);\n public static final PluginConfigKey FEATURE_DISABLED_COMMANDS_COMMANDS = new PluginConfigKey(\"features.disabled-commands.commands\", Arrays.asList(\"spawn\", \"home\"));\n\n public static final PluginConfigKey FEATURE_PLAY_SOUND_ENABLED = new PluginConfigKey(\"features.play-sound.enabled\", true);\n public static final PluginConfigKey FEATURE_PLAY_SOUND_SOUND = new PluginConfigKey(\"features.play-sound.sound\", \"WITHER_SPAWN\");\n public static final PluginConfigKey FEATURE_PLAY_SOUND_PITCH = new PluginConfigKey(\"features.play-sound.pitch\", 1.0d);\n public static final PluginConfigKey FEATURE_PLAY_SOUND_VOLUME = new PluginConfigKey(\"features.play-sound.volume\", 1.0d);\n\n public static final PluginConfigKey FEATURE_ARROW_RATE_ENABLED = new PluginConfigKey(\"features.arrow-rate.enabled\", true);\n public static final PluginConfigKey FEATURE_ARROW_RATE_MULTIPLIER = new PluginConfigKey(\"features.arrow-rate.multiplier\", 2);\n\n public static final PluginConfigKey FEATURE_FIRE_ARROWS_ENABLED = new PluginConfigKey(\"features.fire-arrows.enabled\", true);\n public static final PluginConfigKey FEATURE_FIRE_ARROWS_CHANCE = new PluginConfigKey(\"features.fire-arrows.chance\", 100);\n public static final PluginConfigKey FEATURE_FIRE_ARROWS_IGNITE_TARGET = new PluginConfigKey(\"features.fire-arrows.ignite-target\", true);\n\n public static final PluginConfigKey FEATURE_ZOMBIE_WEAPON_ENABLED = new PluginConfigKey(\"features.zombie-weapon.enabled\", true);\n public static final PluginConfigKey FEATURE_ZOMBIE_WEAPON_CHANCE = new PluginConfigKey(\"features.zombie-weapon.chance\", 60);\n public static final PluginConfigKey FEATURE_ZOMBIE_WEAPON_DROP_CHANCE = new PluginConfigKey(\"features.zombie-weapon.drop-chance\", 25);\n public static final PluginConfigKey FEATURE_ZOMBIE_WEAPON_IGNORE_SPAWNERS = new PluginConfigKey(\"features.zombie-weapon.ignore-spawners\", true);\n public static final PluginConfigKey FEATURE_ZOMBIE_WEAPON_WEAPONS = new PluginConfigKey(\"features.zombie-weapon.weapons\", Arrays.asList(\"DIAMOND_SWORD\", \"GOLD_SWORD\", \"IRON_SWORD\"));\n\n public static final PluginConfigKey FEATURE_ZOMBIE_ARMOR_ENABLED = new PluginConfigKey(\"features.zombie-armor.enabled\", true);\n public static final PluginConfigKey FEATURE_ZOMBIE_ARMOR_CHANCE = new PluginConfigKey(\"features.zombie-armor.chance\", 60);\n public static final PluginConfigKey FEATURE_ZOMBIE_ARMOR_DROP_CHANCE = new PluginConfigKey(\"features.zombie-armor.drop-chance\", 7);\n public static final PluginConfigKey FEATURE_ZOMBIE_ARMOR_IGNORE_SPAWNERS = new PluginConfigKey(\"features.zombie-armor.ignore-spawners\", true);\n public static final PluginConfigKey FEATURE_ZOMBIE_ARMOR_ARMOR = new PluginConfigKey(\"features.zombie-armor.armor\", Arrays.asList(\"DIAMOND\", \"GOLD\", \"IRON\"));\n\n public static final PluginConfigKey FEATURE_TARGET_DISTANCE_ENABLED = new PluginConfigKey(\"features.target-distance.enabled\", true);\n public static final PluginConfigKey FEATURE_TARGET_DISTANCE_MULTIPLIER = new PluginConfigKey(\"features.target-distance.multiplier\", 2.0d);\n public static final PluginConfigKey FEATURE_TARGET_DISTANCE_MOBS = new PluginConfigKey(\"features.target-distance.mobs\", Arrays.asList(\"ZOMBIE\", \"SKELETON\", \"SPIDER\", \"CREEPER\"));\n\n public static final PluginConfigKey FEATURE_MOVEMENT_SPEED_ENABLED = new PluginConfigKey(\"features.movement-speed.enabled\", true);\n public static final PluginConfigKey FEATURE_MOVEMENT_SPEED_MULTIPLIER = new PluginConfigKey(\"features.movement-speed.multiplier\", 1.20d);\n public static final PluginConfigKey FEATURE_MOVEMENT_SPEED_FAST_CHANCE = new PluginConfigKey(\"features.movement-speed.fast-chance\", 15);\n public static final PluginConfigKey FEATURE_MOVEMENT_SPEED_FAST_MULTIPLIER = new PluginConfigKey(\"features.movement-speed.fast-multiplier\", 1.3d);\n public static final PluginConfigKey FEATURE_MOVEMENT_SPEED_MOBS = new PluginConfigKey(\"features.movement-speed.mobs\", Arrays.asList(\"ZOMBIE\", \"SKELETON\", \"CREEPER\"));\n\n public static final PluginConfigKey FEATURE_BREAK_BLOCKS_ENABLED = new PluginConfigKey(\"features.break-blocks.enabled\", true);\n public static final PluginConfigKey FEATURE_BREAK_BLOCKS_DROP_ITEMS = new PluginConfigKey(\"features.break-blocks.drop-items\", true);\n public static final PluginConfigKey FEATURE_BREAK_BLOCKS_REALISTIC_DROP = new PluginConfigKey(\"features.break-blocks.realistic-drop\", true);\n public static final PluginConfigKey FEATURE_BREAK_BLOCKS_MOBS = new PluginConfigKey(\"features.break-blocks.mobs\", Arrays.asList(\"ZOMBIE\", \"SKELETON\", \"SPIDER\", \"CREEPER\", \"ENDERMAN\"));\n public static final PluginConfigKey FEATURE_BREAK_BLOCKS_BLOCKS = new PluginConfigKey(\"features.break-blocks.blocks\", Arrays.asList(\"WOOD\", \"LOG\", \"GLASS\"));\n\n public static final PluginConfigKey FEATURE_MAX_HEALTH_ENABLED = new PluginConfigKey(\"features.max-health.enabled\", true);\n public static final PluginConfigKey FEATURE_MAX_HEALTH_MULTIPLIER = new PluginConfigKey(\"features.max-health.multiplier\", 2.0d);\n public static final PluginConfigKey FEATURE_MAX_HEALTH_MOBS = new PluginConfigKey(\"features.max-health.mobs\", Arrays.asList(\"ZOMBIE\", \"SKELETON\", \"SPIDER\", \"CREEPER\", \"ENDERMAN\"));\n\n public static final PluginConfigKey FEATURE_MORE_SPAWNING_ENABLED = new PluginConfigKey(\"features.more-spawning.enabled\", true);\n public static final PluginConfigKey FEATURE_MORE_SPAWNING_MULTIPLIER = new PluginConfigKey(\"features.more-spawning.multiplier\", 2);\n public static final PluginConfigKey FEATURE_MORE_SPAWNING_MOBS = new PluginConfigKey(\"features.more-spawning.mobs\", Arrays.asList(\"ZOMBIE\", \"SKELETON\", \"SPIDER\", \"CREEPER\", \"ENDERMAN\"));\n\n public static final PluginConfigKey FEATURE_MORE_EXP_ENABLED = new PluginConfigKey(\"features.more-exp.enabled\", true);\n public static final PluginConfigKey FEATURE_MORE_EXP_IGNORE_SPAWNERS = new PluginConfigKey(\"features.more-exp.ignore-spawners\", false);\n public static final PluginConfigKey FEATURE_MORE_EXP_MULTIPLIER = new PluginConfigKey(\"features.more-exp.multiplier\", 2);\n\n public static final PluginConfigKey FEATURE_MORE_DROPS_ENABLED = new PluginConfigKey(\"features.more-drops.enabled\", true);\n public static final PluginConfigKey FEATURE_MORE_DROPS_IGNORE_SPAWNERS = new PluginConfigKey(\"features.more-drops.ignore-spawners\", false);\n public static final PluginConfigKey FEATURE_MORE_DROPS_MULTIPLIER = new PluginConfigKey(\"features.more-drops.multiplier\", 2);\n\n public static final PluginConfigKey FEATURE_SWORD_DAMAGE_ENABLED = new PluginConfigKey(\"features.sword-damage.enabled\", true);\n public static final PluginConfigKey FEATURE_SWORD_DAMAGE_MOBS = new PluginConfigKey(\"features.sword-damage.mobs\", Arrays.asList(\"ZOMBIE\", \"SKELETON\", \"SPIDER\", \"CREEPER\", \"ENDERMAN\"));\n public static final PluginConfigKey FEATURE_SWORD_DAMAGE_CHANCE = new PluginConfigKey(\"features.sword-damage.chance\", 10);\n\n public static final PluginConfigKey FEATURE_SUPER_CREEPERS_ENABLED = new PluginConfigKey(\"features.super-creepers.enabled\", true);\n public static final PluginConfigKey FEATURE_SUPER_CREEPERS_POWER = new PluginConfigKey(\"features.super-creepers.power\", 4.0D);\n public static final PluginConfigKey FEATURE_SUPER_CREEPERS_FIRE = new PluginConfigKey(\"features.super-creepers.fire\", true);\n public static final PluginConfigKey FEATURE_SUPER_CREEPERS_LIGHTNING = new PluginConfigKey(\"features.super-creepers.lightning\", true);\n\n public static final PluginConfigKey FEATURE_SPAWN_ON_KILL_ENABLED = new PluginConfigKey(\"features.spawn-on-kill.enabled\", true);\n public static final PluginConfigKey FEATURE_SPAWN_ON_KILL_MOBS = new PluginConfigKey(\"features.spawn-on-kill.mobs\", Arrays.asList(\"ZOMBIE\", \"SKELETON\", \"SPIDER\", \"CREEPER\", \"ENDERMAN\"));\n public static final PluginConfigKey FEATURE_SPAWN_ON_KILL_CHANCE = new PluginConfigKey(\"features.spawn-on-kill.chance\", 10);\n public static final PluginConfigKey FEATURE_SPAWN_ON_KILL_SPAWN = new PluginConfigKey(\"features.spawn-on-kill.spawn\", Arrays.asList(\"ZOMBIE\", \"SKELETON\", \"SPIDER\", \"CREEPER\", \"ENDERMAN\"));\n\n public static final PluginConfigKey FEATURE_SPAWN_ON_SLEEP_ENABLED = new PluginConfigKey(\"features.spawn-on-sleep.enabled\", true);\n public static final PluginConfigKey FEATURE_SPAWN_ON_SLEEP_SPAWN = new PluginConfigKey(\"features.spawn-on-sleep.spawn\", Arrays.asList(\"ZOMBIE\"));\n\n public static final PluginConfigKey FEATURE_SPAWN_CONTROL_ENABLED = new PluginConfigKey(\"features.spawn-control.enabled\", true);\n public static final PluginConfigKey FEATURE_SPAWN_CONTROL_SPAWN = new PluginConfigKey(\"features.spawn-control.spawn\", Arrays.asList(\"ZOMBIE\", \"SKELETON\", \"SPIDER\", \"CREEPER\", \"ENDERMAN\", \"PIG_ZOMBIE\", \"BLAZE\", \"MAGMA_CUBE\"));\n\n public static final PluginConfigKey FEATURE_LOCK_IN_WORLD_ENABLED = new PluginConfigKey(\"features.lock-in-world.enabled\", false);\n\n public static final PluginConfigKey FEATURE_TEXTURE_PACK_ENABLED = new PluginConfigKey(\"features.texture-pack.enabled\", false);\n public static final PluginConfigKey FEATURE_TEXTURE_PACK_NORMAL = new PluginConfigKey(\"features.texture-pack.normal\", \"http://bukkit.jacekk.co.uk/bloodmoon_tps/normal.zip\");\n public static final PluginConfigKey FEATURE_TEXTURE_PACK_BLOODMOON = new PluginConfigKey(\"features.texture-pack.bloodmoon\", \"http://bukkit.jacekk.co.uk/bloodmoon_tps/bloodmoon.zip\");\n\n public static final PluginConfigKey FEATURE_EXTENDED_NIGHT_ENABLED = new PluginConfigKey(\"features.extended-night.enabled\", true);\n public static final PluginConfigKey FEATURE_EXTENDED_NIGHT_MIN_KILLS = new PluginConfigKey(\"features.extended-night.min-kills\", 16);\n\n public static final PluginConfigKey FEATURE_WEATHER_ENABLED = new PluginConfigKey(\"features.weather.enabled\", true);\n public static final PluginConfigKey FEATURE_WEATHER_THUNDER = new PluginConfigKey(\"features.weather.thunder\", true);\n public static final PluginConfigKey FEATURE_WEATHER_RAIN = new PluginConfigKey(\"features.weather.rain\", true);\n public static final PluginConfigKey FEATURE_WEATHER_CHANCE = new PluginConfigKey(\"features.weather.chance\", 50);\n\n public static final PluginConfigKey FEATURE_DAYLIGHT_PROOF_MOBS_ENABLED = new PluginConfigKey(\"features.daylight-proof-mobs.enabled\", true);\n\n public static final PluginConfigKey FEATURE_NETHER_SKY_ENABLED = new PluginConfigKey(\"features.nether-sky.enabled\", false);\n\n public static final PluginConfigKey FEATURE_DUNGEONS_ENABLED = new PluginConfigKey(\"features.dungeons.enabled\", true);\n public static final PluginConfigKey FEATURE_DUNGEONS_PROTECTED = new PluginConfigKey(\"features.dungeons.protected\", true);\n public static final PluginConfigKey FEATURE_DUNGEONS_BIOMES = new PluginConfigKey(\"features.dungeons.biomes\", Arrays.asList(Biome.PLAINS.name(), Biome.ICE_PLAINS.name(), Biome.DESERT.name(), Biome.SWAMPLAND.name()));\n public static final PluginConfigKey FEATURE_DUNGEONS_CHANCE = new PluginConfigKey(\"features.dungeons.chance\", 10);\n public static final PluginConfigKey FEATURE_DUNGEONS_MIN_LAYERS = new PluginConfigKey(\"features.dungeons.min-layers\", 3);\n public static final PluginConfigKey FEATURE_DUNGEONS_MAX_LAYERS = new PluginConfigKey(\"features.dungeons.max-layers\", 5);\n public static final PluginConfigKey FEATURE_DUNGEONS_SPAWNER_TYPES = new PluginConfigKey(\"features.dungeons.spawner-types\", Arrays.asList(EntityType.ZOMBIE.name(), EntityType.SKELETON.name()));\n public static final PluginConfigKey FEATURE_DUNGEONS_SPAWNER_DELAY = new PluginConfigKey(\"features.dungeons.spawner-delay\", 100);\n public static final PluginConfigKey FEATURE_DUNGEONS_SPAWNER_COUNT = new PluginConfigKey(\"features.dungeons.spawner-count\", 6);\n public static final PluginConfigKey FEATURE_DUNGEONS_SPAWNER_MAX_MOBS = new PluginConfigKey(\"features.dungeons.spawner-max-mobs\", 8);\n public static final PluginConfigKey FEATURE_DUNGEONS_CHEST_ITEMS = new PluginConfigKey(\"features.dungeons.chest-items\", Arrays.asList(Material.BREAD.name(), Material.APPLE.name(), Material.PORK.name(), Material.SADDLE.name(), Material.BUCKET.name(), Material.STRING.name(), Material.REDSTONE.name(), Material.SULPHUR.name(), Material.COCOA.name()));\n public static final PluginConfigKey FEATURE_DUNGEONS_MIN_STACK_SIZE = new PluginConfigKey(\"features.dungeons.min-stack-size\", 1);\n public static final PluginConfigKey FEATURE_DUNGEONS_MAX_STACK_SIZE = new PluginConfigKey(\"features.dungeons.max-stack-size\", 8);\n public static final PluginConfigKey FEATURE_DUNGEONS_ITEMS_PER_CHEST = new PluginConfigKey(\"features.dungeons.items-per-chest\", 12);\n\n public static final PluginConfigKey FEATURE_GIANTS_ENABLED = new PluginConfigKey(\"features.giants.enabled\", true);\n public static final PluginConfigKey FEATURE_GIANTS_BREAK_BLOCKS = new PluginConfigKey(\"features.giants.break-blocks\", Arrays.asList(Material.GRASS.name(), Material.LEAVES.name(), Material.WOOD.name(), Material.GLASS.name(), Material.CROPS.name(), Material.SOIL.name(), Material.LOG.name(), Material.WOOD_STEP.name(), Material.WOOD_STAIRS.name()));\n\n}",
"public enum Feature {\n\t\n\t// Mob features\n\tSUPER_CREEPERS(SuperCreepersListener.class, Config.FEATURE_SUPER_CREEPERS_ENABLED),\n\tZOMBIE_ARMOR(ZombieArmorListener.class, Config.FEATURE_ZOMBIE_ARMOR_ENABLED),\n\tZOMBIE_WEAPON(ZombieWeaponListener.class, Config.FEATURE_ZOMBIE_WEAPON_ENABLED),\n\tDAYLIGHT_PROOF_MOBS(DaylightProofMobsListener.class, Config.FEATURE_DAYLIGHT_PROOF_MOBS_ENABLED),\n\tFIRE_ARROWS(FireArrowsListener.class, Config.FEATURE_FIRE_ARROWS_ENABLED),\n\tMAX_HEALTH(MaxHealthListener.class, Config.FEATURE_MAX_HEALTH_ENABLED),\n\tMORE_DROPS(MoreDropsListener.class, Config.FEATURE_MORE_DROPS_ENABLED),\n\tMORE_EXP(MoreExpListener.class, Config.FEATURE_MORE_EXP_ENABLED),\n\tBREAK_BLOCKS(null, Config.FEATURE_BREAK_BLOCKS_ENABLED), // handled in BloodMoonEntity*\n\tTARGET_DISTANCE(TargetDistanceListener.class, Config.FEATURE_TARGET_DISTANCE_ENABLED),\n\tARROW_RATE(null, Config.FEATURE_ARROW_RATE_ENABLED), // handled in BloodMoonPathfinderGoalArrowAttack\n\tMOVEMENT_SPEED(MovementSpeedListener.class, Config.FEATURE_MOVEMENT_SPEED_ENABLED),\n\t\n\t// World features\n\tWEATHER(WeatherListener.class, Config.FEATURE_WEATHER_ENABLED),\n\tNETHER_SKY(NetherSkyListener.class, Config.FEATURE_NETHER_SKY_ENABLED),\n\tLOCK_IN_WORLD(LockInWorldListener.class, Config.FEATURE_LOCK_IN_WORLD_ENABLED),\n\tEXTENDED_NIGHT(ExtendedNightListener.class, Config.FEATURE_EXTENDED_NIGHT_ENABLED),\n\tDUNGEONS(DungeonListener.class, Config.FEATURE_DUNGEONS_ENABLED),\n\t\n\t// Spawning features\n\tSPAWN_ON_KILL(SpawnOnKillListener.class, Config.FEATURE_SPAWN_ON_KILL_ENABLED),\n\tSPAWN_ON_SLEEP(SpawnOnSleepListener.class, Config.FEATURE_SPAWN_ON_SLEEP_ENABLED),\n\tMORE_SPAWNING(MoreSpawningListener.class, Config.FEATURE_MORE_SPAWNING_ENABLED),\n\tSPAWN_CONTROL(MoreMobsListener.class, Config.FEATURE_SPAWN_CONTROL_ENABLED), // partially handled in ChunkProviderServer\n\tGIANTS(GiantsListener.class, Config.FEATURE_GIANTS_ENABLED),\n\t\n\t// Server features\n\tSERVER_COMMANDS(ServerCommandsListener.class, Config.FEATURE_SERVER_COMMANDS_ENABLED),\n\tDISABLED_COMMANDS(DisabledCommandsListener.class, Config.FEATURE_DISABLED_COMMANDS_ENABLED),\n\t\n\t// Player features\n\tSWORD_DAMAGE(SwordDamageListener.class, Config.FEATURE_SWORD_DAMAGE_ENABLED),\n\t\n\t// Client Features.\n\tPLAY_SOUND(PlaySoundListener.class, Config.FEATURE_PLAY_SOUND_ENABLED),\n\tCHAT_MESSAGE(ChatMessageListener.class, Config.FEATURE_CHAT_MESSAGE_ENABLED),\n\tTEXTURE_PACK(TexturePackListener.class, Config.FEATURE_TEXTURE_PACK_ENABLED);\n\t\n\t//private Class<? extends BaseListener<BloodMoon>> listenerClass;\n private final Class<? extends Listener> listenerClass;\n\tprivate final PluginConfigKey enabledConfigKey;\n\t\n\t/*private Feature(Class<? extends BaseListener<BloodMoon>> listenerClass, PluginConfigKey enabledConfigKey){\n\t\tthis.listenerClass = listenerClass;\n\t\tthis.enabledConfigKey = enabledConfigKey;\n\t}\n\t\n\tpublic Class<? extends BaseListener<BloodMoon>> getListenerClass(){\n\t\treturn this.listenerClass;\n\t}*/\n \n private Feature(Class<? extends Listener> listenerClass, PluginConfigKey enabledConfigKey){\n\t\tthis.listenerClass = listenerClass;\n\t\tthis.enabledConfigKey = enabledConfigKey;\n\t}\n\t\n\tpublic Class<? extends Listener> getListenerClass(){\n\t\treturn this.listenerClass;\n\t}\n\t\n\tpublic PluginConfigKey getEnabledConfigKey(){\n\t\treturn this.enabledConfigKey;\n\t}\n\t\n}",
"public class BloodMoonEndEvent extends Event implements Cancellable {\n\n private static final HandlerList handlers = new HandlerList();\n\n private boolean isCancelled = false;\n\n private final World world;\n\n public BloodMoonEndEvent(World world) {\n this.world = world;\n }\n\n @Override\n public HandlerList getHandlers() {\n return handlers;\n }\n\n public static HandlerList getHandlerList() {\n return handlers;\n }\n\n public World getWorld() {\n return this.world;\n }\n\n @Override\n public boolean isCancelled() {\n return this.isCancelled;\n }\n\n @Override\n public void setCancelled(boolean cancelled) {\n this.isCancelled = cancelled;\n }\n}",
"public class BloodMoonStartEvent extends Event implements Cancellable {\n\n private static final HandlerList handlers = new HandlerList();\n private boolean isCancelled = false;\n private final World world;\n\n public BloodMoonStartEvent(World world) {\n this.world = world;\n }\n\n @Override\n public HandlerList getHandlers() {\n return handlers;\n }\n\n public static HandlerList getHandlerList() {\n return handlers;\n }\n\n public World getWorld() {\n return this.world;\n }\n\n @Override\n public boolean isCancelled() {\n return this.isCancelled;\n }\n\n @Override\n public void setCancelled(boolean cancelled) {\n this.isCancelled = cancelled;\n }\n\n}"
] | import java.util.ArrayList;
import java.util.HashMap;
import org.bukkit.World;
import org.bukkit.entity.EntityType;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.entity.EntityDeathEvent;
import uk.co.jacekk.bukkit.baseplugin.config.PluginConfig;
import uk.co.jacekk.bukkit.baseplugin.event.BaseListener;
import uk.co.jacekk.bukkit.bloodmoon.BloodMoon;
import uk.co.jacekk.bukkit.bloodmoon.Config;
import uk.co.jacekk.bukkit.bloodmoon.Feature;
import uk.co.jacekk.bukkit.bloodmoon.event.BloodMoonEndEvent;
import uk.co.jacekk.bukkit.bloodmoon.event.BloodMoonStartEvent; | package uk.co.jacekk.bukkit.bloodmoon.feature.world;
public class ExtendedNightListener extends BaseListener<BloodMoon> {
private final HashMap<String, Integer> killCount = new HashMap<>();
private final ArrayList<EntityType> hostileTypes = new ArrayList<EntityType>() {
{
add(EntityType.SKELETON);
add(EntityType.SPIDER);
add(EntityType.CAVE_SPIDER);
add(EntityType.ZOMBIE);
add(EntityType.PIG_ZOMBIE);
add(EntityType.CREEPER);
add(EntityType.ENDERMAN);
add(EntityType.BLAZE);
add(EntityType.GHAST);
add(EntityType.MAGMA_CUBE);
add(EntityType.WITCH);
add(EntityType.ENDERMITE);
add(EntityType.ENDER_DRAGON);
add(EntityType.GUARDIAN);
add(EntityType.SILVERFISH);
}
};
public ExtendedNightListener(BloodMoon plugin) {
super(plugin);
}
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true) | public void onStart(BloodMoonStartEvent event) { | 4 |
b0noI/AIF2 | src/main/java/io/aif/language/sentence/splitters/AbstractSentenceSplitter.java | [
"@FunctionalInterface\npublic interface ISplitter<T1, T2> extends Function<T1, List<T2>> {\n\n public List<T2> split(final T1 target);\n\n @Override\n public default List<T2> apply(final T1 t1) {\n return split(t1);\n }\n}",
"public interface ISettings {\n\n @Deprecated\n public ISettings SETTINGS = Guice.createInjector(new SettingsModule()).getInstance(ISettings.class);\n\n public String getVersion();\n\n public int recommendedMinimumTokensInputCount();\n\n public boolean useIsAlphabeticMethod();\n\n public double thresholdPForSeparatorCharacterInSecondFilter();\n\n public int minimalValuableTokenSizeForSentenceSplit();\n\n public int minimumCharacterObservationsCountForMakingCharacterValuableDuringSentenceSplitting();\n\n public double thresholdPFirstFilterForSeparatorCharacter();\n\n public double splitterCharactersGrouperSearchStep();\n\n public double splitterCharactersGrouperInitSearchPValue();\n\n public double wordSetDictComparatorThreshold();\n\n public double recursiveSubstringComparatorWeight();\n\n public double simpleTokenComparatorWeight();\n\n public double characterDensityComparatorWeight();\n\n public String predefinedSeparators();\n}",
"public class SettingsModule extends AbstractModule {\n\n @Override\n protected void configure() {\n bind(ISettings.class).toProvider(new PropertyBasedSettings.Provider());\n }\n\n}",
"public interface ISeparatorExtractor extends IExtractor<List<String>, List<Character>> {\n\n public static enum Type {\n PREDEFINED(new PredefinedSeparatorExtractor()),\n PROBABILITY(new StatSeparatorExtractor()),\n NON_ALPHABETIC_CHARACTERS_EXTRACTOR(new NonAlphabeticCharactersExtractor());\n\n private final ISeparatorExtractor instance;\n\n private Type(final ISeparatorExtractor instance) {\n this.instance = instance;\n }\n\n public static ISeparatorExtractor getDefault() {\n final ISettings settings = Guice.createInjector(new SettingsModule()).getInstance(ISettings.class);\n return settings.useIsAlphabeticMethod() ?\n Type.NON_ALPHABETIC_CHARACTERS_EXTRACTOR.getInstance() :\n Type.PROBABILITY.getInstance();\n }\n\n public ISeparatorExtractor getInstance() {\n return instance;\n }\n\n }\n\n\n}",
"public interface ISeparatorsGrouper {\n\n public List<Set<Character>> group(final List<String> tokens, final List<Character> splitters);\n\n public enum Type {\n\n PREDEFINED(new PredefinedGrouper()),\n PROBABILITY(new StatGrouper());\n\n private final ISeparatorsGrouper instance;\n\n Type(ISeparatorsGrouper instance) {\n this.instance = instance;\n }\n\n public ISeparatorsGrouper getInstance() {\n return instance;\n }\n\n }\n\n}"
] | import com.google.common.annotations.VisibleForTesting;
import com.google.inject.Guice;
import org.apache.log4j.Logger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import io.aif.language.common.ISplitter;
import io.aif.language.common.settings.ISettings;
import io.aif.language.common.settings.SettingsModule;
import io.aif.language.sentence.separators.classificators.ISeparatorGroupsClassifier;
import io.aif.language.sentence.separators.extractors.ISeparatorExtractor;
import io.aif.language.sentence.separators.groupers.ISeparatorsGrouper; | package io.aif.language.sentence.splitters;
public abstract class AbstractSentenceSplitter implements ISplitter<List<String>, List<String>> {
private static final Logger logger = Logger.getLogger(AbstractSentenceSplitter.class);
private final ISeparatorExtractor sentenceSeparatorExtractor;
private final ISeparatorsGrouper sentenceSeparatorsGrouper;
private final ISeparatorGroupsClassifier sentenceSeparatorGroupsClassificatory;
protected AbstractSentenceSplitter(final ISeparatorExtractor sentenceSeparatorExtractor,
final ISeparatorsGrouper sentenceSeparatorsGrouper,
final ISeparatorGroupsClassifier
sentenceSeparatorGroupsClassificatory) {
this.sentenceSeparatorExtractor = sentenceSeparatorExtractor;
this.sentenceSeparatorsGrouper = sentenceSeparatorsGrouper;
this.sentenceSeparatorGroupsClassificatory = sentenceSeparatorGroupsClassificatory;
}
@VisibleForTesting
static List<String> prepareSentences(final List<String> sentence,
final List<Character> separators) {
final List<String> preparedTokens = new ArrayList<>();
for (String token : sentence) {
preparedTokens.addAll(prepareToken(token, separators));
}
return preparedTokens;
}
@VisibleForTesting
static List<String> prepareToken(final String token, final List<Character> separators) {
final List<String> tokens = new ArrayList<>(3);
final int lastPosition = lastNonSeparatorPosition(token, separators);
final int firstPosition = firstNonSeparatorPosition(token, separators);
if (firstPosition != 0) {
tokens.add(token.substring(0, firstPosition));
}
tokens.add(token.substring(firstPosition, lastPosition));
if (lastPosition != token.length()) {
tokens.add(token.substring(lastPosition, token.length()));
}
return tokens;
}
@VisibleForTesting
static int firstNonSeparatorPosition(final String token, final List<Character> separarors) {
if (!separarors.contains(token.charAt(0))) {
return 0;
}
int i = 0;
while (i < token.length() && separarors.contains(token.charAt(i))) {
i++;
}
if (i == token.length()) {
return 0;
}
return i;
}
@VisibleForTesting
static int lastNonSeparatorPosition(final String token, final List<Character> separators) {
if (!separators.contains(token.charAt(token.length() - 1))) {
return token.length();
}
int i = token.length() - 1;
while (i > 0 && separators.contains(token.charAt(i))) {
i--;
}
i++;
if (i == 0) {
return token.length();
}
return i;
}
public List<List<String>> split(final List<String> tokens) { | final ISettings settings = Guice.createInjector(new SettingsModule()).getInstance(ISettings.class); | 2 |
free-iot/freeiot-android | app/src/main/java/com/pandocloud/freeiot/ui/helper/ProductInfoHelper.java | [
"public class ProductApi extends AbsOpenApi {\n\t\n\t/**\n\t * get product info\n\t */\n\tprivate static final String PRODUCT_INFO = \"/v1/product/info\";\n\t\n\n\t/**\n\t * get product information by product key\n\t * \n\t * <p>Method: GET</p>\n\t * @param context\n\t * @param productKey\n\t * @param responseHandler\n\t */\n\tpublic static void getProductInfo(Context context, String productKey, AsyncHttpResponseHandler responseHandler) {\n\t\tList<Header> headerList = new ArrayList<Header>();\n\t\theaderList.add(new BasicHeader(ApiKey.HeadKey.PRODUCT_KEY, productKey));\n\t\tget(context, getApiServerUrl() + PRODUCT_INFO, headerList, null, responseHandler);\n\t}\n\n}",
"public class AppConstants {\r\n\t\r\n\tpublic static final String VENDOR_KEY = \"570f93557db3532727b54336e47f1a3500b3c0e564\";\r\n\t\r\n //FreeIOT\r\n public static final String PRODUCT_KEY = \"f07fd3f2782ff4964b74d51e89ad0aabf0192ec066\";\r\n}\r",
"public class ProductInfoPrefs {\n\n\tprivate static final String USER_PREFS_NAME = \"pando_product_infos_prefs\";\n\n\tprivate SharedPreferences mPrefs;\n\n\tprivate static ProductInfoPrefs sInstances;\n\n\tprivate void init(Context context) {\n\t\tif (mPrefs == null) {\n\t\t\tmPrefs = context.getApplicationContext().getSharedPreferences(\n\t\t\t\t\tUSER_PREFS_NAME, Context.MODE_PRIVATE);\n\t\t}\n\t}\n\n\tprivate ProductInfoPrefs(Context context) {\n\t\tinit(context);\n\t}\n\n\tpublic static ProductInfoPrefs getInstances(Context context) {\n\t\tif (sInstances == null) {\n\t\t\tsynchronized (ProductInfoPrefs.class) {\n\t\t\t\tif (sInstances == null) {\n\t\t\t\t\tsInstances = new ProductInfoPrefs(context);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn sInstances;\n\t}\n\n\tpublic void clear() {\n\t\tmPrefs.edit().clear().commit();\n\t}\n\n\tpublic void putString(String key, String value) {\n\t\tmPrefs.edit().putString(key, value).commit();\n\t}\n\n\tpublic String getString(String key, String defValue) {\n\t\treturn mPrefs.getString(key, defValue);\n\t}\n\n\tpublic void putInt(String key, int value) {\n\t\tmPrefs.edit().putInt(key, value).commit();\n\t}\n\n\tpublic int getInt(String key, int defValue) {\n\t\treturn mPrefs.getInt(key, defValue);\n\t}\n\n\tpublic void putBoolean(String key, boolean value) {\n\t\tmPrefs.edit().putBoolean(key, value).commit();\n\t}\n\n\tpublic boolean getBoolean(String key, boolean defValue) {\n\t\treturn mPrefs.getBoolean(key, defValue);\n\t}\n\n\tprivate SharedPreferences getSharedPreferences() {\n\t\treturn mPrefs;\n\t}\n\n\tpublic static class Builder {\n\n\t\tprivate SharedPreferences.Editor mEditor;\n\n\t\tpublic Builder(Context context) {\n\t\t\tif (mEditor == null) {\n\t\t\t\tmEditor = ProductInfoPrefs.getInstances(context)\n\t\t\t\t\t\t.getSharedPreferences().edit();\n\t\t\t}\n\t\t}\n\n\t\tpublic Builder saveString(String key, String value) {\n\t\t\tmEditor.putString(key, value);\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic Builder saveLong(String key, long value) {\n\t\t\tmEditor.putLong(key, value);\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic Builder saveInt(String key, int value) {\n\t\t\tmEditor.putInt(key, value);\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic void commit() {\n\t\t\tmEditor.commit();\n\t\t}\n\t}\n\n}",
"public class ProductInfo {\n\n\tpublic String name;\n\t\n\tpublic String code;\n\t\n\tpublic String description;\n\t\n\tpublic String icon;\n\t\n\tpublic String app;\n\t\n}",
"public class ProductInfoResponse extends BaseResponse {\n\n\tpublic ProductInfo data;\n\t\n}",
"public class GsonUtils {\r\n\t\r\n\tprivate static GsonUtils sInstance;\r\n\t\r\n\tpublic static GsonUtils getInstance() {\r\n\t\tif (sInstance == null) {\r\n\t\t\tsInstance = new GsonUtils();\r\n\t\t}\r\n\t\treturn sInstance;\r\n\t}\r\n\t\r\n\tprivate Gson mGson;\r\n\t\r\n\tprivate GsonUtils() {\r\n//\t\tmGson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation()\r\n//\t\t\t\t.enableComplexMapKeySerialization()\r\n//\t\t\t\t.create();\r\n\t\tmGson = new Gson();\r\n\t}\r\n\t\r\n\tpublic String toJson(Object object) {\r\n\t\treturn mGson.toJson(object);\r\n\t}\r\n\t\r\n\tpublic Gson getGson() {\r\n\t\treturn mGson;\r\n\t}\r\n}\r",
"public class LogUtils {\r\n\tpublic static final int VERBOSE = 0x0001;\r\n\tpublic static final int DEBUG = 0x0002;\r\n\tpublic static final int INFO = 0x0004;\r\n\tpublic static final int WARN = 0x0008;\r\n\tpublic static final int ERROR = 0x0010;\r\n\t\r\n\tpublic static final int LEVEL_RELEASE = 0x0000;\r\n\r\n\tpublic static final int LEVEL_TEST = VERBOSE | DEBUG | INFO | WARN | ERROR;\r\n\t\r\n\tprivate static int LEVEL = LEVEL_TEST;//上线时改成LEVEL_RELEASE\r\n\t\r\n\tprivate static final String TAG = \"PANDO_LOG\";\r\n\t\r\n\tpublic static final void setLevel(int level) {\r\n\t\tLEVEL = level;\r\n\t}\r\n\t\r\n\tprivate static boolean check(int level) {\r\n\t\tif ((LEVEL & level) > 0) {\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\treturn false;\r\n\t}\r\n\t\r\n\tpublic static void v(String text) {\r\n\t\tif (check(VERBOSE)) android.util.Log.v(TAG, text);\r\n\t}\r\n\t\r\n\tpublic static void v(String tag, String text) {\r\n\t\tif (check(VERBOSE)) android.util.Log.v(tag, text);\r\n\t}\r\n\t\r\n\tpublic static void d(String text) {\r\n\t\tif (check(DEBUG)) android.util.Log.d(TAG, text);\r\n\t}\r\n\r\n\tpublic static void d(String text, Throwable tr) {\r\n\t\tif (check(DEBUG)) android.util.Log.d(TAG, text, tr);\r\n\t}\r\n\t\r\n\tpublic static void d(String tag, String text) {\r\n\t\tif (check(DEBUG)) android.util.Log.d(tag, text);\r\n\t}\r\n\r\n\tpublic static void d(String tag, String text, Throwable tr) {\r\n\t\tif (check(DEBUG)) android.util.Log.d(tag, text, tr);\r\n\t}\r\n\r\n\tpublic static void i(String text) {\r\n\t\tif (check(INFO)) android.util.Log.i(TAG, text);\r\n\t}\r\n\r\n\tpublic static void i(String text, Throwable tr) {\r\n\t\tif (check(INFO)) android.util.Log.i(TAG, text, tr);\r\n\t}\r\n\r\n\tpublic static void i(String tag, String text) {\r\n\t\tif (check(INFO)) android.util.Log.i(tag, text);\r\n\t}\r\n\t\r\n\tpublic static void i(String tag, String text, Throwable tr) {\r\n\t\tif (check(INFO)) android.util.Log.i(tag, text, tr);\r\n\t}\r\n\t\r\n\tpublic static void w(String text) {\r\n\t\tif (check(WARN)) android.util.Log.w(TAG, text);\r\n\t}\r\n\t\r\n\tpublic static void w(String text, Throwable tr) {\r\n\t\tif (check(WARN)) android.util.Log.w(TAG, text, tr);\r\n\t}\r\n\t\r\n\tpublic static void w(String tag, String text) {\r\n\t\tif (check(WARN)) android.util.Log.w(tag, text);\r\n\t}\r\n\t\r\n\tpublic static void w(String tag, String text, Throwable tr) {\r\n\t\tif (check(WARN)) android.util.Log.w(tag, text, tr);\r\n\t}\r\n\t\r\n\tpublic static void e(String text) {\r\n\t\tif (check(ERROR)) android.util.Log.e(TAG, text);\r\n\t}\r\n\t\r\n\tpublic static void e(Throwable e) {\r\n\t\te(getStringFromThrowable(e));\r\n\t}\r\n\t\r\n\tpublic static void e(Throwable e, String message) {\r\n\t\te(message +\"\\n\" + getStringFromThrowable(e));\r\n\t}\r\n\t\r\n\tpublic static void e(String text, Throwable tr) {\r\n\t\tif (check(ERROR)) android.util.Log.e(TAG, text, tr);\r\n\t}\r\n\t\r\n\tpublic static void e(String tag, String text) {\r\n\t\tif (check(ERROR)) android.util.Log.e(tag, text);\r\n\t}\r\n\t\r\n\tpublic static void e(String tag, String text, Throwable tr) {\r\n\t\tif (check(ERROR)) android.util.Log.e(tag, text, tr);\r\n\t}\r\n\r\n public static String getStackTraceString(Throwable tr) {\r\n return android.util.Log.getStackTraceString(tr);\r\n }\r\n\r\n public static int println(int priority, String tag, String msg) {\r\n return android.util.Log.println(priority, tag, msg);\r\n }\r\n \r\n public static String getStringFromThrowable(Throwable e) {\r\n\t\tStringWriter sw = new StringWriter();\r\n\t PrintWriter pw = new PrintWriter(sw);\r\n\t e.printStackTrace(pw);\r\n\t return sw.toString();\r\n\t}\r\n \r\n public static void e(String tag, byte[] data) {\r\n \tif (data == null) {\r\n\t\t\treturn;\r\n\t\t}\r\n \tStringBuffer sBuffer = new StringBuffer();\r\n\t\tfor (int i = 0; i< data.length; i++) {\r\n\t\t\tsBuffer.append(Integer.toHexString(data[i])).append(\" \");\r\n\t\t}\r\n\t\tLogUtils.e(\"body length: \" + sBuffer.toString());\r\n }\r\n}\r"
] | import com.pandocloud.android.api.interfaces.RequestListener;
import com.pandocloud.freeiot.api.ProductApi;
import com.pandocloud.freeiot.ui.app.AppConstants;
import com.pandocloud.freeiot.ui.app.ProductInfoPrefs;
import com.pandocloud.freeiot.ui.bean.ProductInfo;
import com.pandocloud.freeiot.ui.bean.http.ProductInfoResponse;
import com.pandocloud.freeiot.utils.GsonUtils;
import org.apache.http.Header;
import android.content.Context;
import android.text.TextUtils;
import com.loopj.android.http.BaseJsonHttpResponseHandler;
import com.pandocloud.freeiot.utils.LogUtils; | package com.pandocloud.freeiot.ui.helper;
public class ProductInfoHelper {
private RequestListener listener;
public ProductInfoHelper(RequestListener listener) {
if (listener == null) {
throw new IllegalArgumentException("ReuqestListener not allow be null...");
}
this.listener = listener;
}
public void getProductInfo(final Context context) {
ProductApi.getProductInfo(context, AppConstants.PRODUCT_KEY, new BaseJsonHttpResponseHandler<ProductInfoResponse>() {
@Override
public void onFailure(int statusCode, Header[] headers, Throwable e,
String rawJsonResponse, ProductInfoResponse response) {
listener.onFail(new Exception(e));
}
@Override
public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse,
ProductInfoResponse response) {
if (response != null) {
ProductInfo productInfo = response.data;
if (productInfo != null && context != null) { | ProductInfoPrefs.Builder builder = new ProductInfoPrefs.Builder(context); | 2 |
steevp/UpdogFarmer | app/src/main/java/com/steevsapps/idledaddy/LoginActivity.java | [
"public class PrefsManager {\n private final static int CURRENT_VERSION = 2;\n\n private final static String USERNAME = \"username\";\n private final static String PASSWORD = \"password\";\n private final static String LOGIN_KEY = \"login_key\";\n private final static String SENTRY_HASH = \"sentry_hash\";\n private final static String SHARED_SECRET = \"shared_secret\";\n private final static String OFFLINE = \"offline\";\n private final static String STAY_AWAKE = \"stay_awake\";\n private final static String MINIMIZE_DATA = \"minimize_data\";\n private final static String PARENTAL_PIN = \"parental_pin\";\n private final static String BLACKLIST = \"blacklist\";\n private final static String LAST_SESSION = \"last_session\";\n private final static String HOURS_UNTIL_DROPS = \"hours_until_drops\";\n private final static String INCLUDE_FREE_GAMES = \"include_free_games\";\n private final static String USE_CUSTOM_LOGINID = \"use_custom_loginid\";\n private final static String PERSONA_NAME = \"persona_name\";\n private final static String AVATAR_HASH = \"avatar_hash\";\n private final static String API_KEY = \"api_key\";\n private final static String LANGUAGE = \"language\";\n private final static String VERSION = \"version\";\n private final static String SORT_VALUE = \"sort_value\";\n\n private static SharedPreferences prefs;\n\n private PrefsManager() {\n }\n\n public static void init(Context c) {\n if (prefs == null) {\n prefs = PreferenceManager.getDefaultSharedPreferences(c);\n }\n\n if (getVersion() != CURRENT_VERSION) {\n onUpgrade(getVersion());\n }\n }\n\n private static void onUpgrade(int oldVersion) {\n if (oldVersion < 2) {\n // Serialized names have changed\n writeLastSession(new ArrayList<>());\n }\n writeVersion(CURRENT_VERSION);\n }\n\n /**\n * Clear all preferences related to user\n */\n public static void clearUser() {\n prefs.edit()\n .putString(USERNAME, \"\")\n .putString(PASSWORD, \"\")\n .putString(LOGIN_KEY, \"\")\n .putString(SENTRY_HASH, \"\")\n .putString(BLACKLIST, \"\")\n .putString(LAST_SESSION, \"\")\n .putString(PARENTAL_PIN, \"\")\n .putString(PERSONA_NAME, \"\")\n .putString(AVATAR_HASH, \"\")\n .putString(API_KEY, \"\")\n .apply();\n }\n\n public static SharedPreferences getPrefs() {\n return prefs;\n }\n\n public static void writeUsername(String username) {\n writePref(USERNAME, username);\n }\n\n public static void writePassword(Context context, String password) {\n writePref(PASSWORD, CryptHelper.encryptString(context, password));\n }\n\n public static void writeLoginKey(String loginKey) {\n writePref(LOGIN_KEY, loginKey);\n }\n\n public static void writeSentryHash(String sentryHash) {\n writePref(SENTRY_HASH, sentryHash);\n }\n\n public static void writeSharedSecret(String sharedSecret) {\n writePref(SHARED_SECRET, sharedSecret);\n }\n\n public static void writeBlacklist(List<String> blacklist) {\n writePref(BLACKLIST, Utils.arrayToString(blacklist));\n }\n\n public static void writeLastSession(List<Game> games) {\n final String json = new Gson().toJson(games);\n writePref(LAST_SESSION, json);\n }\n\n public static void writePersonaName(String personaName) {\n writePref(PERSONA_NAME, personaName);\n }\n\n public static void writeAvatarHash(String avatarHash) {\n writePref(AVATAR_HASH, avatarHash);\n }\n\n public static void writeApiKey(String apiKey) {\n writePref(API_KEY, apiKey);\n }\n\n public static void writeLanguage(String language) {\n writePref(LANGUAGE, language);\n }\n\n public static void writeVersion(int version) {\n writePref(VERSION, version);\n }\n\n public static void writeSortValue(int sortValue) {\n writePref(SORT_VALUE, sortValue);\n }\n\n public static String getUsername() {\n return prefs.getString(USERNAME, \"\");\n }\n\n public static String getPassword(Context context) {\n return CryptHelper.decryptString(context, prefs.getString(PASSWORD, \"\"));\n }\n\n public static String getLoginKey() {\n return prefs.getString(LOGIN_KEY, \"\");\n }\n\n public static String getSentryHash() {\n return prefs.getString(SENTRY_HASH, \"\");\n }\n\n public static String getSharedSecret() {\n return prefs.getString(SHARED_SECRET, \"\");\n }\n\n public static boolean getOffline() {\n return prefs.getBoolean(OFFLINE, false);\n }\n\n public static boolean stayAwake() {\n return prefs.getBoolean(STAY_AWAKE, false);\n }\n\n public static boolean minimizeData() { return prefs.getBoolean(MINIMIZE_DATA, false); }\n\n public static String getParentalPin() {\n return prefs.getString(PARENTAL_PIN, \"\");\n }\n\n public static List<String> getBlacklist() {\n final String[] blacklist = prefs.getString(BLACKLIST, \"\").split(\",\");\n return new ArrayList<>(Arrays.asList(blacklist));\n }\n\n public static List<Game> getLastSession() {\n final String json = prefs.getString(LAST_SESSION, \"\");\n final Type type = new TypeToken<List<Game>>(){}.getType();\n final List<Game> games = new Gson().fromJson(json, type);\n if (games == null) {\n return new ArrayList<>();\n }\n return games;\n }\n\n public static String getPersonaName() {\n return prefs.getString(PERSONA_NAME, \"\");\n }\n\n public static String getAvatarHash() {\n return prefs.getString(AVATAR_HASH, \"\");\n }\n\n public static int getHoursUntilDrops() {\n return prefs.getInt(HOURS_UNTIL_DROPS, 3);\n }\n\n public static boolean includeFreeGames() {\n return prefs.getBoolean(INCLUDE_FREE_GAMES, false);\n }\n\n public static boolean useCustomLoginId() {\n return prefs.getBoolean(USE_CUSTOM_LOGINID, false);\n }\n\n public static String getApiKey() {\n return prefs.getString(API_KEY, \"\");\n }\n\n public static String getLanguage() {\n return prefs.getString(LANGUAGE, \"\");\n }\n\n public static int getVersion() {\n return prefs.getInt(VERSION, 1);\n }\n\n public static int getSortValue() {\n return prefs.getInt(SORT_VALUE, 0);\n }\n\n private static void writePref(String key, String value) {\n prefs.edit().putString(key, value).apply();\n }\n\n private static void writePref(String key, int value) {\n prefs.edit().putInt(key, value).apply();\n }\n}",
"public class SteamGuard {\n private final static String TAG = SteamGuard.class.getSimpleName();\n\n private final static byte[] steamGuardCodeTranslations = new byte[] {50, 51, 52, 53, 54, 55, 56, 57, 66, 67, 68, 70, 71, 72, 74, 75, 77, 78, 80, 81, 82, 84, 86, 87, 88, 89};\n\n private SteamGuard(){\n // private empty constructor\n }\n\n public static String generateSteamGuardCodeForTime(long time) {\n final String sharedSecret = PrefsManager.getSharedSecret();\n if (TextUtils.isEmpty(sharedSecret)) {\n Log.w(TAG, \"shared_secret is empty!\");\n return \"\";\n }\n\n final byte[] sharedSecretArray;\n try {\n sharedSecretArray = Base64.decode(sharedSecret, Base64.DEFAULT);\n } catch (IllegalArgumentException e) {\n Log.e(TAG, \"Invalid base64\", e);\n return \"\";\n }\n final byte[] timeArray = new byte[8];\n\n time /= 30L;\n\n for (int i=8; i>0; i--) {\n timeArray[i - 1] = (byte) time;\n time >>= 8;\n }\n\n final byte[] hashedData;\n final byte[] codeArray = new byte[5];\n try {\n hashedData = Utils.calculateRFC2104HMAC(timeArray,sharedSecretArray);\n } catch (NoSuchAlgorithmException|InvalidKeyException e) {\n Log.e(TAG, \"Failed to compute HMAC SHA1!\", e);\n return \"\";\n }\n\n try {\n final byte b = (byte) (hashedData[19] & 0xF);\n int codePoint = (hashedData[b] & 0x7F) << 24 | (hashedData[b + 1] & 0xFF) << 16 | (hashedData[b + 2] & 0xFF) << 8 | (hashedData[b + 3] & 0xFF);\n for (int i=0; i<5; i++) {\n codeArray[i] = steamGuardCodeTranslations[codePoint % steamGuardCodeTranslations.length];\n codePoint /= steamGuardCodeTranslations.length;\n }\n return new String(codeArray, Charset.forName(\"UTF-8\"));\n } catch (Exception e) {\n Log.e(TAG, \"Failed to generate SteamGuard code!\", e);\n return \"\";\n }\n }\n}",
"public class SteamService extends Service {\n private final static String TAG = SteamService.class.getSimpleName();\n private final static int NOTIF_ID = 6896; // Ongoing notification ID\n private final static String CHANNEL_ID = \"idle_channel\"; // Notification channel\n // Some Huawei phones reportedly kill apps when they hold a WakeLock for a long time.\n // This can be prevented by using a WakeLock tag from the PowerGenie whitelist.\n private final static String WAKELOCK_TAG = \"LocationManagerService\";\n private final static int CUSTOM_OBFUSCATION_MASK = 0xF00DBAAD;\n\n // Events\n public final static String LOGIN_EVENT = \"LOGIN_EVENT\"; // Emitted on login\n public final static String RESULT = \"RESULT\"; // Login result\n public final static String DISCONNECT_EVENT = \"DISCONNECT_EVENT\"; // Emitted on disconnect\n public final static String STOP_EVENT = \"STOP_EVENT\"; // Emitted when stop clicked\n public final static String FARM_EVENT = \"FARM_EVENT\"; // Emitted when farm() is called\n public final static String GAME_COUNT = \"GAME_COUNT\"; // Number of games left to farm\n public final static String CARD_COUNT = \"CARD_COUNT\"; // Number of card drops remaining\n public final static String PERSONA_EVENT = \"PERSONA_EVENT\"; // Emitted when we get PersonaStateCallback\n public final static String PERSONA_NAME = \"PERSONA_NAME\"; // Username\n public final static String AVATAR_HASH = \"AVATAR_HASH\"; // User avatar hash\n public final static String NOW_PLAYING_EVENT = \"NOW_PLAYING_EVENT\"; // Emitted when the game you're idling changes\n\n // Actions\n public final static String SKIP_INTENT = \"SKIP_INTENT\";\n public final static String STOP_INTENT = \"STOP_INTENT\";\n public final static String PAUSE_INTENT = \"PAUSE_INTENT\";\n public final static String RESUME_INTENT = \"RESUME_INTENT\";\n\n private SteamClient steamClient;\n private CallbackManager manager;\n private SteamUser steamUser;\n private SteamFriends steamFriends;\n private SteamApps steamApps;\n private SteamWebHandler webHandler = SteamWebHandler.getInstance();\n private PowerManager.WakeLock wakeLock;\n\n private int farmIndex = 0;\n private List<Game> gamesToFarm;\n private List<Game> currentGames = new ArrayList<>();\n private int gameCount = 0;\n private int cardCount = 0;\n private LogOnDetails logOnDetails = null;\n\n private volatile boolean running = false; // Service running\n private volatile boolean connected = false; // Connected to Steam\n private volatile boolean farming = false; // Currently farming\n private volatile boolean paused = false; // Game paused\n private volatile boolean waiting = false; // Waiting for user to stop playing\n private volatile boolean loginInProgress = true; // Currently logging in, so don't reconnect on disconnects\n\n private long steamId;\n private boolean loggedIn = false;\n private boolean isHuawei = false;\n\n private final ExecutorService executor = Executors.newCachedThreadPool();\n private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(8);\n private ScheduledFuture<?> farmHandle;\n private ScheduledFuture<?> waitHandle;\n\n private String keyToRedeem = null;\n private final LinkedList<Integer> pendingFreeLicenses = new LinkedList<>();\n\n private File sentryFolder;\n\n /**\n * Class for clients to access. Because we know this service always\n * runs in the same process as its clients, we don't need to deal with\n * IPC.\n */\n public class LocalBinder extends Binder {\n public SteamService getService() {\n return SteamService.this;\n }\n }\n\n // This is the object that receives interactions from clients.\n private final IBinder binder = new LocalBinder();\n\n private final BroadcastReceiver receiver = new BroadcastReceiver() {\n @Override\n public void onReceive(Context context, Intent intent) {\n switch (intent.getAction()) {\n case SKIP_INTENT:\n skipGame();\n break;\n case STOP_INTENT:\n stopGame();\n break;\n case PAUSE_INTENT:\n pauseGame();\n break;\n case RESUME_INTENT:\n resumeGame();\n break;\n }\n }\n };\n\n private final Runnable farmTask = new Runnable() {\n @Override\n public void run() {\n try {\n farm();\n } catch (Exception e) {\n Log.i(TAG, \"FarmTask failed\", e);\n }\n }\n };\n\n /**\n * Wait for user to NOT be in-game so we can resume idling\n */\n private final Runnable waitTask = new Runnable() {\n @Override\n public void run() {\n try {\n Log.i(TAG, \"Checking if we can resume idling...\");\n final Boolean notInGame = webHandler.checkIfNotInGame();\n if (notInGame == null) {\n Log.i(TAG, \"Invalid cookie data or no internet, reconnecting...\");\n steamClient.disconnect();\n } else if (notInGame) {\n Log.i(TAG, \"Resuming...\");\n waiting = false;\n steamClient.disconnect();\n waitHandle.cancel(false);\n }\n } catch (Exception e) {\n Log.i(TAG, \"WaitTask failed\", e);\n }\n }\n };\n\n public void startFarming() {\n if (!farming) {\n farming = true;\n paused = false;\n executor.execute(farmTask);\n }\n }\n\n public void stopFarming() {\n if (farming) {\n farming = false;\n gamesToFarm = null;\n farmIndex = 0;\n currentGames.clear();\n unscheduleFarmTask();\n }\n }\n\n /**\n * Resume farming/idling\n */\n private void resumeFarming() {\n if (paused || waiting) {\n return;\n }\n\n if (farming) {\n Log.i(TAG, \"Resume farming\");\n executor.execute(farmTask);\n } else if (currentGames.size() == 1) {\n Log.i(TAG, \"Resume playing\");\n new Handler(Looper.getMainLooper()).post(() -> idleSingle(currentGames.get(0)));\n } else if (currentGames.size() > 1) {\n Log.i(TAG, \"Resume playing (multiple)\");\n idleMultiple(currentGames);\n }\n }\n\n private void farm() {\n if (paused || waiting) {\n return;\n }\n Log.i(TAG, \"Checking remaining card drops\");\n for (int i=0;i<3;i++) {\n gamesToFarm = webHandler.getRemainingGames();\n if (gamesToFarm != null) {\n Log.i(TAG, \"gotem\");\n break;\n }\n if (i + 1 < 3) {\n Log.i(TAG, \"retrying...\");\n try {\n Thread.sleep(500);\n } catch (InterruptedException e) {\n e.printStackTrace();\n return;\n }\n }\n }\n\n if (gamesToFarm == null) {\n Log.i(TAG, \"Invalid cookie data or no internet, reconnecting\");\n //steamClient.disconnect();\n steamUser.requestWebAPIUserNonce();\n return;\n }\n\n // Count the games and cards\n gameCount = gamesToFarm.size();\n cardCount = 0;\n for (Game g : gamesToFarm) {\n cardCount += g.dropsRemaining;\n }\n\n // Send farm event\n final Intent event = new Intent(FARM_EVENT);\n event.putExtra(GAME_COUNT, gameCount);\n event.putExtra(CARD_COUNT, cardCount);\n LocalBroadcastManager.getInstance(SteamService.this)\n .sendBroadcast(event);\n\n if (gamesToFarm.isEmpty()) {\n Log.i(TAG, \"Finished idling\");\n stopPlaying();\n updateNotification(getString(R.string.idling_finished));\n stopFarming();\n return;\n }\n\n // Sort by hours played descending\n Collections.sort(gamesToFarm, Collections.reverseOrder());\n\n if (farmIndex >= gamesToFarm.size()) {\n farmIndex = 0;\n }\n final Game game = gamesToFarm.get(farmIndex);\n\n // TODO: Steam only updates play time every half hour, so maybe we should keep track of it ourselves\n if (game.hoursPlayed >= PrefsManager.getHoursUntilDrops() || gamesToFarm.size() == 1 || farmIndex > 0) {\n // Idle a single game\n new Handler(Looper.getMainLooper()).post(() -> idleSingle(game));\n unscheduleFarmTask();\n } else {\n // Idle multiple games (max 32) until one has reached 2 hrs\n idleMultiple(gamesToFarm);\n scheduleFarmTask();\n }\n }\n\n public void skipGame() {\n if (gamesToFarm == null || gamesToFarm.size() < 2) {\n return;\n }\n\n farmIndex++;\n if (farmIndex >= gamesToFarm.size()) {\n farmIndex = 0;\n }\n\n idleSingle(gamesToFarm.get(farmIndex));\n }\n\n public void stopGame() {\n paused = false;\n stopPlaying();\n stopFarming();\n updateNotification(getString(R.string.stopped));\n LocalBroadcastManager.getInstance(SteamService.this).sendBroadcast(new Intent(STOP_EVENT));\n }\n\n public void pauseGame() {\n paused = true;\n stopPlaying();\n showPausedNotification();\n // Tell the activity to update\n LocalBroadcastManager.getInstance(SteamService.this).sendBroadcast(new Intent(NOW_PLAYING_EVENT));\n }\n\n public void resumeGame() {\n if (farming) {\n Log.i(TAG, \"Resume farming\");\n paused = false;\n executor.execute(farmTask);\n } else if (currentGames.size() == 1) {\n Log.i(TAG, \"Resume playing\");\n idleSingle(currentGames.get(0));\n } else if (currentGames.size() > 1) {\n Log.i(TAG, \"Resume playing (multiple)\");\n idleMultiple(currentGames);\n }\n }\n\n private void scheduleFarmTask() {\n if (farmHandle == null || farmHandle.isCancelled()) {\n Log.i(TAG, \"Starting farmtask\");\n farmHandle = scheduler.scheduleAtFixedRate(farmTask, 10, 10, TimeUnit.MINUTES);\n }\n }\n\n private void unscheduleFarmTask() {\n if (farmHandle != null) {\n Log.i(TAG, \"Stopping farmtask\");\n farmHandle.cancel(true);\n }\n }\n\n @Nullable\n @Override\n public IBinder onBind(Intent intent) {\n return binder;\n }\n\n\n public static Intent createIntent(Context c) {\n return new Intent(c, SteamService.class);\n }\n\n @Override\n public void onCreate() {\n Log.i(TAG, \"Service created\");\n super.onCreate();\n\n sentryFolder = new File(getFilesDir(), \"sentry\");\n sentryFolder.mkdirs();\n\n final SteamConfiguration config = SteamConfiguration.create(b -> {\n b.withServerListProvider(new FileServerListProvider(new File(getFilesDir(), \"servers.bin\")));\n });\n\n steamClient = new SteamClient(config);\n steamClient.addHandler(new PurchaseResponse());\n steamUser = steamClient.getHandler(SteamUser.class);\n steamFriends = steamClient.getHandler(SteamFriends.class);\n steamApps = steamClient.getHandler(SteamApps.class);\n\n // Subscribe to callbacks\n manager = new CallbackManager(steamClient);\n manager.subscribe(ConnectedCallback.class, this::onConnected);\n manager.subscribe(DisconnectedCallback.class, this::onDisconnected);\n manager.subscribe(LoggedOffCallback.class, this::onLoggedOff);\n manager.subscribe(LoggedOnCallback.class, this::onLoggedOn);\n manager.subscribe(LoginKeyCallback.class, this::onLoginKey);\n manager.subscribe(UpdateMachineAuthCallback.class, this::onUpdateMachineAuth);\n manager.subscribe(PersonaStatesCallback.class, this::onPersonaStates);\n manager.subscribe(FreeLicenseCallback.class, this::onFreeLicense);\n manager.subscribe(AccountInfoCallback.class, this::onAccountInfo);\n manager.subscribe(WebAPIUserNonceCallback.class, this::onWebAPIUserNonce);\n manager.subscribe(ItemAnnouncementsCallback.class, this::onItemAnnouncements);\n manager.subscribe(PurchaseResponseCallback.class, this::onPurchaseResponse);\n\n // Detect Huawei devices running Lollipop which have a bug with MediaStyle notifications\n isHuawei = (android.os.Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP_MR1 ||\n android.os.Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP) &&\n Build.MANUFACTURER.toLowerCase(Locale.getDefault()).contains(\"huawei\");\n if (PrefsManager.stayAwake()) {\n acquireWakeLock();\n }\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {\n // Create notification channel\n createChannel();\n }\n if (BuildConfig.DEBUG) {\n LogManager.addListener(new AndroidLogListener());\n }\n startForeground(NOTIF_ID, buildNotification(getString(R.string.service_started)));\n }\n\n @Override\n protected void attachBaseContext(Context base) {\n super.attachBaseContext(LocaleManager.setLocale(base));\n }\n\n @Override\n public int onStartCommand(Intent intent, int flags, int startId) {\n if (!running) {\n Log.i(TAG, \"Command starting\");\n final IntentFilter filter = new IntentFilter();\n filter.addAction(SKIP_INTENT);\n filter.addAction(STOP_INTENT);\n filter.addAction(PAUSE_INTENT);\n filter.addAction(RESUME_INTENT);\n registerReceiver(receiver, filter);\n start();\n }\n return Service.START_NOT_STICKY;\n }\n\n @Override\n public void onDestroy() {\n Log.i(TAG, \"Service destroyed\");\n new Thread(() -> {\n steamUser.logOff();\n steamClient.disconnect();\n }).start();\n stopForeground(true);\n running = false;\n stopFarming();\n executor.shutdownNow();\n scheduler.shutdownNow();\n releaseWakeLock();\n unregisterReceiver(receiver);\n super.onDestroy();\n }\n\n /**\n * Create notification channel for Android O\n */\n @RequiresApi(Build.VERSION_CODES.O)\n private void createChannel() {\n final CharSequence name = getString(R.string.channel_name);\n final int importance = NotificationManager.IMPORTANCE_LOW;\n final NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);\n channel.setShowBadge(false);\n channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);\n channel.enableVibration(false);\n channel.enableLights(false);\n channel.setBypassDnd(false);\n final NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);\n nm.createNotificationChannel(channel);\n }\n\n public boolean isLoggedIn() {\n return loggedIn;\n }\n\n public boolean isFarming() {\n return farming;\n }\n\n public boolean isPaused() {\n return paused;\n }\n\n /**\n * Get the games we're currently idling\n */\n public ArrayList<Game> getCurrentGames() {\n return new ArrayList<>(currentGames);\n }\n\n public int getGameCount() {\n return gameCount;\n }\n\n public int getCardCount() {\n return cardCount;\n }\n\n public long getSteamId() {\n return steamId;\n }\n\n public void changeStatus(EPersonaState status) {\n if (isLoggedIn()) {\n executor.execute(() -> steamFriends.setPersonaState(status));\n }\n }\n\n /**\n * Acquire WakeLock to keep the CPU from sleeping\n */\n public void acquireWakeLock() {\n if (wakeLock == null) {\n Log.i(TAG, \"Acquiring WakeLock\");\n final PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);\n wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_TAG);\n wakeLock.acquire();\n }\n }\n\n /**\n * Release the WakeLock\n */\n public void releaseWakeLock() {\n if (wakeLock != null) {\n Log.i(TAG, \"Releasing WakeLock\");\n wakeLock.release();\n wakeLock = null;\n }\n }\n\n private Notification buildNotification(String text) {\n final Intent notificationIntent = new Intent(this, MainActivity.class);\n final PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,\n notificationIntent, 0);\n return new NotificationCompat.Builder(this, CHANNEL_ID)\n .setSmallIcon(R.drawable.ic_notification)\n .setContentTitle(getString(R.string.app_name))\n .setContentText(text)\n .setContentIntent(pendingIntent)\n .build();\n }\n\n /**\n * Show idling notification\n * @param game\n */\n private void showIdleNotification(Game game) {\n Log.i(TAG, \"Idle notification\");\n final Intent notificationIntent = new Intent(this, MainActivity.class);\n final PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,\n notificationIntent, 0);\n\n final NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)\n .setSmallIcon(R.drawable.ic_notification)\n .setContentTitle(getString(R.string.app_name))\n .setContentText(getString(R.string.now_playing2,\n (game.appId == 0) ? getString(R.string.playing_non_steam_game, game.name) : game.name))\n .setPriority(NotificationCompat.PRIORITY_MAX)\n .setContentIntent(pendingIntent);\n\n // MediaStyle causes a crash on certain Huawei devices running Lollipop\n // https://stackoverflow.com/questions/34851943/couldnt-expand-remoteviews-mediasessioncompat-and-notificationcompat-mediastyl\n if (!isHuawei) {\n builder.setStyle(new MediaStyle());\n }\n\n if (game.dropsRemaining > 0) {\n // Show drops remaining\n builder.setSubText(getResources().getQuantityString(R.plurals.card_drops_remaining, game.dropsRemaining, game.dropsRemaining));\n }\n\n // Add the stop and pause actions\n final PendingIntent stopIntent = PendingIntent.getBroadcast(this, 0, new Intent(STOP_INTENT), PendingIntent.FLAG_CANCEL_CURRENT);\n final PendingIntent pauseIntent = PendingIntent.getBroadcast(this, 0, new Intent(PAUSE_INTENT), PendingIntent.FLAG_CANCEL_CURRENT);\n builder.addAction(R.drawable.ic_action_stop, getString(R.string.stop), stopIntent);\n builder.addAction(R.drawable.ic_action_pause, getString(R.string.pause), pauseIntent);\n\n if (farming) {\n // Add the skip action\n final PendingIntent skipIntent = PendingIntent.getBroadcast(this, 0, new Intent(SKIP_INTENT), PendingIntent.FLAG_CANCEL_CURRENT);\n builder.addAction(R.drawable.ic_action_skip, getString(R.string.skip), skipIntent);\n }\n\n final NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);\n if (!PrefsManager.minimizeData()) {\n // Load game icon into notification\n Glide.with(getApplicationContext())\n .load(game.iconUrl)\n .asBitmap()\n .into(new SimpleTarget<Bitmap>() {\n @Override\n public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {\n builder.setLargeIcon(resource);\n nm.notify(NOTIF_ID, builder.build());\n }\n\n @Override\n public void onLoadFailed(Exception e, Drawable errorDrawable) {\n super.onLoadFailed(e, errorDrawable);\n nm.notify(NOTIF_ID, builder.build());\n }\n });\n } else {\n nm.notify(NOTIF_ID, builder.build());\n }\n }\n\n /**\n * Show \"Big Text\" style notification with the games we're idling\n * @param msg the games\n */\n private void showMultipleNotification(String msg) {\n final PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,\n new Intent(this, MainActivity.class), 0);\n\n // Add stop and pause actions\n final PendingIntent stopIntent = PendingIntent.getBroadcast(this, 0, new Intent(STOP_INTENT), PendingIntent.FLAG_CANCEL_CURRENT);\n final PendingIntent pauseIntent = PendingIntent.getBroadcast(this, 0, new Intent(PAUSE_INTENT), PendingIntent.FLAG_CANCEL_CURRENT);\n\n final Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)\n .setStyle(new NotificationCompat.BigTextStyle()\n .bigText(msg))\n .setSmallIcon(R.drawable.ic_notification)\n .setContentTitle(getString(R.string.app_name))\n .setContentText(getString(R.string.idling_multiple))\n .setPriority(NotificationCompat.PRIORITY_MAX)\n .setContentIntent(pendingIntent)\n .addAction(R.drawable.ic_action_stop, getString(R.string.stop), stopIntent)\n .addAction(R.drawable.ic_action_pause, getString(R.string.pause), pauseIntent)\n .build();\n\n final NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);\n nm.notify(NOTIF_ID, notification);\n }\n\n private void showPausedNotification() {\n final PendingIntent pi = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0);\n final PendingIntent resumeIntent = PendingIntent.getBroadcast(this, 0, new Intent(RESUME_INTENT), PendingIntent.FLAG_CANCEL_CURRENT);\n final Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)\n .setSmallIcon(R.drawable.ic_notification)\n .setContentTitle(getString(R.string.app_name))\n .setContentText(getString(R.string.paused))\n .setContentIntent(pi)\n .addAction(R.drawable.ic_action_play, getString(R.string.resume), resumeIntent)\n .build();\n final NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);\n nm.notify(NOTIF_ID, notification);\n }\n\n /**\n * Used to update the notification\n * @param text the text to display\n */\n private void updateNotification(String text) {\n final NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);\n notificationManager.notify(NOTIF_ID, buildNotification(text));\n }\n\n private void idleSingle(Game game) {\n Log.i(TAG, \"Now playing \" + game.name);\n paused = false;\n currentGames.clear();\n currentGames.add(game);\n playGames(game);\n showIdleNotification(game);\n }\n\n private void idleMultiple(List<Game> games) {\n Log.i(TAG, \"Idling multiple\");\n paused = false;\n final List<Game> gamesCopy = new ArrayList<>(games);\n currentGames.clear();\n\n int size = gamesCopy.size();\n if (size > 32) {\n size = 32;\n }\n\n final StringBuilder msg = new StringBuilder();\n for (int i=0;i<size;i++) {\n final Game game = gamesCopy.get(i);\n currentGames.add(game);\n if (game.appId == 0) {\n // Non-Steam game\n msg.append(getString(R.string.playing_non_steam_game, game.name));\n } else {\n msg.append(game.name);\n }\n if (i + 1 < size) {\n msg.append(\"\\n\");\n }\n }\n\n playGames(currentGames.toArray(new Game[0]));\n showMultipleNotification(msg.toString());\n }\n\n public void addGame(Game game) {\n stopFarming();\n if (currentGames.isEmpty()) {\n idleSingle(game);\n } else {\n currentGames.add(game);\n idleMultiple(currentGames);\n }\n }\n\n public void addGames(List<Game> games) {\n stopFarming();\n if (games.size() == 1) {\n idleSingle(games.get(0));\n } else if (games.size() > 1){\n idleMultiple(games);\n } else {\n stopGame();\n }\n }\n\n public void removeGame(Game game) {\n stopFarming();\n currentGames.remove(game);\n if (currentGames.size() == 1) {\n idleSingle(currentGames.get(0));\n } else if (currentGames.size() > 1) {\n idleMultiple(currentGames);\n } else {\n stopGame();\n }\n }\n\n public void start() {\n running = true;\n if (!PrefsManager.getLoginKey().isEmpty()) {\n // We can log in using saved credentials\n executor.execute(() -> steamClient.connect());\n }\n // Run the the callback handler\n executor.execute(() -> {\n while (running) {\n try {\n manager.runWaitCallbacks(1000L);\n } catch (Exception e) {\n Log.i(TAG, \"update() failed\", e);\n }\n }\n });\n }\n\n public void login(final LogOnDetails details) {\n Log.i(TAG, \"logging in\");\n loginInProgress = true;\n logOnDetails = details;\n executor.execute(() -> steamClient.connect());\n }\n\n public void logoff() {\n Log.i(TAG, \"logging off\");\n loginInProgress = true;\n loggedIn = false;\n steamId = 0;\n logOnDetails = null;\n currentGames.clear();\n keyToRedeem = null;\n pendingFreeLicenses.clear();\n stopFarming();\n executor.execute(() -> {\n steamUser.logOff();\n steamClient.disconnect();\n });\n PrefsManager.clearUser();\n updateNotification(getString(R.string.logged_out));\n }\n\n /**\n * Redeem Steam key or activate free license\n */\n public void redeemKey(String key) {\n if (!loggedIn && !PrefsManager.getLoginKey().isEmpty()) {\n Log.i(TAG, \"Will redeem key at login\");\n keyToRedeem = key;\n return;\n }\n Log.i(TAG, \"Redeeming key...\");\n if (key.matches(\"\\\\d+\")) {\n // Request a free license\n try {\n int freeLicense = Integer.parseInt(key);\n addFreeLicense(freeLicense);\n } catch (NumberFormatException e) {\n showToast(getString(R.string.invalid_key));\n }\n } else {\n // Register product key\n registerProductKey(key);\n }\n }\n\n /**\n * Request a free license\n */\n private void addFreeLicense(int freeLicense) {\n pendingFreeLicenses.add(freeLicense);\n executor.execute(() -> steamApps.requestFreeLicense(freeLicense));\n }\n\n /**\n * Register a product key\n */\n private void registerProductKey(String productKey) {\n final ClientMsgProtobuf<SteammessagesClientserver2.CMsgClientRegisterKey.Builder> registerKey;\n registerKey = new ClientMsgProtobuf<>(SteammessagesClientserver2.CMsgClientRegisterKey.class, EMsg.ClientRegisterKey);\n registerKey.getBody().setKey(productKey);\n executor.execute(() -> steamClient.send(registerKey));\n }\n\n /**\n * Perform log in. Needs to happen as soon as we connect or else we'll get an error\n */\n private void doLogin() {\n if (PrefsManager.useCustomLoginId()) {\n final int localIp = NetHelpers.getIPAddress(steamClient.getLocalIP());\n logOnDetails.setLoginID(localIp ^ CUSTOM_OBFUSCATION_MASK);\n }\n steamUser.logOn(logOnDetails);\n logOnDetails = null; // No longer need this\n }\n\n /**\n * Log in using saved credentials\n */\n private void attemptRestoreLogin() {\n final String username = PrefsManager.getUsername();\n final String loginKey = PrefsManager.getLoginKey();\n if (username.isEmpty() || loginKey.isEmpty()) {\n return;\n }\n Log.i(TAG, \"Restoring login\");\n final LogOnDetails details = new LogOnDetails();\n details.setUsername(username);\n details.setLoginKey(loginKey);\n details.setClientOSType(EOSType.LinuxUnknown);\n if (PrefsManager.useCustomLoginId()) {\n final int localIp = NetHelpers.getIPAddress(steamClient.getLocalIP());\n details.setLoginID(localIp ^ CUSTOM_OBFUSCATION_MASK);\n }\n try {\n final File sentryFile = new File(sentryFolder, username + \".sentry\");\n details.setSentryFileHash(Utils.calculateSHA1(sentryFile));\n } catch (IOException | NoSuchAlgorithmException e) {\n e.printStackTrace();\n }\n details.setShouldRememberPassword(true);\n steamUser.logOn(details);\n }\n\n private boolean attemptAuthentication(String nonce) {\n Log.i(TAG, \"Attempting SteamWeb authentication\");\n for (int i=0;i<3;i++) {\n if (webHandler.authenticate(steamClient, nonce)) {\n Log.i(TAG, \"Authenticated!\");\n return true;\n }\n\n if (i + 1 < 3) {\n Log.i(TAG, \"Retrying...\");\n try {\n Thread.sleep(1000);\n } catch (InterruptedException e) {\n e.printStackTrace();\n return false;\n }\n }\n }\n return false;\n }\n\n private void registerApiKey() {\n Log.i(TAG, \"Registering API key\");\n final int result = webHandler.updateApiKey();\n Log.i(TAG, \"API key result: \" + result);\n switch (result) {\n case SteamWebHandler.ApiKeyState.REGISTERED:\n break;\n case SteamWebHandler.ApiKeyState.ACCESS_DENIED:\n showToast(getString(R.string.apikey_access_denied));\n break;\n case SteamWebHandler.ApiKeyState.UNREGISTERED:\n // Call updateApiKey once more to actually update it\n webHandler.updateApiKey();\n break;\n case SteamWebHandler.ApiKeyState.ERROR:\n showToast(getString(R.string.apikey_register_failed));\n break;\n }\n }\n\n private void showToast(final String message) {\n new Handler(Looper.getMainLooper()).post(() -> Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show());\n }\n\n private void onConnected(ConnectedCallback callback) {\n Log.i(TAG, \"Connected()\");\n connected = true;\n if (logOnDetails != null) {\n doLogin();\n } else {\n attemptRestoreLogin();\n }\n }\n\n private void onDisconnected(DisconnectedCallback callback) {\n Log.i(TAG, \"Disconnected()\");\n connected = false;\n loggedIn = false;\n\n if (!loginInProgress) {\n // Try to reconnect after a 5 second delay\n scheduler.schedule(() -> {\n Log.i(TAG, \"Reconnecting\");\n steamClient.connect();\n }, 5, TimeUnit.SECONDS);\n } else {\n // SteamKit may disconnect us while logging on (if already connected),\n // but since it reconnects immediately after we do not have to reconnect here.\n Log.i(TAG, \"NOT reconnecting (logon in progress)\");\n }\n\n // Tell the activity that we've been disconnected from Steam\n LocalBroadcastManager.getInstance(SteamService.this).sendBroadcast(new Intent(DISCONNECT_EVENT));\n }\n\n private void onLoggedOff(LoggedOffCallback callback) {\n Log.i(TAG, \"Logoff result \" + callback.getResult().toString());\n if (callback.getResult() == EResult.LoggedInElsewhere) {\n updateNotification(getString(R.string.logged_in_elsewhere));\n unscheduleFarmTask();\n if (!waiting) {\n waiting = true;\n waitHandle = scheduler.scheduleAtFixedRate(waitTask, 0, 30, TimeUnit.SECONDS);\n }\n } else {\n // Reconnect\n steamClient.disconnect();\n }\n }\n\n private void onLoggedOn(LoggedOnCallback callback) {\n final EResult result = callback.getResult();\n\n if (result == EResult.OK) {\n // Successful login\n Log.i(TAG, \"Logged on!\");\n loginInProgress = false;\n loggedIn = true;\n steamId = steamClient.getSteamID().convertToUInt64();\n if (paused) {\n showPausedNotification();\n } else if (waiting) {\n updateNotification(getString(R.string.logged_in_elsewhere));\n } else {\n updateNotification(getString(R.string.logged_in));\n }\n executor.execute(() -> {\n final boolean gotAuth = attemptAuthentication(callback.getWebAPIUserNonce());\n\n if (gotAuth) {\n resumeFarming();\n registerApiKey();\n } else {\n // Request a new WebAPI user authentication nonce\n steamUser.requestWebAPIUserNonce();\n }\n });\n if (keyToRedeem != null) {\n redeemKey(keyToRedeem);\n keyToRedeem = null;\n }\n } else if (result == EResult.InvalidPassword && !PrefsManager.getLoginKey().isEmpty()) {\n // Probably no longer valid\n Log.i(TAG, \"Login key expired\");\n PrefsManager.writeLoginKey(\"\");\n updateNotification(getString(R.string.login_key_expired));\n keyToRedeem = null;\n steamClient.disconnect();\n } else {\n Log.i(TAG, \"LogOn result: \" + result.toString());\n keyToRedeem = null;\n steamClient.disconnect();\n }\n\n // Tell LoginActivity the result\n final Intent intent = new Intent(LOGIN_EVENT);\n intent.putExtra(RESULT, result);\n LocalBroadcastManager.getInstance(SteamService.this).sendBroadcast(intent);\n }\n\n private void onLoginKey(LoginKeyCallback callback) {\n Log.i(TAG, \"Saving loginkey\");\n PrefsManager.writeLoginKey(callback.getLoginKey());\n steamUser.acceptNewLoginKey(callback);\n }\n\n private void onUpdateMachineAuth(UpdateMachineAuthCallback callback) {\n final File sentryFile = new File(sentryFolder, PrefsManager.getUsername() + \".sentry\");\n Log.i(TAG, \"Saving sentry file to \" + sentryFile.getAbsolutePath());\n try (final FileOutputStream fos = new FileOutputStream(sentryFile)) {\n final FileChannel channel = fos.getChannel();\n channel.position(callback.getOffset());\n channel.write(ByteBuffer.wrap(callback.getData(), 0, callback.getBytesToWrite()));\n\n final byte[] sha1 = Utils.calculateSHA1(sentryFile);\n\n final OTPDetails otp = new OTPDetails();\n otp.setIdentifier(callback.getOneTimePassword().getIdentifier());\n otp.setType(callback.getOneTimePassword().getType());\n\n final MachineAuthDetails auth = new MachineAuthDetails();\n auth.setJobID(callback.getJobID());\n auth.setFileName(callback.getFileName());\n auth.setBytesWritten(callback.getBytesToWrite());\n auth.setFileSize((int) sentryFile.length());\n auth.setOffset(callback.getOffset());\n auth.seteResult(EResult.OK);\n auth.setLastError(0);\n auth.setSentryFileHash(sha1);\n auth.setOneTimePassword(otp);\n\n steamUser.sendMachineAuthResponse(auth);\n\n PrefsManager.writeSentryHash(Utils.bytesToHex(sha1));\n } catch (IOException | NoSuchAlgorithmException e) {\n Log.i(TAG, \"Error saving sentry file\", e);\n }\n }\n\n private void onPurchaseResponse(PurchaseResponseCallback callback) {\n if (callback.getResult() == EResult.OK) {\n final KeyValue kv = callback.getPurchaseReceiptInfo();\n final EPaymentMethod paymentMethod = EPaymentMethod.from(kv.get(\"PaymentMethod\").asInteger());\n if (paymentMethod == EPaymentMethod.ActivationCode) {\n final StringBuilder products = new StringBuilder();\n final int size = kv.get(\"LineItemCount\").asInteger();\n Log.i(TAG, \"LineItemCount \" + size);\n for (int i=0;i<size;i++) {\n final String lineItem = kv.get(\"lineitems\").get(i + \"\").get(\"ItemDescription\").asString();\n Log.i(TAG, \"lineItem \" + i + \" \" + lineItem);\n products.append(lineItem);\n if (i + 1 < size) {\n products.append(\", \");\n }\n }\n showToast(getString(R.string.activated, products.toString()));\n }\n } else {\n final EPurchaseResultDetail purchaseResult = callback.getPurchaseResultDetails();\n final int errorId;\n if (purchaseResult == EPurchaseResultDetail.AlreadyPurchased) {\n errorId = R.string.product_already_owned;\n } else if (purchaseResult == EPurchaseResultDetail.BadActivationCode) {\n errorId = R.string.invalid_key;\n } else {\n errorId = R.string.activation_failed;\n }\n showToast(getString(errorId));\n }\n }\n\n private void onPersonaStates(PersonaStatesCallback callback) {\n for (PersonaState ps : callback.getPersonaStates()) {\n if (ps.getFriendID().equals(steamClient.getSteamID())) {\n final String personaName = ps.getName();\n final String avatarHash = Utils.bytesToHex(ps.getAvatarHash()).toLowerCase();\n Log.i(TAG, \"Avatar hash \" + avatarHash);\n final Intent event = new Intent(PERSONA_EVENT);\n event.putExtra(PERSONA_NAME, personaName);\n event.putExtra(AVATAR_HASH, avatarHash);\n LocalBroadcastManager.getInstance(SteamService.this).sendBroadcast(event);\n break;\n }\n }\n }\n\n private void onFreeLicense(FreeLicenseCallback callback) {\n final int freeLicense = pendingFreeLicenses.removeFirst();\n if (!callback.getGrantedApps().isEmpty()) {\n showToast(getString(R.string.activated, String.valueOf(callback.getGrantedApps().get(0))));\n } else if (!callback.getGrantedPackages().isEmpty()) {\n showToast(getString(R.string.activated, String.valueOf(callback.getGrantedPackages().get(0))));\n } else {\n // Try activating it with the web handler\n executor.execute(() -> {\n final String msg;\n if (webHandler.addFreeLicense(freeLicense)) {\n msg = getString(R.string.activated, String.valueOf(freeLicense));\n } else {\n msg = getString(R.string.activation_failed);\n }\n showToast(msg);\n });\n }\n }\n\n private void onAccountInfo(AccountInfoCallback callback) {\n if (!PrefsManager.getOffline()) {\n steamFriends.setPersonaState(EPersonaState.Online);\n }\n }\n\n private void onWebAPIUserNonce(WebAPIUserNonceCallback callback) {\n Log.i(TAG, \"Got new WebAPI user authentication nonce\");\n executor.execute(() -> {\n final boolean gotAuth = attemptAuthentication(callback.getNonce());\n\n if (gotAuth) {\n resumeFarming();\n } else {\n updateNotification(getString(R.string.web_login_failed));\n }\n });\n }\n\n private void onItemAnnouncements(ItemAnnouncementsCallback callback) {\n Log.i(TAG, \"New item notification \" + callback.getCount());\n if (callback.getCount() > 0 && farming) {\n // Possible card drop\n executor.execute(farmTask);\n }\n }\n\n /**\n * Idle one or more games\n * @param games the games to idle\n */\n private void playGames(Game...games) {\n final ClientMsgProtobuf<SteammessagesClientserver.CMsgClientGamesPlayed.Builder> gamesPlayed;\n gamesPlayed = new ClientMsgProtobuf<>(SteammessagesClientserver.CMsgClientGamesPlayed.class, EMsg.ClientGamesPlayed);\n for (Game game : games) {\n if (game.appId == 0) {\n // Non-Steam game\n final GameID gameId = new GameID(game.appId);\n gameId.setAppType(GameID.GameType.SHORTCUT);\n final CRC32 crc = new CRC32();\n crc.update(game.name.getBytes());\n // set the high-bit on the mod-id\n // reduces crc32 to 31bits, but lets us use the modID as a guaranteed unique\n // replacement for appID\n gameId.setModID(crc.getValue() | (0x80000000));\n gamesPlayed.getBody().addGamesPlayedBuilder()\n .setGameId(gameId.convertToUInt64())\n .setGameExtraInfo(game.name);\n } else {\n gamesPlayed.getBody().addGamesPlayedBuilder()\n .setGameId(game.appId);\n }\n }\n executor.execute(() -> {\n steamClient.send(gamesPlayed);\n });\n // Tell the activity\n LocalBroadcastManager.getInstance(SteamService.this).sendBroadcast(new Intent(NOW_PLAYING_EVENT));\n }\n\n private void stopPlaying() {\n if (!paused) {\n currentGames.clear();\n }\n final ClientMsgProtobuf<SteammessagesClientserver.CMsgClientGamesPlayed.Builder> stopGame;\n stopGame = new ClientMsgProtobuf<>(SteammessagesClientserver.CMsgClientGamesPlayed.class, EMsg.ClientGamesPlayed);\n stopGame.getBody().addGamesPlayedBuilder().setGameId(0);\n executor.execute(() -> steamClient.send(stopGame));\n // Tell the activity\n LocalBroadcastManager.getInstance(SteamService.this).sendBroadcast(new Intent(NOW_PLAYING_EVENT));\n }\n\n /**\n * Register and idle a game for a few seconds to complete the Spring Cleaning daily tasks\n */\n public void registerAndIdle(String game) {\n try {\n final int appId = Integer.parseInt(game);\n\n // Register the game\n steamApps.requestFreeLicense(appId);\n Thread.sleep(1000);\n\n // Play it for a few seconds\n final ClientMsgProtobuf<SteammessagesClientserver.CMsgClientGamesPlayed.Builder> playGame;\n playGame = new ClientMsgProtobuf<>(SteammessagesClientserver.CMsgClientGamesPlayed.class, EMsg.ClientGamesPlayed);\n playGame.getBody().addGamesPlayedBuilder().setGameId(appId);\n steamClient.send(playGame);\n Thread.sleep(3000);\n\n // Stop playing\n playGame.getBody().clearGamesPlayed().addGamesPlayedBuilder().setGameId(0);\n steamClient.send(playGame);\n Thread.sleep(1000);\n } catch (NumberFormatException|InterruptedException e) {\n e.printStackTrace();\n }\n }\n\n /**\n * Open a cottage door (Winter Sale 2018)\n */\n public void openCottageDoor() {\n executor.execute(new Runnable() {\n @Override\n public void run() {\n boolean result = webHandler.openCottageDoor();\n if (result) {\n showToast(getString(R.string.door_success));\n } else {\n showToast(getString(R.string.door_fail));\n }\n }\n });\n }\n}",
"public class SteamWebHandler {\n private final static String TAG = SteamWebHandler.class.getSimpleName();\n\n private final static int TIMEOUT_SECS = 30;\n\n private final static String STEAM_STORE = \"https://store.steampowered.com/\";\n private final static String STEAM_COMMUNITY = \"https://steamcommunity.com/\";\n private final static String STEAM_API = \"https://api.steampowered.com/\";\n\n // Pattern to match app ID\n private final static Pattern playPattern = Pattern.compile(\"^steam://run/(\\\\d+)$\");\n // Pattern to match card drops remaining\n private final static Pattern dropPattern = Pattern.compile(\"^(\\\\d+) card drops? remaining$\");\n // Pattern to match play time\n private final static Pattern timePattern = Pattern.compile(\"([0-9\\\\.]+) hrs on record\");\n\n private final static SteamWebHandler ourInstance = new SteamWebHandler();\n\n private boolean authenticated;\n private long steamId;\n private String sessionId;\n private String token;\n private String tokenSecure;\n private String steamParental;\n private String apiKey = BuildConfig.SteamApiKey;\n\n private final SteamAPI api;\n\n private SteamWebHandler() {\n final Gson gson = new GsonBuilder()\n .registerTypeAdapter(GamesOwnedResponse.class, new GamesOwnedResponseDeserializer())\n .create();\n\n final OkHttpClient client = new OkHttpClient.Builder()\n .connectTimeout(TIMEOUT_SECS, TimeUnit.SECONDS)\n .readTimeout(TIMEOUT_SECS, TimeUnit.SECONDS)\n .writeTimeout(TIMEOUT_SECS, TimeUnit.SECONDS)\n .build();\n\n final Retrofit retrofit = new Retrofit.Builder()\n .baseUrl(STEAM_API)\n .addConverterFactory(VdfConverterFactory.create())\n .addConverterFactory(GsonConverterFactory.create(gson))\n .client(client)\n .build();\n\n api = retrofit.create(SteamAPI.class);\n }\n\n public static SteamWebHandler getInstance() {\n return ourInstance;\n }\n\n /**\n * Authenticate on the Steam website\n *\n * @param client the Steam client\n * @param webApiUserNonce the WebAPI User Nonce returned by LoggedOnCallback\n * @return true if authenticated\n */\n boolean authenticate(SteamClient client, String webApiUserNonce) {\n authenticated = false;\n final SteamID clientSteamId = client.getSteamID();\n if (clientSteamId == null) {\n return false;\n }\n steamId = clientSteamId.convertToUInt64();\n sessionId = Utils.bytesToHex(CryptoHelper.generateRandomBlock(4));\n\n // generate an AES session key\n final byte[] sessionKey = CryptoHelper.generateRandomBlock(32);\n\n // rsa encrypt it with the public key for the universe we're on\n final byte[] publicKey = KeyDictionary.getPublicKey(client.getUniverse());\n if (publicKey == null) {\n return false;\n }\n\n final RSACrypto rsa = new RSACrypto(publicKey);\n final byte[] cryptedSessionKey = rsa.encrypt(sessionKey);\n\n final byte[] loginKey = new byte[20];\n System.arraycopy(webApiUserNonce.getBytes(), 0, loginKey, 0, webApiUserNonce.length());\n\n // aes encrypt the loginkey with our session key\n final byte[] cryptedLoginKey;\n try {\n cryptedLoginKey = CryptoHelper.symmetricEncrypt(loginKey, sessionKey);\n } catch (CryptoException e) {\n e.printStackTrace();\n return false;\n }\n\n final KeyValue authResult;\n\n final Map<String,String> args = new HashMap<>();\n args.put(\"steamid\", String.valueOf(steamId));\n args.put(\"sessionkey\", WebHelpers.urlEncode(cryptedSessionKey));\n args.put(\"encrypted_loginkey\", WebHelpers.urlEncode(cryptedLoginKey));\n args.put(\"format\", \"vdf\");\n\n try {\n authResult = api.authenticateUser(args).execute().body();\n } catch (IOException e) {\n e.printStackTrace();\n return false;\n }\n\n if (authResult == null) {\n return false;\n }\n\n token = authResult.get(\"token\").asString();\n tokenSecure = authResult.get(\"tokenSecure\").asString();\n\n authenticated = true;\n\n final String pin = PrefsManager.getParentalPin().trim();\n if (!pin.isEmpty()) {\n // Unlock family view\n steamParental = unlockParental(pin);\n }\n\n return true;\n }\n\n /**\n * Generate Steam web cookies\n * @return Map of the cookies\n */\n private Map<String,String> generateWebCookies() {\n if (!authenticated) {\n return new HashMap<>();\n }\n\n final Map<String, String> cookies = new HashMap<>();\n cookies.put(\"sessionid\", sessionId);\n cookies.put(\"steamLogin\", token);\n cookies.put(\"steamLoginSecure\", tokenSecure);\n final String sentryHash = PrefsManager.getSentryHash().trim();\n if (!sentryHash.isEmpty()) {\n cookies.put(\"steamMachineAuth\" + steamId, sentryHash);\n }\n if (steamParental != null) {\n cookies.put(\"steamparental\", steamParental);\n }\n\n return cookies;\n }\n\n /**\n * Get a list of games with card drops remaining\n * @return list of games with remaining drops\n */\n List<Game> getRemainingGames() {\n final String url = STEAM_COMMUNITY + \"my/badges?l=english\";\n final List<Game> badgeList = new ArrayList<>();\n Document doc;\n try {\n doc = Jsoup.connect(url)\n .followRedirects(true)\n .cookies(generateWebCookies())\n .get();\n } catch (Exception e) {\n e.printStackTrace();\n return null;\n }\n\n final Element userAvatar = doc.select(\"a.user_avatar\").first();\n if (userAvatar == null) {\n // Invalid cookie data\n return null;\n }\n\n final Elements badges = doc.select(\"div.badge_title_row\");\n\n final Element pages = doc.select(\"a.pagelink\").last();\n if (pages != null) {\n // Multiple pages\n final int p = Integer.parseInt(pages.text());\n // Try to combine all the pages\n for (int i=2;i<=p;i++) {\n try {\n final Document doc2 = Jsoup.connect(url + \"&p=\" + i)\n .followRedirects(true)\n .cookies(generateWebCookies())\n .get();\n final Elements badges2 = doc2.select(\"div.badge_title_row\");\n badges.addAll(badges2);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n }\n\n final List<String> blacklist = PrefsManager.getBlacklist();\n Matcher m;\n for (Element b: badges) {\n // Get app id\n final Element playGame = b.select(\"div.badge_title_playgame\").first();\n if (playGame == null) {\n continue;\n }\n m = playPattern.matcher(playGame.select(\"a[href]\").first().attr(\"href\"));\n if (!m.find()) {\n continue;\n }\n\n if (blacklist.contains(m.group(1))) {\n // Skip appids in the blacklist\n continue;\n }\n\n final int appId = Integer.parseInt(m.group(1));\n\n // Get remaining card drops\n final Element progressInfo = b.select(\"span.progress_info_bold\").first();\n if (progressInfo == null) {\n continue;\n }\n m = dropPattern.matcher(progressInfo.text());\n if (!m.find()) {\n continue;\n }\n final int drops = Integer.parseInt(m.group(1));\n\n // Get app name\n final Element badgeTitle = b.select(\"div.badge_title\").first();\n if (badgeTitle == null) {\n continue;\n }\n final String name = badgeTitle.ownText().trim();\n\n // Get play time\n final Element playTime = b.select(\"div.badge_title_stats_playtime\").first();\n if (playTime == null) {\n continue;\n }\n final String playTimeText = playTime.text().trim();\n m = timePattern.matcher(playTimeText);\n float time = 0;\n if (m.find()) {\n time = Float.parseFloat(m.group(1));\n }\n\n badgeList.add(new Game(appId, name, time, drops));\n }\n\n return badgeList;\n }\n\n /**\n * Unlock Steam parental controls with a pin\n */\n private String unlockParental(String pin) {\n final String url = STEAM_STORE + \"parental/ajaxunlock\";\n try {\n final Map<String,String> responseCookies = Jsoup.connect(url)\n .referrer(STEAM_STORE)\n .followRedirects(true)\n .ignoreContentType(true)\n .cookies(generateWebCookies())\n .data(\"pin\", pin)\n .method(Connection.Method.POST)\n .execute()\n .cookies();\n return responseCookies.get(\"steamparental\");\n } catch (Exception e) {\n e.printStackTrace();\n }\n return null;\n }\n\n public Call<GamesOwnedResponse> getGamesOwned(long steamId) {\n final Map<String,String> args = new HashMap<>();\n args.put(\"key\", apiKey);\n args.put(\"steamid\", String.valueOf(steamId));\n if (PrefsManager.includeFreeGames()) {\n args.put(\"include_played_free_games\", \"1\");\n }\n return api.getGamesOwned(args);\n }\n\n public Call<TimeQuery> queryServerTime() {\n return api.queryServerTime(\"0\");\n }\n\n /**\n * Check if user is currently NOT in-game, so we can resume farming.\n */\n Boolean checkIfNotInGame() {\n final String url = STEAM_COMMUNITY + \"my/profile?l=english\";\n Document doc;\n try {\n doc = Jsoup.connect(url)\n .followRedirects(true)\n .cookies(generateWebCookies())\n .get();\n } catch (Exception e) {\n e.printStackTrace();\n return null;\n }\n\n final Element userAvatar = doc.select(\"a.user_avatar\").first();\n if (userAvatar == null) {\n // Invalid cookie data\n return null;\n }\n\n return doc.select(\"div.profile_in_game_name\").first() == null;\n }\n\n /**\n * Add a free license to your account\n *\n * @param subId subscription id\n * @return true if successful\n */\n boolean addFreeLicense(int subId) {\n final String url = STEAM_STORE + \"checkout/addfreelicense\";\n try {\n final Document doc = Jsoup.connect(url)\n .referrer(STEAM_STORE)\n .followRedirects(true)\n .cookies(generateWebCookies())\n .data(\"sessionid\", sessionId)\n .data(\"subid\", String.valueOf(subId))\n .data(\"action\", \"add_to_cart\")\n .post();\n return doc.select(\"div.add_free_content_success_area\").first() != null;\n } catch (IOException e) {\n e.printStackTrace();\n }\n return false;\n }\n\n public JSONArray generateNewDiscoveryQueue() throws Exception {\n final String url = STEAM_STORE + \"explore/generatenewdiscoveryqueue\";\n final String json = Jsoup.connect(url)\n .ignoreContentType(true)\n .referrer(STEAM_STORE)\n .followRedirects(true)\n .cookies(generateWebCookies())\n .method(Connection.Method.POST)\n .data(\"sessionid\", sessionId)\n .data(\"queuetype\", \"0\")\n .execute()\n .body();\n return new JSONObject(json).getJSONArray(\"queue\");\n }\n\n public void clearFromQueue(String appId) throws Exception {\n final String url = STEAM_STORE + \"app/10\";\n final Document doc = Jsoup.connect(url)\n .ignoreContentType(true)\n .referrer(STEAM_STORE)\n .followRedirects(true)\n .cookies(generateWebCookies())\n .data(\"sessionid\", sessionId)\n .data(\"appid_to_clear_from_queue\", appId)\n .post();\n }\n\n @ApiKeyState int updateApiKey() {\n if (Utils.isValidKey(PrefsManager.getApiKey())) {\n // Use saved API key\n apiKey = PrefsManager.getApiKey();\n return ApiKeyState.REGISTERED;\n }\n // Try to fetch key from web\n final String url = STEAM_COMMUNITY + \"dev/apikey?l=english\";\n try {\n final Document doc = Jsoup.connect(url)\n .referrer(STEAM_COMMUNITY)\n .followRedirects(true)\n .cookies(generateWebCookies())\n .get();\n final Element titleNode = doc.select(\"div#mainContents h2\").first();\n if (titleNode == null) {\n return ApiKeyState.ERROR;\n }\n final String title = titleNode.text().trim();\n if (title.toLowerCase().contains(\"access denied\")) {\n // Limited account, use the built-in API key\n apiKey = BuildConfig.SteamApiKey;\n PrefsManager.writeApiKey(apiKey);\n return ApiKeyState.ACCESS_DENIED;\n }\n final Element bodyContentsEx = doc.select(\"div#bodyContents_ex p\").first();\n if (bodyContentsEx == null) {\n return ApiKeyState.ERROR;\n }\n final String text = bodyContentsEx.text().trim();\n if (text.toLowerCase().contains(\"registering for a steam web api key\")\n && registerApiKey()) {\n // Should actually be registered here, but we have to call this method again to get the key\n return ApiKeyState.UNREGISTERED;\n } else if (text.toLowerCase().startsWith(\"key: \")) {\n final String key = text.substring(5);\n if (Utils.isValidKey(key)) {\n apiKey = key;\n PrefsManager.writeApiKey(apiKey);\n return ApiKeyState.REGISTERED;\n }\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n return ApiKeyState.ERROR;\n }\n\n private boolean registerApiKey() {\n final String url = STEAM_COMMUNITY + \"dev/registerkey\";\n try {\n final Document doc = Jsoup.connect(url)\n .ignoreContentType(true)\n .followRedirects(true)\n .referrer(STEAM_COMMUNITY)\n .cookies(generateWebCookies())\n .data(\"domain\", \"localhost\")\n .data(\"agreeToTerms\", \"agreed\")\n .data(\"sessionid\", sessionId)\n .data(\"Submit\", \"Register\")\n .post();\n return true;\n } catch (IOException e) {\n e.printStackTrace();\n }\n return false;\n }\n\n /**\n * Get a list of task appid for the Spring Cleaning Event\n * @return\n */\n public List<String> getTaskAppIds() {\n final String url = STEAM_STORE + \"springcleaning?l=english\";\n final List<String> taskAppIds = new ArrayList<>();\n try {\n final Document doc = Jsoup.connect(url)\n .referrer(STEAM_STORE)\n .followRedirects(true)\n .cookies(generateWebCookies())\n .get();\n\n final Elements tasks = doc.select(\"div.spring_cleaning_task_ctn\");\n\n for (Element task : tasks) {\n final Element springGame = task.select(\"div.spring_game\").first();\n if (springGame == null || !springGame.hasAttr(\"data-sg-appid\")) {\n Log.d(TAG, \"Skipping spring game\");\n continue;\n }\n taskAppIds.add(springGame.attr(\"data-sg-appid\").trim());\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n return taskAppIds;\n }\n\n public boolean openCottageDoor() {\n String url = STEAM_STORE + \"promotion/cottage_2018/?l=english\";\n Document doc;\n try {\n doc = Jsoup.connect(url)\n .followRedirects(true)\n .referrer(STEAM_STORE)\n .cookies(generateWebCookies())\n .get();\n } catch (IOException e) {\n Log.e(TAG, \"Failed to open door\", e);\n return false;\n }\n\n final Element door = doc.select(\"div[data-door-id]\").not(\".cottage_door_open\").first();\n if (door == null) {\n Log.e(TAG, \"Didn't find any doors to open\");\n return false;\n }\n\n final String doorId = door.attr(\"data-door-id\");\n Log.i(TAG, \"Opening door \" + doorId);\n\n final SimpleDateFormat sdf = new SimpleDateFormat(\"yyyy-MM-dd'T'HH:mm:ss\", Locale.US);\n final String t = sdf.format(new Date());\n\n url = STEAM_STORE + \"promotion/opencottagedoorajax\";\n try {\n Jsoup.connect(url)\n .ignoreContentType(true)\n .followRedirects(true)\n .referrer(url)\n .cookies(generateWebCookies())\n .data(\"sessionid\", sessionId)\n .data(\"door_index\", doorId)\n .data(\"t\", t)\n .data(\"open_door\", \"true\")\n .post();\n } catch (IOException e) {\n Log.e(TAG, \"Failed to open door \" + doorId, e);\n return false;\n }\n\n return true;\n }\n\n @IntDef({\n ApiKeyState.REGISTERED,\n ApiKeyState.UNREGISTERED,\n ApiKeyState.ACCESS_DENIED,\n ApiKeyState.ERROR\n })\n @Retention(RetentionPolicy.SOURCE)\n public @interface ApiKeyState {\n // Account has registered an API key\n int REGISTERED = 1;\n // Account has not registered an API key yet\n int UNREGISTERED = 2;\n // Account is limited and can't register an API key\n int ACCESS_DENIED = -1;\n // Some other error occurred\n int ERROR = -2;\n }\n}",
"public class Utils {\n private final static String SHA1_ALGORITHM = \"SHA-1\";\n private final static String HMAC_SHA1_ALGORITHM = \"HmacSHA1\";\n\n /**\n * Convert byte array to hex string\n * https://stackoverflow.com/a/9855338\n */\n public static String bytesToHex(byte[] bytes) {\n final char[] hexArray = \"0123456789ABCDEF\".toCharArray();\n\n char[] hexChars = new char[bytes.length * 2];\n for ( int j = 0; j < bytes.length; j++ ) {\n int v = bytes[j] & 0xFF;\n hexChars[j * 2] = hexArray[v >>> 4];\n hexChars[j * 2 + 1] = hexArray[v & 0x0F];\n }\n return new String(hexChars);\n }\n\n /**\n * Convert ArrayList to comma-separated String\n */\n public static String arrayToString(List<String> list) {\n final StringBuilder builder = new StringBuilder();\n for (int i=0,size=list.size();i<size;i++) {\n final String string = list.get(i);\n builder.append(string);\n if (i + 1 < size) {\n builder.append(\",\");\n }\n }\n return builder.toString();\n }\n\n /**\n * Convert array to comma-separated String\n */\n public static String arrayToString(String[] array) {\n return arrayToString(Arrays.asList(array));\n }\n\n /**\n * Save Logcat to file\n */\n public static void saveLogcat(File file) throws IOException {\n final Process p = Runtime.getRuntime().exec(\"logcat -d\");\n try ( final BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));\n final BufferedWriter bw = new BufferedWriter(new FileWriter(file)) ) {\n String line;\n while ((line = br.readLine()) != null) {\n bw.write(line);\n bw.write(\"\\n\");\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n /**\n * Strips non-ASCII characters from String\n */\n public static String removeSpecialChars(String s) {\n return s.replaceAll(\"[^\\\\u0000-\\\\u007F]\", \"\");\n }\n\n /**\n * Check if API key is valid\n */\n public static boolean isValidKey(String key) {\n return key.matches(\"^[0-9A-Fa-f]+$\");\n }\n\n /**\n * Calculate the SHA-1 hash of a file\n */\n public static byte[] calculateSHA1(File file) throws IOException, NoSuchAlgorithmException {\n try (final InputStream fis = new FileInputStream(file)) {\n final MessageDigest md = MessageDigest.getInstance(SHA1_ALGORITHM);\n final byte[] buffer = new byte[8192];\n int n;\n while ((n = fis.read(buffer)) != -1) {\n md.update(buffer, 0, n);\n }\n return md.digest();\n }\n }\n\n /**\n * Get the current unix time\n */\n public static long getCurrentUnixTime() {\n return System.currentTimeMillis() / 1000L;\n }\n\n /**\n * Calculate HMAC SHA1\n */\n public static byte[] calculateRFC2104HMAC(byte[] data, byte[] key) throws NoSuchAlgorithmException, InvalidKeyException {\n final SecretKeySpec secretKey = new SecretKeySpec(key, HMAC_SHA1_ALGORITHM);\n final Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);\n mac.init(secretKey);\n return mac.doFinal(data);\n }\n\n /**\n * Run a block of code a maximum of maxTries\n */\n public static void runWithRetries(int maxTries, ThrowingTask task) throws Exception {\n int count = 0;\n while (count < maxTries) {\n try {\n task.run();\n return;\n } catch (Exception e) {\n if (++count >= maxTries) {\n throw e;\n }\n Thread.sleep(1000);\n }\n }\n }\n}",
"public final static String LOGIN_EVENT = \"LOGIN_EVENT\"; // Emitted on login"
] | import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import com.steevsapps.idledaddy.preferences.PrefsManager;
import com.steevsapps.idledaddy.steam.SteamGuard;
import com.steevsapps.idledaddy.steam.SteamService;
import com.steevsapps.idledaddy.steam.SteamWebHandler;
import com.steevsapps.idledaddy.utils.Utils;
import in.dragonbra.javasteam.enums.EOSType;
import in.dragonbra.javasteam.enums.EResult;
import in.dragonbra.javasteam.steam.handlers.steamuser.LogOnDetails;
import static com.steevsapps.idledaddy.steam.SteamService.LOGIN_EVENT; | package com.steevsapps.idledaddy;
public class LoginActivity extends BaseActivity {
private final static String TAG = LoginActivity.class.getSimpleName();
private final static String LOGIN_IN_PROGRESS = "LOGIN_IN_PROGRESS";
private final static String TWO_FACTOR_REQUIRED = "TWO_FACTOR_REQUIRED";
private boolean loginInProgress;
private boolean twoFactorRequired;
private Integer timeDifference = null;
private LoginViewModel viewModel;
// Views
private CoordinatorLayout coordinatorLayout;
private TextInputLayout usernameInput;
private TextInputEditText usernameEditText;
private TextInputLayout passwordInput;
private TextInputEditText passwordEditText;
private TextInputLayout twoFactorInput;
private TextInputEditText twoFactorEditText;
private Button loginButton;
private ProgressBar progress;
// Used to receive messages from SteamService
private final BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (SteamService.LOGIN_EVENT.equals(intent.getAction())) {
stopTimeout();
progress.setVisibility(View.GONE);
final EResult result = (EResult) intent.getSerializableExtra(SteamService.RESULT);
if (result != EResult.OK) {
loginButton.setEnabled(true);
usernameInput.setErrorEnabled(false);
passwordInput.setErrorEnabled(false);
twoFactorInput.setErrorEnabled(false);
if (result == EResult.InvalidPassword) {
passwordInput.setError(getString(R.string.invalid_password));
} else if (result == EResult.AccountLoginDeniedNeedTwoFactor || result == EResult.AccountLogonDenied || result == EResult.AccountLogonDeniedNoMail || result == EResult.AccountLogonDeniedVerifiedEmailRequired) {
twoFactorRequired = result == EResult.AccountLoginDeniedNeedTwoFactor;
if (twoFactorRequired && timeDifference != null) {
// Fill in the SteamGuard code | twoFactorEditText.setText(SteamGuard.generateSteamGuardCodeForTime(Utils.getCurrentUnixTime() + timeDifference)); | 4 |
Idrinth/WARAddonClient | src/main/java/de/idrinth/waraddonclient/model/addon/UnknownAddon.java | [
"public class Utils {\r\n\r\n private Utils() {\r\n }\r\n\r\n public static void emptyFolder(File folder) throws IOException {\r\n if (folder == null || !folder.exists()) {\r\n return;\r\n }\r\n for (File file : Objects.requireNonNull(folder.listFiles())) {\r\n if (file.isDirectory()) {\r\n emptyFolder(file);\r\n }\r\n Files.deleteIfExists(file.toPath());\r\n }\r\n }\r\n\r\n public static void deleteFolder(File folder) throws IOException {\r\n if (folder == null || !folder.exists()) {\r\n return;\r\n }\r\n emptyFolder(folder);\r\n Files.deleteIfExists(folder.toPath());\r\n }\r\n public static void sleep(int duration, BaseLogger logger) {\r\n try {\r\n Thread.sleep(duration);\r\n } catch (InterruptedException exception) {\r\n logger.info(exception);\r\n }\r\n }\r\n}\r",
"public class InvalidArgumentException extends Exception {\r\n\r\n public InvalidArgumentException(String message) {\r\n super(message);\r\n } \r\n}\r",
"public class Config {\r\n\r\n private static final String KEY_WAR_PATH = \"war-path\";\r\n\r\n private static final String KEY_THEME = \"theme\";\r\n\r\n private static final String KEY_LANGUAGE = \"language\";\r\n\r\n private static final String KEY_WINDOW_LOCATION_X = \"window-x\";\r\n\r\n private static final String KEY_WINDOW_LOCATION_Y = \"window-y\";\r\n\r\n private static final String KEY_WINDOW_WIDTH = \"window-width\";\r\n\r\n private static final String KEY_WINDOW_HEIGHT = \"window-height\";\r\n\r\n private static final String KEY_PROGRESS_LOCATION_X = \"progress-x\";\r\n\r\n private static final String KEY_PROGRESS_LOCATION_Y = \"progress-y\";\r\n\r\n private static final String KEY_PROGRESS_WIDTH = \"progress-width\";\r\n\r\n private static final String KEY_PROGRESS_HEIGHT = \"progress-height\";\r\n\r\n private static final String KEY_AUTO_CLOSE = \"auto-close\";\r\n\r\n private static final String KEY_PREFIX_ADDON_UPLOAD = \"addon-upload-\";\r\n\r\n private static final String LOG_FILE = \"waraddonclient.log\";\r\n\r\n private static final String LINUX_LOG_FILE = \"/var/log/waraddonclient.log\";\r\n\r\n private static final String ADDON_FOLDER = \"/Interface/AddOns/\";\r\n\r\n private static final String LOGS = \"/logs/\";\r\n\r\n private static final String BASE_URL = \"https://tools.idrinth.de/\";\r\n\r\n private static final String VERSION_FILE = \"/self.idrinth\";\r\n \r\n private static final String AUTO_BACKUP_ON_UPDATE_ALL = \"auto-update.on.update-all\";\r\n\r\n private final Preferences prefs = Preferences.userNodeForPackage(Main.class);\r\n\r\n private final String version;\r\n\r\n private final File logFile;\r\n\r\n private final File jarDir;\r\n\r\n public Config() throws IOException, URISyntaxException {\r\n //check to look for old conf\r\n if (prefs.get(KEY_THEME, \"missing\").equals(\"missing\")) {\r\n Preferences oldPref = Preferences.userRoot().node(Config.class.getCanonicalName());\r\n prefs.put(KEY_THEME, oldPref.get(KEY_THEME, getTheme()));\r\n prefs.put(KEY_WAR_PATH, oldPref.get(KEY_WAR_PATH, getWARPath()));\r\n prefs.put(KEY_LANGUAGE, oldPref.get(KEY_LANGUAGE, getLanguage()));\r\n prefs.putInt(KEY_WINDOW_HEIGHT, oldPref.getInt(KEY_WINDOW_HEIGHT, getWindowDimension().height));\r\n prefs.putInt(KEY_WINDOW_WIDTH, oldPref.getInt(KEY_WINDOW_WIDTH, getWindowDimension().width));\r\n prefs.putInt(KEY_WINDOW_LOCATION_X, oldPref.getInt(KEY_WINDOW_LOCATION_X, getWindowPosition().x));\r\n prefs.putInt(KEY_WINDOW_LOCATION_Y, oldPref.getInt(KEY_WINDOW_LOCATION_Y, getWindowPosition().y));\r\n //cleanup and remove old preferences as we have now extracted all info from it\r\n try {\r\n oldPref.removeNode();\r\n oldPref.flush();\r\n } catch (BackingStoreException e) {\r\n //do nothing\r\n }\r\n }\r\n version = IOUtils.toString(Objects.requireNonNull(Config.class.getResourceAsStream(\"/version\")), StandardCharsets.UTF_8);\r\n jarDir = new File(Main.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()).getParentFile();\r\n if (System.getProperty(\"os.name\").startsWith(\"Windows\")) {\r\n logFile = new File(jarDir.getAbsolutePath(), LOG_FILE);\r\n } else {\r\n logFile = new File(LINUX_LOG_FILE);\r\n }\r\n }\r\n\r\n public void setWARPath(String path) {\r\n prefs.put(KEY_WAR_PATH, path);\r\n }\r\n\r\n public String getWARPath() {\r\n return prefs.get(KEY_WAR_PATH, \".\");\r\n }\r\n\r\n public String getTheme() {\r\n return prefs.get(KEY_THEME, \"Nimbus\");\r\n }\r\n\r\n public void setTheme(String theme) {\r\n prefs.put(KEY_THEME, theme);\r\n }\r\n\r\n public String getLanguage() {\r\n return prefs.get(KEY_LANGUAGE, \"en\");\r\n }\r\n\r\n public void setLanguage(String language) {\r\n prefs.put(KEY_LANGUAGE, language);\r\n }\r\n\r\n public int getAutoClose() {\r\n return prefs.getInt(KEY_AUTO_CLOSE, 60);\r\n }\r\n\r\n public void setAutoClose(int autoClose) {\r\n prefs.putInt(KEY_AUTO_CLOSE, autoClose);\r\n }\r\n\r\n public void setWindowDimension(Dimension dimension) {\r\n prefs.putInt(KEY_WINDOW_WIDTH, dimension.width);\r\n prefs.putInt(KEY_WINDOW_HEIGHT, dimension.height);\r\n }\r\n\r\n public Dimension getWindowDimension() {\r\n return new Dimension(\r\n prefs.getInt(KEY_WINDOW_WIDTH, 800),\r\n prefs.getInt(KEY_WINDOW_HEIGHT, 450)\r\n );\r\n }\r\n\r\n public void setWindowPosition(Point point) {\r\n prefs.putInt(KEY_WINDOW_LOCATION_X, point.x);\r\n prefs.putInt(KEY_WINDOW_LOCATION_Y, point.y);\r\n }\r\n\r\n public Point getWindowPosition() {\r\n return new Point(\r\n prefs.getInt(KEY_WINDOW_LOCATION_X, 0),\r\n prefs.getInt(KEY_WINDOW_LOCATION_Y, 0)\r\n );\r\n }\r\n\r\n public void setProgressDimension(Dimension dimension) {\r\n prefs.putInt(KEY_PROGRESS_WIDTH, dimension.width);\r\n prefs.putInt(KEY_PROGRESS_HEIGHT, dimension.height);\r\n }\r\n\r\n public Dimension getProgressDimension() {\r\n return new Dimension(\r\n prefs.getInt(KEY_PROGRESS_WIDTH, 300),\r\n prefs.getInt(KEY_PROGRESS_HEIGHT, 150)\r\n );\r\n }\r\n\r\n public void setProgressPosition(Point point) {\r\n prefs.putInt(KEY_PROGRESS_LOCATION_X, point.x);\r\n prefs.putInt(KEY_PROGRESS_LOCATION_Y, point.y);\r\n }\r\n\r\n public Point getProgressPosition() {\r\n return new Point(\r\n prefs.getInt(KEY_PROGRESS_LOCATION_X, 0),\r\n prefs.getInt(KEY_PROGRESS_LOCATION_Y, 0)\r\n );\r\n }\r\n\r\n public String getVersion() {\r\n return version;\r\n }\r\n\r\n public boolean isEnabled(String addon) {\r\n return prefs.getBoolean(KEY_PREFIX_ADDON_UPLOAD + addon, false);\r\n }\r\n\r\n public void setEnabled(String addon, boolean enable) {\r\n prefs.putBoolean(KEY_PREFIX_ADDON_UPLOAD + addon, enable);\r\n }\r\n\r\n public File getLogFile() {\r\n return logFile;\r\n }\r\n\r\n public String getAddonFolder() {\r\n return getWARPath() + ADDON_FOLDER;\r\n }\r\n\r\n public String getLogsFolder() {\r\n return getWARPath() + LOGS;\r\n }\r\n\r\n public String getURL() {\r\n return BASE_URL;\r\n }\r\n \r\n public File getJarDir() {\r\n return jarDir;\r\n }\r\n\r\n public String getVersionFile() {\r\n return VERSION_FILE;\r\n }\r\n\r\n public int getAutoBackupOnUpdateAll() {\r\n return prefs.getInt(AUTO_BACKUP_ON_UPDATE_ALL, 2);\r\n }\r\n\r\n public void setAutoBackupOnUpdateAll(int choice) {\r\n prefs.putInt(AUTO_BACKUP_ON_UPDATE_ALL, choice);\r\n }\r\n}\r",
"public interface ProgressReporter\r\n{\r\n void incrementCurrent();\r\n\r\n void incrementMax(int amount);\r\n\r\n void start(String title, Runnable callback);\r\n\r\n void stop();\r\n}\r",
"public abstract class BaseLogger {\r\n protected static final String LEVEL_INFO = \"INFO\";\r\n\r\n protected static final String LEVEL_ERROR = \"ERROR\";\r\n\r\n protected static final String LEVEL_WARNING = \"WARN\";\r\n\r\n protected abstract void log(String message, String severity);\r\n\r\n public void info(Throwable message) {\r\n info(message.getLocalizedMessage());\r\n }\r\n\r\n public void info(String message) {\r\n log(message, LEVEL_INFO);\r\n }\r\n\r\n public void warn(Throwable message) {\r\n warn(message.getLocalizedMessage());\r\n }\r\n\r\n public void warn(String message) {\r\n log(message, LEVEL_WARNING);\r\n }\r\n\r\n public void error(Throwable message) {\r\n error(message.getLocalizedMessage());\r\n }\r\n\r\n public void error(String message) {\r\n log(message, LEVEL_ERROR);\r\n }\r\n}\r",
"public class Request {\n\n private volatile boolean requestActive;\n\n private org.apache.http.impl.client.CloseableHttpClient client;\n\n private final javax.net.ssl.SSLContext sslContext;\n\n private final BaseLogger logger;\n \n private final Config config;\n\n public Request(TrustManager manager, BaseLogger logger, Config config) throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {\n this.logger = logger;\n this.config = config;\n sslContext = org.apache.http.ssl.SSLContextBuilder.create().loadTrustMaterial(\n manager.getKeyStore(),\n manager\n ).build();\n }\n\n public javax.json.JsonArray getAddonList() throws IOException {\n HttpResponse response = executionHandler(new HttpGet(config.getURL() + \"addon-api2/\"));\n JsonReader reader = Json.createReader(response.getEntity().getContent());\n JsonArray data = reader.readArray();\n reader.close();\n client.close();\n return data;\n }\n\n public JsonObject getAddon(String slug) throws IOException {\n HttpResponse response = executionHandler(new HttpGet(config.getURL() + \"addon-api2/\"+slug+\"/\"));\n JsonReader reader = Json.createReader(response.getEntity().getContent());\n JsonObject data = reader.readObject();\n reader.close();\n client.close();\n return data;\n }\n\n public java.io.InputStream getAddonDownload(String url) throws IOException {\n org.apache.http.HttpResponse response = executionHandler(new org.apache.http.client.methods.HttpGet(config.getURL() + \"addons/\" + url));\n return response.getEntity().getContent();\n }\n\n private synchronized org.apache.http.HttpResponse executionHandler(org.apache.http.client.methods.HttpRequestBase uri) throws IOException {\n uri.setConfig(org.apache.http.client.config.RequestConfig.DEFAULT);\n uri.setHeader(\"User-Agent\", \"IdrinthsWARAddonClient/\" + config.getVersion());\n uri.setHeader(\"Cache-Control\", \"no-cache\");\n while (requestActive) {\n Utils.sleep(150, logger);\n }\n requestActive = true;\n client = org.apache.http.impl.client.HttpClientBuilder.create()\n .useSystemProperties()\n .setSSLContext(sslContext)\n .build();\n org.apache.http.HttpResponse response = client.execute(uri);\n if (response.getStatusLine().getStatusCode() < 200 || response.getStatusLine().getStatusCode() > 299) {\n requestActive = false;\n throw new java.net.ConnectException(response.getStatusLine().getReasonPhrase());\n }\n requestActive = false;\n return response;\n }\n\n public void upload(String url, File file) {\n org.apache.http.client.methods.HttpPost request = new org.apache.http.client.methods.HttpPost(url);\n request.setEntity(new org.apache.http.entity.FileEntity(file));\n try {\n executionHandler(request);\n client.close();\n } catch (IOException exception) {\n logger.error(exception);\n }\n }\n\n public String getVersion()\n {\n try {\n HttpGet request = new HttpGet(\"https://api.github.com/repos/Idrinth/WARAddonClient/releases/latest\");\n HttpResponse response = executionHandler(request);\n JsonObject data;\n try (JsonReader reader = Json.createReader(response.getEntity().getContent())) {\n data = reader.readObject();\n }\n String version = data.getString(\"tag_name\");\n client.close();\n return version;\n } catch (IOException exception) {\n return \"unknown\";\n }\n }\n}",
"public class SilencingErrorHandler implements ErrorHandler {\r\n private final BaseLogger logger;\r\n\r\n public SilencingErrorHandler(BaseLogger logger) {\r\n this.logger = logger;\r\n }\r\n\r\n @Override\r\n public void warning(SAXParseException exception) {\r\n logger.info(exception);\r\n }\r\n\r\n @Override\r\n public void error(SAXParseException exception) {\r\n logger.warn(exception);\r\n }\r\n\r\n @Override\r\n public void fatalError(SAXParseException exception) throws SAXException {\r\n throw new SAXException(exception);\r\n }\r\n}\r",
"public class XmlParser {\r\n\r\n private final DocumentBuilder builder;\r\n\r\n public XmlParser() throws ParserConfigurationException {\r\n DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();\r\n factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, \"\");\r\n factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, \"\");\r\n factory.setAttribute(XMLConstants.FEATURE_SECURE_PROCESSING, true);\r\n builder = factory.newDocumentBuilder();\r\n }\r\n\r\n public Document parse(File input) throws SAXException, IOException {\r\n return builder.parse(input);\r\n }\r\n\r\n public Document parse(File input, ErrorHandler handler) throws SAXException, IOException {\r\n builder.setErrorHandler(handler);\r\n return builder.parse(input);\r\n }\r\n}\r"
] | import de.idrinth.waraddonclient.Utils;
import de.idrinth.waraddonclient.model.InvalidArgumentException;
import de.idrinth.waraddonclient.service.Config;
import de.idrinth.waraddonclient.service.ProgressReporter;
import de.idrinth.waraddonclient.service.logger.BaseLogger;
import de.idrinth.waraddonclient.service.Request;
import de.idrinth.waraddonclient.service.SilencingErrorHandler;
import de.idrinth.waraddonclient.service.XmlParser;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.Executor;
import javax.xml.parsers.FactoryConfigurationError;
import org.apache.commons.io.FilenameUtils;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
| package de.idrinth.waraddonclient.model.addon;
public class UnknownAddon implements Addon {
private boolean hasSettings = false;
private String file = "";
private String reason = "";
private String url = "";
private String name;
private String installed = "-";
private final Request client;
private final BaseLogger logger;
private final XmlParser parser;
private final Config config;
private final File folder;
private String defaultDescription = "";
private final Executor runner;
public UnknownAddon(File folder, Request client, BaseLogger logger, XmlParser parser, Config config, Executor runner) throws InvalidArgumentException {
this.client = client;
this.logger = logger;
this.parser = parser;
this.config = config;
this.folder = folder;
this.runner = runner;
if (new File(folder.getAbsolutePath() + config.getVersionFile()).exists()) {
throw new InvalidArgumentException("Folder is known Add-On folder.");
}
for (java.io.File fileEntry : folder.listFiles()) {
if (!fileEntry.isDirectory() && FilenameUtils.getExtension(fileEntry.getName()).equalsIgnoreCase("mod")) {
try {
Document doc = parser.parse(fileEntry, new SilencingErrorHandler(logger));
NodeList list = doc.getElementsByTagName("UiMod");
installed = list.item(0).getAttributes().getNamedItem("version").getTextContent();
name = list.item(0).getAttributes().getNamedItem("name").getTextContent();
NodeList description = doc.getElementsByTagName("Description");
if (description.getLength() > 0) {
defaultDescription = description.item(0).getAttributes().getNamedItem("text").getTextContent();
}
} catch (FactoryConfigurationError | SAXException | IOException exception) {
logger.warn(exception);
}
}
}
if (name == null) {
throw new InvalidArgumentException("Folder is no Add-On folder.");
}
refresh();
}
@Override
public ArrayList<String> getTags() {
ArrayList <String> list = new ArrayList<>();
list.add("Not Tagged");
list.add("Auto-Discovered");
return list;
}
public boolean hasTag(String tag) {
return "Not Tagged".equals(tag) || "Auto-Discovered".equals(tag);
}
public String getVersion() {
return "unknown";
}
public String getInstalled() {
return installed;
}
/**
* get the table row configuration for this addon
*
* @return String[[
*/
public Object[] getTableRow() {
Object[] row = new Object[6];
row[0] = this.getStatus();
row[1] = this.name;
row[2] = getVersion();
row[3] = this.installed;
row[4] = 0;
row[5] = 0;
return row;
}
public String getDescription(String language) {
return "<p><strong>There is currently no Description for " + name + ".</strong></p>"
+ "<p>You can help by adding the addon and one at <a href=\"http://tools.idrinth.de/addons/\">http://tools.idrinth.de/addons/</a>.</p>"
+ "<p>"+defaultDescription+"</p>";
}
public HashMap<String, String> getDescriptions() {
return new HashMap<>();
}
public String getName() {
return name;
}
| public void uninstall(ProgressReporter reporter) {
| 3 |
grt192/grtframework | src/sensor/base/GRTDriverStation.java | [
"public abstract class Sensor extends GRTLoggedProcess {\n\n //Constants\n public static final double TRUE = 1.0;\n public static final double FALSE = 0.0;\n public static final double ERROR = Double.NaN;\n //Instance variables\n private final Vector stateChangeListeners; //Collection of things that listen to this sensor\n private double[] data;\n\n /**\n * Constructs a sensor that doesn't poll.\n *\n * @param name name of sensor.\n * @param numData number of pieces of data.\n */\n public Sensor(String name, int numData) {\n this(name, -1, numData);\n }\n\n /**\n * Construct a polling sensor. Subclasses need to start themselves--make a\n * call to startPolling();\n *\n * @param name name of the sensor.\n * @param sleepTime time between polls [ms].\n * @param numData number of pieces of data.\n */\n public Sensor(String name, int sleepTime, int numData) {\n super(name, sleepTime);\n stateChangeListeners = new Vector();\n running = true;\n data = new double[numData];\n }\n\n /**\n * Stores a datum, and notifies listeners if the state of it has changed.\n *\n * @param id key of the data\n * @param datum fresh datum\n */\n protected void setState(int id, double datum) {\n double previous = data[id];\n //notify self and state change listeners if the datum has changed\n if (previous != datum) {\n notifyStateChange(id, datum);\n }\n data[id] = datum;\n }\n\n /**\n * Retrieves sensor data.\n *\n * @param id numeric identifier of data.\n * @return representative sensor data.\n */\n public double getState(int id) {\n if (id >= data.length || id < 0) {\n return ERROR;\n }\n return data[id];\n }\n\n /**\n * Returns the number of different data stored by this sensor.\n *\n * @return number of data.\n */\n public int numData() {\n return data.length;\n }\n\n /**\n * Enables listening. Sensors need not listen to events, however.\n */\n protected void startListening() {\n }\n\n /**\n * Disables listening. Sensors need not listen to events, however.\n */\n protected void stopListening() {\n }\n\n public void enable() {\n //enable() always works because a Sensor is always running\n super.enable();\n startListening();\n }\n\n public void disable() {\n super.disable();\n stopListening();\n }\n\n /**\n * Calls the listener events based on what has changed\n *\n * @param id the key of the data that changed\n * @param newDatum the datum's new value\n */\n protected abstract void notifyListeners(int id, double newDatum);\n\n protected void notifyStateChange(int id, double newDatum) {\n notifyListeners(id, newDatum);\n SensorEvent e = new SensorEvent(this, id, newDatum);\n for (Enumeration en = stateChangeListeners.elements(); en.hasMoreElements();) {\n ((SensorChangeListener) en.nextElement()).sensorStateChanged(e);\n }\n }\n\n /**\n * Adds a sensor state change listener.\n *\n * @param l state change listener to add.\n */\n public void addSensorStateChangeListener(SensorChangeListener l) {\n stateChangeListeners.addElement(l);\n }\n\n /**\n * Removes a sensor state change listener.\n *\n * @param l state change listener to remove.\n */\n public void removeSensorStateChangeListener(SensorChangeListener l) {\n stateChangeListeners.removeElement(l);\n }\n}",
"public class DrivingEvent extends SensorEvent {\n\n public static final int SIDE_LEFT = 0;\n public static final int SIDE_RIGHT = 1;\n\n /**\n * Creates a new DrivingEvent.\n *\n * @param source source of event\n * @param sideID left or right side\n * @param value the speed of that side\n */\n public DrivingEvent(GRTDriverStation source, int sideID, double value) {\n super(source, sideID, value);\n }\n\n /**\n * Whether or not this is a left side event or a right side event.\n *\n * @return DrivingEvent.SIDE_LEFT or DrivingEvent.SIDE_RIGHT\n */\n public int getSide() {\n return getID();\n }\n\n /**\n * Returns the speed specified by this event.\n *\n * @return speed of side, as number from -1 to 1\n */\n public double getSpeed() {\n return getData();\n }\n}",
"public class ShiftEvent extends SensorEvent {\n\n public static final int KEY_SHIFT_UP = 1;\n public static final int KEY_SHIFT_DOWN = 0;\n public static final int SIDE_LEFT = 0;\n public static final int SIDE_RIGHT = 1;\n\n /**\n * Creates a new ShiftEvent.\n *\n * @param source source of event\n * @param sideID left or right side\n * @param shiftDirection the key indicating shift up or down\n */\n public ShiftEvent(GRTDriverStation source, int sideID, double shiftDirection) {\n super(source, sideID, shiftDirection);\n }\n\n /**\n * Whether or not this is a left side event or a right side event.\n *\n * @return ShiftEvent.SIDE_LEFT or ShiftEvent.SIDE_RIGHT\n */\n public int getSide() {\n return getID();\n }\n\n /**\n * Returns the speed specified by this event.\n *\n * @return speed of side, as number from -1 to 1\n */\n public double getShiftDirection() {\n return getData();\n }\n}",
"public interface DrivingListener {\n\n /**\n * Called to set speed of left drivetrain.\n *\n * @param e event specifying left side speed\n */\n public void driverLeftSpeed(DrivingEvent e);\n\n /**\n * Called to set speed of right drivetrain.\n *\n * @param e event specifying right side speed\n */\n public void driverRightSpeed(DrivingEvent e);\n}",
"public interface ShiftListener {\r\n\r\n /**\r\n * Called to set shift drivetrain. \r\n *\r\n * @param e event specifying shifter and direction\r\n */\r\n public void shift(ShiftEvent e);\r\n\r\n}\r"
] | import core.Sensor;
import event.events.DrivingEvent;
import event.events.ShiftEvent;
import event.listeners.DrivingListener;
import event.listeners.ShiftListener;
import java.util.Enumeration;
import java.util.Vector; | package sensor.base;
/**
* Superclass for all DriverStations.
*
* @author ajc
*/
public abstract class GRTDriverStation extends Sensor {
/*
* State Keys
*/
public static final int KEY_LEFT_VELOCITY = 0;
public static final int KEY_RIGHT_VELOCITY = 1;
public static final int KEY_LEFT_SHIFT = 2;
public static final int KEY_RIGHT_SHIFT = 3;
private final Vector drivingListeners;
private final Vector shiftListeners;
/**
* Creates a new driver station.
*
* @param name name of driver station.
*/
public GRTDriverStation(String name) {
super(name, 2);
drivingListeners = new Vector();
shiftListeners = new Vector();
}
public void addDrivingListener(DrivingListener l) {
drivingListeners.addElement(l);
}
public void removeDrivingListener(DrivingListener l) {
drivingListeners.removeElement(l);
}
public void addShiftListener(ShiftListener l) {
shiftListeners.addElement(l);
}
public void removeShiftListener(ShiftListener l) {
shiftListeners.removeElement(l);
}
protected void notifyLeftDriveSpeed(double speed) {
setState(KEY_LEFT_VELOCITY, speed);
}
protected void notifyRightDriveSpeed(double speed) {
setState(KEY_RIGHT_VELOCITY, speed);
}
protected void notifyListeners(int id, double newValue) {
DrivingEvent ev; | ShiftEvent sev; | 2 |
taoneill/war | war/src/main/java/com/tommytony/war/command/SetCapturePointCommand.java | [
"public class War extends JavaPlugin {\n\tstatic final boolean HIDE_BLANK_MESSAGES = true;\n\tpublic static War war;\n\tprivate static ResourceBundle messages = ResourceBundle.getBundle(\"messages\");\n\tprivate final List<OfflinePlayer> zoneMakerNames = new ArrayList<>();\n\tprivate final List<String> commandWhitelist = new ArrayList<String>();\n\tprivate final List<Warzone> incompleteZones = new ArrayList<Warzone>();\n\tprivate final List<OfflinePlayer> zoneMakersImpersonatingPlayers = new ArrayList<>();\n\tprivate final HashMap<String, String> wandBearers = new HashMap<String, String>(); // playername to zonename\n\tprivate final List<String> deadlyAdjectives = new ArrayList<String>();\n\tprivate final List<String> killerVerbs = new ArrayList<String>();\n\tprivate final InventoryBag defaultInventories = new InventoryBag();\n\tprivate final WarConfigBag warConfig = new WarConfigBag();\n\tprivate final WarzoneConfigBag warzoneDefaultConfig = new WarzoneConfigBag();\n\tprivate final TeamConfigBag teamDefaultConfig = new TeamConfigBag();\n\t// general\n\tprivate WarPlayerListener playerListener = new WarPlayerListener();\n\tprivate WarEntityListener entityListener = new WarEntityListener();\n\tprivate WarBlockListener blockListener = new WarBlockListener();\n\tprivate WarCommandHandler commandHandler = new WarCommandHandler();\n\tprivate PluginDescriptionFile desc = null;\n\tprivate boolean loaded = false;\n\t// Zones and hub\n\tprivate List<Warzone> warzones = new ArrayList<Warzone>();\n\tprivate WarHub warHub;\n\tprivate HashMap<String, PlayerState> disconnected = new HashMap<String, PlayerState>();\n\tprivate KillstreakReward killstreakReward;\n\tprivate MySQLConfig mysqlConfig;\n\tprivate Economy econ = null;\n\tprivate HubLobbyMaterials warhubMaterials = new HubLobbyMaterials(\n\t\t\tnew ItemStack(Material.GLASS), new ItemStack(Material.OAK_WOOD),\n\t\t\tnew ItemStack(Material.OBSIDIAN), new ItemStack(Material.GLOWSTONE));\n\tprivate UIManager UIManager;\n\n\tpublic War() {\n\t\tsuper();\n\t\tWar.war = this;\n\t}\n\n\tpublic static void reloadLanguage() {\n\t\tString[] parts = War.war.getWarConfig().getString(WarConfig.LANGUAGE).replace(\"-\", \"_\").split(\"_\");\n\t\tLocale lang = new Locale(parts[0]);\n\t\tif (parts.length >= 2) {\n\t\t\tlang = new Locale(parts[0], parts[1]);\n\t\t}\n\t\tWar.messages = ResourceBundle.getBundle(\"messages\", lang);\n\t}\n\n\t/**\n\t * @see JavaPlugin#onEnable()\n\t * @see War#loadWar()\n\t */\n\tpublic void onEnable() {\n\t\tthis.loadWar();\n\t}\n\n\t/**\n\t * @see JavaPlugin#onDisable()\n\t * @see War#unloadWar()\n\t */\n\tpublic void onDisable() {\n\t\tthis.unloadWar();\n\t}\n\n\t/**\n\t * Initializes war\n\t */\n\tpublic void loadWar() {\n\t\tthis.setLoaded(true);\n\t\tthis.desc = this.getDescription();\n\n\t\ttry {\n\t\t\tClass.forName(\"org.sqlite.JDBC\").newInstance();\n\t\t} catch (Exception e) {\n\t\t\tthis.log(\"SQLite3 driver not found!\", Level.SEVERE);\n\t\t\tthis.getServer().getPluginManager().disablePlugin(this);\n\t\t\treturn;\n\t\t}\n\t\tthis.UIManager = new UIManager(this);\n\n\t\t// Register events\n\t\tPluginManager pm = this.getServer().getPluginManager();\n\t\tpm.registerEvents(this.playerListener, this);\n\t\tpm.registerEvents(this.entityListener, this);\n\t\tpm.registerEvents(this.blockListener, this);\n\t\tpm.registerEvents(this.UIManager, this);\n\n\t\t// Add defaults\n\t\twarConfig.put(WarConfig.BUILDINZONESONLY, false);\n\t\twarConfig.put(WarConfig.DISABLEBUILDMESSAGE, false);\n\t\twarConfig.put(WarConfig.DISABLEPVPMESSAGE, false);\n\t\twarConfig.put(WarConfig.KEEPOLDZONEVERSIONS, true);\n\t\twarConfig.put(WarConfig.MAXZONES, 12);\n\t\twarConfig.put(WarConfig.PVPINZONESONLY, false);\n\t\twarConfig.put(WarConfig.TNTINZONESONLY, false);\n\t\twarConfig.put(WarConfig.RESETSPEED, 5000);\n\t\twarConfig.put(WarConfig.MAXSIZE, 750);\n\t\twarConfig.put(WarConfig.LANGUAGE, Locale.getDefault().toString());\n\t\twarConfig.put(WarConfig.AUTOJOIN, \"\");\n\t\twarConfig.put(WarConfig.TPWARMUP, 0);\n\t\twarConfig.put(WarConfig.DISABLECOOLDOWN, false);\n\n\t\twarzoneDefaultConfig.put(WarzoneConfig.AUTOASSIGN, false);\n\t\twarzoneDefaultConfig.put(WarzoneConfig.BLOCKHEADS, true);\n\t\twarzoneDefaultConfig.put(WarzoneConfig.DISABLED, false);\n\t\twarzoneDefaultConfig.put(WarzoneConfig.FRIENDLYFIRE, false);\n\t\twarzoneDefaultConfig.put(WarzoneConfig.GLASSWALLS, true);\n\t\twarzoneDefaultConfig.put(WarzoneConfig.INSTABREAK, false);\n\t\twarzoneDefaultConfig.put(WarzoneConfig.MINPLAYERS, 1);\n\t\twarzoneDefaultConfig.put(WarzoneConfig.MINTEAMS, 1);\n\t\twarzoneDefaultConfig.put(WarzoneConfig.MONUMENTHEAL, 5);\n\t\twarzoneDefaultConfig.put(WarzoneConfig.NOCREATURES, false);\n\t\twarzoneDefaultConfig.put(WarzoneConfig.NODROPS, false);\n\t\twarzoneDefaultConfig.put(WarzoneConfig.PVPINZONE, true);\n\t\twarzoneDefaultConfig.put(WarzoneConfig.REALDEATHS, false);\n\t\twarzoneDefaultConfig.put(WarzoneConfig.RESETONEMPTY, false);\n\t\twarzoneDefaultConfig.put(WarzoneConfig.RESETONCONFIGCHANGE, false);\n\t\twarzoneDefaultConfig.put(WarzoneConfig.RESETONLOAD, false);\n\t\twarzoneDefaultConfig.put(WarzoneConfig.RESETONUNLOAD, false);\n\t\twarzoneDefaultConfig.put(WarzoneConfig.UNBREAKABLE, false);\n\t\twarzoneDefaultConfig.put(WarzoneConfig.DEATHMESSAGES, true);\n\t\twarzoneDefaultConfig.put(WarzoneConfig.JOINMIDBATTLE, true);\n\t\twarzoneDefaultConfig.put(WarzoneConfig.AUTOJOIN, false);\n\t\twarzoneDefaultConfig.put(WarzoneConfig.SCOREBOARD, ScoreboardType.NONE);\n\t\twarzoneDefaultConfig.put(WarzoneConfig.SOUPHEALING, false);\n\t\twarzoneDefaultConfig.put(WarzoneConfig.ALLOWENDER, true);\n\t\twarzoneDefaultConfig.put(WarzoneConfig.RESETBLOCKS, true);\n\t\twarzoneDefaultConfig.put(WarzoneConfig.CAPTUREPOINTTIME, 15);\n\t\twarzoneDefaultConfig.put(WarzoneConfig.PREPTIME, 0);\n\n\t\tteamDefaultConfig.put(TeamConfig.FLAGMUSTBEHOME, true);\n\t\tteamDefaultConfig.put(TeamConfig.FLAGPOINTSONLY, false);\n\t\tteamDefaultConfig.put(TeamConfig.FLAGRETURN, FlagReturn.BOTH);\n\t\tteamDefaultConfig.put(TeamConfig.LIFEPOOL, 7);\n\t\tteamDefaultConfig.put(TeamConfig.MAXSCORE, 10);\n\t\tteamDefaultConfig.put(TeamConfig.NOHUNGER, false);\n\t\tteamDefaultConfig.put(TeamConfig.PLAYERLOADOUTASDEFAULT, false);\n\t\tteamDefaultConfig.put(TeamConfig.RESPAWNTIMER, 0);\n\t\tteamDefaultConfig.put(TeamConfig.SATURATION, 10);\n\t\tteamDefaultConfig.put(TeamConfig.SPAWNSTYLE, TeamSpawnStyle.SMALL);\n\t\tteamDefaultConfig.put(TeamConfig.TEAMSIZE, 10);\n\t\tteamDefaultConfig.put(TeamConfig.PERMISSION, \"war.player\");\n\t\tteamDefaultConfig.put(TeamConfig.XPKILLMETER, false);\n\t\tteamDefaultConfig.put(TeamConfig.KILLSTREAK, false);\n\t\tteamDefaultConfig.put(TeamConfig.BLOCKWHITELIST, \"all\");\n\t\tteamDefaultConfig.put(TeamConfig.PLACEBLOCK, true);\n\t\tteamDefaultConfig.put(TeamConfig.APPLYPOTION, \"\");\n\t\tteamDefaultConfig.put(TeamConfig.ECOREWARD, 0.0);\n\t\tteamDefaultConfig.put(TeamConfig.INVENTORYDROP, false);\n\t\tteamDefaultConfig.put(TeamConfig.BORDERDROP, false);\n\n\t\tthis.getDefaultInventories().clearLoadouts();\n\t\tHashMap<Integer, ItemStack> defaultLoadout = new HashMap<Integer, ItemStack>();\n\n\t\tItemStack stoneSword = Compat.createDamagedIS(Material.STONE_SWORD, 1, (byte) 8);\n\t\tdefaultLoadout.put(0, stoneSword);\n\n\t\tItemStack bow = Compat.createDamagedIS(Material.BOW, 1, (byte) 8);\n\t\tdefaultLoadout.put(1, bow);\n\n\t\tItemStack arrows = new ItemStack(Material.ARROW, 7);\n\t\tdefaultLoadout.put(2, arrows);\n\n\t\tItemStack stonePick = Compat.createDamagedIS(Material.IRON_PICKAXE, 1, (byte) 8);\n\t\tdefaultLoadout.put(3, stonePick);\n\n\t\tItemStack stoneSpade = Compat.createDamagedIS(Material.STONE_SHOVEL, 1, (byte) 8);\n\t\tdefaultLoadout.put(4, stoneSpade);\n\n\t\tthis.getDefaultInventories().addLoadout(\"default\", defaultLoadout);\n\n\t\tHashMap<Integer, ItemStack> reward = new HashMap<Integer, ItemStack>();\n\t\treward.put(0, new ItemStack(Material.CAKE, 1));\n\t\tthis.getDefaultInventories().setReward(reward);\n\n\t\tthis.getCommandWhitelist().add(\"who\");\n\t\tthis.setKillstreakReward(new KillstreakReward());\n\t\tthis.setMysqlConfig(new MySQLConfig());\n\n\t\t// Add constants\n\t\tthis.getDeadlyAdjectives().clear();\n\t\tfor (String adjective : this.getString(\"pvp.kill.adjectives\").split(\";\")) {\n\t\t\tthis.getDeadlyAdjectives().add(adjective);\n\t\t}\n\t\tthis.getKillerVerbs().clear();\n\t\tfor (String verb : this.getString(\"pvp.kill.verbs\").split(\";\")) {\n\t\t\tthis.getKillerVerbs().add(verb);\n\t\t}\n\n\t\t// Load files\n\t\tWarYmlMapper.load();\n\n\t\t// Start tasks\n\t\tHelmetProtectionTask helmetProtectionTask = new HelmetProtectionTask();\n\t\tthis.getServer().getScheduler().scheduleSyncRepeatingTask(this, helmetProtectionTask, 250, 100);\n\n\t\tCapturePointTimer cpt = new CapturePointTimer();\n\t\tcpt.runTaskTimer(this, 100, 20);\n\t\tScoreboardSwitchTimer sst = new ScoreboardSwitchTimer();\n\t\tsst.runTaskTimer(this, 500, 20 * 60);\n\n\t\tif (this.mysqlConfig.isEnabled()) {\n\t\t\ttry {\n\t\t\t\tClass.forName(\"com.mysql.jdbc.Driver\").newInstance();\n\t\t\t} catch (Exception ex) {\n\t\t\t\tthis.log(\"MySQL driver not found!\", Level.SEVERE);\n\t\t\t\tthis.getServer().getPluginManager().disablePlugin(this);\n\t\t\t}\n\t\t}\n\t\tif (this.getServer().getPluginManager().isPluginEnabled(\"Vault\")) {\n\t\t\tRegisteredServiceProvider<Economy> rsp = this.getServer().getServicesManager()\n\t\t\t\t.getRegistration(Economy.class);\n\t\t\tif (rsp != null) {\n\t\t\t\tthis.econ = rsp.getProvider();\n\t\t\t}\n\t\t}\n\n\t\tWar.reloadLanguage();\n\n\t\t// Get own log file\n\t\ttry {\n\t\t\t// Create an appending file handler\n\t\t\tnew File(this.getDataFolder() + \"/temp/\").mkdir();\n\t\t\tFileHandler handler = new FileHandler(this.getDataFolder() + \"/temp/war.log\", true);\n\n\t\t\t// Add to War-specific logger\n\t\t\tFormatter formatter = new WarLogFormatter();\n\t\t\thandler.setFormatter(formatter);\n\t\t\tthis.getLogger().addHandler(handler);\n\t\t} catch (IOException e) {\n\t\t\tthis.getLogger().log(Level.WARNING, \"Failed to create War log file\");\n\t\t}\n\n\t\t// Size check\n\t\tlong datSize = SizeCounter.getFileOrDirectorySize(new File(this.getDataFolder() + \"/dat/\")) / 1024 / 1024;\n\t\tlong tempSize = SizeCounter.getFileOrDirectorySize(new File(this.getDataFolder() + \"/temp/\")) / 1024 / 1024;\n\n\t\tif (datSize + tempSize > 100) {\n\t\t\tthis.log(\"War data files are taking \" + datSize + \"MB and its temp files \" + tempSize + \"MB. Consider permanently deleting old warzone versions and backups in /plugins/War/temp/.\", Level.WARNING);\n\t\t}\n\n\t\tthis.log(\"War v\" + this.desc.getVersion() + \" is on.\", Level.INFO);\n\t}\n\n\t/**\n\t * Cleans up war\n\t */\n\tpublic void unloadWar() {\n\t\tfor (Warzone warzone : this.warzones) {\n\t\t\twarzone.unload();\n\t\t}\n\t\tthis.warzones.clear();\n\n\t\tif (this.warHub != null) {\n\t\t\tthis.warHub.getVolume().resetBlocks();\n\t\t}\n\n\t\tthis.getServer().getScheduler().cancelTasks(this);\n\t\tthis.playerListener.purgeLatestPositions();\n\n\t\tHandlerList.unregisterAll(this);\n\t\tthis.log(\"War v\" + this.desc.getVersion() + \" is off.\", Level.INFO);\n\t\tthis.setLoaded(false);\n\t}\n\n\t/**\n\t * @see org.bukkit.command.CommandExecutor#onCommand(org.bukkit.command.CommandSender, org.bukkit.command.Command, String, String[])\n\t */\n\tpublic boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {\n\t\treturn this.commandHandler.handle(sender, cmd, args);\n\t}\n\n\t/**\n\t * Converts the player-inventory to a loadout hashmap\n\t *\n\t * @param inv\n\t * inventory to get the items from\n\t * @param loadout\n\t * the hashmap to save to\n\t */\n\tprivate void inventoryToLoadout(PlayerInventory inv, HashMap<Integer, ItemStack> loadout) {\n\t\tloadout.clear();\n\t\tint i = 0;\n\t\tfor (ItemStack stack : inv.getStorageContents()) {\n\t\t\tif (stack != null && stack.getType() != Material.AIR) {\n\t\t\t\tloadout.put(i, stack.clone());\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\t\tif (inv.getBoots() != null && inv.getBoots().getType() != Material.AIR) {\n\t\t\tloadout.put(100, inv.getBoots().clone());\n\t\t}\n\t\tif (inv.getLeggings() != null && inv.getLeggings().getType() != Material.AIR) {\n\t\t\tloadout.put(101, inv.getLeggings().clone());\n\t\t}\n\t\tif (inv.getChestplate() != null && inv.getChestplate().getType() != Material.AIR) {\n\t\t\tloadout.put(102, inv.getChestplate().clone());\n\t\t}\n\t\tif (inv.getHelmet() != null && inv.getHelmet().getType() != Material.AIR) {\n\t\t\tloadout.put(103, inv.getHelmet().clone());\n\t\t}\n\t}\n\n\tpublic void safelyEnchant(ItemStack target, Enchantment enchantment, int level) {\n\t\tif (level > enchantment.getMaxLevel()) {\n\t\t\ttarget.addUnsafeEnchantment(enchantment, level);\n\t\t} else {\n\t\t\ttarget.addEnchantment(enchantment, level);\n\t\t}\n\t}\n\n\t/**\n\t * Converts the player-inventory to a loadout hashmap\n\t *\n\t * @param player\n\t * player to get the inventory to get the items from\n\t * @param loadout\n\t * the hashmap to save to\n\t */\n\tprivate void inventoryToLoadout(Player player, HashMap<Integer, ItemStack> loadout) {\n\t\tthis.inventoryToLoadout(player.getInventory(), loadout);\n\t}\n\n\tpublic String updateTeamFromNamedParams(Team team, CommandSender commandSender, String[] arguments) {\n\t\ttry {\n\t\t\tMap<String, String> namedParams = new HashMap<String, String>();\n\t\t\tMap<String, String> thirdParameter = new HashMap<String, String>();\n\t\t\tfor (String namedPair : arguments) {\n\t\t\t\tString[] pairSplit = namedPair.split(\":\");\n\t\t\t\tif (pairSplit.length == 2) {\n\t\t\t\t\tnamedParams.put(pairSplit[0].toLowerCase(), pairSplit[1]);\n\t\t\t\t} else if (pairSplit.length == 3) {\n\t\t\t\t\tnamedParams.put(pairSplit[0].toLowerCase(), pairSplit[1]);\n\t\t\t\t\tthirdParameter.put(pairSplit[0].toLowerCase(), pairSplit[2]);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tStringBuilder returnMessage = new StringBuilder();\n\t\t\treturnMessage.append(team.getTeamConfig().updateFromNamedParams(namedParams));\n\n\t\t\tif (commandSender instanceof Player) {\n\t\t\t\tPlayer player = (Player) commandSender;\n\t\t\t\tif (namedParams.containsKey(\"loadout\")) {\n\t\t\t\t\tString loadoutName = namedParams.get(\"loadout\");\n\t\t\t\t\tHashMap<Integer, ItemStack> loadout = team.getInventories().getLoadout(loadoutName);\n\t\t\t\t\tif (loadout == null) {\n\t\t\t\t\t\t// Check if any loadouts exist, if not gotta use the default inventories then add the newly created one\n\t\t\t\t\t\tif(!team.getInventories().hasLoadouts()) {\n\t\t\t\t\t\t\tWarzone warzone = team.getZone();\n\t\t\t\t\t\t\tfor (String key : warzone.getDefaultInventories().resolveLoadouts().keySet()) {\n\t\t\t\t\t\t\t\tHashMap<Integer, ItemStack> transferredLoadout = warzone.getDefaultInventories().resolveLoadouts().get(key);\n\t\t\t\t\t\t\t\tif (transferredLoadout != null) {\n\t\t\t\t\t\t\t\t\tteam.getInventories().setLoadout(key, transferredLoadout);\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tWar.war.log(\"Failed to transfer loadout \" + key + \" down to team \" + team.getName() + \" in warzone \" + warzone.getName(), Level.WARNING);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tloadout = new HashMap<Integer, ItemStack>();\n\t\t\t\t\t\tteam.getInventories().setLoadout(loadoutName, loadout);\n\t\t\t\t\t\treturnMessage.append(loadoutName + \" respawn loadout added.\");\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturnMessage.append(loadoutName + \" respawn loadout updated.\");\n\t\t\t\t\t}\n\t\t\t\t\tthis.inventoryToLoadout(player, loadout);\n\t\t\t\t\tLoadout ldt = team.getInventories().getNewLoadout(loadoutName);\n\t\t\t\t\tif (thirdParameter.containsKey(\"loadout\")) {\n\t\t\t\t\t\tString permission = thirdParameter.get(\"loadout\");\n\t\t\t\t\t\tldt.setPermission(permission);\n\t\t\t\t\t\treturnMessage.append(' ').append(loadoutName).append(\" respawn loadout permission set to \").append(permission).append('.');\n\t\t\t\t\t} else if (ldt.requiresPermission()) {\n\t\t\t\t\t\tldt.setPermission(null);\n\t\t\t\t\t\treturnMessage.append(' ').append(loadoutName).append(\" respawn loadout permission deleted.\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (namedParams.containsKey(\"deleteloadout\")) {\n\t\t\t\t\tString loadoutName = namedParams.get(\"deleteloadout\");\n\t\t\t\t\tif (team.getInventories().containsLoadout(loadoutName)) {\n\t\t\t\t\t\tteam.getInventories().removeLoadout(loadoutName);\n\t\t\t\t\t\treturnMessage.append(\" \" + loadoutName + \" loadout removed.\");\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturnMessage.append(\" \" + loadoutName + \" loadout not found.\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (namedParams.containsKey(\"reward\")) {\n\t\t\t\t\tHashMap<Integer, ItemStack> reward = new HashMap<Integer, ItemStack>();\n\t\t\t\t\tthis.inventoryToLoadout(player, reward);\n\t\t\t\t\tteam.getInventories().setReward(reward);\n\t\t\t\t\treturnMessage.append(\" game end reward updated.\");\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn returnMessage.toString();\n\t\t} catch (Exception e) {\n\t\t\treturn \"PARSE-ERROR\";\n\t\t}\n\t}\n\n\tpublic String updateZoneFromNamedParams(Warzone warzone, CommandSender commandSender, String[] arguments) {\n\t\ttry {\n\t\t\tMap<String, String> namedParams = new HashMap<String, String>();\n\t\t\tMap<String, String> thirdParameter = new HashMap<String, String>();\n\t\t\tfor (String namedPair : arguments) {\n\t\t\t\tString[] pairSplit = namedPair.split(\":\");\n\t\t\t\tif (pairSplit.length == 2) {\n\t\t\t\t\tnamedParams.put(pairSplit[0].toLowerCase(), pairSplit[1]);\n\t\t\t\t} else if (pairSplit.length == 3) {\n\t\t\t\t\tnamedParams.put(pairSplit[0].toLowerCase(), pairSplit[1]);\n\t\t\t\t\tthirdParameter.put(pairSplit[0].toLowerCase(), pairSplit[2]);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tStringBuilder returnMessage = new StringBuilder();\n\t\t\tif (namedParams.containsKey(\"author\")) {\n\t\t\t\tfor(String author : namedParams.get(\"author\").split(\",\")) {\n\t\t\t\t\tif (!author.equals(\"\") && !warzone.getAuthors().contains(author)) {\n\t\t\t\t\t\twarzone.addAuthor(author);\n\t\t\t\t\t\treturnMessage.append(\" author \" + author + \" added.\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (namedParams.containsKey(\"deleteauthor\")) {\n\t\t\t\tfor(String author : namedParams.get(\"deleteauthor\").split(\",\")) {\n\t\t\t\t\tif (warzone.getAuthors().contains(author)) {\n\t\t\t\t\t\twarzone.getAuthors().remove(author);\n\t\t\t\t\t\treturnMessage.append(\" \" + author + \" removed from zone authors.\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturnMessage.append(warzone.getWarzoneConfig().updateFromNamedParams(namedParams));\n\t\t\treturnMessage.append(warzone.getTeamDefaultConfig().updateFromNamedParams(namedParams));\n\n\t\t\tif (commandSender instanceof Player) {\n\t\t\t\tPlayer player = (Player) commandSender;\n\t\t\t\tif (namedParams.containsKey(\"loadout\")) {\n\t\t\t\t\tString loadoutName = namedParams.get(\"loadout\");\n\t\t\t\t\tHashMap<Integer, ItemStack> loadout = warzone.getDefaultInventories().getLoadout(loadoutName);\n\t\t\t\t\tif (loadout == null) {\n\t\t\t\t\t\tloadout = new HashMap<Integer, ItemStack>();\n\n\t\t\t\t\t\t// Check if any loadouts exist, if not gotta use the default inventories then add the newly created one\n\t\t\t\t\t\tif(!warzone.getDefaultInventories().hasLoadouts()) {\n\t\t\t\t\t\t\tfor (String key : warzone.getDefaultInventories().resolveLoadouts().keySet()) {\n\t\t\t\t\t\t\t\tHashMap<Integer, ItemStack> transferredLoadout = warzone.getDefaultInventories().resolveLoadouts().get(key);\n\t\t\t\t\t\t\t\tif (transferredLoadout != null) {\n\t\t\t\t\t\t\t\t\twarzone.getDefaultInventories().setLoadout(key, transferredLoadout);\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tWar.war.log(\"Failed to transfer loadout \" + key + \" down to warzone \" + warzone.getName(), Level.WARNING);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\twarzone.getDefaultInventories().setLoadout(loadoutName, loadout);\n\t\t\t\t\t\treturnMessage.append(loadoutName).append(\" respawn loadout added.\");\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturnMessage.append(loadoutName).append(\" respawn loadout updated.\");\n\t\t\t\t\t}\n\t\t\t\t\tthis.inventoryToLoadout(player, loadout);\n\t\t\t\t\tLoadout ldt = warzone.getDefaultInventories().getNewLoadout(loadoutName);\n\t\t\t\t\tif (thirdParameter.containsKey(\"loadout\")) {\n\t\t\t\t\t\tString permission = thirdParameter.get(\"loadout\");\n\t\t\t\t\t\tldt.setPermission(permission);\n\t\t\t\t\t\treturnMessage.append(' ').append(loadoutName).append(\" respawn loadout permission set to \").append(permission).append('.');\n\t\t\t\t\t} else if (ldt.requiresPermission()) {\n\t\t\t\t\t\tldt.setPermission(null);\n\t\t\t\t\t\treturnMessage.append(' ').append(loadoutName).append(\" respawn loadout permission deleted.\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (namedParams.containsKey(\"deleteloadout\")) {\n\t\t\t\t\tString loadoutName = namedParams.get(\"deleteloadout\");\n\t\t\t\t\tif (warzone.getDefaultInventories().containsLoadout(loadoutName)) {\n\t\t\t\t\t\twarzone.getDefaultInventories().removeLoadout(loadoutName);\n\t\t\t\t\t\treturnMessage.append(\" \" + loadoutName + \" loadout removed.\");\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturnMessage.append(\" \" + loadoutName + \" loadout not found.\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (namedParams.containsKey(\"reward\")) {\n\t\t\t\t\tHashMap<Integer, ItemStack> reward = new HashMap<Integer, ItemStack>();\n\t\t\t\t\tthis.inventoryToLoadout(player, reward);\n\t\t\t\t\twarzone.getDefaultInventories().setReward(reward);\n\t\t\t\t\treturnMessage.append(\" game end reward updated.\");\n\t\t\t\t}\n\t\t\t\tif (namedParams.containsKey(\"lobbymaterial\")) {\n\t\t\t\t\tString whichBlocks = namedParams.get(\"lobbymaterial\");\n\t\t\t\t\tItemStack blockInHand = player.getInventory().getItemInMainHand();\n\t\t\t\t\tboolean updatedLobbyMaterials = false;\n\n\t\t\t\t\tif (!blockInHand.getType().isBlock() && !blockInHand.getType().equals(Material.AIR)) {\n\t\t\t\t\t\tthis.badMsg(player, \"Can only use blocks or air as lobby material.\");\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (whichBlocks.equals(\"floor\")) {\n\t\t\t\t\t\t\twarzone.getLobbyMaterials().setFloorBlock(blockInHand);\n\t\t\t\t\t\t\treturnMessage.append(\" lobby floor material set to \").append(blockInHand.getType());\n\t\t\t\t\t\t\tupdatedLobbyMaterials = true;\n\t\t\t\t\t\t} else if (whichBlocks.equals(\"outline\")) {\n\t\t\t\t\t\t\twarzone.getLobbyMaterials().setOutlineBlock(blockInHand);\n\t\t\t\t\t\t\treturnMessage.append(\" lobby outline material set to \").append(blockInHand.getType());\n\t\t\t\t\t\t\tupdatedLobbyMaterials = true;\n\t\t\t\t\t\t} else if (whichBlocks.equals(\"gate\")) {\n\t\t\t\t\t\t\twarzone.getLobbyMaterials().setGateBlock(blockInHand);\n\t\t\t\t\t\t\treturnMessage.append(\" lobby gate material set to \").append(blockInHand.getType());\n\t\t\t\t\t\t\tupdatedLobbyMaterials = true;\n\t\t\t\t\t\t} else if (whichBlocks.equals(\"light\")) {\n\t\t\t\t\t\t\twarzone.getLobbyMaterials().setLightBlock(blockInHand);\n\t\t\t\t\t\t\treturnMessage.append(\" lobby light material set to \").append(blockInHand.getType());\n\t\t\t\t\t\t\tupdatedLobbyMaterials = true;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (updatedLobbyMaterials && warzone.getLobby() != null) {\n\t\t\t\t\t\t\twarzone.getLobby().getVolume().resetBlocks();\n\t\t\t\t\t\t\twarzone.getLobby().initialize();\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (namedParams.containsKey(\"material\")) {\n\t\t\t\t\tString whichBlocks = namedParams.get(\"material\");\n\t\t\t\t\tItemStack blockInHand = player.getInventory().getItemInMainHand();\n\t\t\t\t\tboolean updatedMaterials = false;\n\n\t\t\t\t\tif (!blockInHand.getType().isBlock()) {\n\t\t\t\t\t\tthis.badMsg(player, \"Can only use blocks as material.\");\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (whichBlocks.equals(\"main\")) {\n\t\t\t\t\t\t\twarzone.getWarzoneMaterials().setMainBlock(blockInHand);\n\t\t\t\t\t\t\treturnMessage.append(\" main material set to \").append(blockInHand.getType());\n\t\t\t\t\t\t\tupdatedMaterials = true;\n\t\t\t\t\t\t} else if (whichBlocks.equals(\"stand\")) {\n\t\t\t\t\t\t\twarzone.getWarzoneMaterials().setStandBlock(blockInHand);\n\t\t\t\t\t\t\treturnMessage.append(\" stand material set to \").append(blockInHand.getType());\n\t\t\t\t\t\t\tupdatedMaterials = true;\n\t\t\t\t\t\t} else if (whichBlocks.equals(\"light\")) {\n\t\t\t\t\t\t\twarzone.getWarzoneMaterials().setLightBlock(blockInHand);\n\t\t\t\t\t\t\treturnMessage.append(\" light material set to \").append(blockInHand.getType());\n\t\t\t\t\t\t\tupdatedMaterials = true;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (updatedMaterials) {\n\t\t\t\t\t\t\t// reset all structures\n\t\t\t\t\t\t\tfor (Monument monument : warzone.getMonuments()) {\n\t\t\t\t\t\t\t\tmonument.getVolume().resetBlocks();\n\t\t\t\t\t\t\t\tmonument.addMonumentBlocks();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tfor (Cake cake : warzone.getCakes()) {\n\t\t\t\t\t\t\t\tcake.getVolume().resetBlocks();\n\t\t\t\t\t\t\t\tcake.addCakeBlocks();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tfor (Bomb bomb : warzone.getBombs()) {\n\t\t\t\t\t\t\t\tbomb.getVolume().resetBlocks();\n\t\t\t\t\t\t\t\tbomb.addBombBlocks();\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tfor (Team team : warzone.getTeams()) {\n\t\t\t\t\t\t\t\tfor (Volume spawnVolume : team.getSpawnVolumes().values()) {\n\t\t\t\t\t\t\t\t\tspawnVolume.resetBlocks();\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tteam.initializeTeamSpawns();\n\t\t\t\t\t\t\t\tif (team.getTeamFlag() != null) {\n\t\t\t\t\t\t\t\t\tteam.getFlagVolume().resetBlocks();\n\t\t\t\t\t\t\t\t\tteam.initializeTeamFlag();\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn returnMessage.toString();\n\t\t} catch (Exception e) {\n\t\t\treturn \"PARSE-ERROR\";\n\t\t}\n\t}\n\n\tpublic String updateFromNamedParams(CommandSender commandSender, String[] arguments) {\n\t\ttry {\n\t\t\tMap<String, String> namedParams = new HashMap<String, String>();\n\t\t\tMap<String, String> thirdParameter = new HashMap<String, String>();\n\t\t\tfor (String namedPair : arguments) {\n\t\t\t\tString[] pairSplit = namedPair.split(\":\");\n\t\t\t\tif (pairSplit.length == 2) {\n\t\t\t\t\tnamedParams.put(pairSplit[0].toLowerCase(), pairSplit[1]);\n\t\t\t\t} else if (pairSplit.length == 3) {\n\t\t\t\t\tnamedParams.put(pairSplit[0].toLowerCase(), pairSplit[1]);\n\t\t\t\t\tthirdParameter.put(pairSplit[0].toLowerCase(), pairSplit[2]);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tStringBuilder returnMessage = new StringBuilder();\n\n\t\t\treturnMessage.append(this.getWarConfig().updateFromNamedParams(namedParams));\n\t\t\treturnMessage.append(this.getWarzoneDefaultConfig().updateFromNamedParams(namedParams));\n\t\t\treturnMessage.append(this.getTeamDefaultConfig().updateFromNamedParams(namedParams));\n\n\t\t\tif (commandSender instanceof Player) {\n\t\t\t\tPlayer player = (Player) commandSender;\n\t\t\t\tif (namedParams.containsKey(\"loadout\")) {\n\t\t\t\t\tString loadoutName = namedParams.get(\"loadout\");\n\t\t\t\t\tHashMap<Integer, ItemStack> loadout = this.getDefaultInventories().getLoadout(loadoutName);\n\t\t\t\t\tif (loadout == null) {\n\t\t\t\t\t\tloadout = new HashMap<Integer, ItemStack>();\n\t\t\t\t\t\tthis.getDefaultInventories().addLoadout(loadoutName, loadout);\n\t\t\t\t\t\treturnMessage.append(loadoutName + \" respawn loadout added.\");\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturnMessage.append(loadoutName + \" respawn loadout updated.\");\n\t\t\t\t\t}\n\t\t\t\t\tthis.inventoryToLoadout(player, loadout);\n\t\t\t\t\tLoadout ldt = this.getDefaultInventories().getNewLoadout(loadoutName);\n\t\t\t\t\tif (thirdParameter.containsKey(\"loadout\")) {\n\t\t\t\t\t\tString permission = thirdParameter.get(\"loadout\");\n\t\t\t\t\t\tldt.setPermission(permission);\n\t\t\t\t\t\treturnMessage.append(' ').append(loadoutName).append(\" respawn loadout permission set to \").append(permission).append('.');\n\t\t\t\t\t} else if (ldt.requiresPermission()) {\n\t\t\t\t\t\tldt.setPermission(null);\n\t\t\t\t\t\treturnMessage.append(' ').append(loadoutName).append(\" respawn loadout permission deleted.\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (namedParams.containsKey(\"deleteloadout\")) {\n\t\t\t\t\tString loadoutName = namedParams.get(\"deleteloadout\");\n\t\t\t\t\tif (this.getDefaultInventories().containsLoadout(loadoutName)) {\n\t\t\t\t\t\tif (this.getDefaultInventories().getNewLoadouts().size() > 1) {\n\t\t\t\t\t\t\tthis.getDefaultInventories().removeLoadout(loadoutName);\n\t\t\t\t\t\t\treturnMessage.append(\" \" + loadoutName + \" loadout removed.\");\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\treturnMessage.append(\" Can't remove only loadout.\");\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturnMessage.append(\" \" + loadoutName + \" loadout not found.\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (namedParams.containsKey(\"reward\")) {\n\t\t\t\t\tHashMap<Integer, ItemStack> reward = new HashMap<Integer, ItemStack>();\n\t\t\t\t\tthis.inventoryToLoadout(player, reward);\n\t\t\t\t\tthis.getDefaultInventories().setReward(reward);\n\t\t\t\t\treturnMessage.append(\" game end reward updated.\");\n\t\t\t\t}\n\t\t\t\tif (namedParams.containsKey(\"rallypoint\")) {\n\t\t\t\t\tString zoneName = namedParams.get(\"rallypoint\");\n\t\t\t\t\tthis.setZoneRallyPoint(zoneName, player);\n\t\t\t\t\treturnMessage.append(\" rallypoint set for zone \" + zoneName + \".\");\n\t\t\t\t}\n\t\t\t\tif (namedParams.containsKey(\"warhubmaterial\")) {\n\t\t\t\t\tString whichBlocks = namedParams.get(\"warhubmaterial\");\n\t\t\t\t\tItemStack blockInHand = player.getInventory().getItemInMainHand();\n\t\t\t\t\tboolean updatedWarhubMaterials = false;\n\n\t\t\t\t\tif (!blockInHand.getType().isBlock() && !blockInHand.getType().equals(Material.AIR)) {\n\t\t\t\t\t\tthis.badMsg(player, \"Can only use blocks or air as warhub material.\");\n\t\t\t\t\t} else {\n\t\t\t\t\t\tif (whichBlocks.equals(\"floor\")) {\n\t\t\t\t\t\t\tthis.warhubMaterials.setFloorBlock(blockInHand);\n\t\t\t\t\t\t\treturnMessage.append(\" warhub floor material set to \" + blockInHand.getType());\n\t\t\t\t\t\t\tupdatedWarhubMaterials = true;\n\t\t\t\t\t\t} else if (whichBlocks.equals(\"outline\")) {\n\t\t\t\t\t\t\tthis.warhubMaterials.setOutlineBlock(blockInHand);\n\t\t\t\t\t\t\treturnMessage.append(\" warhub outline material set to \" + blockInHand.getType());\n\t\t\t\t\t\t\tupdatedWarhubMaterials = true;\n\t\t\t\t\t\t} else if (whichBlocks.equals(\"gate\")) {\n\t\t\t\t\t\t\tthis.warhubMaterials.setGateBlock(blockInHand);\n\t\t\t\t\t\t\treturnMessage.append(\" warhub gate material set to \" + blockInHand.getType());\n\t\t\t\t\t\t\tupdatedWarhubMaterials = true;\n\t\t\t\t\t\t} else if (whichBlocks.equals(\"light\")) {\n\t\t\t\t\t\t\tthis.warhubMaterials.setLightBlock(blockInHand);\n\t\t\t\t\t\t\treturnMessage.append(\" warhub light material set to \" + blockInHand.getType());\n\t\t\t\t\t\t\tupdatedWarhubMaterials = true;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (updatedWarhubMaterials && War.war.getWarHub() != null) {\n\t\t\t\t\t\t\tWar.war.getWarHub().getVolume().resetBlocks();\n\t\t\t\t\t\t\tWar.war.getWarHub().initialize();\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn returnMessage.toString();\n\t\t} catch (Exception e) {\n\t\t\treturn \"PARSE-ERROR\";\n\t\t}\n\t}\n\n\tpublic String printConfig(Team team) {\n\t\tChatColor teamColor = ChatColor.AQUA;\n\n\t\tChatColor normalColor = ChatColor.WHITE;\n\n\t\tString teamConfigStr = \"\";\n\t\tInventoryBag invs = team.getInventories();\n\t\tteamConfigStr += getLoadoutsString(invs);\n\n\t\tfor (TeamConfig teamConfig : TeamConfig.values()) {\n\t\t\tObject value = team.getTeamConfig().getValue(teamConfig);\n\t\t\tif (value != null) {\n\t\t\t\tteamConfigStr += \" \" + teamConfig.toStringWithValue(value).replace(\":\", \":\" + teamColor) + normalColor;\n\t\t\t}\n\t\t}\n\n\t\treturn \" ::\" + teamColor + \"Team \" + team.getName() + teamColor + \" config\" + normalColor + \"::\"\n\t\t\t+ ifEmptyInheritedForTeam(teamConfigStr);\n\t}\n\n\tprivate String getLoadoutsString(InventoryBag invs) {\n\t\tStringBuilder loadoutsString = new StringBuilder();\n\t\tChatColor loadoutColor = ChatColor.GREEN;\n\t\tChatColor normalColor = ChatColor.WHITE;\n\n\t\tif (invs.hasLoadouts()) {\n\t\t\tStringBuilder loadouts = new StringBuilder();\n\t\t\tfor (Loadout ldt : invs.getNewLoadouts()) {\n\t\t\t\tif (ldt.requiresPermission()) {\n\t\t\t\t\tloadouts.append(ldt.getName()).append(\":\").append(ldt.getPermission()).append(\",\");\n\t\t\t\t} else {\n\t\t\t\t\tloadouts.append(ldt.getName()).append(\",\");\n\t\t\t\t}\n\t\t\t}\n\t\t\tloadoutsString.append(\" loadout:\").append(loadoutColor).append(loadouts.toString()).append(normalColor);\n\t\t}\n\n\t\tif (invs.hasReward()) {\n\t\t\tloadoutsString.append(\" reward:\").append(loadoutColor).append(\"default\").append(normalColor);\n\t\t}\n\n\t\treturn loadoutsString.toString();\n\t}\n\n\tpublic String printConfig(Warzone zone) {\n\t\tChatColor teamColor = ChatColor.AQUA;\n\t\tChatColor zoneColor = ChatColor.DARK_AQUA;\n\t\tChatColor authorColor = ChatColor.GREEN;\n\t\tChatColor normalColor = ChatColor.WHITE;\n\n\t\tString warzoneConfigStr = \"\";\n\t\tfor (WarzoneConfig warzoneConfig : WarzoneConfig.values()) {\n\t\t\tObject value = zone.getWarzoneConfig().getValue(warzoneConfig);\n\t\t\tif (value != null) {\n\t\t\t\twarzoneConfigStr += \" \" + warzoneConfig.toStringWithValue(value).replace(\":\", \":\" + zoneColor) + normalColor;\n\t\t\t}\n\t\t}\n\n\t\tString teamDefaultsStr = \"\";\n\t\tteamDefaultsStr += getLoadoutsString( zone.getDefaultInventories());\n\t\tfor (TeamConfig teamConfig : TeamConfig.values()) {\n\t\t\tObject value = zone.getTeamDefaultConfig().getValue(teamConfig);\n\t\t\tif (value != null) {\n\t\t\t\tteamDefaultsStr += \" \" + teamConfig.toStringWithValue(value).replace(\":\", \":\" + teamColor) + normalColor;\n\t\t\t}\n\t\t}\n\n\t\treturn \"::\" + zoneColor + \"Warzone \" + authorColor + zone.getName() + zoneColor + \" config\" + normalColor + \"::\"\n\t\t + \" author:\" + authorColor + ifEmptyEveryone(zone.getAuthorsString()) + normalColor\n\t\t + ifEmptyInheritedForWarzone(warzoneConfigStr)\n\t\t + \" ::\" + teamColor + \"Team defaults\" + normalColor + \"::\"\n\t\t + ifEmptyInheritedForWarzone(teamDefaultsStr);\n\t}\n\t\n\tprivate String ifEmptyInheritedForWarzone(String maybeEmpty) {\n\t\tif (maybeEmpty.equals(\"\")) {\n\t\t\tmaybeEmpty = \" all values inherited (see \" + ChatColor.GREEN + \"/warcfg -p)\" + ChatColor.WHITE;\n\t\t}\n\t\treturn maybeEmpty;\n\t}\n\n\tprivate String ifEmptyInheritedForTeam(String maybeEmpty) {\n\t\tif (maybeEmpty.equals(\"\")) {\n\t\t\tmaybeEmpty = \" all values inherited (see \" + ChatColor.GREEN + \"/warcfg -p\" + ChatColor.WHITE\n\t\t\t\t+ \" and \" + ChatColor.GREEN + \"/zonecfg -p\" + ChatColor.WHITE + \")\";\n\t\t}\n\t\treturn maybeEmpty;\n\t}\n\n\tprivate String ifEmptyEveryone(String maybeEmpty) {\n\t\tif (maybeEmpty.equals(\"\")) {\n\t\t\tmaybeEmpty = \"*\";\n\t\t}\n\t\treturn maybeEmpty;\n\t}\n\n\tpublic String printConfig() {\n\t\tChatColor teamColor = ChatColor.AQUA;\n\t\tChatColor zoneColor = ChatColor.DARK_AQUA;\n\t\tChatColor globalColor = ChatColor.DARK_GREEN;\n\t\tChatColor normalColor = ChatColor.WHITE;\n\n\t\tString warConfigStr = \"\";\n\t\tfor (WarConfig warConfig : WarConfig.values()) {\n\t\t\twarConfigStr += \" \" + warConfig.toStringWithValue(this.getWarConfig().getValue(warConfig)).replace(\":\", \":\" + globalColor) + normalColor;\n\t\t}\n\n\t\tString warzoneDefaultsStr = \"\";\n\t\tfor (WarzoneConfig warzoneConfig : WarzoneConfig.values()) {\n\t\t\twarzoneDefaultsStr += \" \" + warzoneConfig.toStringWithValue(this.getWarzoneDefaultConfig().getValue(warzoneConfig)).replace(\":\", \":\" + zoneColor) + normalColor;\n\t\t}\n\n\t\tString teamDefaultsStr = \"\";\n\t\tteamDefaultsStr += getLoadoutsString(this.getDefaultInventories());\n\t\tfor (TeamConfig teamConfig : TeamConfig.values()) {\n\t\t\tteamDefaultsStr += \" \" + teamConfig.toStringWithValue(this.getTeamDefaultConfig().getValue(teamConfig)).replace(\":\", \":\" + teamColor) + normalColor;\n\t\t}\n\n\t\treturn normalColor + \"::\" + globalColor + \"War config\" + normalColor + \"::\" + warConfigStr\n\t\t\t+ normalColor + \" ::\" + zoneColor + \"Warzone defaults\" + normalColor + \"::\" + warzoneDefaultsStr\n\t\t\t\t+ normalColor + \" ::\" + teamColor + \"Team defaults\" + normalColor + \"::\" + teamDefaultsStr;\n\t}\n\n\tprivate void setZoneRallyPoint(String warzoneName, Player player) {\n\t\tWarzone zone = this.findWarzone(warzoneName);\n\t\tif (zone == null) {\n\t\t\tthis.badMsg(player, \"Can't set rally point. No such warzone.\");\n\t\t} else {\n\t\t\tzone.setRallyPoint(player.getLocation());\n\t\t\tWarzoneYmlMapper.save(zone);\n\t\t}\n\t}\n\n\tpublic void addWarzone(Warzone zone) {\n\t\tthis.warzones.add(zone);\n\t}\n\n\tpublic List<Warzone> getWarzones() {\n\t\treturn this.warzones;\n\t}\n\n\t/**\n\t * Get a list of warzones that are not disabled.\n\t * @return List of enabled warzones.\n\t */\n\tpublic List<Warzone> getEnabledWarzones() {\n\t\tList<Warzone> enabledZones = new ArrayList<Warzone>(this.warzones.size());\n\t\tfor (Warzone zone : this.warzones) {\n\t\t\tif (zone.getWarzoneConfig().getBoolean(WarzoneConfig.DISABLED) == false) {\n\t\t\t\tenabledZones.add(zone);\n\t\t\t}\n\t\t}\n\t\treturn enabledZones;\n\t}\n\n\t/**\n\t * Get a list of warzones that have players in them.\n\t * @return List of enabled warzones with players.\n\t */\n\tpublic List<Warzone> getActiveWarzones() {\n\t\tList<Warzone> activeZones = new ArrayList<Warzone>(this.warzones.size());\n\t\tfor (Warzone zone : this.warzones) {\n\t\t\tif (zone.getWarzoneConfig().getBoolean(WarzoneConfig.DISABLED) == false\n\t\t\t\t&& zone.getPlayerCount() > 0) {\n\t\t\t\tactiveZones.add(zone);\n\t\t\t}\n\t\t}\n\t\treturn activeZones;\n\t}\n\n\tpublic void msg(CommandSender sender, String str) {\n\t\tif (messages.containsKey(str)) str = this.getString(str);\n\t\tif (HIDE_BLANK_MESSAGES && (str == null || str.isEmpty())) return;\n\t\tif (sender instanceof Player) {\n\t\t\tStringBuilder output = new StringBuilder(ChatColor.GRAY.toString())\n\t\t\t\t\t.append(this.getString(\"war.prefix\")).append(ChatColor.WHITE).append(' ');\n\t\t\toutput.append(this.colorKnownTokens(str, ChatColor.WHITE));\n\t\t\tsender.sendMessage(output.toString());\n\t\t} else {\n\t\t\tsender.sendMessage(str);\n\t\t}\n\t}\n\n\tpublic void badMsg(CommandSender sender, String str) {\n\t\tif (messages.containsKey(str)) str = this.getString(str);\n\t\tif (HIDE_BLANK_MESSAGES && (str == null || str.isEmpty())) return;\n\t\tif (sender instanceof Player) {\n\t\t\tStringBuilder output = new StringBuilder(ChatColor.GRAY.toString())\n\t\t\t\t\t.append(this.getString(\"war.prefix\")).append(ChatColor.RED).append(' ');\n\t\t\toutput.append(this.colorKnownTokens(str, ChatColor.RED));\n\t\t\tsender.sendMessage(output.toString());\n\t\t} else {\n\t\t\tsender.sendMessage(str);\n\t\t}\n\t}\n\n\tpublic void msg(CommandSender sender, String str, Object... obj) {\n\t\tif (messages.containsKey(str)) str = this.getString(str);\n\t\tif (HIDE_BLANK_MESSAGES && (str == null || str.isEmpty())) return;\n\t\tif (sender instanceof Player) {\n\t\t\tStringBuilder output = new StringBuilder(ChatColor.GRAY.toString())\n\t\t\t\t\t.append(this.getString(\"war.prefix\")).append(ChatColor.WHITE).append(' ');\n\t\t\toutput.append(MessageFormat.format(\n\t\t\t\t\t\tthis.colorKnownTokens(str, ChatColor.WHITE), obj));\n\t\t\tsender.sendMessage(output.toString());\n\t\t} else {\n\t\t\tStringBuilder output = new StringBuilder();\n\t\t\toutput.append(MessageFormat.format(str, obj));\n\t\t\tsender.sendMessage(output.toString());\n\t\t}\n\t}\n\n\tpublic void badMsg(CommandSender sender, String str, Object... obj) {\n\t\tif (messages.containsKey(str)) str = this.getString(str);\n\t\tif (HIDE_BLANK_MESSAGES && (str == null || str.isEmpty())) return;\n\t\tif (sender instanceof Player) {\n\t\t\tStringBuilder output = new StringBuilder(ChatColor.GRAY.toString())\n\t\t\t\t\t.append(this.getString(\"war.prefix\")).append(ChatColor.RED).append(' ');\n\t\t\toutput.append(MessageFormat.format(\n\t\t\t\t\t\tthis.colorKnownTokens(str, ChatColor.RED), obj));\n\t\t\tsender.sendMessage(output.toString());\n\t\t} else {\n\t\t\tStringBuilder output = new StringBuilder();\n\t\t\toutput.append(MessageFormat.format(str, obj));\n\t\t\tsender.sendMessage(output.toString());\n\t\t}\n\t}\n\n\t/**\n\t * Colors the teams and examples in messages\n\t *\n\t * @param str message-string\n\t * @param msgColor current message-color\n\t * @return String Message with colored teams\n\t */\n\tprivate String colorKnownTokens(String str, ChatColor msgColor) {\n\t\tstr = str.replaceAll(\"Ex -\", ChatColor.BLUE + \"Ex -\" + ChatColor.GRAY);\n\t\tstr = str.replaceAll(\"\\\\\\\\\", ChatColor.BLUE + \"\\\\\\\\\" + ChatColor.GRAY);\n\t\tstr = str.replaceAll(\"->\", ChatColor.LIGHT_PURPLE + \"->\" + ChatColor.GRAY);\n\t\tstr = str.replaceAll(\"/teamcfg\", ChatColor.AQUA + \"/teamcfg\" + ChatColor.GRAY);\n\t\tstr = str.replaceAll(\"Team defaults\", ChatColor.AQUA + \"Team defaults\" + ChatColor.GRAY);\n\t\tstr = str.replaceAll(\"Team config\", ChatColor.AQUA + \"Team config\" + ChatColor.GRAY);\n\t\tstr = str.replaceAll(\"/zonecfg\", ChatColor.DARK_AQUA + \"/zonecfg\" + ChatColor.GRAY);\n\t\tstr = str.replaceAll(\"Warzone defaults\", ChatColor.DARK_AQUA + \"Warzone defaults\" + ChatColor.GRAY);\n\t\tstr = str.replaceAll(\"Warzone config\", ChatColor.DARK_AQUA + \"Warzone config\" + ChatColor.GRAY);\n\t\tstr = str.replaceAll(\"/warcfg\", ChatColor.DARK_GREEN + \"/warcfg\" + ChatColor.GRAY);\n\t\tstr = str.replaceAll(\"War config\", ChatColor.DARK_GREEN + \"War config\" + ChatColor.GRAY);\n\t\tstr = str.replaceAll(\"Print config\", ChatColor.WHITE + \"Print config\" + ChatColor.GREEN);\n\t\t\n\t\tfor (TeamKind kind : TeamKind.values()) {\n\t\t\tstr = str.replaceAll(\" \" + kind.toString(), \" \" + kind.getColor() + kind.toString() + msgColor);\n\t\t\tstr = str.replaceAll(kind.toString() + \"/\", kind.getColor() + kind.toString() + ChatColor.GRAY + \"/\");\n\t\t}\n\t\t\n\t\treturn str;\n\t}\n\n\t/**\n\t * Logs a specified message with a specified level\n\t *\n\t * @param str message to log\n\t * @param lvl level to use\n\t */\n\tpublic void log(String str, Level lvl) {\n\t\tthis.getLogger().log(lvl, str);\n\t}\n\n\t// the only way to find a zone that has only one corner\n\tpublic Warzone findWarzone(String warzoneName) {\n\t\tfor (Warzone warzone : this.warzones) {\n\t\t\tif (warzone.getName().toLowerCase().equals(warzoneName.toLowerCase())) {\n\t\t\t\treturn warzone;\n\t\t\t}\n\t\t}\n\t\tfor (Warzone warzone : this.incompleteZones) {\n\t\t\tif (warzone.getName().equals(warzoneName)) {\n\t\t\t\treturn warzone;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n \n\t/**\n\t * Checks whether the given player is allowed to play in a certain team\n\t *\n\t * @param \tplayer\tPlayer to check\n * @param team Team to check \n\t * @return\t\ttrue if the player may play in the team\n\t */\n\tpublic boolean canPlayWar(Player player, Team team) {\n\t\treturn player.hasPermission(team.getTeamConfig().resolveString(TeamConfig.PERMISSION));\n\t}\n\n\t/**\n\t * Checks whether the given player is allowed to warp.\n\t *\n\t * @param \tplayer\tPlayer to check\n\t * @return\t\ttrue if the player may warp\n\t */\n\tpublic boolean canWarp(Player player) {\n\t\treturn player.hasPermission(\"war.warp\");\n\t}\n\n\t/**\n\t * Checks whether the given player is allowed to build outside zones\n\t *\n\t * @param \tplayer\tPlayer to check\n\t * @return\t\ttrue if the player may build outside zones\n\t */\n\tpublic boolean canBuildOutsideZone(Player player) {\n\t\tif (this.getWarConfig().getBoolean(WarConfig.BUILDINZONESONLY)) {\n\t\t\treturn player.hasPermission(\"war.build\");\n\t\t} else {\n\t\t\treturn true;\n\t\t}\n\t}\n\n\t/**\n\t * Checks whether the given player is allowed to pvp outside zones\n\t *\n\t * @param \tplayer\tPlayer to check\n\t * @return\t\ttrue if the player may pvp outside zones\n\t */\n\tpublic boolean canPvpOutsideZones(Player player) {\n\t\tif (this.getWarConfig().getBoolean(WarConfig.PVPINZONESONLY)) {\n\t\t\treturn player.hasPermission(\"war.pvp\");\n\t\t} else {\n\t\t\treturn true;\n\t\t}\n\t}\n\n\t/**\n\t * Checks whether the given player is a zone maker\n\t *\n\t * @param \tplayer\tPlayer to check\n\t * @return\t\ttrue if the player is a zone maker\n\t */\n\tpublic boolean isZoneMaker(Player player) {\n\t\t// sort out disguised first\n\t\tfor (OfflinePlayer disguised : this.zoneMakersImpersonatingPlayers) {\n\t\t\tif (disguised.isOnline() && disguised.getPlayer().equals(player)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tfor (OfflinePlayer zoneMaker : this.zoneMakerNames) {\n\t\t\tif (zoneMaker.isOnline() && zoneMaker.getPlayer().equals(player)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn player.hasPermission(\"war.zonemaker\");\n\t}\n\t\n\t/**\n\t * Checks whether the given player is a War admin\n\t *\n\t * @param \tplayer\tPlayer to check\n\t * @return\t\ttrue if the player is a War admin\n\t */\n\tpublic boolean isWarAdmin(Player player) {\n\t\treturn player.hasPermission(\"war.admin\");\n\t}\n\n\tpublic void addWandBearer(Player player, String zoneName) {\n\t\tif (this.wandBearers.containsKey(player.getName())) {\n\t\t\tString alreadyHaveWand = this.wandBearers.get(player.getName());\n\t\t\tif (player.getInventory().first(Material.WOODEN_SWORD) != -1) {\n\t\t\t\tif (zoneName.equals(alreadyHaveWand)) {\n\t\t\t\t\tthis.badMsg(player, \"You already have a wand for zone \" + alreadyHaveWand + \". Drop the wooden sword first.\");\n\t\t\t\t} else {\n\t\t\t\t\t// new zone, already have sword\n\t\t\t\t\tthis.wandBearers.remove(player.getName());\n\t\t\t\t\tthis.wandBearers.put(player.getName(), zoneName);\n\t\t\t\t\tthis.msg(player, \"Switched wand to zone \" + zoneName + \".\");\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// lost his sword, or new warzone\n\t\t\t\tif (zoneName.equals(alreadyHaveWand)) {\n\t\t\t\t\t// same zone, give him a new sword\n\t\t\t\t\tplayer.getInventory().addItem(Compat.createDamagedIS(Material.WOODEN_SWORD, 1, 8));\n\t\t\t\t\tthis.msg(player, \"Here's a new sword for zone \" + zoneName + \".\");\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tif (player.getInventory().firstEmpty() == -1) {\n\t\t\t\tthis.badMsg(player, \"Your inventory is full. Please drop an item and try again.\");\n\t\t\t} else {\n\t\t\t\tthis.wandBearers.put(player.getName(), zoneName);\n\t\t\t\tplayer.getInventory().addItem(Compat.createDamagedIS(Material.WOODEN_SWORD, 1, 8));\n\t\t\t\tthis.msg(player, \"You now have a wand for zone \" + zoneName + \". Left-click with wooden sword for corner 1. Right-click for corner 2.\");\n\t\t\t\tWar.war.log(player.getName() + \" now has a wand for warzone \" + zoneName, Level.INFO);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic boolean isWandBearer(Player player) {\n\t\treturn this.wandBearers.containsKey(player.getName());\n\t}\n\n\tpublic String getWandBearerZone(Player player) {\n\t\tif (this.isWandBearer(player)) {\n\t\t\treturn this.wandBearers.get(player.getName());\n\t\t}\n\t\treturn \"\";\n\t}\n\n\tpublic void removeWandBearer(Player player) {\n\t\tthis.wandBearers.remove(player.getName());\n\t}\n\n\tpublic Warzone zoneOfZoneWallAtProximity(Location location) {\n\t\tfor (Warzone zone : this.warzones) {\n\t\t\tif (zone.getWorld() == location.getWorld() && zone.isNearWall(location)) {\n\t\t\t\treturn zone;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic List<OfflinePlayer> getZoneMakerNames() {\n\t\treturn this.zoneMakerNames;\n\t}\n\n\tpublic List<String> getCommandWhitelist() {\n\t\treturn this.commandWhitelist;\n\t}\n\n\tpublic boolean inAnyWarzoneLobby(Location location) {\n\t\treturn ZoneLobby.getLobbyByLocation(location) != null;\n\t}\n\n\tpublic List<OfflinePlayer> getZoneMakersImpersonatingPlayers() {\n\t\treturn this.zoneMakersImpersonatingPlayers;\n\t}\n\n\tpublic List<Warzone> getIncompleteZones() {\n\t\treturn this.incompleteZones;\n\t}\n\n\tpublic WarHub getWarHub() {\n\t\treturn this.warHub;\n\t}\n\n\tpublic void setWarHub(WarHub warHub) {\n\t\tthis.warHub = warHub;\n\t}\n\n\tpublic boolean isLoaded() {\n\t\treturn this.loaded;\n\t}\n\n\tpublic void setLoaded(boolean loaded) {\n\t\tthis.loaded = loaded;\n\t}\n\n\tpublic HashMap<String, PlayerState> getDisconnected() {\n\t\treturn this.disconnected;\n\t}\n\n\tpublic void setDisconnected(HashMap<String, PlayerState> disconnected) {\n\t\tthis.disconnected = disconnected;\n\t}\n\n\tpublic InventoryBag getDefaultInventories() {\n\t\treturn defaultInventories;\n\t}\n\n\tpublic List<String> getDeadlyAdjectives() {\n\t\treturn deadlyAdjectives;\n\t}\n\n\tpublic List<String> getKillerVerbs() {\n\t\treturn killerVerbs;\n\t}\n\n\tpublic TeamConfigBag getTeamDefaultConfig() {\n\t\treturn this.teamDefaultConfig ;\n\t}\n\n\tpublic WarzoneConfigBag getWarzoneDefaultConfig() {\n\t\treturn this.warzoneDefaultConfig;\n\t}\n\t\n\tpublic WarConfigBag getWarConfig() {\n\t\treturn this.warConfig;\n\t}\n\n\tpublic HubLobbyMaterials getWarhubMaterials() {\n\t\treturn this.warhubMaterials;\n\t}\n\n\tpublic void setWarhubMaterials(HubLobbyMaterials warhubMaterials) {\n\t\tthis.warhubMaterials = warhubMaterials;\n\t}\n\n\tpublic KillstreakReward getKillstreakReward() {\n\t\treturn killstreakReward;\n\t}\n\n\tpublic void setKillstreakReward(KillstreakReward killstreakReward) {\n\t\tthis.killstreakReward = killstreakReward;\n\t}\n\n\tpublic MySQLConfig getMysqlConfig() {\n\t\treturn mysqlConfig;\n\t}\n\n\tpublic void setMysqlConfig(MySQLConfig mysqlConfig) {\n\t\tthis.mysqlConfig = mysqlConfig;\n\t}\n\n\tpublic String getString(String key) {\n\t\treturn messages.getString(key);\n\t}\n\n\tpublic Locale getLoadedLocale() {\n\t\treturn messages.getLocale();\n\t}\n\n\t/**\n\t * Convert serialized effect to actual effect.\n\t * @param serializedEffect String stored in configuration.\n\t * Format: TYPE;DURATION;AMPLIFY\n\t * @return Potion effect or null otherwise\n\t */\n\tpublic PotionEffect getPotionEffect(String serializedEffect) {\n\t\tString[] arr = serializedEffect.split(\";\");\n\t\tif (arr.length != 3) return null;\n\t\ttry {\n\t\t\tPotionEffectType type = PotionEffectType.getByName(arr[0]);\n\t\t\tint duration = Integer.parseInt(arr[1]);\n\t\t\tint amplification = Integer.parseInt(arr[2]);\n\t\t\treturn new PotionEffect(type, duration, amplification);\n\t\t} catch (RuntimeException ex) {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tpublic Economy getEconomy() {\n\t\treturn econ;\n\t}\n\n\tpublic UIManager getUIManager() {\n\t\treturn UIManager;\n\t}\n\n\tpublic void setUIManager(UIManager UIManager) {\n\t\tthis.UIManager = UIManager;\n\t}\n}",
"public class Warzone {\n\n\n\tstatic final Comparator<Team> LEAST_PLAYER_COUNT_ORDER = new Comparator<Team>() {\n\t\t@Override\n\t\tpublic int compare(Team arg0, Team arg1) {\n\t\t\treturn arg0.getPlayers().size() - arg1.getPlayers().size();\n\t\t}\n\t};\n\tprivate final List<Team> teams = new ArrayList<Team>();\n\tprivate final List<Monument> monuments = new ArrayList<Monument>();\n\tprivate final List<CapturePoint> capturePoints = new ArrayList<CapturePoint>();\n\tprivate final List<Bomb> bombs = new ArrayList<Bomb>();\n\tprivate final List<Cake> cakes = new ArrayList<Cake>();\n\tprivate final List<String> authors = new ArrayList<String>();\n\tprivate final int minSafeDistanceFromWall = 6;\n\tprivate final List<Player> respawn = new ArrayList<Player>();\n\tprivate final List<String> reallyDeadFighters = new ArrayList<String>();\n\tprivate final WarzoneConfigBag warzoneConfig;\n\tprivate final TeamConfigBag teamDefaultConfig;\n\tprivate String name;\n\tprivate ZoneVolume volume;\n\tprivate World world;\n\tprivate Location teleport;\n\tprivate ZoneLobby lobby;\n\tprivate Location rallyPoint;\n\tprivate List<ZoneWallGuard> zoneWallGuards = new ArrayList<ZoneWallGuard>();\n\tprivate HashMap<String, PlayerState> playerStates = new HashMap<String, PlayerState>();\n\tprivate HashMap<UUID, Team> flagThieves = new HashMap<UUID, Team>();\n\tprivate HashMap<UUID, Bomb> bombThieves = new HashMap<UUID, Bomb>();\n\tprivate HashMap<UUID, Cake> cakeThieves = new HashMap<UUID, Cake>();\n\tprivate HashMap<String, LoadoutSelection> loadoutSelections = new HashMap<String, LoadoutSelection>();\n\tprivate HashMap<String, PlayerState> deadMenInventories = new HashMap<String, PlayerState>();\n\tprivate HashMap<String, Integer> killCount = new HashMap<String, Integer>();\n\tprivate HashMap<Player, PermissionAttachment> attachments = new HashMap<Player, PermissionAttachment>();\n\tprivate HashMap<Player, Team> delayedJoinPlayers = new HashMap<Player, Team>();\n\tprivate List<LogKillsDeathsJob.KillsDeathsRecord> killsDeathsTracker = new ArrayList<KillsDeathsRecord>();\n\tprivate InventoryBag defaultInventories = new InventoryBag();\n\n\tprivate Scoreboard scoreboard;\n\t\n\tprivate HubLobbyMaterials lobbyMaterials = null;\n\tprivate WarzoneMaterials warzoneMaterials = new WarzoneMaterials(\n\t\t\tnew ItemStack(Material.OBSIDIAN), new ItemStack(Material.OAK_FENCE),\n\t\t\tnew ItemStack(Material.GLOWSTONE));\n\t\n\tprivate boolean isEndOfGame = false;\n\tprivate boolean isReinitializing = false;\n\t//private final Object gameEndLock = new Object();\n\n private boolean pvpReady = true;\n\tprivate Random killSeed = new Random();\n\t// prevent tryCallDelayedPlayers from being recursively called by Warzone#assign\n\tprivate boolean activeDelayedCall = false;\n\tprivate ScoreboardType scoreboardType;\n\n\tpublic Warzone(World world, String name) {\n\t\tthis.world = world;\n\t\tthis.name = name;\n\t\tthis.warzoneConfig = new WarzoneConfigBag(this);\n\t\tthis.teamDefaultConfig = new TeamConfigBag();\t// don't use ctor with Warzone, as this changes config resolution\n\t\tthis.volume = new ZoneVolume(name, this.getWorld(), this);\n\t\tthis.lobbyMaterials = War.war.getWarhubMaterials().clone();\n\t\tthis.pvpReady = true;\n\t\tthis.scoreboardType = this.getWarzoneConfig().getScoreboardType(WarzoneConfig.SCOREBOARD);\n\t\tif (scoreboardType == ScoreboardType.SWITCHING)\n\t\t\tscoreboardType = ScoreboardType.LIFEPOOL;\n\t}\n\n\tpublic static Warzone getZoneByName(String name) {\n\t\tWarzone bestGuess = null;\n\t\tfor (Warzone warzone : War.war.getWarzones()) {\n\t\t\tif (warzone.getName().toLowerCase().equals(name.toLowerCase())) {\n\t\t\t\t// perfect match, return right away\n\t\t\t\treturn warzone;\n\t\t\t} else if (warzone.getName().toLowerCase().startsWith(name.toLowerCase())) {\n\t\t\t\t// perhaps there's a perfect match in the remaining zones, let's take this one aside\n\t\t\t\tbestGuess = warzone;\n\t\t\t}\n\t\t}\n\t\treturn bestGuess;\n\t}\n\n\tpublic static Warzone getZoneByNameExact(String name) {\n\t\tfor (Warzone zone : War.war.getWarzones()) {\n\t\t\tif (zone.getName().equalsIgnoreCase(name)) return zone;\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic static Warzone getZoneByLocation(Location location) {\n\t\tfor (Warzone warzone : War.war.getWarzones()) {\n\t\t\tif (location.getWorld().getName().equals(warzone.getWorld().getName()) && warzone.getVolume() != null && warzone.getVolume().contains(location)) {\n\t\t\t\treturn warzone;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic static Warzone getZoneByLocation(Player player) {\n\t\treturn Warzone.getZoneByLocation(player.getLocation());\n\t}\n\n\tpublic static Warzone getZoneByPlayerName(String playerName) {\n\t\tfor (Warzone warzone : War.war.getWarzones()) {\n\t\t\tTeam team = warzone.getPlayerTeam(playerName);\n\t\t\tif (team != null) {\n\t\t\t\treturn warzone;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic static Warzone getZoneForDeadPlayer(Player player) {\n\t\tfor (Warzone warzone : War.war.getWarzones()) {\n\t\t\tif (warzone.getReallyDeadFighters().contains(player.getName())) {\n\t\t\t\treturn warzone;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic boolean ready() {\n\t\treturn this.volume.hasTwoCorners() && !this.volume.tooSmall() && !this.volume.tooBig();\n\t}\n\n\tpublic List<Team> getTeams() {\n\t\treturn this.teams;\n\t}\n\n\tpublic Team getPlayerTeam(String playerName) {\n\t\tfor (Team team : this.teams) {\n\t\t\tfor (Player player : team.getPlayers()) {\n\t\t\t\tif (player.getName().equals(playerName)) {\n\t\t\t\t\treturn team;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic String getTeamInformation() {\n\t\tStringBuilder teamsMessage = new StringBuilder(War.war.getString(\"zone.teaminfo.prefix\"));\n\t\tif (this.getTeams().isEmpty()) {\n\t\t\tteamsMessage.append(War.war.getString(\"zone.teaminfo.none\"));\n\t\t} else {\n\t\t\tfor (Team team : this.getTeams()) {\n\t\t\t\tteamsMessage.append('\\n');\n\t\t\t\tteamsMessage.append(MessageFormat.format(War.war.getString(\"zone.teaminfo.format\"),\n\t\t\t\t\t\tteam.getName(), team.getPoints(), team.getRemainingLives(),\n\t\t\t\t\t\tteam.getTeamConfig().resolveInt(TeamConfig.LIFEPOOL), StringUtils.join(team.getPlayerNames().iterator(), \", \")));\n\t\t\t}\n\t\t}\n\t\treturn teamsMessage.toString();\n\t}\n\n\tpublic String getName() {\n\t\treturn this.name;\n\t}\n\n\tpublic void setName(String newName) {\n\t\tthis.name = newName;\n\t\tthis.volume.setName(newName);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn this.getName();\n\t}\n\n\tpublic Location getTeleport() {\n\t\treturn this.teleport;\n\t}\n\n\tpublic void setTeleport(Location location) {\n\t\tthis.teleport = location;\n\t}\n\n\tpublic int saveState(boolean clearArtifacts) {\n\t\tif (this.ready()) {\n\t\t\tif (clearArtifacts) {\n\t\t\t\t// removed everything to keep save clean\n\t\t\t\tfor (ZoneWallGuard guard : this.zoneWallGuards) {\n\t\t\t\t\tguard.deactivate();\n\t\t\t\t}\n\t\t\t\tthis.zoneWallGuards.clear();\n\n\t\t\t\tfor (Team team : this.teams) {\n\t\t\t\t\tfor (Volume teamVolume : team.getSpawnVolumes().values()) {\n\t\t\t\t\t\tteamVolume.resetBlocks();\n\t\t\t\t\t}\n\t\t\t\t\tif (team.getTeamFlag() != null) {\n\t\t\t\t\t\tteam.getFlagVolume().resetBlocks();\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tfor (Monument monument : this.monuments) {\n\t\t\t\t\tmonument.getVolume().resetBlocks();\n\t\t\t\t}\n\n\t\t\t\tfor (CapturePoint cp : this.capturePoints) {\n\t\t\t\t\tcp.getVolume().resetBlocks();\n\t\t\t\t}\n\n\t\t\t\tfor (Bomb bomb : this.bombs) {\n\t\t\t\t\tbomb.getVolume().resetBlocks();\n\t\t\t\t}\n\n\t\t\t\tfor (Cake cake : this.cakes) {\n\t\t\t\t\tcake.getVolume().resetBlocks();\n\t\t\t\t}\n\n\t\t\t\tif (this.lobby != null) {\n\t\t\t\t\tthis.lobby.getVolume().resetBlocks();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tthis.volume.saveBlocks();\n\t\t\tif (clearArtifacts) {\n\t\t\t\tthis.initializeZone(); // bring back stuff\n\t\t\t}\n\t\t\treturn this.volume.size();\n\t\t}\n\t\treturn 0;\n\t}\n\n\t/**\n\t * Goes back to the saved state of the warzone (resets only block types, not physics). Also teleports all players back to their respective spawns.\n\t *\n\t * @return\n\t */\n\tpublic void initializeZone() {\n\t\tthis.initializeZone(null);\n\t}\n\n\tpublic void initializeZone(Player respawnExempted) {\n\t\tif (this.ready() && this.volume.isSaved()) {\n\t\t\tif (this.scoreboard != null) {\n\t\t\t\tfor (String entry : this.scoreboard.getEntries()) {\n\t\t\t\t\tthis.scoreboard.resetScores(entry);\n\t\t\t\t}\n\t\t\t\tthis.scoreboard.clearSlot(DisplaySlot.SIDEBAR);\n\t\t\t\tfor (Objective obj : this.scoreboard.getObjectives()) {\n\t\t\t\t\tobj.unregister();\n\t\t\t\t}\n\t\t\t\tfor (Player player : Bukkit.getOnlinePlayers()) {\n\t\t\t\t\tif (player.getScoreboard() == this.scoreboard) {\n\t\t\t\t\t\tplayer.setScoreboard(Bukkit.getScoreboardManager().getMainScoreboard());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tthis.scoreboard = null;\n\t\t\t}\n\t\t\t// everyone back to team spawn with full health\n\t\t\tfor (Team team : this.teams) {\n\t\t\t\tfor (Player player : team.getPlayers()) {\n\t\t\t\t\tif (player.equals(respawnExempted)) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tif (this.getReallyDeadFighters().contains(player.getName())) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tthis.respawnPlayer(team, player);\n\t\t\t\t}\n\t\t\t\tteam.setRemainingLives(team.getTeamConfig().resolveInt(TeamConfig.LIFEPOOL));\n\t\t\t\tteam.initializeTeamSpawns();\n\t\t\t\tif (team.getTeamFlag() != null) {\n\t\t\t\t\tteam.setTeamFlag(team.getTeamFlag());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tthis.initZone();\n\n\t\t\tif (War.war.getWarHub() != null) {\n\t\t\t\tWar.war.getWarHub().resetZoneSign(this);\n\t\t\t}\n\t\t}\n\n\t\t// Don't forget to reset these to false, or we won't be able to score or empty lifepools anymore\n\t\tthis.isReinitializing = false;\n\t\tthis.isEndOfGame = false;\n\t}\n\n\tpublic void initializeZoneAsJob(Player respawnExempted) {\n\t\tInitZoneJob job = new InitZoneJob(this, respawnExempted);\n\t\tWar.war.getServer().getScheduler().scheduleSyncDelayedTask(War.war, job);\n\t}\n\n\tpublic void initializeZoneAsJob() {\n\t\tInitZoneJob job = new InitZoneJob(this);\n\t\tWar.war.getServer().getScheduler().scheduleSyncDelayedTask(War.war, job);\n\t}\n\n\tprivate void initZone() {\n\t\t// reset monuments\n\t\tfor (Monument monument : this.monuments) {\n\t\t\tmonument.getVolume().resetBlocks();\n\t\t\tmonument.addMonumentBlocks();\n\t\t}\n\n\t\t// reset capture points\n\t\tfor (CapturePoint cp : this.capturePoints) {\n\t\t\tcp.getVolume().resetBlocks();\n\t\t\tcp.reset();\n\t\t}\n\n\t\t// reset bombs\n\t\tfor (Bomb bomb : this.bombs) {\n\t\t\tbomb.getVolume().resetBlocks();\n\t\t\tbomb.addBombBlocks();\n\t\t}\n\n\t\t// reset cakes\n\t\tfor (Cake cake : this.cakes) {\n\t\t\tcake.getVolume().resetBlocks();\n\t\t\tcake.addCakeBlocks();\n\t\t}\n\n\t\t// reset lobby (here be demons)\n\t\tif (this.lobby != null) {\n\t\t\tif (this.lobby.getVolume() != null) {\n\t\t\t\tthis.lobby.getVolume().resetBlocks();\n\t\t\t}\n\t\t\tthis.lobby.initialize();\n\t\t}\n\n\t\tthis.flagThieves.clear();\n\t\tthis.bombThieves.clear();\n\t\tthis.cakeThieves.clear();\n\t\tif (this.getScoreboardType() != ScoreboardType.NONE) {\n\t\t\tthis.scoreboard = Bukkit.getScoreboardManager().getNewScoreboard();\n\t\t\tthis.updateScoreboard();\n\t\t\tfor (Team team : this.getTeams()) {\n\t\t\t\tfor (Player player : team.getPlayers()) {\n\t\t\t\t\tplayer.setScoreboard(scoreboard);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tthis.reallyDeadFighters.clear();\n\n\t\t//get them config (here be crazy grinning's!)\n\t\tint pvpready = warzoneConfig.getInt(WarzoneConfig.PREPTIME);\n\n\t\tif(pvpready != 0) { //if it is equalz to zeroz then dinosaurs will take over the earth\n\t\t\tthis.pvpReady = false;\n\t\t\tZoneTimeJob timer = new ZoneTimeJob(this);\n\t\t\tWar.war.getServer().getScheduler().runTaskLater(War.war, timer, pvpready * 20);\n\t\t}\n\n\t\t// nom drops\n\t\tfor(Entity entity : (this.getWorld().getEntities())) {\n\t\t\tif (!(entity instanceof Item)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// validate position\n\t\t\tif (!this.getVolume().contains(entity.getLocation())) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// omnomnomnom\n\t\t\tentity.remove();\n\t\t}\n\t}\n\n\tpublic void endRound() {\n\n\t}\n\n\tpublic void respawnPlayer(Team team, Player player) {\n\t\tthis.handleRespawn(team, player);\n\t\t// Teleport the player back to spawn\n\t\tplayer.teleport(team.getRandomSpawn());\n\t}\n\n\tpublic void respawnPlayer(PlayerMoveEvent event, Team team, Player player) {\n\t\tthis.handleRespawn(team, player);\n\t\t// Teleport the player back to spawn\n\t\tevent.setTo(team.getRandomSpawn());\n\t}\n\n\tpublic boolean isRespawning(Player p) {\n\t\treturn respawn.contains(p);\n\t}\n\n\tprivate void handleRespawn(final Team team, final Player player) {\n\t\t// first, wipe inventory to disable attribute modifications\n\t\tthis.preventItemHackingThroughOpenedInventory(player);\n\t\tplayer.getInventory().clear();\n\n\t\t// clear potion effects\n\t\tPotionEffectHelper.clearPotionEffects(player);\n\n\t\t// Fill hp\n\t\tplayer.setRemainingAir(player.getMaximumAir());\n\t\tAttributeInstance ai = player.getAttribute(Attribute.GENERIC_MAX_HEALTH);\n\t\tfor (AttributeModifier mod : ai.getModifiers()) {\n\t\t\tai.removeModifier(mod);\n\t\t}\n\t\tai.setBaseValue(20.0);\n\t\tplayer.setHealth(ai.getValue());\n\t\tplayer.setFoodLevel(20);\n\t\tplayer.setSaturation(team.getTeamConfig().resolveInt(TeamConfig.SATURATION));\n\t\tplayer.setExhaustion(0);\n\t\tplayer.setFallDistance(0);\n\t\tplayer.setFireTicks(0);\n\t\tplayer.addPotionEffect(new PotionEffect(PotionEffectType.FIRE_RESISTANCE, 5, 255));\n\t\tRunnable antiFireAction = new Runnable() {\n\n\t\t\t@Override\n\t\t\tpublic void run() {\n\t\t\t\t// Stop fire here, since doing it in the same tick as death doesn't extinguish it\n\t\t\t\tplayer.setFireTicks(0);\n\t\t\t}\n\n\t\t};\n\t\t// ughhhhh bukkit\n\t\tWar.war.getServer().getScheduler().runTaskLater(War.war, antiFireAction, 1L);\n\t\tWar.war.getServer().getScheduler().runTaskLater(War.war, antiFireAction, 2L);\n\t\tWar.war.getServer().getScheduler().runTaskLater(War.war, antiFireAction, 3L);\n\t\tWar.war.getServer().getScheduler().runTaskLater(War.war, antiFireAction, 4L);\n\t\tWar.war.getServer().getScheduler().runTaskLater(War.war, antiFireAction, 5L);\n\n\n\t\tplayer.setLevel(0);\n\t\tplayer.setExp(0);\n\t\tplayer.setAllowFlight(false);\n\t\tplayer.setFlying(false);\n\n\n\t\tthis.setKillCount(player.getName(), 0);\n\n\t\tif (player.getGameMode() != GameMode.SURVIVAL) {\n\t\t\t// Players are always in survival mode in warzones\n\t\t\tplayer.setGameMode(GameMode.SURVIVAL);\n\t\t}\n\n\n\t\tString potionEffect = team.getTeamConfig().resolveString(TeamConfig.APPLYPOTION);\n\t\tif (!potionEffect.isEmpty()) {\n\t\t\tPotionEffect effect = War.war.getPotionEffect(potionEffect);\n\t\t\tif (effect != null) {\n\t\t\t\tplayer.addPotionEffect(effect);\n\t\t\t} else {\n\t\t\t\tWar.war.getLogger().log(Level.WARNING,\n\t\t\t\t\t\"Failed to apply potion effect {0} in warzone {1}.\",\n\t\t\t\t\tnew Object[] {potionEffect, name});\n\t\t\t}\n\t\t}\n\n\t\tint respawnTime = team.getTeamConfig().resolveInt(TeamConfig.RESPAWNTIMER);\n\t\tint respawnTimeTicks = respawnTime * 20;\n\t\tif (respawnTimeTicks > 0) {\n\t\t\tplayer.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, respawnTimeTicks, 255));\n\t\t\tplayer.addPotionEffect(new PotionEffect(PotionEffectType.JUMP, respawnTimeTicks, 200));\n\t\t\tplayer.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, respawnTimeTicks, 255));\n\t\t\tplayer.sendTitle(\"\", ChatColor.RED + MessageFormat.format(War.war.getString(\"zone.spawn.timer.title\"), respawnTime), 1, respawnTimeTicks, 10);\n\t\t}\n\n\t\tboolean isFirstRespawn = false;\n\t\tif (!this.getLoadoutSelections().keySet().contains(player.getName())) {\n\t\t\tisFirstRespawn = true;\n\t\t\tthis.getLoadoutSelections().put(player.getName(), new LoadoutSelection(true, 0));\n\t\t} else if (this.isReinitializing) {\n\t\t\tisFirstRespawn = true;\n\t\t\tthis.getLoadoutSelections().get(player.getName()).setStillInSpawn(true);\n\t\t} else {\n\t\t\tthis.getLoadoutSelections().get(player.getName()).setStillInSpawn(true);\n\t\t}\n\n\t\tWar.war.getKillstreakReward().getAirstrikePlayers().remove(player.getName());\n\n\t\tfinal LoadoutResetJob job = new LoadoutResetJob(this, team, player, isFirstRespawn, false);\n\t\tif (team.getTeamConfig().resolveInt(TeamConfig.RESPAWNTIMER) == 0 || isFirstRespawn) {\n\t\t\tjob.run();\n\t\t}\n\t\telse {\n\t\t\t// \"Respawn\" Timer - player will not be able to leave spawn for a few seconds\n\t\t\trespawn.add(player);\n\n\t\t\tWar.war.getServer().getScheduler().scheduleSyncDelayedTask(War.war, new Runnable() {\n\t\t\t\tpublic void run() {\n\t\t\t\t respawn.remove(player);\n\t\t\t\t\tWar.war.getServer().getScheduler().scheduleSyncDelayedTask(War.war, job);\n\t\t\t\t}\n\t\t\t}, team.getTeamConfig().resolveInt(TeamConfig.RESPAWNTIMER) * 20L); // 20 ticks = 1 second\n\t\t}\n\t}\n\n\tprivate void resetInventory(Team team, Player player, Map<Integer, ItemStack> loadout) {\n\t\t// Reset inventory to loadout\n\t\tPlayerInventory playerInv = player.getInventory();\n\t\tplayerInv.clear();\n\t\tplayerInv.clear(playerInv.getSize());\n\t\tplayerInv.clear(playerInv.getSize() + 1);\n\t\tplayerInv.clear(playerInv.getSize() + 2);\n\t\tplayerInv.clear(playerInv.getSize() + 3); // helmet/blockHead\n\n\t\tLoadout banned = Loadout.getLoadout(team.getInventories().resolveNewLoadouts(), \"banned\");\n\t\tSet<Material> bannedMaterials = new HashSet<Material>();\n\t\tif (banned != null) {\n\t\t\tfor (ItemStack bannedItem : banned.getContents().values()) {\n\t\t\t\tbannedMaterials.add(bannedItem.getType());\n\t\t\t}\n\t\t}\n\n\t\tfor (Integer slot : loadout.keySet()) {\n\t\t\tItemStack item = loadout.get(slot);\n\t\t\tif (item == null || item.getType() == Material.AIR) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (bannedMaterials.contains(item.getType())) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (slot == 100) {\n\t\t\t\tplayerInv.setBoots(item.clone());\n\t\t\t} else if (slot == 101) {\n\t\t\t\tplayerInv.setLeggings(item.clone());\n\t\t\t} else if (slot == 102) {\n\t\t\t\tplayerInv.setChestplate(item.clone());\n\t\t\t} else if (slot == 103) {\n\t\t\t\tplayerInv.setHelmet(item.clone());\n\t\t\t} else {\n\t\t\t\tplayerInv.addItem(item.clone());\n\t\t\t}\n\t\t}\n\t\tif (this.getWarzoneConfig().getBoolean(WarzoneConfig.BLOCKHEADS)) {\n\t\t\tplayerInv.setHelmet(team.getKind().getHat());\n\t\t}\n\t}\n\n\tpublic boolean isMonumentCenterBlock(Block block) {\n\t\tfor (Monument monument : this.monuments) {\n\t\t\tint x = monument.getLocation().getBlockX();\n\t\t\tint y = monument.getLocation().getBlockY() + 1;\n\t\t\tint z = monument.getLocation().getBlockZ();\n\t\t\tif (x == block.getX() && y == block.getY() && z == block.getZ()) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tpublic Monument getMonumentFromCenterBlock(Block block) {\n\t\tfor (Monument monument : this.monuments) {\n\t\t\tint x = monument.getLocation().getBlockX();\n\t\t\tint y = monument.getLocation().getBlockY() + 1;\n\t\t\tint z = monument.getLocation().getBlockZ();\n\t\t\tif (x == block.getX() && y == block.getY() && z == block.getZ()) {\n\t\t\t\treturn monument;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic boolean nearAnyOwnedMonument(Location to, Team team) {\n\t\tfor (Monument monument : this.monuments) {\n\t\t\tif (monument.isNear(to) && monument.isOwner(team)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tpublic List<Monument> getMonuments() {\n\t\treturn this.monuments;\n\t}\n\n\tpublic boolean hasPlayerState(String playerName) {\n\t\treturn this.playerStates.containsKey(playerName);\n\t}\n\n\tpublic void keepPlayerState(Player player) {\n\t\tPlayerInventory inventory = player.getInventory();\n\t\tItemStack[] contents = inventory.getContents();\n\n\t\tString playerTitle = player.getName();\n\n\t\tthis.playerStates.put(\n\t\t\t\tplayer.getName(),\n\t\t\t\tnew PlayerState(player.getGameMode(), contents, inventory\n\t\t\t\t\t\t.getHelmet(), inventory.getChestplate(), inventory\n\t\t\t\t\t\t.getLeggings(), inventory.getBoots(), player\n\t\t\t\t\t\t.getHealth(), player.getExhaustion(), player\n\t\t\t\t\t\t.getSaturation(), player.getFoodLevel(), player\n\t\t\t\t\t\t.getActivePotionEffects(), playerTitle, player\n\t\t\t\t\t\t.getLevel(), player.getExp(), player.getAllowFlight()));\n\t}\n\n\tpublic void restorePlayerState(Player player) {\n\t\tPlayerState originalState = this.playerStates.remove(player.getName());\n\t\tPlayerInventory playerInv = player.getInventory();\n\t\tif (originalState != null) {\n\t\t\t// prevent item hacking thru CRAFTING personal inventory slots\n\t\t\tthis.preventItemHackingThroughOpenedInventory(player);\n\n\t\t\tthis.playerInvFromInventoryStash(playerInv, originalState);\n\t\t\tplayer.setGameMode(originalState.getGamemode());\n\t\t\tdouble maxH = player.getAttribute(Attribute.GENERIC_MAX_HEALTH).getValue();\n\t\t\tplayer.setHealth(Math.max(Math.min(originalState.getHealth(), maxH), 0.0D));\n\t\t\tplayer.setExhaustion(originalState.getExhaustion());\n\t\t\tplayer.setSaturation(originalState.getSaturation());\n\t\t\tplayer.setFoodLevel(originalState.getFoodLevel());\n\t\t\tPotionEffectHelper.restorePotionEffects(player, originalState.getPotionEffects());\n\t\t\tplayer.setLevel(originalState.getLevel());\n\t\t\tplayer.setExp(originalState.getExp());\n\t\t\tplayer.setAllowFlight(originalState.canFly());\n\n\t\t}\n\t\tplayer.setScoreboard(Bukkit.getScoreboardManager().getMainScoreboard());\n\t}\n\n\tprivate void preventItemHackingThroughOpenedInventory(Player player) {\n\t\tInventoryView openedInv = player.getOpenInventory();\n\t\tif (openedInv.getType() == InventoryType.CRAFTING) {\n\t\t\t// prevent abuse of personal crafting slots (this behavior doesn't seem to happen\n\t\t\t// for containers like workbench and furnace - those get closed properly)\n\t\t\topenedInv.getTopInventory().clear();\n\t\t}\n\n\t\t// Prevent player from keeping items he was transferring in his inventory\n\t\topenedInv.setCursor(null);\n\t}\n\n\tprivate void playerInvFromInventoryStash(PlayerInventory playerInv, PlayerState originalContents) {\n\t\tplayerInv.clear();\n\n\t\tplayerInv.clear(playerInv.getSize() + 0);\n\t\tplayerInv.clear(playerInv.getSize() + 1);\n\t\tplayerInv.clear(playerInv.getSize() + 2);\n\t\tplayerInv.clear(playerInv.getSize() + 3); // helmet/blockHead\n\n\t\tint invIndex = 0;\n\t\tfor (ItemStack item : originalContents.getContents()) {\n\t\t\tif (item != null && item.getType() != Material.AIR) {\n\t\t\t\tplayerInv.setItem(invIndex, item);\n\t\t\t}\n\t\t\tinvIndex++;\n\t\t}\n\n\t\tif (originalContents.getHelmet() != null) {\n\t\t\tplayerInv.setHelmet(originalContents.getHelmet());\n\t\t}\n\t\tif (originalContents.getChest() != null) {\n\t\t\tplayerInv.setChestplate(originalContents.getChest());\n\t\t}\n\t\tif (originalContents.getLegs() != null) {\n\t\t\tplayerInv.setLeggings(originalContents.getLegs());\n\t\t}\n\t\tif (originalContents.getFeet() != null) {\n\t\t\tplayerInv.setBoots(originalContents.getFeet());\n\t\t}\n\t}\n\n\tpublic boolean hasMonument(String monumentName) {\n\t\tfor (Monument monument : this.monuments) {\n\t\t\tif (monument.getName().startsWith(monumentName)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tpublic Monument getMonument(String monumentName) {\n\t\tfor (Monument monument : this.monuments) {\n\t\t\tif (monument.getName().startsWith(monumentName)) {\n\t\t\t\treturn monument;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic boolean hasCapturePoint(String capturePointName) {\n\t\treturn this.getCapturePoint(capturePointName) != null;\n\t}\n\n\tpublic CapturePoint getCapturePoint(String capturePointName) {\n\t\tfor (CapturePoint cp : this.capturePoints) {\n\t\t\tif (cp.getName().startsWith(capturePointName)) {\n\t\t\t\treturn cp;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic boolean hasBomb(String bombName) {\n\t\tfor (Bomb bomb : this.bombs) {\n\t\t\tif (bomb.getName().equals(bombName)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tpublic Bomb getBomb(String bombName) {\n\t\tfor (Bomb bomb : this.bombs) {\n\t\t\tif (bomb.getName().startsWith(bombName)) {\n\t\t\t\treturn bomb;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic boolean hasCake(String cakeName) {\n\t\tfor (Cake cake : this.cakes) {\n\t\t\tif (cake.getName().equals(cakeName)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tpublic Cake getCake(String cakeName) {\n\t\tfor (Cake cake : this.cakes) {\n\t\t\tif (cake.getName().startsWith(cakeName)) {\n\t\t\t\treturn cake;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic boolean isImportantBlock(Block block) {\n\t\tif (block == null) {\n\t\t\treturn false;\n\t\t}\n\t\tif (this.ready()) {\n\t\t\tfor (Monument m : this.monuments) {\n\t\t\t\tif (m.getVolume().contains(block)) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (CapturePoint cp : this.capturePoints) {\n\t\t\t\tif (cp.getVolume().contains(block)) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (Bomb b : this.bombs) {\n\t\t\t\tif (b.getVolume().contains(block)) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (Cake c : this.cakes) {\n\t\t\t\tif (c.getVolume().contains(block)) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (Team t : this.teams) {\n\t\t\t\tfor (Volume tVolume : t.getSpawnVolumes().values()) {\n\t\t\t\t\tif (tVolume.contains(block)) {\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (t.getFlagVolume() != null && t.getFlagVolume().contains(block)) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (this.volume.isWallBlock(block)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tpublic World getWorld() {\n\n\t\treturn this.world;\n\t}\n\n\tpublic void setWorld(World world) {\n\t\tthis.world = world;\n\t}\n\n\tpublic ZoneVolume getVolume() {\n\t\treturn this.volume;\n\t}\n\n\tpublic void setVolume(ZoneVolume zoneVolume) {\n\t\tthis.volume = zoneVolume;\n\t}\n\n\tpublic Team getTeamByKind(TeamKind kind) {\n\t\tfor (Team t : this.teams) {\n\t\t\tif (t.getKind() == kind) {\n\t\t\t\treturn t;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic boolean isNearWall(Location latestPlayerLocation) {\n\t\tif (this.volume.hasTwoCorners()) {\n\t\t\tif (Math.abs(this.volume.getSoutheastZ() - latestPlayerLocation.getBlockZ()) < this.minSafeDistanceFromWall && latestPlayerLocation.getBlockX() <= this.volume.getSoutheastX() && latestPlayerLocation.getBlockX() >= this.volume.getNorthwestX() && latestPlayerLocation.getBlockY() >= this.volume.getMinY() && latestPlayerLocation.getBlockY() <= this.volume.getMaxY()) {\n\t\t\t\treturn true; // near east wall\n\t\t\t} else if (Math.abs(this.volume.getSoutheastX() - latestPlayerLocation.getBlockX()) < this.minSafeDistanceFromWall && latestPlayerLocation.getBlockZ() <= this.volume.getNorthwestZ() && latestPlayerLocation.getBlockZ() >= this.volume.getSoutheastZ() && latestPlayerLocation.getBlockY() >= this.volume.getMinY() && latestPlayerLocation.getBlockY() <= this.volume.getMaxY()) {\n\t\t\t\treturn true; // near south wall\n\t\t\t} else if (Math.abs(this.volume.getNorthwestX() - latestPlayerLocation.getBlockX()) < this.minSafeDistanceFromWall && latestPlayerLocation.getBlockZ() <= this.volume.getNorthwestZ() && latestPlayerLocation.getBlockZ() >= this.volume.getSoutheastZ() && latestPlayerLocation.getBlockY() >= this.volume.getMinY() && latestPlayerLocation.getBlockY() <= this.volume.getMaxY()) {\n\t\t\t\treturn true; // near north wall\n\t\t\t} else if (Math.abs(this.volume.getNorthwestZ() - latestPlayerLocation.getBlockZ()) < this.minSafeDistanceFromWall && latestPlayerLocation.getBlockX() <= this.volume.getSoutheastX() && latestPlayerLocation.getBlockX() >= this.volume.getNorthwestX() && latestPlayerLocation.getBlockY() >= this.volume.getMinY() && latestPlayerLocation.getBlockY() <= this.volume.getMaxY()) {\n\t\t\t\treturn true; // near west wall\n\t\t\t} else if (Math.abs(this.volume.getMaxY() - latestPlayerLocation.getBlockY()) < this.minSafeDistanceFromWall && latestPlayerLocation.getBlockX() <= this.volume.getMaxX() && latestPlayerLocation.getBlockX() >= this.volume.getMinX() && latestPlayerLocation.getBlockZ() <= this.volume.getMaxZ() && latestPlayerLocation.getBlockZ() >= this.volume.getMinZ()) {\n\t\t\t\treturn true; // near up wall\n\t\t\t} else if (Math.abs(this.volume.getMinY() - latestPlayerLocation.getBlockY()) < this.minSafeDistanceFromWall && latestPlayerLocation.getBlockX() <= this.volume.getMaxX() && latestPlayerLocation.getBlockX() >= this.volume.getMinX() && latestPlayerLocation.getBlockZ() <= this.volume.getMaxZ() && latestPlayerLocation.getBlockZ() >= this.volume.getMinZ()) {\n\t\t\t\treturn true; // near down wall\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tpublic List<Block> getNearestWallBlocks(Location latestPlayerLocation) {\n\t\tList<Block> nearestWallBlocks = new ArrayList<Block>();\n\t\tif (Math.abs(this.volume.getSoutheastZ() - latestPlayerLocation.getBlockZ()) < this.minSafeDistanceFromWall && latestPlayerLocation.getBlockX() <= this.volume.getSoutheastX() && latestPlayerLocation.getBlockX() >= this.volume.getNorthwestX() && latestPlayerLocation.getBlockY() >= this.volume.getMinY() && latestPlayerLocation.getBlockY() <= this.volume.getMaxY()) {\n\t\t\t// near east wall\n\t\t\tBlock eastWallBlock = this.world.getBlockAt(latestPlayerLocation.getBlockX() + 1, latestPlayerLocation.getBlockY() + 1, this.volume.getSoutheastZ());\n\t\t\tnearestWallBlocks.add(eastWallBlock);\n\t\t}\n\n\t\tif (Math.abs(this.volume.getSoutheastX() - latestPlayerLocation.getBlockX()) < this.minSafeDistanceFromWall && latestPlayerLocation.getBlockZ() <= this.volume.getNorthwestZ() && latestPlayerLocation.getBlockZ() >= this.volume.getSoutheastZ() && latestPlayerLocation.getBlockY() >= this.volume.getMinY() && latestPlayerLocation.getBlockY() <= this.volume.getMaxY()) {\n\t\t\t// near south wall\n\t\t\tBlock southWallBlock = this.world.getBlockAt(this.volume.getSoutheastX(), latestPlayerLocation.getBlockY() + 1, latestPlayerLocation.getBlockZ());\n\t\t\tnearestWallBlocks.add(southWallBlock);\n\t\t}\n\n\t\tif (Math.abs(this.volume.getNorthwestX() - latestPlayerLocation.getBlockX()) < this.minSafeDistanceFromWall && latestPlayerLocation.getBlockZ() <= this.volume.getNorthwestZ() && latestPlayerLocation.getBlockZ() >= this.volume.getSoutheastZ() && latestPlayerLocation.getBlockY() >= this.volume.getMinY() && latestPlayerLocation.getBlockY() <= this.volume.getMaxY()) {\n\t\t\t// near north wall\n\t\t\tBlock northWallBlock = this.world.getBlockAt(this.volume.getNorthwestX(), latestPlayerLocation.getBlockY() + 1, latestPlayerLocation.getBlockZ());\n\t\t\tnearestWallBlocks.add(northWallBlock);\n\t\t}\n\n\t\tif (Math.abs(this.volume.getNorthwestZ() - latestPlayerLocation.getBlockZ()) < this.minSafeDistanceFromWall && latestPlayerLocation.getBlockX() <= this.volume.getSoutheastX() && latestPlayerLocation.getBlockX() >= this.volume.getNorthwestX() && latestPlayerLocation.getBlockY() >= this.volume.getMinY() && latestPlayerLocation.getBlockY() <= this.volume.getMaxY()) {\n\t\t\t// near west wall\n\t\t\tBlock westWallBlock = this.world.getBlockAt(latestPlayerLocation.getBlockX(), latestPlayerLocation.getBlockY() + 1, this.volume.getNorthwestZ());\n\t\t\tnearestWallBlocks.add(westWallBlock);\n\t\t}\n\n\t\tif (Math.abs(this.volume.getMaxY() - latestPlayerLocation.getBlockY()) < this.minSafeDistanceFromWall && latestPlayerLocation.getBlockX() <= this.volume.getMaxX() && latestPlayerLocation.getBlockX() >= this.volume.getMinX() && latestPlayerLocation.getBlockZ() <= this.volume.getMaxZ() && latestPlayerLocation.getBlockZ() >= this.volume.getMinZ()) {\n\t\t\t// near up wall\n\t\t\tBlock upWallBlock = this.world.getBlockAt(latestPlayerLocation.getBlockX(), this.volume.getMaxY(), latestPlayerLocation.getBlockZ());\n\t\t\tnearestWallBlocks.add(upWallBlock);\n\t\t}\n\n\t\tif (Math.abs(this.volume.getMinY() - latestPlayerLocation.getBlockY()) < this.minSafeDistanceFromWall && latestPlayerLocation.getBlockX() <= this.volume.getMaxX() && latestPlayerLocation.getBlockX() >= this.volume.getMinX() && latestPlayerLocation.getBlockZ() <= this.volume.getMaxZ() && latestPlayerLocation.getBlockZ() >= this.volume.getMinZ()) {\n\t\t\t// near down wall\n\t\t\tBlock downWallBlock = this.world.getBlockAt(latestPlayerLocation.getBlockX(), this.volume.getMinY(), latestPlayerLocation.getBlockZ());\n\t\t\tnearestWallBlocks.add(downWallBlock);\n\t\t}\n\t\treturn nearestWallBlocks;\n\t\t// note: y + 1 to line up 3 sided square with player eyes\n\t}\n\n\tpublic List<BlockFace> getNearestWalls(Location latestPlayerLocation) {\n\t\tList<BlockFace> walls = new ArrayList<BlockFace>();\n\t\tif (Math.abs(this.volume.getSoutheastZ() - latestPlayerLocation.getBlockZ()) < this.minSafeDistanceFromWall && latestPlayerLocation.getBlockX() <= this.volume.getSoutheastX() && latestPlayerLocation.getBlockX() >= this.volume.getNorthwestX() && latestPlayerLocation.getBlockY() >= this.volume.getMinY() && latestPlayerLocation.getBlockY() <= this.volume.getMaxY()) {\n\t\t\t// near east wall\n\t\t\twalls.add(Direction.EAST());\n\t\t}\n\n\t\tif (Math.abs(this.volume.getSoutheastX() - latestPlayerLocation.getBlockX()) < this.minSafeDistanceFromWall && latestPlayerLocation.getBlockZ() <= this.volume.getNorthwestZ() && latestPlayerLocation.getBlockZ() >= this.volume.getSoutheastZ() && latestPlayerLocation.getBlockY() >= this.volume.getMinY() && latestPlayerLocation.getBlockY() <= this.volume.getMaxY()) {\n\t\t\t// near south wall\n\t\t\twalls.add(Direction.SOUTH());\n\t\t}\n\n\t\tif (Math.abs(this.volume.getNorthwestX() - latestPlayerLocation.getBlockX()) < this.minSafeDistanceFromWall && latestPlayerLocation.getBlockZ() <= this.volume.getNorthwestZ() && latestPlayerLocation.getBlockZ() >= this.volume.getSoutheastZ() && latestPlayerLocation.getBlockY() >= this.volume.getMinY() && latestPlayerLocation.getBlockY() <= this.volume.getMaxY()) {\n\t\t\t// near north wall\n\t\t\twalls.add(Direction.NORTH());\n\t\t}\n\n\t\tif (Math.abs(this.volume.getNorthwestZ() - latestPlayerLocation.getBlockZ()) < this.minSafeDistanceFromWall && latestPlayerLocation.getBlockX() <= this.volume.getSoutheastX() && latestPlayerLocation.getBlockX() >= this.volume.getNorthwestX() && latestPlayerLocation.getBlockY() >= this.volume.getMinY() && latestPlayerLocation.getBlockY() <= this.volume.getMaxY()) {\n\t\t\t// near west wall\n\t\t\twalls.add(Direction.WEST());\n\t\t}\n\n\t\tif (Math.abs(this.volume.getMaxY() - latestPlayerLocation.getBlockY()) < this.minSafeDistanceFromWall && latestPlayerLocation.getBlockX() <= this.volume.getMaxX() && latestPlayerLocation.getBlockX() >= this.volume.getMinX() && latestPlayerLocation.getBlockZ() <= this.volume.getMaxZ() && latestPlayerLocation.getBlockZ() >= this.volume.getMinZ()) {\n\t\t\t// near up wall\n\t\t\twalls.add(BlockFace.UP);\n\t\t}\n\n\t\tif (Math.abs(this.volume.getMinY() - latestPlayerLocation.getBlockY()) < this.minSafeDistanceFromWall && latestPlayerLocation.getBlockX() <= this.volume.getMaxX() && latestPlayerLocation.getBlockX() >= this.volume.getMinX() && latestPlayerLocation.getBlockZ() <= this.volume.getMaxZ() && latestPlayerLocation.getBlockZ() >= this.volume.getMinZ()) {\n\t\t\t// near down wall\n\t\t\twalls.add(BlockFace.DOWN);\n\t\t}\n\t\treturn walls;\n\t}\n\n\tpublic ZoneWallGuard getPlayerZoneWallGuard(String name, BlockFace wall) {\n\t\tfor (ZoneWallGuard guard : this.zoneWallGuards) {\n\t\t\tif (guard.getPlayer().getName().equals(name) && wall == guard.getWall()) {\n\t\t\t\treturn guard;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic boolean protectZoneWallAgainstPlayer(Player player) {\n\t\tList<BlockFace> nearestWalls = this.getNearestWalls(player.getLocation());\n\t\tboolean protecting = false;\n\t\tfor (BlockFace wall : nearestWalls) {\n\t\t\tZoneWallGuard guard = this.getPlayerZoneWallGuard(player.getName(), wall);\n\t\t\tif (guard != null) {\n\t\t\t\t// already protected, need to move the guard\n\t\t\t\tguard.updatePlayerPosition(player.getLocation());\n\t\t\t} else {\n\t\t\t\t// new guard\n\t\t\t\tguard = new ZoneWallGuard(player, War.war, this, wall);\n\t\t\t\tthis.zoneWallGuards.add(guard);\n\t\t\t}\n\t\t\tprotecting = true;\n\t\t}\n\t\treturn protecting;\n\t}\n\n\tpublic void dropZoneWallGuardIfAny(Player player) {\n\t\tList<ZoneWallGuard> playerGuards = new ArrayList<ZoneWallGuard>();\n\t\tfor (ZoneWallGuard guard : this.zoneWallGuards) {\n\t\t\tif (guard.getPlayer().getName().equals(player.getName())) {\n\t\t\t\tplayerGuards.add(guard);\n\t\t\t\tguard.deactivate();\n\t\t\t}\n\t\t}\n\t\t// now remove those zone guards\n\t\tfor (ZoneWallGuard playerGuard : playerGuards) {\n\t\t\tthis.zoneWallGuards.remove(playerGuard);\n\t\t}\n\t\tplayerGuards.clear();\n\t}\n\n\tpublic ZoneLobby getLobby() {\n\t\treturn this.lobby;\n\t}\n\n\tpublic void setLobby(ZoneLobby lobby) {\n\t\tthis.lobby = lobby;\n\t}\n\t\n\tpublic Team autoAssign(Player player) {\n\t\tCollections.sort(teams, LEAST_PLAYER_COUNT_ORDER);\n\t\tTeam lowestNoOfPlayers = null;\n\t\tfor (Team team : this.teams) {\n\t\t\tif (War.war.canPlayWar(player, team)) {\n\t\t\t\tlowestNoOfPlayers = team;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif (lowestNoOfPlayers != null) {\n\t\t\tthis.assign(player, lowestNoOfPlayers);\n\t\t}\n\t\treturn lowestNoOfPlayers;\n\t}\n\n\t/**\n\t * Assign a player to a specific team.\n\t *\n\t * @param player\n\t * Player to assign to team.\n\t * @param team\n\t * Team to add the player to.\n\t * @return false if player does not have permission to join this team.\n\t */\n\tpublic boolean assign(Player player, Team team) {\n\t\tif (!War.war.canPlayWar(player, team)) {\n\t\t\tWar.war.badMsg(player, \"join.permission.single\");\n\t\t\treturn false;\n\t\t}\n\t\tif (player.getWorld() != this.getWorld()) {\n\t\t\tplayer.teleport(this.getWorld().getSpawnLocation());\n\t\t}\n\t\tPermissionAttachment attachment = player.addAttachment(War.war);\n\t\tthis.attachments.put(player, attachment);\n\t\tattachment.setPermission(\"war.playing\", true);\n\t\tattachment.setPermission(\"war.playing.\" + this.getName().toLowerCase(), true);\n\t\tteam.addPlayer(player);\n\t\tteam.resetSign();\n\t\tif (this.hasPlayerState(player.getName())) {\n\t\t\tWar.war.getLogger().log(Level.WARNING, \"Player {0} in warzone {1} already has a stored state - they may have lost items\",\n\t\t\t\t\tnew Object[] {player.getName(), this.getName()});\n\t\t\tthis.playerStates.remove(player.getName());\n\t\t}\n\t\tthis.getReallyDeadFighters().remove(player.getName());\n\t\tthis.keepPlayerState(player);\n\t\tWar.war.msg(player, \"join.inventorystored\");\n\t\tthis.respawnPlayer(team, player);\n\t\tthis.broadcast(\"join.broadcast\", player.getName(), team.getKind().getFormattedName());\n\t\tthis.tryCallDelayedPlayers();\n\t\treturn true;\n\t}\n\t\n\tprivate void dropItems(Location location, ItemStack[] items) {\n\t\tfor (ItemStack item : items) {\n\t\t\tif (item == null || item.getType() == Material.AIR) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tlocation.getWorld().dropItem(location, item);\n\t\t}\n\t}\n\t\n\t/**\n\t * Send death messages and process other records before passing off the\n\t * death to the {@link #handleDeath(Player)} method.\n\t * @param attacker Player who killed the defender\n\t * @param defender Player who was killed\n\t * @param damager Entity who caused the damage. Usually an arrow. Used for\n\t * specific death messages. Can be null.\n\t */\n\tpublic void handleKill(Player attacker, Player defender, Entity damager) {\n\t\tTeam attackerTeam = this.getPlayerTeam(attacker.getName());\n\t\tTeam defenderTeam = this.getPlayerTeam(defender.getName());\n\t\tif (this.getWarzoneConfig().getBoolean(WarzoneConfig.DEATHMESSAGES)) {\n\t\t\tString attackerString = attackerTeam.getKind().getColor() + attacker.getName();\n\t\t\tString defenderString = defenderTeam.getKind().getColor() + defender.getName();\n\t\t\tItemStack weapon = attacker.getInventory().getItemInMainHand(); // Not the right way to do this, as they could kill with their other hand, but whatever\n\t\t\tMaterial killerWeapon = weapon.getType();\n\t\t\tString weaponString = killerWeapon.toString();\n\t\t\tif (weapon.hasItemMeta() && weapon.getItemMeta().hasDisplayName()) {\n\t\t\t\tweaponString = weapon.getItemMeta().getDisplayName() + ChatColor.WHITE;\n\t\t\t}\n\t\t\tif (killerWeapon == Material.AIR) {\n\t\t\t\tweaponString = War.war.getString(\"pvp.kill.weapon.hand\");\n\t\t\t} else if (killerWeapon == Material.BOW || damager instanceof Arrow) {\n\t\t\t\tint rand = killSeed.nextInt(3);\n\t\t\t\tif (rand == 0) {\n\t\t\t\t\tweaponString = War.war.getString(\"pvp.kill.weapon.bow\");\n\t\t\t\t} else {\n\t\t\t\t\tweaponString = War.war.getString(\"pvp.kill.weapon.aim\");\n\t\t\t\t}\n\t\t\t} else if (damager instanceof Projectile) {\n\t\t\t\tweaponString = War.war.getString(\"pvp.kill.weapon.aim\");\n\t\t\t}\n\t\t\tString adjectiveString = War.war.getDeadlyAdjectives().isEmpty() ? \"\" : War.war.getDeadlyAdjectives().get(this.killSeed.nextInt(War.war.getDeadlyAdjectives().size()));\n\t\t\tString verbString = War.war.getKillerVerbs().isEmpty() ? \"\" : War.war.getKillerVerbs().get(this.killSeed.nextInt(War.war.getKillerVerbs().size()));\n\t\t\tthis.broadcast(\"pvp.kill.format\", attackerString + ChatColor.WHITE, adjectiveString,\n\t\t\t\t\tweaponString.toLowerCase().replace('_', ' '), verbString, defenderString);\n\t\t}\n\t\tthis.addKillCount(attacker.getName(), 1);\n\t\tthis.addKillDeathRecord(attacker, 1, 0);\n\t\tthis.addKillDeathRecord(defender, 0, 1);\n\t\tif (attackerTeam.getTeamConfig().resolveBoolean(TeamConfig.XPKILLMETER)) {\n\t\t\tattacker.setLevel(this.getKillCount(attacker.getName()));\n\t\t}\n\t\tif (attackerTeam.getTeamConfig().resolveBoolean(TeamConfig.KILLSTREAK)) {\n\t\t\tWar.war.getKillstreakReward().rewardPlayer(attacker, this.getKillCount(attacker.getName()));\n\t\t}\n\t\tthis.updateScoreboard();\n\t\tif (defenderTeam.getTeamConfig().resolveBoolean(TeamConfig.INVENTORYDROP)) {\n\t\t\tdropItems(defender.getLocation(), defender.getInventory().getContents());\n\t\t\tdropItems(defender.getLocation(), defender.getInventory().getArmorContents());\n\t\t}\n\t\tthis.handleDeath(defender);\n\t}\n\n\tpublic void updateScoreboard() {\n\t\tif (this.getScoreboardType() == ScoreboardType.NONE)\n\t\t\treturn;\n\t\tif (this.getScoreboard() == null)\n\t\t\treturn;\n\t\tif (this.scoreboard.getObjective(this.getScoreboardType().name()) == null) {\n\t\t\tfor (String entry : this.scoreboard.getEntries()) {\n\t\t\t\tthis.scoreboard.resetScores(entry);\n\t\t\t}\n\t\t\tthis.scoreboard.clearSlot(DisplaySlot.SIDEBAR);\n\t\t\tfor (Objective obj : this.scoreboard.getObjectives()) {\n\t\t\t\tobj.unregister();\n\t\t\t}\n\t\t\tscoreboard.registerNewObjective(this.getScoreboardType().name(), \"dummy\", this.getScoreboardType().getDisplayName());\n\t\t\tObjective obj = scoreboard.getObjective(this.getScoreboardType().name());\n\t\t\tValidate.isTrue(obj.isModifiable(), \"Cannot modify players' scores on the \" + this.name + \" scoreboard.\");\n\t\t\tobj.setDisplaySlot(DisplaySlot.SIDEBAR);\n\t\t}\n\t\tswitch (this.getScoreboardType()) {\n\t\t\tcase POINTS:\n\t\t\t\tfor (Team team : this.getTeams()) {\n\t\t\t\t\tString teamName = team.getKind().getColor() + team.getName() + ChatColor.RESET;\n\t\t\t\t\tthis.getScoreboard().getObjective(DisplaySlot.SIDEBAR).getScore(teamName).setScore(team.getPoints());\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase LIFEPOOL:\n\t\t\t\tfor (Team team : this.getTeams()) {\n\t\t\t\t\tString teamName = team.getKind().getColor() + team.getName() + ChatColor.RESET;\n\t\t\t\t\tthis.getScoreboard().getObjective(DisplaySlot.SIDEBAR).getScore(teamName).setScore(team.getRemainingLives());\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase TOPKILLS:\n\t\t\t\tfor (Player player : this.getPlayers()) {\n\t\t\t\t\tthis.getScoreboard().getObjective(DisplaySlot.SIDEBAR).getScore(player.getName()).setScore(this.getKillCount(player.getName()));\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase PLAYERCOUNT:\n\t\t\t\tfor (Team team : this.getTeams()) {\n\t\t\t\t\tString teamName = team.getKind().getColor() + team.getName() + ChatColor.RESET;\n\t\t\t\t\tthis.getScoreboard().getObjective(DisplaySlot.SIDEBAR).getScore(teamName).setScore(team.getPlayers().size());\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t}\n\t}\n\t\n\t/**\n\t * Handle death messages before passing to {@link #handleDeath(Player)}\n\t * for post-processing. It's like\n\t * {@link #handleKill(Player, Player, Entity)}, but only for suicides.\n\t * @param player Player who killed himself\n\t */\n\tpublic void handleSuicide(Player player) {\n\t\tif (this.getWarzoneConfig().getBoolean(WarzoneConfig.DEATHMESSAGES)) {\n\t\t\tString defenderString = this.getPlayerTeam(player.getName()).getKind().getColor() + player.getName() + ChatColor.WHITE;\n\t\t\tthis.broadcast(\"pvp.kill.self\", defenderString);\n\t\t}\n\t\tthis.handleDeath(player);\n\t}\n\n\t/**\n\t * Handle a player killed naturally (like by a dispenser or explosion).\n\t * @param player Player killed\n\t * @param event Event causing damage\n\t */\n\tpublic void handleNaturalKill(Player player, EntityDamageEvent event) {\n\t\tif (this.getWarzoneConfig().getBoolean(WarzoneConfig.DEATHMESSAGES)) {\n\t\t\tString defenderString = this.getPlayerTeam(player.getName()).getKind().getColor() + player.getName() + ChatColor.WHITE;\n\t\t\tif (event instanceof EntityDamageByEntityEvent\n\t\t\t\t\t&& ((EntityDamageByEntityEvent) event).getDamager() instanceof TNTPrimed) {\n\t\t\t\tthis.broadcast(\"pvp.death.explosion\", defenderString + ChatColor.WHITE);\n\t\t\t} else if (event.getCause() == DamageCause.FIRE || event.getCause() == DamageCause.FIRE_TICK\n\t\t\t\t\t|| event.getCause() == DamageCause.LAVA || event.getCause() == DamageCause.LIGHTNING) {\n\t\t\t\tthis.broadcast(\"pvp.death.fire\", defenderString);\n\t\t\t} else if (event.getCause() == DamageCause.DROWNING) {\n\t\t\t\tthis.broadcast(\"pvp.death.drown\", defenderString);\n\t\t\t} else if (event.getCause() == DamageCause.FALL) {\n\t\t\t\tthis.broadcast(\"pvp.death.fall\", defenderString);\n\t\t\t} else {\n\t\t\t\tthis.broadcast(\"pvp.death.other\", defenderString);\n\t\t\t}\n\t\t}\n\t\tthis.handleDeath(player);\n\t}\n\n\t/**\n\t * Cleanup after a player who has died. This decrements the team's\n\t * remaining lifepool, drops stolen flags, and respawns the player.\n\t * It also handles team lose and score cap conditions.\n\t * This method is synchronized to prevent concurrent battle resets.\n\t * @param player Player who died\n\t */\n\tpublic synchronized void handleDeath(Player player) {\n\t\tTeam playerTeam = this.getPlayerTeam(player.getName());\n\t\tValidate.notNull(playerTeam, \"Can't find team for dead player \" + player.getName());\n\t\tif (this.getWarzoneConfig().getBoolean(WarzoneConfig.REALDEATHS)) {\n\t\t\tthis.getReallyDeadFighters().add(player.getName());\n\t\t} else {\n\t\t\tthis.respawnPlayer(playerTeam, player);\n\t\t}\n\t\tif (playerTeam.getRemainingLives() <= 0) {\n\t\t\thandleTeamLoss(playerTeam, player);\n\t\t} else {\n\t\t\tthis.dropAllStolenObjects(player, false);\n\t\t\tplayerTeam.setRemainingLives(playerTeam.getRemainingLives() - 1);\n\t\t\t// Lifepool empty warning\n\t\t\tif (playerTeam.getRemainingLives() == 0) {\n\t\t\t\tthis.broadcast(\"zone.lifepool.empty\", playerTeam.getName());\n\t\t\t}\n\t\t}\n\t\tplayerTeam.resetSign();\n\t}\n\n\tprivate void handleTeamLoss(Team losingTeam, Player player) {\n\t\tStringBuilder teamScores = new StringBuilder();\n\t\tList<Team> winningTeams = new ArrayList<Team>(teams.size());\n\t\tfor (Team team : this.teams) {\n\t\t\tif (team.getPlayers().isEmpty())\n\t\t\t\tcontinue;\n\t\t\tif (team != losingTeam) {\n\t\t\t\tteam.addPoint();\n\t\t\t\tteam.resetSign();\n\t\t\t\twinningTeams.add(team);\n\t\t\t}\n\t\t\tteamScores.append(String.format(\"\\n%s (%d/%d) \", team.getName(), team.getPoints(), team.getTeamConfig().resolveInt(TeamConfig.MAXSCORE)));\n\t\t\tteam.sendAchievement(\"Round over! \" + losingTeam.getKind().getFormattedName(), \"ran out of lives.\", losingTeam.getKind().getBlockHead(), 10000);\n\t\t}\n\t\tthis.broadcast(\"zone.battle.end\", losingTeam.getName(), player.getName());\n\t\tWarBattleWinEvent event1 = new WarBattleWinEvent(this, winningTeams);\n\t\tWar.war.getServer().getPluginManager().callEvent(event1);\n\t\tif (!teamScores.toString().isEmpty()) {\n\t\t\tthis.broadcast(\"zone.battle.newscores\", teamScores.toString());\n\t\t}\n\t\tif (War.war.getMysqlConfig().isEnabled() && War.war.getMysqlConfig().isLoggingEnabled()) {\n\t\t\tLogKillsDeathsJob logKillsDeathsJob = new LogKillsDeathsJob(ImmutableList.copyOf(this.getKillsDeathsTracker()));\n\t\t\tlogKillsDeathsJob.runTaskAsynchronously(War.war);\n\t\t}\n\t\tthis.getKillsDeathsTracker().clear();\n\t\tif (!detectScoreCap()) {\n\t\t\tthis.broadcast(\"zone.battle.reset\");\n\t\t\tif (this.getWarzoneConfig().getBoolean(WarzoneConfig.RESETBLOCKS)) {\n\t\t\t\tthis.reinitialize();\n\t\t\t} else {\n\t\t\t\tthis.initializeZone();\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Check if a team has achieved max score \"score cap\".\n\t * @return true if team has achieved max score, false otherwise.\n\t */\n\tpublic boolean detectScoreCap() {\n\t\tStringBuilder winnersStr = new StringBuilder();\n\t\tfor (Team team : this.teams) {\n\t\t\tif (team.getPoints() >= team.getTeamConfig().resolveInt(TeamConfig.MAXSCORE)) {\n\t\t\t\twinnersStr.append(team.getName()).append(' ');\n\t\t\t}\n\t\t}\n\t\tif (!winnersStr.toString().isEmpty())\n\t\t\tthis.handleScoreCapReached(winnersStr.toString());\n\t\treturn !winnersStr.toString().isEmpty();\n\t}\n\n\tpublic void reinitialize() {\n\t\tthis.isReinitializing = true;\n\t\tthis.getVolume().resetBlocksAsJob();\n\t}\n\n\tpublic void handlePlayerLeave(Player player, Location destination, PlayerMoveEvent event, boolean removeFromTeam) {\n\t\tthis.handlePlayerLeave(player);\n\t\tevent.setTo(destination);\n\t}\n\n\tpublic void handlePlayerLeave(Player player, Location destination, boolean removeFromTeam) {\n\t\tthis.handlePlayerLeave(player);\n\t\tplayer.teleport(destination);\n\t}\n\n\tprivate void handlePlayerLeave(Player player) {\n\t\tTeam playerTeam = Team.getTeamByPlayerName(player.getName());\n\t\tif (playerTeam != null) {\n\t\t\tplayerTeam.removePlayer(player);\n\t\t\tthis.broadcast(\"leave.broadcast\", playerTeam.getKind().getColor() + player.getName() + ChatColor.WHITE);\n\t\t\tplayerTeam.resetSign();\n\t\t\tplayer.removeAttachment(this.attachments.remove(player));\n\t\t\tif (this.getPlayerCount() == 0 && this.getWarzoneConfig().getBoolean(WarzoneConfig.RESETONEMPTY)) {\n\t\t\t\t// reset the zone for a new game when the last player leaves\n\t\t\t\tfor (Team team : this.getTeams()) {\n\t\t\t\t\tteam.resetPoints();\n\t\t\t\t\tteam.setRemainingLives(team.getTeamConfig().resolveInt(TeamConfig.LIFEPOOL));\n\t\t\t\t}\n\t\t\t\tif (!this.isReinitializing()) {\n\t\t\t\t\tthis.reinitialize();\n\t\t\t\t\tWar.war.getLogger().log(Level.INFO, \"Last player left warzone {0}. Warzone blocks resetting automatically...\", new Object[] {this.getName()});\n\t\t\t\t}\n\t\t\t}\n\t\t\tthis.autoTeamBalance();\n\n\t\t\tWarPlayerLeaveEvent event1 = new WarPlayerLeaveEvent(player.getName());\n\t\t\tWar.war.getServer().getPluginManager().callEvent(event1);\n\t\t}\n\t}\n\n\t/**\n\t * Moves players from team to team if the player size delta is greater than or equal to 2.\n\t * Only works for autoassign zones.\n\t */\n\tprivate void autoTeamBalance() {\n\t\tif (!this.getWarzoneConfig().getBoolean(WarzoneConfig.AUTOASSIGN)) {\n\t\t\treturn;\n\t\t}\n\t\tboolean rerun = false;\n\t\tfor (Team team1 : this.teams) {\n\t\t\tfor (Team team2 : this.teams) {\n\t\t\t\tif (team1 == team2) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tint t1p = team1.getPlayers().size();\n\t\t\t\tint t2p = team2.getPlayers().size();\n\t\t\t\tif (t1p - t2p >= 2) {\n\t\t\t\t\tPlayer eject = team1.getPlayers().get(killSeed.nextInt(t1p));\n\t\t\t\t\tteam1.removePlayer(eject);\n\t\t\t\t\tteam1.resetSign();\n\t\t\t\t\tthis.assign(eject, team2);\n\t\t\t\t\trerun = true;\n\t\t\t\t\tbreak;\n\t\t\t\t} else if (t2p - t1p >= 2) {\n\t\t\t\t\tPlayer eject = team2.getPlayers().get(killSeed.nextInt(t2p));\n\t\t\t\t\tteam2.removePlayer(eject);\n\t\t\t\t\tteam2.resetSign();\n\t\t\t\t\tthis.assign(eject, team1);\n\t\t\t\t\trerun = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (rerun) {\n\t\t\tthis.autoTeamBalance();\n\t\t}\n\t}\n\n\tpublic boolean isEnemyTeamFlagBlock(Team playerTeam, Block block) {\n\t\tfor (Team team : this.teams) {\n\t\t\tif (!team.getName().equals(playerTeam.getName()) && team.isTeamFlagBlock(block)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tpublic boolean isFlagBlock(Block block) {\n\t\tfor (Team team : this.teams) {\n\t\t\tif (team.isTeamFlagBlock(block)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tpublic Team getTeamForFlagBlock(Block block) {\n\t\tfor (Team team : this.teams) {\n\t\t\tif (team.isTeamFlagBlock(block)) {\n\t\t\t\treturn team;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic boolean isBombBlock(Block block) {\n\t\tfor (Bomb bomb : this.bombs) {\n\t\t\tif (bomb.isBombBlock(block.getLocation())) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tpublic Bomb getBombForBlock(Block block) {\n\t\tfor (Bomb bomb : this.bombs) {\n\t\t\tif (bomb.isBombBlock(block.getLocation())) {\n\t\t\t\treturn bomb;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic boolean isCakeBlock(Block block) {\n\t\tfor (Cake cake : this.cakes) {\n\t\t\tif (cake.isCakeBlock(block.getLocation())) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tpublic Cake getCakeForBlock(Block block) {\n\t\tfor (Cake cake : this.cakes) {\n\t\t\tif (cake.isCakeBlock(block.getLocation())) {\n\t\t\t\treturn cake;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\t// Flags\n\tpublic void addFlagThief(Team lostFlagTeam, Player flagThief) {\n\t\tthis.flagThieves.put(flagThief.getUniqueId(), lostFlagTeam);\n\t\tWarPlayerThiefEvent event1 = new WarPlayerThiefEvent(flagThief, WarPlayerThiefEvent.StolenObject.FLAG);\n\t\tWar.war.getServer().getPluginManager().callEvent(event1);\n\t}\n\n\tpublic boolean isFlagThief(Player suspect) {\n\t\treturn this.flagThieves.containsKey(suspect.getUniqueId());\n\t}\n\n\tpublic Team getVictimTeamForFlagThief(Player thief) {\n\t\treturn this.flagThieves.get(thief.getUniqueId());\n\t}\n\n\tpublic void removeFlagThief(Player thief) {\n\t\tthis.flagThieves.remove(thief.getUniqueId());\n\t}\n\n\t// Bomb\n\tpublic void addBombThief(Bomb bomb, Player bombThief) {\n\t\tthis.bombThieves.put(bombThief.getUniqueId(), bomb);\n\t\tWarPlayerThiefEvent event1 = new WarPlayerThiefEvent(bombThief, WarPlayerThiefEvent.StolenObject.BOMB);\n\t\tWar.war.getServer().getPluginManager().callEvent(event1);\n\t}\n\n\tpublic boolean isBombThief(Player suspect) {\n\t\treturn this.bombThieves.containsKey(suspect.getUniqueId());\n\t}\n\n\tpublic Bomb getBombForThief(Player thief) {\n\t\treturn this.bombThieves.get(thief.getUniqueId());\n\t}\n\t\n\t// Cake\n\n\tpublic void removeBombThief(Player thief) {\n\t\tthis.bombThieves.remove(thief.getUniqueId());\n\t}\n\n\tpublic void addCakeThief(Cake cake, Player cakeThief) {\n\t\tthis.cakeThieves.put(cakeThief.getUniqueId(), cake);\n\t\tWarPlayerThiefEvent event1 = new WarPlayerThiefEvent(cakeThief, WarPlayerThiefEvent.StolenObject.CAKE);\n\t\tWar.war.getServer().getPluginManager().callEvent(event1);\n\t}\n\n\tpublic boolean isCakeThief(Player suspect) {\n\t\treturn this.cakeThieves.containsKey(suspect.getUniqueId());\n\t}\n\n\tpublic Cake getCakeForThief(Player thief) {\n\t\treturn this.cakeThieves.get(thief.getUniqueId());\n\t}\n\n\tpublic void removeCakeThief(Player thief) {\n\t\tthis.cakeThieves.remove(thief.getUniqueId());\n\t}\n\n\tpublic void clearThieves() {\n\t\tthis.flagThieves.clear();\n\t\tthis.bombThieves.clear();\n\t\tthis.cakeThieves.clear();\n\t}\n\n\tpublic boolean isTeamFlagStolen(Team team) {\n\t\tfor (UUID playerKey : this.flagThieves.keySet()) {\n\t\t\tif (this.flagThieves.get(playerKey).getName().equals(team.getName())) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tpublic void handleScoreCapReached(String winnersStr) {\n\t\t// Score cap reached. Reset everything.\n\t\tthis.isEndOfGame = true;\n\t\tList<Team> winningTeams = new ArrayList<Team>(teams.size());\n\t\tfor (String team : winnersStr.split(\" \")) {\n\t\t\twinningTeams.add(this.getTeamByKind(TeamKind.getTeam(team)));\n\t\t}\n\t\tWarScoreCapEvent event1 = new WarScoreCapEvent(winningTeams);\n\t\tWar.war.getServer().getPluginManager().callEvent(event1);\n\n\t\tfor (Team t : this.getTeams()) {\n\t\t\tString winnersStrAndExtra = \"Score cap reached. Game is over! Winning team(s): \" + winnersStr;\n\t\t\twinnersStrAndExtra += \". Resetting warzone and your inventory...\";\n\t\t\tt.teamcast(winnersStrAndExtra);\n\t\t\tdouble ecoReward = t.getTeamConfig().resolveDouble(TeamConfig.ECOREWARD);\n\t\t\tboolean doEcoReward = ecoReward != 0 && War.war.getEconomy() != null;\n\t\t\tfor (Iterator<Player> it = t.getPlayers().iterator(); it.hasNext();) {\n\t\t\t\tPlayer tp = it.next();\n\t\t\t\tit.remove(); // Remove player from team first to prevent anti-tp\n\t\t\t\tt.removePlayer(tp);\n\t\t\t\ttp.teleport(this.getEndTeleport(LeaveCause.SCORECAP));\n\t\t\t\tif (winnersStr.contains(t.getName())) {\n\t\t\t\t\t// give reward\n\t\t\t\t\trewardPlayer(tp, t.getInventories().resolveReward());\n\t\t\t\t\tif (doEcoReward) {\n\t\t\t\t\t\tEconomyResponse r;\n\t\t\t\t\t\tif (ecoReward > 0) {\n\t\t\t\t\t\t\tr = War.war.getEconomy().depositPlayer(tp.getName(), ecoReward);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tr = War.war.getEconomy().withdrawPlayer(tp.getName(), ecoReward);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!r.transactionSuccess()) {\n\t\t\t\t\t\t\tWar.war.getLogger().log(Level.WARNING,\n\t\t\t\t\t\t\t\t\"Failed to reward player {0} ${1}. Error: {2}\",\n\t\t\t\t\t\t\t\tnew Object[] {tp.getName(), ecoReward, r.errorMessage});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tt.resetPoints();\n\t\t\tt.getPlayers().clear(); // empty the team\n\t\t\tt.resetSign();\n\t\t}\n\t\tif (this.getWarzoneConfig().getBoolean(WarzoneConfig.RESETBLOCKS)) {\n\t\t\tthis.reinitialize();\n\t\t} else {\n\t\t\tthis.initializeZone();\n\t\t}\n\t}\n\n\tpublic void rewardPlayer(Player player, Map<Integer, ItemStack> reward) {\n\t\tfor (Integer slot : reward.keySet()) {\n\t\t\tItemStack item = reward.get(slot);\n\t\t\tif (item != null) {\n\t\t\t\tplayer.getInventory().addItem(item);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic boolean isDeadMan(String playerName) {\n\t\treturn this.deadMenInventories.containsKey(playerName);\n\t}\n\n\tpublic void restoreDeadmanInventory(Player player) {\n\t\tif (this.isDeadMan(player.getName())) {\n\t\t\tthis.playerInvFromInventoryStash(player.getInventory(), this.deadMenInventories.get(player.getName()));\n\t\t\tthis.deadMenInventories.remove(player.getName());\n\t\t}\n\t}\n\n\tpublic Location getRallyPoint() {\n\t\treturn this.rallyPoint;\n\t}\n\n\tpublic void setRallyPoint(Location location) {\n\t\tthis.rallyPoint = location;\n\t}\n\n\tpublic void unload() {\n\t\tWar.war.log(\"Unloading zone \" + this.getName() + \"...\", Level.INFO);\n\t\tfor (Team team : this.getTeams()) {\n\t\t\tfor (Iterator<Player> it = team.getPlayers().iterator(); it.hasNext(); ) {\n\t\t\t\tfinal Player player = it.next();\n\t\t\t\tit.remove();\n\t\t\t\tteam.removePlayer(player);\n\t\t\t\tplayer.teleport(this.getTeleport());\n\t\t\t}\n\t\t}\n\t\tif (this.getLobby() != null) {\n\t\t\tthis.getLobby().getVolume().resetBlocks();\n\t\t}\n\t\tif (this.getWarzoneConfig().getBoolean(WarzoneConfig.RESETONUNLOAD)) {\n\t\t\tthis.getVolume().resetBlocks();\n\t\t}\n\t}\n\n\tpublic boolean isEnoughPlayers() {\n\t\tint teamsWithEnough = 0;\n\t\tfor (Team team : teams) {\n\t\t\tif (team.getPlayers().size() >= this.getWarzoneConfig().getInt(WarzoneConfig.MINPLAYERS)) {\n\t\t\t\tteamsWithEnough++;\n\t\t\t}\n\t\t}\n\t\treturn teamsWithEnough >= this.getWarzoneConfig().getInt(WarzoneConfig.MINTEAMS);\n\t}\n\n\t/**\n\t * Test whether there would be enough players with the addition of one more player\n\t *\n\t * @param plusOne Team to test\n\t * @return true if there would be enough players\n\t */\n\tpublic boolean testEnoughPlayers(TeamKind plusOne, boolean testDelayedJoin) {\n\t\tint teamsWithEnough = 0;\n\t\tfor (Team team : teams) {\n\t\t\tint addl = 0;\n\t\t\tif (team.getKind() == plusOne) {\n\t\t\t\taddl = 1;\n\t\t\t}\n\t\t\tif (testDelayedJoin) {\n\t\t\t\tfor (Iterator<Map.Entry<Player, Team>> iterator = this.delayedJoinPlayers.entrySet().iterator(); iterator.hasNext(); ) {\n\t\t\t\t\tMap.Entry<Player, Team> e = iterator.next();\n\t\t\t\t\tif (!isDelayedPlayerStillValid(e.getKey())) {\n\t\t\t\t\t\titerator.remove();\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tif (e.getValue() == team) {\n\t\t\t\t\t\taddl += 1;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (team.getPlayers().size() + addl >= this.getWarzoneConfig().getInt(WarzoneConfig.MINPLAYERS)) {\n\t\t\t\tteamsWithEnough++;\n\t\t\t}\n\t\t}\n\t\treturn teamsWithEnough >= this.getWarzoneConfig().getInt(WarzoneConfig.MINTEAMS);\n\t}\n\n\tpublic void signup(Player player, Team team) {\n\t\tWar.war.msg(player, \"You will be automatically sent to warzone when minplayers is reached.\");\n\t\tthis.delayedJoinPlayers.put(player, team);\n\t\ttryCallDelayedPlayers();\n\t}\n\n\tprivate void tryCallDelayedPlayers() {\n\t\tif (activeDelayedCall || (!isEnoughPlayers() && !testEnoughPlayers(null, true))) {\n\t\t\treturn;\n\t\t}\n\t\tactiveDelayedCall = true;\n\t\tfor (Map.Entry<Player, Team> e : delayedJoinPlayers.entrySet()) {\n\t\t\tthis.assign(e.getKey(), e.getValue());\n\t\t}\n\t\tdelayedJoinPlayers.clear();\n\t\tactiveDelayedCall = false;\n\t}\n\n\tprivate boolean isDelayedPlayerStillValid(Player player) {\n\t\t// Make sure they're online, they can play in this team, and they're not in another game\n\t\treturn player.isOnline() && War.war.canPlayWar(player, delayedJoinPlayers.get(player))\n\t\t\t\t&& Warzone.getZoneByPlayerName(player.getName()) == null;\n\t}\n\n\n\tpublic HashMap<String, LoadoutSelection> getLoadoutSelections() {\n\t\treturn loadoutSelections;\n\t}\n\n\tpublic boolean isAuthor(Player player) {\n\t\t// if no authors, all zonemakers can edit the zone\n\t\treturn authors.size() == 0 || authors.contains(player.getName());\n\t}\n\t\t\n\tpublic void addAuthor(String playerName) {\n\t\tauthors.add(playerName);\n\t}\n\t\n\tpublic List<String> getAuthors() {\n\t\treturn this.authors;\n\t}\n\n\tpublic String getAuthorsString() {\n\t\tString authors = \"\";\n\t\tfor (String author : this.getAuthors()) {\n\t\t\tauthors += author + \",\";\n\t\t}\n\t\treturn authors;\n\t}\n\n\tpublic void equipPlayerLoadoutSelection(Player player, Team playerTeam, boolean isFirstRespawn, boolean isToggle) {\n\t\tLoadoutSelection selection = this.getLoadoutSelections().get(player.getName());\n\t\tif (selection != null && !this.isRespawning(player) && playerTeam.getPlayers().contains(player)) {\n\t\t\t// Make sure that inventory resets dont occur if player has already tp'ed out (due to game end, or somesuch) \n\t\t\t// - repawn timer + this method is why inventories were getting wiped as players exited the warzone. \n\t\t\tList<Loadout> loadouts = playerTeam.getInventories().resolveNewLoadouts();\n\t\t\tList<String> sortedNames = LoadoutYmlMapper.sortNames(Loadout.toLegacyFormat(loadouts));\n\t\t\tsortedNames.remove(\"first\");\n\t\t\tsortedNames.remove(\"banned\");\n\t\t\tfor (Iterator<String> it = sortedNames.iterator(); it.hasNext();) {\n\t\t\t\tString loadoutName = it.next();\n\t\t\t\tLoadout ldt = Loadout.getLoadout(loadouts, loadoutName);\n\t\t\t\tif (ldt == null) {\n\t\t\t\t\tWar.war.getLogger().warning(\"Failed to resolve loadout \" + loadoutName);\n\t\t\t\t\tit.remove();\n\t\t\t\t}\n\t\t\t\tif (ldt.requiresPermission() && !player.hasPermission(ldt.getPermission())) {\n\t\t\t\t\tit.remove();\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (sortedNames.isEmpty()) {\n\t\t\t\t// Fix for zones that mistakenly only specify a `first' loadout, but do not add any others.\n\t\t\t\tthis.resetInventory(playerTeam, player, Collections.<Integer, ItemStack>emptyMap());\n\t\t\t\tWar.war.msg(player, \"404 No loadouts found\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tint currentIndex = selection.getSelectedIndex();\n\t\t\tLoadout firstLoadout = Loadout.getLoadout(loadouts, \"first\");\n\t\t\tint i = 0;\n\t\t\tIterator<String> it = sortedNames.iterator();\n\t\t\twhile (it.hasNext()) {\n\t\t\t\tString name = it.next();\n\t\t\t\tif (i == currentIndex) {\n\t\t\t\t\tif (playerTeam.getTeamConfig().resolveBoolean(TeamConfig.PLAYERLOADOUTASDEFAULT) && name.equals(\"default\")) {\n\t\t\t\t\t\t// Use player's own inventory as loadout\n\t\t\t\t\t\tthis.resetInventory(playerTeam, player, this.getPlayerInventoryFromSavedState(player));\n\t\t\t\t\t} else if (isFirstRespawn && firstLoadout != null && name.equals(\"default\")\n\t\t\t\t\t\t\t&& (!firstLoadout.requiresPermission() || player.hasPermission(firstLoadout.getPermission()))) {\n\t\t\t\t\t\t// Get the loadout for the first spawn\n\t\t\t\t\t\tthis.resetInventory(playerTeam, player, firstLoadout.getContents());\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Use the loadout from the list in the settings\n\t\t\t\t\t\tthis.resetInventory(playerTeam, player, Loadout.getLoadout(loadouts, name).getContents());\n\t\t\t\t\t}\n\t\t\t\t\tif (isFirstRespawn && playerTeam.getInventories().resolveLoadouts().keySet().size() > 1 || isToggle) {\n\t\t\t\t\t\tWar.war.msg(player, \"zone.loadout.equip\", name);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate HashMap<Integer, ItemStack> getPlayerInventoryFromSavedState(Player player) {\n\t\tHashMap<Integer, ItemStack> playerItems = new HashMap<Integer, ItemStack>();\n\t\tPlayerState originalState = this.playerStates.get(player.getName());\n\n\t\tif (originalState != null) {\n\t\t\tint invIndex = 0;\n\t\t\tplayerItems = new HashMap<Integer, ItemStack>();\n\t\t\tfor (ItemStack item : originalState.getContents()) {\n\t\t\t\tif (item != null && item.getType() != Material.AIR) {\n\t\t\t\t\tplayerItems.put(invIndex, item);\n\t\t\t\t}\n\t\t\t\tinvIndex++;\n\t\t\t}\n\t\t\tif (originalState.getFeet() != null) {\n\t\t\t\tplayerItems.put(100, originalState.getFeet());\n\t\t\t}\n\t\t\tif (originalState.getLegs() != null) {\n\t\t\t\tplayerItems.put(101, originalState.getLegs());\n\t\t\t}\n\t\t\tif (originalState.getChest() != null) {\n\t\t\t\tplayerItems.put(102, originalState.getChest());\n\t\t\t}\n\t\t\tif (originalState.getHelmet() != null) {\n\t\t\t\tplayerItems.put(103, originalState.getHelmet());\n\t\t\t}\n\t\t\t\n\t\t}\n\t\t\n\t\treturn playerItems;\n\t}\n\n\tpublic WarzoneConfigBag getWarzoneConfig() {\n\t\treturn this.warzoneConfig;\n\t}\n\t\n\tpublic TeamConfigBag getTeamDefaultConfig() {\n\t\treturn this.teamDefaultConfig;\n\t}\n\n\tpublic InventoryBag getDefaultInventories() {\n\t\treturn this.defaultInventories ;\n\t}\n\n\tpublic List<Bomb> getBombs() {\n\t\treturn bombs;\n\t}\n\n\tpublic List<Cake> getCakes() {\n\t\treturn cakes;\n\t}\n\n\tpublic List<CapturePoint> getCapturePoints() {\n\t\treturn capturePoints;\n\t}\n\n\tpublic List<String> getReallyDeadFighters() {\n\t\treturn this.reallyDeadFighters ;\n\t}\n\n\tpublic boolean isEndOfGame() {\n\t\treturn this.isEndOfGame;\n\t}\n\n\tpublic boolean isReinitializing() {\n\t\treturn this.isReinitializing;\n\t}\n\n//\tpublic Object getGameEndLock() {\n//\t\treturn gameEndLock;\n//\t}\n\n\tpublic HubLobbyMaterials getLobbyMaterials() {\n\t\treturn this.lobbyMaterials;\n\t}\n\n\tpublic void setLobbyMaterials(HubLobbyMaterials lobbyMaterials) {\n\t\tthis.lobbyMaterials = lobbyMaterials;\n\t}\n\n\tpublic boolean isOpponentSpawnPeripheryBlock(Team team, Block block) {\n\t\tfor (Team maybeOpponent : this.getTeams()) {\n\t\t\tif (maybeOpponent != team) {\n\t\t\t\tfor (Volume teamSpawnVolume : maybeOpponent.getSpawnVolumes().values()) {\n\t\t\t\t\tVolume periphery = new Volume(new Location(\n\t\t\t\t\t\t\tteamSpawnVolume.getWorld(),\n\t\t\t\t\t\t\tteamSpawnVolume.getMinX() - 1,\n\t\t\t\t\t\t\tteamSpawnVolume.getMinY() - 1,\n\t\t\t\t\t\t\tteamSpawnVolume.getMinZ() - 1), new Location(\n\t\t\t\t\t\t\tteamSpawnVolume.getWorld(),\n\t\t\t\t\t\t\tteamSpawnVolume.getMaxX() + 1,\n\t\t\t\t\t\t\tteamSpawnVolume.getMaxY() + 1,\n\t\t\t\t\t\t\tteamSpawnVolume.getMaxZ() + 1));\n\t\t\t\t\tif (periphery.contains(block)) {\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tpublic WarzoneMaterials getWarzoneMaterials() {\n\t\treturn warzoneMaterials;\n\t}\n\n\tpublic void setWarzoneMaterials(WarzoneMaterials warzoneMaterials) {\n\t\tthis.warzoneMaterials = warzoneMaterials;\n\t}\n\n\tpublic Scoreboard getScoreboard() {\n\t\treturn scoreboard;\n\t}\n\n\tpublic ScoreboardType getScoreboardType() {\n\t\treturn scoreboardType;\n\t}\n\n\t/**\n\t * Sets the TEMPORARY scoreboard type for use in this warzone.\n\t * This type will NOT be persisted in the Warzone config.\n\t *\n\t * @param scoreboardType temporary scoreboard type\n\t */\n\tpublic void setScoreboardType(ScoreboardType scoreboardType) {\n\t\tthis.scoreboardType = scoreboardType;\n\t}\n\n\tpublic boolean hasKillCount(String player) {\n\t\treturn killCount.containsKey(player);\n\t}\n\n\tpublic int getKillCount(String player) {\n\t\treturn killCount.get(player);\n\t}\n\n\tpublic void setKillCount(String player, int totalKills) {\n\t\tif (totalKills < 0) {\n\t\t\tthrow new IllegalArgumentException(\"Amount of kills to set cannot be a negative number.\");\n\t\t}\n\t\tkillCount.put(player, totalKills);\n\t}\n\n\tpublic void addKillCount(String player, int amount) {\n\t\tif (amount < 0) {\n\t\t\tthrow new IllegalArgumentException(\"Amount of kills to add cannot be a negative number.\");\n\t\t}\n\t\tkillCount.put(player, killCount.get(player) + amount);\n\t}\n\n\tpublic void addKillDeathRecord(OfflinePlayer player, int kills, int deaths) {\n\t\tfor (Iterator<KillsDeathsRecord> it = this.killsDeathsTracker.iterator(); it.hasNext();) {\n\t\t\tLogKillsDeathsJob.KillsDeathsRecord kdr = it.next();\n\t\t\tif (kdr.getPlayer().equals(player)) {\n\t\t\t\tkills += kdr.getKills();\n\t\t\t\tdeaths += kdr.getDeaths();\n\t\t\t\tit.remove();\n\t\t\t}\n\t\t}\n\t\tLogKillsDeathsJob.KillsDeathsRecord kdr = new LogKillsDeathsJob.KillsDeathsRecord(player, kills, deaths);\n\t\tthis.killsDeathsTracker.add(kdr);\n\t}\n\n\tpublic List<LogKillsDeathsJob.KillsDeathsRecord> getKillsDeathsTracker() {\n\t\treturn killsDeathsTracker;\n\t}\n\n\t/**\n\t * Send a message to all teams.\n\t * @param message Message or key to translate.\n\t */\n\tpublic void broadcast(String message) {\n\t\tfor (Team team : this.teams) {\n\t\t\tteam.teamcast(message);\n\t\t}\n\t}\n\n\t/**\n\t * Send a message to all teams.\n\t * @param message Message or key to translate.\n\t * @param args Arguments for the formatter.\n\t */\n\tpublic void broadcast(String message, Object... args) {\n\t\tfor (Team team : this.teams) {\n\t\t\tteam.teamcast(message, args);\n\t\t}\n\t}\n\n\t/**\n\t * Get a list of all players in the warzone. The list is immutable. If you\n\t * need to modify the player list, you must use the per-team lists\n\t *\n\t * @return list containing all team players.\n\t */\n\tpublic List<Player> getPlayers() {\n\t\tList<Player> players = new ArrayList<Player>();\n\t\tfor (Team team : this.teams) {\n\t\t\tplayers.addAll(team.getPlayers());\n\t\t}\n\t\treturn players;\n\t}\n\n\t/**\n\t * Get the amount of players in all teams in this warzone.\n\t *\n\t * @return total player count\n\t */\n\tpublic int getPlayerCount() {\n\t\tint count = 0;\n\t\tfor (Team team : this.teams) {\n\t\t\tcount += team.getPlayers().size();\n\t\t}\n\t\treturn count;\n\t}\n\n\tpublic int getMaxPlayers() {\n\t\tint zoneCap = 0;\n\t\tfor (Team t : this.getTeams()) {\n\t\t\tzoneCap += t.getTeamConfig().resolveInt(TeamConfig.TEAMSIZE);\n\t\t}\n\t\treturn zoneCap;\n\t}\n\n\t/**\n\t * Get the amount of players in all teams in this warzone. Same as\n\t * {@link #getPlayerCount()}, except only checks teams that the specified\n\t * player has permission to join.\n\t *\n\t * @param target\n\t * Player to check for permissions.\n\t * @return total player count in teams the player has access to.\n\t */\n\tpublic int getPlayerCount(Permissible target) {\n\t\tint playerCount = 0;\n\t\tfor (Team team : this.teams) {\n\t\t\tif (target.hasPermission(team.getTeamConfig().resolveString(\n\t\t\t\t\tTeamConfig.PERMISSION))) {\n\t\t\t\tplayerCount += team.getPlayers().size();\n\t\t\t}\n\t\t}\n\t\treturn playerCount;\n\t}\n\n\t/**\n\t * Get the total capacity of all teams in this zone. This should be\n\t * preferred over {@link TeamConfig#TEAMSIZE} as that can differ per team.\n\t *\n\t * @return capacity of all teams in this zone\n\t */\n\tpublic int getTotalCapacity() {\n\t\tint capacity = 0;\n\t\tfor (Team team : this.teams) {\n\t\t\tcapacity += team.getTeamConfig().resolveInt(TeamConfig.TEAMSIZE);\n\t\t}\n\t\treturn capacity;\n\t}\n\n\t/**\n\t * Get the total capacity of all teams in this zone. Same as\n\t * {@link #getTotalCapacity()}, except only checks teams that the specified\n\t * player has permission to join.\n\t *\n\t * @param target\n\t * Player to check for permissions.\n\t * @return capacity of teams the player has access to.\n\t */\n\tpublic int getTotalCapacity(Permissible target) {\n\t\tint capacity = 0;\n\t\tfor (Team team : this.teams) {\n\t\t\tif (target.hasPermission(team.getTeamConfig().resolveString(\n\t\t\t\t\tTeamConfig.PERMISSION))) {\n\t\t\t\tcapacity += team.getTeamConfig()\n\t\t\t\t\t\t.resolveInt(TeamConfig.TEAMSIZE);\n\t\t\t}\n\t\t}\n\t\treturn capacity;\n\t}\n\n\t/**\n\t * Check if all teams are full.\n\t *\n\t * @return true if all teams are full, false otherwise.\n\t */\n\tpublic boolean isFull() {\n\t\treturn this.getPlayerCount() == this.getTotalCapacity();\n\t}\n\n\t/**\n\t * Check if all teams are full. Same as {@link #isFull()}, except only\n\t * checks teams that the specified player has permission to join.\n\t *\n\t * @param target\n\t * Player to check for permissions.\n\t * @return true if all teams are full, false otherwise.\n\t */\n\tpublic boolean isFull(Permissible target) {\n\t\treturn this.getPlayerCount(target) == this.getTotalCapacity(target);\n\t}\n\n\tpublic void dropAllStolenObjects(Player player, boolean quiet) {\n\t\tif (this.isFlagThief(player)) {\n\t\t\tTeam victimTeam = this.getVictimTeamForFlagThief(player);\n\n\t\t\tthis.removeFlagThief(player);\n\n\t\t\t// Bring back flag of victim team\n\t\t\tvictimTeam.getFlagVolume().resetBlocks();\n\t\t\tvictimTeam.initializeTeamFlag();\n\n\t\t\tif (!quiet) {\n\t\t\t\tthis.broadcast(\"drop.flag.broadcast\", player.getName(), victimTeam.getKind().getColor() + victimTeam.getName() + ChatColor.WHITE);\n\t\t\t}\n\t\t} else if (this.isCakeThief(player)) {\n\t\t\tCake cake = this.getCakeForThief(player);\n\n\t\t\tthis.removeCakeThief(player);\n\n\t\t\t// Bring back cake\n\t\t\tcake.getVolume().resetBlocks();\n\t\t\tcake.addCakeBlocks();\n\n\t\t\tif (!quiet) {\n\t\t\t\tthis.broadcast(\"drop.cake.broadcast\", player.getName(), ChatColor.GREEN + cake.getName() + ChatColor.WHITE);\n\t\t\t}\n\t\t} else if (this.isBombThief(player)) {\n\t\t\tBomb bomb = this.getBombForThief(player);\n\n\t\t\tthis.removeBombThief(player);\n\n\t\t\t// Bring back bomb\n\t\t\tbomb.getVolume().resetBlocks();\n\t\t\tbomb.addBombBlocks();\n\n\t\t\tif (!quiet) {\n\t\t\t\tthis.broadcast(\"drop.bomb.broadcast\", player.getName(), ChatColor.GREEN + bomb.getName() + ChatColor.WHITE);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Get the proper ending teleport location for players leaving the warzone.\n\t * <p>\n\t * Specifically, it gets teleports in this order:\n\t * <ul>\n\t * <li>Rally point (if scorecap)\n\t * <li>Warhub (if autojoin)\n\t * <li>Lobby\n\t * </ul>\n\t * </p>\n\t * @param reason Reason for leaving zone\n\t * @return\n\t */\n\tpublic Location getEndTeleport(LeaveCause reason) {\n\t\tif (reason.useRallyPoint() && this.getRallyPoint() != null) {\n\t\t\treturn this.getRallyPoint();\n\t\t}\n\t\tif (this.getWarzoneConfig().getBoolean(WarzoneConfig.AUTOJOIN)\n\t\t\t\t&& War.war.getWarHub() != null) {\n\t\t\treturn War.war.getWarHub().getLocation();\n\t\t}\n\t\treturn this.getTeleport();\n\t}\n\n\tpublic Volume loadStructure(String volName, World world) throws SQLException {\n\t\treturn loadStructure(volName, world, ZoneVolumeMapper.getZoneConnection(volume, name));\n\t}\n\n\tpublic Volume loadStructure(String volName, Connection zoneConnection) throws SQLException {\n\t\treturn loadStructure(volName, world, zoneConnection);\n\t}\n\n\tpublic Volume loadStructure(String volName, World world, Connection zoneConnection) throws SQLException {\n\t\tVolume volume = new Volume(volName, world);\n\t\tZoneVolumeMapper.loadStructure(volume, zoneConnection);\n\t\treturn volume;\n\t}\n\n\tprivate boolean containsTable(String table, Connection connection) throws SQLException {\n\t\tPreparedStatement stmt = connection.prepareStatement(\"SELECT COUNT(*) AS ct FROM sqlite_master WHERE type = ? AND name = ?\");\n\t\tstmt.setString(1, \"table\");\n\t\tstmt.setString(2, table);\n\t\tResultSet resultSet = stmt.executeQuery();\n\t\ttry {\n\t\t\treturn resultSet.next() && resultSet.getInt(\"ct\") > 0;\n\t\t} finally {\n\t\t\tresultSet.close();\n\t\t\tstmt.close();\n\t\t}\n\t}\n\n\t/**\n\t * Check if a player has stolen from a warzone flag, bomb, or cake.\n\t * @param suspect Player to check.\n\t * @return true if suspect has stolen a structure.\n\t */\n\tpublic boolean isThief(Player suspect) {\n\t\treturn this.isFlagThief(suspect) || this.isBombThief(suspect) || this.isCakeThief(suspect);\n\t}\n\n\tpublic boolean getPvpReady() {\n\t\treturn this.pvpReady;\n\t}\n\t\n\tpublic void setPvpReady(boolean ready) {\n\t\tthis.pvpReady = ready;\n\t}\n\n\tpublic enum LeaveCause {\n\t\tCOMMAND, DISCONNECT, SCORECAP, RESET;\n\n\t\tpublic boolean useRallyPoint() {\n\t\t\treturn this == SCORECAP;\n\t\t}\n\t}\n}",
"public enum TeamKind {\n\tWHITE (DyeColor.WHITE, Material.WHITE_WOOL, ChatColor.WHITE, 450),\n\tORANGE (DyeColor.ORANGE, Material.ORANGE_WOOL, ChatColor.GOLD, 51),\n\tMAGENTA (DyeColor.MAGENTA, Material.MAGENTA_WOOL, ChatColor.LIGHT_PURPLE, 353),\n\tBLUE (DyeColor.LIGHT_BLUE, Material.LIGHT_BLUE_WOOL, ChatColor.BLUE, 23),\n\tGOLD (DyeColor.YELLOW, Material.YELLOW_WOOL, ChatColor.YELLOW, 403), // yellow = gold\n\tGREEN (DyeColor.LIME, Material.LIME_WOOL, ChatColor.GREEN, 612),\n\tPINK (DyeColor.PINK, Material.PINK_WOOL, ChatColor.LIGHT_PURPLE, 929),\n\tGRAY (DyeColor.GRAY, Material.GRAY_WOOL, ChatColor.DARK_GRAY, 600),\n\tIRON (DyeColor.GRAY, Material.GRAY_WOOL, ChatColor.GRAY, 154), // lightgrey = iron\n\tDIAMOND (DyeColor.CYAN, Material.CYAN_WOOL, ChatColor.DARK_AQUA, 738), // cyan = diamond\n\tPURPLE (DyeColor.PURPLE, Material.PURPLE_WOOL, ChatColor.DARK_PURPLE, 153),\n\tNAVY (DyeColor.BLUE, Material.BLUE_WOOL, ChatColor.DARK_BLUE, 939),\n\tBROWN (DyeColor.BROWN, Material.BROWN_WOOL, ChatColor.DARK_RED, 908),\n\tDARKGREEN (DyeColor.GREEN, Material.GREEN_WOOL, ChatColor.DARK_GREEN, 612),\n\tRED (DyeColor.RED, Material.RED_WOOL, ChatColor.RED, 245),\n\tBLACK (DyeColor.BLACK, Material.BLACK_WOOL, ChatColor.BLACK, 0);\n\n\tprivate final DyeColor dyeColor;\n\tprivate final ChatColor chatColor;\n\tprivate final Material material;\n\tprivate final int potionEffectColor;\n\n\tTeamKind(DyeColor blockHeadColor, Material material, ChatColor color, int potionEffectColor) {\n\t\tthis.dyeColor = blockHeadColor;\n\t\tthis.material = material;\n\t\tthis.chatColor = color;\n\t\tthis.potionEffectColor = potionEffectColor;\n\t}\n\n\tpublic static TeamKind teamKindFromString(String str) {\n\t\tString lowered = str.toLowerCase();\n\t\tfor (TeamKind kind : TeamKind.values()) {\n\t\t\tif (kind.toString().startsWith(lowered)) {\n\t\t\t\treturn kind;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic static TeamKind getTeam(String teamName) {\n\t\tfor (TeamKind team : TeamKind.values()) {\n\t\t\tif (team.toString().equalsIgnoreCase(teamName)) {\n\t\t\t\treturn team;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\t/**\n\t * Get wool block data for the dye color.\n\t * @deprecated TODO remove all spout craft support\n\t * @return wool color data value\n\t */\n\tpublic byte getData() {\n\t\treturn this.dyeColor.getWoolData();\n\t}\n\n\t/**\n\t * Get the color of this team in chat messages.\n\t *\n\t * @return team chat color.\n\t */\n\tpublic ChatColor getColor() {\n\t\treturn this.chatColor;\n\t}\n\n\t/**\n\t * Get the color of the wool block as a bukkit color.\n\t *\n\t * @return wool block color.\n\t */\n\tpublic org.bukkit.Color getBukkitColor() {\n\t\treturn this.dyeColor.getColor();\n\t}\n\n\t/**\n\t * Get head block material.\n\t *\n\t * @return team head block material.\n\t */\n\tpublic Material getMaterial() {\n\t\treturn this.material;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn super.toString().toLowerCase();\n\t}\n\n\t/**\n\t * Get color of the team's potion effect, for thieves.\n\t *\n\t * @return potion effect color.\n\t */\n\tpublic int getPotionEffectColor() {\n\t\treturn this.potionEffectColor;\n\t}\n\n\t/**\n\t * Get a single item of this team's wool head block.\n\t *\n\t * @return single block head item.\n\t */\n\tpublic ItemStack getBlockHead() {\n\t\treturn new ItemStack(this.material, 1);\n\t}\n\n\t/**\n\t * Check if a block is this team's color block.\n\t *\n\t * @param block Wool block to check.\n\t * @return true if block is this team's color.\n\t */\n\tpublic boolean isTeamBlock(BlockState block) {\n\t\treturn block.getType() == material;\n\t}\n\n\t/**\n\t * Check if an item is this team's color block.\n\t *\n\t * @param item Wool item to check.\n\t * @return true if item is this team's color.\n\t */\n\tpublic boolean isTeamItem(ItemStack item) {\n\t\treturn item.getType() == material;\n\t}\n\n\tpublic String getFormattedName() {\n\t\treturn this.getColor() + this.name().toLowerCase() + ChatColor.WHITE;\n\t}\n\n\tpublic String getCapsName() {\n\t\treturn String.valueOf(name().charAt(0)) + name().substring(1).toLowerCase();\n\t}\n\n\t/**\n\t * Get a colored hat item for the team.\n\t * @return Hat item with the team's color.\n\t */\n\tpublic ItemStack getHat() {\n\t\tItemStack helmet = new ItemStack(Material.LEATHER_HELMET);\n\t\tLeatherArmorMeta meta = (LeatherArmorMeta) helmet.getItemMeta();\n\t\tmeta.setColor(this.getBukkitColor());\n\t\thelmet.setItemMeta(meta);\n\t\treturn helmet;\n\t}\n}",
"public class WarzoneYmlMapper {\n\n\tpublic static Warzone load(String name) { // removed createNewVolume, as it did nothing\n\t\tFile warzoneTxtFile = new File(War.war.getDataFolder().getPath() + \"/warzone-\" + name + \".txt\");\n\t\tFile warzoneYmlFile = new File(War.war.getDataFolder().getPath() + \"/warzone-\" + name + \".yml\");\n\t\t\n\t\t// Convert from TXT to YML if needed\n\t\tif (warzoneTxtFile.exists() && !warzoneYmlFile.exists()) {\n\t\t\t// dropped nimitz compatibility with the MC 1.13 update\n\t\t\tWar.war.log(\"Failed to load Warzone \" + name + \" - backwards compatibility was dropped with MC 1.13. Please delete this zone to continue.\", Level.WARNING);\n\t\t\treturn null;\n\t\t}\n\t\t\n\t\tif (!warzoneYmlFile.exists()) {\n\t\t\tWar.war.log(\"File warzone-\" + name + \".yml not found\", Level.WARNING);\n\t\t} else {\n\t\t\tYamlConfiguration warzoneYmlConfig = YamlConfiguration.loadConfiguration(warzoneYmlFile);\n\t\t\tConfigurationSection warzoneRootSection = warzoneYmlConfig.getConfigurationSection(\"set\");\n\t\t\t\n\t\t\t// Bukkit config API forces all Yml nodes to lowercase, now, it seems, sigh...\n\t\t\t// We need to keep this original (non-lowercase) implementation because old warzone.yml\n\t\t\t// files are not lowercased yet if they haven't been saved since the API change.\n\t\t\tString zoneInfoPrefix = \"warzone.\" + name + \".info.\";\n\t\t\t\n\t\t\t// world of the warzone\n\t\t\tString worldStr = warzoneRootSection.getString(zoneInfoPrefix + \"world\");\n\t\t\tif (worldStr == null) {\n\t\t\t\t// Ah! Seems that the new (post 1.2.3-ish) Bukkit config API has lowercased our map name on the previous save.\n\t\t\t\t// Retry with lowercase warzone name.\n\t\t\t\tzoneInfoPrefix = \"warzone.\" + name.toLowerCase() + \".info.\";\n\t\t\t\tworldStr = warzoneRootSection.getString(zoneInfoPrefix + \"world\");\n\t\t\t}\n\t\t\tWorld world = War.war.getServer().getWorld(worldStr);\n\t\t\t\n\t\t\t// Create the zone\n\t\t\tWarzone warzone = new Warzone(world, name);\n\n\t\t\t// teleport\n\t\t\tint teleX = warzoneRootSection.getInt(zoneInfoPrefix + \"teleport.x\");\n\t\t\tint teleY = warzoneRootSection.getInt(zoneInfoPrefix + \"teleport.y\");\n\t\t\tint teleZ = warzoneRootSection.getInt(zoneInfoPrefix + \"teleport.z\");\n\t\t\tint teleYaw = warzoneRootSection.getInt(zoneInfoPrefix + \"teleport.yaw\");\n\t\t\twarzone.setTeleport(new Location(world, teleX, teleY, teleZ, teleYaw, 0));\n\t\t\t\n\t\t\t// defaultLoadouts\n\t\t\tif (warzoneRootSection.contains(\"team.default.loadout\")) {\n\t\t\t\tConfigurationSection loadoutsSection = warzoneRootSection.getConfigurationSection(\"team.default.loadout\");\n\t\t\t\twarzone.getDefaultInventories().setLoadouts(LoadoutYmlMapper.fromConfigToLoadouts(loadoutsSection, new HashMap<String, HashMap<Integer, ItemStack>>()));\n\t\t\t}\n\n\t\t\t// defaultReward\n\t\t\tif (warzoneRootSection.contains(\"team.default.reward\")) {\n\t\t\t\tConfigurationSection rewardsSection = warzoneRootSection.getConfigurationSection(\"team.default.reward\");\n\t\t\t\tHashMap<Integer, ItemStack> reward = new HashMap<Integer, ItemStack>();\n\t\t\t\tLoadoutYmlMapper.fromConfigToLoadout(rewardsSection, reward, \"default\");\n\t\t\t\twarzone.getDefaultInventories().setReward(reward);\n\t\t\t}\n\t\t\t\n\t\t\t// Team default settings\n\t\t\tif (warzoneRootSection.contains(\"team.default.config\")) {\n\t\t\t\tConfigurationSection teamConfigSection = warzoneRootSection.getConfigurationSection(\"team.default.config\");\n\t\t\t\twarzone.getTeamDefaultConfig().loadFrom(teamConfigSection);\n\t\t\t}\n\t\t\t\n\t\t\t// Warzone settings\n\t\t\tif (warzoneRootSection.contains(\"warzone.\" + warzone.getName() + \".config\")) {\n\t\t\t\tConfigurationSection warzoneConfigSection = warzoneRootSection.getConfigurationSection(\"warzone.\" + warzone.getName() + \".config\");\n\t\t\t\twarzone.getWarzoneConfig().loadFrom(warzoneConfigSection);\n\t\t\t} else if (warzoneRootSection.contains(\"warzone.\" + warzone.getName().toLowerCase() + \".config\")) {\n\t\t\t\t// Workaround for broken Bukkit backward-compatibility for non-lowercase Yml nodes\n\t\t\t\tConfigurationSection warzoneConfigSection = warzoneRootSection.getConfigurationSection(\"warzone.\" + warzone.getName().toLowerCase() + \".config\");\n\t\t\t\twarzone.getWarzoneConfig().loadFrom(warzoneConfigSection);\n\t\t\t}\n\n\t\t\t// authors\n\t\t\tif (warzoneRootSection.contains(zoneInfoPrefix + \"authors\")) {\n\t\t\t\tfor(String authorStr : warzoneRootSection.getStringList(zoneInfoPrefix + \"authors\")) {\n\t\t\t\t\tif (!authorStr.equals(\"\")) {\n\t\t\t\t\t\twarzone.addAuthor(authorStr);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// rallyPoint\n\t\t\tif (warzoneRootSection.contains(zoneInfoPrefix + \"rallypoint\")) {\n\t\t\t\tint rpX = warzoneRootSection.getInt(zoneInfoPrefix + \"rallypoint.x\");\n\t\t\t\tint rpY = warzoneRootSection.getInt(zoneInfoPrefix + \"rallypoint.y\");\n\t\t\t\tint rpZ = warzoneRootSection.getInt(zoneInfoPrefix + \"rallypoint.z\");\n\t\t\t\tint rpYaw = warzoneRootSection.getInt(zoneInfoPrefix + \"rallypoint.yaw\");\n\t\t\t\tLocation rallyPoint = new Location(world, rpX, rpY, rpZ, rpYaw, 0);\n\t\t\t\twarzone.setRallyPoint(rallyPoint);\n\t\t\t}\n\n\t\t\t// monuments\n\t\t\tif (warzoneRootSection.contains(zoneInfoPrefix + \"monument\")) {\n\t\t\t\tList<String> monunmentNames = warzoneRootSection.getStringList(zoneInfoPrefix + \"monument.names\");\n\t\t\t\tfor (String monumentName : monunmentNames) {\n\t\t\t\t\tif (monumentName != null && !monumentName.equals(\"\")) {\n\t\t\t\t\t\tString monumentPrefix = zoneInfoPrefix + \"monument.\" + monumentName + \".\";\n\t\t\t\t\t\tif (!warzoneRootSection.contains(monumentPrefix + \"x\")) {\n\t\t\t\t\t\t\t// try lowercase instead\n\t\t\t\t\t\t\tmonumentPrefix = zoneInfoPrefix + \"monument.\" + monumentName.toLowerCase() + \".\";\n\t\t\t\t\t\t}\n\t\t\t\t\t\tint monumentX = warzoneRootSection.getInt(monumentPrefix + \"x\");\n\t\t\t\t\t\tint monumentY = warzoneRootSection.getInt(monumentPrefix + \"y\");\n\t\t\t\t\t\tint monumentZ = warzoneRootSection.getInt(monumentPrefix + \"z\");\n\t\t\t\t\t\tint monumentYaw = warzoneRootSection.getInt(monumentPrefix + \"yaw\");\n\t\t\t\t\t\tMonument monument = new Monument(monumentName, warzone, new Location(world, monumentX, monumentY, monumentZ, monumentYaw, 0));\n\t\t\t\t\t\twarzone.getMonuments().add(monument);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// capture points\n\t\t\tif (warzoneRootSection.contains(zoneInfoPrefix + \"capturepoint\")) {\n\t\t\t\tList<String> cpNames = warzoneRootSection.getStringList(zoneInfoPrefix + \"capturepoint.names\");\n\t\t\t\tfor (String cpName : cpNames) {\n\t\t\t\t\tif (cpName != null && !cpName.equals(\"\")) {\n\t\t\t\t\t\tString cpPrefix = zoneInfoPrefix + \"capturepoint.\" + cpName + \".\";\n\t\t\t\t\t\tif (!warzoneRootSection.contains(cpPrefix + \"x\")) {\n\t\t\t\t\t\t\t// try lowercase instead\n\t\t\t\t\t\t\tcpPrefix = zoneInfoPrefix + \"capturepoint.\" + cpName.toLowerCase() + \".\";\n\t\t\t\t\t\t}\n\t\t\t\t\t\tint cpX = warzoneRootSection.getInt(cpPrefix + \"x\");\n\t\t\t\t\t\tint cpY = warzoneRootSection.getInt(cpPrefix + \"y\");\n\t\t\t\t\t\tint cpZ = warzoneRootSection.getInt(cpPrefix + \"z\");\n\t\t\t\t\t\tfloat cpYaw = (float) warzoneRootSection.getDouble(cpPrefix + \"yaw\");\n\t\t\t\t\t\tTeamKind controller = null;\n\t\t\t\t\t\tint strength = 0;\n\t\t\t\t\t\tif (warzoneRootSection.contains(cpPrefix + \"controller\")) {\n\t\t\t\t\t\t\tcontroller = TeamKind.teamKindFromString(warzoneRootSection.getString(cpPrefix + \"controller\"));\n\t\t\t\t\t\t\tstrength = warzone.getWarzoneConfig().getInt(WarzoneConfig.CAPTUREPOINTTIME);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tCapturePoint cp = new CapturePoint(cpName, new Location(world, cpX, cpY, cpZ, cpYaw, 0), controller, strength, warzone);\n\t\t\t\t\t\twarzone.getCapturePoints().add(cp);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// bombs\n\t\t\tif (warzoneRootSection.contains(zoneInfoPrefix + \"bomb\")) {\n\t\t\t\tList<String> bombNames = warzoneRootSection.getStringList(zoneInfoPrefix + \"bomb.names\");\n\t\t\t\tfor (String bombName : bombNames) {\n\t\t\t\t\tif (bombName != null && !bombName.equals(\"\")) {\n\t\t\t\t\t\tString bombPrefix = zoneInfoPrefix + \"bomb.\" + bombName + \".\";\n\t\t\t\t\t\tif (!warzoneRootSection.contains(bombPrefix + \"x\")) {\n\t\t\t\t\t\t\t// try lowercase instead\n\t\t\t\t\t\t\tbombPrefix = zoneInfoPrefix + \"bomb.\" + bombName.toLowerCase() + \".\";\n\t\t\t\t\t\t}\n\t\t\t\t\t\tint bombX = warzoneRootSection.getInt(bombPrefix + \"x\");\n\t\t\t\t\t\tint bombY = warzoneRootSection.getInt(bombPrefix + \"y\");\n\t\t\t\t\t\tint bombZ = warzoneRootSection.getInt(bombPrefix + \"z\");\n\t\t\t\t\t\tint bombYaw = warzoneRootSection.getInt(bombPrefix + \"yaw\");\n\t\t\t\t\t\tBomb bomb = new Bomb(bombName, warzone, new Location(world, bombX, bombY, bombZ, bombYaw, 0));\n\t\t\t\t\t\twarzone.getBombs().add(bomb);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\t// cakes\n\t\t\tif (warzoneRootSection.contains(zoneInfoPrefix + \"cake\")) {\n\t\t\t\tList<String> cakeNames = warzoneRootSection.getStringList(zoneInfoPrefix + \"cake.names\");\n\t\t\t\tfor (String cakeName : cakeNames) {\n\t\t\t\t\tif (cakeName != null && !cakeName.equals(\"\")) {\n\t\t\t\t\t\tString cakePrefix = zoneInfoPrefix + \"cake.\" + cakeName + \".\";\n\t\t\t\t\t\tif (!warzoneRootSection.contains(cakePrefix + \"x\")) {\n\t\t\t\t\t\t\t// try lowercase instead\n\t\t\t\t\t\t\tcakePrefix = zoneInfoPrefix + \"cake.\" + cakeName + \".\";\n\t\t\t\t\t\t}\n\t\t\t\t\t\tint cakeX = warzoneRootSection.getInt(cakePrefix + \"x\");\n\t\t\t\t\t\tint cakeY = warzoneRootSection.getInt(cakePrefix + \"y\");\n\t\t\t\t\t\tint cakeZ = warzoneRootSection.getInt(cakePrefix + \"z\");\n\t\t\t\t\t\tint cakeYaw = warzoneRootSection.getInt(cakePrefix + \"yaw\");\n\t\t\t\t\t\tCake cake = new Cake(cakeName, warzone, new Location(world, cakeX, cakeY, cakeZ, cakeYaw, 0));\n\t\t\t\t\t\twarzone.getCakes().add(cake);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\t// teams (maybe no teams)\n\t\t\tif (warzoneRootSection.contains(\"team.names\")) {\n\t\t\t\tList<String> teamsNames = warzoneRootSection.getStringList(\"team.names\");\n\t\t\t\tfor (String teamName : teamsNames) {\n\t\t\t\t\t// team info\n\t\t\t\t\tString teamInfoPrefix = \"team.\" + teamName + \".info.\";\n\t\t\t\t\tif (!warzoneRootSection.contains(teamInfoPrefix + \"spawn.x\")) {\n\t\t\t\t\t\t// try lowercase instead - supports custom team names\n\t\t\t\t\t\tteamInfoPrefix = \"team.\" + teamName.toLowerCase() + \".info.\";\n\t\t\t\t\t}\n\t\t\t\t\tList<Location> teamSpawns = new ArrayList<Location>();\n\t\t\t\t\tif (warzoneRootSection.contains(teamInfoPrefix + \"spawn\")) {\n\t\t\t\t\t\tint teamX = warzoneRootSection.getInt(teamInfoPrefix + \"spawn.x\");\n\t\t\t\t\t\tint teamY = warzoneRootSection.getInt(teamInfoPrefix + \"spawn.y\");\n\t\t\t\t\t\tint teamZ = warzoneRootSection.getInt(teamInfoPrefix + \"spawn.z\");\n\t\t\t\t\t\tint teamYaw = warzoneRootSection.getInt(teamInfoPrefix + \"spawn.yaw\");\n\t\t\t\t\t\tLocation teamLocation = new Location(world, teamX, teamY, teamZ, teamYaw, 0);\n\t\t\t\t\t\tteamSpawns.add(teamLocation);\n\t\t\t\t\t\tFile original = new File(War.war.getDataFolder().getPath() + \"/dat/warzone-\" + name + \"/volume-\" + teamName + \".dat\");\n\t\t\t\t\t\tFile modified = new File(War.war.getDataFolder().getPath() + \"/dat/warzone-\" + name + \"/volume-\" + teamName + teamSpawns.indexOf(teamLocation) + \".dat\");\n\t\t\t\t\t\tFile originalSql = new File(War.war.getDataFolder().getPath() + \"/dat/warzone-\" + name + \"/volume-\" + teamName + \".sl3\");\n\t\t\t\t\t\tFile modifiedSql = new File(War.war.getDataFolder().getPath() + \"/dat/warzone-\" + name + \"/volume-\" + teamName + teamSpawns.indexOf(teamLocation) + \".sl3\");\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\toriginal.renameTo(modified);\n\t\t\t\t\t\t} catch (Exception ignored) {\n\t\t\t\t\t\t}\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\toriginalSql.renameTo(modifiedSql);\n\t\t\t\t\t\t} catch (Exception ignored) {\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (warzoneRootSection.contains(teamInfoPrefix + \"spawns\")) {\n\t\t\t\t\t\tfor (Map<?, ?> map : warzoneRootSection.getMapList(teamInfoPrefix + \"spawns\")) {\n\t\t\t\t\t\t\tint teamX = (Integer) map.get(\"x\");\n\t\t\t\t\t\t\tint teamY = (Integer) map.get(\"y\");\n\t\t\t\t\t\t\tint teamZ = (Integer) map.get(\"z\");\n\t\t\t\t\t\t\tint teamYaw = (Integer) map.get(\"yaw\");\n\t\t\t\t\t\t\tLocation teamLocation = new Location(world, teamX, teamY, teamZ, teamYaw, 0);\n\t\t\t\t\t\t\tteamSpawns.add(teamLocation);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\n\t\t\t\t\tTeam team = new Team(teamName, TeamKind.teamKindFromString(teamName), teamSpawns, warzone);\n\t\t\t\t\twarzone.getTeams().add(team);\n\t\t\t\t\t\n\t\t\t\t\tif (warzoneRootSection.contains(teamInfoPrefix + \"flag\")) {\n\t\t\t\t\t\tint flagX = warzoneRootSection.getInt(teamInfoPrefix + \"flag.x\");\n\t\t\t\t\t\tint flagY = warzoneRootSection.getInt(teamInfoPrefix + \"flag.y\");\n\t\t\t\t\t\tint flagZ = warzoneRootSection.getInt(teamInfoPrefix + \"flag.z\");\n\t\t\t\t\t\tint flagYaw = warzoneRootSection.getInt(teamInfoPrefix + \"flag.yaw\");\n\t\t\t\t\t\tLocation flagLocation = new Location(world, flagX, flagY, flagZ, flagYaw, 0);\n\t\t\t\t\t\tteam.setTeamFlag(flagLocation);\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tString teamConfigPrefix = \"team.\" + teamName + \".config\";\n\t\t\t\t\tif (warzoneRootSection.contains(teamConfigPrefix)) {\n\t\t\t\t\t\t// team specific config\n\t\t\t\t\t\tConfigurationSection teamConfigSection = warzoneRootSection.getConfigurationSection(teamConfigPrefix);\n\t\t\t\t\t\tteam.getTeamConfig().loadFrom(teamConfigSection);\n\t\t\t\t\t} else if (warzoneRootSection.contains(teamConfigPrefix.toLowerCase())) {\n\t\t\t\t\t\t// try lowercase instead\n\t\t\t\t\t\tConfigurationSection teamConfigSection = warzoneRootSection.getConfigurationSection(teamConfigPrefix.toLowerCase());\n\t\t\t\t\t\tteam.getTeamConfig().loadFrom(teamConfigSection);\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\t// LIFEPOOL INITIALIZATION HERE\n\t\t\t\t\tteam.setRemainingLives(team.getTeamConfig().resolveInt(TeamConfig.LIFEPOOL));\n\t\t\t\t\t\n\t\t\t\t\tString teamLoadoutPrefix = \"team.\" + teamName + \".loadout\";\n\t\t\t\t\tif (warzoneRootSection.contains(teamLoadoutPrefix)) {\n\t\t\t\t\t\t// team specific loadouts\n\t\t\t\t\t\tConfigurationSection loadoutsSection = warzoneRootSection.getConfigurationSection(teamLoadoutPrefix);\n\t\t\t\t\t\tteam.getInventories().setLoadouts(LoadoutYmlMapper.fromConfigToLoadouts(loadoutsSection, new HashMap<String, HashMap<Integer, ItemStack>>()));\n\t\t\t\t\t} else if (warzoneRootSection.contains(teamLoadoutPrefix.toLowerCase())) {\n\t\t\t\t\t\t// try lowercase instead\n\t\t\t\t\t\tConfigurationSection loadoutsSection = warzoneRootSection.getConfigurationSection(teamLoadoutPrefix.toLowerCase());\n\t\t\t\t\t\tteam.getInventories().setLoadouts(LoadoutYmlMapper.fromConfigToLoadouts(loadoutsSection, new HashMap<String, HashMap<Integer, ItemStack>>()));\n\t\t\t\t\t} \n\t\t\t\t\t\n\t\t\t\t\tString teamRewardPrefix = \"team.\" + teamName + \".reward\";\n\t\t\t\t\tif (warzoneRootSection.contains(teamRewardPrefix)) {\n\t\t\t\t\t\t// team specific reward\n\t\t\t\t\t\tConfigurationSection rewardsSection = warzoneRootSection.getConfigurationSection(teamRewardPrefix);\n\t\t\t\t\t\tHashMap<Integer, ItemStack> reward = new HashMap<Integer, ItemStack>();\n\t\t\t\t\t\tLoadoutYmlMapper.fromConfigToLoadout(rewardsSection, reward, \"default\");\n\t\t\t\t\t\twarzone.getDefaultInventories().setReward(reward);\n\t\t\t\t\t} else if (warzoneRootSection.contains(teamRewardPrefix.toLowerCase())) {\n\t\t\t\t\t\t// try lowercase instead\n\t\t\t\t\t\tConfigurationSection rewardsSection = warzoneRootSection.getConfigurationSection(teamRewardPrefix.toLowerCase());\n\t\t\t\t\t\tHashMap<Integer, ItemStack> reward = new HashMap<Integer, ItemStack>();\n\t\t\t\t\t\tLoadoutYmlMapper.fromConfigToLoadout(rewardsSection, reward, \"default\");\n\t\t\t\t\t\twarzone.getDefaultInventories().setReward(reward);\n\t\t\t\t\t} \n\t\t\t\t}\n\t\t\t}\n\t\t\tConnection connection = null;\n\t\t\ttry {\n\t\t\t\tconnection = ZoneVolumeMapper.getZoneConnection(warzone.getVolume(), warzone.getName());\n\t\t\t} catch (SQLException e) {\n\t\t\t\tWar.war.getLogger().log(Level.WARNING, \"Failed to load warzone structures volume\", e);\n\t\t\t}\n\t\t\t// monument blocks\n\t\t\tfor (Monument monument : warzone.getMonuments()) {\n\t\t\t\ttry {\n\t\t\t\t\tmonument.setVolume(warzone.loadStructure(monument.getName(), connection));\n\t\t\t\t} catch (SQLException e) {\n\t\t\t\t\tWar.war.getLogger().log(Level.WARNING, \"Failed to load warzone structures volume\", e);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// capture point blocks\n\t\t\tfor (CapturePoint cp : warzone.getCapturePoints()) {\n\t\t\t\ttry {\n\t\t\t\t\tcp.setVolume(warzone.loadStructure(\"cp-\" + cp.getName(), connection));\n\t\t\t\t} catch (SQLException e) {\n\t\t\t\t\tWar.war.getLogger().log(Level.WARNING, \"Failed to load warzone structures volume\", e);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// bomb blocks\n\t\t\tfor (Bomb bomb : warzone.getBombs()) {\n\t\t\t\ttry {\n\t\t\t\t\tbomb.setVolume(warzone.loadStructure(\"bomb-\" + bomb.getName(), connection));\n\t\t\t\t} catch (SQLException e) {\n\t\t\t\t\tWar.war.getLogger().log(Level.WARNING, \"Failed to load warzone structures volume\", e);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\t// cake blocks\n\t\t\tfor (Cake cake : warzone.getCakes()) {\n\t\t\t\ttry {\n\t\t\t\t\tcake.setVolume(warzone.loadStructure(\"cake-\" + cake.getName(), connection));\n\t\t\t\t} catch (SQLException e) {\n\t\t\t\t\tWar.war.getLogger().log(Level.WARNING, \"Failed to load warzone structures volume\", e);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\t// team spawn blocks\n\t\t\tfor (Team team : warzone.getTeams()) {\n\t\t\t\tfor (Location teamSpawn : team.getTeamSpawns()) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tteam.setSpawnVolume(teamSpawn, warzone.loadStructure(team.getName() + team.getTeamSpawns().indexOf(teamSpawn), connection));\n\t\t\t\t\t} catch (SQLException e) {\n\t\t\t\t\t\tWar.war.getLogger().log(Level.WARNING, \"Failed to load warzone structures volume\", e);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (team.getTeamFlag() != null) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tteam.setFlagVolume(warzone.loadStructure(team.getName() + \"flag\", connection));\n\t\t\t\t\t} catch (SQLException e) {\n\t\t\t\t\t\tWar.war.getLogger().log(Level.WARNING, \"Failed to load warzone structures volume\", e);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// lobby\n\t\t\tString lobbyPrefix = zoneInfoPrefix + \"lobby.\";\n\t\t\t\n\t\t\t// lobby orientation\n\t\t\tString lobbyOrientation = warzoneRootSection.getString(lobbyPrefix + \"orientation\");\n\t\t\tBlockFace lobbyFace = null;\n\t\t\tif (lobbyOrientation.equals(\"south\")) {\n\t\t\t\tlobbyFace = Direction.SOUTH();\n\t\t\t} else if (lobbyOrientation.equals(\"east\")) {\n\t\t\t\tlobbyFace = Direction.EAST();\n\t\t\t} else if (lobbyOrientation.equals(\"north\")) {\n\t\t\t\tlobbyFace = Direction.NORTH();\n\t\t\t} else if (lobbyOrientation.equals(\"west\")) {\n\t\t\t\tlobbyFace = Direction.WEST();\n\t\t\t}\n\t\t\t\n\t\t\t// lobby materials\n\t\t\tif (warzoneRootSection.isItemStack(lobbyPrefix + \"materials.floor\")) {\n\t\t\t\twarzone.getLobbyMaterials().setFloorBlock(\n\t\t\t\t\t\twarzoneRootSection.getItemStack(lobbyPrefix + \"materials.floor\"));\n\t\t\t}\n\t\t\tif (warzoneRootSection.isItemStack(lobbyPrefix + \"materials.outline\")) {\n\t\t\t\twarzone.getLobbyMaterials().setOutlineBlock(\n\t\t\t\t\t\twarzoneRootSection.getItemStack(lobbyPrefix + \"materials.outline\"));\n\t\t\t}\n\t\t\tif (warzoneRootSection.isItemStack(lobbyPrefix + \"materials.gate\")) {\n\t\t\t\twarzone.getLobbyMaterials().setGateBlock(\n\t\t\t\t\t\twarzoneRootSection.getItemStack(lobbyPrefix + \"materials.gate\"));\n\t\t\t}\n\t\t\tif (warzoneRootSection.isItemStack(lobbyPrefix + \"materials.light\")) {\n\t\t\t\twarzone.getLobbyMaterials().setLightBlock(\n\t\t\t\t\t\twarzoneRootSection.getItemStack(lobbyPrefix + \"materials.light\"));\n\t\t\t}\n\t\t\t\n\t\t\t// lobby world\n\t\t\tString lobbyWorldName = warzoneRootSection.getString(lobbyPrefix + \"world\");\n\t\t\tWorld lobbyWorld = War.war.getServer().getWorld(lobbyWorldName);\n\t\t\t\t\t\t\n\t\t\t// create the lobby\n\t\t\tVolume lobbyVolume = null;\n\t\t\ttry {\n\t\t\t\tlobbyVolume = warzone.loadStructure(\"lobby\", lobbyWorld, connection);\n\t\t\t} catch (SQLException e) {\n\t\t\t\tWar.war.getLogger().log(Level.WARNING, \"Failed to load warzone lobby\", e);\n\t\t\t}\n\t\t\tZoneLobby lobby = new ZoneLobby(warzone, lobbyFace, lobbyVolume);\n\t\t\twarzone.setLobby(lobby);\n\t\t\t\n\t\t\t// warzone materials\n\t\t\tif (warzoneRootSection.isItemStack(zoneInfoPrefix + \"materials.main\")) {\n\t\t\t\twarzone.getWarzoneMaterials().setMainBlock(\n\t\t\t\t\t\twarzoneRootSection.getItemStack(zoneInfoPrefix + \"materials.main\"));\n\t\t\t}\n\t\t\tif (warzoneRootSection.isItemStack(zoneInfoPrefix + \"materials.stand\")) {\n\t\t\t\twarzone.getWarzoneMaterials().setStandBlock(\n\t\t\t\t\t\twarzoneRootSection.getItemStack(zoneInfoPrefix + \"materials.stand\"));\n\t\t\t}\n\t\t\tif (warzoneRootSection.isItemStack(zoneInfoPrefix + \"materials.light\")) {\n\t\t\t\twarzone.getWarzoneMaterials().setLightBlock(\n\t\t\t\t\t\twarzoneRootSection.getItemStack(zoneInfoPrefix + \"materials.light\"));\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconnection.close();\n\t\t\t} catch (SQLException ignored) {\n\t\t\t}\n\n\t\t\treturn warzone;\n\t\t}\n\t\t\n\t\treturn null;\n\t}\n\t\n\tpublic static void save(Warzone warzone) {\n\t\tYamlConfiguration warzoneYmlConfig = new YamlConfiguration();\n\t\tConfigurationSection warzoneRootSection = warzoneYmlConfig.createSection(\"set\");\n\t\t(new File(War.war.getDataFolder().getPath() + \"/dat/warzone-\" + warzone.getName())).mkdir();\t// create folder\n\t\t\n\t\tConfigurationSection warzoneSection = warzoneRootSection.createSection(\"warzone.\" + warzone.getName());\n\t\t\n\t\t// Warzone settings\n\t\tif (!warzone.getWarzoneConfig().isEmpty()) {\n\t\t\tConfigurationSection warzoneConfigSection = warzoneSection.createSection(\"config\");\n\t\t\twarzone.getWarzoneConfig().saveTo(warzoneConfigSection);\n\t\t}\n\t\t\t\t\n\t\tConfigurationSection warzoneInfoSection = warzoneSection.createSection(\"info\");\n\t\t\n\t\t// authors\n\t\twarzoneInfoSection.set(\"authors\", warzone.getAuthors());\n\t\t\n\t\t// teleport\n\t\tConfigurationSection teleSection = warzoneInfoSection.createSection(\"teleport\");\n\t\tteleSection.set(\"x\", warzone.getTeleport().getBlockX());\n\t\tteleSection.set(\"y\", warzone.getTeleport().getBlockY());\n\t\tteleSection.set(\"z\", warzone.getTeleport().getBlockZ());\n\t\tteleSection.set(\"yaw\", toIntYaw(warzone.getTeleport().getYaw()));\n\t\n\t\t// world\n\t\twarzoneInfoSection.set(\"world\", warzone.getWorld().getName());\t\n\t\t\n\t\t// lobby\n\t\tif (warzone.getLobby() != null) {\n\t\t\tString lobbyOrientation = \"\";\n\t\t\tif (Direction.SOUTH() == warzone.getLobby().getWall()) {\n\t\t\t\tlobbyOrientation = \"south\";\n\t\t\t} else if (Direction.EAST() == warzone.getLobby().getWall()) {\n\t\t\t\tlobbyOrientation = \"east\";\n\t\t\t} else if (Direction.NORTH() == warzone.getLobby().getWall()) {\n\t\t\t\tlobbyOrientation = \"north\";\n\t\t\t} else if (Direction.WEST() == warzone.getLobby().getWall()) {\n\t\t\t\tlobbyOrientation = \"west\";\n\t\t\t}\n\t\t\t\n\t\t\tConfigurationSection lobbySection = warzoneInfoSection.createSection(\"lobby\");\n\t\t\tlobbySection.set(\"orientation\", lobbyOrientation);\n\t\t\tlobbySection.set(\"world\", warzone.getLobby().getVolume().getWorld().getName());\n\t\t\t\n\t\t\tlobbySection.set(\"materials.floor\", warzone.getLobbyMaterials().getFloorBlock());\n\t\t\tlobbySection.set(\"materials.outline\", warzone.getLobbyMaterials().getOutlineBlock());\n\t\t\tlobbySection.set(\"materials.gate\", warzone.getLobbyMaterials().getGateBlock());\n\t\t\tlobbySection.set(\"materials.light\", warzone.getLobbyMaterials().getLightBlock());\n\t\t}\n\t\t\n\t\t// materials\n\t\tif (warzone.getLobby() != null) {\n\t\t\twarzoneInfoSection.set(\"materials.main\", warzone.getWarzoneMaterials().getMainBlock());\n\t\t\twarzoneInfoSection.set(\"materials.stand\", warzone.getWarzoneMaterials().getStandBlock());\n\t\t\twarzoneInfoSection.set(\"materials.light\", warzone.getWarzoneMaterials().getLightBlock());\n\t\t}\n\n\t\t// rallyPoint\n\t\tif (warzone.getRallyPoint() != null) {\n\t\t\tConfigurationSection rpSection = warzoneInfoSection.createSection(\"rallypoint\");\n\t\t\trpSection.set(\"x\", warzone.getRallyPoint().getBlockX());\n\t\t\trpSection.set(\"y\", warzone.getRallyPoint().getBlockY());\n\t\t\trpSection.set(\"z\", warzone.getRallyPoint().getBlockZ());\n\t\t\trpSection.set(\"yaw\", toIntYaw(warzone.getRallyPoint().getYaw()));\n\t\t}\n\t\t\n\t\t// monuments\n\t\tif (warzone.getMonuments().size() > 0) {\n\t\t\tConfigurationSection monumentsSection = warzoneInfoSection.createSection(\"monument\");\n\t\t\t\n\t\t\tList<String> monumentNames = new ArrayList<String>();\n\t\t\tfor (Monument monument : warzone.getMonuments()) {\n\t\t\t\tmonumentNames.add(monument.getName());\n\t\t\t}\n\t\t\tmonumentsSection.set(\"names\", monumentNames);\n\t\t\t\n\t\t\tfor (Monument monument : warzone.getMonuments()) {\n\t\t\t\t\n\t\t\t\tConfigurationSection monumentSection = monumentsSection.createSection(monument.getName());\n\t\t\t\tmonumentSection.set(\"x\", monument.getLocation().getBlockX());\n\t\t\t\tmonumentSection.set(\"y\", monument.getLocation().getBlockY());\n\t\t\t\tmonumentSection.set(\"z\", monument.getLocation().getBlockZ());\n\t\t\t\tmonumentSection.set(\"yaw\", toIntYaw(monument.getLocation().getYaw()));\n\t\t\t}\n\t\t}\n\n\t\t// capture points\n\t\tif (warzone.getCapturePoints().size() > 0) {\n\t\t\tConfigurationSection cpsSection = warzoneInfoSection.createSection(\"capturepoint\");\n\n\t\t\tList<String> cpNames = new ArrayList<String>();\n\t\t\tfor (CapturePoint cp : warzone.getCapturePoints()) {\n\t\t\t\tcpNames.add(cp.getName());\n\t\t\t}\n\t\t\tcpsSection.set(\"names\", cpNames);\n\n\t\t\tfor (CapturePoint cp : warzone.getCapturePoints()) {\n\n\t\t\t\tConfigurationSection cpSection = cpsSection.createSection(cp.getName());\n\t\t\t\tcpSection.set(\"x\", cp.getLocation().getBlockX());\n\t\t\t\tcpSection.set(\"y\", cp.getLocation().getBlockY());\n\t\t\t\tcpSection.set(\"z\", cp.getLocation().getBlockZ());\n\t\t\t\tcpSection.set(\"yaw\", cp.getLocation().getYaw());\n\t\t\t\tif (cp.getDefaultController() != null) {\n\t\t\t\t\tcpSection.set(\"controller\", cp.getDefaultController().name());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// bombs\n\t\tif (warzone.getBombs().size() > 0) {\n\t\t\tConfigurationSection bombsSection = warzoneInfoSection.createSection(\"bomb\");\n\n\t\t\tList<String> bombNames = new ArrayList<String>();\n\t\t\tfor (Bomb bomb : warzone.getBombs()) {\n\t\t\t\tbombNames.add(bomb.getName());\n\t\t\t}\n\t\t\tbombsSection.set(\"names\", bombNames);\n\n\t\t\tfor (Bomb bomb : warzone.getBombs()) {\n\n\t\t\t\tConfigurationSection bombSection = bombsSection.createSection(bomb.getName());\n\t\t\t\tbombSection.set(\"x\", bomb.getLocation().getBlockX());\n\t\t\t\tbombSection.set(\"y\", bomb.getLocation().getBlockY());\n\t\t\t\tbombSection.set(\"z\", bomb.getLocation().getBlockZ());\n\t\t\t\tbombSection.set(\"yaw\", toIntYaw(bomb.getLocation().getYaw()));\n\t\t\t}\n\t\t}\n\n\t\t// cakes\n\t\tif (warzone.getCakes().size() > 0) {\n\t\t\tConfigurationSection cakesSection = warzoneInfoSection.createSection(\"cake\");\n\t\t\t\n\t\t\tList<String> cakeNames = new ArrayList<String>();\n\t\t\tfor (Cake cake : warzone.getCakes()) {\n\t\t\t\tcakeNames.add(cake.getName());\n\t\t\t}\n\t\t\tcakesSection.set(\"names\", cakeNames);\n\t\t\t\n\t\t\tfor (Cake cake : warzone.getCakes()) {\n\t\t\t\t\n\t\t\t\tConfigurationSection cakeSection = cakesSection.createSection(cake.getName());\n\t\t\t\tcakeSection.set(\"x\", cake.getLocation().getBlockX());\n\t\t\t\tcakeSection.set(\"y\", cake.getLocation().getBlockY());\n\t\t\t\tcakeSection.set(\"z\", cake.getLocation().getBlockZ());\n\t\t\t\tcakeSection.set(\"yaw\", toIntYaw(cake.getLocation().getYaw()));\n\t\t\t}\n\t\t}\n\t\t\n\t\tConfigurationSection teamsSection = warzoneRootSection.createSection(\"team\");\n\t\t\n\t\t// teams\n\t\tList<Team> teams = warzone.getTeams();\n\t\t\n\t\tList<String> teamNames = new ArrayList<String>();\n\t\tfor (Team team : teams) {\n\t\t\tteamNames.add(team.getName());\n\t\t}\n\t\tif (teamNames.size() > 0) {\n\t\t\tteamsSection.set(\"names\", teamNames);\n\t\t}\n\n\t\t// Team default settings\n\t\tif (!warzone.getTeamDefaultConfig().isEmpty()) {\n\t\t\tConfigurationSection teamConfigSection = teamsSection.createSection(\"default.config\");\n\t\t\twarzone.getTeamDefaultConfig().saveTo(teamConfigSection);\n\t\t}\t\t\n\t\t\n\t\t// defaultLoadouts\n\t\tif (warzone.getDefaultInventories().hasLoadouts()) {\n\t\t\tConfigurationSection loadoutsSection = teamsSection.createSection(\"default.loadout\");\n\t\t\tLoadoutYmlMapper.fromLoadoutsToConfig(warzone.getDefaultInventories().getNewLoadouts(), loadoutsSection);\n\t\t}\n\t\t\n\t\t// defaultReward\n\t\tif (warzone.getDefaultInventories().hasReward()) {\n\t\t\tConfigurationSection rewardsSection = teamsSection.createSection(\"default.reward\");\n\t\t\tLoadoutYmlMapper.fromLoadoutToConfig(\"default\", warzone.getDefaultInventories().getReward(), rewardsSection);\n\t\t}\t\n\t\t\n\t\tfor (Team team : teams) {\n\t\t\tif (!team.getTeamConfig().isEmpty()) {\n\t\t\t\t// team specific config\n\t\t\t\tConfigurationSection teamConfigSection = teamsSection.createSection(team.getName() + \".config\");\n\t\t\t\tteam.getTeamConfig().saveTo(teamConfigSection);\n\t\t\t}\n\t\t\t\n\t\t\tif (team.getInventories().hasLoadouts()) {\n\t\t\t\t// team specific loadouts\n\t\t\t\tConfigurationSection loadoutsSection = teamsSection.createSection(team.getName() + \".loadout\");\n\t\t\t\tLoadoutYmlMapper.fromLoadoutsToConfig(team.getInventories().getNewLoadouts(), loadoutsSection);\n\t\t\t}\n\t\t\t\n\t\t\tif (team.getInventories().hasReward()) {\n\t\t\t\t// team specific reward\n\t\t\t\tConfigurationSection rewardsSection = teamsSection.createSection(team.getName() + \".reward\");\n\t\t\t\tLoadoutYmlMapper.fromLoadoutToConfig(\"default\", team.getInventories().getReward(), rewardsSection);\n\t\t\t}\n\n\t\t\tConfigurationSection teamInfoSection = teamsSection.createSection(team.getName() + \".info\");\n\t\t\t\n\t\t\tList<Map<String, Object>> spawnSerilization = new ArrayList<Map<String, Object>>();\n\t\t\tfor (Location spawn : team.getTeamSpawns()) {\n\t\t\t\tMap<String, Object> map = new HashMap<String, Object>();\n\t\t\t\tmap.put(\"x\", spawn.getBlockX());\n\t\t\t\tmap.put(\"y\", spawn.getBlockY());\n\t\t\t\tmap.put(\"z\", spawn.getBlockZ());\n\t\t\t\tmap.put(\"yaw\", toIntYaw(spawn.getYaw()));\n\t\t\t\tspawnSerilization.add(map);\n\t\t\t}\n\t\t\tteamInfoSection.set(\"spawns\", spawnSerilization);\n\t\t\t\n\t\t\tif (team.getTeamFlag() != null) {\n\t\t\t\tConfigurationSection flagSection = teamInfoSection.createSection(\"flag\");\n\t\t\t\tLocation teamFlag = team.getTeamFlag();\n\t\t\t\tflagSection.set(\"x\", teamFlag.getBlockX());\n\t\t\t\tflagSection.set(\"y\", teamFlag.getBlockY());\n\t\t\t\tflagSection.set(\"z\", teamFlag.getBlockZ());\n\t\t\t\tflagSection.set(\"yaw\", toIntYaw(teamFlag.getYaw()));\n\t\t\t}\n\t\t}\n\t\tConnection connection = null;\n\t\ttry {\n\t\t\tconnection = ZoneVolumeMapper.getZoneConnection(warzone.getVolume(), warzone.getName());\n\t\t} catch (SQLException e) {\n\t\t\tWar.war.getLogger().log(Level.WARNING, \"Failed to load warzone structures volume\", e);\n\t\t}\n\t\t// monument blocks\n\t\tfor (Monument monument : warzone.getMonuments()) {\n\t\t\ttry {\n\t\t\t\tZoneVolumeMapper.saveStructure(monument.getVolume(), connection);\n\t\t\t} catch (SQLException e) {\n\t\t\t\tWar.war.getLogger().log(Level.WARNING, \"Failed to save warzone structures volume\", e);\n\t\t\t}\n\t\t}\n\n\t\t// capture point blocks\n\t\tfor (CapturePoint cp : warzone.getCapturePoints()) {\n\t\t\ttry {\n\t\t\t\tZoneVolumeMapper.saveStructure(cp.getVolume(), connection);\n\t\t\t} catch (SQLException e) {\n\t\t\t\tWar.war.getLogger().log(Level.WARNING, \"Failed to save warzone structures volume\", e);\n\t\t\t}\n\t\t}\n\n\t\t// bomb blocks\n\t\tfor (Bomb bomb : warzone.getBombs()) {\n\t\t\ttry {\n\t\t\t\tZoneVolumeMapper.saveStructure(bomb.getVolume(), connection);\n\t\t\t} catch (SQLException e) {\n\t\t\t\tWar.war.getLogger().log(Level.WARNING, \"Failed to save warzone structures volume\", e);\n\t\t\t}\n\t\t}\n\t\t\n\t\t// cake blocks\n\t\tfor (Cake cake : warzone.getCakes()) {\n\t\t\ttry {\n\t\t\t\tZoneVolumeMapper.saveStructure(cake.getVolume(), connection);\n\t\t\t} catch (SQLException e) {\n\t\t\t\tWar.war.getLogger().log(Level.WARNING, \"Failed to save warzone structures volume\", e);\n\t\t\t}\n\t\t}\n\n\t\t// team spawn & flag blocks\n\t\tfor (Team team : teams) {\n\t\t\tfor (Volume volume : team.getSpawnVolumes().values()) {\n\t\t\t\ttry {\n\t\t\t\t\tZoneVolumeMapper.saveStructure(volume, connection);\n\t\t\t\t} catch (SQLException e) {\n\t\t\t\t\tWar.war.getLogger().log(Level.WARNING, \"Failed to save warzone structures volume\", e);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (team.getFlagVolume() != null) {\n\t\t\t\ttry {\n\t\t\t\t\tZoneVolumeMapper.saveStructure(team.getFlagVolume(), connection);\n\t\t\t\t} catch (SQLException e) {\n\t\t\t\t\tWar.war.getLogger().log(Level.WARNING, \"Failed to save warzone structures volume\", e);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (warzone.getLobby() != null) {\n\t\t\ttry {\n\t\t\t\tZoneVolumeMapper.saveStructure(warzone.getLobby().getVolume(), connection);\n\t\t\t} catch (SQLException e) {\n\t\t\t\tWar.war.getLogger().log(Level.WARNING, \"Failed to save warzone structures volume\", e);\n\t\t\t}\n\t\t}\n\t\ttry {\n\t\t\tconnection.close();\n\t\t} catch (SQLException ignored) {\n\t\t}\n\n\t\t// Save to disk\n\t\ttry {\n\t\t\tFile warzoneConfigFile = new File(War.war.getDataFolder().getPath() + \"/warzone-\" + warzone.getName() + \".yml\");\n\t\t\twarzoneYmlConfig.save(warzoneConfigFile);\n\t\t} catch (IOException e) {\n\t\t\tWar.war.log(\"Failed to save warzone-\" + warzone.getName() + \".yml\", Level.WARNING);\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\n\tprivate static int toIntYaw(float yaw) {\n\t\tint intYaw = 0;\n\t\tif (yaw >= 0) {\n\t\t\tintYaw = (int) (yaw % 360);\n\t\t} else {\n\t\t\tintYaw = (int) (360 + (yaw % 360));\n\t\t}\n\t\treturn intYaw;\n\t}\n\n\tpublic static void delete(Warzone zone) {\n\t\t// Kill old warzone, but use it to create the renamed copy\n\t\tzone.unload();\n\t\tzone.getVolume().resetBlocks();\t// We're need a clean land\n\t\t\n\t\tString name = zone.getName();\n\t\t\t\t\n\t\t// Move old files\n\t\t(new File(War.war.getDataFolder().getPath() + \"/temp/deleted/\")).mkdir();\n\t\t(new File(War.war.getDataFolder().getPath() + \"/warzone-\" + name + \".yml\")).renameTo(new File(War.war.getDataFolder().getPath() + \"/temp/deleted/warzone-\" + name + \".yml\"));\n\t\t(new File(War.war.getDataFolder().getPath() + \"/temp/deleted/dat/warzone-\" + name)).mkdirs();\n\n\t\tString oldPath = War.war.getDataFolder().getPath() + \"/dat/warzone-\" + name + \"/\";\n\t\tFile oldZoneFolder = new File(oldPath);\n\t\tFile[] oldZoneFiles = oldZoneFolder.listFiles();\n\t\tfor (File file : oldZoneFiles) {\n\t\t\tfile.renameTo(new File(War.war.getDataFolder().getPath() + \"/temp/deleted/dat/warzone-\" + name + \"/\" + file.getName()));\n\t\t}\n\t\toldZoneFolder.delete();\n\t}\n}",
"public class CapturePoint {\n\tprivate static int[][][] structure = {\n\t\t\t{\n\t\t\t\t\t{1, 1, 1},\n\t\t\t\t\t{1, 2, 1},\n\t\t\t\t\t{1, 1, 1}\n\t\t\t},\n\t\t\t{\n\t\t\t\t\t{0, 0, 0},\n\t\t\t\t\t{0, 3, 0},\n\t\t\t\t\t{0, 0, 0}\n\t\t\t},\n\t\t\t{\n\t\t\t\t\t{0, 0, 0},\n\t\t\t\t\t{0, 3, 0},\n\t\t\t\t\t{0, 0, 0}\n\t\t\t},\n\t\t\t{\n\t\t\t\t\t{0, 0, 0},\n\t\t\t\t\t{0, 3, 0},\n\t\t\t\t\t{0, 0, 0}\n\t\t\t},\n\t\t\t{\n\t\t\t\t\t{0, 0, 0},\n\t\t\t\t\t{0, 3, 0},\n\t\t\t\t\t{0, 0, 0}\n\t\t\t}\n\t};\n\n\tprivate final String name;\n\tprivate Volume volume;\n\tprivate Location location;\n\tprivate TeamKind controller, defaultController;\n\tprivate int strength, controlTime;\n\tprivate Warzone warzone;\n\n\tpublic CapturePoint(String name, Location location, TeamKind defaultController, int strength, Warzone warzone) {\n\t\tthis.name = name;\n\t\tthis.defaultController = defaultController;\n\t\tthis.controller = defaultController;\n\t\tthis.strength = strength;\n\t\tthis.controlTime = 0;\n\t\tthis.warzone = warzone;\n\t\tthis.volume = new Volume(\"cp-\" + name, warzone.getWorld());\n\t\tthis.setLocation(location);\n\t}\n\n\tprivate Location getOrigin() {\n\t\treturn location.clone().subtract(1, 1, 1).getBlock().getLocation();\n\t}\n\n\tprivate void updateBlocks() {\n\t\tValidate.notNull(location);\n\t\t// Set origin to back left corner\n\t\tLocation origin = this.getOrigin();\n\t\t// Build structure\n\t\tfor (int y = 0; y < structure.length; y++) {\n\t\t\tfor (int z = 0; z < structure[0].length; z++) {\n\t\t\t\tfor (int x = 0; x < structure[0][0].length; x++) {\n\t\t\t\t\tBlockState state = origin.clone().add(x, y, z).getBlock().getState();\n\t\t\t\t\tswitch (structure[y][z][x]) {\n\t\t\t\t\t\tcase 0:\n\t\t\t\t\t\t\tstate.setType(Material.AIR);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 1:\n\t\t\t\t\t\t\tstate.setType(this.warzone.getWarzoneMaterials().getMainBlock().getType());\n\t\t\t\t\t\t\tstate.setData(this.warzone.getWarzoneMaterials().getMainBlock().getData());\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 2:\n\t\t\t\t\t\t\tstate.setType(this.warzone.getWarzoneMaterials().getLightBlock().getType());\n\t\t\t\t\t\t\tstate.setData(this.warzone.getWarzoneMaterials().getLightBlock().getData());\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase 3:\n\t\t\t\t\t\t\tstate.setType(this.warzone.getWarzoneMaterials().getStandBlock().getType());\n\t\t\t\t\t\t\tstate.setData(this.warzone.getWarzoneMaterials().getStandBlock().getData());\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\tthrow new IllegalStateException(\"Invalid structure\");\n\t\t\t\t\t}\n\t\t\t\t\tstate.update(true);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// Add flag block\n\t\tif (strength > 0 && controller != null) {\n\t\t\t// Make flag point direction of player when setting the capture point\n\t\t\tint flagHeight = (int) (strength / (getMaxStrength() / 4.0));\n\t\t\tVector dir = new Vector(1 + -Math.round(Math.sin(Math.toRadians(location.getYaw()))), flagHeight,\n\t\t\t\t\t1 + Math.round(Math.cos(Math.toRadians(location.getYaw()))));\n\t\t\tBlockState state = origin.clone().add(dir).getBlock().getState();\n\t\t\tstate.setType(controller.getMaterial());\n\t\t\tstate.update(true);\n\t\t}\n\t}\n\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic Location getLocation() {\n\t\treturn location;\n\t}\n\n\tpublic void setLocation(Location location) {\n\t\tthis.location = new Location(location.getWorld(), location.getBlockX(), location.getBlockY(),\n\t\t\t\tlocation.getBlockZ(), location.getYaw(), 0);\n\t\tthis.volume.setCornerOne(this.getOrigin());\n\t\tthis.volume.setCornerTwo(this.getOrigin().add(structure[0][0].length, structure.length, structure[0].length));\n\t\tthis.volume.saveBlocks();\n\t\tthis.updateBlocks();\n\t}\n\n\tpublic TeamKind getDefaultController() {\n\t\treturn defaultController;\n\t}\n\n\tpublic TeamKind getController() {\n\t\treturn controller;\n\t}\n\n\tpublic void setController(TeamKind controller) {\n\t\tthis.controller = controller;\n\t\tif (strength > 0) {\n\t\t\tthis.updateBlocks();\n\t\t}\n\t}\n\n\tpublic int getStrength() {\n\t\treturn strength;\n\t}\n\n\tpublic void setStrength(int strength) {\n\t\tValidate.isTrue(strength <= getMaxStrength());\n\t\tthis.strength = strength;\n\t\tthis.updateBlocks();\n\t}\n\n\tpublic int getControlTime() {\n\t\treturn controlTime;\n\t}\n\n\tpublic void setControlTime(int controlTime) {\n\t\tthis.controlTime = controlTime;\n\t}\n\n\tpublic Volume getVolume() {\n\t\treturn volume;\n\t}\n\n\tpublic void setVolume(Volume volume) {\n\t\tthis.volume = volume;\n\t}\n\n\tpublic void reset() {\n\t\tthis.controller = defaultController;\n\t\tif (this.controller != null) {\n\t\t\tthis.strength = 4;\n\t\t} else {\n\t\t\tthis.strength = 0;\n\t\t}\n\t\tthis.updateBlocks();\n\t}\n\n\tprivate long lastMessage = 0;\n\tpublic boolean antiChatSpam() {\n\t\tlong now = System.currentTimeMillis();\n\t\tif (now - lastMessage > 3000) {\n\t\t\tlastMessage = now;\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tpublic int getMaxStrength() {\n\t\treturn warzone.getWarzoneConfig().getInt(WarzoneConfig.CAPTUREPOINTTIME);\n\t}\n}",
"public class Monument {\n\tprivate Location location;\n\tprivate Volume volume;\n\n\tprivate Team ownerTeam = null;\n\tprivate final String name;\n\tprivate Warzone warzone;\n\n\tpublic Monument(String name, Warzone warzone, Location location) {\n\t\tthis.name = name;\n\t\tthis.location = location;\n\t\tthis.warzone = warzone;\n\t\tthis.volume = new Volume(name, warzone.getWorld());\n\t\tthis.setLocation(location);\n\t}\n\n\tpublic void addMonumentBlocks() {\n\t\t// make air (old three-high above floor)\n\t\tVolume airGap = new Volume(new Location(this.volume.getWorld(),\n\t\t\t\tthis.volume.getCornerOne().getX(), this.volume.getCornerOne()\n\t\t\t\t\t\t.getY() + 1, this.volume.getCornerOne().getZ()),\n\t\t\t\tnew Location(this.volume.getWorld(), this.volume.getCornerTwo()\n\t\t\t\t\t\t.getX(), this.volume.getCornerOne().getY() + 3,\n\t\t\t\t\t\tthis.volume.getCornerTwo().getZ()));\n\t\tairGap.setToMaterial(Material.AIR);\n\n\t\tthis.ownerTeam = null;\n\t\tint x = this.location.getBlockX();\n\t\tint y = this.location.getBlockY();\n\t\tint z = this.location.getBlockZ();\n\t\tfinal Material main = this.warzone.getWarzoneMaterials().getMainBlock().getType();\n\t\tfinal MaterialData mainData = this.warzone.getWarzoneMaterials().getMainBlock().getData();\n\t\tfinal Material light = this.warzone.getWarzoneMaterials().getLightBlock().getType();\n\t\tfinal MaterialData lightData = this.warzone.getWarzoneMaterials().getLightBlock().getData();\n\n\t\t// center\n\t\tBlockState current = this.warzone.getWorld().getBlockAt(x, y - 1, z).getState();\n\t\tcurrent.setType(main);\n\t\tcurrent.setData(mainData);\n\t\tcurrent.update(true);\n\n\t\t// inner ring\n\t\tcurrent = this.warzone.getWorld().getBlockAt(x + 1, y - 1, z + 1).getState();\n\t\tcurrent.setType(main);\n\t\tcurrent.setData(mainData);\n\t\tcurrent.update(true);\n\t\tcurrent = this.warzone.getWorld().getBlockAt(x + 1, y - 1, z).getState();\n\t\tcurrent.setType(main);\n\t\tcurrent.setData(mainData);\n\t\tcurrent.update(true);\n\t\tcurrent = this.warzone.getWorld().getBlockAt(x + 1, y - 1, z - 1).getState();\n\t\tcurrent.setType(main);\n\t\tcurrent.setData(mainData);\n\t\tcurrent.update(true);\n\n\t\tcurrent = this.warzone.getWorld().getBlockAt(x, y - 1, z + 1).getState();\n\t\tcurrent.setType(main);\n\t\tcurrent.setData(mainData);\n\t\tcurrent.update(true);\n\t\tcurrent = this.warzone.getWorld().getBlockAt(x, y - 1, z - 1).getState();\n\t\tcurrent.setType(main);\n\t\tcurrent.setData(mainData);\n\t\tcurrent.update(true);\n\n\t\tcurrent = this.warzone.getWorld().getBlockAt(x - 1, y - 1, z + 1).getState();\n\t\tcurrent.setType(main);\n\t\tcurrent.setData(mainData);\n\t\tcurrent.update(true);\n\t\tcurrent = this.warzone.getWorld().getBlockAt(x - 1, y - 1, z).getState();\n\t\tcurrent.setType(main);\n\t\tcurrent.setData(mainData);\n\t\tcurrent.update(true);\n\t\tcurrent = this.warzone.getWorld().getBlockAt(x - 1, y - 1, z - 1).getState();\n\t\tcurrent.setType(main);\n\t\tcurrent.setData(mainData);\n\t\tcurrent.update(true);\n\n\t\t// outer ring\n\t\tcurrent = this.warzone.getWorld().getBlockAt(x + 2, y - 1, z + 2).getState();\n\t\tcurrent.setType(light);\n\t\tcurrent.setData(lightData);\n\t\tcurrent.update(true);\n\t\tcurrent = this.warzone.getWorld().getBlockAt(x + 2, y - 1, z + 1).getState();\n\t\tcurrent.setType(main);\n\t\tcurrent.setData(mainData);\n\t\tcurrent.update(true);\n\t\tcurrent = this.warzone.getWorld().getBlockAt(x + 2, y - 1, z).getState();\n\t\tcurrent.setType(main);\n\t\tcurrent.setData(mainData);\n\t\tcurrent.update(true);\n\t\tcurrent = this.warzone.getWorld().getBlockAt(x + 2, y - 1, z - 1).getState();\n\t\tcurrent.setType(main);\n\t\tcurrent.setData(mainData);\n\t\tcurrent.update(true);\n\t\tcurrent = this.warzone.getWorld().getBlockAt(x + 2, y - 1, z - 2).getState();\n\t\tcurrent.setType(light);\n\t\tcurrent.setData(lightData);\n\t\tcurrent.update(true);\n\n\t\tcurrent = this.warzone.getWorld().getBlockAt(x - 1, y - 1, z + 2).getState();\n\t\tcurrent.setType(main);\n\t\tcurrent.setData(mainData);\n\t\tcurrent.update(true);\n\t\tcurrent = this.warzone.getWorld().getBlockAt(x - 1, y - 1, z - 2).getState();\n\t\tcurrent.setType(main);\n\t\tcurrent.setData(mainData);\n\t\tcurrent.update(true);\n\n\t\tcurrent = this.warzone.getWorld().getBlockAt(x, y - 1, z + 2).getState();\n\t\tcurrent.setType(main);\n\t\tcurrent.setData(mainData);\n\t\tcurrent.update(true);\n\t\tcurrent = this.warzone.getWorld().getBlockAt(x, y - 1, z - 2).getState();\n\t\tcurrent.setType(main);\n\t\tcurrent.setData(mainData);\n\t\tcurrent.update(true);\n\t\t\n\t\tcurrent = this.warzone.getWorld().getBlockAt(x + 1, y - 1, z + 2).getState();\n\t\tcurrent.setType(main);\n\t\tcurrent.setData(mainData);\n\t\tcurrent.update(true);\n\t\tcurrent = this.warzone.getWorld().getBlockAt(x + 1, y - 1, z - 2).getState();\n\t\tcurrent.setType(main);\n\t\tcurrent.setData(mainData);\n\t\tcurrent.update(true);\n\n\t\tcurrent = this.warzone.getWorld().getBlockAt(x - 2, y - 1, z + 2).getState();\n\t\tcurrent.setType(light);\n\t\tcurrent.setData(lightData);\n\t\tcurrent.update(true);\n\t\tcurrent = this.warzone.getWorld().getBlockAt(x - 2, y - 1, z + 1).getState();\n\t\tcurrent.setType(main);\n\t\tcurrent.setData(mainData);\n\t\tcurrent.update(true);\n\t\tcurrent = this.warzone.getWorld().getBlockAt(x - 2, y - 1, z).getState();\n\t\tcurrent.setType(main);\n\t\tcurrent.setData(mainData);\n\t\tcurrent.update(true);\n\t\tcurrent = this.warzone.getWorld().getBlockAt(x - 2, y - 1, z - 1).getState();\n\t\tcurrent.setType(main);\n\t\tcurrent.setData(mainData);\n\t\tcurrent.update(true);\n\t\tcurrent = this.warzone.getWorld().getBlockAt(x - 2, y - 1, z - 2).getState();\n\t\tcurrent.setType(light);\n\t\tcurrent.setData(lightData);\n\t\tcurrent.update(true);\n\n\t\t// block holder\n\t\tcurrent = this.warzone.getWorld().getBlockAt(x, y, z).getState();\n\t\tcurrent.setType(main);\n\t\tcurrent.setData(mainData);\n\t\tcurrent.update(true);\n\t\tcurrent = this.warzone.getWorld().getBlockAt(x, y, z - 1).getState();\n\t\tcurrent.setType(main);\n\t\tcurrent.setData(mainData);\n\t\tcurrent.update(true);\n\t\tcurrent = this.warzone.getWorld().getBlockAt(x, y, z + 1).getState();\n\t\tcurrent.setType(main);\n\t\tcurrent.setData(mainData);\n\t\tcurrent.update(true);\n\n\t\tcurrent = this.warzone.getWorld().getBlockAt(x, y + 1, z - 1).getState();\n\t\tcurrent.setType(main);\n\t\tcurrent.setData(mainData);\n\t\tcurrent.update(true);\n\t\tcurrent = this.warzone.getWorld().getBlockAt(x, y + 1, z + 1).getState();\n\t\tcurrent.setType(main);\n\t\tcurrent.setData(mainData);\n\t\tcurrent.update(true);\n\n\t\tcurrent = this.warzone.getWorld().getBlockAt(x, y + 2, z).getState();\n\t\tcurrent.setType(main);\n\t\tcurrent.setData(mainData);\n\t\tcurrent.update(true);\n\t\tcurrent = this.warzone.getWorld().getBlockAt(x, y + 2, z - 1).getState();\n\t\tcurrent.setType(main);\n\t\tcurrent.setData(mainData);\n\t\tcurrent.update(true);\n\t\tcurrent = this.warzone.getWorld().getBlockAt(x, y + 2, z + 1).getState();\n\t\tcurrent.setType(main);\n\t\tcurrent.setData(mainData);\n\t\tcurrent.update(true);\n\t}\n\n\tpublic boolean isNear(Location playerLocation) {\n\t\tint x = this.location.getBlockX();\n\t\tint y = this.location.getBlockY();\n\t\tint z = this.location.getBlockZ();\n\t\tint playerX = playerLocation.getBlockX();\n\t\tint playerY = playerLocation.getBlockY();\n\t\tint playerZ = playerLocation.getBlockZ();\n\t\tint diffX = Math.abs(playerX - x);\n\t\tint diffY = Math.abs(playerY - y);\n\t\tint diffZ = Math.abs(playerZ - z);\n\t\tif (diffX < 6 && diffY < 6 && diffZ < 6) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tpublic boolean isOwner(Team team) {\n\t\tif (team == this.ownerTeam) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tpublic boolean hasOwner() {\n\t\treturn this.ownerTeam != null;\n\t}\n\n\tpublic void capture(Team team) {\n\t\tthis.ownerTeam = team;\n\t}\n\n\tpublic void uncapture() {\n\t\tthis.ownerTeam = null;\n\t}\n\n\tpublic Location getLocation() {\n\t\treturn this.location;\n\t}\n\n\tpublic void setOwnerTeam(Team team) {\n\t\tthis.ownerTeam = team;\n\n\t}\n\n\tpublic String getName() {\n\t\treturn this.name;\n\t}\n\n\tpublic void setLocation(Location location) {\n\t\tBlock locationBlock = this.warzone.getWorld().getBlockAt(location.getBlockX(), location.getBlockY(), location.getBlockZ());\n\t\tthis.volume.setCornerOne(locationBlock.getRelative(BlockFace.DOWN).getRelative(Direction.EAST(), 2).getRelative(Direction.SOUTH(), 2));\n\t\tthis.volume.setCornerTwo(locationBlock.getRelative(BlockFace.UP, 2).getRelative(Direction.WEST(), 2).getRelative(Direction.NORTH(), 2));\n\t\tthis.volume.saveBlocks();\n\t\tthis.location = location;\n\t\t\n\t\tthis.addMonumentBlocks();\n\t}\n\n\tpublic Volume getVolume() {\n\t\treturn this.volume;\n\t}\n\n\tpublic void setVolume(Volume newVolume) {\n\t\tthis.volume = newVolume;\n\n\t}\n\n\tpublic Team getOwnerTeam() {\n\n\t\treturn this.ownerTeam;\n\t}\n}"
] | import com.tommytony.war.War;
import com.tommytony.war.Warzone;
import com.tommytony.war.config.TeamKind;
import com.tommytony.war.mapper.WarzoneYmlMapper;
import com.tommytony.war.structure.CapturePoint;
import com.tommytony.war.structure.Monument;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.logging.Level; | package com.tommytony.war.command;
/**
* Sets a capture point
*
* @author Connor Monahan
*/
public class SetCapturePointCommand extends AbstractZoneMakerCommand {
public SetCapturePointCommand(WarCommandHandler handler, CommandSender sender, String[] args) throws NotZoneMakerException {
super(handler, sender, args);
}
@Override
public boolean handle() {
if (!(this.getSender() instanceof Player)) {
this.badMsg("You can't do this if you are not in-game.");
return true;
}
Player player = (Player) this.getSender();
if (this.args.length < 1) {
return false;
}
Warzone zone = Warzone.getZoneByLocation(player);
if (zone == null) {
return false;
} else if (!this.isSenderAuthorOfZone(zone)) {
return true;
}
if (this.args[0].equals(zone.getName())) {
return false;
}
if (zone.hasCapturePoint(this.args[0])) {
// move the existing capture point | CapturePoint cp = zone.getCapturePoint(this.args[0]); | 4 |
teisun/Android-SunmiLauncher | U3DLauncherPlugin/src/sunmi/launcher/LauncherActivity.java | [
"public class Adaptation{\n\n\tpublic static final int NOTE1 = 1;\n\t\n\tpublic static int screenHeight=0;\n\tpublic static int screenWidth=0;\n\tpublic static float screenDensity=0;\n\tpublic static int densityDpi = 0;\n\tpublic static int version = Integer.valueOf(android.os.Build.VERSION.SDK_INT);\n\t\n\tpublic static final int SCREEN_9_16 = 1;//9:16\n\tpublic static final int SCREEN_3_4 = 2;//3:4\n\tpublic static final int SCREEN_4_3 = 3;//4:3\n\tpublic static final int SCREEN_16_9 = 4;//16:9\n\tpublic static int proportion = SCREEN_9_16;\n\t\n\tpublic static final float PROPORTION_9_16 = 0.56f;//9:16\n\tpublic static final float PROPORTION_3_4 = 0.75f;//3:4\n\tpublic static final float PROPORTION_4_3 = 1.33f;//4:3\n\tpublic static final float PROPORTION_16_9 = 1.77f;//16:9\n\t\n\tpublic static final float AVERAGE1 = 0.655f;//(9:16+3:4)/2\n\tpublic static final float AVERAGE2 = 1.04f;//(3:4+4:3)/2\n\tpublic static final float AVERAGE3 = 1.55f;//(4:3+16:9)/2\n\t\n\tpublic static void init(Activity context) {\n\t\t\tif(screenDensity==0||screenWidth==0||screenHeight==0){\n\t\t\t\tDisplayMetrics dm = new DisplayMetrics();\n\t\t\t\tcontext.getWindowManager().getDefaultDisplay().getMetrics(dm);\n\t\t\t\tAdaptation.screenDensity = dm.density;\n\t\t\t\tAdaptation.screenHeight = dm.heightPixels;\n\t\t\t\tAdaptation.screenWidth = dm.widthPixels;\n\t\t\t\tAdaptation.densityDpi = dm.densityDpi;\n\t\t\t}\n\t\t\t\n\t\t\tfloat proportionF = (float)screenWidth/(float)screenHeight;\n\t\t\t\n\t\t\tif( proportionF<=AVERAGE1 ){\n\t\t\t\tproportion = SCREEN_9_16;\n\t\t\t}else if(proportionF>AVERAGE1&&proportionF<=AVERAGE2){\n\t\t\t\tproportion = SCREEN_3_4;\n\t\t\t}else if(proportionF>AVERAGE2&&proportionF<=AVERAGE3){\n\t\t\t\tproportion = SCREEN_4_3;\n\t\t\t}else if(proportionF>AVERAGE3){\n\t\t\t\tproportion = SCREEN_16_9;\n\t\t\t}\n\t\t\t\n\t\t\tLog.i(\"SCREEN CONFIG\", \"screenHeight:\"+screenHeight+\";screenWidth:\"+screenWidth\n\t\t\t\t\t+\";screenDensity:\"+screenDensity+\";densityDpi:\"+densityDpi);\n\t\t\t\n\t}\n \n}",
"public class BitmapUtils {\n\n private static final String TAG = \"BitmapUtils\"; \n private static final int DEFAULT_COMPRESS_QUALITY = 100;\n private static final int INDEX_ORIENTATION = 0;\n\n private static final String[] IMAGE_PROJECTION = new String[] {\n ImageColumns.ORIENTATION\n };\n\n private final Context context;\n\n public BitmapUtils(Context context) {\n this.context = context;\n }\n\n /**\n * Creates a mutable bitmap from subset of source bitmap, transformed by the optional matrix.\n */\n private static Bitmap createBitmap(\n Bitmap source, int x, int y, int width, int height, Matrix m) {\n // Re-implement Bitmap createBitmap() to always return a mutable bitmap.\n Canvas canvas = new Canvas();\n\n Bitmap bitmap;\n Paint paint;\n if ((m == null) || m.isIdentity()) {\n bitmap = Bitmap.createBitmap(width, height, source.getConfig());\n paint = null;\n } else {\n RectF rect = new RectF(0, 0, width, height);\n m.mapRect(rect);\n bitmap = Bitmap.createBitmap(\n Math.round(rect.width()), Math.round(rect.height()), source.getConfig());\n\n canvas.translate(-rect.left, -rect.top);\n canvas.concat(m);\n\n paint = new Paint(Paint.FILTER_BITMAP_FLAG);\n if (!m.rectStaysRect()) {\n paint.setAntiAlias(true);\n }\n }\n bitmap.setDensity(source.getDensity());\n canvas.setBitmap(bitmap);\n\n Rect srcBounds = new Rect(x, y, x + width, y + height);\n RectF dstBounds = new RectF(0, 0, width, height);\n canvas.drawBitmap(source, srcBounds, dstBounds, paint);\n return bitmap;\n }\n\n private void closeStream(Closeable stream) {\n if (stream != null) {\n try {\n stream.close();\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n }\n\n public Rect getBitmapBounds(byte[] data){\n \tRect bounds = new Rect();\n \ttry {\n \t\tBitmapFactory.Options options = new BitmapFactory.Options();\n options.inJustDecodeBounds = true;\n BitmapFactory.decodeByteArray(data, 0, data.length, options);\n bounds.right = options.outWidth;\n bounds.bottom = options.outHeight;\n Log.i(TAG, \"options.outWidth=\"+options.outWidth+\" , \"+\"options.outHeight=\"+options.outHeight);\n\t\t} catch (Exception e) {\n\t\t}finally {\n }\n return bounds;\n }\n \n public Rect getBitmapBounds(Uri uri) {\n Rect bounds = new Rect();\n InputStream is = null;\n\n try {\n is = context.getContentResolver().openInputStream(uri);\n BitmapFactory.Options options = new BitmapFactory.Options();\n options.inJustDecodeBounds = true;\n BitmapFactory.decodeStream(is, null, options);\n\n bounds.right = options.outWidth;\n bounds.bottom = options.outHeight;\n Log.i(TAG, \"options.outWidth=\"+options.outWidth+\" , \"+\"options.outHeight=\"+options.outHeight);\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n closeStream(is);\n }\n\n return bounds;\n }\n \n public Rect getBitmapBounds(InputStream is, boolean isClose) {\n \tRect bounds = new Rect();\n \t\n \ttry {\n \t\tBitmapFactory.Options options = new BitmapFactory.Options();\n \t\toptions.inJustDecodeBounds = true;\n \t\tBitmapFactory.decodeStream(is, null, options);\n \t\t\n \t\tbounds.right = options.outWidth;\n \t\tbounds.bottom = options.outHeight;\n \t\tLog.i(TAG, \"options.outWidth=\"+options.outWidth+\" , \"+\"options.outHeight=\"+options.outHeight);\n \t} catch (Exception e) {\n \t\te.printStackTrace();\n \t} finally {\n \t\tif( isClose )\n \t\t closeStream(is);\n \t}\n \t\n \treturn bounds;\n }\n\n private int getOrientation(Uri uri) {\n int orientation = 0;\n Cursor cursor = null;\n try {\n cursor = context.getContentResolver().query(uri, IMAGE_PROJECTION, null, null, null);\n if ((cursor != null) && cursor.moveToNext()) {\n orientation = cursor.getInt(INDEX_ORIENTATION);\n }\n } catch (Exception e) {\n // Ignore error for no orientation column; just use the default orientation value 0.\n } finally {\n if (cursor != null) {\n cursor.close();\n }\n }\n return orientation;\n }\n\n /**\n * Decodes bitmap (maybe immutable) that keeps aspect-ratio and spans most within the bounds.\n */\n public Bitmap decodeBitmapByStream(InputStream is, Rect bounds, int width, int height) {\n \tLog.i(TAG, \"width = \" + width + \" , \" + \"height = \" + height);\n \tBitmap bitmap = null;\n \ttry {\n \t\t// TODO: Take max pixels allowed into account for calculation to avoid possible OOM.\n// \t\tRect bounds = getBitmapBounds(is, false);\n \t\tint sampleSize = Math.max(bounds.width() / width, bounds.height() / height);\n \t\tsampleSize = Math.min(sampleSize,\n \t\t\t\tMath.max(bounds.width() / height, bounds.height() / width));\n \t\t\n \t\tBitmapFactory.Options options = new BitmapFactory.Options();\n \t\toptions.inSampleSize = Math.max(sampleSize, 1);\n \t\toptions.inPreferredConfig = Bitmap.Config.ARGB_8888;\n \t\t\n \t\tLog.i(TAG, \"sampleSize = \" + sampleSize + \" , \" + \"options.inSampleSize = \" + options.inSampleSize);\n \t\tbitmap = BitmapFactory.decodeStream(is, null, options);//!!!!溢出\n \t} catch (Exception e) {\n \t\tLog.e(TAG, e.getMessage());\n \t} finally {\n \t\tcloseStream(is);\n \t}\n \t\n \t// Ensure bitmap in 8888 format, good for editing as well as GL compatible.\n \tif ((bitmap != null) && (bitmap.getConfig() != Bitmap.Config.ARGB_8888)) {\n \t\tBitmap copy = bitmap.copy(Bitmap.Config.ARGB_8888, true);\n \t\tbitmap.recycle();\n \t\tbitmap = copy;\n \t}\n \t\n \tif (bitmap != null) {\n \t\t// Scale down the sampled bitmap if it's still larger than the desired dimension.\n \t\tfloat scale = Math.min((float) width / bitmap.getWidth(),\n \t\t\t\t(float) height / bitmap.getHeight());\n \t\tscale = Math.max(scale, Math.min((float) height / bitmap.getWidth(),\n \t\t\t\t(float) width / bitmap.getHeight()));\n \t\tif (scale < 1) {\n \t\t\tMatrix m = new Matrix();\n \t\t\tm.setScale(scale, scale);\n \t\t\tBitmap transformed = createBitmap(\n \t\t\t\t\tbitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), m);\n \t\t\tbitmap.recycle();\n \t\t\treturn transformed;\n \t\t}\n \t}\n \treturn bitmap;\n }\n \n /**\n * Decodes bitmap (maybe immutable) that keeps aspect-ratio and spans most within the bounds.\n */\n public Bitmap decodeBitmap(byte[] data, int width, int height){\n \tLog.i(TAG, \"width = \" + width + \" , \" + \"height = \" + height);\n Bitmap bitmap = null;\n try {\n // TODO: Take max pixels allowed into account for calculation to avoid possible OOM.\n Rect bounds = getBitmapBounds(data);\n int sampleSize = Math.max(bounds.width() / width, bounds.height() / height);\n sampleSize = Math.min(sampleSize,\n Math.max(bounds.width() / height, bounds.height() / width));\n\n BitmapFactory.Options options = new BitmapFactory.Options();\n options.inSampleSize = Math.max(sampleSize, 1);\n options.inPreferredConfig = Bitmap.Config.ARGB_8888;\n\n Log.i(TAG, \"sampleSize = \" + sampleSize + \" , \" + \"options.inSampleSize = \" + options.inSampleSize);\n bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, options);//!!!!溢出\n } catch (Exception e) {\n Log.e(TAG, e.getMessage());\n } finally {\n \tdata = null;\n }\n\n // Ensure bitmap in 8888 format, good for editing as well as GL compatible.\n if ((bitmap != null) && (bitmap.getConfig() != Bitmap.Config.ARGB_8888)) {\n Bitmap copy = bitmap.copy(Bitmap.Config.ARGB_8888, true);\n bitmap.recycle();\n bitmap = copy;\n }\n\n if (bitmap != null) {\n // Scale down the sampled bitmap if it's still larger than the desired dimension.\n float scale = Math.min((float) width / bitmap.getWidth(),\n (float) height / bitmap.getHeight());\n scale = Math.max(scale, Math.min((float) height / bitmap.getWidth(),\n (float) width / bitmap.getHeight()));\n if (scale < 1) {\n Matrix m = new Matrix();\n m.setScale(scale, scale);\n Bitmap transformed = createBitmap(\n bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), m);\n bitmap.recycle();\n return transformed;\n }\n }\n return bitmap;\n }\n \n /**\n * Decodes bitmap (maybe immutable) that keeps aspect-ratio and spans most within the bounds.\n */\n private Bitmap decodeBitmap(Uri uri, int width, int height) {\n \tLog.i(TAG, \"width = \" + width + \" , \" + \"height = \" + height);\n InputStream is = null;\n Bitmap bitmap = null;\n\n try {\n // TODO: Take max pixels allowed into account for calculation to avoid possible OOM.\n Rect bounds = getBitmapBounds(uri);\n int sampleSize = Math.max(bounds.width() / width, bounds.height() / height);\n sampleSize = Math.min(sampleSize,\n Math.max(bounds.width() / height, bounds.height() / width));\n\n BitmapFactory.Options options = new BitmapFactory.Options();\n options.inSampleSize = Math.max(sampleSize, 1);\n options.inPreferredConfig = Bitmap.Config.ARGB_8888;\n\n is = context.getContentResolver().openInputStream(uri);\n Log.i(TAG, \"sampleSize = \" + sampleSize + \" , \" + \"options.inSampleSize = \" + options.inSampleSize);\n bitmap = BitmapFactory.decodeStream(is, null, options);//!!!!溢出\n } catch (Exception e) {\n } finally {\n closeStream(is);\n }\n\n // Ensure bitmap in 8888 format, good for editing as well as GL compatible.\n if ((bitmap != null) && (bitmap.getConfig() != Bitmap.Config.ARGB_8888)) {\n Bitmap copy = bitmap.copy(Bitmap.Config.ARGB_8888, true);\n bitmap.recycle();\n bitmap = copy;\n }\n\n if (bitmap != null) {\n // Scale down the sampled bitmap if it's still larger than the desired dimension.\n float scale = Math.min((float) width / bitmap.getWidth(),\n (float) height / bitmap.getHeight());\n scale = Math.max(scale, Math.min((float) height / bitmap.getWidth(),\n (float) width / bitmap.getHeight()));\n if (scale < 1) {\n Matrix m = new Matrix();\n m.setScale(scale, scale);\n Bitmap transformed = createBitmap(\n bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), m);\n bitmap.recycle();\n return transformed;\n }\n }\n return bitmap;\n }\n \n public Bitmap transform(Bitmap bitmap, int width, int height){\n \t // Scale down the sampled bitmap if it's still larger than the desired dimension.\n float scale = Math.min((float) width / bitmap.getWidth(),\n (float) height / bitmap.getHeight());\n scale = Math.max(scale, Math.min((float) height / bitmap.getWidth(),\n (float) width / bitmap.getHeight()));\n if (scale < 1) {\n Matrix m = new Matrix();\n m.setScale(scale, scale);\n Bitmap transformed = createBitmap(\n bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), m);\n bitmap.recycle();\n return transformed;\n }\n return bitmap;\n }\n\n /**\n * Gets decoded bitmap that keeps orientation as well.\n */\n public Bitmap getBitmap(Uri uri, int width, int height) {\n Bitmap bitmap = decodeBitmap(uri, width, height);\n\n // Rotate the decoded bitmap according to its orientation if it's necessary.\n if (bitmap != null) {\n int orientation = getOrientation(uri);\n if (orientation != 0) {\n Matrix m = new Matrix();\n m.setRotate(orientation);\n Bitmap transformed = createBitmap(\n bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), m);\n bitmap.recycle();\n return transformed;\n }\n }\n return bitmap;\n }\n\n /**\n * Saves the bitmap by given directory, filename, and format; if the directory is given null,\n * then saves it under the cache directory.\n */\n public File saveBitmap(\n Bitmap bitmap, String directory, String filename, CompressFormat format) {\n\n if (directory == null) {\n directory = context.getCacheDir().getAbsolutePath();\n } else {\n // Check if the given directory exists or try to create it.\n File file = new File(directory);\n if (!file.isDirectory() && !file.mkdirs()) {\n return null;\n }\n }\n\n File file = null;\n OutputStream os = null;\n \n try {\n filename = (format == CompressFormat.PNG) ? filename + \".png\" : filename + \".jpg\";\n file = new File(directory, filename); \n os = new FileOutputStream(file);\n bitmap.compress(format, DEFAULT_COMPRESS_QUALITY, os);\n Log.d(TAG, \"save bitmap success:\" + filename);\n } catch (FileNotFoundException e) {\n e.printStackTrace();\n Log.d(TAG, \"save bitmap fail:\" + e.getMessage());\n } finally {\n closeStream(os);\n }\n return file;\n }\n\n /**\n * 缩放bitmap\n * @param bitmap\n * @param w\n * @param h\n * @return\n */\n public static Bitmap zoomBitmap(Bitmap bitmap, float w, float h){\n \tint width = bitmap.getWidth();\n \tint height = bitmap.getHeight();\n \tMatrix matrix = new Matrix();\n \tfloat scaleW = ((float)w / width);\n \tfloat scaleH = ((float)h / height);\n \tmatrix.postScale(scaleW, scaleH);\n \tBitmap newBmp = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);\n \t \n \treturn newBmp;\n }\n \n public static Bitmap rotateBitmap(Bitmap bitmap, float degrees){\n \t if (degrees != 0 && bitmap != null) {\n Matrix m = new Matrix();\n m.postRotate(degrees);\n// m.setRotate(degrees,\n// (float) bitmap.getWidth() / 2, (float) bitmap.getHeight() / 2);\n try {\n bitmap = Bitmap.createBitmap(\n \t\t bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), m, true);\n// if (bitmap != b2) {\n// \t bitmap.recycle(); //Android开发网再次提示Bitmap操作完应该显示的释放\n// \t bitmap = b2;\n// }\n } catch (OutOfMemoryError ex) {\n // Android建议大家如果出现了内存不足异常,最好return 原始的bitmap对象。.\n }\n }\n return bitmap;\n }\n\n\tpublic static Bitmap drawTextToBitmap(Context gContext, int gResId, String gText) { \n \t Log.i(TAG, \"drawTextToBitmap = \" + gText);\n\t\t Resources resources = gContext.getResources(); \n\t\t float scale = resources.getDisplayMetrics().density; \n\t\t Bitmap bitmap = \n\t\t BitmapFactory.decodeResource(resources, gResId); \n\t\t \n\t\t android.graphics.Bitmap.Config bitmapConfig = \n\t\t bitmap.getConfig(); \n\t\t // set default bitmap config if none \n\t\t if(bitmapConfig == null) { \n\t\t bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888; \n\t\t } \n\t\t // resource bitmaps are imutable, \n\t\t // so we need to convert it to mutable one \n\t\t bitmap = bitmap.copy(bitmapConfig, true); \n\t\t \n\t\t Canvas canvas = new Canvas(bitmap); \n\t\t // new antialised Paint \n\t\t Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); \n\t\t // text color - #3D3D3D \n\t\t paint.setColor(Color.WHITE); \n\t\t // text size in pixels \n\t\t paint.setTextSize((int) (12 * scale)); \n\t\t // text shadow \n//\t\t paint.setShadowLayer(1f, 0f, 1f, Color.WHITE); \n\t\t \n\t\t // draw text to the Canvas center \n\t\t Rect bounds = new Rect(); \n\t\t paint.getTextBounds(gText, 0, gText.length(), bounds); \n\t\t int x = (bitmap.getWidth() - bounds.width())/2; \n\t\t int y = (bitmap.getHeight())/2 + (int)scale*2; \n\t\t \n\t\t canvas.drawText(gText, x, y, paint); \n\t \n\t\t canvas.save(Canvas.ALL_SAVE_FLAG); \n\t canvas.restore();\n\t\t \n\t\t return bitmap; \n\t} \n\t\n\t\n}",
"public class DeviceUtitls {\n\n\tpublic static String getDeviceInfo(Context context) {\n\t\ttry {\n\t\t\torg.json.JSONObject json = new org.json.JSONObject();\n\t\t\tandroid.telephony.TelephonyManager tm = (android.telephony.TelephonyManager) context\n\t\t\t\t\t.getSystemService(Context.TELEPHONY_SERVICE);\n\n\t\t\tString device_id = tm.getDeviceId();\n\n\t\t\tandroid.net.wifi.WifiManager wifi = (android.net.wifi.WifiManager) context\n\t\t\t\t\t.getSystemService(Context.WIFI_SERVICE);\n\n\t\t\tString mac = wifi.getConnectionInfo().getMacAddress();\n\t\t\tjson.put(\"mac\", mac);\n\n\t\t\tif (TextUtils.isEmpty(device_id)) {\n\t\t\t\tdevice_id = mac;\n\t\t\t}\n\n\t\t\tif (TextUtils.isEmpty(device_id)) {\n\t\t\t\tdevice_id = android.provider.Settings.Secure.getString(\n\t\t\t\t\t\tcontext.getContentResolver(),\n\t\t\t\t\t\tandroid.provider.Settings.Secure.ANDROID_ID);\n\t\t\t}\n\n\t\t\tjson.put(\"device_id\", device_id);\n\n\t\t\treturn json.toString();\n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn null;\n\t}\n\t\n\t/**\n\t * 获取设备型号\n\t * @return\n\t */\n\tpublic static String getDeviceModel(){\n\t\tString model = Build.MODEL;\n\t\tLogUtil.e(\"model\", model);\n\t\treturn model;\n\t}\n\n}",
"@SuppressLint(\"NewApi\")\npublic class FileUtils {\n\n\tprivate static final String TAG = \"FileUtils\";\n\t\n\tprivate static final int ERROR = -1;\n\n\t/**\n\t * 判断是否存在sd卡\n\t * \n\t * @return\n\t */\n\tpublic static boolean isSDCARDMounted() {\n\t\tString status = Environment.getExternalStorageState();\n\t\tif (status.equals(Environment.MEDIA_MOUNTED))\n\t\t\treturn true;\n\t\treturn false;\n\t}\n\t\n\tpublic static String getSDCardPath(){\n\t\treturn Environment.getExternalStorageDirectory().getPath();\n\t}\n\n\n\n\t/**\n\t * 创建文件夹\n\t * \n\t * @param folderName\n\t */\n\tpublic static boolean createFolder(String folderName) {\n\t\tfor (int i = 0; i < 3; i++) {\n\t\t\tFile file = new File(folderName);\n\t\t\tif (!file.exists()) { // 文件不存在\n\t\t\t\t// 创建临时文件夹\n\t\t\t\tboolean mkdir = file.mkdir();\n\t\t\t\tif (mkdir) {\n\t\t\t\t\treturn true;\n\t\t\t\t} else {\n\t\t\t\t\tLogUtil.e(TAG, \"创建文件夹失败\" + folderName);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (!file.isDirectory()) {\n\t\t\t\t\tfile.delete();\n\t\t\t\t\tboolean mkdir = file.mkdir();\n\t\t\t\t\tif (mkdir) {\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tLogUtil.e(TAG, \"创建文件夹失败\");\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\n\t}\n\n\t/**\n\t * 创建文件\n\t * \n\t * @param fileName\n\t * @return\n\t */\n\tpublic static boolean createFile(String fileName) {\n\t\tFile file = new File(fileName);\n\t\tif (file.exists() && file.isFile()) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * 删除临时文件\n\t */\n\tpublic static void deleteFile(String fileName) {\n\t\tFile _file = new File(fileName);\n\t\tif (_file.isDirectory()) {\n\t\t\tFile[] tempFiles = getTempFiles(fileName);\n\t\t\tif(tempFiles ==null )return;\n\t\t\tfor (File file : tempFiles) {\n\t\t\t\tfile.delete();\n\t\t\t}\n\t\t} else {\n\t\t\t_file.delete();\n\t\t}\n\n\t}\n\n\t/**\n\t * 获得临时文件夹的文件列表\n\t * \n\t * @return\n\t */\n\tpublic static File[] getTempFiles(String folderName) {\n\t\tFile folder = new File(folderName);\n\t\treturn folder.listFiles();\n\t}\n\n\tpublic static int fileSize(String folderName) {\n\t\treturn getTempFiles(folderName).length;\n\t}\n\t\n\t/**\n\t * 根据文件path得到文件大小\n\t */\n\tpublic static long getFileSizeByFilePath(String path){\n\t\tlong size;\n\t\tFile file = new File(path);\n\t\tif (file.exists()) {\n\t\t\tsize = file.length();\n\t\t} else {\n\t\t\tsize = 0;\n\t\t}\n\t\treturn size;\n\t}\n\n\t/**\n\t * \n\t * bit装换成MB\n\t * \n\t * @return\n\t */\n\n\tpublic static String FileSize(float FileBitSize) {\n\t\tString fileSize = null;\n\t\tDecimalFormat df = new DecimalFormat(\"0.0\");\n\t\tfileSize = df.format(FileBitSize / (1024 * 1024)) + \"M\";\n\t\treturn fileSize;\n\t}\n\t\n\t/**创建异常文件*/\n\tpublic static File createErrorFile(){\n\t\tFile file = null;\n\t\ttry {\n\t\t\tString DIR = Environment.getExternalStorageDirectory().getAbsolutePath() + \"/LauncherPlugin/log/\";\n\t\t\tString NAME = DateUtils.getCurrentDateString() + \".txt\";\n\t\t\tFile dir = new File(DIR);\n\t\t\tif (!dir.exists()) {\n\t\t\t\tdir.mkdirs();\n\t\t\t}\n\t\t\tfile = new File(dir, NAME);\n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn file;\n\t}\n\t\n\t/**\n\t * 删除一个文件\n\t * @param file\n\t */\n\tpublic static void deleteFile(File file){\n\t\tFile to = new File(file.getAbsolutePath() + System.currentTimeMillis());\n\t\tfile.renameTo(to);\n\t\tto.delete();\n\t}\n\t\n}",
"public class LogUtil {\n\n\tpublic static final int VERBOSE = 1;\n\tpublic static final int DEBUG = 2;\n\tpublic static final int INFO = 3;\n\tpublic static final int WARN = 4;\n\tpublic static final int ERROR = 5;\n\tpublic static final int NOTHING = 6;\n\tpublic static final int LEVEL = VERBOSE;\n\n\tpublic static void v(String tag, String msg) {\n\t\tif (LEVEL <= VERBOSE) {\n\t\t\tLog.v(tag, msg);\n\t\t}\n\t}\n\n\tpublic static void d(String tag, String msg) {\n\t\tif (LEVEL <= DEBUG) {\n\t\t\tLog.d(tag, msg);\n\t\t}\n\t}\n\n\tpublic static void i(String tag, String msg) {\n\t\tif (LEVEL <= INFO) {\n\t\t\tif( msg!=null )\n\t\t\t Log.i(tag, msg);\n\t\t}\n\t}\n\n\tpublic static void w(String tag, String msg) {\n\t\tif (LEVEL <= WARN) {\n\t\t\tLog.w(tag, msg);\n\t\t}\n\t}\n\n\tpublic static void e(String tag, String msg) {\n\t\tif (LEVEL <= ERROR) {\n\t\t\tLog.e(tag, msg);\n\t\t}\n\t}\n\t\n}",
"public class ProcessUtils {\n\n\t/**\n\t * 根据包名判断应用在前台还是后台\n\t * \n\t * @param context\n\t * @return\n\t */\n\tpublic static boolean isBackground(Context context, String packageName) {\n\t\tActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);\n\t\tList<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();\n\t\tfor (RunningAppProcessInfo appProcess : appProcesses) {\n\t\t\tif (appProcess.processName.equals(packageName)) {\n\t\t\t\tif (appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {\n\t\t\t\t\tLog.i(\"前台\", appProcess.processName);\n\t\t\t\t\treturn false;\n\t\t\t\t} else {\n\t\t\t\t\tLog.i(\"后台\", appProcess.processName);\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n\n\t/**\n\t * 用来判断服务是否运行.\n\t * \n\t * @param context\n\t * @param className\n\t * 判断的服务名字\n\t * @return true 在运行 false 不在运行\n\t */\n\tpublic static boolean isServiceRunning(Context mContext, String className) {\n\t\tboolean isRunning = false;\n\t\tActivityManager activityManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);\n\t\tList<ActivityManager.RunningServiceInfo> serviceList = activityManager.getRunningServices(100);\n\t\tif (!(serviceList.size() > 0)) {\n\t\t\treturn false;\n\t\t}\n\t\tfor (int i = 0; i < serviceList.size(); i++) {\n\t\t\tString name = serviceList.get(i).service.getClassName();\n\t\t\tif (name.equals(className) == true) {\n\t\t\t\tisRunning = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn isRunning;\n\t}\n\n\t/**\n\t * 打开app\n\t * \n\t * @param mContext\n\t * @param packageName\n\t */\n\tpublic static void launchApp(Context mContext, String packageName) {\n\t\tPackageManager packageManager = mContext.getPackageManager();\n\t\t// 获取目标应用安装包的Intent\n\t\tIntent intent = packageManager.getLaunchIntentForPackage(packageName);\n\t\tmContext.startActivity(intent);\n\t}\n\n\t/**\n\t * 判断指定包名的进程是否运行\n\t * \n\t * @param context\n\t * @param packageName\n\t * 指定包名\n\t * @return 是否运行\n\t */\n\tpublic static boolean isRunning(Context context, String packageName) {\n\t\tActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);\n\t\tList<RunningAppProcessInfo> infos = am.getRunningAppProcesses();\n\t\tfor (RunningAppProcessInfo rapi : infos) {\n\t\t\tif (rapi.processName.equals(packageName))\n\t\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * 判断应用是否已安装\n\t * \n\t * @param context\n\t * @param packageName\n\t * @return\n\t */\n\tpublic static boolean isInstalled(Context context, String packageName) {\n\t\tboolean hasInstalled = false;\n\t\tPackageManager pm = context.getPackageManager();\n\t\tList<PackageInfo> list = pm.getInstalledPackages(PackageManager.PERMISSION_GRANTED);\n\t\tfor (PackageInfo p : list) {\n\t\t\tif (packageName != null && packageName.equals(p.packageName)) {\n\t\t\t\thasInstalled = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn hasInstalled;\n\t}\n\n\t/**\n\t * Android中如何判断Intent是否存在\n\t * \n\t * @param context\n\t * @param intent\n\t * @return\n\t */\n\tpublic static boolean isIntentAvailable(Context context, Intent intent) {\n\t\tPackageManager packageManager = context.getPackageManager();\n\t\tList<ResolveInfo> list = packageManager.queryIntentActivities(intent, PackageManager.GET_ACTIVITIES);\n\t\treturn list.size() > 0;\n\t}\n}",
"public class UninstallUtils {\n\tprivate static final String TAG = \"UninstallDialogUtils\";\n\t\n\t/**\n\t * 是否可以静默卸载\n\t * @param context\n\t * @param appModel\n\t * @return\n\t */\n\tpublic static boolean canSilenceUninstall(Context context, String packageName){\n\t\tUri packageURI = Uri.parse(\"package:\" + packageName);\n\t\tIntent intent = new Intent(BroadcastConstants.ACTION_DELETE_HIDE, packageURI);\n\t\treturn ProcessUtils.isIntentAvailable(context, intent);\n\t}\n\t\n\t/**\n\t * 静默卸载\n\t * @param context\n\t * @param appModel\n\t */\n\tpublic static void silenceUninstall(Context context, AppModel appModel){\n\t\tUri packageURI = Uri.parse(\"package:\" + appModel.getPackageName());\n\t\tIntent intent = new Intent(BroadcastConstants.ACTION_DELETE_HIDE, packageURI);\n\t\tintent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);\n\t\tcontext.startActivity(intent);\n\t}\n\t\n\t/**\n\t * 卸载\n\t * @param context\n\t * @param appModel\n\t */\n\tpublic static void uninstall(Context context, AppModel appModel){\n\t\tUri packageURI = Uri.parse(\"package:\" + appModel.getPackageName());\n\t\tIntent intent = new Intent(Intent.ACTION_DELETE, packageURI);\n\t\tcontext.startActivity(intent);\n\t}\n\n\t/**\n\t * 移除应用广播\n\t * @param mContext\n\t * @param appModel\n\t */\n\tprivate static void broadcastUninstall(Context mContext, AppModel appModel) {\n\t\tIntent i = new Intent();\n\t\ti.setAction(BroadcastConstants.APP_REMOVE);\n\t\ti.putExtra(\"packageName\", appModel.getPackageName());\n\t\tmContext.sendBroadcast(i);\n\t}\n}"
] | import java.io.File;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import sunmi.launcher.utils.Adaptation;
import sunmi.launcher.utils.BitmapUtils;
import sunmi.launcher.utils.DeviceUtitls;
import sunmi.launcher.utils.FileUtils;
import sunmi.launcher.utils.LogUtil;
import sunmi.launcher.utils.ProcessUtils;
import sunmi.launcher.utils.UninstallUtils;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.WindowManager;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.unity3d.player.UnityPlayer;
import com.unity3d.player.UnityPlayerActivity; | package sunmi.launcher;
/**
*
* TODO主页面
*
* @author xuron
* @versionCode 1 <1>
*/
@SuppressLint("NewApi")
public class LauncherActivity extends UnityPlayerActivity {
//public class LauncherActivity extends Activity {
private static final String TAG = "LauncherActivity"; | private static final String ICON_FOLDER = FileUtils.getSDCardPath()+"/launcher_icon/"; | 3 |
BlochsTech/BitcoinCardTerminal | src/com/blochstech/bitcoincardterminal/ViewModel/ViewStateManagers/MessageManager.java | [
"public class MainActivity extends FragmentActivity {\n\t\n\tprivate NfcAdapter mAdapter;\n\tprivate PendingIntent mPendingIntent;\n\tprivate String[][] techListsArray;\n\t\n\tpublic static MainActivity instance;\n\t\n\tpublic static Context GetMainContext(){\n\t\tContext res = instance != null ? instance.getApplicationContext() : null;\n\t\treturn res;\n\t}\n\t\n\t\n\t\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n \n if(instance == null)\n \tinstance = this;\n \n setContentView(R.layout.fragment_placeholder);\n if (findViewById(R.id.reuseablePlaceholder) != null) {\n\t\t\tif (savedInstanceState == null) {\n\t\t\t\tMainPage mainPage = new MainPage();\n\t\t\t\tFragmentTransaction transaction = getSupportFragmentManager().beginTransaction();\n\t\t\t\tif(getSupportFragmentManager().findFragmentById(R.id.reuseablePlaceholder) != null)\n\t\t\t\t{\n\t\t\t\t\ttransaction.replace(R.id.reuseablePlaceholder, mainPage);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\ttransaction.add(R.id.reuseablePlaceholder, mainPage);\n\t\t\t\t}\n\n\t\t\t\ttransaction.commit();\n\t\t\t}\n\t\t}\n \n ListenForNFCIntent();\n CurrencyApiConnector.SynchPrices(\"MainInit\");\n \n MessageManager.Instance().AddMessage(\"Init \" + Calendar.getInstance().getTime().toString(), false);\n \n Model.Instance(); //Init Model. (starts network task, among other things, that will upload pending TXs if there is network)\n \n //TEMP TEST\n /*try{\n\t\t\tTXObject parsedTX = TXUtil.ParseTXToObjectForm(\"0100000001C412E231F2941550BF4FB097FE231456072145BF9E8162670D3403E19E007D96020000008B483045022050CCF0CB8F8552BB13FE1338339572B578053428884D61DD5D7298249B906E9D02210091CDCC7DABB9E8D1BCAA47D6D022695EC49FB343CFA77385C4CAF90EB6BF990D014104E9C4C6AD2BE6D97BD4BBBA18FC51E62A0B4B393735FB8C0FB859253AAF4427789CE6D4D1B653C29D67B99E9DCCA1FBFAF1AB86AEBE50B5B277ECD8BA8DBCAC65FFFFFFFF025E150000000000001976A914B22A5A0F48C42A0219A4BFE146E2A2432D9F9E1388AC6D860000000000001976A9140044B6662B972525F7FB6C2B40D51AA4CB56BC5D88AC00000000\");\n\t\t\tif(parsedTX != null)\n\t\t\t\tparsedTX = TXUtil.CorrectSignatureS(parsedTX);\n\t\t\tLog.i(Tags.APP_TAG, parsedTX.HexValue);\n\t\t}catch(Exception ex){\n\t\t\tLog.e(Tags.APP_TAG, \"Failed to correct potential high S values in TX.\" + (ex!=null?ex.toString():\"\"));\n\t\t\tif(Tags.DEBUG)\n\t\t\t\tex.printStackTrace();\n\t\t}*/\n //TEMP TEST\n }\n \n private void ListenForNFCIntent(){\n \tmAdapter = NfcAdapter.getDefaultAdapter(this);\n mPendingIntent = PendingIntent.getActivity(\n \t\tthis,\n \t\t0,\n \t\tnew Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP),\n \t\t0);\n IntentFilter filter = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);\n filter.addDataScheme(\"vnd.android.nfc\");\n techListsArray = new String[][] { new String[] { NfcA.class.getName() } };\n Intent launchIntent = getIntent();\n if(launchIntent != null && launchIntent.getAction().equals(NfcAdapter.ACTION_TECH_DISCOVERED))\n {\n \tonNewIntent(launchIntent);\n }\n }\n \n @Override\n public void onResume(){\n \tsuper.onResume();\n \tif(mAdapter != null)\n \t\tmAdapter.enableForegroundDispatch(this, mPendingIntent, null, techListsArray);\n \t//Re-start listening when app returns.\n }\n \n @Override\n public void onPause(){\n \tsuper.onPause();\n \tModel.Instance().persistData();\n \tif(mAdapter != null)\n \t\tmAdapter.disableForegroundDispatch(this); //Stop listening when app not active.\n }\n \n @Override\n public void onNewIntent(Intent intent){\n \t\n \tif(intent != null && intent.getAction().equals(NfcAdapter.ACTION_TECH_DISCOVERED))\n {\n\t \tTag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);\n\t \tModel.Instance().setCard(tag);\n }\n }\n\n @Override\n public boolean onCreateOptionsMenu(Menu menu) {\n getMenuInflater().inflate(R.menu.main, menu);\n return true;\n } \n \n @Override \n public boolean onOptionsItemSelected(MenuItem item) { \n switch (item.getItemId()) { \n case R.id.action_settings: \n \tNavigationManager.Instance().setPage(PageTags.SETTINGS_PAGE);\n \treturn true;\n default: \n return super.onOptionsItemSelected(item); \n } \n } \n}",
"public class Message {\n\tpublic long CreatedMillis;\n\tpublic String Message;\n\tpublic MessageType Type;\n\n\tpublic Message(String message, MessageType type, long createdMillis){\n\t\tthis.Type = type;\n\t\tthis.Message = message;\n\t\tthis.CreatedMillis = createdMillis;\n\t}\n\tpublic Message(String message, MessageType type){\n\t\tthis.Type = type;\n\t\tthis.Message = message;\n\t\tthis.CreatedMillis = System.currentTimeMillis();\n\t}\n\tpublic Message(String message){\n\t\tthis.Type = MessageType.Info;\n\t\tthis.Message = message;\n\t\tthis.CreatedMillis = System.currentTimeMillis();\n\t}\n\t\n\tpublic enum MessageType{\n\t\tInfo,\n\t\tWarning,\n\t\tError\n\t}\n}",
"public enum MessageType{\n\tInfo,\n\tWarning,\n\tError\n}",
"public class Model implements IModel{\n\t//Singleton pattern:\n\tprivate static Model instance = null;\n\tpublic static Model Instance()\n\t{\n\t\tif(instance == null)\n\t\t{\n\t\t\tinstance = new Model();\n\t\t}\n\t\treturn instance;\n\t}\n\tprivate Model()\n\t{\n\t\tmessageEvent = new Event<Message>(fireKey);\n\t\tupdateEvent = new Event<Object>(fireKey, 3); //PinPageVM, ChargePageVM and SettingsPageVM\n\t\tDAL.Instance().MessageEventReference().register(messageListener);\n\t\tpaymentModel = new PaymentModel();\n\t\tcardModel = new CardModel();\n\t\tcardModel.MessageEventReference().register(messageListener);\n\t}\n\t//Singleton pattern end.\n\t\n\tprivate PaymentModel paymentModel;\n\tprivate CardModel cardModel;\n\t\n\tprivate EventListener<Message> messageListener = new MessageListener();\n\t\n\tpublic Event<Message> messageEvent;\n\tpublic Event<Object> updateEvent; //Whatever object was updated or an enum if needed.\n\t\n\tprivate Object fireKey = new Object();\n\t\n\tvoid fireUpdate(Object event){ //Accesible to model only.\n\t\tupdateEvent.fire(fireKey, event);\n\t}\n\t\n\t@Override\n\tpublic void persistData(){\n\t\tpaymentModel.persistData();\n\t\tcardModel.persistData();\n\t}\n\t\n\t@Override\n\tpublic void setCard(Tag tag) {\n\t\tcardModel.setCard(tag);\n\t}\n\t\n\t@Override\n\tpublic void setPin(int value){\n\t\tcardModel.setPin(value);\n\t}\n\t\n\t@Override\n\tpublic boolean setAddress(String address) {\n\t\treturn paymentModel.setAddress(address);\n\t}\n\t@Override\n\tpublic String getAddress() {\n\t\treturn paymentModel.getAddress();\n\t}\n\t\n\t@Override\n\tpublic boolean setFee(Double feeDollarValue) {\n\t\treturn paymentModel.setFee(feeDollarValue);\n\t}\n\t@Override\n\tpublic Double getFee() {\n\t\treturn paymentModel.getFee();\n\t}\n\t\n\t@Override\n\tpublic void setCourtesyOK(boolean courtesyOK) {\n\t\tpaymentModel.setCourtesyOK(courtesyOK);\n\t}\n\t@Override\n\tpublic boolean getCourtesyOK() {\n\t\treturn paymentModel.getCourtesyOK();\n\t}\n\t\n\t@Override\n\tpublic void setCurrency(Currency currency) {\n\t\tpaymentModel.setCurrency(currency);\n\t}\n\t@Override\n\tpublic Currency getCurrency() {\n\t\treturn paymentModel.getCurrency();\n\t}\n\t\n\t@Override\n\tpublic void setPrice(Double value) {\n\t\tpaymentModel.setPrice(value);\n\n\t\tDouble feeDollarValue = paymentModel.getFee();\n\t\tDouble btcVal = feeDollarValue / CurrencyApiConnector.DollarValue(Currency.Bitcoins);\n\t\tif(btcVal < AppSettings.MIN_FEE_BITCOINS)\n\t\t{\n\t\t\tfeeDollarValue = AppSettings.MIN_FEE_BITCOINS * CurrencyApiConnector.DollarValue(Currency.Bitcoins);\n\t\t\tModel.Instance().setFee(feeDollarValue);\n\t\t}\n\n\t\tcardModel.setCharge(value / CurrencyApiConnector.DollarValue(Currency.Bitcoins), feeDollarValue / CurrencyApiConnector.DollarValue(Currency.Bitcoins), paymentModel.getAddress(), paymentModel.getCourtesyOK());\n\t}\n\t@Override\n\tpublic Double getPrice() {\n\t\treturn paymentModel.getPrice();\n\t}\n\t\n\t@Override\n\tpublic String getCardMessage() {\n\t\treturn cardModel.getCardMessage();\n\t}\n\t\n\t@Override\n\tpublic String getShortCharge() {\n\t\treturn cardModel.getShortCharge();\n\t}\n\t\n\t@Override\n\tpublic String getVignereCode() {\n\t\treturn cardModel.getVignereCode();\n\t}\n\t\n\t@Override\n\tpublic boolean getPinRequired() {\n\t\treturn cardModel.getPinRequired();\n\t}\n\t\n\t@Override\n\tpublic String getCardAddress() {\n\t\treturn cardModel.getCardAddress();\n\t}\n\t\n\t@Override\n\tpublic Event<Message> MessageEventReference() {\n\t\treturn messageEvent;\n\t}\n\n\tprivate class MessageListener extends EventListener<Message>{\n\t\t@Override\n\t\tpublic void onEvent(Message event) {\n\t\t\tmessageEvent.fire(fireKey, event);\n\t\t}\n\t}\n}",
"public abstract class EventListener<T> implements IEventListener<T> {\n\tprivate LinkedList<Event<T>> list = new LinkedList<Event<T>>();\n\n\t//CONCURRENCY/MONITOR PATTERN:\n\tprivate Thread holder = null;\n\tsynchronized void Enter() //Allow same thread re-entry.\n\t{\n\t\tlong startTime = System.currentTimeMillis();\n\t\t\n\t\twhile(holder != null)\n\t\t{\n\t\t\ttry {\n\t\t\t\tthis.wait();\n\t\t\t} catch (InterruptedException e) {}\n\t\t\tif(System.currentTimeMillis() - startTime > 20000)\n\t\t\t{\n\t\t\t\tLog.e(Tags.APP_TAG, \"FATAL: EventListener was deadlocked for 20 seconds.\");\n\t\t\t}\n\t\t}\n\t\tholder = Thread.currentThread();\n\t}\n\tsynchronized void Leave() \n\t{\n\t\tif(holder == Thread.currentThread())\n\t\t{\n\t\t\tholder = null;\n\t\t\tnotifyAll();\n\t\t}else\n\t\t{\n\t\t\tLog.e(Tags.APP_TAG, \"ERROR: Non lock holder tried to call Leave in Utils class Event.\");\n\t\t}\n\t}\n\n\tvoid addEvent(Event<T> eventDispatcher) //Don't use other than in Event\n\t{\n\t\tif(eventDispatcher != null)\n\t\t{\n\t\t\tlist.add(eventDispatcher);\n\t\t}\n\t}\n\tvoid removeEvent(Event<T> eventDispatcher) //Don't use other than in Event\n\t{\n\t\tif(eventDispatcher != null)\n\t\t{\n\t\t\twhile(list.contains(eventDispatcher))\n\t\t\t{\n\t\t\t\tlist.remove(eventDispatcher);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void unregisterAll() //Call this on your listeners and then null the listener; when you want to destroy your listener-using-object.\n\t{\n\t\tint i = 0;\n\t\tEvent<T> eventDispatcher;\n\t\tEnter();\n\t\twhile(i < list.size()) {\n\t\t\teventDispatcher = list.get(i);\n\t\t\teventDispatcher.Enter();\n\t\t\tif(eventDispatcher != null)\n\t\t\t{\n\t\t\t\teventDispatcher.removeListener(this); //Don't use other than in EventListener\n\t\t\t}\n\t\t\teventDispatcher.Leave();\n\t\t\ti++;\n\t\t}\n\t\tlist.clear();\n\t\tLeave();\n\t}\n\n\tpublic abstract void onEvent(T event);\n}",
"public class Tags {\n\t//Set this to false when building to Google Play app store.\n\tpublic static final boolean DEBUG = false;\n\t\n\tpublic static final String APP_TAG = \"BitcoinCardTerminal\";\n}"
] | import java.util.LinkedList;
import java.util.Queue;
import com.blochstech.bitcoincardterminal.MainActivity;
import com.blochstech.bitcoincardterminal.Interfaces.Message;
import com.blochstech.bitcoincardterminal.Interfaces.Message.MessageType;
import com.blochstech.bitcoincardterminal.Model.Model;
import com.blochstech.bitcoincardterminal.Utils.EventListener;
import com.blochstech.bitcoincardterminal.Utils.Tags;
import android.util.Log;
import android.widget.Toast; | package com.blochstech.bitcoincardterminal.ViewModel.ViewStateManagers;
//The core idea is to avoid any one View having to know all the other Views in order to update say a global status icon,
//message or page number..
public class MessageManager {
//Singleton pattern:
private static MessageManager instance = null;
public static MessageManager Instance()
{
if(instance == null)
{
instance = new MessageManager();
}
return instance;
}
private MessageManager()
{
Model.Instance().MessageEventReference().register(modelMessageListener);
}
//Singleton pattern end.
private Queue<String> messages = new LinkedList<String>();
private final int maxMessages = 500;
private EventListener<Message> modelMessageListener = new ModelMessageListener();
public void AddMessage(String msg, boolean isError){
AddMessage(msg, isError, false);
}
@SuppressWarnings("unused")
public void AddMessage(String msg, boolean isError, boolean isWarning){
//TODO: Add to list + android log... rest can wait... post log guide in this class. | if(msg != null && !msg.isEmpty() && (Tags.DEBUG || isError)){ | 5 |
optimaize/command4j | src/test/java/com/optimaize/command4j/ext/extensions/exception/exceptiontranslation/ExceptionTranslationExtensionTest.java | [
"public interface CommandExecutor {\n\n /**\n * Executes it in the current thread, and blocks until it either finishes successfully or aborts by\n * throwing an exception.\n *\n * @param <A> argument\n * @param <R> Result\n */\n @NotNull\n <A, R> Optional<R> execute(@NotNull Command<A, R> cmd, @NotNull Mode mode, @Nullable A arg) throws Exception;\n\n /**\n * Creates a new command executor service based on your <code>executorService</code> and returns it.\n */\n @NotNull\n CommandExecutorService service(@NotNull final ExecutorService executorService);\n\n /**\n * @return The same default executor service on each call. It is a simple single-threaded service.\n * For anything beyond testing you should use {@link #service(java.util.concurrent.ExecutorService)}.\n */\n @NotNull\n CommandExecutorService service();\n\n}",
"public class CommandExecutorBuilder {\n\n private static final Logger defaultLogger = LoggerFactory.getLogger(CommandExecutor.class); //yes, the class is CommandExecutor.class\n\n private Logger logger;\n private ExecutorCache cache;\n private List<ModeExtension> extensions;\n\n\n /**\n * If not set then <code>LoggerFactory.getLogger(CommandExecutor.class)</code> is used.\n */\n @NotNull\n public CommandExecutorBuilder logger(@NotNull Logger logger) {\n this.logger = logger;\n return this;\n }\n\n /**\n * If not set then <code>new ExecutorCache()</code> is used.\n */\n @NotNull\n public CommandExecutorBuilder cache(@NotNull ExecutorCache cache) {\n this.cache = cache;\n return this;\n }\n\n /**\n * Adds an extension to the executor. This is used for intercepting commands executed by the executor\n * built by this builder.\n *\n * <p>The extension is added in the order of the call; the first added extension will be the first executed,\n * and so on.</p>\n *\n * It is perfectly valid to add the same extension more than once. Such situations occur when there are\n * multiple extensions in use. Example cases:\n * <pre>\n * - logging\n * - once inside, right around the actual command execution,\n * - and once outside, before returning the result.\n * If there was an auto-retry extension in between then we can see in the logs later that\n * a command failed (the inner logger logged it), but in the end it succeeded (the outer\n * logger records the success).\n * - timeout (give up if it takes too long)\n * - once inside, right around the actual command execution,\n * - and once outside, before returning the result.\n * If there was an auto-retry extension in between then we can use a per-execution timeout,\n * and a total execution timeout. If this is a remove method invocation then we could\n * switch the destination server in between and try again, but still enforce a total maximal\n * permitted execution time.\n * </pre>\n *\n * <p>No method for removing extensions is provided. For two reasons.\n * <ol>\n * <li>First, because this is a builder and you're just about assembling it, so your code\n * logic should not need it. (If it was added, then adding extensions would also require the\n * feature to add in a specific position and not just append at the end. And that's all way\n * above the scope of this. We would then use a separate builder class just for making the\n * list of extensions.)</li>\n * <li>Second, it would be a difficult api. In case the same extension is added more than once,\n * then it must be possible to specify which to remove.</li>\n * </ol>\n * </p>\n *\n * <p>If never called then no extensions are used.</p>\n */\n @NotNull\n public CommandExecutorBuilder withExtension(@NotNull ModeExtension extension) {\n if (extensions==null) {\n extensions = new ArrayList<>();\n }\n extensions.add(extension);\n return this;\n }\n\n /**\n * Constructs the object with the added extensions. Uses defaults for the {@link #logger logger}\n * and {@link #cache cache}.\n */\n @NotNull\n public CommandExecutor build() {\n return new DefaultCommandExecutor(\n logger!=null ? logger : defaultLogger,\n cache!=null ? cache : new ExecutorCache(),\n extensions==null ? Collections.<ModeExtension>emptyList() : extensions\n );\n }\n\n}",
"@Immutable\npublic final class Mode {\n\n /**\n * Because it's immutable anyway it does not need to be created over and over again.\n */\n private static final Mode INITIAL_MODE = new Mode();\n\n /**\n * Does not contain null values.\n */\n @NotNull\n private final Map<Key<?>, Object> defs = Maps.newHashMap();\n\n private Mode() {\n }\n\n private Mode(@NotNull Map<Key<?>, Object> defs) {\n this.defs.putAll(defs);\n }\n\n @NotNull\n public static Mode create() {\n return INITIAL_MODE;\n }\n\n /**\n * @return The Optional's value is <code>absent</code> only if there was no such key because the mode\n * class does not allow <code>null</code> values.\n */\n @NotNull\n public <V> Optional<V> get(@NotNull Key<V> key) {\n //noinspection unchecked\n return (Optional<V>) Optional.fromNullable(defs.get(key));\n }\n\n /**\n * Returns {@code true} if the given key exists and does not map to a boolean value of {@code false}.\n *\n * <p>So any other object, such as a string for example (even if empty) or an Integer\n * (even with value 0) will return true.\n *\n * <p>Remember that this object contains no <code>null</code> values, see {@link #with}, thus\n * after \"adding\" <code>null</code> this <code>'is'</code> check returns false.</p>\n */\n public boolean is(@NotNull Key<?> key) {\n final Optional<?> v = get(key);\n return v.isPresent() && !v.get().equals(Boolean.FALSE);\n }\n\n /**\n * Creates and returns a new mode object of the current list of options together with\n * the given one.\n *\n * <p>If {@code value} is {@code null} the option key is removed (same as\n * calling {@link #without(Key)}.</p>\n *\n * <p>If there is a value for that <code>key</code> already then this overrides\n * the previously used value.</p>\n */\n @NotNull\n public <T> Mode with(@NotNull Key<T> key, @Nullable T value) {\n return new Mode(Map(this.defs, key, value));\n }\n\n /**\n * Short for {@link #with(Key, Object) with(Key, true)}\n */\n @NotNull\n public Mode with(@NotNull Key<Boolean> key) {\n return new Mode(Map(this.defs, key, true));\n }\n\n /**\n * Creates and returns a new mode object of the current list of options but without\n * the value for the given <code>key</code>.\n *\n * <p>It causes no exception in case it wasn't there.</p>\n */\n @NotNull\n public Mode without(@NotNull Key<?> key) {\n return new Mode(Map(this.defs, key, null));\n }\n\n\n @NotNull\n private static <T> Map<Key<?>, Object> Map(@NotNull Key<T> key, T value) {\n return Map(Maps.<Key<?>, Object>newHashMap(), key, value);\n }\n\n @NotNull\n private static <T> Map<Key<?>, Object> Map(@NotNull Map<Key<?>, Object> values, @NotNull Key<T> key1, @Nullable T value1) {\n Map<Key<?>, Object> defs = Maps.newHashMap();\n defs.putAll(values);\n if (value1 == null) {\n defs.remove(key1);\n } else {\n if (!key1.type().isAssignableFrom(value1.getClass())) {\n throw new IllegalArgumentException(\"Value '\" + value1 + \"' not appropriate for key '\" + key1 + \"'\");\n }\n defs.put(key1, value1);\n }\n return defs;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n\n Mode mode = (Mode) o;\n\n if (!defs.equals(mode.defs)) return false;\n\n return true;\n }\n\n @Override\n public int hashCode() {\n return defs.hashCode();\n }\n\n @Override\n public String toString() {\n return \"Mode{\" + defs + '}';\n }\n}",
"public abstract class BaseCommand<A, R> implements CombinableCommand<A,R> {\n\n @NotNull @Override\n public final <C> BaseCommand<A, C> andThen(@NotNull Command<R, C> cmd) {\n return new ComposedCommand<>(this, cmd);\n }\n\n @NotNull @Override\n public final BaseCommand<A, R> ifTrueOr(Predicate<R> cond, Command<A, R> alternative) {\n return Commands.firstIfTrue(this, cond, alternative);\n }\n\n @NotNull @Override\n public final BaseCommand<A, R> ifNotNullOr(Command<A, R> alternative) {\n return Commands.firstIfTrue(this, Predicates.<R>notNull(), alternative);\n }\n\n @NotNull @Override\n public final BaseListCommand<A, R> and(Command<A, R> cmd) {\n return Commands.and(this, cmd);\n }\n\n @NotNull @Override\n public final BaseListCommand<Iterable<A>, R> concat(Command<A, R> cmd) {\n return Commands.concat(this, cmd);\n }\n\n /**\n * @see Commands#withValue(Command, Key, Object)\n */\n public final <V> BaseCommand<A, R> withValue(@NotNull Key<V> key, V value) {\n return Commands.withValue(this, key, value);\n }\n\n @Override\n public String toString() {\n return getClass().getSimpleName();\n }\n\n @Override\n public String getName() {\n return getClass().getSimpleName();\n }\n}",
"public class ThrowUnsupportedOperation extends BaseCommand<Void, Void> {\n\n @Override\n public Void call(@NotNull Optional<Void> arg, @NotNull ExecutionContext ec) throws Exception {\n throw new UnsupportedOperationException(\"Nah, can't do!\");\n }\n\n}",
"public class ExceptionExtensions {\n\n public static final ExceptionExtensions INSTANCE = new ExceptionExtensions();\n private ExceptionExtensions(){}\n\n\n /**\n * @see ExceptionTranslationExtension\n */\n public static <A, R> BaseCommand<A, R> withExceptionTranslation(@NotNull Command<A, R> cmd,\n @NotNull ExceptionTranslator exceptionTranslator) {\n return new ExceptionTranslationExtension.Interceptor<>(cmd, exceptionTranslator);\n }\n\n}"
] | import com.optimaize.command4j.CommandExecutor;
import com.optimaize.command4j.CommandExecutorBuilder;
import com.optimaize.command4j.Mode;
import com.optimaize.command4j.commands.BaseCommand;
import com.optimaize.command4j.commands.ThrowUnsupportedOperation;
import com.optimaize.command4j.ext.extensions.exception.ExceptionExtensions;
import org.jetbrains.annotations.NotNull;
import org.testng.annotations.Test; | package com.optimaize.command4j.ext.extensions.exception.exceptiontranslation;
/**
* @author Fabian Kessler
*/
public class ExceptionTranslationExtensionTest {
private static class MyException extends Exception {
private MyException(String message, Throwable cause) {
super(message, cause);
}
}
private static final ExceptionTranslator myExceptionTranslator = new ExceptionTranslator() {
@Override
public boolean canTranslate(@NotNull Throwable t) {
return t instanceof UnsupportedOperationException;
}
@NotNull @Override
public Exception translate(@NotNull Throwable t) throws Exception {
throw new MyException("Translated", t);
}
};
@Test(expectedExceptions=UnsupportedOperationException.class)
public void withoutTranslation() throws Exception {
CommandExecutor nakedExecutor = new CommandExecutorBuilder().build();
BaseCommand<Void,Void> cmd = new ThrowUnsupportedOperation(); | nakedExecutor.execute(cmd, Mode.create(), null); | 2 |
goodow/realtime-channel | src/main/java/com/goodow/realtime/channel/impl/WebSocketBus.java | [
"@JsType\npublic interface Bus {\n String ON_OPEN = \"@realtime/bus/onOpen\";\n String ON_CLOSE = \"@realtime/bus/onClose\";\n String ON_ERROR = \"@realtime/bus/onError\";\n\n /**\n * Close the Bus and release all resources.\n */\n void close();\n\n /* The state of the Bus. */\n State getReadyState();\n\n /* Returns the session ID used by this bus. */\n String getSessionId();\n\n /**\n * Publish a message\n *\n * @param topic The topic to publish it to\n * @param msg The message\n */\n Bus publish(String topic, Object msg);\n\n /**\n * Publish a local message\n *\n * @param topic The topic to publish it to\n * @param msg The message\n */\n Bus publishLocal(String topic, Object msg);\n\n /**\n * Send a message\n *\n * @param topic The topic to send it to\n * @param msg The message\n * @param replyHandler Reply handler will be called when any reply from the recipient is received\n */\n <T> Bus send(String topic, Object msg, Handler<Message<T>> replyHandler);\n\n /**\n * Send a local message\n *\n * @param topic The topic to send it to\n * @param msg The message\n * @param replyHandler Reply handler will be called when any reply from the recipient is received\n */\n <T> Bus sendLocal(String topic, Object msg, Handler<Message<T>> replyHandler);\n\n /**\n * Set a BusHook on the Bus\n *\n * @param hook The hook\n */\n Bus setHook(BusHook hook);\n\n /**\n * Registers a handler against the specified topic\n *\n * @param topic The topic to register it at\n * @param handler The handler\n * @return the handler registration, can be stored in order to unregister the handler later\n */\n @SuppressWarnings(\"rawtypes\")\n Registration subscribe(String topic, Handler<? extends Message> handler);\n\n /**\n * Registers a local handler against the specified topic. The handler info won't be propagated\n * across the cluster\n *\n * @param topic The topic to register it at\n * @param handler The handler\n */\n @SuppressWarnings(\"rawtypes\")\n Registration subscribeLocal(String topic, Handler<? extends Message> handler);\n}",
"@JsType\npublic interface Message<T> {\n /**\n * The body of the message\n */\n T body();\n\n /**\n * Signal that processing of this message failed. If the message was sent specifying a result\n * handler the handler will be called with a failure corresponding to the failure code and message\n * specified here\n *\n * @param failureCode A failure code to pass back to the sender\n * @param msg A message to pass back to the sender\n */\n void fail(int failureCode, String msg);\n\n /**\n * @return Whether this message originated in the local session.\n */\n boolean isLocal();\n\n /**\n * Reply to this message. If the message was sent specifying a reply handler, that handler will be\n * called when it has received a reply. If the message wasn't sent specifying a receipt handler\n * this method does nothing.\n */\n @JsNoExport\n void reply(Object msg);\n\n /**\n * The same as {@code reply(Object msg)} but you can specify handler for the reply - i.e. to\n * receive the reply to the reply.\n */\n @SuppressWarnings(\"hiding\")\n <T> void reply(Object msg, Handler<Message<T>> replyHandler);\n\n /**\n * The reply topic (if any)\n */\n String replyTopic();\n\n /**\n * The topic the message was sent to\n */\n String topic();\n}",
"@JsExport\n@JsType\npublic enum State {\n CONNECTING, OPEN, CLOSING, CLOSED;\n public static final State values[] = values();\n}",
"public interface Handler<E> {\n\n /**\n * Something has happened, so handle it.\n */\n void handle(E event);\n}",
"public class Platform {\n public enum Type {\n JAVA, HTML, ANDROID, IOS, FLASH, STUB, VERTX\n }\n\n private static PlatformFactory FACTORY;\n\n public static Diff diff() {\n return get().diff();\n }\n\n public static Net net() {\n return get().net();\n }\n\n public static Scheduler scheduler() {\n return get().scheduler();\n }\n\n /**\n * Configures the current {@link Platform}. Do not call this directly unless you're implementing a\n * new platform.\n */\n public static void setFactory(PlatformFactory factory) {\n FACTORY = factory;\n }\n\n public static Platform.Type type() {\n return get().type();\n }\n\n private static PlatformFactory get() {\n assert FACTORY != null :\n \"You must register a platform first by invoke {Java|Android}Platform.register()\";\n return FACTORY;\n }\n\n // Non-instantiable\n protected Platform() {\n }\n}",
"public interface WebSocket {\n /**\n * Listens for events on a {@link WebSocket}.\n */\n interface WebSocketHandler {\n\n /**\n * Called when the socket is closed. When the socket is closed, it cannot be reopened.\n */\n void onClose(JsonObject reason);\n\n /**\n * Called when an error occurs on the socket.\n */\n void onError(String error);\n\n /**\n * Called when the socket receives a message.\n */\n void onMessage(String message);\n\n /**\n * Called when the socket is ready to receive messages.\n */\n void onOpen();\n }\n\n /**\n * Close the socket. The socket cannot be used again after calling close; the server must create a\n * new socket.\n */\n void close();\n\n State getReadyState();\n\n void send(String data);\n\n void setListen(WebSocketHandler handler);\n}"
] | import com.goodow.realtime.channel.Bus;
import com.goodow.realtime.channel.Message;
import com.goodow.realtime.channel.State;
import com.goodow.realtime.core.Handler;
import com.goodow.realtime.core.Platform;
import com.goodow.realtime.core.WebSocket;
import com.goodow.realtime.json.Json;
import com.goodow.realtime.json.JsonObject; | /*
* Copyright 2013 Goodow.com
*
* 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.goodow.realtime.channel.impl;
@SuppressWarnings("rawtypes")
public class WebSocketBus extends SimpleBus {
public static final String SESSION = "_session";
public static final String USERNAME = "username";
public static final String PASSWORD = "password";
public static final String PING_INTERVAL = "vertxbus_ping_interval";
public static final String TOPIC_CHANNEL = "realtime/channel";
public static final String TOPIC_CONNECT = TOPIC_CHANNEL + "/_CONNECT";
protected static final String BODY = "body";
protected static final String TOPIC = "address";
protected static final String REPLY_TOPIC = "replyAddress";
protected static final String TYPE = "type";
private final WebSocket.WebSocketHandler webSocketHandler;
String serverUri;
WebSocket webSocket;
private int pingInterval;
private int pingTimerID = -1;
private String sessionId;
private String username;
private String password;
final JsonObject handlerCount = Json.createObject();
public WebSocketBus(String serverUri, JsonObject options) {
webSocketHandler = new WebSocket.WebSocketHandler() {
@Override
public void onClose(JsonObject reason) {
Platform.scheduler().cancelTimer(pingTimerID);
publishLocal(ON_CLOSE, reason);
if (hook != null) {
hook.handlePostClose();
}
}
@Override
public void onError(String error) {
publishLocal(ON_ERROR, Json.createObject().set("message", error));
}
@Override
public void onMessage(String msg) {
JsonObject json = Json.<JsonObject> parse(msg);
@SuppressWarnings({"unchecked"})
MessageImpl message =
new MessageImpl(false, false, WebSocketBus.this, json.getString(TOPIC), json
.getString(REPLY_TOPIC), json.get(BODY));
internalHandleReceiveMessage(message);
}
@Override
public void onOpen() {
sendConnect();
// Send the first ping then send a ping every 5 seconds
sendPing();
pingTimerID = Platform.scheduler().schedulePeriodic(pingInterval, new Handler<Void>() {
@Override
public void handle(Void ignore) {
sendPing();
}
});
if (hook != null) {
hook.handleOpened();
}
publishLocal(ON_OPEN, null);
}
};
connect(serverUri, options);
}
public void connect(String serverUri, JsonObject options) {
this.serverUri = serverUri;
pingInterval =
options == null || !options.has(PING_INTERVAL) ? 5 * 1000 : (int) options
.getNumber(PING_INTERVAL);
sessionId = options == null || !options.has(SESSION) ? idGenerator.next(23) : options.getString(
SESSION);
username = options == null || !options.has(USERNAME) ? null : options.getString(USERNAME);
password = options == null || !options.has(PASSWORD) ? null : options.getString(PASSWORD);
webSocket = Platform.net().createWebSocket(serverUri, options);
webSocket.setListen(webSocketHandler);
}
@Override
public State getReadyState() {
return webSocket.getReadyState();
}
@Override
public String getSessionId() {
return sessionId;
}
@Override
protected void doClose() { | subscribeLocal(Bus.ON_CLOSE, new Handler<Message<JsonObject>>() { | 1 |
mguetlein/CheS-Mapper | src/main/java/org/chesmapper/view/gui/table/TreeView.java | [
"public class Cluster extends ZoomableCompoundGroup implements CompoundGroupWithProperties, DoubleNameElement,\r\n\t\tComparable<Cluster>\r\n{\r\n\tprivate ClusterData clusterData;\r\n\r\n\tHashMap<String, List<Compound>> compoundsOrderedByPropterty = new HashMap<String, List<Compound>>();\r\n\r\n\tprivate boolean watched;\r\n\tprivate CompoundProperty highlightProp;\r\n\tprivate HighlightSorting highlightSorting;\r\n\tprivate boolean showLabel = false;\r\n\r\n\tpublic Cluster(org.chesmapper.map.dataInterface.ClusterData clusterData)\r\n\t{\r\n\t\tthis.clusterData = clusterData;\r\n\t\tList<Compound> c = new ArrayList<Compound>();\r\n\t\tint count = 0;\r\n\t\tfor (CompoundData d : clusterData.getCompounds())\r\n\t\t\tc.add(new Compound(clusterData.getCompoundClusterIndices().get(count++), d));\r\n\t\tsetCompounds(c);\r\n\r\n\t\tdisplayName.name = getName() + \" (#\" + getNumCompounds() + \")\";\r\n\t\tdisplayName.compareIndex = clusterData.getOrigIndex();\r\n\r\n\t\tif (View.instance != null) // for export without graphics\r\n\t\t\tupdate();\r\n\t}\r\n\r\n\tpublic void setFilter(CompoundFilter filter)\r\n\t{\r\n\t\tsuper.setFilter(filter);\r\n\t\tList<Integer> origIndices = new ArrayList<Integer>();\r\n\t\tif (filter != null)\r\n\t\t\tfor (Compound c : getCompounds())\r\n\t\t\t\tif (filter.accept(c))\r\n\t\t\t\t\torigIndices.add(c.getOrigIndex());\r\n\t\tclusterData.setFilter(filter == null ? null : origIndices);\r\n\t\tupdateDisplayName();\r\n\t}\r\n\r\n\tboolean alignedCompoundsCalibrated = false;\r\n\r\n\tpublic void updatePositions()\r\n\t{\r\n\t\t// the actual compound position that is stored in compound is never changed (depends only on scaling)\r\n\t\t// this method moves all compounds to the cluster position\r\n\r\n\t\t// recalculate non-superimposed diameter\r\n\t\tupdate();\r\n\r\n\t\tif (!clusterData.isAligned())\r\n\t\t{\r\n\t\t\t// the compounds have not been aligned\r\n\t\t\t// the compounds may have a center != 0, calibrate to 0\r\n\t\t\tfor (Compound m : getCompounds())\r\n\t\t\t\tm.moveTo(new Vector3f(0f, 0f, 0f));\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\t// the compounds are aligned, cannot calibrate to 0, this would brake the alignment\r\n\t\t\t// however, the compound center may have an offset, calculate and remove\r\n\t\t\tif (!alignedCompoundsCalibrated)\r\n\t\t\t{\r\n\t\t\t\tVector3f[] origCenters = new Vector3f[getCompounds().size()];\r\n\t\t\t\tfor (int i = 0; i < origCenters.length; i++)\r\n\t\t\t\t\torigCenters[i] = getCompounds().get(i).origCenter;\r\n\t\t\t\tVector3f center = Vector3fUtil.center(origCenters);\r\n\t\t\t\tfor (int i = 0; i < origCenters.length; i++)\r\n\t\t\t\t\tgetCompounds().get(i).origCenter.sub(center);\r\n\t\t\t\talignedCompoundsCalibrated = true;\r\n\t\t\t}\r\n\t\t\tfor (Compound m : getCompounds())\r\n\t\t\t\tm.moveTo(m.origCenter);\r\n\t\t}\r\n\r\n\t\t// translate compounds to the cluster position\r\n\t\tView.instance.setAtomCoordRelative(getCenter(true), getBitSet());\r\n\t}\r\n\r\n\tprivate DisplayName displayName = new DisplayName();\r\n\tprivate Color highlightColorText;\r\n\r\n\tpublic String getName()\r\n\t{\r\n\t\treturn clusterData.getName();\r\n\t}\r\n\r\n\t@Override\r\n\tpublic String toString()\r\n\t{\r\n\t\treturn getName();\r\n\t}\r\n\r\n\tpublic String toStringWithValue()\r\n\t{\r\n\t\treturn displayName.toString(false, null);\r\n\t}\r\n\r\n\t@Override\r\n\tpublic String getFirstName()\r\n\t{\r\n\t\treturn displayName.name;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic String getSecondName()\r\n\t{\r\n\t\tif (ObjectUtil.equals(displayName.valDisplay, displayName.name))\r\n\t\t\treturn null;\r\n\t\telse\r\n\t\t\treturn displayName.valDisplay;\r\n\t}\r\n\r\n\tpublic String getSummaryStringValue(CompoundProperty property, boolean html)\r\n\t{\r\n\t\treturn clusterData.getSummaryStringValue(property, html);\r\n\t}\r\n\r\n\tpublic CountedSet<String> getNominalSummary(NominalProperty p)\r\n\t{\r\n\t\treturn clusterData.getNominalSummary(p);\r\n\t}\r\n\r\n\tpublic String getAlignAlgorithm()\r\n\t{\r\n\t\treturn clusterData.getAlignAlgorithm();\r\n\t}\r\n\r\n\tprotected void update()\r\n\t{\r\n\t\tif (getOrigSize() != getNumCompounds())\r\n\t\t\tdisplayName.name = getName() + \" (#\" + getNumCompounds() + \"/\" + getOrigSize() + \")\";\r\n\t\telse\r\n\t\t\tdisplayName.name = getName() + \" (#\" + getNumCompounds() + \")\";\r\n\t\tsuper.update();\r\n\t}\r\n\r\n\tpublic List<Compound> getCompoundsInOrder(final CompoundProperty property, HighlightSorting sorting)\r\n\t{\r\n\t\tString key = property + \"_\" + sorting;\r\n\t\tif (!compoundsOrderedByPropterty.containsKey(key))\r\n\t\t{\r\n\t\t\tList<Compound> c = new ArrayList<Compound>();\r\n\t\t\tfor (Compound compound : getCompounds())\r\n\t\t\t\tc.add(compound);\r\n\t\t\tfinal HighlightSorting finalSorting;\r\n\t\t\tif (sorting == HighlightSorting.Median)\r\n\t\t\t\tfinalSorting = HighlightSorting.Max;\r\n\t\t\telse\r\n\t\t\t\tfinalSorting = sorting;\r\n\t\t\tCollections.sort(c, new Comparator<Compound>()\r\n\t\t\t{\r\n\t\t\t\t@Override\r\n\t\t\t\tpublic int compare(Compound o1, Compound o2)\r\n\t\t\t\t{\r\n\t\t\t\t\tint res;\r\n\t\t\t\t\tif (o1 == null)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tif (o2 == null)\r\n\t\t\t\t\t\t\tres = 0;\r\n\t\t\t\t\t\telse\r\n\t\t\t\t\t\t\tres = 1;\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse if (o2 == null)\r\n\t\t\t\t\t\tres = -1;\r\n\t\t\t\t\telse if (property instanceof NumericProperty)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tDouble d1 = o1.getDoubleValue((NumericProperty) property);\r\n\t\t\t\t\t\tDouble d2 = o2.getDoubleValue((NumericProperty) property);\r\n\t\t\t\t\t\tif (d1 == null)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tif (d2 == null)\r\n\t\t\t\t\t\t\t\tres = 0;\r\n\t\t\t\t\t\t\telse\r\n\t\t\t\t\t\t\t\tres = 1;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse if (d2 == null)\r\n\t\t\t\t\t\t\tres = -1;\r\n\t\t\t\t\t\telse\r\n\t\t\t\t\t\t\tres = d1.compareTo(d2);\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse\r\n\t\t\t\t\t\tres = (o1.getStringValue((NominalProperty) property) + \"\").compareTo(o2\r\n\t\t\t\t\t\t\t\t.getStringValue((NominalProperty) property) + \"\");\r\n\t\t\t\t\treturn (finalSorting == HighlightSorting.Max ? -1 : 1) * res;\r\n\t\t\t\t}\r\n\t\t\t});\r\n\t\t\tif (sorting == HighlightSorting.Median)\r\n\t\t\t{\r\n\t\t\t\t//\t\t\t\tSettings.LOGGER.warn(\"max order: \");\r\n\t\t\t\t//\t\t\t\tfor (Compound mm : m)\r\n\t\t\t\t//\t\t\t\t\tSettings.LOGGER.warn(mm.getStringValue(property) + \" \");\r\n\t\t\t\t//\t\t\t\tSettings.LOGGER.warn();\r\n\r\n\t\t\t\t/**\r\n\t\t\t\t * median sorting:\r\n\t\t\t\t * - first order by max to compute median\r\n\t\t\t\t * - create a dist-to-median array, sort compounds according to that array\r\n\t\t\t\t */\r\n\t\t\t\tCompound medianCompound = c.get(c.size() / 2);\r\n\t\t\t\t//\t\t\t\tSettings.LOGGER.warn(medianCompound.getStringValue(property));\r\n\t\t\t\tdouble distToMedian[] = new double[c.size()];\r\n\t\t\t\tif (property instanceof NumericProperty)\r\n\t\t\t\t{\r\n\t\t\t\t\tDouble med = medianCompound.getDoubleValue((NumericProperty) property);\r\n\t\t\t\t\tfor (int i = 0; i < distToMedian.length; i++)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tDouble d = c.get(i).getDoubleValue((NumericProperty) property);\r\n\t\t\t\t\t\tif (med == null)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tif (d == null)\r\n\t\t\t\t\t\t\t\tdistToMedian[i] = 0;\r\n\t\t\t\t\t\t\telse\r\n\t\t\t\t\t\t\t\tdistToMedian[i] = Double.MAX_VALUE;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse if (d == null)\r\n\t\t\t\t\t\t\tdistToMedian[i] = Double.MAX_VALUE;\r\n\t\t\t\t\t\telse\r\n\t\t\t\t\t\t\tdistToMedian[i] = Math.abs(med - d);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tString medStr = medianCompound.getStringValue((NominalProperty) property);\r\n\t\t\t\t\tfor (int i = 0; i < distToMedian.length; i++)\r\n\t\t\t\t\t\tdistToMedian[i] = Math.abs((c.get(i).getStringValue((NominalProperty) property) + \"\")\r\n\t\t\t\t\t\t\t\t.compareTo(medStr + \"\"));\r\n\t\t\t\t}\r\n\t\t\t\tint order[] = ArrayUtil.getOrdering(distToMedian, true);\r\n\t\t\t\tCompound a[] = new Compound[c.size()];\r\n\t\t\t\tCompound s[] = ArrayUtil.sortAccordingToOrdering(order, c.toArray(a));\r\n\t\t\t\tc = ArrayUtil.toList(s);\r\n\r\n\t\t\t\t//\t\t\t\tSettings.LOGGER.warn(\"med order: \");\r\n\t\t\t\t//\t\t\t\tfor (Compound mm : m)\r\n\t\t\t\t//\t\t\t\t\tSettings.LOGGER.warn(mm.getStringValue(property) + \" \");\r\n\t\t\t\t//\t\t\t\tSettings.LOGGER.warn();\r\n\t\t\t}\r\n\t\t\tcompoundsOrderedByPropterty.put(key, c);\r\n\t\t}\r\n\t\t//\t\tSettings.LOGGER.warn(\"in order: \");\r\n\t\t//\t\tfor (Compound m : order.get(key))\r\n\t\t//\t\t\tSettings.LOGGER.warn(m.getCompoundOrigIndex() + \" \");\r\n\t\t//\t\tSettings.LOGGER.warn(\"\");\r\n\t\treturn compoundsOrderedByPropterty.get(key);\r\n\t}\r\n\r\n\tpublic String getSubstructureSmarts(SubstructureSmartsType type)\r\n\t{\r\n\t\treturn clusterData.getSubstructureSmarts(type);\r\n\t}\r\n\r\n\tpublic void removeWithJmolIndices(int[] compoundJmolIndices)\r\n\t{\r\n\t\tSystem.out.println(\"to remove from cluster: \" + ArrayUtil.toString(compoundJmolIndices));\r\n\t\tList<Compound> toDel = new ArrayList<Compound>();\r\n\t\tint[] toDelIndex = new int[compoundJmolIndices.length];\r\n\r\n\t\tint count = 0;\r\n\t\tfor (int i : compoundJmolIndices)\r\n\t\t{\r\n\t\t\tCompound c = getCompoundWithJmolIndex(i);\r\n\t\t\ttoDel.add(c);\r\n\t\t\ttoDelIndex[count++] = getIndex(c);\r\n\t\t}\r\n\t\tBitSet bs = new BitSet();\r\n\t\tfor (Compound m : toDel)\r\n\t\t{\r\n\t\t\tbs.or(m.getBitSet());\r\n\t\t\tgetCompounds().remove(m);\r\n\t\t}\r\n\t\tView.instance.hide(bs);\r\n\r\n\t\tcompoundsOrderedByPropterty.clear();\r\n\t\tclusterData.remove(toDelIndex);\r\n\t\tupdate();\r\n\t}\r\n\r\n\tpublic boolean isWatched()\r\n\t{\r\n\t\treturn watched;\r\n\t}\r\n\r\n\tpublic void setWatched(boolean watched)\r\n\t{\r\n\t\tthis.watched = watched;\r\n\t}\r\n\r\n\tpublic void setHighlighProperty(CompoundProperty highlightProp, Color highlightColorText)\r\n\t{\r\n\t\tthis.highlightProp = highlightProp;\r\n\t\tthis.highlightColorText = highlightColorText;\r\n\t\tupdateDisplayName();\r\n\t}\r\n\r\n\tprivate void updateDisplayName()\r\n\t{\r\n\t\tdisplayName.valDisplay = null;\r\n\t\tdisplayName.valCompare = null;\r\n\t\tif (highlightProp != null)\r\n\t\t{\r\n\t\t\tif (highlightProp instanceof NumericProperty)\r\n\t\t\t\tdisplayName.valCompare = new Double[] { getDoubleValue((NumericProperty) highlightProp) };\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tString mode = getNominalSummary((NominalProperty) highlightProp).getMode(false);\r\n\t\t\t\tString domain[] = ((NominalProperty) highlightProp).getDomain();\r\n\t\t\t\tboolean invertSecondBinaryVal = false;\r\n\t\t\t\tif (domain.length == 2 && ArrayUtil.indexOf(domain, mode) == 1)\r\n\t\t\t\t\tinvertSecondBinaryVal = true;\r\n\t\t\t\tCountedSet<String> set = getNominalSummary((NominalProperty) highlightProp);\r\n\t\t\t\t/**\r\n\t\t\t\t * Clusters with nominal feature values should be sorted as follows:\r\n\t\t\t\t * 1. according to the mode (the most common feature value)\r\n\t\t\t\t * 2. within equal modes, according to how pure the cluster is with respect to the mode (ratio of compounds with this feature value)\r\n\t\t\t\t * 3. within equal ratios, according to size (and therefore according to number of compounds with this feature value)\r\n\t\t\t\t * 4. within equal size, according to cluster index \r\n\t\t\t\t */\r\n\t\t\t\tdisplayName.valCompare = new Comparable[] { mode,\r\n\t\t\t\t\t\t(invertSecondBinaryVal ? 1 : -1) * (set.getMaxCount(false) / (double) (set.getSum(false))),\r\n\t\t\t\t\t\t(invertSecondBinaryVal ? 1 : -1) * set.getSum(false) };\r\n\t\t\t}\r\n\t\t\tdisplayName.valDisplay = getFormattedValue(highlightProp);\r\n\t\t}\r\n\t}\r\n\r\n\tpublic CompoundProperty getHighlightProperty()\r\n\t{\r\n\t\treturn highlightProp;\r\n\t}\r\n\r\n\tpublic void setHighlightSorting(HighlightSorting highlightSorting)\r\n\t{\r\n\t\tthis.highlightSorting = highlightSorting;\r\n\t}\r\n\r\n\tpublic HighlightSorting getHighlightSorting()\r\n\t{\r\n\t\treturn highlightSorting;\r\n\t}\r\n\r\n\tpublic String[] getStringValues(NominalProperty property, Compound excludeCompound)\r\n\t{\r\n\t\treturn getStringValues(property, excludeCompound, false);\r\n\t}\r\n\r\n\tpublic String[] getStringValues(NominalProperty property, Compound excludeCompound, boolean formatted)\r\n\t{\r\n\t\tList<String> l = new ArrayList<String>();\r\n\t\tfor (Compound c : getCompounds())\r\n\t\t\tif (c != excludeCompound && c.getStringValue(property) != null)\r\n\t\t\t\tl.add(formatted ? c.getFormattedValue(property) : c.getStringValue(property));\r\n\t\tString v[] = new String[l.size()];\r\n\t\treturn l.toArray(v);\r\n\t}\r\n\r\n\tpublic Double[] getDoubleValues(NumericProperty property)\r\n\t{\r\n\t\tDouble v[] = new Double[getCompounds().size()];\r\n\t\tfor (int i = 0; i < v.length; i++)\r\n\t\t\tv[i] = getCompounds().get(i).getDoubleValue(property);\r\n\t\treturn v;\r\n\t}\r\n\r\n\tpublic void setShowLabel(boolean showLabel)\r\n\t{\r\n\t\tthis.showLabel = showLabel;\r\n\t}\r\n\r\n\tpublic boolean isShowLabel()\r\n\t{\r\n\t\treturn showLabel;\r\n\t}\r\n\r\n\tpublic int numMissingValues(CompoundProperty p)\r\n\t{\r\n\t\treturn clusterData.numMissingValues(p);\r\n\t}\r\n\r\n\tpublic boolean containsNotClusteredCompounds()\r\n\t{\r\n\t\treturn clusterData.containsNotClusteredCompounds();\r\n\t}\r\n\r\n\t@Override\r\n\tpublic Double getDoubleValue(NumericProperty p)\r\n\t{\r\n\t\treturn clusterData.getDoubleValue(p);\r\n\t}\r\n\r\n\t@Override\r\n\tpublic String getFormattedValue(CompoundProperty p)\r\n\t{\r\n\t\treturn clusterData.getFormattedValue(p);\r\n\t}\r\n\r\n\tpublic Color getHighlightColorText()\r\n\t{\r\n\t\treturn highlightColorText;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic int compareTo(Cluster m)\r\n\t{\r\n\t\treturn displayName.compareTo(m.displayName);\r\n\t}\r\n\r\n}\r",
"public interface ClusterController\n{\n\tpublic void clearClusterActive(boolean animate, boolean clearCompoundActive);\n\n\tpublic void clearClusterWatched();\n\n\tpublic void clearCompoundActive(boolean animate);\n\n\tpublic void clearCompoundWatched();\n\n\tpublic void setClusterActive(Cluster c, boolean animate, boolean clearCompoundActive);\n\n\tpublic void setClusterWatched(Cluster c);\n\n\tpublic void setCompoundActive(Compound c, boolean animate);\n\n\tpublic void setCompoundActive(Compound[] c, boolean animate);\n\n\tpublic void toggleCompoundActive(Compound c);\n\n\tpublic void setCompoundWatched(Compound... c);\n\n\tpublic CompoundFilter getCompoundFilter();\n\n\tpublic void applyCompoundFilter(List<Compound> compounds, boolean accept);\n\n\tpublic void setCompoundFilter(CompoundFilter filter, boolean animate);\n\n\tpublic void useSelectedCompoundsAsFilter(boolean animate);\n\n\tpublic void removeCompounds(Compound[] c);\n\n\tpublic void removeCluster(Cluster... c);\n\n\tpublic void chooseClustersToRemove();\n\n\tpublic void chooseCompoundsToRemove();\n\n\tpublic void chooseClustersToFilter();\n\n\tpublic void chooseCompoundsToFilter();\n\n\tpublic void newClustering();\n\n}",
"public interface Clustering extends CompoundGroupWithProperties\n{\n\tvoid addListener(PropertyChangeListener propertyChangeListener);\n\n\tint getNumClusters();\n\n\tint numClusters();\n\n\tList<Cluster> getClusters();\n\n\tboolean isClusterActive();\n\n\tboolean isClusterWatched();\n\n\tCluster getCluster(int i);\n\n\tint indexOf(Cluster cluster);\n\n\tCluster getActiveCluster();\n\n\tCluster getWatchedCluster();\n\n\tint getActiveClusterIdx();\n\n\tint getWatchedClusterIdx();\n\n\tboolean isCompoundActive();\n\n\tboolean isCompoundWatched();\n\n\tboolean isCompoundActive(Compound c);\n\n\tCompound[] getActiveCompounds();\n\n\tCompound getActiveCompound();\n\n\tint[] getActiveCompoundsJmolIdx();\n\n\tCompound getWatchedCompound();\n\n\tCompound[] getWatchedCompounds();\n\n\tint[] getWatchedCompoundsJmolIdx();\n\n\tCluster getClusterForCompound(Compound c);\n\n\tList<CompoundProperty> selectPropertiesAndFeaturesWithDialog(String title, CompoundProperty preselected,\n\t\t\tboolean addSmiles, boolean addEmbeddingStress, boolean addActivityCliffs, boolean addDistanceTo);\n\n\tList<CompoundProperty> getPropertiesAndFeatures();\n\n\tList<CompoundProperty> getProperties();\n\n\tList<CompoundProperty> getFeatures();\n\n\tList<Compound> getCompounds(boolean includingMultiClusteredCompounds);\n\n\tCluster getUniqueClusterForCompounds(Compound[] c);\n\n\tString getOrigLocalPath();\n\n\tString getOrigSDFile();\n\n\tString getSDFile();\n\n\tboolean isClusterAlgorithmDisjoint();\n\n\tString getClusterAlgorithm();\n\n\tint getClusterIndexForCompound(Compound m);\n\n\tList<CompoundData> getCompounds();\n\n\tvoid chooseClustersToExport(CompoundProperty compoundDescriptor);\n\n\tvoid chooseCompoundsToExport(CompoundProperty compoundDescriptor);\n\n\tDouble[] getDoubleValues(NumericProperty p);\n\n\tString[] getStringValues(NominalProperty p, Compound m);\n\n\tString getSummaryStringValue(CompoundProperty p, boolean b);\n\n\tint numMissingValues(CompoundProperty p);\n\n\tString getName();\n\n\tDouble getNormalizedLogDoubleValue(CompoundPropertyOwner m, NumericProperty p);\n\n\tDouble getNormalizedDoubleValue(CompoundPropertyOwner m, NumericProperty p);\n\n\tdouble getSpecificity(Compound compound, CompoundProperty p);\n\n\tdouble getSpecificity(Cluster cluster, CompoundProperty p);\n\n\tdouble getSpecificity(CompoundSelection sel, CompoundProperty p);\n\n\tint getNumCompounds(boolean includingMultiClusteredCompounds);\n\n\tint getNumUnfilteredCompounds(boolean includingMultiClusteredCompounds);\n\n\tString getEmbedAlgorithm();\n\n\tString getEmbedQuality();\n\n\tList<CompoundProperty> getAdditionalProperties();\n\n\tCorrelationProperty getEmbeddingQualityProperty();\n\n\tEqualPositionProperty getEqualPosProperty();\n\n\tCompound getCompoundWithJmolIndex(int convertRowIndexToModel);\n\n\tint numDistinctValues(CompoundProperty p);\n\n\tpublic void addSelectionListener(SelectionListener l);\n\n\tpublic abstract static class SelectionListener\n\t{\n\t\tpublic void clusterActiveChanged(Cluster c)\n\t\t{\n\t\t}\n\n\t\tpublic void clusterWatchedChanged(Cluster c)\n\t\t{\n\t\t}\n\n\t\tpublic void compoundActiveChanged(Compound c[])\n\t\t{\n\t\t}\n\n\t\tpublic void compoundWatchedChanged(Compound c[])\n\t\t{\n\t\t}\n\t}\n\n\tboolean isBMBFRealEndpointDataset(boolean b);\n\n\tCompoundProperty addDistanceToCompoundFeature(Compound c);\n\n\tCompoundProperty addSALIFeatures(CompoundProperty c);\n\n\tvoid predict();\n\n\tvoid addPredictionFeature(CompoundProperty clazz, PredictionResult p);\n\n\tNumericProperty addLogFeature(NumericProperty p);\n\n\tpublic CompoundSelection getCompoundSelection(Compound[] c);\n\n\tboolean isRandomEmbedding();\n\n\tCompoundProperty getHighlightProperty();\n\n\tColor getHighlightColorText();\n\n\tDouble getFeatureDistance(int origIndex, int origIndex2);\n\n\tboolean isSkippingRedundantFeatures();\n\n\tboolean isBigDataMode();\n\n\tvoid computeAppDomain();\n\n\tboolean doCheSMappingWarningsExist();\n\n\tvoid showCheSMappingWarnings();\n\n}",
"public class Compound implements Zoomable, Comparable<Compound>, DoubleNameElement, SingleCompoundPropertyOwner\r\n{\r\n\tprivate BitSet bitSet;\r\n\tprivate BitSet dotModeHideBitSet;\r\n\tprivate BitSet dotModeDisplayBitSet;\r\n\r\n\tprivate int jmolIndex;\r\n\tprivate CompoundData compoundData;\r\n\r\n\tprivate Translucency translucency = Translucency.None;\r\n\tprivate String label = null;\r\n\tprivate boolean showHoverBox = false;\r\n\tprivate boolean showActiveBox = false;\r\n\tprivate String smarts = null;\r\n\r\n\tprivate HashMap<String, BitSet> smartsMatches;\r\n\r\n\tprivate String compoundColor;\r\n\tprivate String highlightColorString;\r\n\tprivate Color highlightColorText;\r\n\tprivate String lastHighlightColorString;\r\n\r\n\tprivate Vector3f spherePosition;\r\n\tprivate CompoundProperty highlightCompoundProperty;\r\n\tprivate Style style;\r\n\tprivate CompoundProperty descriptorProperty = null;\r\n\tprivate boolean sphereVisible;\r\n\tprivate boolean lastFeatureSphereVisible;\r\n\tprivate boolean visible = true;\r\n\tprivate boolean featureSortingEnabled = true;\r\n\r\n\tprivate float diameter = -1;\r\n\r\n\tpublic final Vector3f origCenter;\r\n\tpublic final Vector3f origDotPosition;\r\n\r\n\tpublic Compound(int jmolIndex, CompoundData compoundData)\r\n\t{\r\n\t\tthis.jmolIndex = jmolIndex;\r\n\t\tthis.compoundData = compoundData;\r\n\t\tif (View.instance != null)\r\n\t\t{\r\n\t\t\tbitSet = View.instance.getCompoundBitSet(getJmolIndex());\r\n\t\t\tdotModeHideBitSet = View.instance.getDotModeHideBitSet(bitSet);\r\n\t\t\tdotModeDisplayBitSet = View.instance.getDotModeDisplayBitSet(bitSet);\r\n\t\t\torigCenter = new Vector3f(View.instance.getAtomSetCenter(bitSet));\r\n\t\t\torigDotPosition = new Vector3f(View.instance.getAtomSetCenter(getDotModeDisplayBitSet()));\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\t//for export without graphics\r\n\t\t\torigCenter = null;\r\n\t\t\torigDotPosition = null;\r\n\t\t}\r\n\t\tsmartsMatches = new HashMap<String, BitSet>();\r\n\t\tsetDescriptor(ViewControler.COMPOUND_INDEX_PROPERTY);\r\n\t}\r\n\r\n\tpublic String getFormattedValue(CompoundProperty property)\r\n\t{\r\n\t\treturn compoundData.getFormattedValue(property);\r\n\t}\r\n\r\n\t@Override\r\n\tpublic String getStringValue(NominalProperty property)\r\n\t{\r\n\t\treturn compoundData.getStringValue(property);\r\n\t}\r\n\r\n\tpublic Double getDoubleValue(NumericProperty property)\r\n\t{\r\n\t\treturn compoundData.getDoubleValue(property);\r\n\t}\r\n\r\n\tpublic int getJmolIndex()\r\n\t{\r\n\t\treturn jmolIndex;\r\n\t}\r\n\r\n\tpublic int getOrigIndex()\r\n\t{\r\n\t\treturn compoundData.getOrigIndex();\r\n\t}\r\n\r\n\tpublic static class DisplayName implements Comparable<DisplayName>\r\n\t{\r\n\t\tString valDisplay;\r\n\t\t@SuppressWarnings(\"rawtypes\")\r\n\t\tComparable valCompare[];\r\n\t\tInteger compareIndex;\r\n\t\tString name;\r\n\r\n\t\tpublic String toString(boolean html, Color highlightColor)\r\n\t\t{\r\n\t\t\tStringBuffer b = new StringBuffer();\r\n\t\t\tif (html)\r\n\t\t\t\tb.append(StringEscapeUtils.escapeHtml4(name));\r\n\t\t\telse\r\n\t\t\t\tb.append(name);\r\n\t\t\tif (valDisplay != null && !valDisplay.equals(name))\r\n\t\t\t{\r\n\t\t\t\tif (html)\r\n\t\t\t\t{\r\n\t\t\t\t\tb.append(\": \");\r\n\t\t\t\t\tif (highlightColor != null)\r\n\t\t\t\t\t\tb.append(\"<font color='\" + ColorUtil.toHtml(highlightColor) + \"'>\");\r\n\t\t\t\t\tb.append(\"<i>\");\r\n\t\t\t\t\tb.append(StringEscapeUtils.escapeHtml4(valDisplay));\r\n\t\t\t\t\tb.append(\"</i>\");\r\n\t\t\t\t\tif (highlightColor != null)\r\n\t\t\t\t\t\tb.append(\"</font>\");\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tb.append(\": \");\r\n\t\t\t\t\tb.append(valDisplay);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\treturn b.toString();\r\n\t\t}\r\n\r\n\t\t@Override\r\n\t\tpublic int compareTo(DisplayName d)\r\n\t\t{\r\n\t\t\treturn compareTo(d, true);\r\n\t\t}\r\n\r\n\t\tpublic int compareTo(DisplayName d, boolean featureSortingEnabled)\r\n\t\t{\r\n\t\t\tif (featureSortingEnabled && valCompare != null)\r\n\t\t\t{\r\n\t\t\t\tfor (int j = 0; j < valCompare.length; j++)\r\n\t\t\t\t{\r\n\t\t\t\t\tint i = ObjectUtil.compare(valCompare[j], d.valCompare[j]);\r\n\t\t\t\t\tif (i != 0)\r\n\t\t\t\t\t\treturn i;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif (compareIndex != null)\r\n\t\t\t\treturn compareIndex.compareTo(d.compareIndex);\r\n\t\t\t// if nothing is selected, compound should be sorted according to identifier\r\n\t\t\treturn name.compareTo(d.name);\r\n\t\t}\r\n\t}\r\n\r\n\tprivate DisplayName displayName = new DisplayName();\r\n\r\n\t@Override\r\n\tpublic String toString()\r\n\t{\r\n\t\treturn getFirstName();\r\n\t}\r\n\r\n\tpublic String toStringWithValue()\r\n\t{\r\n\t\treturn displayName.toString(false, null);\r\n\t}\r\n\r\n\t@Override\r\n\tpublic String getFirstName()\r\n\t{\r\n\t\treturn displayName.name;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic String getSecondName()\r\n\t{\r\n\t\tif (ObjectUtil.equals(displayName.valDisplay, displayName.name))\r\n\t\t\treturn null;\r\n\t\telse\r\n\t\t\treturn displayName.valDisplay;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic int compareTo(Compound m)\r\n\t{\r\n\t\treturn displayName.compareTo(m.displayName, featureSortingEnabled);\r\n\t}\r\n\r\n\tpublic String getSmiles()\r\n\t{\r\n\t\treturn compoundData.getSmiles();\r\n\t}\r\n\r\n\tpublic Translucency getTranslucency()\r\n\t{\r\n\t\treturn translucency;\r\n\t}\r\n\r\n\tpublic void setTranslucency(Translucency translucency)\r\n\t{\r\n\t\tthis.translucency = translucency;\r\n\t}\r\n\r\n\tpublic String getLabel()\r\n\t{\r\n\t\treturn label;\r\n\t}\r\n\r\n\tpublic void setLabel(String label)\r\n\t{\r\n\t\tthis.label = label;\r\n\t}\r\n\r\n\tpublic boolean isShowHoverBox()\r\n\t{\r\n\t\treturn showHoverBox;\r\n\t}\r\n\r\n\tpublic void setShowHoverBox(boolean showBox)\r\n\t{\r\n\t\tthis.showHoverBox = showBox;\r\n\t}\r\n\r\n\tpublic boolean isShowActiveBox()\r\n\t{\r\n\t\treturn showActiveBox;\r\n\t}\r\n\r\n\tpublic void setShowActiveBox(boolean showBox)\r\n\t{\r\n\t\tthis.showActiveBox = showBox;\r\n\t}\r\n\r\n\tpublic String getHighlightedSmarts()\r\n\t{\r\n\t\treturn smarts;\r\n\t}\r\n\r\n\tpublic void setHighlightedSmarts(String smarts)\r\n\t{\r\n\t\tthis.smarts = smarts;\r\n\t}\r\n\r\n\tpublic void moveTo(Vector3f clusterPos)\r\n\t{\r\n\t\tVector3f center = new Vector3f(View.instance.getAtomSetCenter(getBitSet()));\r\n\t\tVector3f dest = new Vector3f(clusterPos);\r\n\t\tdest.sub(center);\r\n\t\tView.instance.setAtomCoordRelative(dest, getBitSet());\r\n\t}\r\n\r\n\tpublic Vector3f getPosition(boolean scaled)\r\n\t{\r\n\t\tVector3f v = new Vector3f(JitteringProvider.getPosition(compoundData));\r\n\t\tif (scaled)\r\n\t\t\tv.scale(ClusteringUtil.SCALE);\r\n\t\treturn v;\r\n\t}\r\n\r\n\tpublic Vector3f getPosition()\r\n\t{\r\n\t\treturn getPosition(true);\r\n\t}\r\n\r\n\tpublic BitSet getSmartsMatch(String smarts)\r\n\t{\r\n\t\t//compute match dynamically\r\n\t\tif (!smartsMatches.containsKey(smarts))\r\n\t\t{\r\n\t\t\tSettings.LOGGER.info(\"smarts-matching smarts: \" + smarts + \" smiles: \" + getSmiles());\r\n\t\t\tsmartsMatches.put(smarts, View.instance.getSmartsMatch(smarts, bitSet));\r\n\t\t}\r\n\t\treturn smartsMatches.get(smarts);\r\n\t}\r\n\r\n\tpublic void setCompoundColor(String colorString)\r\n\t{\r\n\t\tthis.compoundColor = colorString;\r\n\t}\r\n\r\n\tpublic String getCompoundColor()\r\n\t{\r\n\t\treturn compoundColor;\r\n\t}\r\n\r\n\tpublic void setHighlightColor(String colorString, Color colorText)\r\n\t{\r\n\t\tif (!ObjectUtil.equals(highlightColorString, colorString) || lastHighlightColorString == null)\r\n\t\t{\r\n\t\t\tthis.lastHighlightColorString = highlightColorString;\r\n\t\t\tthis.highlightColorString = colorString;\r\n\t\t\tthis.highlightColorText = colorText;\r\n\t\t}\r\n\t}\r\n\r\n\tpublic Color getHighlightColorText()\r\n\t{\r\n\t\treturn highlightColorText;\r\n\t}\r\n\r\n\tpublic String getHighlightColorString()\r\n\t{\r\n\t\treturn highlightColorString;\r\n\t}\r\n\r\n\tpublic String getLastHighlightColorString()\r\n\t{\r\n\t\treturn lastHighlightColorString;\r\n\t}\r\n\r\n\tpublic Vector3f getSpherePosition()\r\n\t{\r\n\t\treturn spherePosition;\r\n\t}\r\n\r\n\tpublic void setSpherePosition(Vector3f spherePosition)\r\n\t{\r\n\t\tthis.spherePosition = spherePosition;\r\n\t}\r\n\r\n\tpublic void setHighlightCompoundProperty(CompoundProperty highlightCompoundProperty)\r\n\t{\r\n\t\tif (this.highlightCompoundProperty != highlightCompoundProperty)\r\n\t\t{\r\n\t\t\tdisplayName.valDisplay = null;\r\n\t\t\tdisplayName.valCompare = null;\r\n\t\t\tif (highlightCompoundProperty != null)\r\n\t\t\t{\r\n\t\t\t\tif (highlightCompoundProperty instanceof NumericProperty)\r\n\t\t\t\t\tdisplayName.valCompare = new Double[] { getDoubleValue((NumericProperty) highlightCompoundProperty) };\r\n\t\t\t\telse\r\n\t\t\t\t\tdisplayName.valCompare = new String[] { getStringValue((NominalProperty) highlightCompoundProperty) };\r\n\t\t\t\tdisplayName.valDisplay = getFormattedValue(highlightCompoundProperty);\r\n\t\t\t}\r\n\t\t\tthis.highlightCompoundProperty = highlightCompoundProperty;\r\n\t\t\tlastHighlightColorString = null;\r\n\t\t}\r\n\t}\r\n\r\n\tpublic Object getHighlightCompoundProperty()\r\n\t{\r\n\t\treturn highlightCompoundProperty;\r\n\t}\r\n\r\n\tpublic void setStyle(Style style)\r\n\t{\r\n\t\tthis.style = style;\r\n\t}\r\n\r\n\tpublic Style getStyle()\r\n\t{\r\n\t\treturn style;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic Vector3f getCenter(boolean superimposed)\r\n\t{\r\n\t\treturn new Vector3f(View.instance.getAtomSetCenter(bitSet));\r\n\t}\r\n\r\n\t@Override\r\n\tpublic float getDiameter(boolean superimposed)\r\n\t{\r\n\t\treturn getDiameter();\r\n\t}\r\n\r\n\tpublic float getDiameter()\r\n\t{\r\n\t\tif (diameter == -1)\r\n\t\t\tdiameter = View.instance.getDiameter(bitSet);\r\n\t\treturn diameter;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic boolean isSuperimposed()\r\n\t{\r\n\t\treturn false;\r\n\t}\r\n\r\n\tpublic ImageIcon getIcon(boolean backgroundBlack, int width, int height, boolean translucent)\r\n\t{\r\n\t\treturn compoundData.getIcon(backgroundBlack, width, height, translucent);\r\n\t}\r\n\r\n\tpublic void setDescriptor(CompoundProperty descriptorProperty)\r\n\t{\r\n\t\tif (this.descriptorProperty != descriptorProperty)\r\n\t\t{\r\n\t\t\tdisplayName.compareIndex = null;\r\n\t\t\tif (descriptorProperty == ViewControler.COMPOUND_INDEX_PROPERTY)\r\n\t\t\t{\r\n\t\t\t\tdisplayName.compareIndex = getOrigIndex();\r\n\t\t\t\tdisplayName.name = \"Compound \" + (getOrigIndex() + 1);\r\n\t\t\t}\r\n\t\t\telse if (descriptorProperty == ViewControler.COMPOUND_SMILES_PROPERTY)\r\n\t\t\t\tdisplayName.name = getSmiles();\r\n\t\t\telse\r\n\t\t\t\tdisplayName.name = getFormattedValue(descriptorProperty);\r\n\t\t\tthis.descriptorProperty = descriptorProperty;\r\n\t\t}\r\n\t}\r\n\r\n\tpublic boolean isSphereVisible()\r\n\t{\r\n\t\treturn sphereVisible;\r\n\t}\r\n\r\n\tpublic void setSphereVisible(boolean sphereVisible)\r\n\t{\r\n\t\tthis.sphereVisible = sphereVisible;\r\n\t}\r\n\r\n\tpublic boolean isLastFeatureSphereVisible()\r\n\t{\r\n\t\treturn lastFeatureSphereVisible;\r\n\t}\r\n\r\n\tpublic void setLastFeatureSphereVisible(boolean s)\r\n\t{\r\n\t\tthis.lastFeatureSphereVisible = s;\r\n\t}\r\n\r\n\tpublic BitSet getBitSet()\r\n\t{\r\n\t\treturn bitSet;\r\n\t}\r\n\r\n\tpublic BitSet getDotModeHideBitSet()\r\n\t{\r\n\t\treturn dotModeHideBitSet;\r\n\t}\r\n\r\n\tpublic BitSet getDotModeDisplayBitSet()\r\n\t{\r\n\t\treturn dotModeDisplayBitSet;\r\n\t}\r\n\r\n\tpublic DisplayName getDisplayName()\r\n\t{\r\n\t\treturn displayName;\r\n\t}\r\n\r\n\tpublic boolean isVisible()\r\n\t{\r\n\t\treturn visible;\r\n\t}\r\n\r\n\tpublic void setVisible(boolean visible)\r\n\t{\r\n\t\tthis.visible = visible;\r\n\t}\r\n\r\n\tpublic void setFeatureSortingEnabled(boolean featureSortingEnabled)\r\n\t{\r\n\t\tthis.featureSortingEnabled = featureSortingEnabled;\r\n\t}\r\n\r\n\tpublic CompoundData getCompoundData()\r\n\t{\r\n\t\treturn compoundData;\r\n\t}\r\n}\r",
"public class CompoundFilterImpl implements CompoundFilter\n{\n\tprivate String desc;\n\tprivate List<Compound> compounds;\n\n\tpublic CompoundFilterImpl(Clustering clustering, List<Compound> compounds, String additionalDesc)\n\t{\n\t\tthis.compounds = compounds;\n\t\tdesc = \"Show \" + compounds.size() + \"/\" + clustering.getNumUnfilteredCompounds(false) + \" compounds\";\n\t\tif (additionalDesc != null)\n\t\t\tdesc += \" (\" + additionalDesc + \")\";\n\t}\n\n\tpublic static CompoundFilterImpl combine(Clustering clustering, CompoundFilter filter1, CompoundFilter filter2)\n\t{\n\t\treturn new CompoundFilterImpl(clustering, ListUtil.cut2(((CompoundFilterImpl) filter1).compounds,\n\t\t\t\t((CompoundFilterImpl) filter2).compounds), null);\n\t}\n\n\tpublic String toString()\n\t{\n\t\treturn desc;\n\t}\n\n\tpublic boolean accept(Compound c)\n\t{\n\t\treturn compounds.contains(c);\n\t}\n\n}",
"public abstract static class SelectionListener\n{\n\tpublic void clusterActiveChanged(Cluster c)\n\t{\n\t}\n\n\tpublic void clusterWatchedChanged(Cluster c)\n\t{\n\t}\n\n\tpublic void compoundActiveChanged(Compound c[])\n\t{\n\t}\n\n\tpublic void compoundWatchedChanged(Compound c[])\n\t{\n\t}\n}",
"public class ComponentSize\n{\n\tpublic static IntegerProperty ICON_2D = new IntegerProperty(\"Compound image\", 15, 5, 40);\n\tpublic static IntegerProperty ICON_2D_DOTS = new IntegerProperty(\"Compound image (style 'Dots')\", 20, 5, 40);\n\tpublic static IntegerProperty CLUSTER_LIST = new IntegerProperty(\"Cluster list\", 15, 5, 40);\n\tpublic static IntegerProperty COMPOUND_LIST = new IntegerProperty(\"Compound list\", 20, 5, 40);\n\tpublic static IntegerProperty INFO_TABLE = new IntegerProperty(\"Info table\", 20, 5, 40);\n\n\tpublic static IntegerProperty[] MAX_WIDTH = new IntegerProperty[] { CLUSTER_LIST, COMPOUND_LIST, ICON_2D,\n\t\t\tICON_2D_DOTS, INFO_TABLE };\n\n\tstatic\n\t{\n\t\tICON_2D.setHighlightColor(Color.YELLOW);\n\t\tICON_2D_DOTS.setHighlightColor(Color.YELLOW);\n\t\tINFO_TABLE.setHighlightColor(Color.CYAN);\n\t\tCLUSTER_LIST.setHighlightColor(Color.GREEN);\n\t\tCOMPOUND_LIST.setHighlightColor(Color.MAGENTA);\n\t}\n\n}",
"public interface GUIControler extends Blockable\r\n{\r\n\tpublic void updateTitle(Clustering c);\r\n\r\n\tpublic void setFullScreen(boolean b);\r\n\r\n\tpublic boolean isFullScreen();\r\n\r\n\tpublic JPopupMenu getPopup();\r\n\r\n\tpublic void showMessage(String msg);\r\n\r\n\t//\tpublic void handleKeyEvent(KeyEvent e);\r\n\r\n\tpublic static final String PROPERTY_FULLSCREEN_CHANGED = \"PROPERTY_FULLSCREEN_CHANGED\";\r\n\tpublic static final String PROPERTY_VIEWER_SIZE_CHANGED = \"PROPERTY_VIEWER_SIZE_CHANGED\";\r\n\r\n\tpublic void addPropertyChangeListener(PropertyChangeListener l);\r\n\r\n\tpublic int getComponentMaxWidth(double pct);\r\n\r\n\tpublic int getComponentMaxHeight(double pct);\r\n\r\n\tpublic void blockMessages();\r\n\r\n\tpublic void unblockMessages();\r\n\r\n\tpublic boolean isVisible();\r\n\r\n\tpublic void setSelectedString(String s);\r\n\r\n\tpublic String getSelectedString();\r\n\r\n\tpublic void setAccentuateSizeComponents(boolean b);\r\n\r\n\tpublic void registerSizeComponent(Property p, JComponent c);\r\n\r\n\tpublic boolean isAccentuateComponents();\r\n\r\n}\r",
"public interface ViewControler\r\n{\r\n\tpublic enum Style\r\n\t{\r\n\t\twireframe, ballsAndSticks, dots\r\n\t}\r\n\r\n\tpublic enum DisguiseMode\r\n\t{\r\n\t\tsolid, translucent, invisible\r\n\t}\r\n\r\n\tpublic static enum HighlightMode\r\n\t{\r\n\t\tColorCompounds, Spheres;\r\n\t}\r\n\r\n\tpublic static final ColorGradient DEFAULT_COLOR_GRADIENT = new ColorGradient(\r\n\t\t\tCompoundPropertyUtil.getHighValueColor(), Color.WHITE, CompoundPropertyUtil.getLowValueColor());\r\n\r\n\tpublic Color getHighlightColor(CompoundPropertyOwner m, CompoundProperty p, boolean textColor);\r\n\r\n\tpublic Color getHighlightColor(CompoundPropertyOwner m, CompoundProperty p, boolean textColor,\r\n\t\t\tboolean blackBackground);\r\n\r\n\tpublic DisguiseMode getDisguiseUnHovered();\r\n\r\n\tpublic DisguiseMode getDisguiseUnZoomed();\r\n\r\n\tpublic void setDisguiseUnHovered(DisguiseMode hide);\r\n\r\n\tpublic void setDisguiseUnZoomed(DisguiseMode hide);\r\n\r\n\tpublic void resetView();\r\n\r\n\tpublic boolean isSpinEnabled();\r\n\r\n\tpublic void setSpinEnabled(boolean spinEnabled);\r\n\r\n\tpublic boolean canChangeCompoundSize(boolean larger);\r\n\r\n\tpublic void changeCompoundSize(boolean larger);\r\n\r\n\tpublic int getCompoundSize();\r\n\r\n\tpublic int getCompoundSizeMax();\r\n\r\n\tpublic void setCompoundSize(int compoundSize);\r\n\r\n\tpublic HighlightMode getHighlightMode();\r\n\r\n\tpublic void setHighlightMode(HighlightMode mode);\r\n\r\n\tpublic void setSphereSize(double size);\r\n\r\n\tpublic void setSphereTranslucency(double translucency);\r\n\r\n\tpublic Style getStyle();\r\n\r\n\tpublic void setStyle(Style style);\r\n\r\n\tpublic HashMap<String, Highlighter[]> getHighlighters();\r\n\r\n\tpublic void setHighlighter(Highlighter highlighter);\r\n\r\n\tpublic void setHighlighter(Highlighter highlighter, boolean showMessage);\r\n\r\n\tpublic void setHighlighter(CompoundProperty prop);\r\n\r\n\tpublic void setHighlighter(SubstructureSmartsType type);\r\n\r\n\tpublic Highlighter getHighlighter();\r\n\r\n\tpublic Highlighter getHighlighter(SubstructureSmartsType type);\r\n\r\n\tpublic Highlighter getHighlighter(CompoundProperty p);\r\n\r\n\tpublic CompoundProperty getHighlightedProperty();\r\n\r\n\tpublic void setSuperimpose(boolean superimpose);\r\n\r\n\tpublic boolean isSuperimpose();\r\n\r\n\tpublic boolean isAllClustersSpreadable();\r\n\r\n\tpublic boolean isSingleClusterSpreadable();\r\n\r\n\tpublic boolean isHideHydrogens();\r\n\r\n\tpublic void setHideHydrogens(boolean b);\r\n\r\n\tpublic static final String PROPERTY_HIGHLIGHT_CHANGED = \"propertyHighlightChanged\";\r\n\tpublic static final String PROPERTY_SHOW_HYDROGENS = \"propertyShowHydrogens\";\r\n\tpublic static final String PROPERTY_NEW_HIGHLIGHTERS = \"propertyNewHighlighters\";\r\n\tpublic static final String PROPERTY_DENSITY_CHANGED = \"propertyDensityChanged\";\r\n\tpublic static final String PROPERTY_SUPERIMPOSE_CHANGED = \"propertySuperimposeChanged\";\r\n\tpublic static final String PROPERTY_DISGUISE_CHANGED = \"propertyDisguiseChanged\";\r\n\tpublic static final String PROPERTY_SPIN_CHANGED = \"propertySpinChanged\";\r\n\tpublic static final String PROPERTY_BACKGROUND_CHANGED = \"propertyBackgroundChanged\";\r\n\tpublic static final String PROPERTY_FONT_SIZE_CHANGED = \"propertyFontSizeChanged\";\r\n\tpublic static final String PROPERTY_COMPOUND_DESCRIPTOR_CHANGED = \"propertyCompoundDescriptorChanged\";\r\n\tpublic static final String PROPERTY_HIGHLIGHT_MODE_CHANGED = \"propertyHighlightModeChanged\";\r\n\tpublic static final String PROPERTY_HIGHLIGHT_COLORS_CHANGED = \"propertyHighlightColorsChanged\";\r\n\tpublic static final String PROPERTY_ANTIALIAS_CHANGED = \"propertyAntialiasChanged\";\r\n\tpublic static final String PROPERTY_HIGHLIGHT_LAST_FEATURE = \"propertyHighlightLastFeature\";\r\n\tpublic static final String PROPERTY_STYLE_CHANGED = \"propertyStyleChanged\";\r\n\tpublic static final String PROPERTY_FEATURE_FILTER_CHANGED = \"propertyFeatureFilterChanged\";\r\n\tpublic static final String PROPERTY_FEATURE_SORTING_CHANGED = \"propertyFeatureSortingChanged\";\r\n\tpublic static final String PROPERTY_COMPOUND_FILTER_CHANGED = \"propertyCompoundFilterChanged\";\r\n\tpublic static final String PROPERTY_SINGLE_COMPOUND_SELECTION_ENABLED = \"propertySingleCompoundSelectionEnabled\";\r\n\tpublic static final String PROPERTY_JITTERING_CHANGED = \"propertyJitteringChanged\";\r\n\r\n\tpublic boolean isHighlighterLabelsVisible();\r\n\r\n\tpublic void setHighlighterLabelsVisible(boolean selected);\r\n\r\n\tpublic static enum HighlightSorting\r\n\t{\r\n\t\tMax, Median, Min;\r\n\t}\r\n\r\n\tpublic void setHighlightSorting(HighlightSorting sorting);\r\n\r\n\tpublic HighlightSorting getHighlightSorting();\r\n\r\n\tpublic void addViewListener(PropertyChangeListener l);\r\n\r\n\tpublic boolean isBlackgroundBlack();\r\n\r\n\tpublic void setBackgroundBlack(boolean backgroudBlack);\r\n\r\n\tpublic void increaseFontSize(boolean increase);\r\n\r\n\tpublic void setFontSize(int fontsize);\r\n\r\n\tpublic int getFontSize();\r\n\r\n\tstatic final CompoundProperty COMPOUND_INDEX_PROPERTY = new DefaultNominalProperty(null, \"Compound Index\",\r\n\t\t\t\"no-desc\");\r\n\tstatic final CompoundProperty COMPOUND_SMILES_PROPERTY = new DefaultNominalProperty(null, \"Compound SMILES\",\r\n\t\t\t\"no-desc\");\r\n\r\n\tpublic void setCompoundDescriptor(CompoundProperty prop);\r\n\r\n\tpublic CompoundProperty getCompoundDescriptor();\r\n\r\n\tpublic void addIgnoreMouseMovementComponents(JComponent ignore);\r\n\r\n\tpublic void updateMouseSelection(boolean buttonDown);\r\n\r\n\tpublic void setHighlightColors(ColorGradient g, NumericProperty props[]);\r\n\r\n\tpublic void setHighlightColors(Color g[], NominalProperty props[]);\r\n\r\n\tpublic void setClusterColors(Color[] sequence);\r\n\r\n\tvoid setHighlightMatchColors(Color[] colors);\r\n\r\n\tpublic void setSelectLastSelectedHighlighter();\r\n\r\n\tpublic boolean isAntialiasEnabled();\r\n\r\n\tpublic void setAntialiasEnabled(boolean b);\r\n\r\n\tpublic void setHighlightLastFeatureEnabled(boolean b);\r\n\r\n\tpublic boolean isHighlightLastFeatureEnabled();\r\n\r\n\tpublic void increaseSpinSpeed(boolean increase);\r\n\r\n\tpublic static enum FeatureFilter\r\n\t{\r\n\t\tNone, NotSelectedForMapping, SelectedForMapping, UsedForMapping, Filled, Real, Endpoints;\r\n\r\n\t\tpublic static FeatureFilter[] validValues(Clustering clustering)\r\n\t\t{\r\n\t\t\tFeatureFilter f[] = new FeatureFilter[] { None, NotSelectedForMapping, SelectedForMapping };\r\n\t\t\tif (clustering.isSkippingRedundantFeatures())\r\n\t\t\t\tf = ArrayUtil.concat(f, new FeatureFilter[] { UsedForMapping });\r\n\t\t\tif (clustering.isBMBFRealEndpointDataset(true))\r\n\t\t\t\tf = ArrayUtil.concat(f, new FeatureFilter[] { Filled, Real, Endpoints });\r\n\t\t\telse if (clustering.isBMBFRealEndpointDataset(false))\r\n\t\t\t\tf = ArrayUtil.concat(f, new FeatureFilter[] { Real, Endpoints });\r\n\t\t\treturn f;\r\n\t\t}\r\n\r\n\t\tpublic String niceString()\r\n\t\t{\r\n\t\t\tswitch (this)\r\n\t\t\t{\r\n\t\t\t\tcase None:\r\n\t\t\t\t\treturn \"Show all features (no filter)\";\r\n\t\t\t\tcase NotSelectedForMapping:\r\n\t\t\t\t\treturn \"Show features NOT selected for mapping\";\r\n\t\t\t\tcase SelectedForMapping:\r\n\t\t\t\t\treturn \"Show features selected for mapping\";\r\n\t\t\t\tcase UsedForMapping:\r\n\t\t\t\t\treturn \"Show features used for mapping (no redundant/single-valued features)\";\r\n\t\t\t\tcase Filled:\r\n\t\t\t\t\treturn \"Show '_filled' features\";\r\n\t\t\t\tcase Real:\r\n\t\t\t\t\treturn \"Show '_real' features\";\r\n\t\t\t\tcase Endpoints:\r\n\t\t\t\t\treturn \"Show endpoint features\";\r\n\t\t\t}\r\n\t\t\tthrow new IllegalStateException();\r\n\t\t}\r\n\t}\r\n\r\n\tpublic void setFeatureFilter(FeatureFilter filter);\r\n\r\n\tpublic FeatureFilter getFeatureFilter();\r\n\r\n\tpublic boolean isFeatureSortingEnabled();\r\n\r\n\tpublic void setFeatureSortingEnabled(boolean b);\r\n\r\n\tpublic boolean isShowClusteringPropsEnabled();\r\n\r\n\tpublic void showSortFilterDialog();\r\n\r\n\tpublic void setSingleCompoundSelection(boolean b);\r\n\r\n\tpublic boolean isSingleCompoundSelection();\r\n\r\n\tpublic void doMouseMoveWatchUpdates(Runnable runnable);\r\n\r\n\tpublic void clearMouseMoveWatchUpdates(boolean clearWatched);\r\n\r\n\tpublic NominalColoring getNominalColoring();\r\n\r\n\tpublic void setNominalColoring(NominalColoring nominalColoringValue);\r\n\r\n\tpublic int getJitteringLevel();\r\n\r\n\tpublic void setJitteringLevel(int level);\r\n\r\n\tpublic boolean canJitter();\r\n\r\n\t// to remove\r\n\r\n\t//\tpublic void setZoomToSingleActiveCompounds(boolean b);\r\n\r\n\t//\tpublic void setCompoundFilter(CompoundFilter filter, boolean animate);\r\n\t//\r\n\t//\tpublic void useSelectedCompoundsAsFilter(String filterDescription, boolean animate);\r\n\t//\r\n\t//\tpublic CompoundFilter getCompoundFilter();\r\n}\r"
] | import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Graphics;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import javax.swing.Icon;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import org.chesmapper.map.data.DistanceUtil;
import org.chesmapper.map.dataInterface.CompoundData;
import org.chesmapper.map.dataInterface.CompoundProperty;
import org.chesmapper.map.dataInterface.NominalProperty;
import org.chesmapper.map.main.ScreenSetup;
import org.chesmapper.map.main.Settings;
import org.chesmapper.view.cluster.Cluster;
import org.chesmapper.view.cluster.ClusterController;
import org.chesmapper.view.cluster.Clustering;
import org.chesmapper.view.cluster.Compound;
import org.chesmapper.view.cluster.CompoundFilterImpl;
import org.chesmapper.view.cluster.Clustering.SelectionListener;
import org.chesmapper.view.gui.ComponentSize;
import org.chesmapper.view.gui.GUIControler;
import org.chesmapper.view.gui.ViewControler;
import org.mg.javalib.dist.NonNullSimilartiy;
import org.mg.javalib.dist.SimilarityMeasure;
import org.mg.javalib.dist.SimpleMatchingSimilartiy;
import org.mg.javalib.dist.TanimotoSimilartiy;
import org.mg.javalib.gui.BlockableFrame;
import org.mg.javalib.util.ArrayUtil;
import org.mg.javalib.util.CountedSet;
import org.mg.javalib.util.DoubleArraySummary;
import org.mg.javalib.util.ListUtil;
import org.mg.javalib.util.ObjectUtil;
import org.mg.javalib.util.StringUtil;
import org.mg.javalib.util.SwingUtil; | package org.chesmapper.view.gui.table;
public class TreeView extends BlockableFrame
{
private static int ICON_W = 50;
private static int ICON_H = 50;
| protected ViewControler viewControler; | 8 |
jiangqqlmj/Android-Universal-Image-Loader-Modify | sample/src/main/java/com/nostra13/universalimageloader/sample/fragment/ImageListFragment.java | [
"public final class DisplayImageOptions {\n /*图片正在加载过程中的图片*/\n\tprivate final int imageResOnLoading;\n\t/*图片地址为空,显示的图片*/\n\tprivate final int imageResForEmptyUri;\n\t/*图片加载失败,显示的图片*/\n\tprivate final int imageResOnFail;\n\t/*图片资源 正在加载的图片*/\n\tprivate final Drawable imageOnLoading;\n\t/*图片资源 图片地址为空情况*/\n\tprivate final Drawable imageForEmptyUri;\n\t/*图片资源 图片下载失败情况*/\n\tprivate final Drawable imageOnFail;\n\t/*标志在加载之前是否需要重置view*/\n\tprivate final boolean resetViewBeforeLoading;\n\t/*标志是否开启内存缓存*/\n\tprivate final boolean cacheInMemory;\n\t/*标志是否要开启本地文件系统缓存*/\n\tprivate final boolean cacheOnDisk;\n\tprivate final ImageScaleType imageScaleType;\n\t/*图片解码参数配置*/\n\tprivate final Options decodingOptions;\n\t/*在图片记载之前延迟的时间*/\n\tprivate final int delayBeforeLoading;\n\t/*标志是否需要exif参数*/\n\tprivate final boolean considerExifParams;\n\tprivate final Object extraForDownloader;\n\tprivate final BitmapProcessor preProcessor;\n\tprivate final BitmapProcessor postProcessor;\n\tprivate final BitmapDisplayer displayer;\n\tprivate final Handler handler;\n\t//配置是否为同步加载 \n\tprivate final boolean isSyncLoading;\n\n\t/**\n\t * 进行初始化图片显示配置 传入配置项目构建器\n\t * @param builder\n\t */\n\tprivate DisplayImageOptions(Builder builder) {\n\t\timageResOnLoading = builder.imageResOnLoading;\n\t\timageResForEmptyUri = builder.imageResForEmptyUri;\n\t\timageResOnFail = builder.imageResOnFail;\n\t\timageOnLoading = builder.imageOnLoading;\n\t\timageForEmptyUri = builder.imageForEmptyUri;\n\t\timageOnFail = builder.imageOnFail;\n\t\tresetViewBeforeLoading = builder.resetViewBeforeLoading;\n\t\tcacheInMemory = builder.cacheInMemory;\n\t\tcacheOnDisk = builder.cacheOnDisk;\n\t\timageScaleType = builder.imageScaleType;\n\t\tdecodingOptions = builder.decodingOptions;\n\t\tdelayBeforeLoading = builder.delayBeforeLoading;\n\t\tconsiderExifParams = builder.considerExifParams;\n\t\textraForDownloader = builder.extraForDownloader;\n\t\tpreProcessor = builder.preProcessor;\n\t\tpostProcessor = builder.postProcessor;\n\t\tdisplayer = builder.displayer;\n\t\thandler = builder.handler;\n\t\tisSyncLoading = builder.isSyncLoading;\n\t}\n\n\t/**\n\t * 获取是否需要在加载过程中显示图片\n\t * @return\n\t */\n\tpublic boolean shouldShowImageOnLoading() {\n\t\treturn imageOnLoading != null || imageResOnLoading != 0;\n\t}\n\n\t/**\n\t * 获取是否当图片地址为空得时候显示图片\n\t * @return\n\t */\n\tpublic boolean shouldShowImageForEmptyUri() {\n\t\treturn imageForEmptyUri != null || imageResForEmptyUri != 0;\n\t}\n\n\t/**\n\t * 获取是否当图片下载失败的时候显示图片\n\t * @return\n\t */\n\tpublic boolean shouldShowImageOnFail() {\n\t\treturn imageOnFail != null || imageResOnFail != 0;\n\t}\n\n\tpublic boolean shouldPreProcess() {\n\t\treturn preProcessor != null;\n\t}\n\n\tpublic boolean shouldPostProcess() {\n\t\treturn postProcessor != null;\n\t}\n\n\tpublic boolean shouldDelayBeforeLoading() {\n\t\treturn delayBeforeLoading > 0;\n\t}\n\n\tpublic Drawable getImageOnLoading(Resources res) {\n\t\treturn imageResOnLoading != 0 ? res.getDrawable(imageResOnLoading) : imageOnLoading;\n\t}\n\n\tpublic Drawable getImageForEmptyUri(Resources res) {\n\t\treturn imageResForEmptyUri != 0 ? res.getDrawable(imageResForEmptyUri) : imageForEmptyUri;\n\t}\n\n\tpublic Drawable getImageOnFail(Resources res) {\n\t\treturn imageResOnFail != 0 ? res.getDrawable(imageResOnFail) : imageOnFail;\n\t}\n\n\tpublic boolean isResetViewBeforeLoading() {\n\t\treturn resetViewBeforeLoading;\n\t}\n\n\tpublic boolean isCacheInMemory() {\n\t\treturn cacheInMemory;\n\t}\n\n\tpublic boolean isCacheOnDisk() {\n\t\treturn cacheOnDisk;\n\t}\n\n\tpublic ImageScaleType getImageScaleType() {\n\t\treturn imageScaleType;\n\t}\n\n\tpublic Options getDecodingOptions() {\n\t\treturn decodingOptions;\n\t}\n\n\tpublic int getDelayBeforeLoading() {\n\t\treturn delayBeforeLoading;\n\t}\n\n\tpublic boolean isConsiderExifParams() {\n\t\treturn considerExifParams;\n\t}\n\n\tpublic Object getExtraForDownloader() {\n\t\treturn extraForDownloader;\n\t}\n\n\tpublic BitmapProcessor getPreProcessor() {\n\t\treturn preProcessor;\n\t}\n\n\tpublic BitmapProcessor getPostProcessor() {\n\t\treturn postProcessor;\n\t}\n\n\tpublic BitmapDisplayer getDisplayer() {\n\t\treturn displayer;\n\t}\n\n\tpublic Handler getHandler() {\n\t\treturn handler;\n\t}\n\n\tboolean isSyncLoading() {\n\t\treturn isSyncLoading;\n\t}\n\n\t/**\n\t * Builder for {@link DisplayImageOptions}\n\t *\n\t * @author Sergey Tarasevich (nostra13[at]gmail[dot]com)\n\t */\n\tpublic static class Builder {\n\t\t//以下各大属性注释和前面的全局变量注释一样,这边这边加入了默认值\n\t\tprivate int imageResOnLoading = 0;\n\t\tprivate int imageResForEmptyUri = 0;\n\t\tprivate int imageResOnFail = 0;\n\t\tprivate Drawable imageOnLoading = null;\n\t\tprivate Drawable imageForEmptyUri = null;\n\t\tprivate Drawable imageOnFail = null;\n\t\tprivate boolean resetViewBeforeLoading = false;\n\t\tprivate boolean cacheInMemory = false;\n\t\tprivate boolean cacheOnDisk = false;\n\t\tprivate ImageScaleType imageScaleType = ImageScaleType.IN_SAMPLE_POWER_OF_2;\n\t\tprivate Options decodingOptions = new Options();\n\t\tprivate int delayBeforeLoading = 0;\n\t\tprivate boolean considerExifParams = false;\n\t\tprivate Object extraForDownloader = null;\n\t\tprivate BitmapProcessor preProcessor = null;\n\t\tprivate BitmapProcessor postProcessor = null;\n\t\tprivate BitmapDisplayer displayer = DefaultConfigurationFactory.createBitmapDisplayer();\n\t\tprivate Handler handler = null;\n\t\t//是否为同步加载 默认为否\n\t\tprivate boolean isSyncLoading = false;\n\n\t\t/**\n\t\t * Stub image will be displayed in {@link com.nostra13.universalimageloader.core.imageaware.ImageAware\n\t\t * image aware view} during image loading\n\t\t *\n\t\t * @param imageRes Stub image resource\n\t\t * @deprecated Use {@link #showImageOnLoading(int)} instead\n\t\t */\n\t\t@Deprecated\n\t\tpublic Builder showStubImage(int imageRes) {\n\t\t\timageResOnLoading = imageRes;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Incoming image will be displayed in {@link com.nostra13.universalimageloader.core.imageaware.ImageAware\n\t\t * image aware view} during image loading\n\t\t *\n\t\t * @param imageRes Image resource\n\t\t */\n\t\tpublic Builder showImageOnLoading(int imageRes) {\n\t\t\timageResOnLoading = imageRes;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Incoming drawable will be displayed in {@link com.nostra13.universalimageloader.core.imageaware.ImageAware\n\t\t * image aware view} during image loading.\n\t\t * This option will be ignored if {@link DisplayImageOptions.Builder#showImageOnLoading(int)} is set.\n\t\t */\n\t\tpublic Builder showImageOnLoading(Drawable drawable) {\n\t\t\timageOnLoading = drawable;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Incoming image will be displayed in {@link com.nostra13.universalimageloader.core.imageaware.ImageAware\n\t\t * image aware view} if empty URI (null or empty\n\t\t * string) will be passed to <b>ImageLoader.displayImage(...)</b> method.\n\t\t *\n\t\t * @param imageRes Image resource\n\t\t */\n\t\tpublic Builder showImageForEmptyUri(int imageRes) {\n\t\t\timageResForEmptyUri = imageRes;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Incoming drawable will be displayed in {@link com.nostra13.universalimageloader.core.imageaware.ImageAware\n\t\t * image aware view} if empty URI (null or empty\n\t\t * string) will be passed to <b>ImageLoader.displayImage(...)</b> method.\n\t\t * This option will be ignored if {@link DisplayImageOptions.Builder#showImageForEmptyUri(int)} is set.\n\t\t */\n\t\tpublic Builder showImageForEmptyUri(Drawable drawable) {\n\t\t\timageForEmptyUri = drawable;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Incoming image will be displayed in {@link com.nostra13.universalimageloader.core.imageaware.ImageAware\n\t\t * image aware view} if some error occurs during\n\t\t * requested image loading/decoding.\n\t\t *\n\t\t * @param imageRes Image resource\n\t\t */\n\t\tpublic Builder showImageOnFail(int imageRes) {\n\t\t\timageResOnFail = imageRes;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Incoming drawable will be displayed in {@link com.nostra13.universalimageloader.core.imageaware.ImageAware\n\t\t * image aware view} if some error occurs during\n\t\t * requested image loading/decoding.\n\t\t * This option will be ignored if {@link DisplayImageOptions.Builder#showImageOnFail(int)} is set.\n\t\t */\n\t\tpublic Builder showImageOnFail(Drawable drawable) {\n\t\t\timageOnFail = drawable;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * {@link com.nostra13.universalimageloader.core.imageaware.ImageAware\n\t\t * image aware view} will be reset (set <b>null</b>) before image loading start\n\t\t *\n\t\t * @deprecated Use {@link #resetViewBeforeLoading(boolean) resetViewBeforeLoading(true)} instead\n\t\t */\n\t\tpublic Builder resetViewBeforeLoading() {\n\t\t\tresetViewBeforeLoading = true;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Sets whether {@link com.nostra13.universalimageloader.core.imageaware.ImageAware\n\t\t * image aware view} will be reset (set <b>null</b>) before image loading start\n\t\t */\n\t\tpublic Builder resetViewBeforeLoading(boolean resetViewBeforeLoading) {\n\t\t\tthis.resetViewBeforeLoading = resetViewBeforeLoading;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Loaded image will be cached in memory\n\t\t *\n\t\t * @deprecated Use {@link #cacheInMemory(boolean) cacheInMemory(true)} instead\n\t\t */\n\t\t@Deprecated\n\t\tpublic Builder cacheInMemory() {\n\t\t\tcacheInMemory = true;\n\t\t\treturn this;\n\t\t}\n\n\t\t/** Sets whether loaded image will be cached in memory */\n\t\tpublic Builder cacheInMemory(boolean cacheInMemory) {\n\t\t\tthis.cacheInMemory = cacheInMemory;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Loaded image will be cached on disk\n\t\t *\n\t\t * @deprecated Use {@link #cacheOnDisk(boolean) cacheOnDisk(true)} instead\n\t\t */\n\t\t@Deprecated\n\t\tpublic Builder cacheOnDisc() {\n\t\t\treturn cacheOnDisk(true);\n\t\t}\n\n\t\t/**\n\t\t * Sets whether loaded image will be cached on disk\n\t\t *\n\t\t * @deprecated Use {@link #cacheOnDisk(boolean)} instead\n\t\t */\n\t\t@Deprecated\n\t\tpublic Builder cacheOnDisc(boolean cacheOnDisk) {\n\t\t\treturn cacheOnDisk(cacheOnDisk);\n\t\t}\n\n\t\t/** Sets whether loaded image will be cached on disk */\n\t\tpublic Builder cacheOnDisk(boolean cacheOnDisk) {\n\t\t\tthis.cacheOnDisk = cacheOnDisk;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Sets {@linkplain ImageScaleType scale type} for decoding image. This parameter is used while define scale\n\t\t * size for decoding image to Bitmap. Default value - {@link ImageScaleType#IN_SAMPLE_POWER_OF_2}\n\t\t */\n\t\tpublic Builder imageScaleType(ImageScaleType imageScaleType) {\n\t\t\tthis.imageScaleType = imageScaleType;\n\t\t\treturn this;\n\t\t}\n\n\t\t/** Sets {@link Bitmap.Config bitmap config} for image decoding. Default value - {@link Bitmap.Config#ARGB_8888} */\n\t\tpublic Builder bitmapConfig(Bitmap.Config bitmapConfig) {\n\t\t\tif (bitmapConfig == null) throw new IllegalArgumentException(\"bitmapConfig can't be null\");\n\t\t\tdecodingOptions.inPreferredConfig = bitmapConfig;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Sets options for image decoding.<br />\n\t\t * <b>NOTE:</b> {@link Options#inSampleSize} of incoming options will <b>NOT</b> be considered. Library\n\t\t * calculate the most appropriate sample size itself according yo {@link #imageScaleType(ImageScaleType)}\n\t\t * options.<br />\n\t\t * <b>NOTE:</b> This option overlaps {@link #bitmapConfig(android.graphics.Bitmap.Config) bitmapConfig()}\n\t\t * option.\n\t\t */\n\t\tpublic Builder decodingOptions(Options decodingOptions) {\n\t\t\tif (decodingOptions == null) throw new IllegalArgumentException(\"decodingOptions can't be null\");\n\t\t\tthis.decodingOptions = decodingOptions;\n\t\t\treturn this;\n\t\t}\n\n\t\t/** Sets delay time before starting loading task. Default - no delay. */\n\t\tpublic Builder delayBeforeLoading(int delayInMillis) {\n\t\t\tthis.delayBeforeLoading = delayInMillis;\n\t\t\treturn this;\n\t\t}\n\n\t\t/** Sets auxiliary object which will be passed to {@link ImageDownloader#getStream(String, Object)} */\n\t\tpublic Builder extraForDownloader(Object extra) {\n\t\t\tthis.extraForDownloader = extra;\n\t\t\treturn this;\n\t\t}\n\n\t\t/** Sets whether ImageLoader will consider EXIF parameters of JPEG image (rotate, flip) */\n\t\tpublic Builder considerExifParams(boolean considerExifParams) {\n\t\t\tthis.considerExifParams = considerExifParams;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Sets bitmap processor which will be process bitmaps before they will be cached in memory. So memory cache\n\t\t * will contain bitmap processed by incoming preProcessor.<br />\n\t\t * Image will be pre-processed even if caching in memory is disabled.\n\t\t */\n\t\tpublic Builder preProcessor(BitmapProcessor preProcessor) {\n\t\t\tthis.preProcessor = preProcessor;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Sets bitmap processor which will be process bitmaps before they will be displayed in\n\t\t * {@link com.nostra13.universalimageloader.core.imageaware.ImageAware image aware view} but\n\t\t * after they'll have been saved in memory cache.\n\t\t */\n\t\tpublic Builder postProcessor(BitmapProcessor postProcessor) {\n\t\t\tthis.postProcessor = postProcessor;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Sets custom {@link BitmapDisplayer displayer} for image loading task. Default value -\n\t\t * {@link DefaultConfigurationFactory#createBitmapDisplayer()}\n\t\t */\n\t\tpublic Builder displayer(BitmapDisplayer displayer) {\n\t\t\tif (displayer == null) throw new IllegalArgumentException(\"displayer can't be null\");\n\t\t\tthis.displayer = displayer;\n\t\t\treturn this;\n\t\t}\n\n\t\tBuilder syncLoading(boolean isSyncLoading) {\n\t\t\tthis.isSyncLoading = isSyncLoading;\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * Sets custom {@linkplain Handler handler} for displaying images and firing {@linkplain ImageLoadingListener\n\t\t * listener} events.\n\t\t */\n\t\tpublic Builder handler(Handler handler) {\n\t\t\tthis.handler = handler;\n\t\t\treturn this;\n\t\t}\n\n\t\t/** Sets all options equal to incoming options */\n\t\tpublic Builder cloneFrom(DisplayImageOptions options) {\n\t\t\timageResOnLoading = options.imageResOnLoading;\n\t\t\timageResForEmptyUri = options.imageResForEmptyUri;\n\t\t\timageResOnFail = options.imageResOnFail;\n\t\t\timageOnLoading = options.imageOnLoading;\n\t\t\timageForEmptyUri = options.imageForEmptyUri;\n\t\t\timageOnFail = options.imageOnFail;\n\t\t\tresetViewBeforeLoading = options.resetViewBeforeLoading;\n\t\t\tcacheInMemory = options.cacheInMemory;\n\t\t\tcacheOnDisk = options.cacheOnDisk;\n\t\t\timageScaleType = options.imageScaleType;\n\t\t\tdecodingOptions = options.decodingOptions;\n\t\t\tdelayBeforeLoading = options.delayBeforeLoading;\n\t\t\tconsiderExifParams = options.considerExifParams;\n\t\t\textraForDownloader = options.extraForDownloader;\n\t\t\tpreProcessor = options.preProcessor;\n\t\t\tpostProcessor = options.postProcessor;\n\t\t\tdisplayer = options.displayer;\n\t\t\thandler = options.handler;\n\t\t\tisSyncLoading = options.isSyncLoading;\n\t\t\treturn this;\n\t\t}\n\n\t\t/** Builds configured {@link DisplayImageOptions} object */\n\t\tpublic DisplayImageOptions build() {\n\t\t\treturn new DisplayImageOptions(this);\n\t\t}\n\t}\n\n\t/**\n\t * 进行创建默认的图片显示配置\n\t * Creates options appropriate for single displaying:\n\t * <ul>\n\t * <li>View will <b>not</b> be reset before loading</li>\n\t * <li>Loaded image will <b>not</b> be cached in memory</li>\n\t * <li>Loaded image will <b>not</b> be cached on disk</li>\n\t * <li>{@link ImageScaleType#IN_SAMPLE_POWER_OF_2} decoding type will be used</li>\n\t * <li>{@link Bitmap.Config#ARGB_8888} bitmap config will be used for image decoding</li>\n\t * <li>{@link SimpleBitmapDisplayer} will be used for image displaying</li>\n\t * </ul>\n\t * <p/>\n\t * These option are appropriate for simple single-use image (from drawables or from Internet) displaying.\n\t */\n\tpublic static DisplayImageOptions createSimple() {\n\t\treturn new Builder().build();\n\t}\n}",
"public class ImageLoader {\n\n\tpublic static final String TAG = ImageLoader.class.getSimpleName();\n\n\tstatic final String LOG_INIT_CONFIG = \"Initialize ImageLoader with configuration\";\n\tstatic final String LOG_DESTROY = \"Destroy ImageLoader\";\n\tstatic final String LOG_LOAD_IMAGE_FROM_MEMORY_CACHE = \"Load image from memory cache [%s]\";\n\n\tprivate static final String WARNING_RE_INIT_CONFIG = \"Try to initialize ImageLoader which had already been initialized before. \" + \"To re-init ImageLoader with new configuration call ImageLoader.destroy() at first.\";\n\tprivate static final String ERROR_WRONG_ARGUMENTS = \"Wrong arguments were passed to displayImage() method (ImageView reference must not be null)\";\n\tprivate static final String ERROR_NOT_INIT = \"ImageLoader must be init with configuration before using\";\n\tprivate static final String ERROR_INIT_CONFIG_WITH_NULL = \"ImageLoader configuration can not be initialized with null\";\n\n\t//ImageLoader配置项\n\tprivate ImageLoaderConfiguration configuration;\n\t//ImageLoader加载任务引擎\n\tprivate ImageLoaderEngine engine;\n //图片加载监听器 默认采用SimpleImageLoadingListener\n\tprivate ImageLoadingListener defaultListener = new SimpleImageLoadingListener();\n //采用volatile 这边修饰被不同线程访问和修改的变量\n\tprivate volatile static ImageLoader instance;\n\n\t/** Returns singleton class instance */\n\tpublic static ImageLoader getInstance() {\n\t\tif (instance == null) {\n\t\t\tsynchronized (ImageLoader.class) {\n\t\t\t\tif (instance == null) {\n\t\t\t\t\tinstance = new ImageLoader();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn instance;\n\t}\n\n\tprotected ImageLoader() {\n\t}\n\n\t/**\n\t * 给ImageLoder进行初始化配置项\n\t * Initializes ImageLoader instance with configuration.<br />\n\t * If configurations was set before ( {@link #isInited()} == true) then this method does nothing.<br />\n\t * To force initialization with new configuration you should {@linkplain #destroy() destroy ImageLoader} at first.\n\t *\n\t * @param configuration {@linkplain ImageLoaderConfiguration ImageLoader configuration}\n\t * @throws IllegalArgumentException if <b>configuration</b> parameter is null\n\t */\n\tpublic synchronized void init(ImageLoaderConfiguration configuration) {\n\t\tif (configuration == null) {\n\t\t\tthrow new IllegalArgumentException(ERROR_INIT_CONFIG_WITH_NULL);\n\t\t}\n\t\tif (this.configuration == null) {\n\t\t\tL.d(LOG_INIT_CONFIG);\n\t\t\t//创建图片加载引擎\n\t\t\tengine = new ImageLoaderEngine(configuration);\n\t\t\tthis.configuration = configuration;\n\t\t} else {\n\t\t\tL.w(WARNING_RE_INIT_CONFIG);\n\t\t}\n\t}\n\n\t/**\n\t * 判断当前ImageLoderConfiguration是否已经被初始化\n\t * Returns <b>true</b> - if ImageLoader {@linkplain #init(ImageLoaderConfiguration) is initialized with\n\t * configuration}; <b>false</b> - otherwise\n\t */\n\tpublic boolean isInited() {\n\t\treturn configuration != null;\n\t}\n\n\t/**\n\t * 添加图片加载显示任务到执行线程池中,这边显示图片ImageView控件被包装成ImageAware对象\n\t * Adds display image task to execution pool. Image will be set to ImageAware when it's turn. <br/>\n\t * Default {@linkplain DisplayImageOptions display image options} from {@linkplain ImageLoaderConfiguration\n\t * configuration} will be used.<br />\n\t * <b>NOTE:</b> {@link #init(ImageLoaderConfiguration)} method must be called before this method call\n\t *\n\t * @param uri Image URI (i.e. \"http://site.com/image.png\", \"file:///mnt/sdcard/image.png\")\n\t * @param imageAware {@linkplain com.nostra13.universalimageloader.core.imageaware.ImageAware Image aware view}\n\t * which should display image\n\t * @throws IllegalStateException if {@link #init(ImageLoaderConfiguration)} method wasn't called before\n\t * @throws IllegalArgumentException if passed <b>imageAware</b> is null\n\t */\n\t/**\n\t *\n\t * @param uri 图片URL地址\n\t * @param imageAware ImageView包装成ImageAware\n\t */\n\tpublic void displayImage(String uri, ImageAware imageAware) {\n\t\tdisplayImage(uri, imageAware, null, null, null);\n\t}\n\n\t/**\n\t * 添加图片加载显示任务到执行线程池中,这边显示图片ImageView控件被包装成ImageAware对象\n\t * Adds display image task to execution pool. Image will be set to ImageAware when it's turn.<br />\n\t * Default {@linkplain DisplayImageOptions display image options} from {@linkplain ImageLoaderConfiguration\n\t * configuration} will be used.<br />\n\t * <b>NOTE:</b> {@link #init(ImageLoaderConfiguration)} method must be called before this method call\n\t *\n\t * @param uri Image URI (i.e. \"http://site.com/image.png\", \"file:///mnt/sdcard/image.png\")\n\t * @param imageAware {@linkplain com.nostra13.universalimageloader.core.imageaware.ImageAware Image aware view}\n\t * which should display image\n\t * @param listener {@linkplain ImageLoadingListener Listener} for image loading process. Listener fires events on\n\t * UI thread if this method is called on UI thread.\n\t * @throws IllegalStateException if {@link #init(ImageLoaderConfiguration)} method wasn't called before\n\t * @throws IllegalArgumentException if passed <b>imageAware</b> is null\n\t */\n\t/**\n\t *\n\t * @param uri 图片URL地址\n\t * @param imageAware ImageView包装成ImageAware\n\t * @param listener 图片加载进度监听器\n\t */\n\tpublic void displayImage(String uri, ImageAware imageAware, ImageLoadingListener listener) {\n\t\tdisplayImage(uri, imageAware, null, listener, null);\n\t}\n\n\t/**\n\t * 添加图片加载显示任务到执行线程池中,这边显示图片ImageView控件被包装成ImageAware对象\n\t * Adds display image task to execution pool. Image will be set to ImageAware when it's turn.<br />\n\t * <b>NOTE:</b> {@link #init(ImageLoaderConfiguration)} method must be called before this method call\n\t *\n\t * @param uri Image URI (i.e. \"http://site.com/image.png\", \"file:///mnt/sdcard/image.png\")\n\t * @param imageAware {@linkplain com.nostra13.universalimageloader.core.imageaware.ImageAware Image aware view}\n\t * which should display image\n\t * @param options {@linkplain com.nostra13.universalimageloader.core.DisplayImageOptions Options} for image\n\t * decoding and displaying. If <b>null</b> - default display image options\n\t * {@linkplain ImageLoaderConfiguration.Builder#defaultDisplayImageOptions(DisplayImageOptions)\n\t * from configuration} will be used.\n\t * @throws IllegalStateException if {@link #init(ImageLoaderConfiguration)} method wasn't called before\n\t * @throws IllegalArgumentException if passed <b>imageAware</b> is null\n\t */\n\t/**\n\t *\n\t * @param uri 图片URL地址\n\t * @param imageAware ImageView包装成ImageAware\n\t * @param options 图片显示参数配置\n\t */\n\tpublic void displayImage(String uri, ImageAware imageAware, DisplayImageOptions options) {\n\t\tdisplayImage(uri, imageAware, options, null, null);\n\t}\n\n\t/**\n\t * 添加图片加载显示任务到执行线程池中,这边显示图片ImageView控件被包装成ImageAware对象\n\t * Adds display image task to execution pool. Image will be set to ImageAware when it's turn.<br />\n\t * <b>NOTE:</b> {@link #init(ImageLoaderConfiguration)} method must be called before this method call\n\t *\n\t * @param uri Image URI (i.e. \"http://site.com/image.png\", \"file:///mnt/sdcard/image.png\")\n\t * @param imageAware {@linkplain com.nostra13.universalimageloader.core.imageaware.ImageAware Image aware view}\n\t * which should display image\n\t * @param options {@linkplain com.nostra13.universalimageloader.core.DisplayImageOptions Options} for image\n\t * decoding and displaying. If <b>null</b> - default display image options\n\t * {@linkplain ImageLoaderConfiguration.Builder#defaultDisplayImageOptions(DisplayImageOptions)\n\t * from configuration} will be used.\n\t * @param listener {@linkplain ImageLoadingListener Listener} for image loading process. Listener fires events on\n\t * UI thread if this method is called on UI thread.\n\t * @throws IllegalStateException if {@link #init(ImageLoaderConfiguration)} method wasn't called before\n\t * @throws IllegalArgumentException if passed <b>imageAware</b> is null\n\t */\n\t/**\n\t *\n\t * @param uri 图片URL地址\n\t * @param imageAware imageview包装成ImageAware\n\t * @param options 图片显示相关参数\n\t * @param listener 图片加载进度监听器\n\t */\n\tpublic void displayImage(String uri, ImageAware imageAware, DisplayImageOptions options,\n\t\t\tImageLoadingListener listener) {\n\t\tdisplayImage(uri, imageAware, options, listener, null);\n\t}\n\n\t/**\n\t * 添加图片加载显示任务到执行线程池中,这边显示图片ImageView控件被包装成ImageAware对象\n\t * Adds display image task to execution pool. Image will be set to ImageAware when it's turn.<br />\n\t * <b>NOTE:</b> {@link #init(ImageLoaderConfiguration)} method must be called before this method call\n\t *\n\t * @param uri Image URI (i.e. \"http://site.com/image.png\", \"file:///mnt/sdcard/image.png\")\n\t * @param imageAware {@linkplain com.nostra13.universalimageloader.core.imageaware.ImageAware Image aware view}\n\t * which should display image\n\t * @param options {@linkplain com.nostra13.universalimageloader.core.DisplayImageOptions Options} for image\n\t * decoding and displaying. If <b>null</b> - default display image options\n\t * {@linkplain ImageLoaderConfiguration.Builder#defaultDisplayImageOptions(DisplayImageOptions)\n\t * from configuration} will be used.\n\t * @param listener {@linkplain ImageLoadingListener Listener} for image loading process. Listener fires\n\t * events on UI thread if this method is called on UI thread.\n\t * @param progressListener {@linkplain com.nostra13.universalimageloader.core.listener.ImageLoadingProgressListener\n\t * Listener} for image loading progress. Listener fires events on UI thread if this method\n\t * is called on UI thread. Caching on disk should be enabled in\n\t * {@linkplain com.nostra13.universalimageloader.core.DisplayImageOptions options} to make\n\t * this listener work.\n\t * @throws IllegalStateException if {@link #init(ImageLoaderConfiguration)} method wasn't called before\n\t * @throws IllegalArgumentException if passed <b>imageAware</b> is null\n\t */\n\t/**\n\t *\n\t * @param uri 图片URL地址\n\t * @param imageAware imageview包装成ImageAware\n\t * @param options 图片显示配置参数\n\t * @param listener 图片加载监听器\n\t * @param progressListener 图片下载进度监听器\n\t */\n\tpublic void displayImage(String uri, ImageAware imageAware, DisplayImageOptions options,\n\t\t\tImageLoadingListener listener, ImageLoadingProgressListener progressListener) {\n\t\tdisplayImage(uri, imageAware, options, null, listener, progressListener);\n\t}\n\n\t/**\n\t * 添加显示相关任务到执行线程池中,当任务执行完成之后,图片会被加入到ImageAware中\n\t * Adds display image task to execution pool. Image will be set to ImageAware when it's turn.<br />\n\t * <b>NOTE:</b> {@link #init(ImageLoaderConfiguration)} method must be called before this method call\n\t *\n\t * @param uri Image URI (i.e. \"http://site.com/image.png\", \"file:///mnt/sdcard/image.png\")\n\t * @param imageAware {@linkplain com.nostra13.universalimageloader.core.imageaware.ImageAware Image aware view}\n\t * which should display image\n\t * @param options {@linkplain com.nostra13.universalimageloader.core.DisplayImageOptions Options} for image\n\t * decoding and displaying. If <b>null</b> - default display image options\n\t * {@linkplain ImageLoaderConfiguration.Builder#defaultDisplayImageOptions(DisplayImageOptions)\n\t * from configuration} will be used.\n\t * @param targetSize {@linkplain ImageSize} Image target size. If <b>null</b> - size will depend on the view\n\t * @param listener {@linkplain ImageLoadingListener Listener} for image loading process. Listener fires\n\t * events on UI thread if this method is called on UI thread.\n\t * @param progressListener {@linkplain com.nostra13.universalimageloader.core.listener.ImageLoadingProgressListener\n\t * Listener} for image loading progress. Listener fires events on UI thread if this method\n\t * is called on UI thread. Caching on disk should be enabled in\n\t * {@linkplain com.nostra13.universalimageloader.core.DisplayImageOptions options} to make\n\t * this listener work.\n\t * @throws IllegalStateException if {@link #init(ImageLoaderConfiguration)} method wasn't called before\n\t * @throws IllegalArgumentException if passed <b>imageAware</b> is null\n\t */\n\tpublic void displayImage(String uri, ImageAware imageAware, DisplayImageOptions options,\n\t\t\tImageSize targetSize, ImageLoadingListener listener, ImageLoadingProgressListener progressListener) {\n\t\t//进行检查ImageLoader全局相关配置\n\t\tcheckConfiguration();\n\t\tif (imageAware == null) {\n\t\t\tthrow new IllegalArgumentException(ERROR_WRONG_ARGUMENTS);\n\t\t}\n\t\tif (listener == null) {\n\t\t\tlistener = defaultListener;\n\t\t}\n\t\t//检查图片显示配置\n\t\tif (options == null) {\n\t\t\toptions = configuration.defaultDisplayImageOptions;\n\t\t}\n //==============图片地址为空=================\n\t\tif (TextUtils.isEmpty(uri)) {\n\t\t\tengine.cancelDisplayTaskFor(imageAware);\n\t\t\t//接口方法回调,当前图片加载任务开始\n\t\t\tlistener.onLoadingStarted(uri, imageAware.getWrappedView());\n\t\t\t//进行判断是否给imageview添加一个空地址的资源图片\n\t\t\tif (options.shouldShowImageForEmptyUri()) {\n\t\t\t\timageAware.setImageDrawable(options.getImageForEmptyUri(configuration.resources));\n\t\t\t} else {\n\t\t\t\timageAware.setImageDrawable(null);\n\t\t\t}\n\t\t\t//直接加载回调加载成功\n\t\t\tlistener.onLoadingComplete(uri, imageAware.getWrappedView(), null);\n\t\t\treturn;\n\t\t}\n //=============图片地址存在=====================\n\t\tif (targetSize == null) {\n\t\t\t//如果图片显示的目标大小没有设置的,那么就使用默认大小尺寸即可\n\t\t\ttargetSize = ImageSizeUtils.defineTargetSizeForView(imageAware, configuration.getMaxImageSize());\n\t\t}\n\t\t//根据地址和图片目标尺寸信息,生成缓存key\n\t\tString memoryCacheKey = MemoryCacheUtils.generateKey(uri, targetSize);\n\t\tengine.prepareDisplayTaskFor(imageAware, memoryCacheKey);\n //开始进行加载图片\n\t\tlistener.onLoadingStarted(uri, imageAware.getWrappedView());\n\n\t\t//首先根据key去缓存中获取是否还存在该图片\n\t\tBitmap bmp = configuration.memoryCache.get(memoryCacheKey);\n\t\tif (bmp != null && !bmp.isRecycled()) {\n\t\t\t//缓存中该图片存在\n\t\t\tL.d(LOG_LOAD_IMAGE_FROM_MEMORY_CACHE, memoryCacheKey);\n\t\t\tif (options.shouldPostProcess()) {\n\t\t\t\tImageLoadingInfo imageLoadingInfo = new ImageLoadingInfo(uri, imageAware, targetSize, memoryCacheKey,\n\t\t\t\t\t\toptions, listener, progressListener, engine.getLockForUri(uri));\n\t\t\t\tProcessAndDisplayImageTask displayTask = new ProcessAndDisplayImageTask(engine, bmp, imageLoadingInfo,\n\t\t\t\t\t\tdefineHandler(options));\n\t\t\t\t//是否允许同步加载\n\t\t\t\tif (options.isSyncLoading()) {\n\t\t\t\t\tdisplayTask.run();\n\t\t\t\t} else {\n\t\t\t\t\t//提交进行显示\n\t\t\t\t\tengine.submit(displayTask);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\toptions.getDisplayer().display(bmp, imageAware, LoadedFrom.MEMORY_CACHE);\n\t\t\t\tlistener.onLoadingComplete(uri, imageAware.getWrappedView(), bmp);\n\t\t\t}\n\t\t} else {\n\t\t\t//缓存中不存在该图片 通过网络加载\n\t\t\tif (options.shouldShowImageOnLoading()) {\n\t\t\t\timageAware.setImageDrawable(options.getImageOnLoading(configuration.resources));\n\t\t\t} else if (options.isResetViewBeforeLoading()) {\n\t\t\t\timageAware.setImageDrawable(null);\n\t\t\t}\n //进行构造图片加载任务相关的所有信息对象\n\t\t\tImageLoadingInfo imageLoadingInfo = new ImageLoadingInfo(uri, imageAware, targetSize, memoryCacheKey,\n\t\t\t\t\toptions, listener, progressListener, engine.getLockForUri(uri));\n\t\t\t//分装图片加载和显示任务对象 然后进行开启执行任务\n\t\t\tLoadAndDisplayImageTask displayTask = new LoadAndDisplayImageTask(engine, imageLoadingInfo,\n\t\t\t\t\tdefineHandler(options));\n\t\t\tif (options.isSyncLoading()) {\n\t\t\t\tdisplayTask.run();\n\t\t\t} else {\n\t\t\t\tengine.submit(displayTask);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * 只是传入图片地址和ImageView控件即可\n\t * Adds display image task to execution pool. Image will be set to ImageView when it's turn. <br/>\n\t * Default {@linkplain DisplayImageOptions display image options} from {@linkplain ImageLoaderConfiguration\n\t * configuration} will be used.<br />\n\t * <b>NOTE:</b> {@link #init(ImageLoaderConfiguration)} method must be called before this method call\n\t *\n\t * @param uri Image URI (i.e. \"http://site.com/image.png\", \"file:///mnt/sdcard/image.png\")\n\t * @param imageView {@link ImageView} which should display image 传入之后进行包装成IamgeViewAware对象\n\t * @throws IllegalStateException if {@link #init(ImageLoaderConfiguration)} method wasn't called before\n\t * @throws IllegalArgumentException if passed <b>imageView</b> is null\n\t */\n\tpublic void displayImage(String uri, ImageView imageView) {\n\t\tdisplayImage(uri, new ImageViewAware(imageView), null, null, null);\n\t}\n\n\t/**\n\t *\n\t * Adds display image task to execution pool. Image will be set to ImageView when it's turn. <br/>\n\t * Default {@linkplain DisplayImageOptions display image options} from {@linkplain ImageLoaderConfiguration\n\t * configuration} will be used.<br />\n\t * <b>NOTE:</b> {@link #init(ImageLoaderConfiguration)} method must be called before this method call\n\t *\n\t * @param uri Image URI (i.e. \"http://site.com/image.png\", \"file:///mnt/sdcard/image.png\")\n\t * @param imageView {@link ImageView} which should display image\n\t * @throws IllegalStateException if {@link #init(ImageLoaderConfiguration)} method wasn't called before\n\t * @throws IllegalArgumentException if passed <b>imageView</b> is null\n\t */\n\tpublic void displayImage(String uri, ImageView imageView, ImageSize targetImageSize) {\n\t\tdisplayImage(uri, new ImageViewAware(imageView), null, targetImageSize, null, null);\n\t}\n\n\t/**\n\t * Adds display image task to execution pool. Image will be set to ImageView when it's turn.<br />\n\t * <b>NOTE:</b> {@link #init(ImageLoaderConfiguration)} method must be called before this method call\n\t *\n\t * @param uri Image URI (i.e. \"http://site.com/image.png\", \"file:///mnt/sdcard/image.png\")\n\t * @param imageView {@link ImageView} which should display image\n\t * @param options {@linkplain com.nostra13.universalimageloader.core.DisplayImageOptions Options} for image\n\t * decoding and displaying. If <b>null</b> - default display image options\n\t * {@linkplain ImageLoaderConfiguration.Builder#defaultDisplayImageOptions(DisplayImageOptions)\n\t * from configuration} will be used.\n\t * @throws IllegalStateException if {@link #init(ImageLoaderConfiguration)} method wasn't called before\n\t * @throws IllegalArgumentException if passed <b>imageView</b> is null\n\t */\n\tpublic void displayImage(String uri, ImageView imageView, DisplayImageOptions options) {\n\t\tdisplayImage(uri, new ImageViewAware(imageView), options, null, null);\n\t}\n\n\t/**\n\t * Adds display image task to execution pool. Image will be set to ImageView when it's turn.<br />\n\t * Default {@linkplain DisplayImageOptions display image options} from {@linkplain ImageLoaderConfiguration\n\t * configuration} will be used.<br />\n\t * <b>NOTE:</b> {@link #init(ImageLoaderConfiguration)} method must be called before this method call\n\t *\n\t * @param uri Image URI (i.e. \"http://site.com/image.png\", \"file:///mnt/sdcard/image.png\")\n\t * @param imageView {@link ImageView} which should display image\n\t * @param listener {@linkplain ImageLoadingListener Listener} for image loading process. Listener fires events on\n\t * UI thread if this method is called on UI thread.\n\t * @throws IllegalStateException if {@link #init(ImageLoaderConfiguration)} method wasn't called before\n\t * @throws IllegalArgumentException if passed <b>imageView</b> is null\n\t */\n\tpublic void displayImage(String uri, ImageView imageView, ImageLoadingListener listener) {\n\t\tdisplayImage(uri, new ImageViewAware(imageView), null, listener, null);\n\t}\n\n\t/**\n\t * Adds display image task to execution pool. Image will be set to ImageView when it's turn.<br />\n\t * <b>NOTE:</b> {@link #init(ImageLoaderConfiguration)} method must be called before this method call\n\t *\n\t * @param uri Image URI (i.e. \"http://site.com/image.png\", \"file:///mnt/sdcard/image.png\")\n\t * @param imageView {@link ImageView} which should display image\n\t * @param options {@linkplain com.nostra13.universalimageloader.core.DisplayImageOptions Options} for image\n\t * decoding and displaying. If <b>null</b> - default display image options\n\t * {@linkplain ImageLoaderConfiguration.Builder#defaultDisplayImageOptions(DisplayImageOptions)\n\t * from configuration} will be used.\n\t * @param listener {@linkplain ImageLoadingListener Listener} for image loading process. Listener fires events on\n\t * UI thread if this method is called on UI thread.\n\t * @throws IllegalStateException if {@link #init(ImageLoaderConfiguration)} method wasn't called before\n\t * @throws IllegalArgumentException if passed <b>imageView</b> is null\n\t */\n\tpublic void displayImage(String uri, ImageView imageView, DisplayImageOptions options,\n\t\t\tImageLoadingListener listener) {\n\t\tdisplayImage(uri, imageView, options, listener, null);\n\t}\n\n\t/**\n\t * Adds display image task to execution pool. Image will be set to ImageView when it's turn.<br />\n\t * <b>NOTE:</b> {@link #init(ImageLoaderConfiguration)} method must be called before this method call\n\t *\n\t * @param uri Image URI (i.e. \"http://site.com/image.png\", \"file:///mnt/sdcard/image.png\")\n\t * @param imageView {@link ImageView} which should display image\n\t * @param options {@linkplain com.nostra13.universalimageloader.core.DisplayImageOptions Options} for image\n\t * decoding and displaying. If <b>null</b> - default display image options\n\t * {@linkplain ImageLoaderConfiguration.Builder#defaultDisplayImageOptions(DisplayImageOptions)\n\t * from configuration} will be used.\n\t * @param listener {@linkplain ImageLoadingListener Listener} for image loading process. Listener fires\n\t * events on UI thread if this method is called on UI thread.\n\t * @param progressListener {@linkplain com.nostra13.universalimageloader.core.listener.ImageLoadingProgressListener\n\t * Listener} for image loading progress. Listener fires events on UI thread if this method\n\t * is called on UI thread. Caching on disk should be enabled in\n\t * {@linkplain com.nostra13.universalimageloader.core.DisplayImageOptions options} to make\n\t * this listener work.\n\t * @throws IllegalStateException if {@link #init(ImageLoaderConfiguration)} method wasn't called before\n\t * @throws IllegalArgumentException if passed <b>imageView</b> is null\n\t */\n\tpublic void displayImage(String uri, ImageView imageView, DisplayImageOptions options,\n\t\t\tImageLoadingListener listener, ImageLoadingProgressListener progressListener) {\n\t\tdisplayImage(uri, new ImageViewAware(imageView), options, listener, progressListener);\n\t}\n\n\t/**\n\t * 添加图片加载任务到执行线程池中。图片会通过回调方法返回\n\t * Adds load image task to execution pool. Image will be returned with\n\t * {@link ImageLoadingListener#onLoadingComplete(String, android.view.View, android.graphics.Bitmap)} callback}.\n\t * <br />\n\t * <b>NOTE:</b> {@link #init(ImageLoaderConfiguration)} method must be called before this method call\n\t *\n\t * @param uri Image URI (i.e. \"http://site.com/image.png\", \"file:///mnt/sdcard/image.png\")\n\t * @param listener {@linkplain ImageLoadingListener Listener} for image loading process. Listener fires events on UI\n\t * thread if this method is called on UI thread.\n\t * @throws IllegalStateException if {@link #init(ImageLoaderConfiguration)} method wasn't called before\n\t */\n\t/**\n\t * 添加图片加载任务到执行线程池中。图片会通过回调方法返回\n\t * @param uri 图片URL地址\n\t * @param listener 图片加载监听器\n\t */\n\tpublic void loadImage(String uri, ImageLoadingListener listener) {\n\t\tloadImage(uri, null, null, listener, null);\n\t}\n\n\t/**\n\t * 添加图片加载任务到执行线程池中。图片会通过回调方法返回\n\t * Adds load image task to execution pool. Image will be returned with\n\t * {@link ImageLoadingListener#onLoadingComplete(String, android.view.View, android.graphics.Bitmap)} callback}.\n\t * <br />\n\t * <b>NOTE:</b> {@link #init(ImageLoaderConfiguration)} method must be called before this method call\n\t *\n\t * @param uri Image URI (i.e. \"http://site.com/image.png\", \"file:///mnt/sdcard/image.png\")\n\t * @param targetImageSize Minimal size for {@link Bitmap} which will be returned in\n\t * {@linkplain ImageLoadingListener#onLoadingComplete(String, android.view.View,\n\t * android.graphics.Bitmap)} callback}. Downloaded image will be decoded\n\t * and scaled to {@link Bitmap} of the size which is <b>equal or larger</b> (usually a bit\n\t * larger) than incoming targetImageSize.\n\t * @param listener {@linkplain ImageLoadingListener Listener} for image loading process. Listener fires\n\t * events on UI thread if this method is called on UI thread.\n\t * @throws IllegalStateException if {@link #init(ImageLoaderConfiguration)} method wasn't called before\n\t */\n\t/**\n\t * 添加图片加载任务到执行线程池中。图片会通过回调方法返回\n\t * @param uri 图片URL地址\n\t * @param targetImageSize 期望目标图片大小尺寸\n\t * @param listener 图片加载监听器\n\t */\n\tpublic void loadImage(String uri, ImageSize targetImageSize, ImageLoadingListener listener) {\n\t\tloadImage(uri, targetImageSize, null, listener, null);\n\t}\n\n\t/**\n\t * 添加图片加载任务到执行线程池中。图片会通过回调方法返回\n\t * Adds load image task to execution pool. Image will be returned with\n\t * {@link ImageLoadingListener#onLoadingComplete(String, android.view.View, android.graphics.Bitmap)} callback}.\n\t * <br />\n\t * <b>NOTE:</b> {@link #init(ImageLoaderConfiguration)} method must be called before this method call\n\t *\n\t * @param uri Image URI (i.e. \"http://site.com/image.png\", \"file:///mnt/sdcard/image.png\")\n\t * @param options {@linkplain com.nostra13.universalimageloader.core.DisplayImageOptions Options} for image\n\t * decoding and displaying. If <b>null</b> - default display image options\n\t * {@linkplain ImageLoaderConfiguration.Builder#defaultDisplayImageOptions(DisplayImageOptions) from\n\t * configuration} will be used.<br />\n\t * @param listener {@linkplain ImageLoadingListener Listener} for image loading process. Listener fires events on UI\n\t * thread if this method is called on UI thread.\n\t * @throws IllegalStateException if {@link #init(ImageLoaderConfiguration)} method wasn't called before\n\t */\n\t/**\n\t * 添加图片加载任务到执行线程池中。图片会通过回调方法返回\n\t * @param uri 图片URL地址\n\t * @param options 图片配置项\n\t * @param listener 图片加载监听器\n\t */\n\tpublic void loadImage(String uri, DisplayImageOptions options, ImageLoadingListener listener) {\n\t\tloadImage(uri, null, options, listener, null);\n\t}\n\n\t/**\n\t * 添加图片加载任务到执行线程池中。图片会通过回调方法返回\n\t * Adds load image task to execution pool. Image will be returned with\n\t * {@link ImageLoadingListener#onLoadingComplete(String, android.view.View, android.graphics.Bitmap)} callback}.\n\t * <br />\n\t * <b>NOTE:</b> {@link #init(ImageLoaderConfiguration)} method must be called before this method call\n\t *\n\t * @param uri Image URI (i.e. \"http://site.com/image.png\", \"file:///mnt/sdcard/image.png\")\n\t * @param targetImageSize Minimal size for {@link Bitmap} which will be returned in\n\t * {@linkplain ImageLoadingListener#onLoadingComplete(String, android.view.View,\n\t * android.graphics.Bitmap)} callback}. Downloaded image will be decoded\n\t * and scaled to {@link Bitmap} of the size which is <b>equal or larger</b> (usually a bit\n\t * larger) than incoming targetImageSize.\n\t * @param options {@linkplain com.nostra13.universalimageloader.core.DisplayImageOptions Options} for image\n\t * decoding and displaying. If <b>null</b> - default display image options\n\t * {@linkplain ImageLoaderConfiguration.Builder#defaultDisplayImageOptions(DisplayImageOptions)\n\t * from configuration} will be used.<br />\n\t * @param listener {@linkplain ImageLoadingListener Listener} for image loading process. Listener fires\n\t * events on UI thread if this method is called on UI thread.\n\t * @throws IllegalStateException if {@link #init(ImageLoaderConfiguration)} method wasn't called before\n\t */\n\t/**\n\t * 添加图片加载任务到执行线程池中。图片会通过回调方法返回\n\t * @param uri 图片URL地址\n\t * @param targetImageSize 期望目标图片大小尺寸\n\t * @param options 图片配置项\n\t * @param listener 图片加载监听器\n\t */\n\tpublic void loadImage(String uri, ImageSize targetImageSize, DisplayImageOptions options,\n\t\t\tImageLoadingListener listener) {\n\t\tloadImage(uri, targetImageSize, options, listener, null);\n\t}\n\n\t/**\n\t * 添加图片加载任务到执行线程池中。图片会通过回调方法返回\n\t * Adds load image task to execution pool. Image will be returned with\n\t * {@link ImageLoadingListener#onLoadingComplete(String, android.view.View, android.graphics.Bitmap)} callback}.\n\t * <br />\n\t * <b>NOTE:</b> {@link #init(ImageLoaderConfiguration)} method must be called before this method call\n\t *\n\t * @param uri Image URI (i.e. \"http://site.com/image.png\", \"file:///mnt/sdcard/image.png\")\n\t * @param targetImageSize Minimal size for {@link Bitmap} which will be returned in\n\t * {@linkplain ImageLoadingListener#onLoadingComplete(String, android.view.View,\n\t * android.graphics.Bitmap)} callback}. Downloaded image will be decoded\n\t * and scaled to {@link Bitmap} of the size which is <b>equal or larger</b> (usually a bit\n\t * larger) than incoming targetImageSize.\n\t * @param options {@linkplain com.nostra13.universalimageloader.core.DisplayImageOptions Options} for image\n\t * decoding and displaying. If <b>null</b> - default display image options\n\t * {@linkplain ImageLoaderConfiguration.Builder#defaultDisplayImageOptions(DisplayImageOptions)\n\t * from configuration} will be used.<br />\n\t * @param listener {@linkplain ImageLoadingListener Listener} for image loading process. Listener fires\n\t * events on UI thread if this method is called on UI thread.\n\t * @param progressListener {@linkplain com.nostra13.universalimageloader.core.listener.ImageLoadingProgressListener\n\t * Listener} for image loading progress. Listener fires events on UI thread if this method\n\t * is called on UI thread. Caching on disk should be enabled in\n\t * {@linkplain com.nostra13.universalimageloader.core.DisplayImageOptions options} to make\n\t * this listener work.\n\t * @throws IllegalStateException if {@link #init(ImageLoaderConfiguration)} method wasn't called before\n\t */\n\t/**\n\t * 添加图片加载任务到执行线程池中。图片会通过回调方法返回\n\t * @param uri 图片URL地址\n\t * @param targetImageSize 期望目标图片大小尺寸\n\t * @param options 图片配置项\n\t * @param listener 图片加载监听器\n\t * @param progressListener 图片下载进度监听器\n\t */\n\tpublic void loadImage(String uri, ImageSize targetImageSize, DisplayImageOptions options,\n\t\t\tImageLoadingListener listener, ImageLoadingProgressListener progressListener) {\n\t\tcheckConfiguration();\n\t\tif (targetImageSize == null) {\n\t\t\ttargetImageSize = configuration.getMaxImageSize();\n\t\t}\n\t\tif (options == null) {\n\t\t\toptions = configuration.defaultDisplayImageOptions;\n\t\t}\n\n\t\tNonViewAware imageAware = new NonViewAware(uri, targetImageSize, ViewScaleType.CROP);\n\t\tdisplayImage(uri, imageAware, options, listener, progressListener);\n\t}\n\n\t/**\n\t * 使用同步方式进行加载和解码图片,传入图片的URL地址\n\t * Loads and decodes image synchronously.<br />\n\t * Default display image options\n\t * {@linkplain ImageLoaderConfiguration.Builder#defaultDisplayImageOptions(DisplayImageOptions) from\n\t * configuration} will be used.<br />\n\t * <b>NOTE:</b> {@link #init(ImageLoaderConfiguration)} method must be called before this method call\n\t *\n\t * @param uri Image URI (i.e. \"http://site.com/image.png\", \"file:///mnt/sdcard/image.png\")\n\t * @return Result image Bitmap. Can be <b>null</b> if image loading/decoding was failed or cancelled.\n\t * @throws IllegalStateException if {@link #init(ImageLoaderConfiguration)} method wasn't called before\n\t */\n\tpublic Bitmap loadImageSync(String uri) {\n\t\treturn loadImageSync(uri, null, null);\n\t}\n\n\t/**\n\t * 使用同步方式进行加载和解码图片,传入图片的URL地址,图片显示的配置项\n\t * Loads and decodes image synchronously.<br />\n\t * <b>NOTE:</b> {@link #init(ImageLoaderConfiguration)} method must be called before this method call\n\t *\n\t * @param uri Image URI (i.e. \"http://site.com/image.png\", \"file:///mnt/sdcard/image.png\")\n\t * @param options {@linkplain com.nostra13.universalimageloader.core.DisplayImageOptions Options} for image\n\t * decoding and scaling. If <b>null</b> - default display image options\n\t * {@linkplain ImageLoaderConfiguration.Builder#defaultDisplayImageOptions(DisplayImageOptions) from\n\t * configuration} will be used.\n\t * @return Result image Bitmap. Can be <b>null</b> if image loading/decoding was failed or cancelled.\n\t * @throws IllegalStateException if {@link #init(ImageLoaderConfiguration)} method wasn't called before\n\t */\n\t/**\n\t *\n\t * @param uri 图片资源URL地址\n\t * @param options 图片显示配置参数\n\t * @return\n\t */\n\tpublic Bitmap loadImageSync(String uri, DisplayImageOptions options) {\n\t\treturn loadImageSync(uri, null, options);\n\t}\n\n\t/**\n\t * 使用同步方式进行加载和解码图片,传入图片的URL地址,期望的尺寸\n\t * Loads and decodes image synchronously.<br />\n\t * Default display image options\n\t * {@linkplain ImageLoaderConfiguration.Builder#defaultDisplayImageOptions(DisplayImageOptions) from\n\t * configuration} will be used.<br />\n\t * <b>NOTE:</b> {@link #init(ImageLoaderConfiguration)} method must be called before this method call\n\t *\n\t * @param uri Image URI (i.e. \"http://site.com/image.png\", \"file:///mnt/sdcard/image.png\")\n\t * @param targetImageSize Minimal size for {@link Bitmap} which will be returned. Downloaded image will be decoded\n\t * and scaled to {@link Bitmap} of the size which is <b>equal or larger</b> (usually a bit\n\t * larger) than incoming targetImageSize.\n\t * @return Result image Bitmap. Can be <b>null</b> if image loading/decoding was failed or cancelled.\n\t * @throws IllegalStateException if {@link #init(ImageLoaderConfiguration)} method wasn't called before\n\t */\n\t/**\n\t *\n\t * @param uri 图片资源URL地址\n\t * @param targetImageSize 图片目标尺寸大小\n\t * @return\n\t */\n\tpublic Bitmap loadImageSync(String uri, ImageSize targetImageSize) {\n\t\treturn loadImageSync(uri, targetImageSize, null);\n\t}\n\n\t/**\n\t * 使用同步方式进行加载和解码图片,传入图片的URL地址,期望的尺寸,图片显示的配置项\n\t * Loads and decodes image synchronously.<br />\n\t * <b>NOTE:</b> {@link #init(ImageLoaderConfiguration)} method must be called before this method call\n\t *\n\t * @param uri Image URI (i.e. \"http://site.com/image.png\", \"file:///mnt/sdcard/image.png\")\n\t * @param targetImageSize Minimal size for {@link Bitmap} which will be returned. Downloaded image will be decoded\n\t * and scaled to {@link Bitmap} of the size which is <b>equal or larger</b> (usually a bit\n\t * larger) than incoming targetImageSize.\n\t * @param options {@linkplain com.nostra13.universalimageloader.core.DisplayImageOptions Options} for image\n\t * decoding and scaling. If <b>null</b> - default display image options\n\t * {@linkplain ImageLoaderConfiguration.Builder#defaultDisplayImageOptions(DisplayImageOptions)\n\t * from configuration} will be used.\n\t * @return Result image Bitmap. Can be <b>null</b> if image loading/decoding was failed or cancelled.\n\t * @throws IllegalStateException if {@link #init(ImageLoaderConfiguration)} method wasn't called before\n\t */\n\t/**\n\t *\n\t * @param uri 资源URL地址\n\t * @param targetImageSize 显示目标图片尺寸大小\n\t * @param options 图片显示配置参数\n\t * @return\n\t */\n\tpublic Bitmap loadImageSync(String uri, ImageSize targetImageSize, DisplayImageOptions options) {\n\t\tif (options == null) {\n\t\t\toptions = configuration.defaultDisplayImageOptions;\n\t\t}\n\t\toptions = new DisplayImageOptions.Builder().cloneFrom(options).syncLoading(true).build();\n\n\t\tSyncImageLoadingListener listener = new SyncImageLoadingListener();\n\t\tloadImage(uri, targetImageSize, options, listener);\n\t\treturn listener.getLoadedBitmap();\n\t}\n\n\t/**\n\t * 检查ImageLoder配置是否已经被初始化\n\t * Checks if ImageLoader's configuration was initialized\n\t *\n\t * @throws IllegalStateException if configuration wasn't initialized\n\t */\n\tprivate void checkConfiguration() {\n\t\tif (configuration == null) {\n\t\t\tthrow new IllegalStateException(ERROR_NOT_INIT);\n\t\t}\n\t}\n\n\t/**\n\t * 为所有图片显示和加载任务添加加载监听器\n\t * Sets a default loading listener for all display and loading tasks.\n\t */\n\tpublic void setDefaultLoadingListener(ImageLoadingListener listener) {\n\t\tdefaultListener = listener == null ? new SimpleImageLoadingListener() : listener;\n\t}\n\n\t/**\n\t * 获取内存缓存器\n\t * Returns memory cache\n\t *\n\t * @throws IllegalStateException if {@link #init(ImageLoaderConfiguration)} method wasn't called before\n\t */\n\tpublic MemoryCache getMemoryCache() {\n\t\tcheckConfiguration();\n\t\treturn configuration.memoryCache;\n\t}\n\n\t/**\n\t * 清楚内存缓存器重的方法\n\t * Clears memory cache\n\t *\n\t * @throws IllegalStateException if {@link #init(ImageLoaderConfiguration)} method wasn't called before\n\t */\n\tpublic void clearMemoryCache() {\n\t\tcheckConfiguration();\n\t\tconfiguration.memoryCache.clear();\n\t}\n\n\t/**\n\t * 获取硬盘(DISK)缓存器\n\t * Returns disk cache\n\t *\n\t * @throws IllegalStateException if {@link #init(ImageLoaderConfiguration)} method wasn't called before\n\t * @deprecated Use {@link #getDiskCache()} instead\n\t */\n\t@Deprecated\n\tpublic DiskCache getDiscCache() {\n\t\treturn getDiskCache();\n\t}\n\n\t/**\n\t * 获取硬盘(DISK)缓存器\n\t * Returns disk cache\n\t *\n\t * @throws IllegalStateException if {@link #init(ImageLoaderConfiguration)} method wasn't called before\n\t */\n\tpublic DiskCache getDiskCache() {\n\t\tcheckConfiguration();\n\t\treturn configuration.diskCache;\n\t}\n\n\t/**\n\t * 清除硬盘(DISK)缓存中的数据\n\t * Clears disk cache.\n\t *\n\t * @throws IllegalStateException if {@link #init(ImageLoaderConfiguration)} method wasn't called before\n\t * @deprecated Use {@link #clearDiskCache()} instead\n\t */\n\t@Deprecated\n\tpublic void clearDiscCache() {\n\t\tclearDiskCache();\n\t}\n\n\t/**\n\t * 清除硬盘(DISK)缓存中的数据\n\t * Clears disk cache.\n\t *\n\t * @throws IllegalStateException if {@link #init(ImageLoaderConfiguration)} method wasn't called before\n\t */\n\tpublic void clearDiskCache() {\n\t\tcheckConfiguration();\n\t\tconfiguration.diskCache.clear();\n\t}\n\n\t/**\n\t * 获取当前正在往ImageAware加载的URL地址\n\t * Returns URI of image which is loading at this moment into passed\n\t * {@link com.nostra13.universalimageloader.core.imageaware.ImageAware ImageAware}\n\t */\n\tpublic String getLoadingUriForView(ImageAware imageAware) {\n\t\treturn engine.getLoadingUriForView(imageAware);\n\t}\n\n\t/**\n\t *获取当前正在往ImageView加载的URL地址\n\t * Returns URI of image which is loading at this moment into passed\n\t * {@link android.widget.ImageView ImageView}\n\t */\n\tpublic String getLoadingUriForView(ImageView imageView) {\n\t\treturn engine.getLoadingUriForView(new ImageViewAware(imageView));\n\t}\n\n\t/**\n\t * 取消加载和显示Image的任务\n\t * Cancel the task of loading and displaying image for passed\n\t * {@link com.nostra13.universalimageloader.core.imageaware.ImageAware ImageAware}.\n\t *\n\t * @param imageAware {@link com.nostra13.universalimageloader.core.imageaware.ImageAware ImageAware} for\n\t * which display task will be cancelled\n\t */\n\tpublic void cancelDisplayTask(ImageAware imageAware) {\n\t\tengine.cancelDisplayTaskFor(imageAware);\n\t}\n\n\t/**\n\t * 取消加载和显示Image的任务\n\t * Cancel the task of loading and displaying image for passed\n\t * {@link android.widget.ImageView ImageView}.\n\t *\n\t * @param imageView {@link android.widget.ImageView ImageView} for which display task will be cancelled\n\t */\n\tpublic void cancelDisplayTask(ImageView imageView) {\n\t\tengine.cancelDisplayTaskFor(new ImageViewAware(imageView));\n\t}\n\n\t/**\n\t * 拒绝或者允许ImageLoder通过网络下载图片\n\t * Denies or allows ImageLoader to download images from the network.<br />\n\t * <br />\n\t * If downloads are denied and if image isn't cached then\n\t * {@link ImageLoadingListener#onLoadingFailed(String, View, FailReason)} callback will be fired with\n\t * {@link FailReason.FailType#NETWORK_DENIED}\n\t *\n\t * @param denyNetworkDownloads pass <b>true</b> - to deny engine to download images from the network; <b>false</b> -\n\t * to allow engine to download images from network.\n\t */\n\tpublic void denyNetworkDownloads(boolean denyNetworkDownloads) {\n\t\tengine.denyNetworkDownloads(denyNetworkDownloads);\n\t}\n\n\t/**\n\t *\n\t * Sets option whether ImageLoader will use {@link FlushedInputStream} for network downloads to handle <a\n\t * href=\"http://code.google.com/p/android/issues/detail?id=6066\">this known problem</a> or not.\n\t *\n\t * @param handleSlowNetwork pass <b>true</b> - to use {@link FlushedInputStream} for network downloads; <b>false</b>\n\t * - otherwise.\n\t */\n\tpublic void handleSlowNetwork(boolean handleSlowNetwork) {\n\t\tengine.handleSlowNetwork(handleSlowNetwork);\n\t}\n\n\t/**\n\t * 暂停ImageLoader加载\n\t * Pause ImageLoader. All new \"load&display\" tasks won't be executed until ImageLoader is {@link #resume() resumed}.\n\t * <br />\n\t * Already running tasks are not paused.\n\t */\n\tpublic void pause() {\n\t\tengine.pause();\n\t}\n\n\t/**\n\t * ImageLoader恢复加载\n\t * Resumes waiting \"load&display\" tasks\n\t *\n\t */\n\tpublic void resume() {\n\t\tengine.resume();\n\t}\n\n\t/**\n\t * 取消所有运行中和挂起的显示图片的任务\n\t * Cancels all running and scheduled display image tasks.<br />\n\t * <b>NOTE:</b> This method doesn't shutdown\n\t * {@linkplain com.nostra13.universalimageloader.core.ImageLoaderConfiguration.Builder#taskExecutor(java.util.concurrent.Executor)\n\t * custom task executors} if you set them.<br />\n\t * ImageLoader still can be used after calling this method.\n\t */\n\tpublic void stop() {\n\t\tengine.stop();\n\t}\n\n\t/**\n\t * 停止并且清除当前配置\n\t * {@linkplain #stop() Stops ImageLoader} and clears current configuration. <br />\n\t * You can {@linkplain #init(ImageLoaderConfiguration) init} ImageLoader with new configuration after calling this\n\t * method.\n\t */\n\tpublic void destroy() {\n\t\tif (configuration != null) L.d(LOG_DESTROY);\n\t\tstop();\n\t\tconfiguration.diskCache.close();\n\t\tengine = null;\n\t\tconfiguration = null;\n\t}\n\n\t/**\n\t * 获取Handler进行任务分发\n\t * @param options\n\t * @return\n\t */\n\tprivate static Handler defineHandler(DisplayImageOptions options) {\n\t\tHandler handler = options.getHandler();\n\t\t//同步加载,handler为null即可\n\t\tif (options.isSyncLoading()) {\n\t\t\thandler = null;\n\t\t} else if (handler == null && Looper.myLooper() == Looper.getMainLooper()) {\n\t\t\t//异步加载需要使用handler进行切换到主线程\n\t\t\thandler = new Handler();\n\t\t}\n\t\treturn handler;\n\t}\n\n\t/**\n\t * 图片同步加载监听器\n\t * Listener which is designed for synchronous image loading.\n\t *\n\t * @author Sergey Tarasevich (nostra13[at]gmail[dot]com)\n\t * @since 1.9.0\n\t */\n\tprivate static class SyncImageLoadingListener extends SimpleImageLoadingListener {\n\n\t\tprivate Bitmap loadedImage;\n\n\t\t@Override\n\t\tpublic void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {\n\t\t\tthis.loadedImage = loadedImage;\n\t\t}\n\n\t\tpublic Bitmap getLoadedBitmap() {\n\t\t\treturn loadedImage;\n\t\t}\n\t}\n}",
"public class CircleBitmapDisplayer implements BitmapDisplayer {\n\n\tprotected final Integer strokeColor;\n\tprotected final float strokeWidth;\n\n\tpublic CircleBitmapDisplayer() {\n\t\tthis(null);\n\t}\n\n\tpublic CircleBitmapDisplayer(Integer strokeColor) {\n\t\tthis(strokeColor, 0);\n\t}\n\n\tpublic CircleBitmapDisplayer(Integer strokeColor, float strokeWidth) {\n\t\tthis.strokeColor = strokeColor;\n\t\tthis.strokeWidth = strokeWidth;\n\t}\n\n\t@Override\n\tpublic void display(Bitmap bitmap, ImageAware imageAware, LoadedFrom loadedFrom) {\n\t\tif (!(imageAware instanceof ImageViewAware)) {\n\t\t\tthrow new IllegalArgumentException(\"ImageAware should wrap ImageView. ImageViewAware is expected.\");\n\t\t}\n\n\t\timageAware.setImageDrawable(new CircleDrawable(bitmap, strokeColor, strokeWidth));\n\t}\n\n\tpublic static class CircleDrawable extends Drawable {\n\n\t\tprotected float radius;\n\n\t\tprotected final RectF mRect = new RectF();\n\t\tprotected final RectF mBitmapRect;\n\t\tprotected final BitmapShader bitmapShader;\n\t\tprotected final Paint paint;\n\t\tprotected final Paint strokePaint;\n\t\tprotected final float strokeWidth;\n\t\tprotected float strokeRadius;\n\n\t\tpublic CircleDrawable(Bitmap bitmap, Integer strokeColor, float strokeWidth) {\n\t\t\tradius = Math.min(bitmap.getWidth(), bitmap.getHeight()) / 2;\n\n\t\t\tbitmapShader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);\n\t\t\tmBitmapRect = new RectF(0, 0, bitmap.getWidth(), bitmap.getHeight());\n\n\t\t\tpaint = new Paint();\n\t\t\tpaint.setAntiAlias(true);\n\t\t\tpaint.setShader(bitmapShader);\n\t\t\tpaint.setFilterBitmap(true);\n\t\t\tpaint.setDither(true);\n\n\t\t\tif (strokeColor == null) {\n\t\t\t\tstrokePaint = null;\n\t\t\t} else {\n\t\t\t\tstrokePaint = new Paint();\n\t\t\t\tstrokePaint.setStyle(Paint.Style.STROKE);\n\t\t\t\tstrokePaint.setColor(strokeColor);\n\t\t\t\tstrokePaint.setStrokeWidth(strokeWidth);\n\t\t\t\tstrokePaint.setAntiAlias(true);\n\t\t\t}\n\t\t\tthis.strokeWidth = strokeWidth;\n\t\t\tstrokeRadius = radius - strokeWidth / 2;\n\t\t}\n\n\t\t@Override\n\t\tprotected void onBoundsChange(Rect bounds) {\n\t\t\tsuper.onBoundsChange(bounds);\n\t\t\tmRect.set(0, 0, bounds.width(), bounds.height());\n\t\t\tradius = Math.min(bounds.width(), bounds.height()) / 2;\n\t\t\tstrokeRadius = radius - strokeWidth / 2;\n\n\t\t\t// Resize the original bitmap to fit the new bound\n\t\t\tMatrix shaderMatrix = new Matrix();\n\t\t\tshaderMatrix.setRectToRect(mBitmapRect, mRect, Matrix.ScaleToFit.FILL);\n\t\t\tbitmapShader.setLocalMatrix(shaderMatrix);\n\t\t}\n\n\t\t@Override\n\t\tpublic void draw(Canvas canvas) {\n\t\t\tcanvas.drawCircle(radius, radius, radius, paint);\n\t\t\tif (strokePaint != null) {\n\t\t\t\tcanvas.drawCircle(radius, radius, strokeRadius, strokePaint);\n\t\t\t}\n\t\t}\n\n\t\t@Override\n\t\tpublic int getOpacity() {\n\t\t\treturn PixelFormat.TRANSLUCENT;\n\t\t}\n\n\t\t@Override\n\t\tpublic void setAlpha(int alpha) {\n\t\t\tpaint.setAlpha(alpha);\n\t\t}\n\n\t\t@Override\n\t\tpublic void setColorFilter(ColorFilter cf) {\n\t\t\tpaint.setColorFilter(cf);\n\t\t}\n\t}\n}",
"public class FadeInBitmapDisplayer implements BitmapDisplayer {\n\n\tprivate final int durationMillis;\n\n\t//从网络加载的图片 加入动画\n\tprivate final boolean animateFromNetwork;\n\t//从本地缓存中加载的图片 加入动画\n\tprivate final boolean animateFromDisk;\n\t//从内存中加载的图片 加入动画\n\tprivate final boolean animateFromMemory;\n\n\t/**\n\t * 加入图片显示动画的构造器\n\t * @param durationMillis Duration of \"fade-in\" animation (in milliseconds)\n\t */\n\tpublic FadeInBitmapDisplayer(int durationMillis) {\n\t\tthis(durationMillis, true, true, true);\n\t}\n\n\t/**\n\t * @param durationMillis Duration of \"fade-in\" animation (in milliseconds)\n\t * @param animateFromNetwork Whether animation should be played if image is loaded from network\n\t * @param animateFromDisk Whether animation should be played if image is loaded from disk cache\n\t * @param animateFromMemory Whether animation should be played if image is loaded from memory cache\n\t */\n\tpublic FadeInBitmapDisplayer(int durationMillis, boolean animateFromNetwork, boolean animateFromDisk,\n\t\t\t\t\t\t\t\t boolean animateFromMemory) {\n\t\tthis.durationMillis = durationMillis;\n\t\tthis.animateFromNetwork = animateFromNetwork;\n\t\tthis.animateFromDisk = animateFromDisk;\n\t\tthis.animateFromMemory = animateFromMemory;\n\t}\n\n\t/**\n\t * 图片进行显示在ImageAware中\n\t * @param bitmap 原图片\n\t * @param imageAware 显示进行显示图片的控件 {@linkplain com.nostra13.universalimageloader.core.imageaware.ImageAware Image aware view} to\n\t * display Bitmap\n\t * @param loadedFrom Source of loaded image 图片来源方式\n\t */\n\t@Override\n\tpublic void display(Bitmap bitmap, ImageAware imageAware, LoadedFrom loadedFrom) {\n\t\timageAware.setImageBitmap(bitmap);\n\n\t\tif ((animateFromNetwork && loadedFrom == LoadedFrom.NETWORK) ||\n\t\t\t\t(animateFromDisk && loadedFrom == LoadedFrom.DISC_CACHE) ||\n\t\t\t\t(animateFromMemory && loadedFrom == LoadedFrom.MEMORY_CACHE)) {\n\t\t\tanimate(imageAware.getWrappedView(), durationMillis);\n\t\t}\n\t}\n\n\t/**\n\t * fade-in(显示) 效果动画\n\t * Animates {@link ImageView} with \"fade-in\" effect\n\t *\n\t * @param imageView {@link ImageView} which display image in\n\t * @param durationMillis The length of the animation in milliseconds\n\t */\n\tpublic static void animate(View imageView, int durationMillis) {\n\t\tif (imageView != null) {\n\t\t\tAlphaAnimation fadeImage = new AlphaAnimation(0, 1);\n\t\t\tfadeImage.setDuration(durationMillis);\n\t\t\tfadeImage.setInterpolator(new DecelerateInterpolator());\n\t\t\timageView.startAnimation(fadeImage);\n\t\t}\n\t}\n}",
"public class RoundedBitmapDisplayer implements BitmapDisplayer {\n\n\tprotected final int cornerRadius;\n\tprotected final int margin;\n\n\t/**\n\t * 圆角图片生成器构造方法\n\t * @param cornerRadiusPixels 圆角大小\n\t */\n\tpublic RoundedBitmapDisplayer(int cornerRadiusPixels) {\n\t\tthis(cornerRadiusPixels, 0);\n\t}\n\n\t/**\n\t * 圆角图片生成器构造方法\n\t * @param cornerRadiusPixels 圆角大小\n\t * @param marginPixels 上下左右的间距margin值\n\t */\n\tpublic RoundedBitmapDisplayer(int cornerRadiusPixels, int marginPixels) {\n\t\tthis.cornerRadius = cornerRadiusPixels;\n\t\tthis.margin = marginPixels;\n\t}\n\n\t@Override\n\tpublic void display(Bitmap bitmap, ImageAware imageAware, LoadedFrom loadedFrom) {\n\t\tif (!(imageAware instanceof ImageViewAware)) {\n\t\t\tthrow new IllegalArgumentException(\"ImageAware should wrap ImageView. ImageViewAware is expected.\");\n\t\t}\n\n\t\timageAware.setImageDrawable(new RoundedDrawable(bitmap, cornerRadius, margin));\n\t}\n\n\t/**\n\t * 进行绘制圆角图片\n\t */\n\tpublic static class RoundedDrawable extends Drawable {\n\n\t\tprotected final float cornerRadius;\n\t\tprotected final int margin;\n\n\t\tprotected final RectF mRect = new RectF(),\n\t\t\t\tmBitmapRect;\n\t\tprotected final BitmapShader bitmapShader;\n\t\tprotected final Paint paint;\n\n\t\tpublic RoundedDrawable(Bitmap bitmap, int cornerRadius, int margin) {\n\t\t\tthis.cornerRadius = cornerRadius;\n\t\t\tthis.margin = margin;\n\n\t\t\tbitmapShader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);\n\t\t\tmBitmapRect = new RectF (margin, margin, bitmap.getWidth() - margin, bitmap.getHeight() - margin);\n\t\t\t\n\t\t\tpaint = new Paint();\n\t\t\tpaint.setAntiAlias(true);\n\t\t\tpaint.setShader(bitmapShader);\n\t\t\tpaint.setFilterBitmap(true);\n\t\t\tpaint.setDither(true);\n\t\t}\n\n\t\t@Override\n\t\tprotected void onBoundsChange(Rect bounds) {\n\t\t\tsuper.onBoundsChange(bounds);\n\t\t\tmRect.set(margin, margin, bounds.width() - margin, bounds.height() - margin);\n\t\t\t\n\t\t\t// Resize the original bitmap to fit the new bound\n\t\t\tMatrix shaderMatrix = new Matrix();\n\t\t\tshaderMatrix.setRectToRect(mBitmapRect, mRect, Matrix.ScaleToFit.FILL);\n\t\t\tbitmapShader.setLocalMatrix(shaderMatrix);\n\t\t\t\n\t\t}\n\n\t\t@Override\n\t\tpublic void draw(Canvas canvas) {\n\t\t\tcanvas.drawRoundRect(mRect, cornerRadius, cornerRadius, paint);\n\t\t}\n\n\t\t@Override\n\t\tpublic int getOpacity() {\n\t\t\treturn PixelFormat.TRANSLUCENT;\n\t\t}\n\n\t\t@Override\n\t\tpublic void setAlpha(int alpha) {\n\t\t\tpaint.setAlpha(alpha);\n\t\t}\n\n\t\t@Override\n\t\tpublic void setColorFilter(ColorFilter cf) {\n\t\t\tpaint.setColorFilter(cf);\n\t\t}\n\t}\n}",
"public class RoundedVignetteBitmapDisplayer extends RoundedBitmapDisplayer {\n\n\t/**\n\t * 构造函数\n\t * @param cornerRadiusPixels 圆角的大小\n\t * @param marginPixels 四周的边距\n\t */\n\tpublic RoundedVignetteBitmapDisplayer(int cornerRadiusPixels, int marginPixels) {\n\t\tsuper(cornerRadiusPixels, marginPixels);\n\t}\n\n\t/**\n\t * 进行创建合适的圆角进行显示\n\t * @param bitmap\n\t * @param imageAware\n\t * @param loadedFrom\n\t */\n\t@Override\n\tpublic void display(Bitmap bitmap, ImageAware imageAware, LoadedFrom loadedFrom) {\n\t\tif (!(imageAware instanceof ImageViewAware)) {\n\t\t\tthrow new IllegalArgumentException(\"ImageAware should wrap ImageView. ImageViewAware is expected.\");\n\t\t}\n\n\t\timageAware.setImageDrawable(new RoundedVignetteDrawable(bitmap, cornerRadius, margin));\n\t}\n\n\tprotected static class RoundedVignetteDrawable extends RoundedDrawable {\n\n\t\tRoundedVignetteDrawable(Bitmap bitmap, int cornerRadius, int margin) {\n\t\t\tsuper(bitmap, cornerRadius, margin);\n\t\t}\n\n\t\t/**\n\t\t *\n\t\t * @param bounds\n\t\t */\n\t\t@Override\n\t\tprotected void onBoundsChange(Rect bounds) {\n\t\t\tsuper.onBoundsChange(bounds);\n\t\t\tRadialGradient vignette = new RadialGradient(\n\t\t\t\t\tmRect.centerX(), mRect.centerY() * 1.0f / 0.7f, mRect.centerX() * 1.3f,\n\t\t\t\t\tnew int[]{0, 0, 0x7f000000}, new float[]{0.0f, 0.7f, 1.0f},\n\t\t\t\t\tShader.TileMode.CLAMP);\n\n\t\t\tMatrix oval = new Matrix();\n\t\t\toval.setScale(1.0f, 0.7f);\n\t\t\tvignette.setLocalMatrix(oval);\n\n\t\t\tpaint.setShader(new ComposeShader(bitmapShader, vignette, PorterDuff.Mode.SRC_OVER));\n\t\t}\n\t}\n}",
"public interface ImageLoadingListener {\n\n\t/**\n\t * 图片加载任务开始的时候回调\n\t * Is called when image loading task was started\n\t *\n\t * @param imageUri Loading image URI\n\t * @param view View for image\n\t */\n\tvoid onLoadingStarted(String imageUri, View view);\n\n\t/**\n\t * 图片加载过程中发生错误回调\n\t * Is called when an error was occurred during image loading\n\t *\n\t * @param imageUri Loading image URI\n\t * @param view View for image. Can be <b>null</b>.\n\t * @param failReason {@linkplain com.nostra13.universalimageloader.core.assist.FailReason The reason} why image\n\t * loading was failed\n\t */\n\tvoid onLoadingFailed(String imageUri, View view, FailReason failReason);\n\n\t/**\n\t * 图片加载成功回调\n\t * Is called when image is loaded successfully (and displayed in View if one was specified)\n\t *\n\t * @param imageUri Loaded image URI\n\t * @param view View for image. Can be <b>null</b>.\n\t * @param loadedImage Bitmap of loaded and decoded image\n\t */\n\tvoid onLoadingComplete(String imageUri, View view, Bitmap loadedImage);\n\n\t/**\n\t * 加载被取消的时候回调\n\t * Is called when image loading task was cancelled because View for image was reused in newer task\n\t *\n\t * @param imageUri Loading image URI\n\t * @param view View for image. Can be <b>null</b>.\n\t */\n\tvoid onLoadingCancelled(String imageUri, View view);\n}",
"public class SimpleImageLoadingListener implements ImageLoadingListener {\n\t/**\n\t * 图片加载开始回调\n\t * @param imageUri Loading image URI\n\t * @param view View for image\n\t */\n\t@Override\n\tpublic void onLoadingStarted(String imageUri, View view) {\n\t\t// Empty implementation\n\t}\n\n\t/**\n\t * 图片加载失败回调\n\t * @param imageUri Loading image URI\n\t * @param view View for image. Can be <b>null</b>.\n\t * @param failReason {@linkplain com.nostra13.universalimageloader.core.assist.FailReason The reason} why image\n\t */\n\t@Override\n\tpublic void onLoadingFailed(String imageUri, View view, FailReason failReason) {\n\t\t// Empty implementation\n\t}\n\n\t/**\n\t * 图片加载完成回调\n\t * @param imageUri Loaded image URI\n\t * @param view View for image. Can be <b>null</b>.\n\t * @param loadedImage Bitmap of loaded and decoded image\n\t */\n\t@Override\n\tpublic void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {\n\t\t// Empty implementation\n\t}\n\n\t/**\n\t * 图片加载取消回调\n\t * @param imageUri Loading image URI\n\t * @param view View for image. Can be <b>null</b>.\n\t */\n\t@Override\n\tpublic void onLoadingCancelled(String imageUri, View view) {\n\t\t// Empty implementation\n\t}\n}"
] | import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.CircleBitmapDisplayer;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.nostra13.universalimageloader.core.display.RoundedVignetteBitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.nostra13.universalimageloader.sample.Constants;
import com.nostra13.universalimageloader.sample.R;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List; | /*******************************************************************************
* Copyright 2011-2014 Sergey Tarasevich
*
* 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.nostra13.universalimageloader.sample.fragment;
/**
* @author Sergey Tarasevich (nostra13[at]gmail[dot]com)
*/
public class ImageListFragment extends AbsListViewBaseFragment {
public static final int INDEX = 0;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fr_image_list, container, false);
listView = (ListView) rootView.findViewById(android.R.id.list);
((ListView) listView).setAdapter(new ImageAdapter(getActivity()));
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
startImagePagerActivity(position);
}
});
return rootView;
}
@Override
public void onDestroy() {
super.onDestroy();
AnimateFirstDisplayListener.displayedImages.clear();
}
private static class ImageAdapter extends BaseAdapter {
private static final String[] IMAGE_URLS = Constants.IMAGES;
private LayoutInflater inflater;
private ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener();
private DisplayImageOptions options;
ImageAdapter(Context context) {
inflater = LayoutInflater.from(context);
options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.ic_stub)
.showImageForEmptyUri(R.drawable.ic_empty)
.showImageOnFail(R.drawable.ic_error)
.cacheInMemory(true)
.cacheOnDisk(true)
.considerExifParams(true)
.displayer(new RoundedVignetteBitmapDisplayer(20,10))
.build();
}
@Override
public int getCount() {
return IMAGE_URLS.length;
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
final ViewHolder holder;
if (convertView == null) {
view = inflater.inflate(R.layout.item_list_image, parent, false);
holder = new ViewHolder();
holder.text = (TextView) view.findViewById(R.id.text);
holder.image = (ImageView) view.findViewById(R.id.image);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.text.setText("Item " + (position + 1));
| ImageLoader.getInstance().displayImage(IMAGE_URLS[position], holder.image, options, animateFirstListener); | 1 |
hawkular/hawkular-android-client | mobile/src/main/java/org/hawkular/client/android/fragment/AlertsFragment.java | [
"public final class HawkularApplication extends Application {\n\n public static Retrofit retrofit;\n private RefWatcher refWatcher;\n\n @Override\n public void onCreate() {\n super.onCreate();\n\n setUpLogging();\n setUpDetections();\n setUpPush();\n setUpLeakCanary();\n\n }\n\n private void setUpLeakCanary() {\n if (LeakCanary.isInAnalyzerProcess(this)) {\n return;\n }\n refWatcher = LeakCanary.install(this);\n }\n\n public static RefWatcher getRefWatcher(Context context) {\n HawkularApplication application = (HawkularApplication) context.getApplicationContext();\n return application.refWatcher;\n }\n\n public static void setUpRetrofit(String url, final String username, final String password) {\n\n\n OkHttpClient.Builder httpClient = new OkHttpClient.Builder();\n\n HttpLoggingInterceptor logging = new HttpLoggingInterceptor();\n logging.setLevel(HttpLoggingInterceptor.Level.BODY);\n\n httpClient.addInterceptor(logging);\n\n httpClient.addInterceptor(new Interceptor() {\n @Override\n public Response intercept(Interceptor.Chain chain) throws IOException {\n Request original = chain.request();\n\n String cred = new String(Base64.encode((username + \":\" +password).getBytes(), Base64.NO_WRAP));\n\n Request request = original.newBuilder()\n .header(\"Hawkular-Tenant\", \"hawkular\")\n .header(\"Authorization\", \"Basic \" + cred)\n .method(original.method(), original.body())\n .build();\n\n return chain.proceed(request);\n }\n });\n\n OkHttpClient client = httpClient.build();\n\n retrofit = new Retrofit.Builder()\n .baseUrl(url)\n .addConverterFactory(MoshiConverterFactory.create())\n .client(client)\n .build();\n }\n\n private void setUpLogging() {\n if (Android.isDebugging()) {\n Timber.plant(new Timber.DebugTree());\n }\n }\n\n private void setUpDetections() {\n if (Android.isDebugging()) {\n StrictMode.enableDefaults();\n }\n }\n\n private void setUpPush() {\n PushClient.of(this).setUpPush();\n }\n}",
"public final class BackendClient {\n\n private final Activity activity;\n private final Fragment fragment;\n\n @NonNull\n @RequiresPermission(Manifest.permission.INTERNET)\n public static BackendClient of(@NonNull Activity activity) {\n return new BackendClient(activity, null);\n }\n\n @NonNull\n @RequiresPermission(Manifest.permission.INTERNET)\n public static BackendClient of(@NonNull Fragment fragment) {\n return new BackendClient(null, fragment);\n }\n\n private BackendClient(Activity activity, Fragment fragment) {\n this.activity = activity;\n this.fragment = fragment;\n }\n\n public void getAlerts(@NonNull Date startTime, @NonNull Date finishTime, @NonNull List<Trigger> triggers,\n @NonNull Callback<List<Alert>> callback) {\n Map<String, String> parameters = new HashMap<>();\n parameters.put(BackendPipes.Parameters.START_TIME, String.valueOf(startTime.getTime()));\n parameters.put(BackendPipes.Parameters.FINISH_TIME, String.valueOf(finishTime.getTime()));\n\n AlertService service = retrofit.create(AlertService.class);\n Call call = service.get();\n call.enqueue(callback);\n\n }\n\n private List<String> getTriggerIds(List<Trigger> triggers) {\n List<String> triggerIds = new ArrayList<>(triggers.size());\n\n for (Trigger trigger : triggers) {\n triggerIds.add(trigger.getId());\n }\n\n return triggerIds;\n }\n\n public void acknowledgeAlert(@NonNull Alert alert,\n @NonNull retrofit2.Callback<List<String>> callback) {\n AlertService service = retrofit.create(AlertService.class);\n Call call = service.ackAlert(alert.getId());\n call.enqueue(callback);\n\n }\n\n public void resolveAlert(@NonNull Alert alert, @NonNull Callback<List<String>> callback) {\n AlertService service = retrofit.create(AlertService.class);\n Call call = service.resolveAlert(alert.getId());\n call.enqueue(callback);\n }\n\n\n public void noteOnAlert(String alertId,String user, String text,\n @NonNull Callback<List<String>> callback) {\n AlertService service = retrofit.create(AlertService.class);\n Call call= service.noteOnAlert(alertId,user,text);\n call.enqueue(callback);\n }\n\n public void updateTrigger(@NonNull String triggerId, Boolean enabled, @NonNull retrofit2.Callback<List<String>> callback){\n TriggerService service = retrofit.create(TriggerService.class);\n Call call = service.updateTrigger(triggerId,enabled);\n call.enqueue(callback);\n }\n\n public void createTrigger(@NonNull FullTrigger trigger, @NonNull retrofit2.Callback<Trigger> callback){\n TriggerService service = retrofit.create(TriggerService.class);\n Call call = service.createTrigger(trigger);\n call.enqueue(callback);\n }\n\n\n public void getFeeds(@NonNull retrofit2.Callback<Feed> callback) {\n TriggerService service = retrofit.create(TriggerService.class);\n Call call = service.getFeeds();\n call.enqueue(callback);\n }\n\n public void getMetricType(@NonNull retrofit2.Callback callback, @NonNull InventoryResponseBody body){\n MetricService service = retrofit.create(MetricService.class);\n Call call = service.getMetricType(body);\n call.enqueue(callback);\n }\n\n public void getOpreations(@NonNull AbstractCallback<List<Operation>> callback, Resource resource) {\n // TODO : after moving to retrofit complete\n }\n\n public void getOperationProperties(@NonNull AbstractCallback<List<OperationProperties>> callback, Operation operation, Resource resource) {\n // TODO : after moving to retrofit complete\n }\n\n public void getResourcesFromFeed(@NonNull retrofit2.Callback<List<Resource>> callback, @NonNull InventoryResponseBody body){\n\n TriggerService service = retrofit.create(TriggerService.class);\n Call call = service.getResourcesFromFeed(body);\n call.enqueue(callback);\n }\n\n\n public void getRecResourcesFromFeed(@NonNull retrofit2.Callback callback, Resource resource) {\n // TODO : after moving to retrofit complete\n }\n\n\n public void getMetricsFromFeed(@NonNull retrofit2.Callback<List<Resource>> callback, @NonNull InventoryResponseBody body) {\n MetricService service = retrofit.create(MetricService.class);\n Call call = service.getMetricFromFeed(body);\n call.enqueue(callback);\n }\n\n\n public void getMetrics(@NonNull Resource resource, @NonNull Callback<List<Metric>> callback){\n // TODO : after moving to retrofit complete\n }\n\n public void getMetricAvailabilityData(@NonNull Metric metric, long bucket, @NonNull Date startTime,\n @NonNull Date finishTime, @NonNull Callback<List<MetricAvailabilityBucket>> callback){\n Map<String, String> parameters = new HashMap<>();\n parameters.put(BackendPipes.Parameters.START, String.valueOf(startTime.getTime()));\n parameters.put(BackendPipes.Parameters.FINISH, String.valueOf(finishTime.getTime()));\n parameters.put(BackendPipes.Parameters.BUCKETS, String.valueOf(bucket));\n\n MetricService service = retrofit.create(MetricService.class);\n\n Log.d(\"BackendClient\",metric.getConfiguration().getType());\n Call call = null;\n\n if (metric.getConfiguration().getType().equalsIgnoreCase(\"AVAILABILITY\")) {\n call = service.getMetricAvailabilityData(metric.getId(), parameters);\n }\n call.enqueue(callback);\n }\n\n public void getMetricCounterData(@NonNull Metric metric, long bucket, @NonNull Date startTime,\n @NonNull Date finishTime, @NonNull Callback<List<MetricCounterBucket>> callback){\n Map<String, String> parameters = new HashMap<>();\n parameters.put(BackendPipes.Parameters.START, String.valueOf(startTime.getTime()));\n parameters.put(BackendPipes.Parameters.FINISH, String.valueOf(finishTime.getTime()));\n parameters.put(BackendPipes.Parameters.BUCKETS, String.valueOf(bucket));\n\n MetricService service = retrofit.create(MetricService.class);\n\n Log.d(\"BackendClient\",metric.getConfiguration().getType());\n Call call = null;\n\n if (metric.getConfiguration().getType().equalsIgnoreCase(\"COUNTER\")) {\n call = service.getMetricCounterData(metric.getId(), parameters);\n }\n call.enqueue(callback);\n }\n\n public void putTriggerThresholdCondition(String triggerId, String triggerMode, List<ThresholdCondition> body, @NonNull retrofit2.Callback<String> callback){\n TriggerService triggerService = retrofit.create(TriggerService.class);\n Call call = triggerService.setConditionsForTrigger(triggerId,triggerMode,body);\n call.enqueue(callback);\n }\n\n public void putTriggerAvailabilityCondition(String triggerId, String triggerMode, List<AvailabilityCondition> body, @NonNull retrofit2.Callback<String> callback){\n TriggerService triggerService = retrofit.create(TriggerService.class);\n Call call = triggerService.setConditionsForAvailabilityTrigger(triggerId,triggerMode,body);\n call.enqueue(callback);\n }\n\n\n public void getMetricGaugeData(@NonNull Metric metric, long bucket, @NonNull Date startTime,\n @NonNull Date finishTime, @NonNull Callback<List<MetricGaugeBucket>> callback){\n Map<String, String> parameters = new HashMap<>();\n parameters.put(BackendPipes.Parameters.START, String.valueOf(startTime.getTime()));\n parameters.put(BackendPipes.Parameters.FINISH, String.valueOf(finishTime.getTime()));\n parameters.put(BackendPipes.Parameters.BUCKETS, String.valueOf(bucket));\n\n MetricService service = retrofit.create(MetricService.class);\n\n Log.d(\"BackendClient\",metric.getConfiguration().getType());\n Call call = null;\n\n if (metric.getConfiguration().getType().equalsIgnoreCase(\"GAUGE\")) {\n call = service.getMetricGaugeData(metric.getId(), parameters);\n }\n call.enqueue(callback);\n }\n\n\n\n\n public void getTriggers(@NonNull Callback<List<Trigger>> callback) {\n TriggerService service = retrofit.create(TriggerService.class);\n Call call = service.get();\n call.enqueue(callback);\n\n\n }\n\n public void deleteTriggers(@NonNull Callback<Void> callback, String triggerId){\n TriggerService service = retrofit.create(TriggerService.class);\n Call call = service.deleteTrigger(triggerId);\n call.enqueue(callback);\n }\n\n\n public void configureAuthorization(String url, String username, String password) {\n HawkularApplication.setUpRetrofit(url, username, password);\n }\n\n\n public void authorize(Callback<List<Metric>> callback) {\n MetricService service = retrofit.create(MetricService.class);\n Call call = service.getAvailabilityMetrics();\n call.enqueue(callback);\n }\n\n public void deauthorize(Context context) {\n Preferences.of(context).authenticated().set(false);\n }\n\n public void configureAuthorization(Context context) {\n String url = Preferences.of(context).url().get();\n String username = Preferences.of(context).username().get();\n String password = Preferences.of(context).password().get();\n HawkularApplication.setUpRetrofit(url, username, password);\n }\n}",
"public final class Alert implements Parcelable {\n @RecordId\n @SerializedName(\"id\")\n private String id;\n\n @SerializedName(\"severity\")\n private String severity;\n\n @SerializedName(\"status\")\n private String status;\n\n @SerializedName(\"ctime\")\n private long ctime;\n\n @SerializedName(\"evalSets\")\n private List<List<AlertEvaluation>> evalSets;\n\n @SerializedName(\"notes\")\n private List<Note> notes;\n\n @SerializedName(\"trigger\")\n private Trigger trigger;\n\n @VisibleForTesting\n public Alert(@NonNull String id, long timestamp, @NonNull List<List<AlertEvaluation>> evaluations, @NonNull String severity,\n @NonNull String status, @NonNull List<Note> notes) {\n this.id = id;\n this.ctime = timestamp;\n this.evalSets = evaluations;\n this.severity = severity;\n this.status = status;\n this.notes = notes;\n }\n\n public String getId() {\n return id;\n }\n\n public void setId(String id) {\n this.id = id;\n }\n\n public String getSeverity() {\n return severity;\n }\n\n public String getStatus() {\n return status;\n }\n\n public long getTimestamp() {\n return ctime;\n }\n\n public List<List<AlertEvaluation>> getEvaluations() {\n return evalSets;\n }\n\n public Trigger getTrigger() {\n return trigger;\n }\n\n public List<Note> getNotes() {\n return notes;\n }\n\n public static Creator<Alert> CREATOR = new Creator<Alert>() {\n @Override\n public Alert createFromParcel(Parcel parcel) {\n return new Alert(parcel);\n }\n\n @Override\n public Alert[] newArray(int size) {\n return new Alert[size];\n }\n };\n\n private Alert(Parcel parcel) {\n this.id = parcel.readString();\n this.severity = parcel.readString();\n this.status = parcel.readString();\n this.ctime = parcel.readLong();\n\n evalSets = new ArrayList<>();\n notes = new ArrayList<>();\n\n parcel.readList(evalSets, Lister.class.getClassLoader());\n parcel.readList(notes, Note.class.getClassLoader());\n\n this.trigger = parcel.readParcelable(Trigger.class.getClassLoader());\n }\n\n @Override\n public void writeToParcel(Parcel parcel, int flags) {\n parcel.writeString(id);\n parcel.writeString(severity);\n parcel.writeString(status);\n parcel.writeLong(ctime);\n\n parcel.writeList(evalSets);\n parcel.writeList(notes);\n\n parcel.writeParcelable(trigger, flags);\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n public static class Lister extends ArrayList<AlertEvaluation> implements Parcelable {\n\n protected Lister(Parcel in) {\n this.addAll(in.readArrayList(AlertEvaluation.class.getClassLoader()));\n }\n\n public static final Creator<Lister> CREATOR = new Creator<Lister>() {\n @Override\n public Lister createFromParcel(Parcel in) {\n return new Lister(in);\n }\n\n @Override\n public Lister[] newArray(int size) {\n return new Lister[size];\n }\n };\n\n @Override public int describeContents() {\n return 0;\n }\n\n @Override public void writeToParcel(Parcel parcel, int flags) {\n parcel.writeList(this);\n }\n }\n\n}",
"public class Resource implements Parcelable\n{\n\n private String id;\n private List<Data> data = null;\n public final static Creator<Resource> CREATOR = new Creator<Resource>() {\n\n\n @SuppressWarnings({\n \"unchecked\"\n })\n public Resource createFromParcel(Parcel in) {\n Resource instance = new Resource();\n instance.id = ((String) in.readValue((String.class.getClassLoader())));\n in.readList(instance.data, (Data.class.getClassLoader()));\n return instance;\n }\n\n public Resource[] newArray(int size) {\n return (new Resource[size]);\n }\n\n }\n ;\n\n public String getId() {\n return id;\n }\n\n public void setId(String id) {\n this.id = id;\n }\n\n public List<Data> getData() {\n return data;\n }\n\n public void setData(List<Data> data) {\n this.data = data;\n }\n\n public void writeToParcel(Parcel dest, int flags) {\n dest.writeValue(id);\n dest.writeList(data);\n }\n\n public int describeContents() {\n return 0;\n }\n\n}",
"public class ErrorUtil {\n /**\n * This method is used to set error message to the EditText.\n * @param editText This is EditText.\n * @param errorMessage This is String resource to be shown as error.\n */\n\n public static void showError(Context context, EditText editText , @StringRes int errorMessage){\n editText.setError(context.getString(errorMessage));\n }\n\n /**\n * This method is used to show error message in a snackbar.\n * @param view This is the view to find a parent from.\n * @param errorMessage String resource to be shown as error.\n */\n\n public static void showError(View view, @StringRes int errorMessage){\n Snackbar.make(view,errorMessage,Snackbar.LENGTH_LONG).show();\n }\n\n /**\n * This method is used to show error message in layout corresponding to a fragment.\n */\n\n public static void showError(Fragment fragment, int animatorId, int viewId){\n ViewDirector.of(fragment).using(animatorId).show(viewId);\n }\n\n}"
] | import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import org.hawkular.client.android.HawkularApplication;
import org.hawkular.client.android.R;
import org.hawkular.client.android.activity.AlertDetailActivity;
import org.hawkular.client.android.adapter.AlertsAdapter;
import org.hawkular.client.android.backend.BackendClient;
import org.hawkular.client.android.backend.model.Alert;
import org.hawkular.client.android.backend.model.Resource;
import org.hawkular.client.android.backend.model.Trigger;
import org.hawkular.client.android.util.ColorSchemer;
import org.hawkular.client.android.util.ErrorUtil;
import org.hawkular.client.android.util.Fragments;
import org.hawkular.client.android.util.Intents;
import org.hawkular.client.android.util.Time;
import org.hawkular.client.android.util.ViewDirector;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PopupMenu;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import com.squareup.leakcanary.RefWatcher;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import icepick.Icepick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import timber.log.Timber; | /*
* Copyright 2015-2017 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* 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 org.hawkular.client.android.fragment;
/**
* Alerts fragment.
* <p/>
* Displays alerts as a list with menus allowing some alert-related actions, such as acknowledgement and resolving.
*/
public class AlertsFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener,
AlertsAdapter.AlertListener, SearchView.OnQueryTextListener {
@BindView(R.id.list) RecyclerView recyclerView;
@BindView(R.id.content) SwipeRefreshLayout swipeRefreshLayout;
public ArrayList<Trigger> triggers;
public ArrayList<Alert> alerts;
public ArrayList<Alert> alertsDump;
public boolean isActionPlus;
public int alertsTimeMenu;
public boolean isAlertsFragmentAvailable;
public SearchView searchView;
public String searchText;
public AlertsAdapter alertsAdapter;
private Unbinder unbinder;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle state) {
View view = inflater.inflate(R.layout.fragment_list, container, false);
unbinder = ButterKnife.bind(this, view);
return view;
}
@Override
public void onActivityCreated(Bundle state) {
super.onActivityCreated(state);
isAlertsFragmentAvailable = true;
setUpState(state);
setUpBindings();
setUpList();
setUpMenu();
isActionPlus = false;
setUpRefreshing();
setUpAlertsUi();
}
private void setUpState(Bundle state) {
Icepick.restoreInstanceState(this, state);
}
private void setUpBindings() {
ButterKnife.bind(this, getView());
}
private void setUpList() {
final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
recyclerView.setLayoutManager(linearLayoutManager);
}
private void setUpMenu() {
setHasOptionsMenu(true);
}
private void setUpRefreshing() {
swipeRefreshLayout.setOnRefreshListener(this);
swipeRefreshLayout.setColorSchemeResources(ColorSchemer.getScheme());
}
@OnClick(R.id.button_retry)
public void setUpAlertsUi() {
if (alerts == null) {
alertsTimeMenu = R.id.menu_time_hour;
setUpAlertsForced();
} else {
setUpAlerts(alertsDump);
}
}
private void setUpAlertsRefreshed() {
setUpAlerts();
}
private void setUpAlertsForced() {
showProgress();
setUpAlerts();
}
private void setUpAlerts() {
if(getResource() == null) { | BackendClient.of(this).getAlerts(getAlertsTime(), Time.current(), null, new AlertsCallback(this)); | 1 |
feldim2425/OC-Minecarts | src/main/java/mods/ocminecart/client/ClientProxy.java | [
"public class ManualRegister {\n\t\n\tpublic static void registermanual(){\n\t\tManual.addProvider(new ResourceContentProvider(OCMinecart.MODID, \"doc/\"));\n\t\tManual.addProvider(new ManualPathProvider());\n\t\t\n\t\tManual.addTab(new ItemStackTabIconRenderer(new ItemStack(ModItems.item_ComputerCartCase,1,0)), \"gui.\"+OCMinecart.MODID+\".manual\", OCMinecart.MODID+\"/%LANGUAGE%/index.md\");\n\t}\n}",
"public class ComputerCartRenderer extends Render {\n\t\n\tprivate static final double EMBLEM_BX = 0.5001;\n\tprivate static final double EMBLEM_X = 0.5002;\n\tprivate static final boolean MOD_RAILCRAFT = Loader.isModLoaded(\"Railcraft\");\n\t\n\tprivate static final ResourceLocation minecartTextures = new ResourceLocation(OCMinecart.MODID+\":textures/entity/computercart.png\");\n\tprivate static final ResourceLocation emblem_back = new ResourceLocation(OCMinecart.MODID+\":textures/entity/computercart_eback.png\");\n\tprotected ComputerCartModel modelMinecart = new ComputerCartModel();\n\t \n\t@Override\n\tpublic void doRender(Entity entity, double x, double y, double z, float p_76986_8_, float p_76986_9_) {\n\t\t\n\t\tComputerCart cart=(ComputerCart)entity;\n\t\t\n\t\tGL11.glPushMatrix();\n this.bindEntityTexture(cart);\n \n double cx= cart.lastTickPosX + (cart.posX - cart.lastTickPosX) * (double)p_76986_9_;\n double cy= cart.lastTickPosY + (cart.posY - cart.lastTickPosY) * (double)p_76986_9_;\n double cz= cart.lastTickPosZ + (cart.posZ - cart.lastTickPosZ) * (double)p_76986_9_;\n double d6 = 0.30000001192092896D;\n double ryaw = (cart.rotationYaw+360D)%360;\n \n double yaw=p_76986_8_;\n float pitch = cart.rotationPitch;\n \n Vec3 vec1 = cart.func_70495_a(cx,cy,cz, d6);\n Vec3 vec2 = cart.func_70495_a(cx,cy,cz, -d6);\n \n if(vec1!=null && vec2!=null){\n y += (vec1.yCoord + vec2.yCoord) / 2.0D - cy;\n Vec3 vec3 = vec2.addVector(-vec1.xCoord, -vec1.yCoord, -vec1.zCoord);\n if(vec3.lengthVector()!=0){\n \t yaw = (float)(Math.atan2(vec3.zCoord, vec3.xCoord) * 180.0D / Math.PI);\n \t pitch = (float)(Math.atan(vec3.yCoord) * 73.0D);\n }\n }\n \n yaw=(yaw+360D)%360D;\n ryaw=yaw-ryaw;\n if(ryaw<=-90 || ryaw>=90){\n \tyaw+=180D;\n \tpitch*=-1;\n }\n yaw=90F-yaw;\n \n GL11.glTranslatef((float)x, (float)y, (float)z);\n GL11.glRotated(yaw, 0.0D, 1.0D, 0.0D);\n GL11.glRotatef(-pitch, 1.0F, 0.0F, 0.0F);\n float rollamp = (float)cart.getRollingAmplitude() - p_76986_9_;\n float dmgamp = cart.getDamage() - p_76986_9_;\n \n if (dmgamp < 0.0F)\n \tdmgamp = 0.0F;\n\n if (rollamp > 0.0F)\n {\n GL11.glRotatef(MathHelper.sin(rollamp) * rollamp * dmgamp / 10.0F * (float)cart.getRollingDirection(), 0.0F, 0.0F, 1.0F);\n }\n \n GL11.glColor3f(1, 1, 1);\n GL11.glScalef(-1.0F, -1.0F, 1.0F);\n this.modelMinecart.renderTile(cart, 0.0625F);\n \n GL11.glRotated(90D, 0.0D, 1.0D, 0.0D);\n \n ResourceLocation emblem = (MOD_RAILCRAFT) ? cart.getEmblemIcon() : null;\n \n if(emblem!=null){\n \tTessellator tes = Tessellator.instance;\n \tMinecraft.getMinecraft().renderEngine.bindTexture(emblem_back);\t//Render the emblem Background.\n \n \ttes.startDrawingQuads();\n \ttes.addVertexWithUV((3D/16D)+(6D/16D), (5D/16D), -EMBLEM_BX, 0, 1);\n \ttes.addVertexWithUV((3D/16D)+(6D/16D) ,0, -EMBLEM_BX, 0, 0);\n \ttes.addVertexWithUV((3D/16D), 0, -EMBLEM_BX, 1, 0);\n \ttes.addVertexWithUV((3D/16D), (5D/16D), -EMBLEM_BX, 1, 1);\n \ttes.draw();\n \n \ttes.startDrawingQuads();\n \ttes.addVertexWithUV((3D/16D), (5D/16D), EMBLEM_BX, 1, 1);\n \ttes.addVertexWithUV((3D/16D), 0, EMBLEM_BX, 1, 0);\n \ttes.addVertexWithUV((3D/16D)+(6D/16D) ,0, EMBLEM_BX, 0, 0);\n \ttes.addVertexWithUV((3D/16D)+(6D/16D), (5D/16D), EMBLEM_BX, 0, 1);\n \ttes.draw();\n \t\n \tMinecraft.getMinecraft().renderEngine.bindTexture(emblem);\t//Render the actual emblem\n \t\n \ttes.startDrawingQuads();\n \ttes.addVertexWithUV((4D/16D)+(5D/16D), (5D/16D), -EMBLEM_X, 1, 1);\n \ttes.addVertexWithUV((4D/16D)+(5D/16D) ,0, -EMBLEM_X, 1, 0);\n \ttes.addVertexWithUV((4D/16D), 0, -EMBLEM_X, 0, 0);\n \ttes.addVertexWithUV((4D/16D), (5D/16D), -EMBLEM_X, 0, 1);\n \ttes.draw();\n \n \ttes.startDrawingQuads();\n \ttes.addVertexWithUV((4D/16D), (5D/16D), EMBLEM_X, 1, 1);\n \ttes.addVertexWithUV((4D/16D), 0, EMBLEM_X, 1, 0);\n \ttes.addVertexWithUV((4D/16D)+(5D/16D) ,0, EMBLEM_X, 0, 0);\n \ttes.addVertexWithUV((4D/16D)+(5D/16D), (5D/16D), EMBLEM_X, 0, 1);\n \ttes.draw();\n }\n \n GL11.glPopMatrix();\n\t}\n\n\n\t@Override\n\tprotected ResourceLocation getEntityTexture(Entity p_110775_1_) {\n\t\treturn minecartTextures;\n\t}\n\n}",
"public class ComputerCartItemRenderer implements IItemRenderer {\n\t\n\tResourceLocation texture = new ResourceLocation(OCMinecart.MODID+\":textures/entity/computercart.png\");\n\tComputerCartModel model = new ComputerCartModel();\n\t\n\t@Override\n\tpublic boolean handleRenderType(ItemStack item, ItemRenderType type) {\n\t\tswitch(type){\n\t\tcase ENTITY: \n\t\t\treturn true;\n\t\tcase EQUIPPED:\n\t\t\treturn true;\n\t\tcase EQUIPPED_FIRST_PERSON:\n\t\t\treturn true;\n\t\tcase INVENTORY:\n\t\t\treturn true;\n\t\tdefault:\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t@Override\n\tpublic boolean shouldUseRenderHelper(ItemRenderType type, ItemStack item, ItemRendererHelper helper) {\n\t\tif(type==ItemRenderType.ENTITY && (helper == ItemRendererHelper.ENTITY_BOBBING || helper == ItemRendererHelper.ENTITY_ROTATION)) return true;\n\t\telse if(type==ItemRenderType.INVENTORY && helper == ItemRendererHelper.INVENTORY_BLOCK) return true;\n\t\telse if(type==ItemRenderType.EQUIPPED_FIRST_PERSON && helper==ItemRendererHelper.BLOCK_3D) return true;\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic void renderItem(ItemRenderType type, ItemStack item, Object... data) {\n\t\tif(type==ItemRenderType.EQUIPPED){\n\t\t\tGL11.glPushMatrix();\n\t\t\tGL11.glRotatef(130.0F,1.0F, 0.0F, 0.0F);\n\t\t\tGL11.glRotatef(-20.0F, 0.0F, 0.0F, 1.0F);\n\t\t\tGL11.glRotatef(45.0F, 0.0F, 1.0F, 0.0F);\n\t\t\tGL11.glTranslatef(0.7F, 0F, 0F);\n\t\t\tGL11.glScaled(0.7, 0.7, 0.7);\n\t\t\tMinecraft.getMinecraft().renderEngine.bindTexture(texture);\n\t\t\tmodel.renderItem(0.0625F);\n\t\t\tGL11.glPopMatrix();\n\t\t}\n\t\telse if(type==ItemRenderType.ENTITY){\n\t\t\tGL11.glPushMatrix();\n\t\t\tGL11.glRotated(180F, 1F, 0, 0);\n\t\t\tGL11.glScaled(0.7, 0.7, 0.7);\n\t\t\tMinecraft.getMinecraft().renderEngine.bindTexture(texture);\n\t\t\tmodel.renderItem(0.0625F);\n\t\t\tGL11.glPopMatrix();\n\t\t}else if(type==ItemRenderType.INVENTORY){\n\t\t\tGL11.glPushMatrix();\n\t\t\tGL11.glRotatef(180.0F,1.0F, 0.0F, 0.0F);\n\t\t\tMinecraft.getMinecraft().renderEngine.bindTexture(texture);\n\t\t\tmodel.renderItem(0.0625F);\n\t\t\tGL11.glPopMatrix();\n\t\t}\n\t\telse if(type==ItemRenderType.EQUIPPED_FIRST_PERSON){\n\t\t\tGL11.glPushMatrix();\n\t\t\tGL11.glRotatef(180.0F,1.0F, 0.0F, 0.0F);\n\t\t\tGL11.glRotatef(-20.0F, 0.0F, 0.0F, 1.0F);\n\t\t\tGL11.glRotatef(45.0F, 0.0F, 1.0F, 0.0F);\n\t\t\tGL11.glTranslatef(1F, 0F, 0.5F);\n\t\t\tMinecraft.getMinecraft().renderEngine.bindTexture(texture);\n\t\t\tmodel.renderItem(0.0625F);\n\t\t\tGL11.glPopMatrix();\n\t\t}\n\t}\n\n}",
"public class CommonProxy {\n\t\n\t\n\tpublic void postInit() {\n\t}\n\n\tpublic void init() {\n\t\tNetworkRegistry.INSTANCE.registerGuiHandler(OCMinecart.instance, new GuiHandler());\n\t\t\n\t\tDisassembleRegister.register();\n\t\tAssembleRegister.register();\n\t\tCustomDriver.init();\n\t\tRecipes.init();\n\t\tRemoteExtenderRegister.register();\n\t\t\n\t\tif(Loader.isModLoaded(\"Waila\")) ModWaila.initWailaModule();\n\t\tif(Loader.isModLoaded(\"Railcraft\")) RailcraftEventHandler.init();\n\t}\n\n\tpublic void preInit() {\n\t\tEventHandler.initHandler();\n\t\t\n\t\tModNetwork.init();\n\t\tModItems.init();\n\t\tModBlocks.init();\n\t\t\n\t\tEntityRegistry.registerModEntity(ComputerCart.class, \"computercart\", 1,OCMinecart.instance, 80, 1, true);\n\t}\n\t\n}",
"public class ModItems {\n\t\n\tpublic static Item item_ComputerCart;\n\tpublic static Item item_ComputerCartCase;\n\tpublic static Item item_CartRemoteModule;\n\tpublic static Item item_CartRemoteAnalyzer;\n\tpublic static Item item_LinkingUpgrade;\n\t\n\tpublic static void init(){\n\t\titem_ComputerCart=new ItemComputerCart().setCreativeTab(OCMinecart.itemGroup);\n\t\titem_ComputerCartCase=new ComputerCartCase().setCreativeTab(OCMinecart.itemGroup);\n\t\titem_CartRemoteModule = new ItemCartRemoteModule().setCreativeTab(OCMinecart.itemGroup);\n\t\titem_CartRemoteAnalyzer = new ItemRemoteAnalyzer().setCreativeTab(OCMinecart.itemGroup);\n\t\titem_LinkingUpgrade = new ItemLinkingUpgrade().setCreativeTab(OCMinecart.itemGroup);\n\t\t\n\t\tGameRegistry.registerItem(item_ComputerCart,\"itemcomputercart\");\n\t\tGameRegistry.registerItem(item_ComputerCartCase,\"itemcomputercartcase\");\n\t\tGameRegistry.registerItem(item_CartRemoteModule,\"itemcartremotemodule\");\n\t\tGameRegistry.registerItem(item_CartRemoteAnalyzer,\"itemcartremoteanalyzer\");\n\t\tGameRegistry.registerItem(item_LinkingUpgrade,\"linkingupgrade\");\n\t}\n}",
"public class ComputerCart extends AdvCart implements MachineHost, Analyzable, ISyncEntity, IComputerCart{\n\t\n\tprivate final boolean isServer = FMLCommonHandler.instance().getEffectiveSide().isServer();\n\t\n\tprivate int tier = -1;\t//The tier of the cart\n\tprivate Machine machine; //The machine object\n\tprivate boolean firstupdate = true; //true if the update() function gets called the first time\n\tprivate boolean chDim = false;\t//true if the cart changing the dimension (Portal, AE2 Storage,...)\n\tprivate boolean isRun = false; //true if the machine is turned on;\n\tprivate ComputerCartController controller = new ComputerCartController(this); //The computer cart component\n\tprivate double startEnergy = -1; //Only used when placing the cart. Start energy stored in the item\n\tprivate int invsize = 0; //The current inventory size depending on the Inventory Upgrades\n\tprivate boolean onrail = false; // Store onRail from last tick to send a Signal\n\tprivate int selSlot = 0; //The index of the current selected slot\n\tprivate int selTank = 1; //The index of the current selected tank\n\tprivate Player player; //OC's fake player\n\tprivate String name; //name of the cart\n\t\n\tprivate int cRailX = 0;\t// Position of the connected Network Rail\n\tprivate int cRailY = 0;\n\tprivate int cRailZ = 0;\n\tprivate int cRailDim = 0;\n\tprivate boolean cRailCon = false; //True if the card is connected to a network rail\n\tprivate Node cRailNode = null; // This node will not get saved in NBT because it should automatic disconnect after restart; \n\t\n\t\n\tpublic ComponetInventory compinv = new ComponetInventory(this){\n\n\t\t@Override\n\t\tpublic int getSizeInventory() {\n\t\t\t// 9 Upgrade Slots; 3 Container Slots; 8 Component Slots(CPU,Memory,...); 3 Provided Container Slots (the Container Slots in the GUI)\n\t\t\treturn 23; \n\t\t}\n\t\t\n\t\t@Override\n\t\tprotected void onItemAdded(int slot, ItemStack stack){\n\t\t\tif(FMLCommonHandler.instance().getEffectiveSide().isServer()){\n\t\t\t\tsuper.onItemAdded(slot, stack);\n\t\t\t\t((ComputerCart) this.host).synchronizeComponentSlot(slot);\n\t\t\t}\n\t\t\t\n\t\t\tif(this.getSlotType(slot) == Slot.Floppy) Sound.play(this.host, \"floppy_insert\");\n\t\t\telse if(this.getSlotType(slot) == Slot.Upgrade && FMLCommonHandler.instance().getEffectiveSide().isServer()){\n\t\t\t\tItem drv = CustomDriver.driverFor(stack, this.host.getClass());\n\t\t\t\tif(drv instanceof Inventory){\n\t\t\t\t\t((ComputerCart)host).setInventorySpace(0);\n\t\t\t\t\t((ComputerCart)host).checkInventorySpace();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\t@Override\n\t\tprotected void onItemRemoved(int slot, ItemStack stack){\n\t\t\tsuper.onItemRemoved(slot, stack);\n\t\t\tif(FMLCommonHandler.instance().getEffectiveSide().isServer())\n\t\t\t\t((ComputerCart) this.host).synchronizeComponentSlot(slot);\n\t\t\t\n\t\t\tif(this.getSlotType(slot) == Slot.Floppy) Sound.play(this.host, \"floppy_eject\");\n\t\t\telse if(this.getSlotType(slot) == Slot.Upgrade && FMLCommonHandler.instance().getEffectiveSide().isServer()){\n\t\t\t\tItem drv = CustomDriver.driverFor(stack, this.host.getClass());\n\t\t\t\tif(drv instanceof Inventory){\n\t\t\t\t\t((ComputerCart)host).setInventorySpace(0);\n\t\t\t\t\t((ComputerCart)host).checkInventorySpace();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic void connectItemNode(Node node){\n\t\t\tsuper.connectItemNode(node);\n\t\t\tif(node!=null){\n\t\t\t\tif(node.host() instanceof TextBuffer){\n\t\t\t\t\tfor(int i=0;i<this.getSizeInventory();i+=1){\n\t\t\t\t\t\tif((this.getSlotComponent(i) instanceof Keyboard) && this.getSlotComponent(i).node()!=null)\n\t\t\t\t\t\t\tnode.connect(this.getSlotComponent(i).node());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if(node.host() instanceof Keyboard){\n\t\t\t\t\tfor(int i=0;i<this.getSizeInventory();i+=1){\n\t\t\t\t\t\tif((this.getSlotComponent(i) instanceof TextBuffer) && this.getSlotComponent(i).node()!=null)\n\t\t\t\t\t\t\tnode.connect(this.getSlotComponent(i).node());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t};\n\t\n\tpublic ComputercartInventory maininv = new ComputercartInventory(this);\n\t\n\tpublic MultiTank tanks = new MultiTank(){\n\t\t@Override\n\t\tpublic int tankCount() {\n\t\t\treturn ComputerCart.this.tankcount();\n\t\t}\n\n\t\t@Override\n\t\tpublic IFluidTank getFluidTank(int index) {\n\t\t\treturn ComputerCart.this.getTank(index);\n\t\t}\n\t};\n\t\n\tpublic ComputerCart(World p_i1712_1_) {\n\t\tsuper(p_i1712_1_);\n\t}\n\n\tpublic ComputerCart(World w, double x, double y, double z, ComputerCartData data) {\n\t\tsuper(w,x,y,z);\n\t\tif(data==null){\n\t\t\tthis.setDead();\n\t\t\tdata=new ComputerCartData();\n\t\t}\n\t\tthis.tier=data.getTier();\n\t\tthis.startEnergy=data.getEnergy();\n\t\tthis.setEmblem(data.getEmblem());\n\t\t\n\t\tIterator<Entry<Integer, ItemStack>> list = data.getComponents().entrySet().iterator();\n\t\twhile(list.hasNext()){\n\t\t\tEntry<Integer, ItemStack> e = list.next();\n\t\t\tif(e.getKey() < this.compinv.getSizeInventory() && e.getValue() != null){\n\t\t\t\tcompinv.updateSlot(e.getKey(), e.getValue());\n\t\t\t}\n\t\t}\n\t\t\n\t\tthis.checkInventorySpace();\n\t}\n\t\n\t@Override\n\tprotected void entityInit(){\n\t\tsuper.entityInit();\n\t\t\n\t\tthis.dataWatcher.addObject(24, 0x0000FF);\n\t\t\n\t\tthis.machine = li.cil.oc.api.Machine.create(this);\n\t\tif(FMLCommonHandler.instance().getEffectiveSide().isServer()){\n\t\t\tthis.machine.setCostPerTick(Settings.ComputerCartEnergyUse);\n\t\t\t((Connector) this.machine.node()).setLocalBufferSize(Settings.ComputerCartEnergyCap);\n\t\t}\n\t\t\n\t}\n\t\n\t/*------NBT/Sync-Stuff-------*/\n\t@Override\n\tpublic void readEntityFromNBT(NBTTagCompound nbt){\n\t\tsuper.readEntityFromNBT(nbt);\n\t\t\n\t\tif(nbt.hasKey(\"components\")) this.compinv.readNBT((NBTTagList) nbt.getTag(\"components\"));\n\t\tif(nbt.hasKey(\"controller\")) this.controller.load(nbt.getCompoundTag(\"controller\"));\n\t\tif(nbt.hasKey(\"inventory\")) this.maininv.readFromNBT((NBTTagList) nbt.getTag(\"inventory\"));\n\t\tif(nbt.hasKey(\"netrail\")){\n\t\t\tNBTTagCompound netrail = nbt.getCompoundTag(\"netrail\");\n\t\t\tthis.cRailCon=true;\n\t\t\tthis.cRailX = netrail.getInteger(\"posX\");\n\t\t\tthis.cRailY = netrail.getInteger(\"posY\");\n\t\t\tthis.cRailZ = netrail.getInteger(\"posZ\");\n\t\t\tthis.cRailDim = netrail.getInteger(\"posDim\");\n\t\t}\n\t\tif(nbt.hasKey(\"settings\")){\n\t\t\tNBTTagCompound set = nbt.getCompoundTag(\"settings\");\n\t\t\tif(set.hasKey(\"lightcolor\")) this.setLightColor(set.getInteger(\"lightcolor\"));\n\t\t\tif(set.hasKey(\"selectedslot\")) this.selSlot = set.getInteger(\"selectedslot\");\n\t\t\tif(set.hasKey(\"selectedtank\")) this.selTank = set.getInteger(\"selectedtank\");\n\t\t\tif(set.hasKey(\"tier\")) this.tier = set.getInteger(\"tier\");\n\t\t}\n\t\t\n\t\t\n\t\tthis.machine.onHostChanged();\n\t\tif(nbt.hasKey(\"machine\"))this.machine.load(nbt.getCompoundTag(\"machine\"));\n\t\t\n\t\tthis.connectNetwork();\n\t\tthis.checkInventorySpace();\n\t}\n\t\n\t@Override\n\tpublic void writeEntityToNBT(NBTTagCompound nbt){\n\t\tif(!this.isServer) return;\n\t\t\n\t\tsuper.writeEntityToNBT(nbt);\n\t\t\n\t\tthis.compinv.saveComponents();\n\t\t\n\t\tnbt.setTag(\"components\", this.compinv.writeNTB());\n\t\tnbt.setTag(\"inventory\", this.maininv.writeToNBT());\n\t\t\n\t\t//Controller tag\n\t\tNBTTagCompound controller = new NBTTagCompound();\n\t\tthis.controller.save(controller);\n\t\tnbt.setTag(\"controller\", controller);\n\t\t\n\t\t//Data about the connected rail\n\t\tif(this.cRailCon){\n\t\t\tNBTTagCompound netrail = new NBTTagCompound();\n\t\t\tnetrail.setInteger(\"posX\", this.cRailX);\n\t\t\tnetrail.setInteger(\"posY\", this.cRailY);\n\t\t\tnetrail.setInteger(\"posZ\", this.cRailZ);\n\t\t\tnetrail.setInteger(\"posDim\", this.cRailDim);\n\t\t\tnbt.setTag(\"netrail\", netrail);\n\t\t}\n\t\telse if(nbt.hasKey(\"netrail\")) nbt.removeTag(\"netrail\");\n\t\t\n\t\t//Some additional values like light color, selected Slot, ...\n\t\tNBTTagCompound set = new NBTTagCompound();\n\t\tset.setInteger(\"lightcolor\", this.getLightColor());\n\t\tset.setInteger(\"selectedslot\",this.selSlot);\n\t\tset.setInteger(\"selectedtank\",this.selTank);\n\t\tset.setInteger(\"tier\", this.tier);\n\t\tnbt.setTag(\"settings\", set);\n\t\t\n\t\tNBTTagCompound machine = new NBTTagCompound();\n\t\tthis.machine.save(machine);\n\t\tnbt.setTag(\"machine\", machine);\n\t}\n\t\n\t@Override\n\tpublic void writeSyncData(NBTTagCompound nbt) {\n\t\tthis.compinv.saveComponents();\n\t\tnbt.setTag(\"components\", this.compinv.writeNTB());\n\t\tnbt.setBoolean(\"isRunning\", this.isRun);\n\t}\n\n\t@Override\n\tpublic void readSyncData(NBTTagCompound nbt) {\n\t\tthis.compinv.readNBT((NBTTagList) nbt.getTag(\"components\"));\n\t\tthis.isRun = nbt.getBoolean(\"isRunning\");\n\t\tthis.compinv.connectComponents();\n\t}\n\t\n\t/*--------------------*/\n\t\n\t/*------Interaction-------*/\n\t\n\tprotected void checkInventorySpace(){\n\t\tfor(int i=0;i<this.compinv.getSizeInventory();i+=1){\n\t\t\tif(this.compinv.getStackInSlot(i)!=null){\n\t\t\t\tItemStack stack = this.compinv.getStackInSlot(i);\n\t\t\t\tItem drv = CustomDriver.driverFor(stack, this.getClass());\n\t\t\t\tif(drv instanceof Inventory && this.invsize<this.maininv.getMaxSizeInventory()){\n\t\t\t\t\tthis.invsize = this.invsize+((Inventory)drv).inventoryCapacity(stack);\n\t\t\t\t\tif(this.invsize>this.maininv.getMaxSizeInventory()) this.invsize = this.maininv.getMaxSizeInventory();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tIterable<ItemStack> over = this.maininv.removeOverflowItems(this.invsize);\n\t\tItemUtil.dropItemList(over, this.worldObj, this.posX, this.posY, this.posZ, true);\n\t}\n\t\n\t@Override\n\tpublic void onUpdate(){\n\t\tsuper.onUpdate();\n\t\t//Only executed at the first function call\n\t\tif(this.firstupdate){\n\t\t\tthis.firstupdate=false;\n\t\t\t//Request a entity data sync\n\t\t\tif(this.worldObj.isRemote) ModNetwork.channel.sendToServer(new EntitySyncRequest(this));\n\t\t\telse{\n\t\t\t\tif(this.startEnergy > 0) ((Connector)this.machine.node()).changeBuffer(this.startEnergy); //Give start energy\n\t\t\t\tif(this.machine.node().network()==null){\n\t\t\t\t\tthis.connectNetwork(); //Connect all nodes (Components & Controller)\n\t\t\t\t}\n\n\t\t\t\tthis.onrail = this.onRail(); //Update onRail Value\n\t\t\t\tthis.player = new li.cil.oc.server.agent.Player(this); //Set the fake Player\n\t\t\t}\n\t\t}\n\t\t\n\t\tif(!this.worldObj.isRemote){\n\t\t\t//Update the machine and the Components\n\t\t\tif(this.isRun){\n\t\t\t\tthis.machine.update();\n\t\t\t\tthis.compinv.updateComponents();\n\t\t\t}\n\t\t\t//Check if the machine state has changed.\n\t\t\tif(this.isRun != this.machine.isRunning()){\n\t\t\t\tthis.isRun=this.machine.isRunning();\n\t\t\t\tModNetwork.sendToNearPlayers(new UpdateRunning(this,this.isRun), this.posX, this.posY, this.posZ, this.worldObj);\n\t\t\t\tif(!this.isRun) this.setEngine(0);\n\t\t\t}\n\t\t\t//Consume energy for the Engine\n\t\t\tif(this.isEngineActive()){\n\t\t\t\tif(!((Connector)this.machine.node()).tryChangeBuffer(-1.0 * this.getEngine() * Settings.ComputerCartEngineUse))\n\t\t\t\t{\n\t\t\t\t\tthis.machine.signal(\"engine_failed\",this.getEngine());\n\t\t\t\t\tthis.setEngine(0);\n\t\t\t\t}\n\t\t\t}\n\t\t\t//Check if the cart is on a Track\n\t\t\tif(this.onrail != this.onRail())\n\t\t\t{\n\t\t\t\tthis.onrail = !this.onrail;\n\t\t\t\tthis.machine.signal(\"track_state\",this.onrail);\n\t\t\t}\n\t\t\t//Give the cart energy if it is a creative cart\n\t\t\tif(this.tier==3)((Connector)this.machine.node()).changeBuffer(Integer.MAX_VALUE);\n\t\t\t//Connect / Disconnect a network rail\n\t\t\tthis.checkRailConnection();\n\t\t}\n\t}\n\t\n\tprivate void connectNetwork(){\n\t\tAPI.network.joinNewNetwork(machine.node());\n\t\tthis.compinv.connectComponents();\n\t\tthis.machine.node().connect(this.controller.node());\n\t}\n\t\n\t@Override\n\tpublic void setDead(){\n\t\tsuper.setDead();\n\t\tif (!this.worldObj.isRemote && !this.chDim) {\n\t\t\tthis.machine.stop();\n\t\t\tthis.machine.node().remove();\n\t\t\tthis.controller.node().remove();\n\t\t\tthis.compinv.disconnectComponents();\n\t\t\tthis.compinv.saveComponents();\n\t\t\tthis.compinv.removeTagsForDrop();\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic void killMinecart(DamageSource dms){\n\t\tsuper.killMinecart(dms);\n\t\tList<ItemStack> drop = new ArrayList<ItemStack>();\n\t\tfor(int i=20;i<23;i+=1){\n\t\t\tif(compinv.getStackInSlot(i)!=null) drop.add(compinv.getStackInSlot(i));\n\t\t}\n\t\tIterator<ItemStack> minv = this.maininv.removeOverflowItems(0).iterator();\n\t\twhile(minv.hasNext()) drop.add(minv.next());\n\t\tItemUtil.dropItemList(drop, this.worldObj, this.posX, this.posY, this.posZ,true);\n\t\tthis.setDamage(Float.MAX_VALUE); //Sometimes the cart stay alive this should fix it.\n\t}\n\t\n\t@Override\n\tpublic boolean interactFirst(EntityPlayer p){\n\t\tItemStack refMan = API.items.get(\"manual\").createItemStack(1);\n\t\tboolean openwiki = p.getHeldItem()!=null && p.isSneaking() && p.getHeldItem().getItem() == refMan.getItem() && p.getHeldItem().getItemDamage() == refMan.getItemDamage();\n\t\t\n\t\tif(Loader.isModLoaded(\"Railcraft\") && RailcraftUtils.isUsingChrowbar(p)) return true;\n\t\t\n\t\tif(this.worldObj.isRemote && openwiki){\n\t\t\tManual.navigate(OCMinecart.MODID+\"/%LANGUAGE%/item/cart.md\");\n\t\t\tManual.openFor(p);\n\t\t}\n\t\telse if(!this.worldObj.isRemote && !openwiki){\n\t\t\tp.openGui(OCMinecart.instance, 1, this.worldObj, this.getEntityId(), -10, 0);\n\t\t}\n\t\telse if(this.worldObj.isRemote && !openwiki){\n\t\t\tp.swingItem();\n\t\t}\n\t\treturn true;\n\t}\n\t\n\t@Override\n\tpublic Node[] onAnalyze(EntityPlayer player, int side, float hitX, float hitY, float hitZ) {\n\t\treturn new Node[]{this.machine.node()};\n\t}\n\t\n\tprivate void checkRailConnection(){\n\t\t//If the cart isn't connected check for a new connection\n\t\tif(!this.cRailCon && this.onRail() && (this.worldObj.getBlock(MathHelper.floor_double(this.posX), MathHelper.floor_double(this.posY), MathHelper.floor_double(this.posZ)) instanceof INetRail)){\n\t\t\tint x = MathHelper.floor_double(this.posX);\n\t\t\tint y = MathHelper.floor_double(this.posY);\n\t\t\tint z = MathHelper.floor_double(this.posZ);\n\t\t\tINetRail netrail = (INetRail) this.worldObj.getBlock(x,y,z);\n\t\t\tif(netrail.isValid(this.worldObj, x, y, z, this) && netrail.getResponseEnvironment(this.worldObj, x, y, z) != null){\n\t\t\t\tthis.cRailX = MathHelper.floor_double(this.posX);\n\t\t\t\tthis.cRailY = MathHelper.floor_double(this.posY);\n\t\t\t\tthis.cRailZ = MathHelper.floor_double(this.posZ);\n\t\t\t\tthis.cRailDim = this.worldObj.provider.dimensionId;\n\t\t\t\tthis.cRailCon = true;\n\t\t\t}\n\t\t}\n\t\t//If the cart is connected to a rail check if the connection is still valid and connect or disconnect\n\t\tif(this.cRailCon){\n\t\t\tWorld w = DimensionManager.getWorld(this.cRailDim);\n\t\t\tif( w.getBlock(this.cRailX,this.cRailY,this.cRailZ) instanceof INetRail){\n\t\t\t\tINetRail netrail = (INetRail) w.getBlock(this.cRailX,this.cRailY,this.cRailZ);\n\t\t\t\t//Connect a new network Rail\n\t\t\t\tif(netrail.isValid(w, this.cRailX, this.cRailY, this.cRailZ, this) && netrail.getResponseEnvironment(w, this.cRailX, this.cRailY, this.cRailZ)!=null){\n\t\t\t\t\tNode railnode = netrail.getResponseEnvironment(w, this.cRailX, this.cRailY, this.cRailZ).node();\n\t\t\t\t\tif(!this.machine.node().canBeReachedFrom(railnode)){\n\t\t\t\t\t\tthis.machine.node().connect(railnode);\n\t\t\t\t\t\tthis.cRailNode = railnode;\n\t\t\t\t\t\tthis.machine.signal(\"network_rail\", true);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t//Disconnect when the cart leaves a network rail\n\t\t\t\telse if(netrail.getResponseEnvironment(w, this.cRailX, this.cRailY, this.cRailZ)!=null){\n\t\t\t\t\tNode railnode = netrail.getResponseEnvironment(w, this.cRailX, this.cRailY, this.cRailZ).node();\n\t\t\t\t\tif(this.machine.node().canBeReachedFrom(railnode)){\n\t\t\t\t\t\tthis.machine.node().disconnect(railnode);\n\t\t\t\t\t\tthis.cRailCon=false;\n\t\t\t\t\t\tthis.cRailNode = null;\n\t\t\t\t\t\tthis.machine.signal(\"network_rail\", false);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t//Disconnect if the network rail is not there\n\t\t\telse{\n\t\t\t\tif(this.cRailNode!=null && this.machine.node().canBeReachedFrom(this.cRailNode)){\n\t\t\t\t\tthis.machine.node().disconnect(this.cRailNode);\n\t\t\t\t\tthis.cRailNode = null;\n\t\t\t\t\tthis.machine.signal(\"network_rail\", false);\n\t\t\t\t}\n\t\t\t\tthis.cRailCon=false;\n\t\t\t}\t\n\t\t}\n\t}\n\t\n\t/*------------------------*/\n\t\n\t/*-----Minecart/Entity-Stuff-------*/\n\t@Override\n\tpublic int getMinecartType() { return -1; }\n\n\tpublic static EntityMinecart create(World w, double x, double y, double z, ComputerCartData data) { return new ComputerCart(w, x, y, z, data); }\n\t\n\t@Override\n\tpublic ItemStack getCartItem(){\n\t\tItemStack stack = new ItemStack(ModItems.item_ComputerCart);\n\t\t\n\t\t\n\t\tMap<Integer,ItemStack> components = new HashMap<Integer,ItemStack>();\n\t\tfor(int i=0;i<20;i+=1){\n\t\t\tif(compinv.getStackInSlot(i)!=null)\n\t\t\t\tcomponents.put(i, compinv.getStackInSlot(i));\n\t\t}\n\t\t\n\t\tComputerCartData data = new ComputerCartData();\n\t\tdata.setEnergy(((Connector)this.machine().node()).localBuffer());\n\t\tdata.setTier(this.tier);\n\t\tdata.setComponents(components);\n\t\tItemComputerCart.setData(stack, data);\n\t\t\n\t\treturn stack;\n\t}\n\t\n\t@Override\n\tpublic void travelToDimension(int dim){\n\t\ttry{\n\t\t\tthis.chDim = true;\n\t\t\tsuper.travelToDimension(dim);\n\t\t}\n\t\tfinally{\n\t\t\tthis.chDim = false;\n\t\t\tthis.setDead();\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic boolean hasCustomInventoryName(){ return true; } // Drop Item on Kill when Player is in Creative Mode\n\t@Override\n\tpublic ItemStack getPickedResult(MovingObjectPosition target){ return null; } \n\t\n\t/*----------------------------------*/\n\t\n\t/*--------MachineHost--------*/\n\t@Override\n\tpublic World world() {\n\t\treturn this.worldObj;\n\t}\n\n\t@Override\n\tpublic double xPosition() {\n\t\treturn this.posX;\n\t}\n\n\t@Override\n\tpublic double yPosition() {\n\t\treturn this.posY;\n\t}\n\n\t@Override\n\tpublic double zPosition() {\n\t\treturn this.posZ;\n\t}\n\n\t@Override\n\tpublic void markChanged() {}\n\n\t@Override\n\tpublic Machine machine() {\n\t\treturn this.machine;\n\t}\n\n\t@Override\n\tpublic Iterable<ItemStack> internalComponents() {\n\t\tArrayList<ItemStack> components = new ArrayList<ItemStack>();\n\t\tfor(int i=0;i<compinv.getSizeInventory();i+=1){\n\t\t\tif(compinv.getStackInSlot(i)!=null && this.compinv.isComponentSlot(i, compinv.getStackInSlot(i)))\n\t\t\t\tcomponents.add(compinv.getStackInSlot(i));\n\t\t}\n\t\treturn components;\n\t}\n\n\t@Override\n\tpublic int componentSlot(String address) {\n\t\tfor(int i=0;i<this.compinv.getSizeInventory();i+=1){\n\t\t\tManagedEnvironment env = this.compinv.getSlotComponent(i);\n\t\t\tif(env != null && env.node()!=null && env.node().address() == address) return i;\n\t\t}\n\t\treturn -1;\n\t}\n\n\t@Override\n\tpublic void onMachineConnect(Node node) {}\n\n\t@Override\n\tpublic void onMachineDisconnect(Node node) {}\n\n\t@Override\n\tpublic IInventory equipmentInventory() { return null; }\n\n\t@Override\n\tpublic IInventory mainInventory() {\n\t\treturn this.maininv;\n\t}\n\n\t@Override\n\tpublic MultiTank tank() {\n\t\treturn this.tanks;\n\t}\n\n\t@Override\n\tpublic int selectedSlot() {\n\t\treturn this.selSlot;\n\t}\n\n\t@Override\n\tpublic void setSelectedSlot(int index) {\n\t\tif(index<this.maininv.getSizeInventory())\n\t\t\tthis.selSlot=index;\n\t}\n\n\t@Override\n\tpublic int selectedTank() {\n\t\treturn this.selTank;\n\t}\n\n\t@Override\n\tpublic void setSelectedTank(int index) {\n\t\tif(index<=this.tank().tankCount())\n\t\t\tthis.selTank=index;\n\t}\n\n\t@Override\n\tpublic EntityPlayer player() {\n\t\tthis.player.updatePositionAndRotation(player, this.facing(), this.facing());\n\t\treturn this.player;\n\t}\n\n\t@Override\n\tpublic String name() {\n\t\treturn this.func_95999_t();\n\t}\n\n\t@Override\n\tpublic void setName(String name) {\n\t\tthis.setMinecartName(name);\n\t}\n\n\t@Override\n\tpublic String ownerName() {\n\t\treturn li.cil.oc.Settings.get().fakePlayerName();\n\t}\n\n\t@Override\n\tpublic UUID ownerUUID() {\n\t\treturn li.cil.oc.Settings.get().fakePlayerProfile().getId();\n\t}\n\n\t@Override\n\tpublic ForgeDirection facing() {\n\t\tForgeDirection res = RotationHelper.directionFromYaw(this.rotationYaw-90D); //Minecarts seem to look at the right side\n\t\treturn res;\n\t}\n\n\t@Override\n\tpublic ForgeDirection toGlobal(ForgeDirection value) {\n\t\treturn RotationHelper.calcGlobalDirection(value, this.facing());\n\t}\n\n\t@Override\n\tpublic ForgeDirection toLocal(ForgeDirection value) {\n\t\treturn RotationHelper.calcLocalDirection(value, this.facing());\n\t}\n\n\t@Override\n\tpublic Node node() {\n\t\treturn this.machine.node();\n\t}\n\n\t@Override\n\tpublic void onConnect(Node node) {}\n\n\t@Override\n\tpublic void onDisconnect(Node node) {}\n\n\t@Override\n\tpublic void onMessage(Message message) {}\n\n\t@Override\n\tpublic int tier() {\n\t\treturn this.tier;\n\t}\n\t/*-----------------------------*/\n\t\n\t/*-------Inventory--------*/\n\n\t@Override\n\tpublic int getSizeInventory() {\n\t\treturn this.maininv.getSizeInventory();\n\t}\n\n\t@Override\n\tpublic ItemStack getStackInSlot(int slot) {\n\t\treturn this.maininv.getStackInSlot(slot);\n\t}\n\n\t@Override\n\tpublic ItemStack decrStackSize(int slot, int number) {\n\t\treturn this.maininv.decrStackSize(slot, number);\n\t}\n\n\t@Override\n\tpublic ItemStack getStackInSlotOnClosing(int slot) {\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic void setInventorySlotContents(int slot, ItemStack stack) {\n\t\tthis.maininv.setInventorySlotContents(slot, stack);\n\t}\n\n\t@Override\n\tpublic String getInventoryName() {\n\t\treturn \"inventory.\"+OCMinecart.MODID+\".computercart\";\n\t}\n\n\t@Override\n\tpublic int getInventoryStackLimit() {\n\t\treturn this.maininv.getInventoryStackLimit();\n\t}\n\n\t@Override\n\tpublic void markDirty() {}\n\n\t@Override\n\tpublic boolean isUseableByPlayer(EntityPlayer player) {\n\t\treturn player.getDistanceSqToEntity(this)<=64 && !this.isDead;\n\t}\n\n\t@Override\n\tpublic void openInventory() {}\n\t@Override\n\tpublic void closeInventory() {}\n\n\t@Override\n\tpublic boolean isItemValidForSlot(int slot, ItemStack stack) {\n\t\treturn this.maininv.isItemValidForSlot(slot, stack);\n\t}\n\t\n/*------Tanks-------*/\n\t\n\tpublic int tankcount(){\n\t\tint c = 0;\n\t\tfor(int i=0;i<this.compinv.getSizeInventory();i+=1){\n\t\t\tif(this.compinv.getSlotComponent(i) instanceof IFluidTank){\n\t\t\t\tc+=1;\n\t\t\t}\n\t\t}\n\t\treturn c;\n\t}\n\t\n\tpublic IFluidTank getTank(int index){\n\t\tint c = 0;\n\t\tfor(int i=0;i<this.compinv.getSizeInventory();i+=1){\n\t\t\tif(this.compinv.getSlotComponent(i) instanceof IFluidTank){\n\t\t\t\tc+=1;\n\t\t\t\tif(c==index) return (IFluidTank) this.compinv.getSlotComponent(i);\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\t\n\t@Override\n\tpublic int fill(ForgeDirection from, FluidStack resource, boolean doFill) {\n\t\treturn 0;\n\t}\n\n\t@Override\n\tpublic FluidStack drain(ForgeDirection from, FluidStack resource, boolean doDrain) {\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic FluidStack drain(ForgeDirection from, int maxDrain, boolean doDrain) {\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic boolean canFill(ForgeDirection from, Fluid fluid) {\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic boolean canDrain(ForgeDirection from, Fluid fluid) {\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic FluidTankInfo[] getTankInfo(ForgeDirection from) {\n\t\treturn new FluidTankInfo[]{};\n\t}\n\t/*--------------------*/\n\n\t/*-----Component-Inv------*/\n\t@Override\n\tpublic int componentCount() {\n\t\tint count = 0;\n\t\tIterator<ManagedEnvironment> list=this.compinv.getComponents().iterator();\n\t\twhile(list.hasNext()){\n\t\t\tcount+=1;\n\t\t\tlist.next();\n\t\t}\n\t\treturn count;\n\t}\n\n\t@Override\n\tpublic Environment getComponentInSlot(int index) {\n\t\tif(index>=this.compinv.getSizeInventory()) return null;\n\t\treturn this.compinv.getSlotComponent(index);\n\t}\n\n\t@Override\n\tpublic void synchronizeComponentSlot(int slot) {\n\t\tif(!this.worldObj.isRemote)\n\t\t\tModNetwork.sendToNearPlayers(new ComputercartInventoryUpdate(this, slot, this.compinv.getStackInSlot(slot)), this.posX, this.posY, this.posZ, this.worldObj);\n\t}\n\t\n\t/*---------Railcraft---------*/\n\t\n\tpublic void lockdown(boolean lock){\n\t\tsuper.lockdown(lock);\n\t\tif(lock != this.isLocked())\n\t\t\tthis.machine.signal(\"cart_lockdown\", lock);\n\t}\n\n\t/*------Setters & Getters-----*/\n\tpublic ComponetInventory getCompinv() {\n\t\treturn this.compinv;\n\t}\n\t\n\tpublic void setRunning(boolean newVal) {\n\t\tif(this.worldObj.isRemote) this.isRun=newVal;\n\t\telse{\n\t\t\tif(newVal) this.machine.start();\n\t\t\telse this.machine.stop();\n\t\t}\n\t}\n\t\n\tpublic boolean getRunning() {\n\t\treturn this.isRun;\n\t}\n\n\tpublic double getCurEnergy() {\n\t\tif(!this.worldObj.isRemote) return ((Connector)this.machine.node()).globalBuffer();\n\t\treturn -1;\n\t}\n\t\n\tpublic double getMaxEnergy() {\n\t\tif(!this.worldObj.isRemote) return ((Connector)this.machine.node()).globalBufferSize();\n\t\treturn -1;\n\t}\n\t\n\tprotected void setInventorySpace(int invsize) { this.invsize = invsize; }\n\tpublic int getInventorySpace() { return this.invsize; }\n\t\n\tpublic boolean getBrakeState(){ return this.getBrake(); }\n\tpublic void setBrakeState(boolean state){ this.setBrake(state);}\n\t\n\tpublic double getEngineState(){ return this.getEngine(); }\n\tpublic void setEngineState(double speed){ this.setEngine(speed); }\n\t\n\tpublic int getLightColor(){ return this.dataWatcher.getWatchableObjectInt(24); }\n\tpublic void setLightColor(int color){ this.dataWatcher.updateObject(24, color);}\n\t\n\tpublic boolean hasNetRail(){ return this.cRailCon; }\n\n\t@Override\n\tprotected double addEnergy(double amount, boolean simulate) {\n\t\tConnector n = ((Connector)this.machine.node());\n\t\tdouble max = Math.min(n.globalBufferSize() - n.globalBuffer(), amount);\n\t\tif(!simulate){\n\t\t\tmax -= n.changeBuffer(max);\n\t\t}\n\t\treturn max;\n\t}\n}"
] | import cpw.mods.fml.client.registry.RenderingRegistry;
import mods.ocminecart.client.manual.ManualRegister;
import mods.ocminecart.client.renderer.entity.ComputerCartRenderer;
import mods.ocminecart.client.renderer.item.ComputerCartItemRenderer;
import mods.ocminecart.common.CommonProxy;
import mods.ocminecart.common.items.ModItems;
import mods.ocminecart.common.minecart.ComputerCart;
import net.minecraftforge.client.MinecraftForgeClient; | package mods.ocminecart.client;
public class ClientProxy extends CommonProxy {
public void init(){
super.init();
RenderingRegistry.registerEntityRenderingHandler(ComputerCart.class, new ComputerCartRenderer()); | MinecraftForgeClient.registerItemRenderer(ModItems.item_ComputerCart, new ComputerCartItemRenderer()); | 4 |
pakoito/SongkickInterview | app/src/main/java/com/pacoworks/dereference/screens/songkicklist/SongkickListPresenter.java | [
"public abstract class ZimplBasePresenter<T extends IUi, U extends ZimpleBaseState> {\n private final Class<U> stateClass;\n\n private final List<Subscription> pauseSubscriptions = new ArrayList<>();\n\n private final List<Subscription> destroySubscriptions = new ArrayList<>();\n\n @Inject\n @Getter(AccessLevel.PROTECTED)\n Gson gson;\n\n @Getter(AccessLevel.PROTECTED)\n private T ui;\n\n @Getter(AccessLevel.PROTECTED)\n private U state;\n\n public ZimplBasePresenter(Class<U> stateClass) {\n this.stateClass = stateClass;\n }\n\n // DEPENDENCY BINDING METHODS\n final void bindUi(T activity) {\n ui = activity;\n }\n\n final void unbindUi() {\n ui = null;\n }\n\n final void restoreState(String restoredState) {\n if (restoredState == null || restoredState.isEmpty()) {\n state = createNewState();\n } else {\n state = gson.fromJson(restoredState, stateClass);\n }\n }\n\n final String saveState() {\n return gson.toJson(state);\n }\n\n // LIFECYCLE\n final void createBase() {\n create();\n }\n\n final void resumeBase() {\n resume();\n }\n\n final void pauseBase() {\n unsubscribeAll(pauseSubscriptions);\n pause();\n }\n\n final void destroyBase() {\n unsubscribeAll(destroySubscriptions);\n destroy();\n }\n\n private void unsubscribeAll(List<Subscription> subscriptions) {\n for (Subscription subscription : subscriptions) {\n subscription.unsubscribe();\n }\n subscriptions.clear();\n }\n\n // PUBLIC API\n public void bindUntilPause(Subscription... subscriptions) {\n if (null != subscriptions) {\n Collections.addAll(pauseSubscriptions, subscriptions);\n }\n }\n\n public void bindUntilDestroy(Subscription... subscriptions) {\n if (null != subscriptions) {\n Collections.addAll(destroySubscriptions, subscriptions);\n }\n }\n\n // ABSTRACTS\n protected abstract U createNewState();\n\n public abstract void create();\n\n public abstract void resume();\n\n public abstract void pause();\n\n public abstract void destroy();\n}",
"@ToString\npublic class Artist implements Serializable {\n static final long serialVersionUID = 4653212L;\n\n @SerializedName(\"displayName\")\n private final String displayName;\n\n @SerializedName(\"id\")\n private final String id;\n\n @SerializedName(\"identifier\")\n private final List<Identifier> identifier;\n\n @SerializedName(\"onTourUntil\")\n private final String onTourUntil;\n\n @SerializedName(\"uri\")\n private final String uri;\n\n public Artist(String displayName, String id, List<Identifier> identifier, String onTourUntil,\n String uri) {\n this.displayName = displayName;\n this.id = id;\n this.identifier = identifier;\n this.onTourUntil = onTourUntil;\n this.uri = uri;\n }\n\n public String getDisplayName() {\n return displayName;\n }\n\n public String getId() {\n return id;\n }\n\n public List<Identifier> getIdentifier() {\n return identifier;\n }\n\n public String getOnTourUntil() {\n return onTourUntil;\n }\n\n public String getUri() {\n return uri;\n }\n}",
"@ToString\npublic class SearchResult {\n @SerializedName(\"resultsPage\")\n private final ResultsPage resultsPage;\n\n public SearchResult(ResultsPage resultsPage) {\n this.resultsPage = resultsPage;\n }\n\n public ResultsPage getResultsPage() {\n return resultsPage;\n }\n}",
"public class EmptyResultException extends RuntimeException {\n public EmptyResultException() {\n }\n\n public EmptyResultException(String detailMessage) {\n super(detailMessage);\n }\n\n public EmptyResultException(String detailMessage, Throwable throwable) {\n super(detailMessage, throwable);\n }\n\n public EmptyResultException(Throwable throwable) {\n super(throwable);\n }\n}",
"public interface SongkickApi {\n @GET(\"search/artists.json\")\n Observable<SearchResult> getSearchResult(@Query(\"apikey\") String apikey,\n @Query(\"query\") String url);\n\n @GET(\"artists/{artist_id}/similar_artists.json\")\n Observable<SearchResult> getRelatedArtists(@Path(\"artist_id\") String artistId,\n @Query(\"apikey\") String apikey);\n}",
"@UtilityClass\npublic class RxActions {\n public static <T> Action1<T> doMultiple(final Action1<T> action1, final Action1<T> action2) {\n return new Action1<T>() {\n @Override\n public void call(T parameter) {\n action1.call(parameter);\n action2.call(parameter);\n }\n };\n }\n\n public static <T> Action1<T> doMultiple(final Action1<T> action1, final Action1<T> action2,\n final Action1<T> action3) {\n return new Action1<T>() {\n @Override\n public void call(T parameter) {\n action1.call(parameter);\n action2.call(parameter);\n action3.call(parameter);\n }\n };\n }\n}",
"@UtilityClass\npublic class RxLog {\n public static Action1<Object> logMessage(final String message, final Object... args) {\n return new Action1<Object>() {\n @Override\n public void call(Object object) {\n /* Varargs only works with one array, so we have to mush them together */\n Object[] allArgs;\n if (null != args) {\n allArgs = new Object[args.length + 1];\n allArgs[0] = object;\n System.arraycopy(args, 0, allArgs, 1, args.length);\n } else {\n allArgs = new Object[] {\n object\n };\n }\n Timber.d(message, allArgs);\n }\n };\n }\n\n public static Action1<Object> logToString() {\n return new Action1<Object>() {\n @Override\n public void call(Object object) {\n Timber.d(\"%s\", object.toString());\n }\n };\n }\n\n public static Action1<Throwable> logError() {\n return new Action1<Throwable>() {\n @Override\n public void call(Throwable throwable) {\n Timber.e(throwable, \"\");\n }\n };\n }\n\n public static Action1<Throwable> logErrorMessage(final String message) {\n return new Action1<Throwable>() {\n @Override\n public void call(Throwable throwable) {\n Timber.e(throwable, message);\n }\n };\n }\n\n public static Action1<Throwable> logErrorMessage(final String message, final Object... params) {\n return new Action1<Throwable>() {\n @Override\n public void call(Throwable throwable) {\n Timber.e(throwable, message, params);\n }\n };\n }\n}",
"@UtilityClass\npublic class RxTuples {\n public static <T, U> Func2<T, U, Tuple<T, U>> singleToTuple() {\n return new Func2<T, U, Tuple<T, U>>() {\n @Override\n public Tuple<T, U> call(T first, U second) {\n return new Tuple<>(first, second);\n }\n };\n }\n\n public static <T, U> Func2<T, U, Tuple<U, T>> singleToTupleInverse() {\n return new Func2<T, U, Tuple<U, T>>() {\n @Override\n public Tuple<U, T> call(T first, U second) {\n return new Tuple<>(second, first);\n }\n };\n }\n\n public static <T, U, V> Func2<T, Tuple<U, V>, Triple<T, U, V>> singleToTriple() {\n return new Func2<T, Tuple<U, V>, Triple<T, U, V>>() {\n @Override\n public Triple<T, U, V> call(T first, Tuple<U, V> second) {\n return new Triple<>(first, second.first, second.second);\n }\n };\n }\n\n public static <T, U, V> Func2<Tuple<T, U>, V, Triple<T, U, V>> tupleToTriple() {\n return new Func2<Tuple<T, U>, V, Triple<T, U, V>>() {\n @Override\n public Triple<T, U, V> call(Tuple<T, U> first, V second) {\n return new Triple<>(first.first, first.second, second);\n }\n };\n }\n\n public static <T, U, V, X> Func2<T, Triple<U, V, X>, Quadriple<T, U, V, X>> singleToQuadruple() {\n return new Func2<T, Triple<U, V, X>, Quadriple<T, U, V, X>>() {\n @Override\n public Quadriple<T, U, V, X> call(T first, Triple<U, V, X> second) {\n return new Quadriple<>(first, second.first, second.second, second.third);\n }\n };\n }\n\n public static <T, U, V, X> Func2<Tuple<T, U>, Tuple<V, X>, Quadriple<T, U, V, X>> tupleToQuadruple() {\n return new Func2<Tuple<T, U>, Tuple<V, X>, Quadriple<T, U, V, X>>() {\n @Override\n public Quadriple<T, U, V, X> call(Tuple<T, U> first, Tuple<V, X> second) {\n return new Quadriple<>(first.first, first.second, second.first, second.second);\n }\n };\n }\n\n public static <T, U, V, X> Func2<Triple<T, U, V>, X, Quadriple<T, U, V, X>> tripleToQuadruple() {\n return new Func2<Triple<T, U, V>, X, Quadriple<T, U, V, X>>() {\n @Override\n public Quadriple<T, U, V, X> call(Triple<T, U, V> first, X second) {\n return new Quadriple<>(first.first, first.second, first.third, second);\n }\n };\n }\n}",
"@EqualsAndHashCode\n@ToString\npublic class Tuple<T, U> implements Serializable {\n public final T first;\n\n public final U second;\n\n public Tuple(T first, U second) {\n this.first = first;\n this.second = second;\n }\n}"
] | import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.inject.Inject;
import rx.Observable;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
import timber.log.Timber;
import com.github.pwittchen.reactivenetwork.library.ConnectivityStatus;
import com.pacoworks.dereference.BuildConfig;
import com.pacoworks.dereference.dependencies.skeleton.ZimplBasePresenter;
import com.pacoworks.dereference.model.Artist;
import com.pacoworks.dereference.model.SearchResult;
import com.pacoworks.dereference.network.EmptyResultException;
import com.pacoworks.dereference.network.SongkickApi;
import com.pacoworks.dereference.reactive.RxActions;
import com.pacoworks.dereference.reactive.RxLog;
import com.pacoworks.dereference.reactive.RxTuples;
import com.pacoworks.dereference.reactive.tuples.Tuple; | /*
* Copyright (c) pakoito 2015
*
* 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 com.pacoworks.dereference.screens.songkicklist;
public class SongkickListPresenter extends ZimplBasePresenter<ISongkickListUI, SongkickListState> {
public static final int INPUT_DEBOUNCE_POLICY = 1;
public static final int CONNECTIVITY_DEBOUNCE_POLICY = 1;
public static final int MIN_SEARCH_POLICY = 2;
private static final int TIMEOUT_POLICY = 60;
private static final long SECOND_IN_NANOS = 1000000000l;
private static final long STALE_SECONDS = 60 * SECOND_IN_NANOS;
@Inject
Observable<ConnectivityStatus> connectivity;
@Inject
SongkickApi songkickApi;
public SongkickListPresenter() {
super(SongkickListState.class);
}
@Override
protected SongkickListState createNewState() {
return new SongkickListState();
}
@Override
public void create() {
}
@Override
public void resume() {
bindUntilPause(observeConnectivity(connectivity),
refreshData(songkickApi, TIMEOUT_POLICY, BuildConfig.API_KEY), handleClicks());
}
private Subscription observeConnectivity(Observable<ConnectivityStatus> connectivity) {
return connectivity.map(ConnectivityStatus.isEqualTo(ConnectivityStatus.OFFLINE))
.subscribe(getUi().showOfflineOverlay());
}
private Subscription refreshData(final SongkickApi songkickApi, final int timeoutPolicy,
final String apiKey) {
return Observable
.combineLatest(getProcessedConnectivityObservable(), getDebouncedSearchBoxInputs(),
RxTuples.<ConnectivityStatus, String> singleToTuple())
.observeOn(AndroidSchedulers.mainThread()).doOnNext(getUi().showLoading())
.flatMap(new Func1<Tuple<ConnectivityStatus, String>, Observable<List<Artist>>>() {
@Override
public Observable<List<Artist>> call(Tuple<ConnectivityStatus, String> status) {
if (ConnectivityStatus.isEqualTo(ConnectivityStatus.OFFLINE).call(
status.first))
return requestLocal(status.second).map(stateToCache())
.observeOn(AndroidSchedulers.mainThread())
.doOnNext(getUi().hideLoading());
else
return requestArtists(songkickApi, timeoutPolicy, status.second, apiKey)
.observeOn(AndroidSchedulers.mainThread())
.doOnError(
RxActions.doMultiple(RxLog.logError(),
handleForErrorType()))
.onErrorReturn(provideEmptyList())
.doOnNext(getUi().hideLoading());
}
}).subscribe(getUi().swapAdapter());
}
Observable<ConnectivityStatus> getProcessedConnectivityObservable() {
return connectivity.distinctUntilChanged()
.debounce(CONNECTIVITY_DEBOUNCE_POLICY, TimeUnit.SECONDS)
.doOnNext(RxLog.logMessage("Network status changed to %s"));
}
Observable<String> getDebouncedSearchBoxInputs() {
return getUi().getSearchBoxInputs().debounce(INPUT_DEBOUNCE_POLICY, TimeUnit.SECONDS)
.filter(new Func1<CharSequence, Boolean>() {
@Override
public Boolean call(CharSequence charSequence) {
return charSequence.length() >= MIN_SEARCH_POLICY;
}
}).map(new Func1<CharSequence, String>() {
@Override
public String call(CharSequence charSequence) {
return charSequence.toString();
}
});
}
Observable<List<Artist>> requestArtists(SongkickApi songkickApi, int timeoutPolicy,
String query, String apiKey) {
return Observable
.concat(requestLocal(query),
requestNetwork(songkickApi, timeoutPolicy, query, apiKey).doOnNext(
storeState())).takeFirst(stalePolicy(query)).map(stateToCache());
}
private Func1<SongkickListState, Boolean> stalePolicy(final String query) {
return new Func1<SongkickListState, Boolean>() {
@Override
public Boolean call(SongkickListState songkickListState) {
final boolean isFresh = query.equalsIgnoreCase(songkickListState.getQuery())
&& songkickListState.getCached().size() != 0
&& System.nanoTime() - songkickListState.getLastUpdate() < STALE_SECONDS;
Timber.d("Is this cache fresh? %s", isFresh);
return isFresh;
}
};
}
Observable<SongkickListState> requestNetwork(SongkickApi songkickApi, int timeoutPolicy,
final String query, String apiKey) {
return songkickApi.getSearchResult(apiKey, query).subscribeOn(Schedulers.newThread())
.unsubscribeOn(Schedulers.computation()).timeout(timeoutPolicy, TimeUnit.SECONDS)
.flatMap(toCorrectResult()).map(new Func1<List<Artist>, SongkickListState>() {
@Override
public SongkickListState call(List<Artist> artists) {
return new SongkickListState(query, artists, System.nanoTime());
}
});
}
| private Func1<SearchResult, Observable<List<Artist>>> toCorrectResult() { | 2 |
dragonite-network/dragonite-java | dragonite-sdk/src/main/java/com/vecsight/dragonite/sdk/msg/types/HeartbeatMessage.java | [
"public class IncorrectMessageException extends DragoniteException {\n\n public IncorrectMessageException(final String msg) {\n super(msg);\n }\n\n}",
"public final class DragoniteGlobalConstants {\n\n public static final String LIBRARY_VERSION = DragoniteBuildConfig.VERSION;\n\n public static final byte PROTOCOL_VERSION = 2;\n\n public static final int MIN_SEND_WINDOW_SIZE = 20;\n\n public static final int ACK_INTERVAL_MS = 10;\n\n public static final int MAX_FAST_RESEND_COUNT = 3;\n\n public static final int MAX_SLOW_RESEND_MULT = 4;\n\n public static final int INIT_RTT_MS = 200, RTT_MAX_VARIATION_MS = 200, RTT_UPDATE_INTERVAL_MS = 100, RTT_RESEND_CORRECTION_INTERVAL_MS = 2000;\n\n public static final int DEV_RTT_MULT = 4;\n\n public static final float RTT_RESENDED_REFRESH_MAX_MULT = 1.5f;\n\n public static final int MIN_CLOSE_WAIT_MS = 100, CLOSE_WAIT_RTT_MULT = 4;\n\n public static final int WEB_PANEL_PORT = 8000;\n\n}",
"public enum MessageType {\n DATA((byte) 0),\n CLOSE((byte) 1),\n ACK((byte) 2),\n HEARTBEAT((byte) 3);\n\n private final byte value;\n\n MessageType(final byte value) {\n this.value = value;\n }\n\n public byte getValue() {\n return value;\n }\n\n private static final MessageType[] types = MessageType.values();\n\n public static MessageType fromByte(final byte type) {\n try {\n return types[type];\n } catch (final ArrayIndexOutOfBoundsException e) {\n throw new IllegalArgumentException(\"Type byte \" + type + \" not found\");\n }\n }\n\n}",
"public interface ReliableMessage extends Message {\n\n int getSequence();\n\n void setSequence(int sequence);\n\n}",
"public class BinaryReader {\n\n private final ByteBuffer byteBuffer;\n\n public BinaryReader(final byte[] bytes) {\n byteBuffer = ByteBuffer.wrap(bytes);\n }\n\n public byte getSignedByte() {\n return byteBuffer.get();\n }\n\n public short getUnsignedByte() {\n return (short) (byteBuffer.get() & (short) 0xff);\n }\n\n public short getSignedShort() {\n return byteBuffer.getShort();\n }\n\n public int getUnsignedShort() {\n return byteBuffer.getShort() & 0xffff;\n }\n\n public int getSignedInt() {\n return byteBuffer.getInt();\n }\n\n public long getUnsignedInt() {\n return (long) byteBuffer.getInt() & 0xffffffffL;\n }\n\n public void getBytes(final byte[] bytes) {\n byteBuffer.get(bytes);\n }\n\n public byte[] getBytesGroupWithByteLength() {\n final short len = getUnsignedByte();\n final byte[] bytes = new byte[len];\n byteBuffer.get(bytes);\n return bytes;\n }\n\n public byte[] getBytesGroupWithShortLength() {\n final int len = getUnsignedShort();\n final byte[] bytes = new byte[len];\n byteBuffer.get(bytes);\n return bytes;\n }\n\n public boolean getBoolean() {\n return byteBuffer.get() != 0;\n }\n\n public int remaining() {\n return byteBuffer.remaining();\n }\n\n}",
"public class BinaryWriter {\n\n private final ByteBuffer byteBuffer;\n\n public BinaryWriter(final int capacity) {\n byteBuffer = ByteBuffer.allocate(capacity);\n }\n\n public BinaryWriter putSignedByte(final byte sb) {\n byteBuffer.put(sb);\n return this;\n }\n\n public BinaryWriter putUnsignedByte(final short ub) {\n byteBuffer.put((byte) (ub & 0xff));\n return this;\n }\n\n public BinaryWriter putSignedShort(final short ss) {\n byteBuffer.putShort(ss);\n return this;\n }\n\n public BinaryWriter putUnsignedShort(final int us) {\n byteBuffer.putShort((short) (us & 0xffff));\n return this;\n }\n\n public BinaryWriter putSignedInt(final int si) {\n byteBuffer.putInt(si);\n return this;\n }\n\n public BinaryWriter putUnsignedInt(final long ui) {\n byteBuffer.putInt((int) (ui & 0xffffffffL));\n return this;\n }\n\n public BinaryWriter putBytes(final byte[] bytes) {\n byteBuffer.put(bytes);\n return this;\n }\n\n public BinaryWriter putBytesGroupWithByteLength(final byte[] bytes) {\n putUnsignedByte((short) bytes.length);\n putBytes(bytes);\n return this;\n }\n\n public BinaryWriter putBytesGroupWithShortLength(final byte[] bytes) {\n putUnsignedShort(bytes.length);\n putBytes(bytes);\n return this;\n }\n\n public BinaryWriter putBoolean(final boolean b) {\n byteBuffer.put((byte) (b ? 1 : 0));\n return this;\n }\n\n public byte[] toBytes() {\n return byteBuffer.array();\n }\n\n}"
] | import com.vecsight.dragonite.sdk.exception.IncorrectMessageException;
import com.vecsight.dragonite.sdk.misc.DragoniteGlobalConstants;
import com.vecsight.dragonite.sdk.msg.MessageType;
import com.vecsight.dragonite.sdk.msg.ReliableMessage;
import com.vecsight.dragonite.utils.binary.BinaryReader;
import com.vecsight.dragonite.utils.binary.BinaryWriter;
import java.nio.BufferUnderflowException; | /*
* The Dragonite Project
* -------------------------
* See the LICENSE file in the root directory for license information.
*/
package com.vecsight.dragonite.sdk.msg.types;
public class HeartbeatMessage implements ReliableMessage {
private static final byte VERSION = DragoniteGlobalConstants.PROTOCOL_VERSION;
private static final MessageType TYPE = MessageType.HEARTBEAT;
public static final int FIXED_LENGTH = 6;
private int sequence;
public HeartbeatMessage(final int sequence) {
this.sequence = sequence;
}
public HeartbeatMessage(final byte[] msg) throws IncorrectMessageException { | final BinaryReader reader = new BinaryReader(msg); | 4 |
saoj/mentabean | src/main/java/org/mentabean/sql/functions/Substring.java | [
"public interface Function extends HasParams {\n\t\n}",
"public abstract class Parametrizable implements HasParams {\n\n\tprotected List<Param> params = new ArrayList<Param>();\n\t\n\tpublic abstract String name();\n\t\n\t@Override\n\tpublic Param[] getParams() {\n\t\treturn params.toArray(new Param[0]);\n\t}\n\t\n\tprotected Parametrizable addParam(Param param) {\n\t\tparams.add(param);\n\t\treturn this;\n\t}\n\t\n\t@Override\n\tpublic String build() {\n\t\t\n\t\tStringBuilder sb = new StringBuilder(name());\n\t\t\n\t\tsb.append(\" (\");\n\t\t\n\t\tfor (Param param : getParams()) {\n\t\t\tsb.append(param.paramInQuery()).append(',');\n\t\t}\n\t\t\n\t\tsb.setCharAt(sb.length()-1, ')');\n\t\t\n\t\treturn sb.toString();\n\t}\n\t\n}",
"public interface Param {\n\n\t/**\n\t * Represents the parameters in query. In other words, this method returns a String\n\t * with the expression exactly as will be shown in SQL before its execution.\n\t * @return String\n\t */\n\tpublic String paramInQuery();\n\t\n\t/**\n\t * The parameter's values\n\t * @return Object[]\n\t */\n\tpublic Object[] values();\n\t\n}",
"public class ParamFunction implements Param {\n\n\tprivate Function function;\n\t\n\tpublic ParamFunction(Function function) {\n\t\tthis.function = function;\n\t}\n\t\n\t@Override\n\tpublic String paramInQuery() {\n\t\treturn function.build();\n\t}\n\n\t@Override\n\tpublic Object[] values() {\n\t\t\n\t\tList<Object> values = new ArrayList<Object>();\n\t\t\n\t\tParam[] params = function.getParams();\n\t\t\n\t\tif (params != null && params.length > 0) {\n\t\t\tfor (Param p : params) {\n\t\t\t\tif (p.values() != null && p.values().length > 0) {\n\t\t\t\t\tvalues.addAll(Arrays.asList(p.values()));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn values.toArray();\n\t}\n\n}",
"public class ParamValue implements Param {\n\n\tprivate Object value;\n\t\n\tpublic ParamValue(Object value) {\n\t\tthis.value = value;\n\t}\n\t\n\t@Override\n\tpublic String paramInQuery() {\n\t\treturn \"?\";\n\t}\n\n\t@Override\n\tpublic Object[] values() {\n\t\treturn new Object[] {value};\n\t}\n\n}"
] | import org.mentabean.sql.Function;
import org.mentabean.sql.Parametrizable;
import org.mentabean.sql.param.Param;
import org.mentabean.sql.param.ParamFunction;
import org.mentabean.sql.param.ParamValue; | package org.mentabean.sql.functions;
public class Substring extends Parametrizable implements Function {
private Param str, beginIndex, endIndex;
public Substring(Param str) {
this.str = str;
}
public Substring endIndex(Param param) {
endIndex = param;
return this;
}
public Substring beginIndex(Param param) {
beginIndex = param;
return this;
}
@Override
public Param[] getParams() {
if (beginIndex == null)
beginIndex = new ParamValue(0);
if (endIndex == null) | endIndex = new ParamFunction(new Length(str)); | 3 |
jaquadro/ForgeMods | HungerStrike/src/com/jaquadro/minecraft/hungerstrike/HungerStrike.java | [
"public class CommandHungerStrike extends CommandBase {\n\n @Override\n public String getCommandName () {\n return \"hungerstrike\";\n }\n\n @Override\n public int getRequiredPermissionLevel() {\n return 3;\n }\n\n @Override\n public String getCommandUsage (ICommandSender sender) {\n return \"commands.hungerstrike.usage\";\n }\n\n @Override\n public void processCommand (ICommandSender sender, String[] args) {\n if (args.length >= 1) {\n if (args[0].equals(\"list\")) {\n List<String> players = playersToNames(PlayerHandler.getStrikingPlayers());\n\n sender.addChatMessage(new ChatComponentTranslation(\"commands.hungerstrike.list\",\n Integer.valueOf(players.size()),\n Integer.valueOf(MinecraftServer.getServer().getConfigurationManager().playerEntityList.size())));\n sender.addChatMessage(new ChatComponentText(joinNiceString(players.toArray(new String[players.size()]))));\n return;\n }\n\n if (args[0].equals(\"add\")) {\n if (args.length < 2)\n throw new WrongUsageException(\"commands.hungerstrike.add.usage\");\n\n ExtendedPlayer player = ExtendedPlayer.get(getPlayer(sender, args[1]));\n player.enableHungerStrike(true);\n\n func_152373_a(sender, this, \"commands.hungerstrike.add.success\", args[1]); // notifyAdmins\n return;\n }\n\n if (args[0].equals(\"remove\")) {\n if (args.length < 2)\n throw new WrongUsageException(\"commands.hungerstrike.remove.usage\");\n\n ExtendedPlayer player = ExtendedPlayer.get(getPlayer(sender, args[1]));\n player.enableHungerStrike(false);\n\n func_152373_a(sender, this, \"commands.hungerstrike.remove.success\", args[1]); // notifyAdmins\n return;\n }\n\n if (args[0].equals(\"mode\")) {\n ConfigManager.Mode mode = HungerStrike.instance.config.getMode();\n\n if (mode == ConfigManager.Mode.NONE)\n func_152373_a(sender, this, \"commands.hungerstrike.mode.none\"); // notifyAdmins\n else if (mode == ConfigManager.Mode.LIST)\n func_152373_a(sender, this, \"commands.hungerstrike.mode.list\"); // notifyAdmins\n else if (mode == ConfigManager.Mode.ALL)\n func_152373_a(sender, this, \"commands.hungerstrike.mode.all\"); // notifyAdmins\n return;\n }\n\n if (args[0].equals(\"setmode\")) {\n if (args.length < 2)\n throw new WrongUsageException(\"commands.hungerstrike.setmode.usage\");\n\n ConfigManager.Mode mode = ConfigManager.Mode.fromValueIgnoreCase(args[1]);\n HungerStrike.instance.config.setMode(mode);\n\n if (!sender.getEntityWorld().isRemote)\n HungerStrike.packetPipeline.sendToAll(new SyncConfigPacket());\n\n if (mode == ConfigManager.Mode.NONE)\n func_152373_a(sender, this, \"commands.hungerstrike.setmode.none\"); // notifyAdmins\n else if (mode == ConfigManager.Mode.LIST)\n func_152373_a(sender, this, \"commands.hungerstrike.setmode.list\"); // notifyAdmins\n else if (mode == ConfigManager.Mode.ALL)\n func_152373_a(sender, this, \"commands.hungerstrike.setmode.all\"); // notifyAdmins\n return;\n }\n }\n\n throw new WrongUsageException(\"commands.hungerstrike.usage\");\n }\n\n @Override\n public List addTabCompletionOptions(ICommandSender sender, String[] args) {\n if (args.length == 1) {\n return getListOfStringsMatchingLastWord(args, \"list\", \"add\", \"remove\", \"mode\", \"setmode\");\n }\n else {\n if (args.length == 2) {\n if (args[0].equals(\"add\")) {\n List<String> players = playersToNames(PlayerHandler.getNonStrikingPlayers());\n return getPartialMatches(args[args.length - 1], players);\n }\n\n if (args[0].equals(\"remove\")) {\n List<String> players = playersToNames(PlayerHandler.getStrikingPlayers());\n return getPartialMatches(args[args.length - 1], players);\n }\n\n if (args[0].equals(\"setmode\")) {\n return getListOfStringsMatchingLastWord(args, \"none\", \"list\", \"all\");\n }\n }\n\n return null;\n }\n }\n\n private List<String> playersToNames (List<EntityPlayer> players) {\n List<String> playerNames = new ArrayList<String>(players.size());\n for (EntityPlayer player : players)\n playerNames.add(player.getCommandSenderName());\n\n return playerNames;\n }\n\n private List<String> getPartialMatches (String partialName, List<String> candidates) {\n List<String> suggestions = new ArrayList<String>();\n for (int i = 0; i < candidates.size(); i++) {\n String playerName = candidates.get(i);\n if (doesStringStartWith(partialName, playerName))\n suggestions.add(playerName);\n }\n\n return suggestions;\n }\n}",
"@ChannelHandler.Sharable\npublic class PacketPipeline extends MessageToMessageCodec<FMLProxyPacket, AbstractPacket> {\n\n private EnumMap<Side, FMLEmbeddedChannel> channels;\n private LinkedList<Class<? extends AbstractPacket>> packets = new LinkedList<Class<? extends AbstractPacket>>();\n private boolean isPostInitialised = false;\n\n /**\n * Register your packet with the pipeline. Discriminators are automatically set.\n *\n * @param clazz the class to register\n *\n * @return whether registration was successful. Failure may occur if 256 packets have been registered or if the registry already contains this packet\n */\n public boolean registerPacket(Class<? extends AbstractPacket> clazz) {\n if (this.packets.size() > 256) {\n // You should log here!!\n return false;\n }\n\n if (this.packets.contains(clazz)) {\n // You should log here!!\n return false;\n }\n\n if (this.isPostInitialised) {\n // You should log here!!\n return false;\n }\n\n this.packets.add(clazz);\n return true;\n }\n\n // In line encoding of the packet, including discriminator setting\n @Override\n protected void encode(ChannelHandlerContext ctx, AbstractPacket msg, List<Object> out) throws Exception {\n ByteBuf buffer = Unpooled.buffer();\n Class<? extends AbstractPacket> clazz = msg.getClass();\n if (!this.packets.contains(msg.getClass())) {\n throw new NullPointerException(\"No Packet Registered for: \" + msg.getClass().getCanonicalName());\n }\n\n byte discriminator = (byte) this.packets.indexOf(clazz);\n buffer.writeByte(discriminator);\n msg.encodeInto(ctx, buffer);\n FMLProxyPacket proxyPacket = new FMLProxyPacket(buffer.copy(), ctx.channel().attr(NetworkRegistry.FML_CHANNEL).get());\n out.add(proxyPacket);\n }\n\n // In line decoding and handling of the packet\n @Override\n protected void decode(ChannelHandlerContext ctx, FMLProxyPacket msg, List<Object> out) throws Exception {\n ByteBuf payload = msg.payload();\n byte discriminator = payload.readByte();\n Class<? extends AbstractPacket> clazz = this.packets.get(discriminator);\n if (clazz == null) {\n throw new NullPointerException(\"No packet registered for discriminator: \" + discriminator);\n }\n\n AbstractPacket pkt = clazz.newInstance();\n pkt.decodeInto(ctx, payload.slice());\n\n EntityPlayer player;\n switch (FMLCommonHandler.instance().getEffectiveSide()) {\n case CLIENT:\n player = this.getClientPlayer();\n pkt.handleClientSide(player);\n break;\n\n case SERVER:\n INetHandler netHandler = ctx.channel().attr(NetworkRegistry.NET_HANDLER).get();\n player = ((NetHandlerPlayServer) netHandler).playerEntity;\n pkt.handleServerSide(player);\n break;\n\n default:\n }\n\n out.add(pkt);\n }\n\n // Method to call from FMLInitializationEvent\n public void initialise() {\n this.channels = NetworkRegistry.INSTANCE.newChannel(\"HungerStrike\", this);\n }\n\n // Method to call from FMLPostInitializationEvent\n // Ensures that packet discriminators are common between server and client by using logical sorting\n public void postInitialise() {\n if (this.isPostInitialised) {\n return;\n }\n\n this.isPostInitialised = true;\n Collections.sort(this.packets, new Comparator<Class<? extends AbstractPacket>>() {\n\n @Override\n public int compare(Class<? extends AbstractPacket> clazz1, Class<? extends AbstractPacket> clazz2) {\n int com = String.CASE_INSENSITIVE_ORDER.compare(clazz1.getCanonicalName(), clazz2.getCanonicalName());\n if (com == 0) {\n com = clazz1.getCanonicalName().compareTo(clazz2.getCanonicalName());\n }\n\n return com;\n }\n });\n }\n\n @SideOnly(Side.CLIENT)\n private EntityPlayer getClientPlayer() {\n return Minecraft.getMinecraft().thePlayer;\n }\n\n /**\n * Send this message to everyone.\n * <p/>\n * Adapted from CPW's code in cpw.mods.fml.common.network.simpleimpl.SimpleNetworkWrapper\n *\n * @param message The message to send\n */\n public void sendToAll(AbstractPacket message) {\n this.channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.ALL);\n this.channels.get(Side.SERVER).writeAndFlush(message);\n }\n\n /**\n * Send this message to the specified player.\n * <p/>\n * Adapted from CPW's code in cpw.mods.fml.common.network.simpleimpl.SimpleNetworkWrapper\n *\n * @param message The message to send\n * @param player The player to send it to\n */\n public void sendTo(AbstractPacket message, EntityPlayerMP player) {\n this.channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.PLAYER);\n this.channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGETARGS).set(player);\n this.channels.get(Side.SERVER).writeAndFlush(message);\n }\n\n /**\n * Send this message to everyone within a certain range of a point.\n * <p/>\n * Adapted from CPW's code in cpw.mods.fml.common.network.simpleimpl.SimpleNetworkWrapper\n *\n * @param message The message to send\n * @param point The {@link cpw.mods.fml.common.network.NetworkRegistry.TargetPoint} around which to send\n */\n public void sendToAllAround(AbstractPacket message, NetworkRegistry.TargetPoint point) {\n this.channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.ALLAROUNDPOINT);\n this.channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGETARGS).set(point);\n this.channels.get(Side.SERVER).writeAndFlush(message);\n }\n\n /**\n * Send this message to everyone within the supplied dimension.\n * <p/>\n * Adapted from CPW's code in cpw.mods.fml.common.network.simpleimpl.SimpleNetworkWrapper\n *\n * @param message The message to send\n * @param dimensionId The dimension id to target\n */\n public void sendToDimension(AbstractPacket message, int dimensionId) {\n this.channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.DIMENSION);\n this.channels.get(Side.SERVER).attr(FMLOutboundHandler.FML_MESSAGETARGETARGS).set(dimensionId);\n this.channels.get(Side.SERVER).writeAndFlush(message);\n }\n\n /**\n * Send this message to the server.\n * <p/>\n * Adapted from CPW's code in cpw.mods.fml.common.network.simpleimpl.SimpleNetworkWrapper\n *\n * @param message The message to send\n */\n public void sendToServer(AbstractPacket message) {\n this.channels.get(Side.CLIENT).attr(FMLOutboundHandler.FML_MESSAGETARGET).set(FMLOutboundHandler.OutboundTarget.TOSERVER);\n this.channels.get(Side.CLIENT).writeAndFlush(message);\n }\n}",
"public class SyncConfigPacket extends AbstractPacket\n{\n private NBTTagCompound data;\n\n public SyncConfigPacket () {\n data = new NBTTagCompound();\n data.setTag(\"mode\", new NBTTagString(HungerStrike.config.getMode().toString()));\n }\n\n @Override\n public void encodeInto (ChannelHandlerContext ctx, ByteBuf buffer) {\n ByteBufUtils.writeTag(buffer, data);\n }\n\n @Override\n public void decodeInto (ChannelHandlerContext ctx, ByteBuf buffer) {\n data = ByteBufUtils.readTag(buffer);\n }\n\n @Override\n public void handleClientSide (EntityPlayer player) {\n if (data.hasKey(\"mode\")) {\n String mode = data.getString(\"mode\");\n HungerStrike.config.setModeSoft(ConfigManager.Mode.valueOf(mode));\n }\n }\n\n @Override\n public void handleServerSide (EntityPlayer player) { }\n}",
"public class SyncExtendedPlayerPacket extends AbstractPacket\n{\n private NBTTagCompound data;\n\n public SyncExtendedPlayerPacket () { }\n\n public SyncExtendedPlayerPacket (EntityPlayer player) {\n data = new NBTTagCompound();\n ExtendedPlayer ep = ExtendedPlayer.get(player);\n if (ep != null)\n ep.saveNBTDataSync(data);\n }\n\n @Override\n public void encodeInto (ChannelHandlerContext ctx, ByteBuf buffer) {\n ByteBufUtils.writeTag(buffer, data);\n }\n\n @Override\n public void decodeInto (ChannelHandlerContext ctx, ByteBuf buffer) {\n data = ByteBufUtils.readTag(buffer);\n }\n\n @Override\n public void handleClientSide (EntityPlayer player) {\n ExtendedPlayer ep = ExtendedPlayer.get(player);\n if (ep != null)\n ep.loadNBTData(data);\n }\n\n @Override\n public void handleServerSide (EntityPlayer player) { }\n}",
"public class CommonProxy\n{\n public PlayerHandler playerHandler;\n\n public CommonProxy () {\n playerHandler = new PlayerHandler();\n }\n\n @SubscribeEvent\n public void tick (TickEvent.PlayerTickEvent event) {\n playerHandler.tick(event.player, event.phase, event.side);\n }\n\n @SubscribeEvent\n public void entityConstructing (EntityEvent.EntityConstructing event) {\n if (event.entity instanceof EntityPlayer && ExtendedPlayer.get((EntityPlayer) event.entity) == null)\n ExtendedPlayer.register((EntityPlayer) event.entity);\n }\n\n @SubscribeEvent\n public void livingDeath (LivingDeathEvent event) {\n if (!event.entity.worldObj.isRemote && event.entity instanceof EntityPlayerMP)\n playerHandler.storeData((EntityPlayer) event.entity);\n }\n\n @SubscribeEvent\n public void entityJoinWorld (EntityJoinWorldEvent event) {\n if (!event.entity.worldObj.isRemote && event.entity instanceof EntityPlayerMP) {\n playerHandler.restoreData((EntityPlayer) event.entity);\n HungerStrike.packetPipeline.sendTo(new SyncExtendedPlayerPacket((EntityPlayer) event.entity), (EntityPlayerMP) event.entity);\n HungerStrike.packetPipeline.sendTo(new SyncConfigPacket(), (EntityPlayerMP) event.entity);\n }\n }\n}"
] | import com.jaquadro.minecraft.hungerstrike.command.CommandHungerStrike;
import com.jaquadro.minecraft.hungerstrike.network.PacketPipeline;
import com.jaquadro.minecraft.hungerstrike.network.SyncConfigPacket;
import com.jaquadro.minecraft.hungerstrike.network.SyncExtendedPlayerPacket;
import com.jaquadro.minecraft.hungerstrike.proxy.CommonProxy;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.SidedProxy;
import cpw.mods.fml.common.event.*;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import cpw.mods.fml.common.gameevent.TickEvent;
import cpw.mods.fml.common.registry.GameData;
import net.minecraft.client.Minecraft;
import net.minecraft.command.CommandHandler;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.Item;
import net.minecraft.item.ItemFood;
import net.minecraft.server.MinecraftServer;
import net.minecraftforge.client.event.RenderGameOverlayEvent;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.entity.EntityEvent;
import net.minecraftforge.event.entity.EntityJoinWorldEvent;
import net.minecraftforge.event.entity.living.LivingDeathEvent; | package com.jaquadro.minecraft.hungerstrike;
@Mod(modid = HungerStrike.MOD_ID, name = HungerStrike.MOD_NAME, version = HungerStrike.MOD_VERSION)
public class HungerStrike
{
public static final String MOD_ID = "hungerstrike";
static final String MOD_NAME = "Hunger Strike";
static final String MOD_VERSION = "1.7.10.4";
static final String SOURCE_PATH = "com.jaquadro.minecraft.hungerstrike.";
@Mod.Instance(MOD_ID)
public static HungerStrike instance;
@SidedProxy(clientSide = SOURCE_PATH + "proxy.ClientProxy", serverSide = SOURCE_PATH + "proxy.CommonProxy")
public static CommonProxy proxy;
public static final PacketPipeline packetPipeline = new PacketPipeline();
public static ConfigManager config = new ConfigManager();
@Mod.EventHandler
public void preInit (FMLPreInitializationEvent event) {
FMLCommonHandler.instance().bus().register(proxy);
config.setup(event.getSuggestedConfigurationFile());
}
@Mod.EventHandler
public void load (FMLInitializationEvent event) {
MinecraftForge.EVENT_BUS.register(proxy);
packetPipeline.initialise();
packetPipeline.registerPacket(SyncExtendedPlayerPacket.class);
packetPipeline.registerPacket(SyncConfigPacket.class);
}
@Mod.EventHandler
public void postInit (FMLPostInitializationEvent event) {
packetPipeline.postInitialise();
if (config.getFoodStackSize() > -1) {
for (Object obj : GameData.itemRegistry) {
Item item = (Item) obj;
if (item instanceof ItemFood)
item.setMaxStackSize(config.getFoodStackSize());
}
}
}
@Mod.EventHandler
public void serverStarted (FMLServerStartedEvent event) {
CommandHandler handler = (CommandHandler) MinecraftServer.getServer().getCommandManager(); | handler.registerCommand(new CommandHungerStrike()); | 0 |
xxonehjh/remote-files-sync | src/main/java/com/hjh/files/sync/server/SyncFileServerHandler.java | [
"public class HLogFactory {\n\n\tprivate static ILogFactory instance;\n\n\tpublic static boolean isInstanceNull() {\n\t\treturn null == instance;\n\t}\n\n\tprivate static ILog empty = new ILog() {\n\n\t\t@Override\n\t\tpublic void debug(String msg) {\n\t\t}\n\n\t\t@Override\n\t\tpublic void info(String msg) {\n\t\t}\n\n\t\t@Override\n\t\tpublic void error(String msg, Throwable e) {\n\t\t}\n\n\t\t@Override\n\t\tpublic void stdout(String msg) {\n\t\t}\n\n\t};\n\n\tpublic static ILog create(Class<?> type) {\n\t\tif (null == instance) {\n\t\t\treturn empty;\n\t\t}\n\t\treturn instance.create(type);\n\t}\n\n\tpublic static void setInstance(ILogFactory instance) {\n\t\tHLogFactory.instance = instance;\n\t}\n\n}",
"public abstract class ILog {\n\n\tpublic abstract void debug(String msg);\n\n\tpublic abstract void info(String msg);\n\n\tpublic abstract void error(String msg, Throwable e);\n\t\n\tpublic abstract void stdout(String msg);\n\n}",
"public interface RemoteFile {\n\t\n\tpublic String name();\n\t\n\tpublic String path();\n\t\n\tpublic long length();\n\t\n\tpublic long lastModify();\n\t\n\tpublic boolean isFolder();\n\n}",
"public class RemoteFileUtil {\n\n\tpublic static int countPart(long size,int page_size) {\n\t\treturn (int) ((size + page_size - 1) / page_size);\n\t}\n\n\tpublic static String formatPath(String path) {\n\t\tAsserts.notBlank(path, \"can as blank path :\" + path);\n\t\tpath = path.replace(\"\\\\\", \"/\");\n\t\tif (path.startsWith(\"/\")) {\n\t\t\tpath = path.substring(1);\n\t\t}\n\t\treturn path;\n\t}\n\n\tprivate static final RemoteFile[] EMPTY = new RemoteFile[0];\n\n\tpublic static RemoteFileInfo to(RemoteFile item) {\n\t\tRemoteFileInfo info = new RemoteFileInfo();\n\t\tinfo.setName(item.name());\n\t\tinfo.setPath(item.path());\n\t\tinfo.setLength(item.length());\n\t\tinfo.setLastModify(item.lastModify());\n\t\tinfo.setIsFolder(item.isFolder());\n\t\treturn info;\n\t}\n\n\tpublic static RemoteFile[] from(List<RemoteFileInfo> listFiles) {\n\t\tif (null == listFiles || 0 == listFiles.size()) {\n\t\t\treturn EMPTY;\n\t\t}\n\t\tint size = listFiles.size();\n\t\tRemoteFile[] result = new RemoteFile[listFiles.size()];\n\t\tfor (int i = 0; i < size; i++) {\n\t\t\tresult[i] = from(listFiles.get(i));\n\t\t}\n\t\treturn result;\n\t}\n\n\tpublic static RemoteFile from(final RemoteFileInfo info) {\n\t\treturn new RemoteFile() {\n\n\t\t\t@Override\n\t\t\tpublic String name() {\n\t\t\t\treturn info.getName();\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic String path() {\n\t\t\t\treturn info.getPath();\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic long length() {\n\t\t\t\treturn info.getLength();\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic long lastModify() {\n\t\t\t\treturn info.getLastModify();\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic boolean isFolder() {\n\t\t\t\treturn info.isIsFolder();\n\t\t\t}\n\t\t};\n\t}\n\n}",
"@SuppressWarnings({\"cast\", \"rawtypes\", \"serial\", \"unchecked\"})\n/**\n * Structs are the basic complex data structures. They are comprised of fields\n * which each have an integer identifier, a type, a symbolic name, and an\n * optional default value.\n * \n * Fields can be declared \"optional\", which ensures they will not be included\n * in the serialized output if they aren't set. Note that this requires some\n * manual management in some languages.\n */\n@Generated(value = \"Autogenerated by Thrift Compiler (0.9.3)\", date = \"2016-07-31\")\npublic class RemoteFileInfo implements org.apache.thrift.TBase<RemoteFileInfo, RemoteFileInfo._Fields>, java.io.Serializable, Cloneable, Comparable<RemoteFileInfo> {\n private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct(\"RemoteFileInfo\");\n\n private static final org.apache.thrift.protocol.TField NAME_FIELD_DESC = new org.apache.thrift.protocol.TField(\"name\", org.apache.thrift.protocol.TType.STRING, (short)1);\n private static final org.apache.thrift.protocol.TField PATH_FIELD_DESC = new org.apache.thrift.protocol.TField(\"path\", org.apache.thrift.protocol.TType.STRING, (short)2);\n private static final org.apache.thrift.protocol.TField LENGTH_FIELD_DESC = new org.apache.thrift.protocol.TField(\"length\", org.apache.thrift.protocol.TType.I64, (short)3);\n private static final org.apache.thrift.protocol.TField LAST_MODIFY_FIELD_DESC = new org.apache.thrift.protocol.TField(\"lastModify\", org.apache.thrift.protocol.TType.I64, (short)4);\n private static final org.apache.thrift.protocol.TField IS_FOLDER_FIELD_DESC = new org.apache.thrift.protocol.TField(\"isFolder\", org.apache.thrift.protocol.TType.BOOL, (short)5);\n\n private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();\n static {\n schemes.put(StandardScheme.class, new RemoteFileInfoStandardSchemeFactory());\n schemes.put(TupleScheme.class, new RemoteFileInfoTupleSchemeFactory());\n }\n\n public String name; // required\n public String path; // required\n public long length; // required\n public long lastModify; // required\n public boolean isFolder; // required\n\n /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */\n public enum _Fields implements org.apache.thrift.TFieldIdEnum {\n NAME((short)1, \"name\"),\n PATH((short)2, \"path\"),\n LENGTH((short)3, \"length\"),\n LAST_MODIFY((short)4, \"lastModify\"),\n IS_FOLDER((short)5, \"isFolder\");\n\n private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();\n\n static {\n for (_Fields field : EnumSet.allOf(_Fields.class)) {\n byName.put(field.getFieldName(), field);\n }\n }\n\n /**\n * Find the _Fields constant that matches fieldId, or null if its not found.\n */\n public static _Fields findByThriftId(int fieldId) {\n switch(fieldId) {\n case 1: // NAME\n return NAME;\n case 2: // PATH\n return PATH;\n case 3: // LENGTH\n return LENGTH;\n case 4: // LAST_MODIFY\n return LAST_MODIFY;\n case 5: // IS_FOLDER\n return IS_FOLDER;\n default:\n return null;\n }\n }\n\n /**\n * Find the _Fields constant that matches fieldId, throwing an exception\n * if it is not found.\n */\n public static _Fields findByThriftIdOrThrow(int fieldId) {\n _Fields fields = findByThriftId(fieldId);\n if (fields == null) throw new IllegalArgumentException(\"Field \" + fieldId + \" doesn't exist!\");\n return fields;\n }\n\n /**\n * Find the _Fields constant that matches name, or null if its not found.\n */\n public static _Fields findByName(String name) {\n return byName.get(name);\n }\n\n private final short _thriftId;\n private final String _fieldName;\n\n _Fields(short thriftId, String fieldName) {\n _thriftId = thriftId;\n _fieldName = fieldName;\n }\n\n public short getThriftFieldId() {\n return _thriftId;\n }\n\n public String getFieldName() {\n return _fieldName;\n }\n }\n\n // isset id assignments\n private static final int __LENGTH_ISSET_ID = 0;\n private static final int __LASTMODIFY_ISSET_ID = 1;\n private static final int __ISFOLDER_ISSET_ID = 2;\n private byte __isset_bitfield = 0;\n public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;\n static {\n Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);\n tmpMap.put(_Fields.NAME, new org.apache.thrift.meta_data.FieldMetaData(\"name\", org.apache.thrift.TFieldRequirementType.DEFAULT, \n new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));\n tmpMap.put(_Fields.PATH, new org.apache.thrift.meta_data.FieldMetaData(\"path\", org.apache.thrift.TFieldRequirementType.DEFAULT, \n new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));\n tmpMap.put(_Fields.LENGTH, new org.apache.thrift.meta_data.FieldMetaData(\"length\", org.apache.thrift.TFieldRequirementType.DEFAULT, \n new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I64)));\n tmpMap.put(_Fields.LAST_MODIFY, new org.apache.thrift.meta_data.FieldMetaData(\"lastModify\", org.apache.thrift.TFieldRequirementType.DEFAULT, \n new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I64)));\n tmpMap.put(_Fields.IS_FOLDER, new org.apache.thrift.meta_data.FieldMetaData(\"isFolder\", org.apache.thrift.TFieldRequirementType.DEFAULT, \n new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.BOOL)));\n metaDataMap = Collections.unmodifiableMap(tmpMap);\n org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(RemoteFileInfo.class, metaDataMap);\n }\n\n public RemoteFileInfo() {\n }\n\n public RemoteFileInfo(\n String name,\n String path,\n long length,\n long lastModify,\n boolean isFolder)\n {\n this();\n this.name = name;\n this.path = path;\n this.length = length;\n setLengthIsSet(true);\n this.lastModify = lastModify;\n setLastModifyIsSet(true);\n this.isFolder = isFolder;\n setIsFolderIsSet(true);\n }\n\n /**\n * Performs a deep copy on <i>other</i>.\n */\n public RemoteFileInfo(RemoteFileInfo other) {\n __isset_bitfield = other.__isset_bitfield;\n if (other.isSetName()) {\n this.name = other.name;\n }\n if (other.isSetPath()) {\n this.path = other.path;\n }\n this.length = other.length;\n this.lastModify = other.lastModify;\n this.isFolder = other.isFolder;\n }\n\n public RemoteFileInfo deepCopy() {\n return new RemoteFileInfo(this);\n }\n\n @Override\n public void clear() {\n this.name = null;\n this.path = null;\n setLengthIsSet(false);\n this.length = 0;\n setLastModifyIsSet(false);\n this.lastModify = 0;\n setIsFolderIsSet(false);\n this.isFolder = false;\n }\n\n public String getName() {\n return this.name;\n }\n\n public RemoteFileInfo setName(String name) {\n this.name = name;\n return this;\n }\n\n public void unsetName() {\n this.name = null;\n }\n\n /** Returns true if field name is set (has been assigned a value) and false otherwise */\n public boolean isSetName() {\n return this.name != null;\n }\n\n public void setNameIsSet(boolean value) {\n if (!value) {\n this.name = null;\n }\n }\n\n public String getPath() {\n return this.path;\n }\n\n public RemoteFileInfo setPath(String path) {\n this.path = path;\n return this;\n }\n\n public void unsetPath() {\n this.path = null;\n }\n\n /** Returns true if field path is set (has been assigned a value) and false otherwise */\n public boolean isSetPath() {\n return this.path != null;\n }\n\n public void setPathIsSet(boolean value) {\n if (!value) {\n this.path = null;\n }\n }\n\n public long getLength() {\n return this.length;\n }\n\n public RemoteFileInfo setLength(long length) {\n this.length = length;\n setLengthIsSet(true);\n return this;\n }\n\n public void unsetLength() {\n __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __LENGTH_ISSET_ID);\n }\n\n /** Returns true if field length is set (has been assigned a value) and false otherwise */\n public boolean isSetLength() {\n return EncodingUtils.testBit(__isset_bitfield, __LENGTH_ISSET_ID);\n }\n\n public void setLengthIsSet(boolean value) {\n __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __LENGTH_ISSET_ID, value);\n }\n\n public long getLastModify() {\n return this.lastModify;\n }\n\n public RemoteFileInfo setLastModify(long lastModify) {\n this.lastModify = lastModify;\n setLastModifyIsSet(true);\n return this;\n }\n\n public void unsetLastModify() {\n __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __LASTMODIFY_ISSET_ID);\n }\n\n /** Returns true if field lastModify is set (has been assigned a value) and false otherwise */\n public boolean isSetLastModify() {\n return EncodingUtils.testBit(__isset_bitfield, __LASTMODIFY_ISSET_ID);\n }\n\n public void setLastModifyIsSet(boolean value) {\n __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __LASTMODIFY_ISSET_ID, value);\n }\n\n public boolean isIsFolder() {\n return this.isFolder;\n }\n\n public RemoteFileInfo setIsFolder(boolean isFolder) {\n this.isFolder = isFolder;\n setIsFolderIsSet(true);\n return this;\n }\n\n public void unsetIsFolder() {\n __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __ISFOLDER_ISSET_ID);\n }\n\n /** Returns true if field isFolder is set (has been assigned a value) and false otherwise */\n public boolean isSetIsFolder() {\n return EncodingUtils.testBit(__isset_bitfield, __ISFOLDER_ISSET_ID);\n }\n\n public void setIsFolderIsSet(boolean value) {\n __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __ISFOLDER_ISSET_ID, value);\n }\n\n public void setFieldValue(_Fields field, Object value) {\n switch (field) {\n case NAME:\n if (value == null) {\n unsetName();\n } else {\n setName((String)value);\n }\n break;\n\n case PATH:\n if (value == null) {\n unsetPath();\n } else {\n setPath((String)value);\n }\n break;\n\n case LENGTH:\n if (value == null) {\n unsetLength();\n } else {\n setLength((Long)value);\n }\n break;\n\n case LAST_MODIFY:\n if (value == null) {\n unsetLastModify();\n } else {\n setLastModify((Long)value);\n }\n break;\n\n case IS_FOLDER:\n if (value == null) {\n unsetIsFolder();\n } else {\n setIsFolder((Boolean)value);\n }\n break;\n\n }\n }\n\n public Object getFieldValue(_Fields field) {\n switch (field) {\n case NAME:\n return getName();\n\n case PATH:\n return getPath();\n\n case LENGTH:\n return getLength();\n\n case LAST_MODIFY:\n return getLastModify();\n\n case IS_FOLDER:\n return isIsFolder();\n\n }\n throw new IllegalStateException();\n }\n\n /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */\n public boolean isSet(_Fields field) {\n if (field == null) {\n throw new IllegalArgumentException();\n }\n\n switch (field) {\n case NAME:\n return isSetName();\n case PATH:\n return isSetPath();\n case LENGTH:\n return isSetLength();\n case LAST_MODIFY:\n return isSetLastModify();\n case IS_FOLDER:\n return isSetIsFolder();\n }\n throw new IllegalStateException();\n }\n\n @Override\n public boolean equals(Object that) {\n if (that == null)\n return false;\n if (that instanceof RemoteFileInfo)\n return this.equals((RemoteFileInfo)that);\n return false;\n }\n\n public boolean equals(RemoteFileInfo that) {\n if (that == null)\n return false;\n\n boolean this_present_name = true && this.isSetName();\n boolean that_present_name = true && that.isSetName();\n if (this_present_name || that_present_name) {\n if (!(this_present_name && that_present_name))\n return false;\n if (!this.name.equals(that.name))\n return false;\n }\n\n boolean this_present_path = true && this.isSetPath();\n boolean that_present_path = true && that.isSetPath();\n if (this_present_path || that_present_path) {\n if (!(this_present_path && that_present_path))\n return false;\n if (!this.path.equals(that.path))\n return false;\n }\n\n boolean this_present_length = true;\n boolean that_present_length = true;\n if (this_present_length || that_present_length) {\n if (!(this_present_length && that_present_length))\n return false;\n if (this.length != that.length)\n return false;\n }\n\n boolean this_present_lastModify = true;\n boolean that_present_lastModify = true;\n if (this_present_lastModify || that_present_lastModify) {\n if (!(this_present_lastModify && that_present_lastModify))\n return false;\n if (this.lastModify != that.lastModify)\n return false;\n }\n\n boolean this_present_isFolder = true;\n boolean that_present_isFolder = true;\n if (this_present_isFolder || that_present_isFolder) {\n if (!(this_present_isFolder && that_present_isFolder))\n return false;\n if (this.isFolder != that.isFolder)\n return false;\n }\n\n return true;\n }\n\n @Override\n public int hashCode() {\n List<Object> list = new ArrayList<Object>();\n\n boolean present_name = true && (isSetName());\n list.add(present_name);\n if (present_name)\n list.add(name);\n\n boolean present_path = true && (isSetPath());\n list.add(present_path);\n if (present_path)\n list.add(path);\n\n boolean present_length = true;\n list.add(present_length);\n if (present_length)\n list.add(length);\n\n boolean present_lastModify = true;\n list.add(present_lastModify);\n if (present_lastModify)\n list.add(lastModify);\n\n boolean present_isFolder = true;\n list.add(present_isFolder);\n if (present_isFolder)\n list.add(isFolder);\n\n return list.hashCode();\n }\n\n @Override\n public int compareTo(RemoteFileInfo other) {\n if (!getClass().equals(other.getClass())) {\n return getClass().getName().compareTo(other.getClass().getName());\n }\n\n int lastComparison = 0;\n\n lastComparison = Boolean.valueOf(isSetName()).compareTo(other.isSetName());\n if (lastComparison != 0) {\n return lastComparison;\n }\n if (isSetName()) {\n lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.name, other.name);\n if (lastComparison != 0) {\n return lastComparison;\n }\n }\n lastComparison = Boolean.valueOf(isSetPath()).compareTo(other.isSetPath());\n if (lastComparison != 0) {\n return lastComparison;\n }\n if (isSetPath()) {\n lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.path, other.path);\n if (lastComparison != 0) {\n return lastComparison;\n }\n }\n lastComparison = Boolean.valueOf(isSetLength()).compareTo(other.isSetLength());\n if (lastComparison != 0) {\n return lastComparison;\n }\n if (isSetLength()) {\n lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.length, other.length);\n if (lastComparison != 0) {\n return lastComparison;\n }\n }\n lastComparison = Boolean.valueOf(isSetLastModify()).compareTo(other.isSetLastModify());\n if (lastComparison != 0) {\n return lastComparison;\n }\n if (isSetLastModify()) {\n lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.lastModify, other.lastModify);\n if (lastComparison != 0) {\n return lastComparison;\n }\n }\n lastComparison = Boolean.valueOf(isSetIsFolder()).compareTo(other.isSetIsFolder());\n if (lastComparison != 0) {\n return lastComparison;\n }\n if (isSetIsFolder()) {\n lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.isFolder, other.isFolder);\n if (lastComparison != 0) {\n return lastComparison;\n }\n }\n return 0;\n }\n\n public _Fields fieldForId(int fieldId) {\n return _Fields.findByThriftId(fieldId);\n }\n\n public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {\n schemes.get(iprot.getScheme()).getScheme().read(iprot, this);\n }\n\n public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {\n schemes.get(oprot.getScheme()).getScheme().write(oprot, this);\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder(\"RemoteFileInfo(\");\n boolean first = true;\n\n sb.append(\"name:\");\n if (this.name == null) {\n sb.append(\"null\");\n } else {\n sb.append(this.name);\n }\n first = false;\n if (!first) sb.append(\", \");\n sb.append(\"path:\");\n if (this.path == null) {\n sb.append(\"null\");\n } else {\n sb.append(this.path);\n }\n first = false;\n if (!first) sb.append(\", \");\n sb.append(\"length:\");\n sb.append(this.length);\n first = false;\n if (!first) sb.append(\", \");\n sb.append(\"lastModify:\");\n sb.append(this.lastModify);\n first = false;\n if (!first) sb.append(\", \");\n sb.append(\"isFolder:\");\n sb.append(this.isFolder);\n first = false;\n sb.append(\")\");\n return sb.toString();\n }\n\n public void validate() throws org.apache.thrift.TException {\n // check for required fields\n // check for sub-struct validity\n }\n\n private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {\n try {\n write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));\n } catch (org.apache.thrift.TException te) {\n throw new java.io.IOException(te);\n }\n }\n\n private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {\n try {\n // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor.\n __isset_bitfield = 0;\n read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));\n } catch (org.apache.thrift.TException te) {\n throw new java.io.IOException(te);\n }\n }\n\n private static class RemoteFileInfoStandardSchemeFactory implements SchemeFactory {\n public RemoteFileInfoStandardScheme getScheme() {\n return new RemoteFileInfoStandardScheme();\n }\n }\n\n private static class RemoteFileInfoStandardScheme extends StandardScheme<RemoteFileInfo> {\n\n public void read(org.apache.thrift.protocol.TProtocol iprot, RemoteFileInfo struct) throws org.apache.thrift.TException {\n org.apache.thrift.protocol.TField schemeField;\n iprot.readStructBegin();\n while (true)\n {\n schemeField = iprot.readFieldBegin();\n if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { \n break;\n }\n switch (schemeField.id) {\n case 1: // NAME\n if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {\n struct.name = iprot.readString();\n struct.setNameIsSet(true);\n } else { \n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\n }\n break;\n case 2: // PATH\n if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {\n struct.path = iprot.readString();\n struct.setPathIsSet(true);\n } else { \n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\n }\n break;\n case 3: // LENGTH\n if (schemeField.type == org.apache.thrift.protocol.TType.I64) {\n struct.length = iprot.readI64();\n struct.setLengthIsSet(true);\n } else { \n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\n }\n break;\n case 4: // LAST_MODIFY\n if (schemeField.type == org.apache.thrift.protocol.TType.I64) {\n struct.lastModify = iprot.readI64();\n struct.setLastModifyIsSet(true);\n } else { \n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\n }\n break;\n case 5: // IS_FOLDER\n if (schemeField.type == org.apache.thrift.protocol.TType.BOOL) {\n struct.isFolder = iprot.readBool();\n struct.setIsFolderIsSet(true);\n } else { \n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\n }\n break;\n default:\n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\n }\n iprot.readFieldEnd();\n }\n iprot.readStructEnd();\n\n // check for required fields of primitive type, which can't be checked in the validate method\n struct.validate();\n }\n\n public void write(org.apache.thrift.protocol.TProtocol oprot, RemoteFileInfo struct) throws org.apache.thrift.TException {\n struct.validate();\n\n oprot.writeStructBegin(STRUCT_DESC);\n if (struct.name != null) {\n oprot.writeFieldBegin(NAME_FIELD_DESC);\n oprot.writeString(struct.name);\n oprot.writeFieldEnd();\n }\n if (struct.path != null) {\n oprot.writeFieldBegin(PATH_FIELD_DESC);\n oprot.writeString(struct.path);\n oprot.writeFieldEnd();\n }\n oprot.writeFieldBegin(LENGTH_FIELD_DESC);\n oprot.writeI64(struct.length);\n oprot.writeFieldEnd();\n oprot.writeFieldBegin(LAST_MODIFY_FIELD_DESC);\n oprot.writeI64(struct.lastModify);\n oprot.writeFieldEnd();\n oprot.writeFieldBegin(IS_FOLDER_FIELD_DESC);\n oprot.writeBool(struct.isFolder);\n oprot.writeFieldEnd();\n oprot.writeFieldStop();\n oprot.writeStructEnd();\n }\n\n }\n\n private static class RemoteFileInfoTupleSchemeFactory implements SchemeFactory {\n public RemoteFileInfoTupleScheme getScheme() {\n return new RemoteFileInfoTupleScheme();\n }\n }\n\n private static class RemoteFileInfoTupleScheme extends TupleScheme<RemoteFileInfo> {\n\n @Override\n public void write(org.apache.thrift.protocol.TProtocol prot, RemoteFileInfo struct) throws org.apache.thrift.TException {\n TTupleProtocol oprot = (TTupleProtocol) prot;\n BitSet optionals = new BitSet();\n if (struct.isSetName()) {\n optionals.set(0);\n }\n if (struct.isSetPath()) {\n optionals.set(1);\n }\n if (struct.isSetLength()) {\n optionals.set(2);\n }\n if (struct.isSetLastModify()) {\n optionals.set(3);\n }\n if (struct.isSetIsFolder()) {\n optionals.set(4);\n }\n oprot.writeBitSet(optionals, 5);\n if (struct.isSetName()) {\n oprot.writeString(struct.name);\n }\n if (struct.isSetPath()) {\n oprot.writeString(struct.path);\n }\n if (struct.isSetLength()) {\n oprot.writeI64(struct.length);\n }\n if (struct.isSetLastModify()) {\n oprot.writeI64(struct.lastModify);\n }\n if (struct.isSetIsFolder()) {\n oprot.writeBool(struct.isFolder);\n }\n }\n\n @Override\n public void read(org.apache.thrift.protocol.TProtocol prot, RemoteFileInfo struct) throws org.apache.thrift.TException {\n TTupleProtocol iprot = (TTupleProtocol) prot;\n BitSet incoming = iprot.readBitSet(5);\n if (incoming.get(0)) {\n struct.name = iprot.readString();\n struct.setNameIsSet(true);\n }\n if (incoming.get(1)) {\n struct.path = iprot.readString();\n struct.setPathIsSet(true);\n }\n if (incoming.get(2)) {\n struct.length = iprot.readI64();\n struct.setLengthIsSet(true);\n }\n if (incoming.get(3)) {\n struct.lastModify = iprot.readI64();\n struct.setLastModifyIsSet(true);\n }\n if (incoming.get(4)) {\n struct.isFolder = iprot.readBool();\n struct.setIsFolderIsSet(true);\n }\n }\n }\n\n}",
"@SuppressWarnings({\"cast\", \"rawtypes\", \"serial\", \"unchecked\"})\n@Generated(value = \"Autogenerated by Thrift Compiler (0.9.3)\", date = \"2016-07-31\")\npublic class SyncFileServer {\n\n /**\n * Ahh, now onto the cool part, defining a service. Services just need a name\n * and can optionally inherit from another service using the extends keyword.\n */\n public interface Iface {\n\n /**\n * A method definition looks like C code. It has a return type, arguments,\n * and optionally a list of exceptions that it may throw. Note that argument\n * lists and exception lists are specified using the exact same syntax as\n * field lists in struct or exception definitions.\n */\n public void ping() throws org.apache.thrift.TException;\n\n public String md5(String folder, String path) throws org.apache.thrift.TException;\n\n public ByteBuffer part(String folder, String path, long part, long part_size) throws org.apache.thrift.TException;\n\n public List<RemoteFileInfo> listFiles(String folder, String path) throws org.apache.thrift.TException;\n\n }\n\n public interface AsyncIface {\n\n public void ping(org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException;\n\n public void md5(String folder, String path, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException;\n\n public void part(String folder, String path, long part, long part_size, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException;\n\n public void listFiles(String folder, String path, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException;\n\n }\n\n public static class Client extends org.apache.thrift.TServiceClient implements Iface {\n public static class Factory implements org.apache.thrift.TServiceClientFactory<Client> {\n public Factory() {}\n public Client getClient(org.apache.thrift.protocol.TProtocol prot) {\n return new Client(prot);\n }\n public Client getClient(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) {\n return new Client(iprot, oprot);\n }\n }\n\n public Client(org.apache.thrift.protocol.TProtocol prot)\n {\n super(prot, prot);\n }\n\n public Client(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) {\n super(iprot, oprot);\n }\n\n public void ping() throws org.apache.thrift.TException\n {\n send_ping();\n recv_ping();\n }\n\n public void send_ping() throws org.apache.thrift.TException\n {\n ping_args args = new ping_args();\n sendBase(\"ping\", args);\n }\n\n public void recv_ping() throws org.apache.thrift.TException\n {\n ping_result result = new ping_result();\n receiveBase(result, \"ping\");\n return;\n }\n\n public String md5(String folder, String path) throws org.apache.thrift.TException\n {\n send_md5(folder, path);\n return recv_md5();\n }\n\n public void send_md5(String folder, String path) throws org.apache.thrift.TException\n {\n md5_args args = new md5_args();\n args.setFolder(folder);\n args.setPath(path);\n sendBase(\"md5\", args);\n }\n\n public String recv_md5() throws org.apache.thrift.TException\n {\n md5_result result = new md5_result();\n receiveBase(result, \"md5\");\n if (result.isSetSuccess()) {\n return result.success;\n }\n throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, \"md5 failed: unknown result\");\n }\n\n public ByteBuffer part(String folder, String path, long part, long part_size) throws org.apache.thrift.TException\n {\n send_part(folder, path, part, part_size);\n return recv_part();\n }\n\n public void send_part(String folder, String path, long part, long part_size) throws org.apache.thrift.TException\n {\n part_args args = new part_args();\n args.setFolder(folder);\n args.setPath(path);\n args.setPart(part);\n args.setPart_size(part_size);\n sendBase(\"part\", args);\n }\n\n public ByteBuffer recv_part() throws org.apache.thrift.TException\n {\n part_result result = new part_result();\n receiveBase(result, \"part\");\n if (result.isSetSuccess()) {\n return result.success;\n }\n throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, \"part failed: unknown result\");\n }\n\n public List<RemoteFileInfo> listFiles(String folder, String path) throws org.apache.thrift.TException\n {\n send_listFiles(folder, path);\n return recv_listFiles();\n }\n\n public void send_listFiles(String folder, String path) throws org.apache.thrift.TException\n {\n listFiles_args args = new listFiles_args();\n args.setFolder(folder);\n args.setPath(path);\n sendBase(\"listFiles\", args);\n }\n\n public List<RemoteFileInfo> recv_listFiles() throws org.apache.thrift.TException\n {\n listFiles_result result = new listFiles_result();\n receiveBase(result, \"listFiles\");\n if (result.isSetSuccess()) {\n return result.success;\n }\n throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, \"listFiles failed: unknown result\");\n }\n\n }\n public static class AsyncClient extends org.apache.thrift.async.TAsyncClient implements AsyncIface {\n public static class Factory implements org.apache.thrift.async.TAsyncClientFactory<AsyncClient> {\n private org.apache.thrift.async.TAsyncClientManager clientManager;\n private org.apache.thrift.protocol.TProtocolFactory protocolFactory;\n public Factory(org.apache.thrift.async.TAsyncClientManager clientManager, org.apache.thrift.protocol.TProtocolFactory protocolFactory) {\n this.clientManager = clientManager;\n this.protocolFactory = protocolFactory;\n }\n public AsyncClient getAsyncClient(org.apache.thrift.transport.TNonblockingTransport transport) {\n return new AsyncClient(protocolFactory, clientManager, transport);\n }\n }\n\n public AsyncClient(org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.async.TAsyncClientManager clientManager, org.apache.thrift.transport.TNonblockingTransport transport) {\n super(protocolFactory, clientManager, transport);\n }\n\n public void ping(org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException {\n checkReady();\n ping_call method_call = new ping_call(resultHandler, this, ___protocolFactory, ___transport);\n this.___currentMethod = method_call;\n ___manager.call(method_call);\n }\n\n public static class ping_call extends org.apache.thrift.async.TAsyncMethodCall {\n public ping_call(org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException {\n super(client, protocolFactory, transport, resultHandler, false);\n }\n\n public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException {\n prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage(\"ping\", org.apache.thrift.protocol.TMessageType.CALL, 0));\n ping_args args = new ping_args();\n args.write(prot);\n prot.writeMessageEnd();\n }\n\n public void getResult() throws org.apache.thrift.TException {\n if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) {\n throw new IllegalStateException(\"Method call not finished!\");\n }\n org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array());\n org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport);\n (new Client(prot)).recv_ping();\n }\n }\n\n public void md5(String folder, String path, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException {\n checkReady();\n md5_call method_call = new md5_call(folder, path, resultHandler, this, ___protocolFactory, ___transport);\n this.___currentMethod = method_call;\n ___manager.call(method_call);\n }\n\n public static class md5_call extends org.apache.thrift.async.TAsyncMethodCall {\n private String folder;\n private String path;\n public md5_call(String folder, String path, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException {\n super(client, protocolFactory, transport, resultHandler, false);\n this.folder = folder;\n this.path = path;\n }\n\n public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException {\n prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage(\"md5\", org.apache.thrift.protocol.TMessageType.CALL, 0));\n md5_args args = new md5_args();\n args.setFolder(folder);\n args.setPath(path);\n args.write(prot);\n prot.writeMessageEnd();\n }\n\n public String getResult() throws org.apache.thrift.TException {\n if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) {\n throw new IllegalStateException(\"Method call not finished!\");\n }\n org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array());\n org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport);\n return (new Client(prot)).recv_md5();\n }\n }\n\n public void part(String folder, String path, long part, long part_size, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException {\n checkReady();\n part_call method_call = new part_call(folder, path, part, part_size, resultHandler, this, ___protocolFactory, ___transport);\n this.___currentMethod = method_call;\n ___manager.call(method_call);\n }\n\n public static class part_call extends org.apache.thrift.async.TAsyncMethodCall {\n private String folder;\n private String path;\n private long part;\n private long part_size;\n public part_call(String folder, String path, long part, long part_size, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException {\n super(client, protocolFactory, transport, resultHandler, false);\n this.folder = folder;\n this.path = path;\n this.part = part;\n this.part_size = part_size;\n }\n\n public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException {\n prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage(\"part\", org.apache.thrift.protocol.TMessageType.CALL, 0));\n part_args args = new part_args();\n args.setFolder(folder);\n args.setPath(path);\n args.setPart(part);\n args.setPart_size(part_size);\n args.write(prot);\n prot.writeMessageEnd();\n }\n\n public ByteBuffer getResult() throws org.apache.thrift.TException {\n if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) {\n throw new IllegalStateException(\"Method call not finished!\");\n }\n org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array());\n org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport);\n return (new Client(prot)).recv_part();\n }\n }\n\n public void listFiles(String folder, String path, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException {\n checkReady();\n listFiles_call method_call = new listFiles_call(folder, path, resultHandler, this, ___protocolFactory, ___transport);\n this.___currentMethod = method_call;\n ___manager.call(method_call);\n }\n\n public static class listFiles_call extends org.apache.thrift.async.TAsyncMethodCall {\n private String folder;\n private String path;\n public listFiles_call(String folder, String path, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException {\n super(client, protocolFactory, transport, resultHandler, false);\n this.folder = folder;\n this.path = path;\n }\n\n public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException {\n prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage(\"listFiles\", org.apache.thrift.protocol.TMessageType.CALL, 0));\n listFiles_args args = new listFiles_args();\n args.setFolder(folder);\n args.setPath(path);\n args.write(prot);\n prot.writeMessageEnd();\n }\n\n public List<RemoteFileInfo> getResult() throws org.apache.thrift.TException {\n if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) {\n throw new IllegalStateException(\"Method call not finished!\");\n }\n org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array());\n org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport);\n return (new Client(prot)).recv_listFiles();\n }\n }\n\n }\n\n public static class Processor<I extends Iface> extends org.apache.thrift.TBaseProcessor<I> implements org.apache.thrift.TProcessor {\n private static final Logger LOGGER = LoggerFactory.getLogger(Processor.class.getName());\n public Processor(I iface) {\n super(iface, getProcessMap(new HashMap<String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>>()));\n }\n\n protected Processor(I iface, Map<String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>> processMap) {\n super(iface, getProcessMap(processMap));\n }\n\n private static <I extends Iface> Map<String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>> getProcessMap(Map<String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>> processMap) {\n processMap.put(\"ping\", new ping());\n processMap.put(\"md5\", new md5());\n processMap.put(\"part\", new part());\n processMap.put(\"listFiles\", new listFiles());\n return processMap;\n }\n\n public static class ping<I extends Iface> extends org.apache.thrift.ProcessFunction<I, ping_args> {\n public ping() {\n super(\"ping\");\n }\n\n public ping_args getEmptyArgsInstance() {\n return new ping_args();\n }\n\n protected boolean isOneway() {\n return false;\n }\n\n public ping_result getResult(I iface, ping_args args) throws org.apache.thrift.TException {\n ping_result result = new ping_result();\n iface.ping();\n return result;\n }\n }\n\n public static class md5<I extends Iface> extends org.apache.thrift.ProcessFunction<I, md5_args> {\n public md5() {\n super(\"md5\");\n }\n\n public md5_args getEmptyArgsInstance() {\n return new md5_args();\n }\n\n protected boolean isOneway() {\n return false;\n }\n\n public md5_result getResult(I iface, md5_args args) throws org.apache.thrift.TException {\n md5_result result = new md5_result();\n result.success = iface.md5(args.folder, args.path);\n return result;\n }\n }\n\n public static class part<I extends Iface> extends org.apache.thrift.ProcessFunction<I, part_args> {\n public part() {\n super(\"part\");\n }\n\n public part_args getEmptyArgsInstance() {\n return new part_args();\n }\n\n protected boolean isOneway() {\n return false;\n }\n\n public part_result getResult(I iface, part_args args) throws org.apache.thrift.TException {\n part_result result = new part_result();\n result.success = iface.part(args.folder, args.path, args.part, args.part_size);\n return result;\n }\n }\n\n public static class listFiles<I extends Iface> extends org.apache.thrift.ProcessFunction<I, listFiles_args> {\n public listFiles() {\n super(\"listFiles\");\n }\n\n public listFiles_args getEmptyArgsInstance() {\n return new listFiles_args();\n }\n\n protected boolean isOneway() {\n return false;\n }\n\n public listFiles_result getResult(I iface, listFiles_args args) throws org.apache.thrift.TException {\n listFiles_result result = new listFiles_result();\n result.success = iface.listFiles(args.folder, args.path);\n return result;\n }\n }\n\n }\n\n public static class AsyncProcessor<I extends AsyncIface> extends org.apache.thrift.TBaseAsyncProcessor<I> {\n private static final Logger LOGGER = LoggerFactory.getLogger(AsyncProcessor.class.getName());\n public AsyncProcessor(I iface) {\n super(iface, getProcessMap(new HashMap<String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase, ?>>()));\n }\n\n protected AsyncProcessor(I iface, Map<String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase, ?>> processMap) {\n super(iface, getProcessMap(processMap));\n }\n\n private static <I extends AsyncIface> Map<String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase,?>> getProcessMap(Map<String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase, ?>> processMap) {\n processMap.put(\"ping\", new ping());\n processMap.put(\"md5\", new md5());\n processMap.put(\"part\", new part());\n processMap.put(\"listFiles\", new listFiles());\n return processMap;\n }\n\n public static class ping<I extends AsyncIface> extends org.apache.thrift.AsyncProcessFunction<I, ping_args, Void> {\n public ping() {\n super(\"ping\");\n }\n\n public ping_args getEmptyArgsInstance() {\n return new ping_args();\n }\n\n public AsyncMethodCallback<Void> getResultHandler(final AsyncFrameBuffer fb, final int seqid) {\n final org.apache.thrift.AsyncProcessFunction fcall = this;\n return new AsyncMethodCallback<Void>() { \n public void onComplete(Void o) {\n ping_result result = new ping_result();\n try {\n fcall.sendResponse(fb,result, org.apache.thrift.protocol.TMessageType.REPLY,seqid);\n return;\n } catch (Exception e) {\n LOGGER.error(\"Exception writing to internal frame buffer\", e);\n }\n fb.close();\n }\n public void onError(Exception e) {\n byte msgType = org.apache.thrift.protocol.TMessageType.REPLY;\n org.apache.thrift.TBase msg;\n ping_result result = new ping_result();\n {\n msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;\n msg = (org.apache.thrift.TBase)new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage());\n }\n try {\n fcall.sendResponse(fb,msg,msgType,seqid);\n return;\n } catch (Exception ex) {\n LOGGER.error(\"Exception writing to internal frame buffer\", ex);\n }\n fb.close();\n }\n };\n }\n\n protected boolean isOneway() {\n return false;\n }\n\n public void start(I iface, ping_args args, org.apache.thrift.async.AsyncMethodCallback<Void> resultHandler) throws TException {\n iface.ping(resultHandler);\n }\n }\n\n public static class md5<I extends AsyncIface> extends org.apache.thrift.AsyncProcessFunction<I, md5_args, String> {\n public md5() {\n super(\"md5\");\n }\n\n public md5_args getEmptyArgsInstance() {\n return new md5_args();\n }\n\n public AsyncMethodCallback<String> getResultHandler(final AsyncFrameBuffer fb, final int seqid) {\n final org.apache.thrift.AsyncProcessFunction fcall = this;\n return new AsyncMethodCallback<String>() { \n public void onComplete(String o) {\n md5_result result = new md5_result();\n result.success = o;\n try {\n fcall.sendResponse(fb,result, org.apache.thrift.protocol.TMessageType.REPLY,seqid);\n return;\n } catch (Exception e) {\n LOGGER.error(\"Exception writing to internal frame buffer\", e);\n }\n fb.close();\n }\n public void onError(Exception e) {\n byte msgType = org.apache.thrift.protocol.TMessageType.REPLY;\n org.apache.thrift.TBase msg;\n md5_result result = new md5_result();\n {\n msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;\n msg = (org.apache.thrift.TBase)new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage());\n }\n try {\n fcall.sendResponse(fb,msg,msgType,seqid);\n return;\n } catch (Exception ex) {\n LOGGER.error(\"Exception writing to internal frame buffer\", ex);\n }\n fb.close();\n }\n };\n }\n\n protected boolean isOneway() {\n return false;\n }\n\n public void start(I iface, md5_args args, org.apache.thrift.async.AsyncMethodCallback<String> resultHandler) throws TException {\n iface.md5(args.folder, args.path,resultHandler);\n }\n }\n\n public static class part<I extends AsyncIface> extends org.apache.thrift.AsyncProcessFunction<I, part_args, ByteBuffer> {\n public part() {\n super(\"part\");\n }\n\n public part_args getEmptyArgsInstance() {\n return new part_args();\n }\n\n public AsyncMethodCallback<ByteBuffer> getResultHandler(final AsyncFrameBuffer fb, final int seqid) {\n final org.apache.thrift.AsyncProcessFunction fcall = this;\n return new AsyncMethodCallback<ByteBuffer>() { \n public void onComplete(ByteBuffer o) {\n part_result result = new part_result();\n result.success = o;\n try {\n fcall.sendResponse(fb,result, org.apache.thrift.protocol.TMessageType.REPLY,seqid);\n return;\n } catch (Exception e) {\n LOGGER.error(\"Exception writing to internal frame buffer\", e);\n }\n fb.close();\n }\n public void onError(Exception e) {\n byte msgType = org.apache.thrift.protocol.TMessageType.REPLY;\n org.apache.thrift.TBase msg;\n part_result result = new part_result();\n {\n msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;\n msg = (org.apache.thrift.TBase)new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage());\n }\n try {\n fcall.sendResponse(fb,msg,msgType,seqid);\n return;\n } catch (Exception ex) {\n LOGGER.error(\"Exception writing to internal frame buffer\", ex);\n }\n fb.close();\n }\n };\n }\n\n protected boolean isOneway() {\n return false;\n }\n\n public void start(I iface, part_args args, org.apache.thrift.async.AsyncMethodCallback<ByteBuffer> resultHandler) throws TException {\n iface.part(args.folder, args.path, args.part, args.part_size,resultHandler);\n }\n }\n\n public static class listFiles<I extends AsyncIface> extends org.apache.thrift.AsyncProcessFunction<I, listFiles_args, List<RemoteFileInfo>> {\n public listFiles() {\n super(\"listFiles\");\n }\n\n public listFiles_args getEmptyArgsInstance() {\n return new listFiles_args();\n }\n\n public AsyncMethodCallback<List<RemoteFileInfo>> getResultHandler(final AsyncFrameBuffer fb, final int seqid) {\n final org.apache.thrift.AsyncProcessFunction fcall = this;\n return new AsyncMethodCallback<List<RemoteFileInfo>>() { \n public void onComplete(List<RemoteFileInfo> o) {\n listFiles_result result = new listFiles_result();\n result.success = o;\n try {\n fcall.sendResponse(fb,result, org.apache.thrift.protocol.TMessageType.REPLY,seqid);\n return;\n } catch (Exception e) {\n LOGGER.error(\"Exception writing to internal frame buffer\", e);\n }\n fb.close();\n }\n public void onError(Exception e) {\n byte msgType = org.apache.thrift.protocol.TMessageType.REPLY;\n org.apache.thrift.TBase msg;\n listFiles_result result = new listFiles_result();\n {\n msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;\n msg = (org.apache.thrift.TBase)new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage());\n }\n try {\n fcall.sendResponse(fb,msg,msgType,seqid);\n return;\n } catch (Exception ex) {\n LOGGER.error(\"Exception writing to internal frame buffer\", ex);\n }\n fb.close();\n }\n };\n }\n\n protected boolean isOneway() {\n return false;\n }\n\n public void start(I iface, listFiles_args args, org.apache.thrift.async.AsyncMethodCallback<List<RemoteFileInfo>> resultHandler) throws TException {\n iface.listFiles(args.folder, args.path,resultHandler);\n }\n }\n\n }\n\n public static class ping_args implements org.apache.thrift.TBase<ping_args, ping_args._Fields>, java.io.Serializable, Cloneable, Comparable<ping_args> {\n private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct(\"ping_args\");\n\n\n private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();\n static {\n schemes.put(StandardScheme.class, new ping_argsStandardSchemeFactory());\n schemes.put(TupleScheme.class, new ping_argsTupleSchemeFactory());\n }\n\n\n /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */\n public enum _Fields implements org.apache.thrift.TFieldIdEnum {\n;\n\n private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();\n\n static {\n for (_Fields field : EnumSet.allOf(_Fields.class)) {\n byName.put(field.getFieldName(), field);\n }\n }\n\n /**\n * Find the _Fields constant that matches fieldId, or null if its not found.\n */\n public static _Fields findByThriftId(int fieldId) {\n switch(fieldId) {\n default:\n return null;\n }\n }\n\n /**\n * Find the _Fields constant that matches fieldId, throwing an exception\n * if it is not found.\n */\n public static _Fields findByThriftIdOrThrow(int fieldId) {\n _Fields fields = findByThriftId(fieldId);\n if (fields == null) throw new IllegalArgumentException(\"Field \" + fieldId + \" doesn't exist!\");\n return fields;\n }\n\n /**\n * Find the _Fields constant that matches name, or null if its not found.\n */\n public static _Fields findByName(String name) {\n return byName.get(name);\n }\n\n private final short _thriftId;\n private final String _fieldName;\n\n _Fields(short thriftId, String fieldName) {\n _thriftId = thriftId;\n _fieldName = fieldName;\n }\n\n public short getThriftFieldId() {\n return _thriftId;\n }\n\n public String getFieldName() {\n return _fieldName;\n }\n }\n public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;\n static {\n Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);\n metaDataMap = Collections.unmodifiableMap(tmpMap);\n org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(ping_args.class, metaDataMap);\n }\n\n public ping_args() {\n }\n\n /**\n * Performs a deep copy on <i>other</i>.\n */\n public ping_args(ping_args other) {\n }\n\n public ping_args deepCopy() {\n return new ping_args(this);\n }\n\n @Override\n public void clear() {\n }\n\n public void setFieldValue(_Fields field, Object value) {\n switch (field) {\n }\n }\n\n public Object getFieldValue(_Fields field) {\n switch (field) {\n }\n throw new IllegalStateException();\n }\n\n /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */\n public boolean isSet(_Fields field) {\n if (field == null) {\n throw new IllegalArgumentException();\n }\n\n switch (field) {\n }\n throw new IllegalStateException();\n }\n\n @Override\n public boolean equals(Object that) {\n if (that == null)\n return false;\n if (that instanceof ping_args)\n return this.equals((ping_args)that);\n return false;\n }\n\n public boolean equals(ping_args that) {\n if (that == null)\n return false;\n\n return true;\n }\n\n @Override\n public int hashCode() {\n List<Object> list = new ArrayList<Object>();\n\n return list.hashCode();\n }\n\n @Override\n public int compareTo(ping_args other) {\n if (!getClass().equals(other.getClass())) {\n return getClass().getName().compareTo(other.getClass().getName());\n }\n\n int lastComparison = 0;\n\n return 0;\n }\n\n public _Fields fieldForId(int fieldId) {\n return _Fields.findByThriftId(fieldId);\n }\n\n public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {\n schemes.get(iprot.getScheme()).getScheme().read(iprot, this);\n }\n\n public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {\n schemes.get(oprot.getScheme()).getScheme().write(oprot, this);\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder(\"ping_args(\");\n boolean first = true;\n\n sb.append(\")\");\n return sb.toString();\n }\n\n public void validate() throws org.apache.thrift.TException {\n // check for required fields\n // check for sub-struct validity\n }\n\n private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {\n try {\n write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));\n } catch (org.apache.thrift.TException te) {\n throw new java.io.IOException(te);\n }\n }\n\n private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {\n try {\n read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));\n } catch (org.apache.thrift.TException te) {\n throw new java.io.IOException(te);\n }\n }\n\n private static class ping_argsStandardSchemeFactory implements SchemeFactory {\n public ping_argsStandardScheme getScheme() {\n return new ping_argsStandardScheme();\n }\n }\n\n private static class ping_argsStandardScheme extends StandardScheme<ping_args> {\n\n public void read(org.apache.thrift.protocol.TProtocol iprot, ping_args struct) throws org.apache.thrift.TException {\n org.apache.thrift.protocol.TField schemeField;\n iprot.readStructBegin();\n while (true)\n {\n schemeField = iprot.readFieldBegin();\n if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { \n break;\n }\n switch (schemeField.id) {\n default:\n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\n }\n iprot.readFieldEnd();\n }\n iprot.readStructEnd();\n\n // check for required fields of primitive type, which can't be checked in the validate method\n struct.validate();\n }\n\n public void write(org.apache.thrift.protocol.TProtocol oprot, ping_args struct) throws org.apache.thrift.TException {\n struct.validate();\n\n oprot.writeStructBegin(STRUCT_DESC);\n oprot.writeFieldStop();\n oprot.writeStructEnd();\n }\n\n }\n\n private static class ping_argsTupleSchemeFactory implements SchemeFactory {\n public ping_argsTupleScheme getScheme() {\n return new ping_argsTupleScheme();\n }\n }\n\n private static class ping_argsTupleScheme extends TupleScheme<ping_args> {\n\n @Override\n public void write(org.apache.thrift.protocol.TProtocol prot, ping_args struct) throws org.apache.thrift.TException {\n TTupleProtocol oprot = (TTupleProtocol) prot;\n }\n\n @Override\n public void read(org.apache.thrift.protocol.TProtocol prot, ping_args struct) throws org.apache.thrift.TException {\n TTupleProtocol iprot = (TTupleProtocol) prot;\n }\n }\n\n }\n\n public static class ping_result implements org.apache.thrift.TBase<ping_result, ping_result._Fields>, java.io.Serializable, Cloneable, Comparable<ping_result> {\n private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct(\"ping_result\");\n\n\n private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();\n static {\n schemes.put(StandardScheme.class, new ping_resultStandardSchemeFactory());\n schemes.put(TupleScheme.class, new ping_resultTupleSchemeFactory());\n }\n\n\n /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */\n public enum _Fields implements org.apache.thrift.TFieldIdEnum {\n;\n\n private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();\n\n static {\n for (_Fields field : EnumSet.allOf(_Fields.class)) {\n byName.put(field.getFieldName(), field);\n }\n }\n\n /**\n * Find the _Fields constant that matches fieldId, or null if its not found.\n */\n public static _Fields findByThriftId(int fieldId) {\n switch(fieldId) {\n default:\n return null;\n }\n }\n\n /**\n * Find the _Fields constant that matches fieldId, throwing an exception\n * if it is not found.\n */\n public static _Fields findByThriftIdOrThrow(int fieldId) {\n _Fields fields = findByThriftId(fieldId);\n if (fields == null) throw new IllegalArgumentException(\"Field \" + fieldId + \" doesn't exist!\");\n return fields;\n }\n\n /**\n * Find the _Fields constant that matches name, or null if its not found.\n */\n public static _Fields findByName(String name) {\n return byName.get(name);\n }\n\n private final short _thriftId;\n private final String _fieldName;\n\n _Fields(short thriftId, String fieldName) {\n _thriftId = thriftId;\n _fieldName = fieldName;\n }\n\n public short getThriftFieldId() {\n return _thriftId;\n }\n\n public String getFieldName() {\n return _fieldName;\n }\n }\n public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;\n static {\n Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);\n metaDataMap = Collections.unmodifiableMap(tmpMap);\n org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(ping_result.class, metaDataMap);\n }\n\n public ping_result() {\n }\n\n /**\n * Performs a deep copy on <i>other</i>.\n */\n public ping_result(ping_result other) {\n }\n\n public ping_result deepCopy() {\n return new ping_result(this);\n }\n\n @Override\n public void clear() {\n }\n\n public void setFieldValue(_Fields field, Object value) {\n switch (field) {\n }\n }\n\n public Object getFieldValue(_Fields field) {\n switch (field) {\n }\n throw new IllegalStateException();\n }\n\n /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */\n public boolean isSet(_Fields field) {\n if (field == null) {\n throw new IllegalArgumentException();\n }\n\n switch (field) {\n }\n throw new IllegalStateException();\n }\n\n @Override\n public boolean equals(Object that) {\n if (that == null)\n return false;\n if (that instanceof ping_result)\n return this.equals((ping_result)that);\n return false;\n }\n\n public boolean equals(ping_result that) {\n if (that == null)\n return false;\n\n return true;\n }\n\n @Override\n public int hashCode() {\n List<Object> list = new ArrayList<Object>();\n\n return list.hashCode();\n }\n\n @Override\n public int compareTo(ping_result other) {\n if (!getClass().equals(other.getClass())) {\n return getClass().getName().compareTo(other.getClass().getName());\n }\n\n int lastComparison = 0;\n\n return 0;\n }\n\n public _Fields fieldForId(int fieldId) {\n return _Fields.findByThriftId(fieldId);\n }\n\n public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {\n schemes.get(iprot.getScheme()).getScheme().read(iprot, this);\n }\n\n public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {\n schemes.get(oprot.getScheme()).getScheme().write(oprot, this);\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder(\"ping_result(\");\n boolean first = true;\n\n sb.append(\")\");\n return sb.toString();\n }\n\n public void validate() throws org.apache.thrift.TException {\n // check for required fields\n // check for sub-struct validity\n }\n\n private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {\n try {\n write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));\n } catch (org.apache.thrift.TException te) {\n throw new java.io.IOException(te);\n }\n }\n\n private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {\n try {\n read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));\n } catch (org.apache.thrift.TException te) {\n throw new java.io.IOException(te);\n }\n }\n\n private static class ping_resultStandardSchemeFactory implements SchemeFactory {\n public ping_resultStandardScheme getScheme() {\n return new ping_resultStandardScheme();\n }\n }\n\n private static class ping_resultStandardScheme extends StandardScheme<ping_result> {\n\n public void read(org.apache.thrift.protocol.TProtocol iprot, ping_result struct) throws org.apache.thrift.TException {\n org.apache.thrift.protocol.TField schemeField;\n iprot.readStructBegin();\n while (true)\n {\n schemeField = iprot.readFieldBegin();\n if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { \n break;\n }\n switch (schemeField.id) {\n default:\n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\n }\n iprot.readFieldEnd();\n }\n iprot.readStructEnd();\n\n // check for required fields of primitive type, which can't be checked in the validate method\n struct.validate();\n }\n\n public void write(org.apache.thrift.protocol.TProtocol oprot, ping_result struct) throws org.apache.thrift.TException {\n struct.validate();\n\n oprot.writeStructBegin(STRUCT_DESC);\n oprot.writeFieldStop();\n oprot.writeStructEnd();\n }\n\n }\n\n private static class ping_resultTupleSchemeFactory implements SchemeFactory {\n public ping_resultTupleScheme getScheme() {\n return new ping_resultTupleScheme();\n }\n }\n\n private static class ping_resultTupleScheme extends TupleScheme<ping_result> {\n\n @Override\n public void write(org.apache.thrift.protocol.TProtocol prot, ping_result struct) throws org.apache.thrift.TException {\n TTupleProtocol oprot = (TTupleProtocol) prot;\n }\n\n @Override\n public void read(org.apache.thrift.protocol.TProtocol prot, ping_result struct) throws org.apache.thrift.TException {\n TTupleProtocol iprot = (TTupleProtocol) prot;\n }\n }\n\n }\n\n public static class md5_args implements org.apache.thrift.TBase<md5_args, md5_args._Fields>, java.io.Serializable, Cloneable, Comparable<md5_args> {\n private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct(\"md5_args\");\n\n private static final org.apache.thrift.protocol.TField FOLDER_FIELD_DESC = new org.apache.thrift.protocol.TField(\"folder\", org.apache.thrift.protocol.TType.STRING, (short)1);\n private static final org.apache.thrift.protocol.TField PATH_FIELD_DESC = new org.apache.thrift.protocol.TField(\"path\", org.apache.thrift.protocol.TType.STRING, (short)2);\n\n private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();\n static {\n schemes.put(StandardScheme.class, new md5_argsStandardSchemeFactory());\n schemes.put(TupleScheme.class, new md5_argsTupleSchemeFactory());\n }\n\n public String folder; // required\n public String path; // required\n\n /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */\n public enum _Fields implements org.apache.thrift.TFieldIdEnum {\n FOLDER((short)1, \"folder\"),\n PATH((short)2, \"path\");\n\n private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();\n\n static {\n for (_Fields field : EnumSet.allOf(_Fields.class)) {\n byName.put(field.getFieldName(), field);\n }\n }\n\n /**\n * Find the _Fields constant that matches fieldId, or null if its not found.\n */\n public static _Fields findByThriftId(int fieldId) {\n switch(fieldId) {\n case 1: // FOLDER\n return FOLDER;\n case 2: // PATH\n return PATH;\n default:\n return null;\n }\n }\n\n /**\n * Find the _Fields constant that matches fieldId, throwing an exception\n * if it is not found.\n */\n public static _Fields findByThriftIdOrThrow(int fieldId) {\n _Fields fields = findByThriftId(fieldId);\n if (fields == null) throw new IllegalArgumentException(\"Field \" + fieldId + \" doesn't exist!\");\n return fields;\n }\n\n /**\n * Find the _Fields constant that matches name, or null if its not found.\n */\n public static _Fields findByName(String name) {\n return byName.get(name);\n }\n\n private final short _thriftId;\n private final String _fieldName;\n\n _Fields(short thriftId, String fieldName) {\n _thriftId = thriftId;\n _fieldName = fieldName;\n }\n\n public short getThriftFieldId() {\n return _thriftId;\n }\n\n public String getFieldName() {\n return _fieldName;\n }\n }\n\n // isset id assignments\n public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;\n static {\n Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);\n tmpMap.put(_Fields.FOLDER, new org.apache.thrift.meta_data.FieldMetaData(\"folder\", org.apache.thrift.TFieldRequirementType.DEFAULT, \n new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));\n tmpMap.put(_Fields.PATH, new org.apache.thrift.meta_data.FieldMetaData(\"path\", org.apache.thrift.TFieldRequirementType.DEFAULT, \n new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));\n metaDataMap = Collections.unmodifiableMap(tmpMap);\n org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(md5_args.class, metaDataMap);\n }\n\n public md5_args() {\n }\n\n public md5_args(\n String folder,\n String path)\n {\n this();\n this.folder = folder;\n this.path = path;\n }\n\n /**\n * Performs a deep copy on <i>other</i>.\n */\n public md5_args(md5_args other) {\n if (other.isSetFolder()) {\n this.folder = other.folder;\n }\n if (other.isSetPath()) {\n this.path = other.path;\n }\n }\n\n public md5_args deepCopy() {\n return new md5_args(this);\n }\n\n @Override\n public void clear() {\n this.folder = null;\n this.path = null;\n }\n\n public String getFolder() {\n return this.folder;\n }\n\n public md5_args setFolder(String folder) {\n this.folder = folder;\n return this;\n }\n\n public void unsetFolder() {\n this.folder = null;\n }\n\n /** Returns true if field folder is set (has been assigned a value) and false otherwise */\n public boolean isSetFolder() {\n return this.folder != null;\n }\n\n public void setFolderIsSet(boolean value) {\n if (!value) {\n this.folder = null;\n }\n }\n\n public String getPath() {\n return this.path;\n }\n\n public md5_args setPath(String path) {\n this.path = path;\n return this;\n }\n\n public void unsetPath() {\n this.path = null;\n }\n\n /** Returns true if field path is set (has been assigned a value) and false otherwise */\n public boolean isSetPath() {\n return this.path != null;\n }\n\n public void setPathIsSet(boolean value) {\n if (!value) {\n this.path = null;\n }\n }\n\n public void setFieldValue(_Fields field, Object value) {\n switch (field) {\n case FOLDER:\n if (value == null) {\n unsetFolder();\n } else {\n setFolder((String)value);\n }\n break;\n\n case PATH:\n if (value == null) {\n unsetPath();\n } else {\n setPath((String)value);\n }\n break;\n\n }\n }\n\n public Object getFieldValue(_Fields field) {\n switch (field) {\n case FOLDER:\n return getFolder();\n\n case PATH:\n return getPath();\n\n }\n throw new IllegalStateException();\n }\n\n /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */\n public boolean isSet(_Fields field) {\n if (field == null) {\n throw new IllegalArgumentException();\n }\n\n switch (field) {\n case FOLDER:\n return isSetFolder();\n case PATH:\n return isSetPath();\n }\n throw new IllegalStateException();\n }\n\n @Override\n public boolean equals(Object that) {\n if (that == null)\n return false;\n if (that instanceof md5_args)\n return this.equals((md5_args)that);\n return false;\n }\n\n public boolean equals(md5_args that) {\n if (that == null)\n return false;\n\n boolean this_present_folder = true && this.isSetFolder();\n boolean that_present_folder = true && that.isSetFolder();\n if (this_present_folder || that_present_folder) {\n if (!(this_present_folder && that_present_folder))\n return false;\n if (!this.folder.equals(that.folder))\n return false;\n }\n\n boolean this_present_path = true && this.isSetPath();\n boolean that_present_path = true && that.isSetPath();\n if (this_present_path || that_present_path) {\n if (!(this_present_path && that_present_path))\n return false;\n if (!this.path.equals(that.path))\n return false;\n }\n\n return true;\n }\n\n @Override\n public int hashCode() {\n List<Object> list = new ArrayList<Object>();\n\n boolean present_folder = true && (isSetFolder());\n list.add(present_folder);\n if (present_folder)\n list.add(folder);\n\n boolean present_path = true && (isSetPath());\n list.add(present_path);\n if (present_path)\n list.add(path);\n\n return list.hashCode();\n }\n\n @Override\n public int compareTo(md5_args other) {\n if (!getClass().equals(other.getClass())) {\n return getClass().getName().compareTo(other.getClass().getName());\n }\n\n int lastComparison = 0;\n\n lastComparison = Boolean.valueOf(isSetFolder()).compareTo(other.isSetFolder());\n if (lastComparison != 0) {\n return lastComparison;\n }\n if (isSetFolder()) {\n lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.folder, other.folder);\n if (lastComparison != 0) {\n return lastComparison;\n }\n }\n lastComparison = Boolean.valueOf(isSetPath()).compareTo(other.isSetPath());\n if (lastComparison != 0) {\n return lastComparison;\n }\n if (isSetPath()) {\n lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.path, other.path);\n if (lastComparison != 0) {\n return lastComparison;\n }\n }\n return 0;\n }\n\n public _Fields fieldForId(int fieldId) {\n return _Fields.findByThriftId(fieldId);\n }\n\n public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {\n schemes.get(iprot.getScheme()).getScheme().read(iprot, this);\n }\n\n public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {\n schemes.get(oprot.getScheme()).getScheme().write(oprot, this);\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder(\"md5_args(\");\n boolean first = true;\n\n sb.append(\"folder:\");\n if (this.folder == null) {\n sb.append(\"null\");\n } else {\n sb.append(this.folder);\n }\n first = false;\n if (!first) sb.append(\", \");\n sb.append(\"path:\");\n if (this.path == null) {\n sb.append(\"null\");\n } else {\n sb.append(this.path);\n }\n first = false;\n sb.append(\")\");\n return sb.toString();\n }\n\n public void validate() throws org.apache.thrift.TException {\n // check for required fields\n // check for sub-struct validity\n }\n\n private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {\n try {\n write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));\n } catch (org.apache.thrift.TException te) {\n throw new java.io.IOException(te);\n }\n }\n\n private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {\n try {\n read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));\n } catch (org.apache.thrift.TException te) {\n throw new java.io.IOException(te);\n }\n }\n\n private static class md5_argsStandardSchemeFactory implements SchemeFactory {\n public md5_argsStandardScheme getScheme() {\n return new md5_argsStandardScheme();\n }\n }\n\n private static class md5_argsStandardScheme extends StandardScheme<md5_args> {\n\n public void read(org.apache.thrift.protocol.TProtocol iprot, md5_args struct) throws org.apache.thrift.TException {\n org.apache.thrift.protocol.TField schemeField;\n iprot.readStructBegin();\n while (true)\n {\n schemeField = iprot.readFieldBegin();\n if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { \n break;\n }\n switch (schemeField.id) {\n case 1: // FOLDER\n if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {\n struct.folder = iprot.readString();\n struct.setFolderIsSet(true);\n } else { \n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\n }\n break;\n case 2: // PATH\n if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {\n struct.path = iprot.readString();\n struct.setPathIsSet(true);\n } else { \n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\n }\n break;\n default:\n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\n }\n iprot.readFieldEnd();\n }\n iprot.readStructEnd();\n\n // check for required fields of primitive type, which can't be checked in the validate method\n struct.validate();\n }\n\n public void write(org.apache.thrift.protocol.TProtocol oprot, md5_args struct) throws org.apache.thrift.TException {\n struct.validate();\n\n oprot.writeStructBegin(STRUCT_DESC);\n if (struct.folder != null) {\n oprot.writeFieldBegin(FOLDER_FIELD_DESC);\n oprot.writeString(struct.folder);\n oprot.writeFieldEnd();\n }\n if (struct.path != null) {\n oprot.writeFieldBegin(PATH_FIELD_DESC);\n oprot.writeString(struct.path);\n oprot.writeFieldEnd();\n }\n oprot.writeFieldStop();\n oprot.writeStructEnd();\n }\n\n }\n\n private static class md5_argsTupleSchemeFactory implements SchemeFactory {\n public md5_argsTupleScheme getScheme() {\n return new md5_argsTupleScheme();\n }\n }\n\n private static class md5_argsTupleScheme extends TupleScheme<md5_args> {\n\n @Override\n public void write(org.apache.thrift.protocol.TProtocol prot, md5_args struct) throws org.apache.thrift.TException {\n TTupleProtocol oprot = (TTupleProtocol) prot;\n BitSet optionals = new BitSet();\n if (struct.isSetFolder()) {\n optionals.set(0);\n }\n if (struct.isSetPath()) {\n optionals.set(1);\n }\n oprot.writeBitSet(optionals, 2);\n if (struct.isSetFolder()) {\n oprot.writeString(struct.folder);\n }\n if (struct.isSetPath()) {\n oprot.writeString(struct.path);\n }\n }\n\n @Override\n public void read(org.apache.thrift.protocol.TProtocol prot, md5_args struct) throws org.apache.thrift.TException {\n TTupleProtocol iprot = (TTupleProtocol) prot;\n BitSet incoming = iprot.readBitSet(2);\n if (incoming.get(0)) {\n struct.folder = iprot.readString();\n struct.setFolderIsSet(true);\n }\n if (incoming.get(1)) {\n struct.path = iprot.readString();\n struct.setPathIsSet(true);\n }\n }\n }\n\n }\n\n public static class md5_result implements org.apache.thrift.TBase<md5_result, md5_result._Fields>, java.io.Serializable, Cloneable, Comparable<md5_result> {\n private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct(\"md5_result\");\n\n private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField(\"success\", org.apache.thrift.protocol.TType.STRING, (short)0);\n\n private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();\n static {\n schemes.put(StandardScheme.class, new md5_resultStandardSchemeFactory());\n schemes.put(TupleScheme.class, new md5_resultTupleSchemeFactory());\n }\n\n public String success; // required\n\n /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */\n public enum _Fields implements org.apache.thrift.TFieldIdEnum {\n SUCCESS((short)0, \"success\");\n\n private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();\n\n static {\n for (_Fields field : EnumSet.allOf(_Fields.class)) {\n byName.put(field.getFieldName(), field);\n }\n }\n\n /**\n * Find the _Fields constant that matches fieldId, or null if its not found.\n */\n public static _Fields findByThriftId(int fieldId) {\n switch(fieldId) {\n case 0: // SUCCESS\n return SUCCESS;\n default:\n return null;\n }\n }\n\n /**\n * Find the _Fields constant that matches fieldId, throwing an exception\n * if it is not found.\n */\n public static _Fields findByThriftIdOrThrow(int fieldId) {\n _Fields fields = findByThriftId(fieldId);\n if (fields == null) throw new IllegalArgumentException(\"Field \" + fieldId + \" doesn't exist!\");\n return fields;\n }\n\n /**\n * Find the _Fields constant that matches name, or null if its not found.\n */\n public static _Fields findByName(String name) {\n return byName.get(name);\n }\n\n private final short _thriftId;\n private final String _fieldName;\n\n _Fields(short thriftId, String fieldName) {\n _thriftId = thriftId;\n _fieldName = fieldName;\n }\n\n public short getThriftFieldId() {\n return _thriftId;\n }\n\n public String getFieldName() {\n return _fieldName;\n }\n }\n\n // isset id assignments\n public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;\n static {\n Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);\n tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData(\"success\", org.apache.thrift.TFieldRequirementType.DEFAULT, \n new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));\n metaDataMap = Collections.unmodifiableMap(tmpMap);\n org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(md5_result.class, metaDataMap);\n }\n\n public md5_result() {\n }\n\n public md5_result(\n String success)\n {\n this();\n this.success = success;\n }\n\n /**\n * Performs a deep copy on <i>other</i>.\n */\n public md5_result(md5_result other) {\n if (other.isSetSuccess()) {\n this.success = other.success;\n }\n }\n\n public md5_result deepCopy() {\n return new md5_result(this);\n }\n\n @Override\n public void clear() {\n this.success = null;\n }\n\n public String getSuccess() {\n return this.success;\n }\n\n public md5_result setSuccess(String success) {\n this.success = success;\n return this;\n }\n\n public void unsetSuccess() {\n this.success = null;\n }\n\n /** Returns true if field success is set (has been assigned a value) and false otherwise */\n public boolean isSetSuccess() {\n return this.success != null;\n }\n\n public void setSuccessIsSet(boolean value) {\n if (!value) {\n this.success = null;\n }\n }\n\n public void setFieldValue(_Fields field, Object value) {\n switch (field) {\n case SUCCESS:\n if (value == null) {\n unsetSuccess();\n } else {\n setSuccess((String)value);\n }\n break;\n\n }\n }\n\n public Object getFieldValue(_Fields field) {\n switch (field) {\n case SUCCESS:\n return getSuccess();\n\n }\n throw new IllegalStateException();\n }\n\n /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */\n public boolean isSet(_Fields field) {\n if (field == null) {\n throw new IllegalArgumentException();\n }\n\n switch (field) {\n case SUCCESS:\n return isSetSuccess();\n }\n throw new IllegalStateException();\n }\n\n @Override\n public boolean equals(Object that) {\n if (that == null)\n return false;\n if (that instanceof md5_result)\n return this.equals((md5_result)that);\n return false;\n }\n\n public boolean equals(md5_result that) {\n if (that == null)\n return false;\n\n boolean this_present_success = true && this.isSetSuccess();\n boolean that_present_success = true && that.isSetSuccess();\n if (this_present_success || that_present_success) {\n if (!(this_present_success && that_present_success))\n return false;\n if (!this.success.equals(that.success))\n return false;\n }\n\n return true;\n }\n\n @Override\n public int hashCode() {\n List<Object> list = new ArrayList<Object>();\n\n boolean present_success = true && (isSetSuccess());\n list.add(present_success);\n if (present_success)\n list.add(success);\n\n return list.hashCode();\n }\n\n @Override\n public int compareTo(md5_result other) {\n if (!getClass().equals(other.getClass())) {\n return getClass().getName().compareTo(other.getClass().getName());\n }\n\n int lastComparison = 0;\n\n lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess());\n if (lastComparison != 0) {\n return lastComparison;\n }\n if (isSetSuccess()) {\n lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success);\n if (lastComparison != 0) {\n return lastComparison;\n }\n }\n return 0;\n }\n\n public _Fields fieldForId(int fieldId) {\n return _Fields.findByThriftId(fieldId);\n }\n\n public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {\n schemes.get(iprot.getScheme()).getScheme().read(iprot, this);\n }\n\n public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {\n schemes.get(oprot.getScheme()).getScheme().write(oprot, this);\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder(\"md5_result(\");\n boolean first = true;\n\n sb.append(\"success:\");\n if (this.success == null) {\n sb.append(\"null\");\n } else {\n sb.append(this.success);\n }\n first = false;\n sb.append(\")\");\n return sb.toString();\n }\n\n public void validate() throws org.apache.thrift.TException {\n // check for required fields\n // check for sub-struct validity\n }\n\n private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {\n try {\n write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));\n } catch (org.apache.thrift.TException te) {\n throw new java.io.IOException(te);\n }\n }\n\n private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {\n try {\n read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));\n } catch (org.apache.thrift.TException te) {\n throw new java.io.IOException(te);\n }\n }\n\n private static class md5_resultStandardSchemeFactory implements SchemeFactory {\n public md5_resultStandardScheme getScheme() {\n return new md5_resultStandardScheme();\n }\n }\n\n private static class md5_resultStandardScheme extends StandardScheme<md5_result> {\n\n public void read(org.apache.thrift.protocol.TProtocol iprot, md5_result struct) throws org.apache.thrift.TException {\n org.apache.thrift.protocol.TField schemeField;\n iprot.readStructBegin();\n while (true)\n {\n schemeField = iprot.readFieldBegin();\n if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { \n break;\n }\n switch (schemeField.id) {\n case 0: // SUCCESS\n if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {\n struct.success = iprot.readString();\n struct.setSuccessIsSet(true);\n } else { \n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\n }\n break;\n default:\n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\n }\n iprot.readFieldEnd();\n }\n iprot.readStructEnd();\n\n // check for required fields of primitive type, which can't be checked in the validate method\n struct.validate();\n }\n\n public void write(org.apache.thrift.protocol.TProtocol oprot, md5_result struct) throws org.apache.thrift.TException {\n struct.validate();\n\n oprot.writeStructBegin(STRUCT_DESC);\n if (struct.success != null) {\n oprot.writeFieldBegin(SUCCESS_FIELD_DESC);\n oprot.writeString(struct.success);\n oprot.writeFieldEnd();\n }\n oprot.writeFieldStop();\n oprot.writeStructEnd();\n }\n\n }\n\n private static class md5_resultTupleSchemeFactory implements SchemeFactory {\n public md5_resultTupleScheme getScheme() {\n return new md5_resultTupleScheme();\n }\n }\n\n private static class md5_resultTupleScheme extends TupleScheme<md5_result> {\n\n @Override\n public void write(org.apache.thrift.protocol.TProtocol prot, md5_result struct) throws org.apache.thrift.TException {\n TTupleProtocol oprot = (TTupleProtocol) prot;\n BitSet optionals = new BitSet();\n if (struct.isSetSuccess()) {\n optionals.set(0);\n }\n oprot.writeBitSet(optionals, 1);\n if (struct.isSetSuccess()) {\n oprot.writeString(struct.success);\n }\n }\n\n @Override\n public void read(org.apache.thrift.protocol.TProtocol prot, md5_result struct) throws org.apache.thrift.TException {\n TTupleProtocol iprot = (TTupleProtocol) prot;\n BitSet incoming = iprot.readBitSet(1);\n if (incoming.get(0)) {\n struct.success = iprot.readString();\n struct.setSuccessIsSet(true);\n }\n }\n }\n\n }\n\n public static class part_args implements org.apache.thrift.TBase<part_args, part_args._Fields>, java.io.Serializable, Cloneable, Comparable<part_args> {\n private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct(\"part_args\");\n\n private static final org.apache.thrift.protocol.TField FOLDER_FIELD_DESC = new org.apache.thrift.protocol.TField(\"folder\", org.apache.thrift.protocol.TType.STRING, (short)1);\n private static final org.apache.thrift.protocol.TField PATH_FIELD_DESC = new org.apache.thrift.protocol.TField(\"path\", org.apache.thrift.protocol.TType.STRING, (short)2);\n private static final org.apache.thrift.protocol.TField PART_FIELD_DESC = new org.apache.thrift.protocol.TField(\"part\", org.apache.thrift.protocol.TType.I64, (short)3);\n private static final org.apache.thrift.protocol.TField PART_SIZE_FIELD_DESC = new org.apache.thrift.protocol.TField(\"part_size\", org.apache.thrift.protocol.TType.I64, (short)4);\n\n private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();\n static {\n schemes.put(StandardScheme.class, new part_argsStandardSchemeFactory());\n schemes.put(TupleScheme.class, new part_argsTupleSchemeFactory());\n }\n\n public String folder; // required\n public String path; // required\n public long part; // required\n public long part_size; // required\n\n /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */\n public enum _Fields implements org.apache.thrift.TFieldIdEnum {\n FOLDER((short)1, \"folder\"),\n PATH((short)2, \"path\"),\n PART((short)3, \"part\"),\n PART_SIZE((short)4, \"part_size\");\n\n private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();\n\n static {\n for (_Fields field : EnumSet.allOf(_Fields.class)) {\n byName.put(field.getFieldName(), field);\n }\n }\n\n /**\n * Find the _Fields constant that matches fieldId, or null if its not found.\n */\n public static _Fields findByThriftId(int fieldId) {\n switch(fieldId) {\n case 1: // FOLDER\n return FOLDER;\n case 2: // PATH\n return PATH;\n case 3: // PART\n return PART;\n case 4: // PART_SIZE\n return PART_SIZE;\n default:\n return null;\n }\n }\n\n /**\n * Find the _Fields constant that matches fieldId, throwing an exception\n * if it is not found.\n */\n public static _Fields findByThriftIdOrThrow(int fieldId) {\n _Fields fields = findByThriftId(fieldId);\n if (fields == null) throw new IllegalArgumentException(\"Field \" + fieldId + \" doesn't exist!\");\n return fields;\n }\n\n /**\n * Find the _Fields constant that matches name, or null if its not found.\n */\n public static _Fields findByName(String name) {\n return byName.get(name);\n }\n\n private final short _thriftId;\n private final String _fieldName;\n\n _Fields(short thriftId, String fieldName) {\n _thriftId = thriftId;\n _fieldName = fieldName;\n }\n\n public short getThriftFieldId() {\n return _thriftId;\n }\n\n public String getFieldName() {\n return _fieldName;\n }\n }\n\n // isset id assignments\n private static final int __PART_ISSET_ID = 0;\n private static final int __PART_SIZE_ISSET_ID = 1;\n private byte __isset_bitfield = 0;\n public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;\n static {\n Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);\n tmpMap.put(_Fields.FOLDER, new org.apache.thrift.meta_data.FieldMetaData(\"folder\", org.apache.thrift.TFieldRequirementType.DEFAULT, \n new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));\n tmpMap.put(_Fields.PATH, new org.apache.thrift.meta_data.FieldMetaData(\"path\", org.apache.thrift.TFieldRequirementType.DEFAULT, \n new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));\n tmpMap.put(_Fields.PART, new org.apache.thrift.meta_data.FieldMetaData(\"part\", org.apache.thrift.TFieldRequirementType.DEFAULT, \n new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I64)));\n tmpMap.put(_Fields.PART_SIZE, new org.apache.thrift.meta_data.FieldMetaData(\"part_size\", org.apache.thrift.TFieldRequirementType.DEFAULT, \n new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I64)));\n metaDataMap = Collections.unmodifiableMap(tmpMap);\n org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(part_args.class, metaDataMap);\n }\n\n public part_args() {\n }\n\n public part_args(\n String folder,\n String path,\n long part,\n long part_size)\n {\n this();\n this.folder = folder;\n this.path = path;\n this.part = part;\n setPartIsSet(true);\n this.part_size = part_size;\n setPart_sizeIsSet(true);\n }\n\n /**\n * Performs a deep copy on <i>other</i>.\n */\n public part_args(part_args other) {\n __isset_bitfield = other.__isset_bitfield;\n if (other.isSetFolder()) {\n this.folder = other.folder;\n }\n if (other.isSetPath()) {\n this.path = other.path;\n }\n this.part = other.part;\n this.part_size = other.part_size;\n }\n\n public part_args deepCopy() {\n return new part_args(this);\n }\n\n @Override\n public void clear() {\n this.folder = null;\n this.path = null;\n setPartIsSet(false);\n this.part = 0;\n setPart_sizeIsSet(false);\n this.part_size = 0;\n }\n\n public String getFolder() {\n return this.folder;\n }\n\n public part_args setFolder(String folder) {\n this.folder = folder;\n return this;\n }\n\n public void unsetFolder() {\n this.folder = null;\n }\n\n /** Returns true if field folder is set (has been assigned a value) and false otherwise */\n public boolean isSetFolder() {\n return this.folder != null;\n }\n\n public void setFolderIsSet(boolean value) {\n if (!value) {\n this.folder = null;\n }\n }\n\n public String getPath() {\n return this.path;\n }\n\n public part_args setPath(String path) {\n this.path = path;\n return this;\n }\n\n public void unsetPath() {\n this.path = null;\n }\n\n /** Returns true if field path is set (has been assigned a value) and false otherwise */\n public boolean isSetPath() {\n return this.path != null;\n }\n\n public void setPathIsSet(boolean value) {\n if (!value) {\n this.path = null;\n }\n }\n\n public long getPart() {\n return this.part;\n }\n\n public part_args setPart(long part) {\n this.part = part;\n setPartIsSet(true);\n return this;\n }\n\n public void unsetPart() {\n __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __PART_ISSET_ID);\n }\n\n /** Returns true if field part is set (has been assigned a value) and false otherwise */\n public boolean isSetPart() {\n return EncodingUtils.testBit(__isset_bitfield, __PART_ISSET_ID);\n }\n\n public void setPartIsSet(boolean value) {\n __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __PART_ISSET_ID, value);\n }\n\n public long getPart_size() {\n return this.part_size;\n }\n\n public part_args setPart_size(long part_size) {\n this.part_size = part_size;\n setPart_sizeIsSet(true);\n return this;\n }\n\n public void unsetPart_size() {\n __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __PART_SIZE_ISSET_ID);\n }\n\n /** Returns true if field part_size is set (has been assigned a value) and false otherwise */\n public boolean isSetPart_size() {\n return EncodingUtils.testBit(__isset_bitfield, __PART_SIZE_ISSET_ID);\n }\n\n public void setPart_sizeIsSet(boolean value) {\n __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __PART_SIZE_ISSET_ID, value);\n }\n\n public void setFieldValue(_Fields field, Object value) {\n switch (field) {\n case FOLDER:\n if (value == null) {\n unsetFolder();\n } else {\n setFolder((String)value);\n }\n break;\n\n case PATH:\n if (value == null) {\n unsetPath();\n } else {\n setPath((String)value);\n }\n break;\n\n case PART:\n if (value == null) {\n unsetPart();\n } else {\n setPart((Long)value);\n }\n break;\n\n case PART_SIZE:\n if (value == null) {\n unsetPart_size();\n } else {\n setPart_size((Long)value);\n }\n break;\n\n }\n }\n\n public Object getFieldValue(_Fields field) {\n switch (field) {\n case FOLDER:\n return getFolder();\n\n case PATH:\n return getPath();\n\n case PART:\n return getPart();\n\n case PART_SIZE:\n return getPart_size();\n\n }\n throw new IllegalStateException();\n }\n\n /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */\n public boolean isSet(_Fields field) {\n if (field == null) {\n throw new IllegalArgumentException();\n }\n\n switch (field) {\n case FOLDER:\n return isSetFolder();\n case PATH:\n return isSetPath();\n case PART:\n return isSetPart();\n case PART_SIZE:\n return isSetPart_size();\n }\n throw new IllegalStateException();\n }\n\n @Override\n public boolean equals(Object that) {\n if (that == null)\n return false;\n if (that instanceof part_args)\n return this.equals((part_args)that);\n return false;\n }\n\n public boolean equals(part_args that) {\n if (that == null)\n return false;\n\n boolean this_present_folder = true && this.isSetFolder();\n boolean that_present_folder = true && that.isSetFolder();\n if (this_present_folder || that_present_folder) {\n if (!(this_present_folder && that_present_folder))\n return false;\n if (!this.folder.equals(that.folder))\n return false;\n }\n\n boolean this_present_path = true && this.isSetPath();\n boolean that_present_path = true && that.isSetPath();\n if (this_present_path || that_present_path) {\n if (!(this_present_path && that_present_path))\n return false;\n if (!this.path.equals(that.path))\n return false;\n }\n\n boolean this_present_part = true;\n boolean that_present_part = true;\n if (this_present_part || that_present_part) {\n if (!(this_present_part && that_present_part))\n return false;\n if (this.part != that.part)\n return false;\n }\n\n boolean this_present_part_size = true;\n boolean that_present_part_size = true;\n if (this_present_part_size || that_present_part_size) {\n if (!(this_present_part_size && that_present_part_size))\n return false;\n if (this.part_size != that.part_size)\n return false;\n }\n\n return true;\n }\n\n @Override\n public int hashCode() {\n List<Object> list = new ArrayList<Object>();\n\n boolean present_folder = true && (isSetFolder());\n list.add(present_folder);\n if (present_folder)\n list.add(folder);\n\n boolean present_path = true && (isSetPath());\n list.add(present_path);\n if (present_path)\n list.add(path);\n\n boolean present_part = true;\n list.add(present_part);\n if (present_part)\n list.add(part);\n\n boolean present_part_size = true;\n list.add(present_part_size);\n if (present_part_size)\n list.add(part_size);\n\n return list.hashCode();\n }\n\n @Override\n public int compareTo(part_args other) {\n if (!getClass().equals(other.getClass())) {\n return getClass().getName().compareTo(other.getClass().getName());\n }\n\n int lastComparison = 0;\n\n lastComparison = Boolean.valueOf(isSetFolder()).compareTo(other.isSetFolder());\n if (lastComparison != 0) {\n return lastComparison;\n }\n if (isSetFolder()) {\n lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.folder, other.folder);\n if (lastComparison != 0) {\n return lastComparison;\n }\n }\n lastComparison = Boolean.valueOf(isSetPath()).compareTo(other.isSetPath());\n if (lastComparison != 0) {\n return lastComparison;\n }\n if (isSetPath()) {\n lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.path, other.path);\n if (lastComparison != 0) {\n return lastComparison;\n }\n }\n lastComparison = Boolean.valueOf(isSetPart()).compareTo(other.isSetPart());\n if (lastComparison != 0) {\n return lastComparison;\n }\n if (isSetPart()) {\n lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.part, other.part);\n if (lastComparison != 0) {\n return lastComparison;\n }\n }\n lastComparison = Boolean.valueOf(isSetPart_size()).compareTo(other.isSetPart_size());\n if (lastComparison != 0) {\n return lastComparison;\n }\n if (isSetPart_size()) {\n lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.part_size, other.part_size);\n if (lastComparison != 0) {\n return lastComparison;\n }\n }\n return 0;\n }\n\n public _Fields fieldForId(int fieldId) {\n return _Fields.findByThriftId(fieldId);\n }\n\n public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {\n schemes.get(iprot.getScheme()).getScheme().read(iprot, this);\n }\n\n public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {\n schemes.get(oprot.getScheme()).getScheme().write(oprot, this);\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder(\"part_args(\");\n boolean first = true;\n\n sb.append(\"folder:\");\n if (this.folder == null) {\n sb.append(\"null\");\n } else {\n sb.append(this.folder);\n }\n first = false;\n if (!first) sb.append(\", \");\n sb.append(\"path:\");\n if (this.path == null) {\n sb.append(\"null\");\n } else {\n sb.append(this.path);\n }\n first = false;\n if (!first) sb.append(\", \");\n sb.append(\"part:\");\n sb.append(this.part);\n first = false;\n if (!first) sb.append(\", \");\n sb.append(\"part_size:\");\n sb.append(this.part_size);\n first = false;\n sb.append(\")\");\n return sb.toString();\n }\n\n public void validate() throws org.apache.thrift.TException {\n // check for required fields\n // check for sub-struct validity\n }\n\n private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {\n try {\n write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));\n } catch (org.apache.thrift.TException te) {\n throw new java.io.IOException(te);\n }\n }\n\n private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {\n try {\n // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor.\n __isset_bitfield = 0;\n read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));\n } catch (org.apache.thrift.TException te) {\n throw new java.io.IOException(te);\n }\n }\n\n private static class part_argsStandardSchemeFactory implements SchemeFactory {\n public part_argsStandardScheme getScheme() {\n return new part_argsStandardScheme();\n }\n }\n\n private static class part_argsStandardScheme extends StandardScheme<part_args> {\n\n public void read(org.apache.thrift.protocol.TProtocol iprot, part_args struct) throws org.apache.thrift.TException {\n org.apache.thrift.protocol.TField schemeField;\n iprot.readStructBegin();\n while (true)\n {\n schemeField = iprot.readFieldBegin();\n if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { \n break;\n }\n switch (schemeField.id) {\n case 1: // FOLDER\n if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {\n struct.folder = iprot.readString();\n struct.setFolderIsSet(true);\n } else { \n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\n }\n break;\n case 2: // PATH\n if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {\n struct.path = iprot.readString();\n struct.setPathIsSet(true);\n } else { \n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\n }\n break;\n case 3: // PART\n if (schemeField.type == org.apache.thrift.protocol.TType.I64) {\n struct.part = iprot.readI64();\n struct.setPartIsSet(true);\n } else { \n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\n }\n break;\n case 4: // PART_SIZE\n if (schemeField.type == org.apache.thrift.protocol.TType.I64) {\n struct.part_size = iprot.readI64();\n struct.setPart_sizeIsSet(true);\n } else { \n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\n }\n break;\n default:\n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\n }\n iprot.readFieldEnd();\n }\n iprot.readStructEnd();\n\n // check for required fields of primitive type, which can't be checked in the validate method\n struct.validate();\n }\n\n public void write(org.apache.thrift.protocol.TProtocol oprot, part_args struct) throws org.apache.thrift.TException {\n struct.validate();\n\n oprot.writeStructBegin(STRUCT_DESC);\n if (struct.folder != null) {\n oprot.writeFieldBegin(FOLDER_FIELD_DESC);\n oprot.writeString(struct.folder);\n oprot.writeFieldEnd();\n }\n if (struct.path != null) {\n oprot.writeFieldBegin(PATH_FIELD_DESC);\n oprot.writeString(struct.path);\n oprot.writeFieldEnd();\n }\n oprot.writeFieldBegin(PART_FIELD_DESC);\n oprot.writeI64(struct.part);\n oprot.writeFieldEnd();\n oprot.writeFieldBegin(PART_SIZE_FIELD_DESC);\n oprot.writeI64(struct.part_size);\n oprot.writeFieldEnd();\n oprot.writeFieldStop();\n oprot.writeStructEnd();\n }\n\n }\n\n private static class part_argsTupleSchemeFactory implements SchemeFactory {\n public part_argsTupleScheme getScheme() {\n return new part_argsTupleScheme();\n }\n }\n\n private static class part_argsTupleScheme extends TupleScheme<part_args> {\n\n @Override\n public void write(org.apache.thrift.protocol.TProtocol prot, part_args struct) throws org.apache.thrift.TException {\n TTupleProtocol oprot = (TTupleProtocol) prot;\n BitSet optionals = new BitSet();\n if (struct.isSetFolder()) {\n optionals.set(0);\n }\n if (struct.isSetPath()) {\n optionals.set(1);\n }\n if (struct.isSetPart()) {\n optionals.set(2);\n }\n if (struct.isSetPart_size()) {\n optionals.set(3);\n }\n oprot.writeBitSet(optionals, 4);\n if (struct.isSetFolder()) {\n oprot.writeString(struct.folder);\n }\n if (struct.isSetPath()) {\n oprot.writeString(struct.path);\n }\n if (struct.isSetPart()) {\n oprot.writeI64(struct.part);\n }\n if (struct.isSetPart_size()) {\n oprot.writeI64(struct.part_size);\n }\n }\n\n @Override\n public void read(org.apache.thrift.protocol.TProtocol prot, part_args struct) throws org.apache.thrift.TException {\n TTupleProtocol iprot = (TTupleProtocol) prot;\n BitSet incoming = iprot.readBitSet(4);\n if (incoming.get(0)) {\n struct.folder = iprot.readString();\n struct.setFolderIsSet(true);\n }\n if (incoming.get(1)) {\n struct.path = iprot.readString();\n struct.setPathIsSet(true);\n }\n if (incoming.get(2)) {\n struct.part = iprot.readI64();\n struct.setPartIsSet(true);\n }\n if (incoming.get(3)) {\n struct.part_size = iprot.readI64();\n struct.setPart_sizeIsSet(true);\n }\n }\n }\n\n }\n\n public static class part_result implements org.apache.thrift.TBase<part_result, part_result._Fields>, java.io.Serializable, Cloneable, Comparable<part_result> {\n private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct(\"part_result\");\n\n private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField(\"success\", org.apache.thrift.protocol.TType.STRING, (short)0);\n\n private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();\n static {\n schemes.put(StandardScheme.class, new part_resultStandardSchemeFactory());\n schemes.put(TupleScheme.class, new part_resultTupleSchemeFactory());\n }\n\n public ByteBuffer success; // required\n\n /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */\n public enum _Fields implements org.apache.thrift.TFieldIdEnum {\n SUCCESS((short)0, \"success\");\n\n private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();\n\n static {\n for (_Fields field : EnumSet.allOf(_Fields.class)) {\n byName.put(field.getFieldName(), field);\n }\n }\n\n /**\n * Find the _Fields constant that matches fieldId, or null if its not found.\n */\n public static _Fields findByThriftId(int fieldId) {\n switch(fieldId) {\n case 0: // SUCCESS\n return SUCCESS;\n default:\n return null;\n }\n }\n\n /**\n * Find the _Fields constant that matches fieldId, throwing an exception\n * if it is not found.\n */\n public static _Fields findByThriftIdOrThrow(int fieldId) {\n _Fields fields = findByThriftId(fieldId);\n if (fields == null) throw new IllegalArgumentException(\"Field \" + fieldId + \" doesn't exist!\");\n return fields;\n }\n\n /**\n * Find the _Fields constant that matches name, or null if its not found.\n */\n public static _Fields findByName(String name) {\n return byName.get(name);\n }\n\n private final short _thriftId;\n private final String _fieldName;\n\n _Fields(short thriftId, String fieldName) {\n _thriftId = thriftId;\n _fieldName = fieldName;\n }\n\n public short getThriftFieldId() {\n return _thriftId;\n }\n\n public String getFieldName() {\n return _fieldName;\n }\n }\n\n // isset id assignments\n public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;\n static {\n Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);\n tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData(\"success\", org.apache.thrift.TFieldRequirementType.DEFAULT, \n new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING , true)));\n metaDataMap = Collections.unmodifiableMap(tmpMap);\n org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(part_result.class, metaDataMap);\n }\n\n public part_result() {\n }\n\n public part_result(\n ByteBuffer success)\n {\n this();\n this.success = org.apache.thrift.TBaseHelper.copyBinary(success);\n }\n\n /**\n * Performs a deep copy on <i>other</i>.\n */\n public part_result(part_result other) {\n if (other.isSetSuccess()) {\n this.success = org.apache.thrift.TBaseHelper.copyBinary(other.success);\n }\n }\n\n public part_result deepCopy() {\n return new part_result(this);\n }\n\n @Override\n public void clear() {\n this.success = null;\n }\n\n public byte[] getSuccess() {\n setSuccess(org.apache.thrift.TBaseHelper.rightSize(success));\n return success == null ? null : success.array();\n }\n\n public ByteBuffer bufferForSuccess() {\n return org.apache.thrift.TBaseHelper.copyBinary(success);\n }\n\n public part_result setSuccess(byte[] success) {\n this.success = success == null ? (ByteBuffer)null : ByteBuffer.wrap(Arrays.copyOf(success, success.length));\n return this;\n }\n\n public part_result setSuccess(ByteBuffer success) {\n this.success = org.apache.thrift.TBaseHelper.copyBinary(success);\n return this;\n }\n\n public void unsetSuccess() {\n this.success = null;\n }\n\n /** Returns true if field success is set (has been assigned a value) and false otherwise */\n public boolean isSetSuccess() {\n return this.success != null;\n }\n\n public void setSuccessIsSet(boolean value) {\n if (!value) {\n this.success = null;\n }\n }\n\n public void setFieldValue(_Fields field, Object value) {\n switch (field) {\n case SUCCESS:\n if (value == null) {\n unsetSuccess();\n } else {\n setSuccess((ByteBuffer)value);\n }\n break;\n\n }\n }\n\n public Object getFieldValue(_Fields field) {\n switch (field) {\n case SUCCESS:\n return getSuccess();\n\n }\n throw new IllegalStateException();\n }\n\n /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */\n public boolean isSet(_Fields field) {\n if (field == null) {\n throw new IllegalArgumentException();\n }\n\n switch (field) {\n case SUCCESS:\n return isSetSuccess();\n }\n throw new IllegalStateException();\n }\n\n @Override\n public boolean equals(Object that) {\n if (that == null)\n return false;\n if (that instanceof part_result)\n return this.equals((part_result)that);\n return false;\n }\n\n public boolean equals(part_result that) {\n if (that == null)\n return false;\n\n boolean this_present_success = true && this.isSetSuccess();\n boolean that_present_success = true && that.isSetSuccess();\n if (this_present_success || that_present_success) {\n if (!(this_present_success && that_present_success))\n return false;\n if (!this.success.equals(that.success))\n return false;\n }\n\n return true;\n }\n\n @Override\n public int hashCode() {\n List<Object> list = new ArrayList<Object>();\n\n boolean present_success = true && (isSetSuccess());\n list.add(present_success);\n if (present_success)\n list.add(success);\n\n return list.hashCode();\n }\n\n @Override\n public int compareTo(part_result other) {\n if (!getClass().equals(other.getClass())) {\n return getClass().getName().compareTo(other.getClass().getName());\n }\n\n int lastComparison = 0;\n\n lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess());\n if (lastComparison != 0) {\n return lastComparison;\n }\n if (isSetSuccess()) {\n lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success);\n if (lastComparison != 0) {\n return lastComparison;\n }\n }\n return 0;\n }\n\n public _Fields fieldForId(int fieldId) {\n return _Fields.findByThriftId(fieldId);\n }\n\n public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {\n schemes.get(iprot.getScheme()).getScheme().read(iprot, this);\n }\n\n public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {\n schemes.get(oprot.getScheme()).getScheme().write(oprot, this);\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder(\"part_result(\");\n boolean first = true;\n\n sb.append(\"success:\");\n if (this.success == null) {\n sb.append(\"null\");\n } else {\n org.apache.thrift.TBaseHelper.toString(this.success, sb);\n }\n first = false;\n sb.append(\")\");\n return sb.toString();\n }\n\n public void validate() throws org.apache.thrift.TException {\n // check for required fields\n // check for sub-struct validity\n }\n\n private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {\n try {\n write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));\n } catch (org.apache.thrift.TException te) {\n throw new java.io.IOException(te);\n }\n }\n\n private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {\n try {\n read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));\n } catch (org.apache.thrift.TException te) {\n throw new java.io.IOException(te);\n }\n }\n\n private static class part_resultStandardSchemeFactory implements SchemeFactory {\n public part_resultStandardScheme getScheme() {\n return new part_resultStandardScheme();\n }\n }\n\n private static class part_resultStandardScheme extends StandardScheme<part_result> {\n\n public void read(org.apache.thrift.protocol.TProtocol iprot, part_result struct) throws org.apache.thrift.TException {\n org.apache.thrift.protocol.TField schemeField;\n iprot.readStructBegin();\n while (true)\n {\n schemeField = iprot.readFieldBegin();\n if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { \n break;\n }\n switch (schemeField.id) {\n case 0: // SUCCESS\n if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {\n struct.success = iprot.readBinary();\n struct.setSuccessIsSet(true);\n } else { \n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\n }\n break;\n default:\n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\n }\n iprot.readFieldEnd();\n }\n iprot.readStructEnd();\n\n // check for required fields of primitive type, which can't be checked in the validate method\n struct.validate();\n }\n\n public void write(org.apache.thrift.protocol.TProtocol oprot, part_result struct) throws org.apache.thrift.TException {\n struct.validate();\n\n oprot.writeStructBegin(STRUCT_DESC);\n if (struct.success != null) {\n oprot.writeFieldBegin(SUCCESS_FIELD_DESC);\n oprot.writeBinary(struct.success);\n oprot.writeFieldEnd();\n }\n oprot.writeFieldStop();\n oprot.writeStructEnd();\n }\n\n }\n\n private static class part_resultTupleSchemeFactory implements SchemeFactory {\n public part_resultTupleScheme getScheme() {\n return new part_resultTupleScheme();\n }\n }\n\n private static class part_resultTupleScheme extends TupleScheme<part_result> {\n\n @Override\n public void write(org.apache.thrift.protocol.TProtocol prot, part_result struct) throws org.apache.thrift.TException {\n TTupleProtocol oprot = (TTupleProtocol) prot;\n BitSet optionals = new BitSet();\n if (struct.isSetSuccess()) {\n optionals.set(0);\n }\n oprot.writeBitSet(optionals, 1);\n if (struct.isSetSuccess()) {\n oprot.writeBinary(struct.success);\n }\n }\n\n @Override\n public void read(org.apache.thrift.protocol.TProtocol prot, part_result struct) throws org.apache.thrift.TException {\n TTupleProtocol iprot = (TTupleProtocol) prot;\n BitSet incoming = iprot.readBitSet(1);\n if (incoming.get(0)) {\n struct.success = iprot.readBinary();\n struct.setSuccessIsSet(true);\n }\n }\n }\n\n }\n\n public static class listFiles_args implements org.apache.thrift.TBase<listFiles_args, listFiles_args._Fields>, java.io.Serializable, Cloneable, Comparable<listFiles_args> {\n private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct(\"listFiles_args\");\n\n private static final org.apache.thrift.protocol.TField FOLDER_FIELD_DESC = new org.apache.thrift.protocol.TField(\"folder\", org.apache.thrift.protocol.TType.STRING, (short)1);\n private static final org.apache.thrift.protocol.TField PATH_FIELD_DESC = new org.apache.thrift.protocol.TField(\"path\", org.apache.thrift.protocol.TType.STRING, (short)2);\n\n private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();\n static {\n schemes.put(StandardScheme.class, new listFiles_argsStandardSchemeFactory());\n schemes.put(TupleScheme.class, new listFiles_argsTupleSchemeFactory());\n }\n\n public String folder; // required\n public String path; // required\n\n /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */\n public enum _Fields implements org.apache.thrift.TFieldIdEnum {\n FOLDER((short)1, \"folder\"),\n PATH((short)2, \"path\");\n\n private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();\n\n static {\n for (_Fields field : EnumSet.allOf(_Fields.class)) {\n byName.put(field.getFieldName(), field);\n }\n }\n\n /**\n * Find the _Fields constant that matches fieldId, or null if its not found.\n */\n public static _Fields findByThriftId(int fieldId) {\n switch(fieldId) {\n case 1: // FOLDER\n return FOLDER;\n case 2: // PATH\n return PATH;\n default:\n return null;\n }\n }\n\n /**\n * Find the _Fields constant that matches fieldId, throwing an exception\n * if it is not found.\n */\n public static _Fields findByThriftIdOrThrow(int fieldId) {\n _Fields fields = findByThriftId(fieldId);\n if (fields == null) throw new IllegalArgumentException(\"Field \" + fieldId + \" doesn't exist!\");\n return fields;\n }\n\n /**\n * Find the _Fields constant that matches name, or null if its not found.\n */\n public static _Fields findByName(String name) {\n return byName.get(name);\n }\n\n private final short _thriftId;\n private final String _fieldName;\n\n _Fields(short thriftId, String fieldName) {\n _thriftId = thriftId;\n _fieldName = fieldName;\n }\n\n public short getThriftFieldId() {\n return _thriftId;\n }\n\n public String getFieldName() {\n return _fieldName;\n }\n }\n\n // isset id assignments\n public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;\n static {\n Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);\n tmpMap.put(_Fields.FOLDER, new org.apache.thrift.meta_data.FieldMetaData(\"folder\", org.apache.thrift.TFieldRequirementType.DEFAULT, \n new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));\n tmpMap.put(_Fields.PATH, new org.apache.thrift.meta_data.FieldMetaData(\"path\", org.apache.thrift.TFieldRequirementType.DEFAULT, \n new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));\n metaDataMap = Collections.unmodifiableMap(tmpMap);\n org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(listFiles_args.class, metaDataMap);\n }\n\n public listFiles_args() {\n }\n\n public listFiles_args(\n String folder,\n String path)\n {\n this();\n this.folder = folder;\n this.path = path;\n }\n\n /**\n * Performs a deep copy on <i>other</i>.\n */\n public listFiles_args(listFiles_args other) {\n if (other.isSetFolder()) {\n this.folder = other.folder;\n }\n if (other.isSetPath()) {\n this.path = other.path;\n }\n }\n\n public listFiles_args deepCopy() {\n return new listFiles_args(this);\n }\n\n @Override\n public void clear() {\n this.folder = null;\n this.path = null;\n }\n\n public String getFolder() {\n return this.folder;\n }\n\n public listFiles_args setFolder(String folder) {\n this.folder = folder;\n return this;\n }\n\n public void unsetFolder() {\n this.folder = null;\n }\n\n /** Returns true if field folder is set (has been assigned a value) and false otherwise */\n public boolean isSetFolder() {\n return this.folder != null;\n }\n\n public void setFolderIsSet(boolean value) {\n if (!value) {\n this.folder = null;\n }\n }\n\n public String getPath() {\n return this.path;\n }\n\n public listFiles_args setPath(String path) {\n this.path = path;\n return this;\n }\n\n public void unsetPath() {\n this.path = null;\n }\n\n /** Returns true if field path is set (has been assigned a value) and false otherwise */\n public boolean isSetPath() {\n return this.path != null;\n }\n\n public void setPathIsSet(boolean value) {\n if (!value) {\n this.path = null;\n }\n }\n\n public void setFieldValue(_Fields field, Object value) {\n switch (field) {\n case FOLDER:\n if (value == null) {\n unsetFolder();\n } else {\n setFolder((String)value);\n }\n break;\n\n case PATH:\n if (value == null) {\n unsetPath();\n } else {\n setPath((String)value);\n }\n break;\n\n }\n }\n\n public Object getFieldValue(_Fields field) {\n switch (field) {\n case FOLDER:\n return getFolder();\n\n case PATH:\n return getPath();\n\n }\n throw new IllegalStateException();\n }\n\n /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */\n public boolean isSet(_Fields field) {\n if (field == null) {\n throw new IllegalArgumentException();\n }\n\n switch (field) {\n case FOLDER:\n return isSetFolder();\n case PATH:\n return isSetPath();\n }\n throw new IllegalStateException();\n }\n\n @Override\n public boolean equals(Object that) {\n if (that == null)\n return false;\n if (that instanceof listFiles_args)\n return this.equals((listFiles_args)that);\n return false;\n }\n\n public boolean equals(listFiles_args that) {\n if (that == null)\n return false;\n\n boolean this_present_folder = true && this.isSetFolder();\n boolean that_present_folder = true && that.isSetFolder();\n if (this_present_folder || that_present_folder) {\n if (!(this_present_folder && that_present_folder))\n return false;\n if (!this.folder.equals(that.folder))\n return false;\n }\n\n boolean this_present_path = true && this.isSetPath();\n boolean that_present_path = true && that.isSetPath();\n if (this_present_path || that_present_path) {\n if (!(this_present_path && that_present_path))\n return false;\n if (!this.path.equals(that.path))\n return false;\n }\n\n return true;\n }\n\n @Override\n public int hashCode() {\n List<Object> list = new ArrayList<Object>();\n\n boolean present_folder = true && (isSetFolder());\n list.add(present_folder);\n if (present_folder)\n list.add(folder);\n\n boolean present_path = true && (isSetPath());\n list.add(present_path);\n if (present_path)\n list.add(path);\n\n return list.hashCode();\n }\n\n @Override\n public int compareTo(listFiles_args other) {\n if (!getClass().equals(other.getClass())) {\n return getClass().getName().compareTo(other.getClass().getName());\n }\n\n int lastComparison = 0;\n\n lastComparison = Boolean.valueOf(isSetFolder()).compareTo(other.isSetFolder());\n if (lastComparison != 0) {\n return lastComparison;\n }\n if (isSetFolder()) {\n lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.folder, other.folder);\n if (lastComparison != 0) {\n return lastComparison;\n }\n }\n lastComparison = Boolean.valueOf(isSetPath()).compareTo(other.isSetPath());\n if (lastComparison != 0) {\n return lastComparison;\n }\n if (isSetPath()) {\n lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.path, other.path);\n if (lastComparison != 0) {\n return lastComparison;\n }\n }\n return 0;\n }\n\n public _Fields fieldForId(int fieldId) {\n return _Fields.findByThriftId(fieldId);\n }\n\n public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {\n schemes.get(iprot.getScheme()).getScheme().read(iprot, this);\n }\n\n public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {\n schemes.get(oprot.getScheme()).getScheme().write(oprot, this);\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder(\"listFiles_args(\");\n boolean first = true;\n\n sb.append(\"folder:\");\n if (this.folder == null) {\n sb.append(\"null\");\n } else {\n sb.append(this.folder);\n }\n first = false;\n if (!first) sb.append(\", \");\n sb.append(\"path:\");\n if (this.path == null) {\n sb.append(\"null\");\n } else {\n sb.append(this.path);\n }\n first = false;\n sb.append(\")\");\n return sb.toString();\n }\n\n public void validate() throws org.apache.thrift.TException {\n // check for required fields\n // check for sub-struct validity\n }\n\n private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {\n try {\n write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));\n } catch (org.apache.thrift.TException te) {\n throw new java.io.IOException(te);\n }\n }\n\n private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {\n try {\n read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));\n } catch (org.apache.thrift.TException te) {\n throw new java.io.IOException(te);\n }\n }\n\n private static class listFiles_argsStandardSchemeFactory implements SchemeFactory {\n public listFiles_argsStandardScheme getScheme() {\n return new listFiles_argsStandardScheme();\n }\n }\n\n private static class listFiles_argsStandardScheme extends StandardScheme<listFiles_args> {\n\n public void read(org.apache.thrift.protocol.TProtocol iprot, listFiles_args struct) throws org.apache.thrift.TException {\n org.apache.thrift.protocol.TField schemeField;\n iprot.readStructBegin();\n while (true)\n {\n schemeField = iprot.readFieldBegin();\n if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { \n break;\n }\n switch (schemeField.id) {\n case 1: // FOLDER\n if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {\n struct.folder = iprot.readString();\n struct.setFolderIsSet(true);\n } else { \n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\n }\n break;\n case 2: // PATH\n if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {\n struct.path = iprot.readString();\n struct.setPathIsSet(true);\n } else { \n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\n }\n break;\n default:\n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\n }\n iprot.readFieldEnd();\n }\n iprot.readStructEnd();\n\n // check for required fields of primitive type, which can't be checked in the validate method\n struct.validate();\n }\n\n public void write(org.apache.thrift.protocol.TProtocol oprot, listFiles_args struct) throws org.apache.thrift.TException {\n struct.validate();\n\n oprot.writeStructBegin(STRUCT_DESC);\n if (struct.folder != null) {\n oprot.writeFieldBegin(FOLDER_FIELD_DESC);\n oprot.writeString(struct.folder);\n oprot.writeFieldEnd();\n }\n if (struct.path != null) {\n oprot.writeFieldBegin(PATH_FIELD_DESC);\n oprot.writeString(struct.path);\n oprot.writeFieldEnd();\n }\n oprot.writeFieldStop();\n oprot.writeStructEnd();\n }\n\n }\n\n private static class listFiles_argsTupleSchemeFactory implements SchemeFactory {\n public listFiles_argsTupleScheme getScheme() {\n return new listFiles_argsTupleScheme();\n }\n }\n\n private static class listFiles_argsTupleScheme extends TupleScheme<listFiles_args> {\n\n @Override\n public void write(org.apache.thrift.protocol.TProtocol prot, listFiles_args struct) throws org.apache.thrift.TException {\n TTupleProtocol oprot = (TTupleProtocol) prot;\n BitSet optionals = new BitSet();\n if (struct.isSetFolder()) {\n optionals.set(0);\n }\n if (struct.isSetPath()) {\n optionals.set(1);\n }\n oprot.writeBitSet(optionals, 2);\n if (struct.isSetFolder()) {\n oprot.writeString(struct.folder);\n }\n if (struct.isSetPath()) {\n oprot.writeString(struct.path);\n }\n }\n\n @Override\n public void read(org.apache.thrift.protocol.TProtocol prot, listFiles_args struct) throws org.apache.thrift.TException {\n TTupleProtocol iprot = (TTupleProtocol) prot;\n BitSet incoming = iprot.readBitSet(2);\n if (incoming.get(0)) {\n struct.folder = iprot.readString();\n struct.setFolderIsSet(true);\n }\n if (incoming.get(1)) {\n struct.path = iprot.readString();\n struct.setPathIsSet(true);\n }\n }\n }\n\n }\n\n public static class listFiles_result implements org.apache.thrift.TBase<listFiles_result, listFiles_result._Fields>, java.io.Serializable, Cloneable, Comparable<listFiles_result> {\n private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct(\"listFiles_result\");\n\n private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField(\"success\", org.apache.thrift.protocol.TType.LIST, (short)0);\n\n private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();\n static {\n schemes.put(StandardScheme.class, new listFiles_resultStandardSchemeFactory());\n schemes.put(TupleScheme.class, new listFiles_resultTupleSchemeFactory());\n }\n\n public List<RemoteFileInfo> success; // required\n\n /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */\n public enum _Fields implements org.apache.thrift.TFieldIdEnum {\n SUCCESS((short)0, \"success\");\n\n private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();\n\n static {\n for (_Fields field : EnumSet.allOf(_Fields.class)) {\n byName.put(field.getFieldName(), field);\n }\n }\n\n /**\n * Find the _Fields constant that matches fieldId, or null if its not found.\n */\n public static _Fields findByThriftId(int fieldId) {\n switch(fieldId) {\n case 0: // SUCCESS\n return SUCCESS;\n default:\n return null;\n }\n }\n\n /**\n * Find the _Fields constant that matches fieldId, throwing an exception\n * if it is not found.\n */\n public static _Fields findByThriftIdOrThrow(int fieldId) {\n _Fields fields = findByThriftId(fieldId);\n if (fields == null) throw new IllegalArgumentException(\"Field \" + fieldId + \" doesn't exist!\");\n return fields;\n }\n\n /**\n * Find the _Fields constant that matches name, or null if its not found.\n */\n public static _Fields findByName(String name) {\n return byName.get(name);\n }\n\n private final short _thriftId;\n private final String _fieldName;\n\n _Fields(short thriftId, String fieldName) {\n _thriftId = thriftId;\n _fieldName = fieldName;\n }\n\n public short getThriftFieldId() {\n return _thriftId;\n }\n\n public String getFieldName() {\n return _fieldName;\n }\n }\n\n // isset id assignments\n public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;\n static {\n Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);\n tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData(\"success\", org.apache.thrift.TFieldRequirementType.DEFAULT, \n new org.apache.thrift.meta_data.ListMetaData(org.apache.thrift.protocol.TType.LIST, \n new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, RemoteFileInfo.class))));\n metaDataMap = Collections.unmodifiableMap(tmpMap);\n org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(listFiles_result.class, metaDataMap);\n }\n\n public listFiles_result() {\n }\n\n public listFiles_result(\n List<RemoteFileInfo> success)\n {\n this();\n this.success = success;\n }\n\n /**\n * Performs a deep copy on <i>other</i>.\n */\n public listFiles_result(listFiles_result other) {\n if (other.isSetSuccess()) {\n List<RemoteFileInfo> __this__success = new ArrayList<RemoteFileInfo>(other.success.size());\n for (RemoteFileInfo other_element : other.success) {\n __this__success.add(new RemoteFileInfo(other_element));\n }\n this.success = __this__success;\n }\n }\n\n public listFiles_result deepCopy() {\n return new listFiles_result(this);\n }\n\n @Override\n public void clear() {\n this.success = null;\n }\n\n public int getSuccessSize() {\n return (this.success == null) ? 0 : this.success.size();\n }\n\n public java.util.Iterator<RemoteFileInfo> getSuccessIterator() {\n return (this.success == null) ? null : this.success.iterator();\n }\n\n public void addToSuccess(RemoteFileInfo elem) {\n if (this.success == null) {\n this.success = new ArrayList<RemoteFileInfo>();\n }\n this.success.add(elem);\n }\n\n public List<RemoteFileInfo> getSuccess() {\n return this.success;\n }\n\n public listFiles_result setSuccess(List<RemoteFileInfo> success) {\n this.success = success;\n return this;\n }\n\n public void unsetSuccess() {\n this.success = null;\n }\n\n /** Returns true if field success is set (has been assigned a value) and false otherwise */\n public boolean isSetSuccess() {\n return this.success != null;\n }\n\n public void setSuccessIsSet(boolean value) {\n if (!value) {\n this.success = null;\n }\n }\n\n public void setFieldValue(_Fields field, Object value) {\n switch (field) {\n case SUCCESS:\n if (value == null) {\n unsetSuccess();\n } else {\n setSuccess((List<RemoteFileInfo>)value);\n }\n break;\n\n }\n }\n\n public Object getFieldValue(_Fields field) {\n switch (field) {\n case SUCCESS:\n return getSuccess();\n\n }\n throw new IllegalStateException();\n }\n\n /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */\n public boolean isSet(_Fields field) {\n if (field == null) {\n throw new IllegalArgumentException();\n }\n\n switch (field) {\n case SUCCESS:\n return isSetSuccess();\n }\n throw new IllegalStateException();\n }\n\n @Override\n public boolean equals(Object that) {\n if (that == null)\n return false;\n if (that instanceof listFiles_result)\n return this.equals((listFiles_result)that);\n return false;\n }\n\n public boolean equals(listFiles_result that) {\n if (that == null)\n return false;\n\n boolean this_present_success = true && this.isSetSuccess();\n boolean that_present_success = true && that.isSetSuccess();\n if (this_present_success || that_present_success) {\n if (!(this_present_success && that_present_success))\n return false;\n if (!this.success.equals(that.success))\n return false;\n }\n\n return true;\n }\n\n @Override\n public int hashCode() {\n List<Object> list = new ArrayList<Object>();\n\n boolean present_success = true && (isSetSuccess());\n list.add(present_success);\n if (present_success)\n list.add(success);\n\n return list.hashCode();\n }\n\n @Override\n public int compareTo(listFiles_result other) {\n if (!getClass().equals(other.getClass())) {\n return getClass().getName().compareTo(other.getClass().getName());\n }\n\n int lastComparison = 0;\n\n lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess());\n if (lastComparison != 0) {\n return lastComparison;\n }\n if (isSetSuccess()) {\n lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success);\n if (lastComparison != 0) {\n return lastComparison;\n }\n }\n return 0;\n }\n\n public _Fields fieldForId(int fieldId) {\n return _Fields.findByThriftId(fieldId);\n }\n\n public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {\n schemes.get(iprot.getScheme()).getScheme().read(iprot, this);\n }\n\n public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {\n schemes.get(oprot.getScheme()).getScheme().write(oprot, this);\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder(\"listFiles_result(\");\n boolean first = true;\n\n sb.append(\"success:\");\n if (this.success == null) {\n sb.append(\"null\");\n } else {\n sb.append(this.success);\n }\n first = false;\n sb.append(\")\");\n return sb.toString();\n }\n\n public void validate() throws org.apache.thrift.TException {\n // check for required fields\n // check for sub-struct validity\n }\n\n private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {\n try {\n write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));\n } catch (org.apache.thrift.TException te) {\n throw new java.io.IOException(te);\n }\n }\n\n private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {\n try {\n read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));\n } catch (org.apache.thrift.TException te) {\n throw new java.io.IOException(te);\n }\n }\n\n private static class listFiles_resultStandardSchemeFactory implements SchemeFactory {\n public listFiles_resultStandardScheme getScheme() {\n return new listFiles_resultStandardScheme();\n }\n }\n\n private static class listFiles_resultStandardScheme extends StandardScheme<listFiles_result> {\n\n public void read(org.apache.thrift.protocol.TProtocol iprot, listFiles_result struct) throws org.apache.thrift.TException {\n org.apache.thrift.protocol.TField schemeField;\n iprot.readStructBegin();\n while (true)\n {\n schemeField = iprot.readFieldBegin();\n if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { \n break;\n }\n switch (schemeField.id) {\n case 0: // SUCCESS\n if (schemeField.type == org.apache.thrift.protocol.TType.LIST) {\n {\n org.apache.thrift.protocol.TList _list0 = iprot.readListBegin();\n struct.success = new ArrayList<RemoteFileInfo>(_list0.size);\n RemoteFileInfo _elem1;\n for (int _i2 = 0; _i2 < _list0.size; ++_i2)\n {\n _elem1 = new RemoteFileInfo();\n _elem1.read(iprot);\n struct.success.add(_elem1);\n }\n iprot.readListEnd();\n }\n struct.setSuccessIsSet(true);\n } else { \n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\n }\n break;\n default:\n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\n }\n iprot.readFieldEnd();\n }\n iprot.readStructEnd();\n\n // check for required fields of primitive type, which can't be checked in the validate method\n struct.validate();\n }\n\n public void write(org.apache.thrift.protocol.TProtocol oprot, listFiles_result struct) throws org.apache.thrift.TException {\n struct.validate();\n\n oprot.writeStructBegin(STRUCT_DESC);\n if (struct.success != null) {\n oprot.writeFieldBegin(SUCCESS_FIELD_DESC);\n {\n oprot.writeListBegin(new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, struct.success.size()));\n for (RemoteFileInfo _iter3 : struct.success)\n {\n _iter3.write(oprot);\n }\n oprot.writeListEnd();\n }\n oprot.writeFieldEnd();\n }\n oprot.writeFieldStop();\n oprot.writeStructEnd();\n }\n\n }\n\n private static class listFiles_resultTupleSchemeFactory implements SchemeFactory {\n public listFiles_resultTupleScheme getScheme() {\n return new listFiles_resultTupleScheme();\n }\n }\n\n private static class listFiles_resultTupleScheme extends TupleScheme<listFiles_result> {\n\n @Override\n public void write(org.apache.thrift.protocol.TProtocol prot, listFiles_result struct) throws org.apache.thrift.TException {\n TTupleProtocol oprot = (TTupleProtocol) prot;\n BitSet optionals = new BitSet();\n if (struct.isSetSuccess()) {\n optionals.set(0);\n }\n oprot.writeBitSet(optionals, 1);\n if (struct.isSetSuccess()) {\n {\n oprot.writeI32(struct.success.size());\n for (RemoteFileInfo _iter4 : struct.success)\n {\n _iter4.write(oprot);\n }\n }\n }\n }\n\n @Override\n public void read(org.apache.thrift.protocol.TProtocol prot, listFiles_result struct) throws org.apache.thrift.TException {\n TTupleProtocol iprot = (TTupleProtocol) prot;\n BitSet incoming = iprot.readBitSet(1);\n if (incoming.get(0)) {\n {\n org.apache.thrift.protocol.TList _list5 = new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, iprot.readI32());\n struct.success = new ArrayList<RemoteFileInfo>(_list5.size);\n RemoteFileInfo _elem6;\n for (int _i7 = 0; _i7 < _list5.size; ++_i7)\n {\n _elem6 = new RemoteFileInfo();\n _elem6.read(iprot);\n struct.success.add(_elem6);\n }\n }\n struct.setSuccessIsSet(true);\n }\n }\n }\n\n }\n\n}"
] | import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import org.apache.thrift.TException;
import com.hjh.files.sync.common.HLogFactory;
import com.hjh.files.sync.common.ILog;
import com.hjh.files.sync.common.RemoteFile;
import com.hjh.files.sync.common.util.RemoteFileUtil;
import tutorial.RemoteFileInfo;
import tutorial.SyncFileServer; | package com.hjh.files.sync.server;
public class SyncFileServerHandler implements SyncFileServer.Iface {
private static ILog logger = HLogFactory.create(ServerForSync.class);
private ServerForSync sync;
public SyncFileServerHandler(ServerForSync serverForSync) {
this.sync = serverForSync;
}
@Override
public String md5(String folder, String path) throws TException {
logger.info(String.format("md5 [%s] [%s]", folder, path));
return sync.get(folder).md5(path);
}
@Override
public ByteBuffer part(String folder, String path, long part, long part_size) throws TException {
logger.info(String.format("part [%s] [%s] [%d]", folder, path, part));
byte[] partData = sync.get(folder).part(path, part, part_size);
logger.info(String.format("send part data %d", partData.length));
return ByteBuffer.wrap(partData);
}
@Override
public List<RemoteFileInfo> listFiles(String folder, String path) throws TException {
logger.info(String.format("list files [%s] [%s]", folder, path == null ? "ROOT" : path));
List<RemoteFileInfo> result = new ArrayList<RemoteFileInfo>();
RemoteFile[] files = sync.get(folder).list(path);
if (null != files) {
for (RemoteFile item : files) { | result.add(RemoteFileUtil.to(item)); | 3 |
maxanier/MinecraftSecondScreenMod | src/main/java/de/maxgb/minecraft/second_screen/data/ObservingManager.java | [
"public class JSONArray {\n\n\t/**\n\t * The arrayList where the JSONArray's properties are kept.\n\t */\n\tprivate final ArrayList myArrayList;\n\n\t/**\n\t * Construct an empty JSONArray.\n\t */\n\tpublic JSONArray() {\n\t\tthis.myArrayList = new ArrayList();\n\t}\n\n\t/**\n\t * Construct a JSONArray from a Collection.\n\t * \n\t * @param collection\n\t * A Collection.\n\t */\n\tpublic JSONArray(Collection collection) {\n\t\tthis.myArrayList = new ArrayList();\n\t\tif (collection != null) {\n\t\t\tIterator iter = collection.iterator();\n\t\t\twhile (iter.hasNext()) {\n\t\t\t\tthis.myArrayList.add(JSONObject.wrap(iter.next()));\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Construct a JSONArray from a JSONTokener.\n\t * \n\t * @param x\n\t * A JSONTokener\n\t * @throws JSONException\n\t * If there is a syntax error.\n\t */\n\tpublic JSONArray(JSONTokener x) throws JSONException {\n\t\tthis();\n\t\tif (x.nextClean() != '[') {\n\t\t\tthrow x.syntaxError(\"A JSONArray text must start with '['\");\n\t\t}\n\t\tif (x.nextClean() != ']') {\n\t\t\tx.back();\n\t\t\tfor (;;) {\n\t\t\t\tif (x.nextClean() == ',') {\n\t\t\t\t\tx.back();\n\t\t\t\t\tthis.myArrayList.add(JSONObject.NULL);\n\t\t\t\t} else {\n\t\t\t\t\tx.back();\n\t\t\t\t\tthis.myArrayList.add(x.nextValue());\n\t\t\t\t}\n\t\t\t\tswitch (x.nextClean()) {\n\t\t\t\tcase ',':\n\t\t\t\t\tif (x.nextClean() == ']') {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tx.back();\n\t\t\t\t\tbreak;\n\t\t\t\tcase ']':\n\t\t\t\t\treturn;\n\t\t\t\tdefault:\n\t\t\t\t\tthrow x.syntaxError(\"Expected a ',' or ']'\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Construct a JSONArray from an array\n\t * \n\t * @throws JSONException\n\t * If not an array.\n\t */\n\tpublic JSONArray(Object array) throws JSONException {\n\t\tthis();\n\t\tif (array.getClass().isArray()) {\n\t\t\tint length = Array.getLength(array);\n\t\t\tfor (int i = 0; i < length; i += 1) {\n\t\t\t\tthis.put(JSONObject.wrap(Array.get(array, i)));\n\t\t\t}\n\t\t} else {\n\t\t\tthrow new JSONException(\n\t\t\t\t\t\"JSONArray initial value should be a string or collection or array.\");\n\t\t}\n\t}\n\n\t/**\n\t * Construct a JSONArray from a source JSON text.\n\t * \n\t * @param source\n\t * A string that begins with <code>[</code> <small>(left\n\t * bracket)</small> and ends with <code>]</code>\n\t * <small>(right bracket)</small>.\n\t * @throws JSONException\n\t * If there is a syntax error.\n\t */\n\tpublic JSONArray(String source) throws JSONException {\n\t\tthis(new JSONTokener(source));\n\t}\n\n\t/**\n\t * Get the object value associated with an index.\n\t * \n\t * @param index\n\t * The index must be between 0 and length() - 1.\n\t * @return An object value.\n\t * @throws JSONException\n\t * If there is no value for the index.\n\t */\n\tpublic Object get(int index) throws JSONException {\n\t\tObject object = this.opt(index);\n\t\tif (object == null) {\n\t\t\tthrow new JSONException(\"JSONArray[\" + index + \"] not found.\");\n\t\t}\n\t\treturn object;\n\t}\n\n\t/**\n\t * Get the boolean value associated with an index. The string values \"true\"\n\t * and \"false\" are converted to boolean.\n\t * \n\t * @param index\n\t * The index must be between 0 and length() - 1.\n\t * @return The truth.\n\t * @throws JSONException\n\t * If there is no value for the index or if the value is not\n\t * convertible to boolean.\n\t */\n\tpublic boolean getBoolean(int index) throws JSONException {\n\t\tObject object = this.get(index);\n\t\tif (object.equals(Boolean.FALSE)\n\t\t\t\t|| (object instanceof String && ((String) object)\n\t\t\t\t\t\t.equalsIgnoreCase(\"false\"))) {\n\t\t\treturn false;\n\t\t} else if (object.equals(Boolean.TRUE)\n\t\t\t\t|| (object instanceof String && ((String) object)\n\t\t\t\t\t\t.equalsIgnoreCase(\"true\"))) {\n\t\t\treturn true;\n\t\t}\n\t\tthrow new JSONException(\"JSONArray[\" + index + \"] is not a boolean.\");\n\t}\n\n\t/**\n\t * Get the double value associated with an index.\n\t * \n\t * @param index\n\t * The index must be between 0 and length() - 1.\n\t * @return The value.\n\t * @throws JSONException\n\t * If the key is not found or if the value cannot be converted\n\t * to a number.\n\t */\n\tpublic double getDouble(int index) throws JSONException {\n\t\tObject object = this.get(index);\n\t\ttry {\n\t\t\treturn object instanceof Number ? ((Number) object).doubleValue()\n\t\t\t\t\t: Double.parseDouble((String) object);\n\t\t} catch (Exception e) {\n\t\t\tthrow new JSONException(\"JSONArray[\" + index + \"] is not a number.\");\n\t\t}\n\t}\n\n\t/**\n\t * Get the int value associated with an index.\n\t * \n\t * @param index\n\t * The index must be between 0 and length() - 1.\n\t * @return The value.\n\t * @throws JSONException\n\t * If the key is not found or if the value is not a number.\n\t */\n\tpublic int getInt(int index) throws JSONException {\n\t\tObject object = this.get(index);\n\t\ttry {\n\t\t\treturn object instanceof Number ? ((Number) object).intValue()\n\t\t\t\t\t: Integer.parseInt((String) object);\n\t\t} catch (Exception e) {\n\t\t\tthrow new JSONException(\"JSONArray[\" + index + \"] is not a number.\");\n\t\t}\n\t}\n\n\t/**\n\t * Get the JSONArray associated with an index.\n\t * \n\t * @param index\n\t * The index must be between 0 and length() - 1.\n\t * @return A JSONArray value.\n\t * @throws JSONException\n\t * If there is no value for the index. or if the value is not a\n\t * JSONArray\n\t */\n\tpublic JSONArray getJSONArray(int index) throws JSONException {\n\t\tObject object = this.get(index);\n\t\tif (object instanceof JSONArray) {\n\t\t\treturn (JSONArray) object;\n\t\t}\n\t\tthrow new JSONException(\"JSONArray[\" + index + \"] is not a JSONArray.\");\n\t}\n\n\t/**\n\t * Get the JSONObject associated with an index.\n\t * \n\t * @param index\n\t * subscript\n\t * @return A JSONObject value.\n\t * @throws JSONException\n\t * If there is no value for the index or if the value is not a\n\t * JSONObject\n\t */\n\tpublic JSONObject getJSONObject(int index) throws JSONException {\n\t\tObject object = this.get(index);\n\t\tif (object instanceof JSONObject) {\n\t\t\treturn (JSONObject) object;\n\t\t}\n\t\tthrow new JSONException(\"JSONArray[\" + index + \"] is not a JSONObject.\");\n\t}\n\n\t/**\n\t * Get the long value associated with an index.\n\t * \n\t * @param index\n\t * The index must be between 0 and length() - 1.\n\t * @return The value.\n\t * @throws JSONException\n\t * If the key is not found or if the value cannot be converted\n\t * to a number.\n\t */\n\tpublic long getLong(int index) throws JSONException {\n\t\tObject object = this.get(index);\n\t\ttry {\n\t\t\treturn object instanceof Number ? ((Number) object).longValue()\n\t\t\t\t\t: Long.parseLong((String) object);\n\t\t} catch (Exception e) {\n\t\t\tthrow new JSONException(\"JSONArray[\" + index + \"] is not a number.\");\n\t\t}\n\t}\n\n\t/**\n\t * Get the string associated with an index.\n\t * \n\t * @param index\n\t * The index must be between 0 and length() - 1.\n\t * @return A string value.\n\t * @throws JSONException\n\t * If there is no string value for the index.\n\t */\n\tpublic String getString(int index) throws JSONException {\n\t\tObject object = this.get(index);\n\t\tif (object instanceof String) {\n\t\t\treturn (String) object;\n\t\t}\n\t\tthrow new JSONException(\"JSONArray[\" + index + \"] not a string.\");\n\t}\n\n\t/**\n\t * Determine if the value is null.\n\t * \n\t * @param index\n\t * The index must be between 0 and length() - 1.\n\t * @return true if the value at the index is null, or if there is no value.\n\t */\n\tpublic boolean isNull(int index) {\n\t\treturn JSONObject.NULL.equals(this.opt(index));\n\t}\n\n\t/**\n\t * Make a string from the contents of this JSONArray. The\n\t * <code>separator</code> string is inserted between each element. Warning:\n\t * This method assumes that the data structure is acyclical.\n\t * \n\t * @param separator\n\t * A string that will be inserted between the elements.\n\t * @return a string.\n\t * @throws JSONException\n\t * If the array contains an invalid number.\n\t */\n\tpublic String join(String separator) throws JSONException {\n\t\tint len = this.length();\n\t\tStringBuffer sb = new StringBuffer();\n\n\t\tfor (int i = 0; i < len; i += 1) {\n\t\t\tif (i > 0) {\n\t\t\t\tsb.append(separator);\n\t\t\t}\n\t\t\tsb.append(JSONObject.valueToString(this.myArrayList.get(i)));\n\t\t}\n\t\treturn sb.toString();\n\t}\n\n\t/**\n\t * Get the number of elements in the JSONArray, included nulls.\n\t * \n\t * @return The length (or size).\n\t */\n\tpublic int length() {\n\t\treturn this.myArrayList.size();\n\t}\n\n\t/**\n\t * Get the optional object value associated with an index.\n\t * \n\t * @param index\n\t * The index must be between 0 and length() - 1.\n\t * @return An object value, or null if there is no object at that index.\n\t */\n\tpublic Object opt(int index) {\n\t\treturn (index < 0 || index >= this.length()) ? null : this.myArrayList\n\t\t\t\t.get(index);\n\t}\n\n\t/**\n\t * Get the optional boolean value associated with an index. It returns false\n\t * if there is no value at that index, or if the value is not Boolean.TRUE\n\t * or the String \"true\".\n\t * \n\t * @param index\n\t * The index must be between 0 and length() - 1.\n\t * @return The truth.\n\t */\n\tpublic boolean optBoolean(int index) {\n\t\treturn this.optBoolean(index, false);\n\t}\n\n\t/**\n\t * Get the optional boolean value associated with an index. It returns the\n\t * defaultValue if there is no value at that index or if it is not a Boolean\n\t * or the String \"true\" or \"false\" (case insensitive).\n\t * \n\t * @param index\n\t * The index must be between 0 and length() - 1.\n\t * @param defaultValue\n\t * A boolean default.\n\t * @return The truth.\n\t */\n\tpublic boolean optBoolean(int index, boolean defaultValue) {\n\t\ttry {\n\t\t\treturn this.getBoolean(index);\n\t\t} catch (Exception e) {\n\t\t\treturn defaultValue;\n\t\t}\n\t}\n\n\t/**\n\t * Get the optional double value associated with an index. NaN is returned\n\t * if there is no value for the index, or if the value is not a number and\n\t * cannot be converted to a number.\n\t * \n\t * @param index\n\t * The index must be between 0 and length() - 1.\n\t * @return The value.\n\t */\n\tpublic double optDouble(int index) {\n\t\treturn this.optDouble(index, Double.NaN);\n\t}\n\n\t/**\n\t * Get the optional double value associated with an index. The defaultValue\n\t * is returned if there is no value for the index, or if the value is not a\n\t * number and cannot be converted to a number.\n\t * \n\t * @param index\n\t * subscript\n\t * @param defaultValue\n\t * The default value.\n\t * @return The value.\n\t */\n\tpublic double optDouble(int index, double defaultValue) {\n\t\ttry {\n\t\t\treturn this.getDouble(index);\n\t\t} catch (Exception e) {\n\t\t\treturn defaultValue;\n\t\t}\n\t}\n\n\t/**\n\t * Get the optional int value associated with an index. Zero is returned if\n\t * there is no value for the index, or if the value is not a number and\n\t * cannot be converted to a number.\n\t * \n\t * @param index\n\t * The index must be between 0 and length() - 1.\n\t * @return The value.\n\t */\n\tpublic int optInt(int index) {\n\t\treturn this.optInt(index, 0);\n\t}\n\n\t/**\n\t * Get the optional int value associated with an index. The defaultValue is\n\t * returned if there is no value for the index, or if the value is not a\n\t * number and cannot be converted to a number.\n\t * \n\t * @param index\n\t * The index must be between 0 and length() - 1.\n\t * @param defaultValue\n\t * The default value.\n\t * @return The value.\n\t */\n\tpublic int optInt(int index, int defaultValue) {\n\t\ttry {\n\t\t\treturn this.getInt(index);\n\t\t} catch (Exception e) {\n\t\t\treturn defaultValue;\n\t\t}\n\t}\n\n\t/**\n\t * Get the optional JSONArray associated with an index.\n\t * \n\t * @param index\n\t * subscript\n\t * @return A JSONArray value, or null if the index has no value, or if the\n\t * value is not a JSONArray.\n\t */\n\tpublic JSONArray optJSONArray(int index) {\n\t\tObject o = this.opt(index);\n\t\treturn o instanceof JSONArray ? (JSONArray) o : null;\n\t}\n\n\t/**\n\t * Get the optional JSONObject associated with an index. Null is returned if\n\t * the key is not found, or null if the index has no value, or if the value\n\t * is not a JSONObject.\n\t * \n\t * @param index\n\t * The index must be between 0 and length() - 1.\n\t * @return A JSONObject value.\n\t */\n\tpublic JSONObject optJSONObject(int index) {\n\t\tObject o = this.opt(index);\n\t\treturn o instanceof JSONObject ? (JSONObject) o : null;\n\t}\n\n\t/**\n\t * Get the optional long value associated with an index. Zero is returned if\n\t * there is no value for the index, or if the value is not a number and\n\t * cannot be converted to a number.\n\t * \n\t * @param index\n\t * The index must be between 0 and length() - 1.\n\t * @return The value.\n\t */\n\tpublic long optLong(int index) {\n\t\treturn this.optLong(index, 0);\n\t}\n\n\t/**\n\t * Get the optional long value associated with an index. The defaultValue is\n\t * returned if there is no value for the index, or if the value is not a\n\t * number and cannot be converted to a number.\n\t * \n\t * @param index\n\t * The index must be between 0 and length() - 1.\n\t * @param defaultValue\n\t * The default value.\n\t * @return The value.\n\t */\n\tpublic long optLong(int index, long defaultValue) {\n\t\ttry {\n\t\t\treturn this.getLong(index);\n\t\t} catch (Exception e) {\n\t\t\treturn defaultValue;\n\t\t}\n\t}\n\n\t/**\n\t * Get the optional string value associated with an index. It returns an\n\t * empty string if there is no value at that index. If the value is not a\n\t * string and is not null, then it is coverted to a string.\n\t * \n\t * @param index\n\t * The index must be between 0 and length() - 1.\n\t * @return A String value.\n\t */\n\tpublic String optString(int index) {\n\t\treturn this.optString(index, \"\");\n\t}\n\n\t/**\n\t * Get the optional string associated with an index. The defaultValue is\n\t * returned if the key is not found.\n\t * \n\t * @param index\n\t * The index must be between 0 and length() - 1.\n\t * @param defaultValue\n\t * The default value.\n\t * @return A String value.\n\t */\n\tpublic String optString(int index, String defaultValue) {\n\t\tObject object = this.opt(index);\n\t\treturn JSONObject.NULL.equals(object) ? defaultValue : object\n\t\t\t\t.toString();\n\t}\n\n\t/**\n\t * Append a boolean value. This increases the array's length by one.\n\t * \n\t * @param value\n\t * A boolean value.\n\t * @return this.\n\t */\n\tpublic JSONArray put(boolean value) {\n\t\tthis.put(value ? Boolean.TRUE : Boolean.FALSE);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Put a value in the JSONArray, where the value will be a JSONArray which\n\t * is produced from a Collection.\n\t * \n\t * @param value\n\t * A Collection value.\n\t * @return this.\n\t */\n\tpublic JSONArray put(Collection value) {\n\t\tthis.put(new JSONArray(value));\n\t\treturn this;\n\t}\n\n\t/**\n\t * Append a double value. This increases the array's length by one.\n\t * \n\t * @param value\n\t * A double value.\n\t * @throws JSONException\n\t * if the value is not finite.\n\t * @return this.\n\t */\n\tpublic JSONArray put(double value) throws JSONException {\n\t\tDouble d = new Double(value);\n\t\tJSONObject.testValidity(d);\n\t\tthis.put(d);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Append an int value. This increases the array's length by one.\n\t * \n\t * @param value\n\t * An int value.\n\t * @return this.\n\t */\n\tpublic JSONArray put(int value) {\n\t\tthis.put(new Integer(value));\n\t\treturn this;\n\t}\n\n\t/**\n\t * Put or replace a boolean value in the JSONArray. If the index is greater\n\t * than the length of the JSONArray, then null elements will be added as\n\t * necessary to pad it out.\n\t * \n\t * @param index\n\t * The subscript.\n\t * @param value\n\t * A boolean value.\n\t * @return this.\n\t * @throws JSONException\n\t * If the index is negative.\n\t */\n\tpublic JSONArray put(int index, boolean value) throws JSONException {\n\t\tthis.put(index, value ? Boolean.TRUE : Boolean.FALSE);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Put a value in the JSONArray, where the value will be a JSONArray which\n\t * is produced from a Collection.\n\t * \n\t * @param index\n\t * The subscript.\n\t * @param value\n\t * A Collection value.\n\t * @return this.\n\t * @throws JSONException\n\t * If the index is negative or if the value is not finite.\n\t */\n\tpublic JSONArray put(int index, Collection value) throws JSONException {\n\t\tthis.put(index, new JSONArray(value));\n\t\treturn this;\n\t}\n\n\t/**\n\t * Put or replace a double value. If the index is greater than the length of\n\t * the JSONArray, then null elements will be added as necessary to pad it\n\t * out.\n\t * \n\t * @param index\n\t * The subscript.\n\t * @param value\n\t * A double value.\n\t * @return this.\n\t * @throws JSONException\n\t * If the index is negative or if the value is not finite.\n\t */\n\tpublic JSONArray put(int index, double value) throws JSONException {\n\t\tthis.put(index, new Double(value));\n\t\treturn this;\n\t}\n\n\t/**\n\t * Put or replace an int value. If the index is greater than the length of\n\t * the JSONArray, then null elements will be added as necessary to pad it\n\t * out.\n\t * \n\t * @param index\n\t * The subscript.\n\t * @param value\n\t * An int value.\n\t * @return this.\n\t * @throws JSONException\n\t * If the index is negative.\n\t */\n\tpublic JSONArray put(int index, int value) throws JSONException {\n\t\tthis.put(index, new Integer(value));\n\t\treturn this;\n\t}\n\n\t/**\n\t * Put or replace a long value. If the index is greater than the length of\n\t * the JSONArray, then null elements will be added as necessary to pad it\n\t * out.\n\t * \n\t * @param index\n\t * The subscript.\n\t * @param value\n\t * A long value.\n\t * @return this.\n\t * @throws JSONException\n\t * If the index is negative.\n\t */\n\tpublic JSONArray put(int index, long value) throws JSONException {\n\t\tthis.put(index, new Long(value));\n\t\treturn this;\n\t}\n\n\t/**\n\t * Put a value in the JSONArray, where the value will be a JSONObject that\n\t * is produced from a Map.\n\t * \n\t * @param index\n\t * The subscript.\n\t * @param value\n\t * The Map value.\n\t * @return this.\n\t * @throws JSONException\n\t * If the index is negative or if the the value is an invalid\n\t * number.\n\t */\n\tpublic JSONArray put(int index, Map value) throws JSONException {\n\t\tthis.put(index, new JSONObject(value));\n\t\treturn this;\n\t}\n\n\t/**\n\t * Put or replace an object value in the JSONArray. If the index is greater\n\t * than the length of the JSONArray, then null elements will be added as\n\t * necessary to pad it out.\n\t * \n\t * @param index\n\t * The subscript.\n\t * @param value\n\t * The value to put into the array. The value should be a\n\t * Boolean, Double, Integer, JSONArray, JSONObject, Long, or\n\t * String, or the JSONObject.NULL object.\n\t * @return this.\n\t * @throws JSONException\n\t * If the index is negative or if the the value is an invalid\n\t * number.\n\t */\n\tpublic JSONArray put(int index, Object value) throws JSONException {\n\t\tJSONObject.testValidity(value);\n\t\tif (index < 0) {\n\t\t\tthrow new JSONException(\"JSONArray[\" + index + \"] not found.\");\n\t\t}\n\t\tif (index < this.length()) {\n\t\t\tthis.myArrayList.set(index, value);\n\t\t} else {\n\t\t\twhile (index != this.length()) {\n\t\t\t\tthis.put(JSONObject.NULL);\n\t\t\t}\n\t\t\tthis.put(value);\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * Append an long value. This increases the array's length by one.\n\t * \n\t * @param value\n\t * A long value.\n\t * @return this.\n\t */\n\tpublic JSONArray put(long value) {\n\t\tthis.put(new Long(value));\n\t\treturn this;\n\t}\n\n\t/**\n\t * Put a value in the JSONArray, where the value will be a JSONObject which\n\t * is produced from a Map.\n\t * \n\t * @param value\n\t * A Map value.\n\t * @return this.\n\t */\n\tpublic JSONArray put(Map value) {\n\t\tthis.put(new JSONObject(value));\n\t\treturn this;\n\t}\n\n\t/**\n\t * Append an object value. This increases the array's length by one.\n\t * \n\t * @param value\n\t * An object value. The value should be a Boolean, Double,\n\t * Integer, JSONArray, JSONObject, Long, or String, or the\n\t * JSONObject.NULL object.\n\t * @return this.\n\t */\n\tpublic JSONArray put(Object value) {\n\t\tthis.myArrayList.add(value);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Remove an index and close the hole.\n\t * \n\t * @param index\n\t * The index of the element to be removed.\n\t * @return The value that was associated with the index, or null if there\n\t * was no value.\n\t */\n\tpublic Object remove(int index) {\n\t\tObject o = this.opt(index);\n\t\tthis.myArrayList.remove(index);\n\t\treturn o;\n\t}\n\n\t/**\n\t * Produce a JSONObject by combining a JSONArray of names with the values of\n\t * this JSONArray.\n\t * \n\t * @param names\n\t * A JSONArray containing a list of key strings. These will be\n\t * paired with the values.\n\t * @return A JSONObject, or null if there are no names or if this JSONArray\n\t * has no values.\n\t * @throws JSONException\n\t * If any of the names are null.\n\t */\n\tpublic JSONObject toJSONObject(JSONArray names) throws JSONException {\n\t\tif (names == null || names.length() == 0 || this.length() == 0) {\n\t\t\treturn null;\n\t\t}\n\t\tJSONObject jo = new JSONObject();\n\t\tfor (int i = 0; i < names.length(); i += 1) {\n\t\t\tjo.put(names.getString(i), this.opt(i));\n\t\t}\n\t\treturn jo;\n\t}\n\n\t/**\n\t * Make a JSON text of this JSONArray. For compactness, no unnecessary\n\t * whitespace is added. If it is not possible to produce a syntactically\n\t * correct JSON text then null will be returned instead. This could occur if\n\t * the array contains an invalid number.\n\t * <p>\n\t * Warning: This method assumes that the data structure is acyclical.\n\t * \n\t * @return a printable, displayable, transmittable representation of the\n\t * array.\n\t */\n\t@Override\n\tpublic String toString() {\n\t\ttry {\n\t\t\treturn this.toString(0);\n\t\t} catch (Exception e) {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t/**\n\t * Make a prettyprinted JSON text of this JSONArray. Warning: This method\n\t * assumes that the data structure is acyclical.\n\t * \n\t * @param indentFactor\n\t * The number of spaces to add to each level of indentation.\n\t * @return a printable, displayable, transmittable representation of the\n\t * object, beginning with <code>[</code> <small>(left\n\t * bracket)</small> and ending with <code>]</code>\n\t * <small>(right bracket)</small>.\n\t * @throws JSONException\n\t */\n\tpublic String toString(int indentFactor) throws JSONException {\n\t\tStringWriter sw = new StringWriter();\n\t\tsynchronized (sw.getBuffer()) {\n\t\t\treturn this.write(sw, indentFactor, 0).toString();\n\t\t}\n\t}\n\n\t/**\n\t * Write the contents of the JSONArray as JSON text to a writer. For\n\t * compactness, no whitespace is added.\n\t * <p>\n\t * Warning: This method assumes that the data structure is acyclical.\n\t * \n\t * @return The writer.\n\t * @throws JSONException\n\t */\n\tpublic Writer write(Writer writer) throws JSONException {\n\t\treturn this.write(writer, 0, 0);\n\t}\n\n\t/**\n\t * Write the contents of the JSONArray as JSON text to a writer. For\n\t * compactness, no whitespace is added.\n\t * <p>\n\t * Warning: This method assumes that the data structure is acyclical.\n\t * \n\t * @param indentFactor\n\t * The number of spaces to add to each level of indentation.\n\t * @param indent\n\t * The indention of the top level.\n\t * @return The writer.\n\t * @throws JSONException\n\t */\n\tWriter write(Writer writer, int indentFactor, int indent)\n\t\t\tthrows JSONException {\n\t\ttry {\n\t\t\tboolean commanate = false;\n\t\t\tint length = this.length();\n\t\t\twriter.write('[');\n\n\t\t\tif (length == 1) {\n\t\t\t\tJSONObject.writeValue(writer, this.myArrayList.get(0),\n\t\t\t\t\t\tindentFactor, indent);\n\t\t\t} else if (length != 0) {\n\t\t\t\tfinal int newindent = indent + indentFactor;\n\n\t\t\t\tfor (int i = 0; i < length; i += 1) {\n\t\t\t\t\tif (commanate) {\n\t\t\t\t\t\twriter.write(',');\n\t\t\t\t\t}\n\t\t\t\t\tif (indentFactor > 0) {\n\t\t\t\t\t\twriter.write('\\n');\n\t\t\t\t\t}\n\t\t\t\t\tJSONObject.indent(writer, newindent);\n\t\t\t\t\tJSONObject.writeValue(writer, this.myArrayList.get(i),\n\t\t\t\t\t\t\tindentFactor, newindent);\n\t\t\t\t\tcommanate = true;\n\t\t\t\t}\n\t\t\t\tif (indentFactor > 0) {\n\t\t\t\t\twriter.write('\\n');\n\t\t\t\t}\n\t\t\t\tJSONObject.indent(writer, indent);\n\t\t\t}\n\t\t\twriter.write(']');\n\t\t\treturn writer;\n\t\t} catch (IOException e) {\n\t\t\tthrow new JSONException(e);\n\t\t}\n\t}\n}",
"public class JSONObject {\n\t/**\n\t * JSONObject.NULL is equivalent to the value that JavaScript calls null,\n\t * whilst Java's null is equivalent to the value that JavaScript calls\n\t * undefined.\n\t */\n\tprivate static final class Null {\n\n\t\t/**\n\t\t * There is only intended to be a single instance of the NULL object, so\n\t\t * the clone method returns itself.\n\t\t * \n\t\t * @return NULL.\n\t\t */\n\t\t@Override\n\t\tprotected final Object clone() {\n\t\t\treturn this;\n\t\t}\n\n\t\t/**\n\t\t * A Null object is equal to the null value and to itself.\n\t\t * \n\t\t * @param object\n\t\t * An object to test for nullness.\n\t\t * @return true if the object parameter is the JSONObject.NULL object or\n\t\t * null.\n\t\t */\n\t\t@Override\n\t\tpublic boolean equals(Object object) {\n\t\t\treturn object == null || object == this;\n\t\t}\n\n\t\t/**\n\t\t * Get the \"null\" string value.\n\t\t * \n\t\t * @return The string \"null\".\n\t\t */\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\treturn \"null\";\n\t\t}\n\t}\n\n\t/**\n\t * Produce a string from a double. The string \"null\" will be returned if the\n\t * number is not finite.\n\t * \n\t * @param d\n\t * A double.\n\t * @return A String.\n\t */\n\tpublic static String doubleToString(double d) {\n\t\tif (Double.isInfinite(d) || Double.isNaN(d)) {\n\t\t\treturn \"null\";\n\t\t}\n\n\t\t// Shave off trailing zeros and decimal point, if possible.\n\n\t\tString string = Double.toString(d);\n\t\tif (string.indexOf('.') > 0 && string.indexOf('e') < 0\n\t\t\t\t&& string.indexOf('E') < 0) {\n\t\t\twhile (string.endsWith(\"0\")) {\n\t\t\t\tstring = string.substring(0, string.length() - 1);\n\t\t\t}\n\t\t\tif (string.endsWith(\".\")) {\n\t\t\t\tstring = string.substring(0, string.length() - 1);\n\t\t\t}\n\t\t}\n\t\treturn string;\n\t}\n\n\t/**\n\t * The map where the JSONObject's properties are kept.\n\t */\n\tprivate final Map map;\n\n\t/**\n\t * It is sometimes more convenient and less ambiguous to have a\n\t * <code>NULL</code> object than to use Java's <code>null</code> value.\n\t * <code>JSONObject.NULL.equals(null)</code> returns <code>true</code>.\n\t * <code>JSONObject.NULL.toString()</code> returns <code>\"null\"</code>.\n\t */\n\tpublic static final Object NULL = new Null();\n\n\t/**\n\t * Get an array of field names from a JSONObject.\n\t * \n\t * @return An array of field names, or null if there are no names.\n\t */\n\tpublic static String[] getNames(JSONObject jo) {\n\t\tint length = jo.length();\n\t\tif (length == 0) {\n\t\t\treturn null;\n\t\t}\n\t\tIterator iterator = jo.keys();\n\t\tString[] names = new String[length];\n\t\tint i = 0;\n\t\twhile (iterator.hasNext()) {\n\t\t\tnames[i] = (String) iterator.next();\n\t\t\ti += 1;\n\t\t}\n\t\treturn names;\n\t}\n\n\t/**\n\t * Get an array of field names from an Object.\n\t * \n\t * @return An array of field names, or null if there are no names.\n\t */\n\tpublic static String[] getNames(Object object) {\n\t\tif (object == null) {\n\t\t\treturn null;\n\t\t}\n\t\tClass klass = object.getClass();\n\t\tField[] fields = klass.getFields();\n\t\tint length = fields.length;\n\t\tif (length == 0) {\n\t\t\treturn null;\n\t\t}\n\t\tString[] names = new String[length];\n\t\tfor (int i = 0; i < length; i += 1) {\n\t\t\tnames[i] = fields[i].getName();\n\t\t}\n\t\treturn names;\n\t}\n\n\tstatic final void indent(Writer writer, int indent) throws IOException {\n\t\tfor (int i = 0; i < indent; i += 1) {\n\t\t\twriter.write(' ');\n\t\t}\n\t}\n\n\t/**\n\t * Produce a string from a Number.\n\t * \n\t * @param number\n\t * A Number\n\t * @return A String.\n\t * @throws JSONException\n\t * If n is a non-finite number.\n\t */\n\tpublic static String numberToString(Number number) throws JSONException {\n\t\tif (number == null) {\n\t\t\tthrow new JSONException(\"Null pointer\");\n\t\t}\n\t\ttestValidity(number);\n\n\t\t// Shave off trailing zeros and decimal point, if possible.\n\n\t\tString string = number.toString();\n\t\tif (string.indexOf('.') > 0 && string.indexOf('e') < 0\n\t\t\t\t&& string.indexOf('E') < 0) {\n\t\t\twhile (string.endsWith(\"0\")) {\n\t\t\t\tstring = string.substring(0, string.length() - 1);\n\t\t\t}\n\t\t\tif (string.endsWith(\".\")) {\n\t\t\t\tstring = string.substring(0, string.length() - 1);\n\t\t\t}\n\t\t}\n\t\treturn string;\n\t}\n\n\t/**\n\t * Produce a string in double quotes with backslash sequences in all the\n\t * right places. A backslash will be inserted within </, producing <\\/,\n\t * allowing JSON text to be delivered in HTML. In JSON text, a string cannot\n\t * contain a control character or an unescaped quote or backslash.\n\t * \n\t * @param string\n\t * A String\n\t * @return A String correctly formatted for insertion in a JSON text.\n\t */\n\tpublic static String quote(String string) {\n\t\tStringWriter sw = new StringWriter();\n\t\tsynchronized (sw.getBuffer()) {\n\t\t\ttry {\n\t\t\t\treturn quote(string, sw).toString();\n\t\t\t} catch (IOException ignored) {\n\t\t\t\t// will never happen - we are writing to a string writer\n\t\t\t\treturn \"\";\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic static Writer quote(String string, Writer w) throws IOException {\n\t\tif (string == null || string.length() == 0) {\n\t\t\tw.write(\"\\\"\\\"\");\n\t\t\treturn w;\n\t\t}\n\n\t\tchar b;\n\t\tchar c = 0;\n\t\tString hhhh;\n\t\tint i;\n\t\tint len = string.length();\n\n\t\tw.write('\"');\n\t\tfor (i = 0; i < len; i += 1) {\n\t\t\tb = c;\n\t\t\tc = string.charAt(i);\n\t\t\tswitch (c) {\n\t\t\tcase '\\\\':\n\t\t\tcase '\"':\n\t\t\t\tw.write('\\\\');\n\t\t\t\tw.write(c);\n\t\t\t\tbreak;\n\t\t\tcase '/':\n\t\t\t\tif (b == '<') {\n\t\t\t\t\tw.write('\\\\');\n\t\t\t\t}\n\t\t\t\tw.write(c);\n\t\t\t\tbreak;\n\t\t\tcase '\\b':\n\t\t\t\tw.write(\"\\\\b\");\n\t\t\t\tbreak;\n\t\t\tcase '\\t':\n\t\t\t\tw.write(\"\\\\t\");\n\t\t\t\tbreak;\n\t\t\tcase '\\n':\n\t\t\t\tw.write(\"\\\\n\");\n\t\t\t\tbreak;\n\t\t\tcase '\\f':\n\t\t\t\tw.write(\"\\\\f\");\n\t\t\t\tbreak;\n\t\t\tcase '\\r':\n\t\t\t\tw.write(\"\\\\r\");\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tif (c < ' ' || (c >= '\\u0080' && c < '\\u00a0')\n\t\t\t\t\t\t|| (c >= '\\u2000' && c < '\\u2100')) {\n\t\t\t\t\tw.write(\"\\\\u\");\n\t\t\t\t\thhhh = Integer.toHexString(c);\n\t\t\t\t\tw.write(\"0000\", 0, 4 - hhhh.length());\n\t\t\t\t\tw.write(hhhh);\n\t\t\t\t} else {\n\t\t\t\t\tw.write(c);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tw.write('\"');\n\t\treturn w;\n\t}\n\n\t/**\n\t * Try to convert a string into a number, boolean, or null. If the string\n\t * can't be converted, return the string.\n\t * \n\t * @param string\n\t * A String.\n\t * @return A simple JSON value.\n\t */\n\tpublic static Object stringToValue(String string) {\n\t\tDouble d;\n\t\tif (string.equals(\"\")) {\n\t\t\treturn string;\n\t\t}\n\t\tif (string.equalsIgnoreCase(\"true\")) {\n\t\t\treturn Boolean.TRUE;\n\t\t}\n\t\tif (string.equalsIgnoreCase(\"false\")) {\n\t\t\treturn Boolean.FALSE;\n\t\t}\n\t\tif (string.equalsIgnoreCase(\"null\")) {\n\t\t\treturn JSONObject.NULL;\n\t\t}\n\n\t\t/*\n\t\t * If it might be a number, try converting it. If a number cannot be\n\t\t * produced, then the value will just be a string.\n\t\t */\n\n\t\tchar b = string.charAt(0);\n\t\tif ((b >= '0' && b <= '9') || b == '-') {\n\t\t\ttry {\n\t\t\t\tif (string.indexOf('.') > -1 || string.indexOf('e') > -1\n\t\t\t\t\t\t|| string.indexOf('E') > -1) {\n\t\t\t\t\td = Double.valueOf(string);\n\t\t\t\t\tif (!d.isInfinite() && !d.isNaN()) {\n\t\t\t\t\t\treturn d;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tLong myLong = new Long(string);\n\t\t\t\t\tif (string.equals(myLong.toString())) {\n\t\t\t\t\t\tif (myLong.longValue() == myLong.intValue()) {\n\t\t\t\t\t\t\treturn new Integer(myLong.intValue());\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\treturn myLong;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} catch (Exception ignore) {\n\t\t\t}\n\t\t}\n\t\treturn string;\n\t}\n\n\t/**\n\t * Throw an exception if the object is a NaN or infinite number.\n\t * \n\t * @param o\n\t * The object to test.\n\t * @throws JSONException\n\t * If o is a non-finite number.\n\t */\n\tpublic static void testValidity(Object o) throws JSONException {\n\t\tif (o != null) {\n\t\t\tif (o instanceof Double) {\n\t\t\t\tif (((Double) o).isInfinite() || ((Double) o).isNaN()) {\n\t\t\t\t\tthrow new JSONException(\n\t\t\t\t\t\t\t\"JSON does not allow non-finite numbers.\");\n\t\t\t\t}\n\t\t\t} else if (o instanceof Float) {\n\t\t\t\tif (((Float) o).isInfinite() || ((Float) o).isNaN()) {\n\t\t\t\t\tthrow new JSONException(\n\t\t\t\t\t\t\t\"JSON does not allow non-finite numbers.\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Make a JSON text of an Object value. If the object has an\n\t * value.toJSONString() method, then that method will be used to produce the\n\t * JSON text. The method is required to produce a strictly conforming text.\n\t * If the object does not contain a toJSONString method (which is the most\n\t * common case), then a text will be produced by other means. If the value\n\t * is an array or Collection, then a JSONArray will be made from it and its\n\t * toJSONString method will be called. If the value is a MAP, then a\n\t * JSONObject will be made from it and its toJSONString method will be\n\t * called. Otherwise, the value's toString method will be called, and the\n\t * result will be quoted.\n\t * \n\t * <p>\n\t * Warning: This method assumes that the data structure is acyclical.\n\t * \n\t * @param value\n\t * The value to be serialized.\n\t * @return a printable, displayable, transmittable representation of the\n\t * object, beginning with <code>{</code> <small>(left\n\t * brace)</small> and ending with <code>}</code> <small>(right\n\t * brace)</small>.\n\t * @throws JSONException\n\t * If the value is or contains an invalid number.\n\t */\n\tpublic static String valueToString(Object value) throws JSONException {\n\t\tif (value == null || value.equals(null)) {\n\t\t\treturn \"null\";\n\t\t}\n\t\tif (value instanceof JSONString) {\n\t\t\tObject object;\n\t\t\ttry {\n\t\t\t\tobject = ((JSONString) value).toJSONString();\n\t\t\t} catch (Exception e) {\n\t\t\t\tthrow new JSONException(e);\n\t\t\t}\n\t\t\tif (object instanceof String) {\n\t\t\t\treturn (String) object;\n\t\t\t}\n\t\t\tthrow new JSONException(\"Bad value from toJSONString: \" + object);\n\t\t}\n\t\tif (value instanceof Number) {\n\t\t\treturn numberToString((Number) value);\n\t\t}\n\t\tif (value instanceof Boolean || value instanceof JSONObject\n\t\t\t\t|| value instanceof JSONArray) {\n\t\t\treturn value.toString();\n\t\t}\n\t\tif (value instanceof Map) {\n\t\t\treturn new JSONObject((Map) value).toString();\n\t\t}\n\t\tif (value instanceof Collection) {\n\t\t\treturn new JSONArray((Collection) value).toString();\n\t\t}\n\t\tif (value.getClass().isArray()) {\n\t\t\treturn new JSONArray(value).toString();\n\t\t}\n\t\treturn quote(value.toString());\n\t}\n\n\t/**\n\t * Wrap an object, if necessary. If the object is null, return the NULL\n\t * object. If it is an array or collection, wrap it in a JSONArray. If it is\n\t * a map, wrap it in a JSONObject. If it is a standard property (Double,\n\t * String, et al) then it is already wrapped. Otherwise, if it comes from\n\t * one of the java packages, turn it into a string. And if it doesn't, try\n\t * to wrap it in a JSONObject. If the wrapping fails, then null is returned.\n\t * \n\t * @param object\n\t * The object to wrap\n\t * @return The wrapped value\n\t */\n\tpublic static Object wrap(Object object) {\n\t\ttry {\n\t\t\tif (object == null) {\n\t\t\t\treturn NULL;\n\t\t\t}\n\t\t\tif (object instanceof JSONObject || object instanceof JSONArray\n\t\t\t\t\t|| NULL.equals(object) || object instanceof JSONString\n\t\t\t\t\t|| object instanceof Byte || object instanceof Character\n\t\t\t\t\t|| object instanceof Short || object instanceof Integer\n\t\t\t\t\t|| object instanceof Long || object instanceof Boolean\n\t\t\t\t\t|| object instanceof Float || object instanceof Double\n\t\t\t\t\t|| object instanceof String) {\n\t\t\t\treturn object;\n\t\t\t}\n\n\t\t\tif (object instanceof Collection) {\n\t\t\t\treturn new JSONArray((Collection) object);\n\t\t\t}\n\t\t\tif (object.getClass().isArray()) {\n\t\t\t\treturn new JSONArray(object);\n\t\t\t}\n\t\t\tif (object instanceof Map) {\n\t\t\t\treturn new JSONObject((Map) object);\n\t\t\t}\n\t\t\tPackage objectPackage = object.getClass().getPackage();\n\t\t\tString objectPackageName = objectPackage != null ? objectPackage\n\t\t\t\t\t.getName() : \"\";\n\t\t\tif (objectPackageName.startsWith(\"java.\")\n\t\t\t\t\t|| objectPackageName.startsWith(\"javax.\")\n\t\t\t\t\t|| object.getClass().getClassLoader() == null) {\n\t\t\t\treturn object.toString();\n\t\t\t}\n\t\t\treturn new JSONObject(object);\n\t\t} catch (Exception exception) {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tstatic final Writer writeValue(Writer writer, Object value,\n\t\t\tint indentFactor, int indent) throws JSONException, IOException {\n\t\tif (value == null || value.equals(null)) {\n\t\t\twriter.write(\"null\");\n\t\t} else if (value instanceof JSONObject) {\n\t\t\t((JSONObject) value).write(writer, indentFactor, indent);\n\t\t} else if (value instanceof JSONArray) {\n\t\t\t((JSONArray) value).write(writer, indentFactor, indent);\n\t\t} else if (value instanceof Map) {\n\t\t\tnew JSONObject((Map) value).write(writer, indentFactor, indent);\n\t\t} else if (value instanceof Collection) {\n\t\t\tnew JSONArray((Collection) value).write(writer, indentFactor,\n\t\t\t\t\tindent);\n\t\t} else if (value.getClass().isArray()) {\n\t\t\tnew JSONArray(value).write(writer, indentFactor, indent);\n\t\t} else if (value instanceof Number) {\n\t\t\twriter.write(numberToString((Number) value));\n\t\t} else if (value instanceof Boolean) {\n\t\t\twriter.write(value.toString());\n\t\t} else if (value instanceof JSONString) {\n\t\t\tObject o;\n\t\t\ttry {\n\t\t\t\to = ((JSONString) value).toJSONString();\n\t\t\t} catch (Exception e) {\n\t\t\t\tthrow new JSONException(e);\n\t\t\t}\n\t\t\twriter.write(o != null ? o.toString() : quote(value.toString()));\n\t\t} else {\n\t\t\tquote(value.toString(), writer);\n\t\t}\n\t\treturn writer;\n\t}\n\n\t/**\n\t * Construct an empty JSONObject.\n\t */\n\tpublic JSONObject() {\n\t\tthis.map = new HashMap();\n\t}\n\n\t/**\n\t * Construct a JSONObject from a subset of another JSONObject. An array of\n\t * strings is used to identify the keys that should be copied. Missing keys\n\t * are ignored.\n\t * \n\t * @param jo\n\t * A JSONObject.\n\t * @param names\n\t * An array of strings.\n\t * @throws JSONException\n\t * @exception JSONException\n\t * If a value is a non-finite number or if a name is\n\t * duplicated.\n\t */\n\tpublic JSONObject(JSONObject jo, String[] names) {\n\t\tthis();\n\t\tfor (int i = 0; i < names.length; i += 1) {\n\t\t\ttry {\n\t\t\t\tthis.putOnce(names[i], jo.opt(names[i]));\n\t\t\t} catch (Exception ignore) {\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Construct a JSONObject from a JSONTokener.\n\t * \n\t * @param x\n\t * A JSONTokener object containing the source string.\n\t * @throws JSONException\n\t * If there is a syntax error in the source string or a\n\t * duplicated key.\n\t */\n\tpublic JSONObject(JSONTokener x) throws JSONException {\n\t\tthis();\n\t\tchar c;\n\t\tString key;\n\n\t\tif (x.nextClean() != '{') {\n\t\t\tthrow x.syntaxError(\"A JSONObject text must begin with '{'\");\n\t\t}\n\t\tfor (;;) {\n\t\t\tc = x.nextClean();\n\t\t\tswitch (c) {\n\t\t\tcase 0:\n\t\t\t\tthrow x.syntaxError(\"A JSONObject text must end with '}'\");\n\t\t\tcase '}':\n\t\t\t\treturn;\n\t\t\tdefault:\n\t\t\t\tx.back();\n\t\t\t\tkey = x.nextValue().toString();\n\t\t\t}\n\n\t\t\t// The key is followed by ':'.\n\n\t\t\tc = x.nextClean();\n\t\t\tif (c != ':') {\n\t\t\t\tthrow x.syntaxError(\"Expected a ':' after a key\");\n\t\t\t}\n\t\t\tthis.putOnce(key, x.nextValue());\n\n\t\t\t// Pairs are separated by ','.\n\n\t\t\tswitch (x.nextClean()) {\n\t\t\tcase ';':\n\t\t\tcase ',':\n\t\t\t\tif (x.nextClean() == '}') {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tx.back();\n\t\t\t\tbreak;\n\t\t\tcase '}':\n\t\t\t\treturn;\n\t\t\tdefault:\n\t\t\t\tthrow x.syntaxError(\"Expected a ',' or '}'\");\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Construct a JSONObject from a Map.\n\t * \n\t * @param map\n\t * A map object that can be used to initialize the contents of\n\t * the JSONObject.\n\t * @throws JSONException\n\t */\n\tpublic JSONObject(Map map) {\n\t\tthis.map = new HashMap();\n\t\tif (map != null) {\n\t\t\tIterator i = map.entrySet().iterator();\n\t\t\twhile (i.hasNext()) {\n\t\t\t\tMap.Entry e = (Map.Entry) i.next();\n\t\t\t\tObject value = e.getValue();\n\t\t\t\tif (value != null) {\n\t\t\t\t\tthis.map.put(e.getKey(), wrap(value));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Construct a JSONObject from an Object using bean getters. It reflects on\n\t * all of the public methods of the object. For each of the methods with no\n\t * parameters and a name starting with <code>\"get\"</code> or\n\t * <code>\"is\"</code> followed by an uppercase letter, the method is invoked,\n\t * and a key and the value returned from the getter method are put into the\n\t * new JSONObject.\n\t * \n\t * The key is formed by removing the <code>\"get\"</code> or <code>\"is\"</code>\n\t * prefix. If the second remaining character is not upper case, then the\n\t * first character is converted to lower case.\n\t * \n\t * For example, if an object has a method named <code>\"getName\"</code>, and\n\t * if the result of calling <code>object.getName()</code> is\n\t * <code>\"Larry Fine\"</code>, then the JSONObject will contain\n\t * <code>\"name\": \"Larry Fine\"</code>.\n\t * \n\t * @param bean\n\t * An object that has getter methods that should be used to make\n\t * a JSONObject.\n\t */\n\tpublic JSONObject(Object bean) {\n\t\tthis();\n\t\tthis.populateMap(bean);\n\t}\n\n\t/**\n\t * Construct a JSONObject from an Object, using reflection to find the\n\t * public members. The resulting JSONObject's keys will be the strings from\n\t * the names array, and the values will be the field values associated with\n\t * those keys in the object. If a key is not found or not visible, then it\n\t * will not be copied into the new JSONObject.\n\t * \n\t * @param object\n\t * An object that has fields that should be used to make a\n\t * JSONObject.\n\t * @param names\n\t * An array of strings, the names of the fields to be obtained\n\t * from the object.\n\t */\n\tpublic JSONObject(Object object, String names[]) {\n\t\tthis();\n\t\tClass c = object.getClass();\n\t\tfor (int i = 0; i < names.length; i += 1) {\n\t\t\tString name = names[i];\n\t\t\ttry {\n\t\t\t\tthis.putOpt(name, c.getField(name).get(object));\n\t\t\t} catch (Exception ignore) {\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Construct a JSONObject from a source JSON text string. This is the most\n\t * commonly used JSONObject constructor.\n\t * \n\t * @param source\n\t * A string beginning with <code>{</code> <small>(left\n\t * brace)</small> and ending with <code>}</code>\n\t * <small>(right brace)</small>.\n\t * @exception JSONException\n\t * If there is a syntax error in the source string or a\n\t * duplicated key.\n\t */\n\tpublic JSONObject(String source) throws JSONException {\n\t\tthis(new JSONTokener(source));\n\t}\n\n\t/**\n\t * Construct a JSONObject from a ResourceBundle.\n\t * \n\t * @param baseName\n\t * The ResourceBundle base name.\n\t * @param locale\n\t * The Locale to load the ResourceBundle for.\n\t * @throws JSONException\n\t * If any JSONExceptions are detected.\n\t */\n\tpublic JSONObject(String baseName, Locale locale) throws JSONException {\n\t\tthis();\n\t\tResourceBundle bundle = ResourceBundle.getBundle(baseName, locale,\n\t\t\t\tThread.currentThread().getContextClassLoader());\n\n\t\t// Iterate through the keys in the bundle.\n\n\t\tEnumeration keys = bundle.getKeys();\n\t\twhile (keys.hasMoreElements()) {\n\t\t\tObject key = keys.nextElement();\n\t\t\tif (key instanceof String) {\n\n\t\t\t\t// Go through the path, ensuring that there is a nested\n\t\t\t\t// JSONObject for each\n\t\t\t\t// segment except the last. Add the value using the last\n\t\t\t\t// segment's name into\n\t\t\t\t// the deepest nested JSONObject.\n\n\t\t\t\tString[] path = ((String) key).split(\"\\\\.\");\n\t\t\t\tint last = path.length - 1;\n\t\t\t\tJSONObject target = this;\n\t\t\t\tfor (int i = 0; i < last; i += 1) {\n\t\t\t\t\tString segment = path[i];\n\t\t\t\t\tJSONObject nextTarget = target.optJSONObject(segment);\n\t\t\t\t\tif (nextTarget == null) {\n\t\t\t\t\t\tnextTarget = new JSONObject();\n\t\t\t\t\t\ttarget.put(segment, nextTarget);\n\t\t\t\t\t}\n\t\t\t\t\ttarget = nextTarget;\n\t\t\t\t}\n\t\t\t\ttarget.put(path[last], bundle.getString((String) key));\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Accumulate values under a key. It is similar to the put method except\n\t * that if there is already an object stored under the key then a JSONArray\n\t * is stored under the key to hold all of the accumulated values. If there\n\t * is already a JSONArray, then the new value is appended to it. In\n\t * contrast, the put method replaces the previous value.\n\t * \n\t * If only one value is accumulated that is not a JSONArray, then the result\n\t * will be the same as using put. But if multiple values are accumulated,\n\t * then the result will be like append.\n\t * \n\t * @param key\n\t * A key string.\n\t * @param value\n\t * An object to be accumulated under the key.\n\t * @return this.\n\t * @throws JSONException\n\t * If the value is an invalid number or if the key is null.\n\t */\n\tpublic JSONObject accumulate(String key, Object value) throws JSONException {\n\t\ttestValidity(value);\n\t\tObject object = this.opt(key);\n\t\tif (object == null) {\n\t\t\tthis.put(key,\n\t\t\t\t\tvalue instanceof JSONArray ? new JSONArray().put(value)\n\t\t\t\t\t\t\t: value);\n\t\t} else if (object instanceof JSONArray) {\n\t\t\t((JSONArray) object).put(value);\n\t\t} else {\n\t\t\tthis.put(key, new JSONArray().put(object).put(value));\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * Append values to the array under a key. If the key does not exist in the\n\t * JSONObject, then the key is put in the JSONObject with its value being a\n\t * JSONArray containing the value parameter. If the key was already\n\t * associated with a JSONArray, then the value parameter is appended to it.\n\t * \n\t * @param key\n\t * A key string.\n\t * @param value\n\t * An object to be accumulated under the key.\n\t * @return this.\n\t * @throws JSONException\n\t * If the key is null or if the current value associated with\n\t * the key is not a JSONArray.\n\t */\n\tpublic JSONObject append(String key, Object value) throws JSONException {\n\t\ttestValidity(value);\n\t\tObject object = this.opt(key);\n\t\tif (object == null) {\n\t\t\tthis.put(key, new JSONArray().put(value));\n\t\t} else if (object instanceof JSONArray) {\n\t\t\tthis.put(key, ((JSONArray) object).put(value));\n\t\t} else {\n\t\t\tthrow new JSONException(\"JSONObject[\" + key\n\t\t\t\t\t+ \"] is not a JSONArray.\");\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * Get the value object associated with a key.\n\t * \n\t * @param key\n\t * A key string.\n\t * @return The object associated with the key.\n\t * @throws JSONException\n\t * if the key is not found.\n\t */\n\tpublic Object get(String key) throws JSONException {\n\t\tif (key == null) {\n\t\t\tthrow new JSONException(\"Null key.\");\n\t\t}\n\t\tObject object = this.opt(key);\n\t\tif (object == null) {\n\t\t\tthrow new JSONException(\"JSONObject[\" + quote(key) + \"] not found.\");\n\t\t}\n\t\treturn object;\n\t}\n\n\t/**\n\t * Get the boolean value associated with a key.\n\t * \n\t * @param key\n\t * A key string.\n\t * @return The truth.\n\t * @throws JSONException\n\t * if the value is not a Boolean or the String \"true\" or\n\t * \"false\".\n\t */\n\tpublic boolean getBoolean(String key) throws JSONException {\n\t\tObject object = this.get(key);\n\t\tif (object.equals(Boolean.FALSE)\n\t\t\t\t|| (object instanceof String && ((String) object)\n\t\t\t\t\t\t.equalsIgnoreCase(\"false\"))) {\n\t\t\treturn false;\n\t\t} else if (object.equals(Boolean.TRUE)\n\t\t\t\t|| (object instanceof String && ((String) object)\n\t\t\t\t\t\t.equalsIgnoreCase(\"true\"))) {\n\t\t\treturn true;\n\t\t}\n\t\tthrow new JSONException(\"JSONObject[\" + quote(key)\n\t\t\t\t+ \"] is not a Boolean.\");\n\t}\n\n\t/**\n\t * Get the double value associated with a key.\n\t * \n\t * @param key\n\t * A key string.\n\t * @return The numeric value.\n\t * @throws JSONException\n\t * if the key is not found or if the value is not a Number\n\t * object and cannot be converted to a number.\n\t */\n\tpublic double getDouble(String key) throws JSONException {\n\t\tObject object = this.get(key);\n\t\ttry {\n\t\t\treturn object instanceof Number ? ((Number) object).doubleValue()\n\t\t\t\t\t: Double.parseDouble((String) object);\n\t\t} catch (Exception e) {\n\t\t\tthrow new JSONException(\"JSONObject[\" + quote(key)\n\t\t\t\t\t+ \"] is not a number.\");\n\t\t}\n\t}\n\n\t/**\n\t * Get the int value associated with a key.\n\t * \n\t * @param key\n\t * A key string.\n\t * @return The integer value.\n\t * @throws JSONException\n\t * if the key is not found or if the value cannot be converted\n\t * to an integer.\n\t */\n\tpublic int getInt(String key) throws JSONException {\n\t\tObject object = this.get(key);\n\t\ttry {\n\t\t\treturn object instanceof Number ? ((Number) object).intValue()\n\t\t\t\t\t: Integer.parseInt((String) object);\n\t\t} catch (Exception e) {\n\t\t\tthrow new JSONException(\"JSONObject[\" + quote(key)\n\t\t\t\t\t+ \"] is not an int.\");\n\t\t}\n\t}\n\n\t/**\n\t * Get the JSONArray value associated with a key.\n\t * \n\t * @param key\n\t * A key string.\n\t * @return A JSONArray which is the value.\n\t * @throws JSONException\n\t * if the key is not found or if the value is not a JSONArray.\n\t */\n\tpublic JSONArray getJSONArray(String key) throws JSONException {\n\t\tObject object = this.get(key);\n\t\tif (object instanceof JSONArray) {\n\t\t\treturn (JSONArray) object;\n\t\t}\n\t\tthrow new JSONException(\"JSONObject[\" + quote(key)\n\t\t\t\t+ \"] is not a JSONArray.\");\n\t}\n\n\t/**\n\t * Get the JSONObject value associated with a key.\n\t * \n\t * @param key\n\t * A key string.\n\t * @return A JSONObject which is the value.\n\t * @throws JSONException\n\t * if the key is not found or if the value is not a JSONObject.\n\t */\n\tpublic JSONObject getJSONObject(String key) throws JSONException {\n\t\tObject object = this.get(key);\n\t\tif (object instanceof JSONObject) {\n\t\t\treturn (JSONObject) object;\n\t\t}\n\t\tthrow new JSONException(\"JSONObject[\" + quote(key)\n\t\t\t\t+ \"] is not a JSONObject.\");\n\t}\n\n\t/**\n\t * Get the long value associated with a key.\n\t * \n\t * @param key\n\t * A key string.\n\t * @return The long value.\n\t * @throws JSONException\n\t * if the key is not found or if the value cannot be converted\n\t * to a long.\n\t */\n\tpublic long getLong(String key) throws JSONException {\n\t\tObject object = this.get(key);\n\t\ttry {\n\t\t\treturn object instanceof Number ? ((Number) object).longValue()\n\t\t\t\t\t: Long.parseLong((String) object);\n\t\t} catch (Exception e) {\n\t\t\tthrow new JSONException(\"JSONObject[\" + quote(key)\n\t\t\t\t\t+ \"] is not a long.\");\n\t\t}\n\t}\n\n\t/**\n\t * Get the string associated with a key.\n\t * \n\t * @param key\n\t * A key string.\n\t * @return A string which is the value.\n\t * @throws JSONException\n\t * if there is no string value for the key.\n\t */\n\tpublic String getString(String key) throws JSONException {\n\t\tObject object = this.get(key);\n\t\tif (object instanceof String) {\n\t\t\treturn (String) object;\n\t\t}\n\t\tthrow new JSONException(\"JSONObject[\" + quote(key) + \"] not a string.\");\n\t}\n\n\t/**\n\t * Determine if the JSONObject contains a specific key.\n\t * \n\t * @param key\n\t * A key string.\n\t * @return true if the key exists in the JSONObject.\n\t */\n\tpublic boolean has(String key) {\n\t\treturn this.map.containsKey(key);\n\t}\n\n\t/**\n\t * Increment a property of a JSONObject. If there is no such property,\n\t * create one with a value of 1. If there is such a property, and if it is\n\t * an Integer, Long, Double, or Float, then add one to it.\n\t * \n\t * @param key\n\t * A key string.\n\t * @return this.\n\t * @throws JSONException\n\t * If there is already a property with this name that is not an\n\t * Integer, Long, Double, or Float.\n\t */\n\tpublic JSONObject increment(String key) throws JSONException {\n\t\tObject value = this.opt(key);\n\t\tif (value == null) {\n\t\t\tthis.put(key, 1);\n\t\t} else if (value instanceof Integer) {\n\t\t\tthis.put(key, ((Integer) value).intValue() + 1);\n\t\t} else if (value instanceof Long) {\n\t\t\tthis.put(key, ((Long) value).longValue() + 1);\n\t\t} else if (value instanceof Double) {\n\t\t\tthis.put(key, ((Double) value).doubleValue() + 1);\n\t\t} else if (value instanceof Float) {\n\t\t\tthis.put(key, ((Float) value).floatValue() + 1);\n\t\t} else {\n\t\t\tthrow new JSONException(\"Unable to increment [\" + quote(key) + \"].\");\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * Determine if the value associated with the key is null or if there is no\n\t * value.\n\t * \n\t * @param key\n\t * A key string.\n\t * @return true if there is no value associated with the key or if the value\n\t * is the JSONObject.NULL object.\n\t */\n\tpublic boolean isNull(String key) {\n\t\treturn JSONObject.NULL.equals(this.opt(key));\n\t}\n\n\t/**\n\t * Get an enumeration of the keys of the JSONObject.\n\t * \n\t * @return An iterator of the keys.\n\t */\n\tpublic Iterator keys() {\n\t\treturn this.keySet().iterator();\n\t}\n\n\t/**\n\t * Get a set of keys of the JSONObject.\n\t * \n\t * @return A keySet.\n\t */\n\tpublic Set keySet() {\n\t\treturn this.map.keySet();\n\t}\n\n\t/**\n\t * Get the number of keys stored in the JSONObject.\n\t * \n\t * @return The number of keys in the JSONObject.\n\t */\n\tpublic int length() {\n\t\treturn this.map.size();\n\t}\n\n\t/**\n\t * Produce a JSONArray containing the names of the elements of this\n\t * JSONObject.\n\t * \n\t * @return A JSONArray containing the key strings, or null if the JSONObject\n\t * is empty.\n\t */\n\tpublic JSONArray names() {\n\t\tJSONArray ja = new JSONArray();\n\t\tIterator keys = this.keys();\n\t\twhile (keys.hasNext()) {\n\t\t\tja.put(keys.next());\n\t\t}\n\t\treturn ja.length() == 0 ? null : ja;\n\t}\n\n\t/**\n\t * Get an optional value associated with a key.\n\t * \n\t * @param key\n\t * A key string.\n\t * @return An object which is the value, or null if there is no value.\n\t */\n\tpublic Object opt(String key) {\n\t\treturn key == null ? null : this.map.get(key);\n\t}\n\n\t/**\n\t * Get an optional boolean associated with a key. It returns false if there\n\t * is no such key, or if the value is not Boolean.TRUE or the String \"true\".\n\t * \n\t * @param key\n\t * A key string.\n\t * @return The truth.\n\t */\n\tpublic boolean optBoolean(String key) {\n\t\treturn this.optBoolean(key, false);\n\t}\n\n\t/**\n\t * Get an optional boolean associated with a key. It returns the\n\t * defaultValue if there is no such key, or if it is not a Boolean or the\n\t * String \"true\" or \"false\" (case insensitive).\n\t * \n\t * @param key\n\t * A key string.\n\t * @param defaultValue\n\t * The default.\n\t * @return The truth.\n\t */\n\tpublic boolean optBoolean(String key, boolean defaultValue) {\n\t\ttry {\n\t\t\treturn this.getBoolean(key);\n\t\t} catch (Exception e) {\n\t\t\treturn defaultValue;\n\t\t}\n\t}\n\n\t/**\n\t * Get an optional double associated with a key, or NaN if there is no such\n\t * key or if its value is not a number. If the value is a string, an attempt\n\t * will be made to evaluate it as a number.\n\t * \n\t * @param key\n\t * A string which is the key.\n\t * @return An object which is the value.\n\t */\n\tpublic double optDouble(String key) {\n\t\treturn this.optDouble(key, Double.NaN);\n\t}\n\n\t/**\n\t * Get an optional double associated with a key, or the defaultValue if\n\t * there is no such key or if its value is not a number. If the value is a\n\t * string, an attempt will be made to evaluate it as a number.\n\t * \n\t * @param key\n\t * A key string.\n\t * @param defaultValue\n\t * The default.\n\t * @return An object which is the value.\n\t */\n\tpublic double optDouble(String key, double defaultValue) {\n\t\ttry {\n\t\t\treturn this.getDouble(key);\n\t\t} catch (Exception e) {\n\t\t\treturn defaultValue;\n\t\t}\n\t}\n\n\t/**\n\t * Get an optional int value associated with a key, or zero if there is no\n\t * such key or if the value is not a number. If the value is a string, an\n\t * attempt will be made to evaluate it as a number.\n\t * \n\t * @param key\n\t * A key string.\n\t * @return An object which is the value.\n\t */\n\tpublic int optInt(String key) {\n\t\treturn this.optInt(key, 0);\n\t}\n\n\t/**\n\t * Get an optional int value associated with a key, or the default if there\n\t * is no such key or if the value is not a number. If the value is a string,\n\t * an attempt will be made to evaluate it as a number.\n\t * \n\t * @param key\n\t * A key string.\n\t * @param defaultValue\n\t * The default.\n\t * @return An object which is the value.\n\t */\n\tpublic int optInt(String key, int defaultValue) {\n\t\ttry {\n\t\t\treturn this.getInt(key);\n\t\t} catch (Exception e) {\n\t\t\treturn defaultValue;\n\t\t}\n\t}\n\n\t/**\n\t * Get an optional JSONArray associated with a key. It returns null if there\n\t * is no such key, or if its value is not a JSONArray.\n\t * \n\t * @param key\n\t * A key string.\n\t * @return A JSONArray which is the value.\n\t */\n\tpublic JSONArray optJSONArray(String key) {\n\t\tObject o = this.opt(key);\n\t\treturn o instanceof JSONArray ? (JSONArray) o : null;\n\t}\n\n\t/**\n\t * Get an optional JSONObject associated with a key. It returns null if\n\t * there is no such key, or if its value is not a JSONObject.\n\t * \n\t * @param key\n\t * A key string.\n\t * @return A JSONObject which is the value.\n\t */\n\tpublic JSONObject optJSONObject(String key) {\n\t\tObject object = this.opt(key);\n\t\treturn object instanceof JSONObject ? (JSONObject) object : null;\n\t}\n\n\t/**\n\t * Get an optional long value associated with a key, or zero if there is no\n\t * such key or if the value is not a number. If the value is a string, an\n\t * attempt will be made to evaluate it as a number.\n\t * \n\t * @param key\n\t * A key string.\n\t * @return An object which is the value.\n\t */\n\tpublic long optLong(String key) {\n\t\treturn this.optLong(key, 0);\n\t}\n\n\t/**\n\t * Get an optional long value associated with a key, or the default if there\n\t * is no such key or if the value is not a number. If the value is a string,\n\t * an attempt will be made to evaluate it as a number.\n\t * \n\t * @param key\n\t * A key string.\n\t * @param defaultValue\n\t * The default.\n\t * @return An object which is the value.\n\t */\n\tpublic long optLong(String key, long defaultValue) {\n\t\ttry {\n\t\t\treturn this.getLong(key);\n\t\t} catch (Exception e) {\n\t\t\treturn defaultValue;\n\t\t}\n\t}\n\n\t/**\n\t * Get an optional string associated with a key. It returns an empty string\n\t * if there is no such key. If the value is not a string and is not null,\n\t * then it is converted to a string.\n\t * \n\t * @param key\n\t * A key string.\n\t * @return A string which is the value.\n\t */\n\tpublic String optString(String key) {\n\t\treturn this.optString(key, \"\");\n\t}\n\n\t/**\n\t * Get an optional string associated with a key. It returns the defaultValue\n\t * if there is no such key.\n\t * \n\t * @param key\n\t * A key string.\n\t * @param defaultValue\n\t * The default.\n\t * @return A string which is the value.\n\t */\n\tpublic String optString(String key, String defaultValue) {\n\t\tObject object = this.opt(key);\n\t\treturn NULL.equals(object) ? defaultValue : object.toString();\n\t}\n\n\tprivate void populateMap(Object bean) {\n\t\tClass klass = bean.getClass();\n\n\t\t// If klass is a System class then set includeSuperClass to false.\n\n\t\tboolean includeSuperClass = klass.getClassLoader() != null;\n\n\t\tMethod[] methods = includeSuperClass ? klass.getMethods() : klass\n\t\t\t\t.getDeclaredMethods();\n\t\tfor (int i = 0; i < methods.length; i += 1) {\n\t\t\ttry {\n\t\t\t\tMethod method = methods[i];\n\t\t\t\tif (Modifier.isPublic(method.getModifiers())) {\n\t\t\t\t\tString name = method.getName();\n\t\t\t\t\tString key = \"\";\n\t\t\t\t\tif (name.startsWith(\"get\")) {\n\t\t\t\t\t\tif (\"getClass\".equals(name)\n\t\t\t\t\t\t\t\t|| \"getDeclaringClass\".equals(name)) {\n\t\t\t\t\t\t\tkey = \"\";\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tkey = name.substring(3);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (name.startsWith(\"is\")) {\n\t\t\t\t\t\tkey = name.substring(2);\n\t\t\t\t\t}\n\t\t\t\t\tif (key.length() > 0\n\t\t\t\t\t\t\t&& Character.isUpperCase(key.charAt(0))\n\t\t\t\t\t\t\t&& method.getParameterTypes().length == 0) {\n\t\t\t\t\t\tif (key.length() == 1) {\n\t\t\t\t\t\t\tkey = key.toLowerCase();\n\t\t\t\t\t\t} else if (!Character.isUpperCase(key.charAt(1))) {\n\t\t\t\t\t\t\tkey = key.substring(0, 1).toLowerCase()\n\t\t\t\t\t\t\t\t\t+ key.substring(1);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tObject result = method.invoke(bean, (Object[]) null);\n\t\t\t\t\t\tif (result != null) {\n\t\t\t\t\t\t\tthis.map.put(key, wrap(result));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} catch (Exception ignore) {\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Put a key/boolean pair in the JSONObject.\n\t * \n\t * @param key\n\t * A key string.\n\t * @param value\n\t * A boolean which is the value.\n\t * @return this.\n\t * @throws JSONException\n\t * If the key is null.\n\t */\n\tpublic JSONObject put(String key, boolean value) throws JSONException {\n\t\tthis.put(key, value ? Boolean.TRUE : Boolean.FALSE);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Put a key/value pair in the JSONObject, where the value will be a\n\t * JSONArray which is produced from a Collection.\n\t * \n\t * @param key\n\t * A key string.\n\t * @param value\n\t * A Collection value.\n\t * @return this.\n\t * @throws JSONException\n\t */\n\tpublic JSONObject put(String key, Collection value) throws JSONException {\n\t\tthis.put(key, new JSONArray(value));\n\t\treturn this;\n\t}\n\n\t/**\n\t * Put a key/double pair in the JSONObject.\n\t * \n\t * @param key\n\t * A key string.\n\t * @param value\n\t * A double which is the value.\n\t * @return this.\n\t * @throws JSONException\n\t * If the key is null or if the number is invalid.\n\t */\n\tpublic JSONObject put(String key, double value) throws JSONException {\n\t\tthis.put(key, new Double(value));\n\t\treturn this;\n\t}\n\n\t/**\n\t * Put a key/int pair in the JSONObject.\n\t * \n\t * @param key\n\t * A key string.\n\t * @param value\n\t * An int which is the value.\n\t * @return this.\n\t * @throws JSONException\n\t * If the key is null.\n\t */\n\tpublic JSONObject put(String key, int value) throws JSONException {\n\t\tthis.put(key, new Integer(value));\n\t\treturn this;\n\t}\n\n\t/**\n\t * Put a key/long pair in the JSONObject.\n\t * \n\t * @param key\n\t * A key string.\n\t * @param value\n\t * A long which is the value.\n\t * @return this.\n\t * @throws JSONException\n\t * If the key is null.\n\t */\n\tpublic JSONObject put(String key, long value) throws JSONException {\n\t\tthis.put(key, new Long(value));\n\t\treturn this;\n\t}\n\n\t/**\n\t * Put a key/value pair in the JSONObject, where the value will be a\n\t * JSONObject which is produced from a Map.\n\t * \n\t * @param key\n\t * A key string.\n\t * @param value\n\t * A Map value.\n\t * @return this.\n\t * @throws JSONException\n\t */\n\tpublic JSONObject put(String key, Map value) throws JSONException {\n\t\tthis.put(key, new JSONObject(value));\n\t\treturn this;\n\t}\n\n\t/**\n\t * Put a key/value pair in the JSONObject. If the value is null, then the\n\t * key will be removed from the JSONObject if it is present.\n\t * \n\t * @param key\n\t * A key string.\n\t * @param value\n\t * An object which is the value. It should be of one of these\n\t * types: Boolean, Double, Integer, JSONArray, JSONObject, Long,\n\t * String, or the JSONObject.NULL object.\n\t * @return this.\n\t * @throws JSONException\n\t * If the value is non-finite number or if the key is null.\n\t */\n\tpublic JSONObject put(String key, Object value) throws JSONException {\n\t\tif (key == null) {\n\t\t\tthrow new NullPointerException(\"Null key.\");\n\t\t}\n\t\tif (value != null) {\n\t\t\ttestValidity(value);\n\t\t\tthis.map.put(key, value);\n\t\t} else {\n\t\t\tthis.remove(key);\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * Put a key/value pair in the JSONObject, but only if the key and the value\n\t * are both non-null, and only if there is not already a member with that\n\t * name.\n\t * \n\t * @param key\n\t * @param value\n\t * @return his.\n\t * @throws JSONException\n\t * if the key is a duplicate\n\t */\n\tpublic JSONObject putOnce(String key, Object value) throws JSONException {\n\t\tif (key != null && value != null) {\n\t\t\tif (this.opt(key) != null) {\n\t\t\t\tthrow new JSONException(\"Duplicate key \\\"\" + key + \"\\\"\");\n\t\t\t}\n\t\t\tthis.put(key, value);\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * Put a key/value pair in the JSONObject, but only if the key and the value\n\t * are both non-null.\n\t * \n\t * @param key\n\t * A key string.\n\t * @param value\n\t * An object which is the value. It should be of one of these\n\t * types: Boolean, Double, Integer, JSONArray, JSONObject, Long,\n\t * String, or the JSONObject.NULL object.\n\t * @return this.\n\t * @throws JSONException\n\t * If the value is a non-finite number.\n\t */\n\tpublic JSONObject putOpt(String key, Object value) throws JSONException {\n\t\tif (key != null && value != null) {\n\t\t\tthis.put(key, value);\n\t\t}\n\t\treturn this;\n\t}\n\n\t/**\n\t * Remove a name and its value, if present.\n\t * \n\t * @param key\n\t * The name to be removed.\n\t * @return The value that was associated with the name, or null if there was\n\t * no value.\n\t */\n\tpublic Object remove(String key) {\n\t\treturn this.map.remove(key);\n\t}\n\n\t/**\n\t * Produce a JSONArray containing the values of the members of this\n\t * JSONObject.\n\t * \n\t * @param names\n\t * A JSONArray containing a list of key strings. This determines\n\t * the sequence of the values in the result.\n\t * @return A JSONArray of values.\n\t * @throws JSONException\n\t * If any of the values are non-finite numbers.\n\t */\n\tpublic JSONArray toJSONArray(JSONArray names) throws JSONException {\n\t\tif (names == null || names.length() == 0) {\n\t\t\treturn null;\n\t\t}\n\t\tJSONArray ja = new JSONArray();\n\t\tfor (int i = 0; i < names.length(); i += 1) {\n\t\t\tja.put(this.opt(names.getString(i)));\n\t\t}\n\t\treturn ja;\n\t}\n\n\t/**\n\t * Make a JSON text of this JSONObject. For compactness, no whitespace is\n\t * added. If this would not result in a syntactically correct JSON text,\n\t * then null will be returned instead.\n\t * <p>\n\t * Warning: This method assumes that the data structure is acyclical.\n\t * \n\t * @return a printable, displayable, portable, transmittable representation\n\t * of the object, beginning with <code>{</code> <small>(left\n\t * brace)</small> and ending with <code>}</code> <small>(right\n\t * brace)</small>.\n\t */\n\t@Override\n\tpublic String toString() {\n\t\ttry {\n\t\t\treturn this.toString(0);\n\t\t} catch (Exception e) {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t/**\n\t * Make a prettyprinted JSON text of this JSONObject.\n\t * <p>\n\t * Warning: This method assumes that the data structure is acyclical.\n\t * \n\t * @param indentFactor\n\t * The number of spaces to add to each level of indentation.\n\t * @return a printable, displayable, portable, transmittable representation\n\t * of the object, beginning with <code>{</code> <small>(left\n\t * brace)</small> and ending with <code>}</code> <small>(right\n\t * brace)</small>.\n\t * @throws JSONException\n\t * If the object contains an invalid number.\n\t */\n\tpublic String toString(int indentFactor) throws JSONException {\n\t\tStringWriter w = new StringWriter();\n\t\tsynchronized (w.getBuffer()) {\n\t\t\treturn this.write(w, indentFactor, 0).toString();\n\t\t}\n\t}\n\n\t/**\n\t * Write the contents of the JSONObject as JSON text to a writer. For\n\t * compactness, no whitespace is added.\n\t * <p>\n\t * Warning: This method assumes that the data structure is acyclical.\n\t * \n\t * @return The writer.\n\t * @throws JSONException\n\t */\n\tpublic Writer write(Writer writer) throws JSONException {\n\t\treturn this.write(writer, 0, 0);\n\t}\n\n\t/**\n\t * Write the contents of the JSONObject as JSON text to a writer. For\n\t * compactness, no whitespace is added.\n\t * <p>\n\t * Warning: This method assumes that the data structure is acyclical.\n\t * \n\t * @return The writer.\n\t * @throws JSONException\n\t */\n\tWriter write(Writer writer, int indentFactor, int indent)\n\t\t\tthrows JSONException {\n\t\ttry {\n\t\t\tboolean commanate = false;\n\t\t\tfinal int length = this.length();\n\t\t\tIterator keys = this.keys();\n\t\t\twriter.write('{');\n\n\t\t\tif (length == 1) {\n\t\t\t\tObject key = keys.next();\n\t\t\t\twriter.write(quote(key.toString()));\n\t\t\t\twriter.write(':');\n\t\t\t\tif (indentFactor > 0) {\n\t\t\t\t\twriter.write(' ');\n\t\t\t\t}\n\t\t\t\twriteValue(writer, this.map.get(key), indentFactor, indent);\n\t\t\t} else if (length != 0) {\n\t\t\t\tfinal int newindent = indent + indentFactor;\n\t\t\t\twhile (keys.hasNext()) {\n\t\t\t\t\tObject key = keys.next();\n\t\t\t\t\tif (commanate) {\n\t\t\t\t\t\twriter.write(',');\n\t\t\t\t\t}\n\t\t\t\t\tif (indentFactor > 0) {\n\t\t\t\t\t\twriter.write('\\n');\n\t\t\t\t\t}\n\t\t\t\t\tindent(writer, newindent);\n\t\t\t\t\twriter.write(quote(key.toString()));\n\t\t\t\t\twriter.write(':');\n\t\t\t\t\tif (indentFactor > 0) {\n\t\t\t\t\t\twriter.write(' ');\n\t\t\t\t\t}\n\t\t\t\t\twriteValue(writer, this.map.get(key), indentFactor,\n\t\t\t\t\t\t\tnewindent);\n\t\t\t\t\tcommanate = true;\n\t\t\t\t}\n\t\t\t\tif (indentFactor > 0) {\n\t\t\t\t\twriter.write('\\n');\n\t\t\t\t}\n\t\t\t\tindent(writer, indent);\n\t\t\t}\n\t\t\twriter.write('}');\n\t\t\treturn writer;\n\t\t} catch (IOException exception) {\n\t\t\tthrow new JSONException(exception);\n\t\t}\n\t}\n}",
"public class Configs {\n\n\tpublic static final String CATEGORY_UPDATE_TIMES = \"update times\";\n\tpublic static final String CATEGORY_CONNECTION_SETTINGS = \"connection settings\";\n\tpublic static final String CATEGORY_GENERAL = Configuration.CATEGORY_GENERAL;\n\tpublic static String hostname;\n\tpublic static int port;\n\tpublic static int server_info_update_time;\n\tpublic static int world_info_update_time;\n\tpublic static int player_info_update_time;\n\tpublic static int chat_update_time;\n\tpublic static boolean auth_required;\n\tpublic static boolean obs_publ_admin;\n\tpublic static boolean debug_mode;\n\tpublic static Configuration config;\n\tprivate static String TAG = \"Configs\";\n\n\t/**\n\t * Creates a Configuration from the given config file and loads configs afterwards\n\t * @param configFile\n\t */\n\tpublic static void init(File configFile) {\n\t\tif (config == null) {\n\t\t\tconfig = new Configuration(configFile);\n\t\t}\n\n\t\tloadConfiguration();\n\n\t}\n\n\t/**\n\t * Loads/refreshes the configuration and adds comments if there aren't any\n\t * {@link #init(File) init} has to be called once before using this\n\t */\n\tpublic static void loadConfiguration() {\n\n\t\t// Categegories\n\t\tConfigCategory update_times = config.getCategory(CATEGORY_UPDATE_TIMES);\n\t\tupdate_times\n\t\t\t\t.setComment(\"How often are the information updated (Measured in ServerTicks, just try out some values).\");\n\t\tConfigCategory con = config.getCategory(CATEGORY_CONNECTION_SETTINGS);\n\t\tcon.setComment(\"On what Ip and port should the mod listen\");\n\n\t\t// Connection settings\n\t\ttry {\n\t\t\thostname = config.get(con.getQualifiedName(), \"hostname\", InetAddress.getLocalHost().getHostAddress())\n\t\t\t\t\t.getString();\n\t\t} catch (UnknownHostException e) {\n\t\t\tLogger.e(TAG, \"Failed to retrieve host address\" + e);\n\t\t\thostname = \"localhost\";\n\t\t}\n\t\tport = config.get(con.getQualifiedName(), \"port\", 25566).getInt();\n\n\t\t// Update times\n\t\tProperty prop = config.get(update_times.getQualifiedName(), \"server_info_update_time\", 500);\n prop.setComment(\"General server info\");\n server_info_update_time = prop.getInt();\n\n\t\tprop = config.get(update_times.getQualifiedName(), \"world_info_update_time\", 200);\n prop.setComment(\"World info\");\n world_info_update_time = prop.getInt();\n\n\t\tprop = config.get(update_times.getQualifiedName(), \"player_info_update_time\", 40);\n prop.setComment(\"Player info\");\n player_info_update_time = prop.getInt();\n\n\t\tprop = config.get(update_times.getQualifiedName(), \"chat_update_time\", 10);\n prop.setComment(\"Chat\");\n chat_update_time = prop.getInt();\n\n\t\t// General configs\n\n\t\tprop = config.get(CATEGORY_GENERAL, \"auth_required\", false);\n prop.setComment(\"Whether the second screen user need to login with username and password, which can be set in game\");\n auth_required = prop.getBoolean(true);\n\n\t\tprop = config.get(CATEGORY_GENERAL, \"public_observer_admin_only\", false);\n prop.setComment(\"If true, only admins can create public block observations\");\n obs_publ_admin = prop.getBoolean(false);\n\t\t\n\t\tprop = config.get(CATEGORY_GENERAL, \"debug_mode\", false);\n prop.setComment(\"Enable logging debug messages to file\");\n debug_mode=prop.getBoolean(false);\n\n\t\tif (config.hasChanged()) {\n\t\t\tconfig.save();\n\t\t}\n\t}\n\n\t@SubscribeEvent\n\tpublic void onConfigurationChanged(ConfigChangedEvent.OnConfigChangedEvent e) {\n if (e.getModID().equalsIgnoreCase(Constants.MOD_ID)) {\n // Resync configs\n\t\t\tLogger.i(TAG, \"Configuration has changed\");\n\t\t\tConfigs.loadConfiguration();\n\t\t}\n\t}\n\n}",
"public class Constants {\n\n\tpublic static final String MOD_ID = \"maxanier_secondscreenmod\";\n\tpublic static final String VERSION = \"@VERSION@\";\n\tpublic static final String MINECRAFT_VERSION = \"@MVERSION@\";\n\tpublic static final String NAME = \"Second Screen Mod\";\n\tpublic static final String UPDATE_FILE_LINK = \"http://maxgb.de/minecraftsecondscreen/modversion.json\";\n\n\t/**\n\t * Feature version for the client to know what feautures the modversion\n\t * supports\n\t */\n\tpublic static final int FEATURE_VERSION = 6;\n\n\tpublic static final String USER_SAVE_DIR = \"mss-users\";\n\n\tpublic static final String OBSERVER_FILE_NAME = \"observer.json\";\n\n\tpublic static final String GUI_FACTORY_CLASS = \"de.maxgb.minecraft.second_screen.client.gui.ModGuiFactory\";\n\n}",
"public class Helper {\n\n\t/**\n\t * Returns the GameProfile for the given username\n\t * \n\t * @param username\n\t * @return GameProfile, null if it does not exist\n\t */\n\tpublic static GameProfile getGameProfile(String username) {\n\t\tfor (GameProfile p : FMLCommonHandler.instance().getMinecraftServerInstance().getPlayerList().getOnlinePlayerProfiles()) {\n\t\t\tif(username.equals(p.getName())){\n\t\t\t\treturn p;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\t/**\n\t * Gets players looking spot.\n\t * \n\t * @param player\n\t * @param restricts\n\t * Keeps distance to players block reach distance\n\t * @return The position as a MovingObjectPosition, null if not existent cf:\n\t * https\n\t * ://github.com/bspkrs/bspkrsCore/blob/master/src/main/java/bspkrs\n\t * /util/CommonUtils.java\n\t */\n\tpublic static RayTraceResult getPlayerLookingSpot(EntityPlayer player, boolean restrict) {\n\t\tfloat scale = 1.0F;\n\t\tfloat pitch = player.prevRotationPitch + (player.rotationPitch - player.prevRotationPitch) * scale;\n\t\tfloat yaw = player.prevRotationYaw + (player.rotationYaw - player.prevRotationYaw) * scale;\n\t\tdouble x = player.prevPosX + (player.posX - player.prevPosX) * scale;\n\t\tdouble y = player.prevPosY + (player.posY - player.prevPosY) * scale + 1.62D - player.getYOffset();\n\t\tdouble z = player.prevPosZ + (player.posZ - player.prevPosZ) * scale;\n\t\tVec3d vector1 = new Vec3d(x, y, z);\n\t\tfloat cosYaw = MathHelper.cos(-yaw * 0.017453292F - (float) Math.PI);\n\t\tfloat sinYaw = MathHelper.sin(-yaw * 0.017453292F - (float) Math.PI);\n\t\tfloat cosPitch = -MathHelper.cos(-pitch * 0.017453292F);\n\t\tfloat sinPitch = MathHelper.sin(-pitch * 0.017453292F);\n\t\tfloat pitchAdjustedSinYaw = sinYaw * cosPitch;\n\t\tfloat pitchAdjustedCosYaw = cosYaw * cosPitch;\n\t\tdouble distance = 500D;\n\t\tif (player instanceof EntityPlayerMP && restrict) {\n\t\t\tdistance = ((EntityPlayerMP) player).interactionManager.getBlockReachDistance();\n\t\t}\n\t\tVec3d vector2 = vector1.addVector(pitchAdjustedSinYaw * distance, sinPitch * distance, pitchAdjustedCosYaw\n\t\t\t\t* distance);\n\t\treturn player.getEntityWorld().rayTraceBlocks(vector1, vector2);\n\t}\n\n\t/**\n\t * Returns if the user with the given username is opped on this server.\n\t * \n\t * @param username\n\t * @return\n\t */\n\tpublic static boolean isPlayerOpped(String username) {\n\t\tfor (String s : FMLCommonHandler.instance().getMinecraftServerInstance().getPlayerList().getOppedPlayerNames()) {\n\t\t\tif(s.equals(username)){\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\t\n\t/**\n\t * Sends a chat message to server chat\n\t * @param msg Message\n\t */\n\tpublic static void sendChatMessage(String msg){\n\t\tsendChatMessage(msg, TextFormatting.WHITE);\n\t}\n\t\n\t/**\n\t * Sends a chat message to server chat\n\t * @param msg Message\n\t * @param color Color\n\t */\n\tpublic static void sendChatMessage(String msg, TextFormatting color) {\n\t\tsendChatMessage(msg,color,false,false,false);\n\t}\n\t\n\t/**\n\t * Sends a chat message to server chat\n\t * @param msg\n\t * @param color\n\t * @param bold\n\t * @param underlined\n\t * @param italic\n\t */\n\tpublic static void sendChatMessage(String msg, TextFormatting color, boolean bold, boolean underlined, boolean italic) {\n\t\tITextComponent com = new TextComponentString(msg);\n\t\tStyle style = new Style().setColor(color);\n\t\tstyle.setBold(bold);\n\t\tstyle.setUnderlined(underlined);\n\t\tstyle.setItalic(italic);\n\t\tcom.setStyle(style);\n\t\tFMLCommonHandler.instance().getMinecraftServerInstance().getPlayerList().sendMessage(com);\n\t}\n\t\n\tpublic static String getCurrentTimeString() {\n\t\tDate timeDate = new Date(System.currentTimeMillis());\n\t\tString min = \"\" + timeDate.getMinutes();\n\t\tif (min.length() < 2) {\n\t\t\tmin = \"0\" + min;\n\t\t}\n\t\tString h = \"\" + timeDate.getHours();\n\t\tif (h.length() < 2) {\n\t\t\th = \"0\" + h;\n\t\t}\n\t\treturn h + \":\" + min;\n\t}\n\t\n\tpublic static ItemStack createTutorialBook(){\n\t\tItemStack bookStack = new ItemStack(Items.WRITTEN_BOOK);\n\t\tNBTTagList bookPages = new NBTTagList();\n\t\tbookPages.appendTag(new NBTTagString(\"Welcome to the MinecraftSecondScreen mod manual!\"\n\t\t\t\t+ \"\\nThis mod allows you to use your mobile device/second screen as a 'Second Screen' or 'Companion app' for Minecraft. \\nIt also allows you to control certain things in game. \"));\n\t\tbookPages.appendTag(new NBTTagString(\"Currently there is a native Android (4.0+) app and a universal webapp which can be used on any device with a modern internet browser,\\nbut the universal app is currently lacking a few features.\"));\n\t\tbookPages.appendTag(new NBTTagString(\"Download of the apps:\\nhttp://maxgb.de/minecraftsecondscreen/files\\n\\nUsage:\\nhttp://maxgb.de/minecraftsecondscreen/usage.html\"));\n\t\t\n\t\tbookStack.setTagInfo(\"pages\", bookPages);\n\t\tbookStack.setTagInfo(\"author\", new NBTTagString(\"maxanier\"));\n\t\tbookStack.setTagInfo(\"title\", new NBTTagString(\"Second Screen Mod Manual\"));\n\t\t\n\t\treturn bookStack;\n\t\t\n\t}\n\t\n\t/**\n\t * Drops Itemstack in world.\n\t * Copied from OpenModsLib and edited\n\t * @param worldObj\n\t * @param x\n\t * @param y\n\t * @param z\n\t * @param stack\n\t * @return\n\t */\n\tpublic static EntityItem dropItemStackInWorld(World worldObj, double x, double y, double z, ItemStack stack) {\n\t\tfloat f = 0.7F;\n\t\tfloat d0 = worldObj.rand.nextFloat() * f + (1.0F - f) * 0.5F;\n\t\tfloat d1 = worldObj.rand.nextFloat() * f + (1.0F - f) * 0.5F;\n\t\tfloat d2 = worldObj.rand.nextFloat() * f + (1.0F - f) * 0.5F;\n\t\tEntityItem entityitem = new EntityItem(worldObj, x + d0, y + d1, z + d2, stack);\n\t\tentityitem.setDefaultPickupDelay();\n\t\tif (stack.hasTagCompound()) {\n\t\t\tentityitem.getItem().setTagCompound(stack.getTagCompound().copy());\n\t\t}\n\t\tworldObj.spawnEntity(entityitem);\n\t\treturn entityitem;\n}\n\n}",
"public class Logger {\r\n\r\n\tpublic static void d(String tag, String msg) {\r\n\t\tif(Configs.debug_mode){\r\n\t\t\tlog(Level.INFO, \"[\" + tag + \"]\" + msg);\r\n\t\t}\r\n\r\n\t}\r\n\r\n\tpublic static void e(String tag, String msg) {\r\n\t\tlog(Level.ERROR, \"[\" + tag + \"]\" + msg);\r\n\t}\r\n\r\n\tpublic static void e(String tag, String msg, Throwable t) {\r\n\t\tString stacktrace = \"\";\r\n\t\t\r\n\t\tPrintStream p;\r\n\t\ttry {\r\n\t\t\tp = new PrintStream(stacktrace);\r\n\t\t\tt.printStackTrace(p);\r\n\t\t} catch (FileNotFoundException e1) {\r\n\t\t\tstacktrace = t.getMessage();\r\n\t\t}\r\n\t\tlog(Level.ERROR, \"[\" + tag + \"]\" + msg + \"\\nThrowable: \"+t.getClass().getCanonicalName()+\"\\nStacktrace: \" + stacktrace+\"\\nMessage: \"+t.getMessage());\r\n\t}\r\n\r\n\r\n\tpublic static void i(String tag, String msg) {\r\n\t\tlog(Level.INFO, \"[\" + tag + \"]\" + msg);\r\n\t}\r\n\r\n\r\n\tprivate static void log(Level level, String msg) {\r\n\t\tFMLLog.log(Constants.MOD_ID, level, msg);\r\n\t}\r\n\r\n\tpublic static void w(String tag, String msg) {\r\n\t\tlog(Level.WARN, \"[\" + tag + \"]\" + msg);\r\n\r\n\t}\r\n}\r",
"public class ObservedBlock {\n\n\t/**\n\t * Collects the data from all observed blocks, seperates them by types and\n\t * puts the results in the parent JSON\n\t *\n\t * @param parent\n\t * JSONObject to store data\n\t * @param worlds\n\t * Minecraftworlds which contain the blocks\n\t */\n\tpublic static void addObservingInfo(JSONObject parent, HashMap<Integer, WorldServer> worlds, String username) {\n\n\t\tArrayList<ObservedBlock> blocks = ObservingManager.getObservedBlocks(username, true);\n\t\tfor (int i = 0; i < blocks.size(); i++) {\n\t\t\tObservedBlock block = blocks.get(i);\n\n\t\t\tWorldServer world = worlds.get(block.dimensionId);\n\n\t\t\tif (world == null) {\n\t\t\t\tLogger.w(TAG, \"Dimension corrosponding to the block not found: \" + block.dimensionId);\n\t\t\t\tObservingManager.removeObservedBlock(username, block.label);\n\n\t\t\t} else {\n\t\t\t\tif (world.getBlockState(block.pos).getMaterial() == Material.AIR) {\n\t\t\t\t\tLogger.w(TAG, \"Blocks material is air -> remove\");\n\t\t\t\t\tObservingManager.removeObservedBlock(username, block.label);\n\t\t\t\t} else {\n\t\t\t\t\tfor (ObservingType t : getObservingTypes()) {\n\t\t\t\t\t\tif (t.getId() == block.type) {\n\t\t\t\t\t\t\tif (!t.addInfoForBlock(world, block)) {\n\t\t\t\t\t\t\t\tObservingManager.removeObservedBlock(username, block.label);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor (ObservingType t : getObservingTypes()) {\n\t\t\tt.finishInfoCreation(parent);\n\t\t}\n\n\t}\n\n\tprivate final static String TAG = \"ObservedBlock\";\n\n\tprivate static List<ObservingType> observingTypes;\n\n\t/**\n\t * Interface for observingtypes e.g. InventoryObserver or FluidTankObserver\n\t *\n\t * @author Max\n\t */\n\tpublic interface ObservingType {\n\t\t/**\n\t\t * Adds the informations about the given block to the next update\n\t\t *\n\t\t * @param block\n\t\t * @param world World the block is in\n\t\t * @return false if the block should be removed from the list\n\t\t */\n\t\tboolean addInfoForBlock(World world, ObservedBlock block);\n\n\t\t/**\n\t\t * Tests if this block/tile can be observed by this observer type\n\t\t *\n\t\t * @param block\n\t\t * @param tile tile can be null\n\t\t * @return\n\t\t */\n\t\tboolean canObserve(IBlockState block, TileEntity tile);\n\n\t\t/**\n\t\t * Adds all information collected by\n\t\t * {@link #addInfoForBlock(ObservedBlock) addInfoForBlock} method. Does\n\t\t * not change anything if nothing to add\n\t\t *\n\t\t * @param parent JSONObject the info shall be added to\n\t\t */\n\t\tvoid finishInfoCreation(JSONObject parent);\n\n\t\t/**\n\t\t * @return ID for this type\n\t\t */\n\t\tint getId();\n\n\t\t/**\n\t\t * @return A string which can be used to indentify this type in commands\n\t\t * etc\n\t\t */\n\t\tString getIdentifier();\n\n\t\t/**\n\t\t * @return A short string which can be used to indentify this type in\n\t\t * commands etc\n\t\t */\n\t\tString getShortIndentifier();\n\t}\n\n\t/**\n\t * Creates an ObservedBlock from its json save data\n\t * \n\t * @param json\n\t * @return\n\t */\n\tpublic static ObservedBlock createFromJson(JSONObject json) {\n\t\ttry {\n\t\t\tObservedBlock b = new ObservedBlock();\n\t\t\tb.label = json.getString(\"label\");\n\n\t\t\tJSONArray coord = json.getJSONArray(\"coord\");\n\t\t\tb.pos=new BlockPos(coord.getInt(0),coord.getInt(1),coord.getInt(2));\n\t\t\tb.dimensionId = coord.getInt(3);\n\n\t\t\tb.type = json.getInt(\"type\");\n\n\t\t\tif (json.has(\"side_str\")) {\n\t\t\t\tb.side = EnumFacing.byName(json.getString(\"side_str\"));\n\t\t\t} else {\n\t\t\t\tb.side = EnumFacing.UP;\n\t\t\t}\n\n\t\t\treturn b;\n\t\t} catch (JSONException e) {\n\t\t\tLogger.e(TAG, \"Failed to parse block\", e);\n\t\t\treturn null;\n\t\t}\n\n\t}\n\n\t/**\n\t * @return A list of all available ObservingTypes\n\t */\n\tpublic static List<ObservingType> getObservingTypes() {\n\t\tif (observingTypes == null) {\n\t\t\tobservingTypes = new ArrayList<ObservingType>();\n\t\t\tobservingTypes.add(new RedstoneObserver());\n\t\t\tobservingTypes.add(new InventoryObserver());\n\t\t\tobservingTypes.add(new FluidTankObserver());\n\t\t\t//observingTypes.add(new NodeObserver());\n\t\t\t//observingTypes.add(new RFEnergyStorageObserver());\n\t\t}\n\n\t\treturn observingTypes;\n\t}\n\n\tprotected String label;\n\n\tprotected int dimensionId;\n\t\n\tprotected BlockPos pos;\n\t\n\tprotected EnumFacing side;\n\n\tprotected int type;\n\n\tprivate ObservedBlock() {\n\n\t}\n\n\t/**\n\t * Creates a ObservedBlock\n\t * @param label Name/Label\n\t * @param x X-Coord\n\t * @param y Y-Coord\n\t * @param z Z-Coord\n\t * @param dimensionId Worlddimension id\n\t * @param type ObservingType given by the corrosponding observer class\n\t * @param sideHit Side it was registered from\n\t */\n\tpublic ObservedBlock(String label, BlockPos pos, int dimensionId, int type, EnumFacing sideHit) {\n\t\tthis.pos=pos;\n\t\tthis.label = label;\n\t\tthis.dimensionId = dimensionId;\n\t\tthis.type = type;\n\t\tthis.side = sideHit;\n\t}\n\n\t/**\n\t * Returns the block assosiated with the coordinated in the given world\n\t * \n\t * @param world\n\t * world\n\t * @return block\n\t */\n\tpublic Block getBlock(IBlockAccess world) {\n\t\treturn world.getBlockState(pos).getBlock();\n\t}\n\n\tpublic String getLabel() {\n\t\treturn label;\n\t}\n\n\t/**\n\t * Created a JsonObject representing this block\n\t * \n\t * @return\n\t */\n\tpublic JSONObject toJSON() {\n\t\tJSONObject json = new JSONObject();\n\t\tjson.put(\"label\", label);\n\n\t\tJSONArray coord = new JSONArray();\n\t\tcoord.put(pos.getX());\n\t\tcoord.put(pos.getY());\n\t\tcoord.put(pos.getZ());\n\t\tcoord.put(dimensionId);\n\n\t\tjson.put(\"coord\", coord);\n\t\tjson.put(\"side_str\", side.getName());\n\n\t\tjson.put(\"type\", type);\n\n\t\treturn json;\n\t}\n}"
] | import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import de.maxgb.minecraft.second_screen.Configs;
import de.maxgb.minecraft.second_screen.util.Constants;
import de.maxgb.minecraft.second_screen.util.Helper;
import de.maxgb.minecraft.second_screen.util.Logger;
import de.maxgb.minecraft.second_screen.world_observer.ObservedBlock;
| package de.maxgb.minecraft.second_screen.data;
/**
* Manages all observed blocks
* Saves and loads them and makes sure that every player gets his private and the public block infos
* @author Max
*
*/
public class ObservingManager {
private static final String TAG = "ObservingManager";
private static final String PUBLIC_USER = "msspublic";
private static HashMap<String, HashMap<String, ObservedBlock>> map;
/**
* Returns all blocks observed by that user
*
* @param username
* player
* @param publ
* if true, the public blocks are returned as well
* @return if none, an empty list is returned
*/
public static ArrayList<ObservedBlock> getObservedBlocks(String username, boolean publ) {
ArrayList<ObservedBlock> blocks = new ArrayList<ObservedBlock>();
if (map != null && map.get(username) != null) {
blocks.addAll(map.get(username).values());
}
if (publ) {
blocks.addAll(getObservedBlocks(PUBLIC_USER, false));
}
return blocks;
}
/**
* Loads the observation map from a jsonfile
*/
public static void loadObservingFile() {
ArrayList<String> lines = DataStorageDriver.readFromWorldFile(Constants.OBSERVER_FILE_NAME);
if (lines == null || lines.size() == 0) {
| Logger.w(TAG, "No saved data found");
| 5 |
jmhertlein/MCTowns | src/main/java/cafe/josh/mctowns/TownManager.java | [
"public abstract class MCTownsRegion {\n\n private static final long serialVersionUID = \"MCTOWNSREGION\".hashCode(); // DO NOT CHANGE\n private static final int VERSION = 0;\n /**\n * The name of the region, the name of the world in which the region exists\n */\n protected volatile String name, worldName;\n\n public MCTownsRegion() {\n }\n\n /**\n * creates a new region with the name name, and sets its world to be\n * worldname\n *\n * @param name the name of the new region\n * @param worldName the world of the new region\n */\n public MCTownsRegion(String name, String worldName) {\n this.name = name.toLowerCase();\n this.worldName = worldName;\n }\n\n /**\n *\n * @return the name of the region\n */\n public String getName() {\n return name;\n }\n\n /**\n *\n * @return the name of the world in which the region resides\n */\n public String getWorldName() {\n return worldName;\n }\n\n /**\n *\n * @param playerID\n *\n * @return\n */\n public boolean removePlayer(UUID playerID) {\n DefaultDomain members, owners;\n boolean removed = false;\n WorldGuardPlugin wgp = MCTowns.getWorldGuardPlugin();\n\n World w = wgp.getServer().getWorld(worldName);\n if(w == null) {\n return false;\n }\n\n ProtectedRegion reg = wgp.getRegionManager(w).getRegion(name);\n if(reg == null) {\n return false;\n }\n\n members = reg.getMembers();\n owners = reg.getOwners();\n\n if(members.contains(playerID)) {\n members.removePlayer(playerID);\n removed = true;\n }\n\n if(owners.contains(playerID)) {\n owners.removePlayer(playerID);\n removed = true;\n }\n\n return removed;\n }\n\n public boolean removePlayer(OfflinePlayer p) {\n return this.removePlayer(p.getUniqueId());\n }\n\n /**\n *\n * @param p\n *\n * @return\n */\n public boolean addPlayer(OfflinePlayer p) {\n return addPlayer(p.getUniqueId());\n }\n\n public boolean addPlayer(UUID playerID) {\n World w = MCTowns.getWorldGuardPlugin().getServer().getWorld(worldName);\n if(w == null) {\n return false;\n }\n\n ProtectedRegion reg = MCTowns.getWorldGuardPlugin().getRegionManager(w).getRegion(name);\n if(reg == null) {\n return false;\n }\n\n DefaultDomain dd = reg.getOwners();\n\n if(!dd.contains(playerID)) {\n dd.addPlayer(playerID);\n return true;\n }\n return false;\n }\n\n public boolean addGuest(UUID playerID) {\n World w = MCTowns.getWorldGuardPlugin().getServer().getWorld(worldName);\n if(w == null) {\n return false;\n }\n\n ProtectedRegion reg = MCTowns.getWorldGuardPlugin().getRegionManager(w).getRegion(name);\n if(reg == null) {\n return false;\n }\n\n DefaultDomain members = reg.getMembers();\n\n if(!members.contains(playerID)) {\n members.addPlayer(playerID);\n return true;\n }\n\n return false;\n }\n\n public boolean addGuest(OfflinePlayer p) {\n return addGuest(p.getUniqueId());\n }\n\n public ProtectedRegion getWGRegion() {\n return MCTowns.getWorldGuardPlugin().getRegionManager(Bukkit.getServer().getWorld(worldName)).getRegion(name);\n }\n\n @Override\n public String toString() {\n return name;\n }\n\n @Override\n public boolean equals(Object obj) {\n if(obj == null) {\n return false;\n }\n if(getClass() != obj.getClass()) {\n return false;\n }\n final MCTownsRegion other = (MCTownsRegion) obj;\n if(!Objects.equals(this.name, other.name)) {\n return false;\n }\n if(!Objects.equals(this.worldName, other.worldName)) {\n return false;\n }\n return true;\n }\n\n @Override\n public int hashCode() {\n int hash = 3;\n hash = 79 * hash + Objects.hashCode(this.name);\n hash = 79 * hash + Objects.hashCode(this.worldName);\n return hash;\n }\n\n public static final String formatRegionName(Town owner, TownLevel type, String plotName) {\n plotName = plotName.toLowerCase();\n\n String infix;\n if(type == TownLevel.PLOT) {\n infix = TownLevel.PLOT_INFIX;\n } else if(type == TownLevel.TERRITORY) {\n infix = TownLevel.TERRITORY_INFIX;\n } else {\n infix = \"\";\n }\n\n return (owner.getName() + infix + plotName).toLowerCase();\n }\n\n public String getReadableName() {\n return name.substring(name.lastIndexOf('_') + 1);\n }\n\n public void writeYAML(FileConfiguration f) {\n f.set(\"name\", name);\n f.set(\"worldName\", worldName);\n }\n}",
"public class Plot extends MCTownsRegion {\n\n private static final long serialVersionUID = \"PLOT\".hashCode(); // DO NOT CHANGE\n private volatile String parTerrName;\n private volatile String parTownName;\n private boolean forSale;\n private volatile BigDecimal price;\n private volatile Location signLoc;\n\n /**\n * Creates a new plot with the specified properties.\n *\n * @param name\n * @param worldName\n * @param parentTerritoryName\n * @param parentTownName\n */\n public Plot(String name, String worldName, String parentTerritoryName, String parentTownName) {\n super(name, worldName);\n\n price = MCTowns.getTownManager().getTown(parentTownName).getDefaultPlotPrice();\n parTerrName = parentTerritoryName;\n parTownName = parentTownName;\n\n //note to self- don't put calculateSignLoc() here because it needs the region to already\n //be added to the region manager\n }\n\n /**\n * Empty constructor for de-serialization. Recommended: Don't use this.\n */\n private Plot() {\n }\n\n /**\n *\n * @return\n */\n public String getParentTerritoryName() {\n return parTerrName;\n }\n\n /**\n *\n * @return\n */\n public String getParentTownName() {\n return parTownName;\n }\n\n /**\n *\n * @return the price of the Plot\n */\n public BigDecimal getPrice() {\n return price;\n }\n\n /**\n *\n * @param price\n */\n public void setPrice(BigDecimal price) {\n this.price = price;\n }\n\n /**\n *\n * @return the location of the plot's sale sign\n */\n public Location getSignLoc() {\n return signLoc;\n }\n\n /**\n *\n * @return the shorter, reading-friendly name of the plot\n */\n public String getTerseName() {\n String absName = name;\n\n for(int i = 0; i < 2; i++) {\n absName = absName.substring(absName.indexOf('_') + 1);\n }\n\n return absName;\n }\n\n /**\n *\n * @param signLoc the new location for the plot's sale sign\n */\n public void setSignLoc(Location signLoc) {\n this.signLoc = signLoc;\n }\n\n /**\n *\n * @return\n */\n public boolean isForSale() {\n return forSale;\n }\n\n /**\n *\n * @param forSale\n */\n public void setForSale(boolean forSale) {\n this.forSale = forSale;\n }\n\n /**\n * @param referencePlayerLocation the location whose yaw will be used to set\n * the sign's yaw such that if the location is that of a player, the sign\n * will point towards him\n *\n * @return whether or not the sign was built\n */\n public boolean buildSign(org.bukkit.Location referencePlayerLocation) {\n if(signLoc == null) {\n MCTowns.logSevere(\"The sign's location was null.\");\n }\n\n org.bukkit.Location loc = Location.convertToBukkitLocation(Bukkit.getServer(), signLoc);\n\n if(loc.getBlock().getType() != Material.AIR) {\n return false;\n }\n\n loc.getBlock().setType(Material.SIGN_POST);\n\n Sign sign = (Sign) loc.getBlock().getState();\n\n org.bukkit.material.Sign signData = (org.bukkit.material.Sign) sign.getData();\n signData.setFacingDirection(Location.getBlockFaceFromYaw(Location.getYawInOppositeDirection(referencePlayerLocation.getYaw())));\n sign.setData(signData);\n\n sign.setLine(0, \"[mct]\");\n sign.setLine(1, \"For sale!\");\n sign.setLine(2, name);\n sign.setLine(3, \"Price: \" + price);\n sign.update();\n\n return true;\n }\n\n /**\n *\n */\n public void demolishSign() {\n Location.convertToBukkitLocation(Bukkit.getServer(), signLoc).getBlock().setType(Material.AIR);\n }\n\n /**\n * Tries to place the sign's location in the middle of the plot.\n */\n public final void calculateSignLoc() {\n WorldGuardPlugin wgp = MCTowns.getWorldGuardPlugin();\n ProtectedRegion reg = wgp.getRegionManager(wgp.getServer().getWorld(worldName)).getRegion(name);\n Vector middle = reg.getMaximumPoint().add(reg.getMinimumPoint());\n middle = middle.divide(2);\n\n org.bukkit.Location loc = new org.bukkit.Location(wgp.getServer().getWorld(worldName), middle.getBlockX(), middle.getBlockY(), middle.getBlockZ());\n\n loc.setY(loc.getWorld().getHighestBlockYAt(loc));\n\n signLoc = Location.convertFromBukkitLocation(loc);\n }\n\n /**\n *\n * @return\n */\n public boolean signLocIsSet() {\n return signLoc != null;\n }\n\n /**\n *\n * @param f\n */\n @Override\n public void writeYAML(FileConfiguration f) {\n super.writeYAML(f);\n f.set(\"forSale\", forSale);\n f.set(\"price\", (price == null) ? \"nil\" : price.toString());\n f.set(\"signLoc\", (signLoc == null) ? \"nil\" : signLoc.toList());\n f.set(\"parentTownName\", parTownName);\n f.set(\"parentTerritoryName\", parTerrName);\n f.set(\"type\", TownLevel.PLOT.name());\n }\n\n /**\n *\n * @param f\n *\n * @return\n */\n public static Plot readYAML(FileConfiguration f) {\n Plot p = new Plot();\n\n p.name = f.getString(\"name\");\n p.worldName = f.getString(\"worldName\");\n p.parTerrName = f.getString(\"parentTerritoryName\");\n p.parTownName = f.getString(\"parentTownName\");\n p.forSale = f.getBoolean(\"forSale\");\n\n if(f.getString(\"signLoc\").equals(\"nil\")) {\n p.signLoc = null;\n } else {\n p.signLoc = Location.fromList(f.getStringList(\"signLoc\"));\n }\n\n if(f.getString(\"price\").equals(\"nil\")) {\n p.price = null;\n } else {\n p.price = new BigDecimal(f.getString(\"price\"));\n }\n\n return p;\n }\n}",
"public class Town {\n private volatile String townName;\n private volatile String townMOTD;\n private volatile ChatColor motdColor;\n private volatile BlockBank bank;\n private Set<String> territories;\n private Set<UUID> residents;\n private UUID mayor;\n private Set<UUID> assistants;\n private boolean buyablePlots;\n private boolean economyJoins;\n private volatile BigDecimal defaultPlotPrice;\n private boolean friendlyFire;\n private Map<String, Location> warps;\n\n /**\n * Creates a new town, setting the name to townName, the mayor to the player\n * passed as mayor, and adds the mayor to the list of residents. The MOTD is\n * set to a default motd.\n *\n * @param townName the desired name of the town\n * @param mayor the player to be made the mayor of the town\n *\n */\n public Town(String townName, Player mayor) {\n initialize(townName, mayor.getUniqueId(), mayor.getLocation());\n }\n\n public Town(String townName, Player mayor, Location townSpawnLoc) {\n initialize(townName, mayor.getUniqueId(), townSpawnLoc);\n }\n\n public Town(String townName, UUID mayorId, Location spawnLoc) {\n initialize(townName, mayorId, spawnLoc);\n }\n\n private void initialize(String townName1, UUID mayorId, Location spawnLoc) {\n this.townName = townName1;\n mayor = mayorId;\n residents = new HashSet<>();\n assistants = new HashSet<>();\n territories = new HashSet<>();\n warps = new HashMap<>();\n setSpawn(spawnLoc);\n bank = new BlockBank(MCTownsPlugin.getPlugin().getOpenDepositInventories());\n townMOTD = \"Use /town motd set <msg> to set the town MOTD!\";\n buyablePlots = false;\n economyJoins = false;\n defaultPlotPrice = BigDecimal.TEN;\n friendlyFire = false;\n motdColor = ChatColor.GOLD;\n residents.add(mayor);\n }\n\n private Town() {\n }\n\n /**\n *\n * @return\n */\n public BlockBank getBank() {\n return bank;\n }\n\n /**\n * Sets the motd to the specified MOTD\n *\n * @param townMOTD - the new MOTD\n */\n public void setTownMOTD(String townMOTD) {\n this.townMOTD = townMOTD;\n }\n\n /**\n * Gets the UUID of the mayor of the town.\n *\n * @return the UUID of the town's mayor\n */\n public UUID getMayor() {\n return mayor;\n }\n\n /**\n * Sets the town's mayor to the given name\n *\n * @param mayor the new mayor's name\n */\n public void setMayor(UUID mayor) {\n this.mayor = mayor;\n }\n\n /**\n * Sets the town's mayor to the given name\n *\n * @param mayor the new mayor\n */\n public void setMayor(OfflinePlayer mayor) {\n this.mayor = UUIDs.getUUIDForOfflinePlayer(mayor);\n }\n\n /**\n * Returns the town MOTD, with color formatting\n *\n * @return the town MOTD\n */\n public String getTownMOTD() {\n return motdColor + townMOTD;\n }\n\n public ChatColor getMotdColor() {\n return motdColor;\n }\n\n /**\n * Returns the town's name\n *\n * @return the town's name\n */\n public String getName() {\n return townName;\n }\n\n /**\n * Adds a player as a resident of the town\n *\n * @param p the player to be added\n *\n * @return false if player was not added because player is already added,\n * true otherwise\n */\n public boolean addPlayer(Player p) {\n return addPlayer(p.getUniqueId());\n }\n\n public boolean addPlayer(UUID u) {\n return residents.add(u);\n }\n\n public boolean addPlayer(OfflinePlayer playerId) {\n return addPlayer(UUIDs.getUUIDForOfflinePlayer(playerId));\n }\n\n /**\n * Removes a player from the town. Postcondition: Player is not a resident\n * of the town, regardless of whether or not they were before. Note: Player\n * must still be removed from the WG regions associated with the town\n *\n * @param p - the player to be removed\n */\n public void removePlayer(OfflinePlayer p) {\n removePlayer(UUIDs.getUUIDForOfflinePlayer(p));\n }\n\n /**\n * Removes the player from the town's list of residents and assistants. Does\n * not remove them from regions.\n *\n * @param playerId\n */\n public void removePlayer(UUID playerId) {\n residents.remove(playerId);\n assistants.remove(playerId);\n }\n\n /**\n * Adds the territory to the town. The region of the territory will need to\n * be handled separately.\n *\n * @param territ the territory to be added\n * @return false if territ was not added because it is already added, true\n * otherwise\n */\n public boolean addTerritory(Territory territ) {\n return territories.add(territ.getName());\n }\n\n /**\n * Removes the territory from the town.\n *\n * @param territName the name of the territory to remove\n *\n * @return the removed territory\n */\n public boolean removeTerritory(String territName) {\n return territories.remove(territName);\n }\n\n /**\n * Adds a player as an assistant to the town\n *\n * @param player the player to be added\n *\n * @return false if player was not added because player was already added,\n * true otherwise\n */\n public boolean addAssistant(OfflinePlayer player) {\n return addAssistant(UUIDs.getUUIDForOfflinePlayer(player));\n }\n\n /**\n * Promotes the resident to an assistant.\n *\n * @param playerId\n *\n * @return true if player was added as assistant, false if they're already\n * an assistant\n * @throws TownException if they're not a resident of the town.\n */\n public boolean addAssistant(UUID playerId) {\n if(!residents.contains(playerId)) {\n throw new TownException(\"Player is not a resident of \" + getName());\n }\n\n return assistants.add(playerId);\n }\n\n /**\n * Removes the assistant from his position as an assistant\n *\n * @param player the player to be demoted\n *\n * @return false if the player was not removed because the player is not an\n * assistant, true otherwise\n */\n public boolean removeAssistant(OfflinePlayer player) {\n return removeAssistant(UUIDs.getUUIDForOfflinePlayer(player));\n\n }\n\n public boolean removeAssistant(UUID playerId) {\n return assistants.remove(playerId);\n\n }\n\n /**\n * Returns the territories this town has.\n *\n * Modifying membership of returned set does not modify which territs are in\n * this Town\n *\n * Sets returned by this method will not update themselves if subsequent\n * Town method calls add Territories to it\n *\n * Returned Set is unmodifiable\n *\n * @return the town's territories\n */\n public Set<String> getTerritoriesCollection() {\n return Collections.unmodifiableSet(territories);\n }\n\n /**\n * Returns whether the player is the mayor or not\n *\n * @param p the player to be checked\n *\n * @return whether the player is mayor or not\n */\n public boolean playerIsMayor(OfflinePlayer p) {\n return p.getUniqueId().equals(mayor);\n }\n\n /**\n * Returns the list of all assistants in the town.\n *\n * Modifying membership of returned set does not modify which players are\n * assistants in this Town.\n *\n * Sets returned by this method will not update themselves if subsequent\n * Town method calls add assistants to it.\n *\n * @return\n */\n public Set<String> getResidentNames() {\n return residents.stream()\n .map(u -> UUIDs.getNameForUUID(u))\n .collect(Collectors.toSet());\n\n }\n\n /**\n *\n * @return A list of the UUIDs for all residents of the town.\n */\n public Set<UUID> getResidents() {\n return Collections.unmodifiableSet(residents);\n }\n\n public Set<String> getAssistantNames() {\n return assistants.stream()\n .map(u -> UUIDs.getNameForUUID(u))\n .collect(Collectors.toSet());\n }\n\n /**\n *\n * @return\n */\n public boolean allowsFriendlyFire() {\n return friendlyFire;\n }\n\n @Override\n public int hashCode() {\n int hash = 7;\n hash = 67 * hash + Objects.hashCode(this.townName);\n return hash;\n }\n\n @Override\n public boolean equals(Object obj) {\n if(obj == null) {\n return false;\n }\n if(getClass() != obj.getClass()) {\n return false;\n }\n final Town other = (Town) obj;\n return Objects.equals(this.townName, other.townName);\n }\n\n /**\n *\n * @param friendlyFire\n */\n public void setFriendlyFire(boolean friendlyFire) {\n this.friendlyFire = friendlyFire;\n }\n\n /**\n * Returns whether or not the player is an assistant in the town\n *\n * @param p the player to be checked\n *\n * @return if the player is an assistant or not\n */\n public boolean playerIsAssistant(OfflinePlayer p) {\n return assistants.contains(UUIDs.getUUIDForOfflinePlayer(p));\n }\n\n /**\n * Returns whether or not the player is a resident of the town\n *\n * @param p the player to be checked\n *\n * @return if the player is a resident or not\n */\n public boolean playerIsResident(OfflinePlayer p) {\n return residents.contains(UUIDs.getUUIDForOfflinePlayer(p));\n }\n\n /**\n * Returns whether or not the player is a resident of the town\n *\n * @param id the id of the player to be checked\n *\n * @return if the player is a resident or not\n */\n public boolean playerIsResident(UUID id) {\n return residents.contains(id);\n }\n\n /**\n *\n * @param id\n *\n * @return\n */\n public boolean playerIsAssistant(UUID id) {\n return assistants.contains(id);\n }\n\n /**\n * Returns the current number of residents in the town.\n *\n * @return the number of residents in the town\n */\n public int getSize() {\n return residents.size();\n }\n\n /**\n *\n * @param message\n */\n public void broadcastMessageToTown(final String message) {\n Bukkit.getOnlinePlayers().stream()\n .filter(p -> residents.contains(p.getUniqueId()))\n .forEach(p -> p.sendMessage(ChatColor.GOLD + message));\n }\n\n /**\n *\n * @param p\n *\n * @return true if the player is in a territory the town owns, false\n * otherwise\n */\n public boolean playerIsInsideTownBorders(Player p) {\n org.bukkit.Location playerLoc = p.getLocation();\n Vector playerVector = new Vector(playerLoc.getBlockX(), playerLoc.getBlockY(), playerLoc.getBlockZ());\n RegionManager regMan = MCTowns.getWorldGuardPlugin().getRegionManager(p.getWorld());\n\n return getTerritoriesCollection().stream()\n .map(name -> MCTowns.getTownManager().getTerritory(name))\n .map(te -> regMan.getRegion(te.getName()))\n .anyMatch(reg -> reg.contains(playerVector));\n }\n\n /**\n *\n * @param loc\n */\n public void setSpawn(org.bukkit.Location loc) {\n warps.put(\"spawn\", loc);\n }\n\n public Location putWarp(String name, Location l) {\n return warps.put(name, l);\n }\n\n public Location removeWarp(String name) {\n return warps.remove(name);\n }\n\n public Set<String> getWarps() {\n return warps.keySet();\n }\n\n /**\n *\n *\n * @return\n */\n public Location getSpawn() {\n return getWarp(\"spawn\");\n }\n\n public Location getWarp(String name) {\n return warps.get(name);\n }\n\n /**\n *\n * @return\n */\n public boolean usesBuyablePlots() {\n return buyablePlots;\n }\n\n /**\n *\n * @param buyablePlots\n */\n public void setBuyablePlots(boolean buyablePlots) {\n this.buyablePlots = buyablePlots;\n }\n\n /**\n *\n * @return\n */\n public boolean usesEconomyJoins() {\n return economyJoins;\n }\n\n /**\n *\n * @param economyJoins\n */\n public void setEconomyJoins(boolean economyJoins) {\n this.economyJoins = economyJoins;\n }\n\n /**\n *\n * @return\n */\n public BigDecimal getDefaultPlotPrice() {\n return defaultPlotPrice;\n }\n\n /**\n *\n * @param defaultPlotPrice\n */\n public void setDefaultPlotPrice(BigDecimal defaultPlotPrice) {\n this.defaultPlotPrice = defaultPlotPrice;\n }\n\n @Override\n public String toString() {\n return this.townName;\n }\n\n public void writeYAML(FileConfiguration f) {\n f.set(\"townName\", townName);\n f.set(\"motd\", townMOTD);\n f.set(\"motdColor\", motdColor.name());\n f.set(\"warps\", warps);\n f.set(\"mayor\", mayor.toString());\n f.set(\"territs\", new LinkedList<>(territories));\n\n List<String> list = new LinkedList<>();\n list.addAll(UUIDs.idsToStrings(assistants));\n f.set(\"assistants\", list);\n\n List<String> resList = new LinkedList<>();\n resList.addAll(UUIDs.idsToStrings(residents));\n f.set(\"residents\", resList);\n\n f.set(\"friendlyFire\", friendlyFire);\n f.set(\"defaultPlotPrice\", defaultPlotPrice.toString());\n f.set(\"economyJoins\", economyJoins);\n f.set(\"buyablePlots\", buyablePlots);\n\n bank.writeYAML(f);\n }\n\n public static Town readYAML(FileConfiguration f) {\n Town t = new Town();\n\n t.townName = f.getString(\"townName\");\n t.townMOTD = f.getString(\"motd\");\n t.motdColor = ChatColor.valueOf(f.getString(\"motdColor\"));\n t.warps = (Map<String, Location>) (Map) ((MemorySection) f.get(\"warps\")).getValues(true);\n\n t.mayor = UUIDs.stringToId(f.getString(\"mayor\"));\n t.territories = new HashSet<>(f.getStringList(\"territs\"));\n\n t.assistants = UUIDs.stringsToIds(f.getStringList(\"assistants\"));\n\n t.residents = UUIDs.stringsToIds(f.getStringList(\"residents\"));\n\n t.friendlyFire = f.getBoolean(\"friendlyFire\");\n t.defaultPlotPrice = new BigDecimal(f.getString(\"defaultPlotPrice\"));\n t.economyJoins = f.getBoolean(\"economyJoins\");\n t.buyablePlots = f.getBoolean(\"buyablePlots\");\n\n t.bank = BlockBank.readYAML(f, MCTownsPlugin.getPlugin().getOpenDepositInventories());\n return t;\n }\n\n public static void recursivelyRemovePlayerFromTown(OfflinePlayer p, Town t) {\n TownManager tMan = MCTowns.getTownManager();\n\n for(String teName : t.getTerritoriesCollection()) {\n Territory te = tMan.getTerritory(teName);\n for(String plName : te.getPlotsCollection()) {\n Plot pl = tMan.getPlot(plName);\n pl.removePlayer(p);\n }\n te.removePlayer(p);\n }\n\n t.removePlayer(p);\n }\n}",
"public enum TownLevel {\n\n TOWN,\n TERRITORY,\n PLOT;\n public static final String TERRITORY_INFIX = \"_territ_\";\n public static final String PLOT_INFIX = \"_plot_\";\n\n @Override\n public String toString() {\n switch(this) {\n case TOWN:\n return \"TOWN\";\n case TERRITORY:\n return \"TERRITORY\";\n case PLOT:\n return \"PLOT\";\n default:\n return \"y u break me? ;_;\";\n }\n }\n\n public static final TownLevel parseTownLevel(String s) {\n s = s.toUpperCase();\n\n switch(s) {\n case \"TOWN\":\n return TOWN;\n case \"TERRITORY\":\n return TERRITORY;\n case \"PLOT\":\n return PLOT;\n default:\n throw new TownLevelFormatException(s);\n }\n }\n\n public static class TownLevelFormatException extends RuntimeException {\n\n public TownLevelFormatException(String badToken) {\n super(\"Error: \" + badToken + \" is not a town level.\");\n }\n }\n}",
"public class ActiveSet {\n\n private Town activeTown;\n private Territory activeTerritory;\n private Plot activePlot;\n\n /**\n *\n */\n public ActiveSet() {\n activeTown = null;\n activeTerritory = null;\n activePlot = null;\n }\n\n public ActiveSet(Town activeTown, Territory activeTerritory, Plot activePlot) {\n this.activeTown = activeTown;\n this.activeTerritory = activeTerritory;\n this.activePlot = activePlot;\n }\n\n /**\n *\n * @return the active plot\n */\n public Plot getActivePlot() {\n return activePlot;\n }\n\n /**\n *\n * @param activePlot the new active plot\n */\n public void setActivePlot(Plot activePlot) {\n this.activePlot = activePlot;\n }\n\n /**\n *\n * @return the active territory\n */\n public Territory getActiveTerritory() {\n return activeTerritory;\n }\n\n /**\n *\n * @param activeTerritory the new active territory\n */\n public void setActiveTerritory(Territory activeTerritory) {\n this.activeTerritory = activeTerritory;\n }\n\n /**\n *\n * @return the active town\n */\n public Town getActiveTown() {\n return activeTown;\n }\n\n /**\n *\n * @param activeTown the new active town\n */\n public void setActiveTown(Town activeTown) {\n this.activeTown = activeTown;\n }\n\n /**\n *\n * @return Town: <town name> Territ: <territ name> Plot: <plot name>\n */\n @Override\n public String toString() {\n return \"Town: \" + activeTown + \" Territ: \" + activeTerritory + \" Plot: \" + activePlot;\n }\n\n void clear() {\n this.activePlot = null;\n this.activeTerritory = null;\n this.activeTown = null;\n }\n}",
"public class Territory extends MCTownsRegion {\n private String parTownName;\n private Set<String> plotNames;\n\n /**\n * Constructs a new territory\n *\n * @param name the desired name of the territory\n * @param worldName the name of the world in which the territory exists\n */\n public Territory(String name, String worldName, String parentTownName) {\n super(name, worldName);\n plotNames = Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>());\n parTownName = parentTownName;\n }\n\n public Territory() {\n }\n\n /**\n * Adds a plot to the territory. Registering the WG region of the territory\n * needs to be done elsewhere.\n *\n * @param dist the plot to be added\n *\n * @return false if the plot was not added because it is already added, true\n * otherwise\n */\n public boolean addPlot(Plot plot) {\n if(plotNames.contains(plot.getName())) {\n return false;\n }\n\n plotNames.add(plot.getName());\n return true;\n }\n\n /**\n * Modifying membership of returned set does not modify which plots are in\n * this territ\n *\n * Sets returned by this method will not update themselves if subsequent\n * Territory method calls add plots to it\n *\n * Returned Set is a LinkedHashSet and as such performs well for iteration\n * and set membership checks\n *\n * @return the plots owned by this territory\n */\n public Set<String> getPlotsCollection() {\n return new LinkedHashSet<>(plotNames);\n }\n\n /**\n * Removes the plot from the territory\n *\n * @param plotName the name of the plot to be removed\n *\n * @return if a plot was removed or not\n */\n public boolean removePlot(String plotName) {\n return plotNames.remove(plotName);\n }\n\n public String getParentTown() {\n return parTownName;\n }\n\n @Override\n public void writeYAML(FileConfiguration f) {\n super.writeYAML(f);\n f.set(\"town\", parTownName);\n f.set(\"plots\", getPlotNameList());\n f.set(\"type\", TownLevel.TERRITORY.name());\n\n }\n\n public static Territory readYAML(FileConfiguration f) {\n Territory ret = new Territory();\n\n ret.name = f.getString(\"name\");\n ret.worldName = f.getString(\"worldName\");\n ret.parTownName = f.getString(\"town\");\n\n ret.plotNames = new HashSet<>();\n ret.plotNames.addAll(f.getStringList(\"plots\"));\n\n return ret;\n }\n\n private List<String> getPlotNameList() {\n LinkedList<String> ret = new LinkedList<>();\n\n for(String s : plotNames) {\n ret.add(s);\n }\n\n return ret;\n }\n}",
"public class UUIDs {\n\n /**\n * Converts a list of Strings to UUID's, using one of two strategies: 1.\n * Assume String is the toString() of a UUID, attempt to convert straight\n * back 2. If that fails, assume String is the name of a player: look up\n * their UUID and use that instead\n *\n * @param strings\n * @return\n */\n public static Set<UUID> stringsToIds(Collection<String> strings) {\n Set<UUID> ret = new HashSet<>();\n for(String s : strings) {\n ret.add(stringToId(s));\n }\n return ret;\n }\n\n /**\n * Converts a String to a UUID, using one of two strategies: 1. Assume\n * String is the toString() of a UUID, attempt to convert straight back 2.\n * If that fails, assume String is the name of a player: look up their UUID\n * and use that instead\n *\n * @param s\n * @return\n */\n public static UUID stringToId(String s) {\n UUID ret;\n try {\n ret = UUID.fromString(s);\n } catch(IllegalArgumentException iae) {\n ret = getUUIDForOfflinePlayer(Bukkit.getOfflinePlayer(s));\n }\n return ret;\n }\n\n public static Set<String> idsToStrings(Collection<UUID> ids) {\n Set<String> ret = new HashSet<>();\n for(UUID i : ids) {\n ret.add(i.toString());\n }\n return ret;\n }\n\n public static UUID getUUIDForOfflinePlayer(OfflinePlayer p) {\n return p.getUniqueId();\n }\n\n public static String getNameForUUID(UUID u) {\n return Bukkit.getOfflinePlayer(u).getName();\n }\n}"
] | import cafe.josh.mctowns.region.MCTownsRegion;
import cafe.josh.mctowns.region.Plot;
import cafe.josh.mctowns.region.Town;
import cafe.josh.mctowns.region.TownLevel;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.sk89q.worldguard.protection.managers.storage.StorageException;
import com.sk89q.worldguard.protection.regions.ProtectedRegion;
import com.sk89q.worldguard.protection.regions.ProtectedRegion.CircularInheritanceException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
import cafe.josh.mctowns.command.ActiveSet;
import cafe.josh.mctowns.region.Territory;
import cafe.josh.mctowns.util.UUIDs;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.OfflinePlayer;
import org.bukkit.World;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player; | /*
* Copyright (C) 2013 Joshua Michael Hertlein <[email protected]>
*
* 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 cafe.josh.mctowns;
/**
*
* @author joshua
*/
public class TownManager {
private final HashMap<String, Town> towns;
private final HashMap<String, MCTownsRegion> regions;
/**
* Constructs a new, empty town manager.
*/
public TownManager() {
towns = new HashMap<>();
regions = new HashMap<>();
}
/**
* Returns the towns that this manager manages
*
* @return the towns
*/
public Collection<Town> getTownsCollection() {
return towns.values();
}
/**
*
* @return
*/
public Collection<MCTownsRegion> getRegionsCollection() {
return regions.values();
}
/**
* Attempts to add a town to the town manager (effectively creating a new
* town as far as the TownManager is concerned).
*
* @param townName the desired name of the new town
* @param mayor the live player to be made the mayor of the new town
*
* @return true if town was added, false if town was not because it was
* already existing
*/
public Town addTown(String townName, Player mayor) {
Town t = new Town(townName, mayor);
if(towns.containsKey(t.getName())) {
return null;
}
towns.put(t.getName(), t);
return t;
}
public Town addTown(String townName, Player mayorName, Location spawn) {
Town t = new Town(townName, mayorName, spawn);
if(towns.containsKey(t.getName())) {
return null;
}
towns.put(t.getName(), t);
return t;
}
/**
* Creates a new territory, adds it to the manager, and registers its region
* in WorldGuard.
*
* @param fullTerritoryName the desired, formatted name of the region
* @param worldTerritoryIsIn
* @param reg the desired region for the territory to occupy, names MUST
* match
* @param parentTown the parent town of the Territory
*
* @throws InvalidWorldGuardRegionNameException if the name of the
* ProtectedRegion contains invalid characters
* @throws RegionAlreadyExistsException if the region already exists
*/
public void addTerritory(String fullTerritoryName, World worldTerritoryIsIn, ProtectedRegion reg, Town parentTown) throws InvalidWorldGuardRegionNameException, RegionAlreadyExistsException { | Territory t = new Territory(fullTerritoryName, | 5 |
hypfvieh/bluez-dbus | bluez-dbus/src/main/java/org/bluez/mesh/Management1.java | [
"@SuppressWarnings(\"serial\")\npublic class BluezMeshAlreadyExistsException extends DBusException {\n\n public BluezMeshAlreadyExistsException(String _message) {\n super(_message);\n }\n\n}",
"@SuppressWarnings(\"serial\")\npublic class BluezMeshBusyException extends DBusException {\n\n public BluezMeshBusyException(String _message) {\n super(_message);\n }\n\n}",
"@SuppressWarnings(\"serial\")\npublic class BluezMeshDoesNotExistException extends DBusException {\n\n public BluezMeshDoesNotExistException(String _message) {\n super(_message);\n }\n\n}",
"@SuppressWarnings(\"serial\")\npublic class BluezMeshFailedException extends DBusException {\n\n public BluezMeshFailedException(String _message) {\n super(_message);\n }\n\n}",
"@SuppressWarnings(\"serial\")\npublic class BluezMeshInProgressException extends DBusException {\n\n public BluezMeshInProgressException(String _message) {\n super(_message);\n }\n\n}",
"@SuppressWarnings(\"serial\")\npublic class BluezMeshInvalidArgumentsException extends DBusException {\n\n public BluezMeshInvalidArgumentsException(String _message) {\n super(_message);\n }\n\n}",
"@SuppressWarnings(\"serial\")\npublic class BluezMeshNotAuthorizedException extends DBusException {\n\n public BluezMeshNotAuthorizedException(String _message) {\n super(_message);\n }\n\n}"
] | import java.util.Map;
import org.bluez.exceptions.mesh.BluezMeshAlreadyExistsException;
import org.bluez.exceptions.mesh.BluezMeshBusyException;
import org.bluez.exceptions.mesh.BluezMeshDoesNotExistException;
import org.bluez.exceptions.mesh.BluezMeshFailedException;
import org.bluez.exceptions.mesh.BluezMeshInProgressException;
import org.bluez.exceptions.mesh.BluezMeshInvalidArgumentsException;
import org.bluez.exceptions.mesh.BluezMeshNotAuthorizedException;
import org.freedesktop.dbus.interfaces.DBusInterface;
import org.freedesktop.dbus.types.UInt16;
import org.freedesktop.dbus.types.Variant; | package org.bluez.mesh;
/**
* File generated - 2020-12-28.<br>
* Based on bluez Documentation: mesh-api.txt.<br>
* <br>
* <b>Service:</b> org.bluez.mesh<br>
* <b>Interface:</b> org.bluez.mesh.Management1<br>
* <br>
* <b>Object path:</b><br>
* /org/bluez/mesh/node<uuid><br>
* where <uuid> is the Device UUID passed to Join(),<br>
* CreateNetwork() or Import()<br>
*/
public interface Management1 extends DBusInterface {
/**
* <b>From bluez documentation:</b><br>
* <br>
* This method is used by the application that supports<br>
* org.bluez.mesh.Provisioner1 interface to start listening<br>
* (scanning) for unprovisioned devices in the area.<br>
* <br>
* The options parameter is a dictionary with the following keys<br>
* defined:<br>
* <pre>
* uint16 Seconds
* Specifies number of seconds for scanning to be active.
* If set to 0 or if this key is not present, then the
* scanning will continue until UnprovisionedScanCancel()
* or AddNode() methods are called.
* </pre>
* <br>
* Each time a unique unprovisioned beacon is heard, the<br>
* ScanResult() method on the app will be called with the result.<br>
*
* @param _options options
*
* @throws BluezMeshInvalidArgumentsException when invalid argument given
* @throws BluezMeshNotAuthorizedException when not authorized
* @throws BluezMeshBusyException when already busy
*/
void UnprovisionedScan(Map<String, Variant<?>> _options) throws BluezMeshInvalidArgumentsException, BluezMeshNotAuthorizedException, BluezMeshBusyException;
/**
* <b>From bluez documentation:</b><br>
* <br>
* This method is used by the application that supports<br>
* org.bluez.mesh.Provisioner1 interface to stop listening<br>
* (scanning) for unprovisioned devices in the area.<br>
*
* @throws BluezMeshInvalidArgumentsException when invalid argument given
* @throws BluezMeshNotAuthorizedException when not authorized
*/
void UnprovisionedScanCancel() throws BluezMeshInvalidArgumentsException, BluezMeshNotAuthorizedException;
/**
* <b>From bluez documentation:</b><br>
* <br>
* This method is used by the application that supports<br>
* org.bluez.mesh.Provisioner1 interface to add the<br>
* unprovisioned device specified by uuid, to the Network.<br>
* <br>
* The uuid parameter is a 16-byte array that contains Device UUID<br>
* of the unprovisioned device to be added to the network.<br>
* <br>
* The options parameter is a dictionary that may contain<br>
* additional configuration info (currently an empty placeholder<br>
* for forward compatibility).<br>
*
* @param _uuid uuid (16-byte array)
* @param _options options
*
* @throws BluezMeshInvalidArgumentsException when invalid argument given
* @throws BluezMeshNotAuthorizedException when not authorized
*/
void AddNode(byte[] _uuid, Map<String, Variant<?>> _options) throws BluezMeshInvalidArgumentsException, BluezMeshNotAuthorizedException;
/**
* <b>From bluez documentation:</b><br>
* <br>
* This method is used by the application to generate and add a new<br>
* network subnet key.<br>
* <br>
* The net_index parameter is a 12-bit value (0x001-0xFFF)<br>
* specifying which net key to add.<br>
* <br>
* This call affects the local bluetooth-meshd key database only.
*
* @param _netIndex net_index
*
* @throws BluezMeshInvalidArgumentsException when invalid argument given
* @throws BluezMeshNotAuthorizedException when not authorized
*/
void CreateSubnet(UInt16 _netIndex) throws BluezMeshInvalidArgumentsException, BluezMeshNotAuthorizedException;
/**
* <b>From bluez documentation:</b><br>
* <br>
* This method is used by the application to add a network subnet<br>
* key, that was originally generated by a remote Config Client.<br>
* <br>
* The net_index parameter is a 12-bit value (0x000-0xFFF)<br>
* specifying which net key to add.<br>
* <br>
* The net_key parameter is the 16-byte value of the net key being<br>
* imported.<br>
* <br>
* This call affects the local bluetooth-meshd key database only.
*
* @param _netIndex net_index
* @param _netKey net_key
*
* @throws BluezMeshInvalidArgumentsException when invalid argument given
* @throws BluezMeshFailedException when operation failed
* @throws BluezMeshAlreadyExistsException when already exists
*/
void ImportSubnet(UInt16 _netIndex, byte[] _netKey) throws BluezMeshInvalidArgumentsException, BluezMeshFailedException, BluezMeshAlreadyExistsException;
/**
* <b>From bluez documentation:</b><br>
* <br>
* This method is used by the application to generate a new network<br>
* subnet key, and set it's key refresh state to Phase 1.<br>
* <br>
* The net_index parameter is a 12-bit value (0x000-0xFFF)<br>
* specifying which net key to update. Note that the subnet must<br>
* exist prior to updating.<br>
* <br>
* This call affects the local bluetooth-meshd key database only.
*
* @param _netIndex net_index
*
* @throws BluezMeshFailedException when operation failed
* @throws BluezMeshInvalidArgumentsException when invalid argument given
* @throws BluezMeshDoesNotExistException when not existing
* @throws BluezMeshBusyException when already busy
*/
void UpdateSubnet(UInt16 _netIndex) throws BluezMeshFailedException, BluezMeshInvalidArgumentsException, BluezMeshDoesNotExistException, BluezMeshBusyException;
/**
* <b>From bluez documentation:</b><br>
* <br>
* This method is used by the application that to delete a subnet.<br>
* <br>
* The net_index parameter is a 12-bit value (0x001-0xFFF)<br>
* specifying which net key to delete. The primary net key (0x000)<br>
* may not be deleted.<br>
* <br>
* This call affects the local bluetooth-meshd key database only.
*
* @param _netIndex net_index
*
* @throws BluezMeshInvalidArgumentsException when invalid argument given
*/
void DeleteSubnet(UInt16 _netIndex) throws BluezMeshInvalidArgumentsException;
/**
* <b>From bluez documentation:</b><br>
* <br>
* This method is used to set the master key update phase of the<br>
* given subnet. When finalizing the procedure, it is important<br>
* to CompleteAppKeyUpdate() on all app keys that have been<br>
* updated during the procedure prior to setting phase 3.<br>
* <br>
* The net_index parameter is a 12-bit value (0x000-0xFFF)<br>
* specifying which subnet phase to set.<br>
* <br>
* The phase parameter is used to cycle the local key database<br>
* through the phases as defined by the Mesh Profile Specification.
* <pre>
* Allowed values:
* 0 - Cancel Key Refresh (May only be called from Phase 1,
* and should never be called once the new key has
* started propagating)
* 1 - Invalid Argument (see NetKeyUpdate method)
* 2 - Go to Phase 2 (May only be called from Phase 1)
* 3 - Complete Key Refresh procedure (May only be called
* from Phase 2)
* </pre>
* This call affects the local bluetooth-meshd key database only.<br>
* It is the responsibility of the application to maintain the key<br>
* refresh phases per the Mesh Profile Specification.<br>
*
* @param _netIndex net_index
* @param _phase phase
*
* @throws BluezMeshFailedException when operation failed
* @throws BluezMeshInvalidArgumentsException when invalid argument given
* @throws BluezMeshDoesNotExistException when not existing
*/
void SetKeyPhase(UInt16 _netIndex, byte _phase) throws BluezMeshFailedException, BluezMeshInvalidArgumentsException, BluezMeshDoesNotExistException;
/**
* <b>From bluez documentation:</b><br>
* <br>
* This method is used by the application to generate and add a new<br>
* application key.<br>
* <br>
* The net_index parameter is a 12-bit value (0x000-0xFFF)<br>
* specifying which net key to bind the application key to.<br>
* <br>
* The app_index parameter is a 12-bit value (0x000-0xFFF)<br>
* specifying which app key to add.<br>
* <br>
* This call affects the local bluetooth-meshd key database only.
*
* @param _netIndex net_index
* @param _appIndex app_index
*
* @throws BluezMeshFailedException when operation failed
* @throws BluezMeshInvalidArgumentsException when invalid argument given
* @throws BluezMeshAlreadyExistsException when already existing
* @throws BluezMeshDoesNotExistException when not existing
*/
void CreateAppKey(UInt16 _netIndex, UInt16 _appIndex) throws BluezMeshFailedException, BluezMeshInvalidArgumentsException, BluezMeshAlreadyExistsException, BluezMeshDoesNotExistException;
/**
* <b>From bluez documentation:</b><br>
* <br>
* This method is used by the application to add an application<br>
* key, that was originally generated by a remote Config Client.<br>
* <br>
* The net_index parameter is a 12-bit value (0x000-0xFFF)<br>
* specifying which net key to bind the application key to.<br>
* <br>
* The app_index parameter is a 12-bit value (0x000-0xFFF)<br>
* specifying which app key to import.<br>
* <br>
* The app_key parameter is the 16-byte value of the key being<br>
* imported.<br>
* <br>
* This call affects the local bluetooth-meshd key database only.
*
* @param _netIndex net_index
* @param _appIndex app_index
* @param _appKey app_key
*
* @throws BluezMeshFailedException when operation failed
* @throws BluezMeshInvalidArgumentsException when invalid argument given
* @throws BluezMeshAlreadyExistsException when already existing
* @throws BluezMeshDoesNotExistException when not existing
*/
void ImportAppKey(UInt16 _netIndex, UInt16 _appIndex, byte[] _appKey) throws BluezMeshFailedException, BluezMeshInvalidArgumentsException, BluezMeshAlreadyExistsException, BluezMeshDoesNotExistException;
/**
* <b>From bluez documentation:</b><br>
* <br>
* This method is used by the application to generate a new<br>
* application key.<br>
* <br>
* The app_index parameter is a 12-bit value (0x000-0xFFF)<br>
* specifying which app key to update. Note that the subnet that<br>
* the key is bound to must exist and be in Phase 1.<br>
* <br>
* This call affects the local bluetooth-meshd key database only.
* @param _appIndex app_index
*
* @throws BluezMeshFailedException when operation failed
* @throws BluezMeshInvalidArgumentsException when invalid argument given
* @throws BluezMeshDoesNotExistException when not existing
* @throws BluezMeshInProgressException when already in progress
*/ | void UpdateAppKey(UInt16 _appIndex) throws BluezMeshFailedException, BluezMeshInvalidArgumentsException, BluezMeshDoesNotExistException, BluezMeshInProgressException; | 4 |
SumoLogic/sumologic-jenkins-plugin | src/main/java/com/sumologic/jenkins/jenkinssumologicplugin/PluginDescriptorImpl.java | [
"public enum EventSourceEnum {\n\n PERIODIC_UPDATE(\"Periodic_Update\"),\n COMPUTER_ONLINE(\"Computer_Online\"),\n COMPUTER_OFFLINE(\"Computer_Offline\"),\n COMPUTER_TEMP_ONLINE(\"Computer_Temp_Online\"),\n COMPUTER_TEMP_OFFLINE(\"Computer_Temp_Offline\"),\n COMPUTER_PRE_ONLINE(\"Computer_Pre_Online\"),\n COMPUTER_PRE_LAUNCH(\"Computer_Pre_Launch\"),\n LAUNCH_FAILURE(\"Launch_Failure\"),\n SHUTDOWN(\"Shutdown\");\n\n private final String value;\n\n EventSourceEnum(final String value) {\n this.value = value;\n }\n\n public String getValue() {\n return value;\n }\n}",
"public enum LogTypeEnum {\n\n JOB_STATUS(\"Job_Status\"),\n TEST_RESULT(\"Test_Result\"),\n PIPELINE_STAGES(\"Pipeline_Stages\"),\n AUDIT_EVENT(\"Audit_Event\"),\n QUEUE_EVENT(\"Queue_Event\"),\n // Changing the value will impact app also.\n AGENT_EVENT(\"Slave_Event\"),\n SCM_STATUS(\"Scm_Status\"),\n JENKINS_LOG(\"Jenkins_Log\");\n private final String value;\n\n LogTypeEnum(final String value) {\n this.value = value;\n }\n\n public String getValue() {\n return value;\n }\n\n}",
"public class SumoMetricDataPublisher {\n\n private static final Logger LOGGER = LoggerFactory.getLogger(SumoMetricDataPublisher.class);\n\n private transient SumoMetricReporter sumoMetricReporter;\n\n\n public synchronized void stopReporter() {\n if (sumoMetricReporter != null) {\n LOGGER.info(\"Stopping Reporter\");\n sumoMetricReporter.stop();\n }\n }\n\n public synchronized void publishMetricData(String metricDataPrefix) {\n LOGGER.info(\"Starting Reporter with prefix as \"+metricDataPrefix);\n MetricRegistry metricRegistry = Metrics.metricRegistry();\n\n sumoMetricReporter = SumoMetricReporter\n .forRegistry(metricRegistry)\n .prefixedWith(metricDataPrefix)\n .convertRatesTo(TimeUnit.SECONDS)\n .convertDurationsTo(TimeUnit.MILLISECONDS)\n .filter(new WhitelistMetricFilter(createMetricFilter()))\n .build(LogSenderHelper.getInstance());\n\n sumoMetricReporter.start(2, TimeUnit.MINUTES);\n\n }\n\n private Set<String> createMetricFilter() {\n final Set<String> whitelist = new HashSet<>();\n\n whitelist.add(\"jenkins.executor.count.value\");\n whitelist.add(\"jenkins.executor.free.value\");\n whitelist.add(\"jenkins.executor.in-use.value\");\n whitelist.add(\"jenkins.job.count.value\");\n whitelist.add(\"jenkins.node.offline.value\");\n whitelist.add(\"jenkins.node.online.value\");\n whitelist.add(\"jenkins.node.count.value\");\n whitelist.add(\"jenkins.queue.blocked.value\");\n whitelist.add(\"jenkins.queue.buildable.value\");\n whitelist.add(\"jenkins.queue.pending.value\");\n whitelist.add(\"jenkins.queue.stuck.value\");\n whitelist.add(\"jenkins.queue.size.value\");\n whitelist.add(\"jenkins.job.total.duration\");\n whitelist.add(\"jenkins.job.blocked.duration\");\n whitelist.add(\"jenkins.job.waiting.duration\");\n whitelist.add(\"jenkins.job.queuing.duration\");\n whitelist.add(\"vm.memory.heap.init\");\n whitelist.add(\"vm.memory.heap.max\");\n whitelist.add(\"vm.memory.heap.used\");\n whitelist.add(\"vm.memory.total.init\");\n whitelist.add(\"vm.memory.total.max\");\n whitelist.add(\"vm.memory.total.used\");\n whitelist.add(\"vm.memory.non-heap.init\");\n whitelist.add(\"vm.memory.non-heap.max\");\n whitelist.add(\"vm.memory.non-heap.used\");\n whitelist.add(\"system.cpu.load\");\n whitelist.add(\"vm.cpu.load\");\n whitelist.add(\"vm.daemon.count\");\n whitelist.add(\"vm.blocked.count\");\n whitelist.add(\"vm.deadlock.count\");\n whitelist.add(\"vm.runnable.count\");\n whitelist.add(\"vm.waiting.count\");\n whitelist.add(\"vm.gc.\");\n\n return whitelist;\n }\n\n static class WhitelistMetricFilter implements MetricFilter {\n private final Set<String> whitelist;\n\n private WhitelistMetricFilter(Set<String> whitelist) {\n this.whitelist = whitelist;\n }\n\n @Override\n public boolean matches(String name, Metric metric) {\n for (String whitelisted : whitelist) {\n if (whitelisted.endsWith(name) || name.contains(whitelisted))\n return true;\n }\n return false;\n }\n }\n}",
"public class PluginConfiguration implements Serializable {\n protected static final long serialVersionUID = 1L;\n\n private String sumoLogicEndpoint;\n private String queryPortal;\n private String sourceCategory;\n private String metricDataPrefix;\n private boolean auditLogEnabled;\n private boolean keepOldConfigData;\n private boolean metricDataEnabled;\n private boolean periodicLogEnabled;\n private boolean jobStatusLogEnabled;\n private boolean jobConsoleLogEnabled;\n private boolean scmLogEnabled;\n\n public PluginConfiguration(PluginDescriptorImpl pluginDescriptor) {\n this.sumoLogicEndpoint = pluginDescriptor.getUrl();\n this.queryPortal = pluginDescriptor.getQueryPortal();\n this.sourceCategory = pluginDescriptor.getSourceCategory();\n this.metricDataPrefix = pluginDescriptor.getMetricDataPrefix();\n this.auditLogEnabled = pluginDescriptor.isAuditLogEnabled();\n this.keepOldConfigData = pluginDescriptor.isKeepOldConfigData();\n this.metricDataEnabled = pluginDescriptor.isMetricDataEnabled();\n this.periodicLogEnabled = pluginDescriptor.isPeriodicLogEnabled();\n this.jobStatusLogEnabled = pluginDescriptor.isJobStatusLogEnabled();\n this.jobConsoleLogEnabled = pluginDescriptor.isJobConsoleLogEnabled();\n this.scmLogEnabled = pluginDescriptor.isScmLogEnabled();\n }\n\n public String getSumoLogicEndpoint() {\n return sumoLogicEndpoint;\n }\n\n public void setSumoLogicEndpoint(String sumoLogicEndpoint) {\n this.sumoLogicEndpoint = sumoLogicEndpoint;\n }\n\n public String getQueryPortal() {\n return queryPortal;\n }\n\n public void setQueryPortal(String queryPortal) {\n this.queryPortal = queryPortal;\n }\n\n public String getSourceCategory() {\n return sourceCategory;\n }\n\n public void setSourceCategory(String sourceCategory) {\n this.sourceCategory = sourceCategory;\n }\n\n public String getMetricDataPrefix() {\n return metricDataPrefix;\n }\n\n public void setMetricDataPrefix(String metricDataPrefix) {\n this.metricDataPrefix = metricDataPrefix;\n }\n\n public boolean isAuditLogEnabled() {\n return auditLogEnabled;\n }\n\n public void setAuditLogEnabled(boolean auditLogEnabled) {\n this.auditLogEnabled = auditLogEnabled;\n }\n\n public boolean isKeepOldConfigData() {\n return keepOldConfigData;\n }\n\n public void setKeepOldConfigData(boolean keepOldConfigData) {\n this.keepOldConfigData = keepOldConfigData;\n }\n\n public boolean isMetricDataEnabled() {\n return metricDataEnabled;\n }\n\n public void setMetricDataEnabled(boolean metricDataEnabled) {\n this.metricDataEnabled = metricDataEnabled;\n }\n\n public boolean isPeriodicLogEnabled() {\n return periodicLogEnabled;\n }\n\n public void setPeriodicLogEnabled(boolean periodicLogEnabled) {\n this.periodicLogEnabled = periodicLogEnabled;\n }\n\n public boolean isJobStatusLogEnabled() {\n return jobStatusLogEnabled;\n }\n\n public void setJobStatusLogEnabled(boolean jobStatusLogEnabled) {\n this.jobStatusLogEnabled = jobStatusLogEnabled;\n }\n\n public boolean isJobConsoleLogEnabled() {\n return jobConsoleLogEnabled;\n }\n\n public void setJobConsoleLogEnabled(boolean jobConsoleLogEnabled) {\n this.jobConsoleLogEnabled = jobConsoleLogEnabled;\n }\n\n public boolean isScmLogEnabled() {\n return scmLogEnabled;\n }\n\n public void setScmLogEnabled(boolean scmLogEnabled) {\n this.scmLogEnabled = scmLogEnabled;\n }\n}",
"public class LogSender {\n public final static Logger LOG = Logger.getLogger(LogSender.class.getName());\n CloseableHttpClient httpclient;\n\n private LogSender() {\n LOG.log(Level.INFO, \"Initializing Log Sender to Send Logs to Sumo Logic.\");\n // Creating the Client Connection Pool Manager by instantiating the PoolingHttpClientConnectionManager class.\n PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(-1L, TimeUnit.MINUTES);\n // Increase max total connection to 200\n connectionManager.setMaxTotal(200);\n // Increase default max connection per route to 20\n connectionManager.setDefaultMaxPerRoute(20);\n //socket timeout for 2 minutes\n SocketConfig defaultSocketConfig = SocketConfig.custom().setSoTimeout((int) TimeUnit.MINUTES.toMillis(3)).build();\n connectionManager.setDefaultSocketConfig(defaultSocketConfig);\n\n ConnectionKeepAliveStrategy myStrategy = new DefaultConnectionKeepAliveStrategy() {\n @Override\n public long getKeepAliveDuration(HttpResponse httpResponse, HttpContext httpContext) {\n long keepAliveTime = super.getKeepAliveDuration(httpResponse, httpContext);\n if (keepAliveTime == -1L) {\n keepAliveTime = TimeUnit.MINUTES.toMillis(2);\n }\n return keepAliveTime;\n }\n };\n\n //Create a ClientBuilder Object by setting the connection manager\n httpclient = HttpClients.custom()\n .setConnectionManager(connectionManager)\n .setKeepAliveStrategy(myStrategy)\n .setDefaultRequestConfig(RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build())\n .useSystemProperties()\n .build();\n }\n\n private String getHost(PluginConfiguration pluginConfiguration) {\n String hostName = \"unknown\";\n try {\n if (pluginConfiguration.getMetricDataPrefix() != null) {\n hostName = pluginConfiguration.getMetricDataPrefix();\n } else {\n hostName = InetAddress.getLocalHost().getHostName();\n }\n } catch (Exception e) {\n LOG.log(Level.WARNING, \"Couldn't resolve jenkins host name... Using unknown.\");\n }\n return hostName;\n }\n\n private static class LogSenderHolder {\n static LogSender logSender = new LogSender();\n }\n\n public static LogSender getInstance() {\n return LogSenderHolder.logSender;\n }\n\n void sendLogs(byte[] msg, String sumoName, String contentType, HashMap<String, String> fields) {\n HttpPost post = null;\n CloseableHttpResponse response = null;\n PluginConfiguration pluginConfiguration = PluginDescriptorImpl.getPluginConfiguration();\n try {\n post = new HttpPost(pluginConfiguration.getSumoLogicEndpoint());\n\n createHeaders(post, sumoName, contentType, fields, pluginConfiguration);\n\n byte[] compressedData = compress(msg);\n post.setEntity(new ByteArrayEntity(compressedData));\n\n response = httpclient.execute(post);\n\n StatusLine statusLine = response.getStatusLine();\n if (statusLine != null && statusLine.getStatusCode() != 200) {\n LOG.log(Level.WARNING, String.format(\"Received HTTP error from Sumo Service: %d\", statusLine.getStatusCode()));\n }\n } catch (Exception e) {\n LOG.log(Level.WARNING, String.format(\"Could not send log to Sumo Logic: %s\", e.toString()));\n } finally {\n if (post != null) {\n post.releaseConnection();\n }\n if (response != null) {\n try {\n response.close();\n } catch (IOException e) {\n LOG.log(Level.WARNING, \"Unable to Close Response\");\n }\n }\n }\n }\n\n public void sendLogs(byte[] msg) {\n sendLogs(msg, null, null, null);\n }\n\n public void sendLogs(byte[] msg, String sumoName) {\n sendLogs(msg, sumoName, null, null);\n }\n\n public void sendLogs(byte[] msg, String sumoName, String contentType) {\n sendLogs(msg, sumoName, contentType, null);\n }\n\n public void sendLogs(byte[] msg, String sumoName, HashMap<String, String> fields) {\n sendLogs(msg, sumoName, null, fields);\n }\n\n private byte[] compress(byte[] content) throws IOException {\n ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();\n GZIPOutputStream gzipOutputStream = new GZIPOutputStream(byteArrayOutputStream);\n gzipOutputStream.write(content);\n gzipOutputStream.close();\n\n return byteArrayOutputStream.toByteArray();\n }\n\n private void createHeaders(final HttpPost post, final String sumoName, final String contentType,\n HashMap<String, String> fields, PluginConfiguration pluginConfiguration) {\n post.addHeader(\"X-Sumo-Host\", getHost(pluginConfiguration));\n\n if (StringUtils.isNotBlank(sumoName)) {\n post.addHeader(\"X-Sumo-Name\", sumoName);\n }\n\n post.addHeader(\"X-Sumo-Category\", pluginConfiguration.getSourceCategory());\n\n post.addHeader(\"Content-Encoding\", \"gzip\");\n\n if (isValidContentType(contentType)) {\n post.addHeader(\"Content-Type\", contentType);\n }\n\n if (fields != null && !fields.isEmpty()) {\n String field_string = fields.keySet().stream().map(key -> key + \"=\" + fields.get(key)).collect(Collectors.joining(\",\"));\n post.addHeader(\"X-Sumo-Fields\", field_string);\n }\n\n post.addHeader(\"X-Sumo-Client\", \"sumologic-jenkins-plugin\");\n }\n\n private boolean isValidContentType(final String contentType) {\n if (contentType != null) {\n return GRAPHITE_CONTENT_TYPE.equals(contentType) || CARBON_CONTENT_TYPE.equals(contentType);\n }\n return false;\n }\n\n public StatusLine testHTTPUrl(String url) throws Exception {\n HttpPost post = null;\n CloseableHttpResponse response = null;\n\n try {\n post = new HttpPost(url);\n\n post.setEntity(new StringEntity(\"This is a Test Message from Jenkins Plugin.\"));\n\n response = httpclient.execute(post);\n\n return response.getStatusLine();\n } finally {\n if (post != null) {\n post.releaseConnection();\n }\n if (response != null) {\n try {\n response.close();\n } catch (IOException e) {\n LOG.log(Level.WARNING, \"Unable to Close Response\");\n }\n }\n }\n }\n}",
"@SuppressFBWarnings(\"DM_DEFAULT_ENCODING\")\npublic class LogSenderHelper {\n\n public final static Logger LOG = Logger.getLogger(LogSenderHelper.class.getName());\n\n public LogSenderHelper() {\n LOG.log(Level.INFO, \"Initialized the Log Sender Helper\");\n }\n\n private static class LogSenderHelperHolder {\n public static LogSenderHelper logSenderHelper = new LogSenderHelper();\n }\n\n public static LogSenderHelper getInstance() {\n return LogSenderHelperHolder.logSenderHelper;\n }\n\n public void sendData(byte[] bytes){\n LogSender.getInstance().sendLogs(bytes);\n }\n\n public void sendDataWithFields(byte[] bytes, HashMap<String, String> fields){\n LogSender.getInstance().sendLogs(bytes, null, fields);\n }\n\n public void sendLogsToPeriodicSourceCategory(String data) {\n\n PluginDescriptorImpl pluginDescriptor = PluginDescriptorImpl.getInstance();\n if (pluginDescriptor.isPeriodicLogEnabled()) {\n LogSender.getInstance().sendLogs(data.getBytes());\n }\n }\n\n public void sendMultiplePeriodicLogs(final List<String> messages) {\n List<String> strings = divideDataIntoEquals(messages);\n for (String data : strings) {\n sendLogsToPeriodicSourceCategory(data);\n }\n }\n\n public void sendFilesData(final List<String> messages, String localFileString, HashMap<String, String> fields) {\n if (CollectionUtils.isNotEmpty(messages)) {\n List<String> strings = divideDataIntoEquals(messages);\n for (String data : strings) {\n LogSender.getInstance().sendLogs(data.getBytes(), localFileString, fields);\n }\n }\n }\n\n public void sendLogsToMetricDataCategory(final List<String> messages) {\n PluginDescriptorImpl pluginDescriptor = PluginDescriptorImpl.getInstance();\n if (pluginDescriptor.isMetricDataEnabled()) {\n List<String> strings = divideDataIntoEquals(messages);\n for (String data : strings) {\n LogSender.getInstance().sendLogs(data.getBytes(), null, GRAPHITE_CONTENT_TYPE);\n }\n }\n\n }\n\n public void sendJobStatusLogs(String data) {\n LogSender.getInstance().sendLogs(data.getBytes());\n }\n\n public void sendConsoleLogs(String data, String jobName, int buildNumber, String stageName) {\n\n String sourceName = jobName + \"#\" + buildNumber;\n if (StringUtils.isNotEmpty(stageName)) {\n sourceName = sourceName + \"#\" + stageName;\n }\n LogSender.getInstance().sendLogs(data.getBytes(), sourceName);\n }\n\n public void sendAuditLogs(String data) {\n PluginDescriptorImpl pluginDescriptor = PluginDescriptorImpl.getInstance();\n if (pluginDescriptor.isAuditLogEnabled()) {\n LogSender.getInstance().sendLogs(data.getBytes());\n }\n }\n\n private static List<String> divideDataIntoEquals(final List<String> messages) {\n List<String> convertedMessages = new ArrayList<>();\n\n StringBuilder stringBuilder = new StringBuilder();\n int count = 1;\n for (String message : messages) {\n stringBuilder.append(message).append(\"\\n\");\n if (count % DIVIDER_FOR_MESSAGES == 0) {\n convertedMessages.add(stringBuilder.toString());\n stringBuilder = new StringBuilder();\n }\n count++;\n }\n convertedMessages.add(stringBuilder.toString());\n\n return convertedMessages;\n }\n\n public static void sendTestResult(TestCaseModel testCaseModel, BuildModel buildModel) {\n Gson gson = new Gson();\n\n Map<String, Object> data = new HashMap<>();\n\n data.put(\"logType\", LogTypeEnum.TEST_RESULT.getValue());\n data.put(\"name\", buildModel.getName());\n data.put(\"number\", buildModel.getNumber());\n\n if (testCaseModel != null) {\n if (CollectionUtils.isNotEmpty(testCaseModel.getTestResults())) {\n List<TestCaseResultModel> testResults = testCaseModel.getTestResults();\n // send test cases based on the size\n List<TestCaseResultModel> toBeSent = new LinkedList<>();\n data.put(\"testResult\", toBeSent);\n int size = gson.toJson(data).getBytes().length;\n for (TestCaseResultModel testCaseResultModel : testResults) {\n if (\"Failed\".equals(testCaseResultModel.getStatus())) {\n testCaseResultModel.setErrorDetails(format(testCaseResultModel.getErrorDetails()));\n testCaseResultModel.setErrorStackTrace(format(testCaseResultModel.getErrorStackTrace()));\n }\n size = size + gson.toJson(testCaseResultModel).getBytes().length;\n if (size > MAX_DATA_SIZE) {\n sendTestResultInChunksOfPreDefinedSize(buildModel, gson, toBeSent, data);\n toBeSent.clear();\n }\n toBeSent.add(testCaseResultModel);\n size = gson.toJson(data).getBytes().length;\n }\n if (CollectionUtils.isNotEmpty(toBeSent)) {\n sendTestResultInChunksOfPreDefinedSize(buildModel, gson, toBeSent, data);\n toBeSent.clear();\n }\n }\n }\n }\n\n private static void sendTestResultInChunksOfPreDefinedSize(BuildModel buildModel, Gson gson,\n List<TestCaseResultModel> toBeSent, Map<String, Object> data) {\n LOG.log(Level.INFO, \"Job Name - \" + buildModel.getName() + \", Build Number - \" + buildModel.getNumber() + \", test result count is \" + toBeSent.size() +\n \", number of bytes is \" + gson.toJson(data).getBytes().length);\n LogSender.getInstance().sendLogs(gson.toJson(data).getBytes());\n }\n\n public static void sendPipelineStages(List<PipelineStageModel> stages, BuildModel buildModel) {\n List<String> allStages = new ArrayList<>();\n Gson gson = new Gson();\n Map<String, Object> data = new HashMap<>();\n\n data.put(\"logType\", LogTypeEnum.PIPELINE_STAGES.getValue());\n data.put(\"name\", buildModel.getName());\n data.put(\"number\", buildModel.getNumber());\n // Adding extra data like Build status, Build run time, Build URL, UpStream URL, Job Type.\n data.put(\"result\", buildModel.getResult());\n data.put(\"jobStartTime\", buildModel.getJobStartTime());\n data.put(\"jobType\", buildModel.getJobType());\n data.put(\"jobRunDuration\", buildModel.getJobRunDuration());\n data.put(\"jobBuildURL\", buildModel.getJobBuildURL());\n data.put(\"upstreamJobURL\", buildModel.getUpstreamJobURL());\n if (CollectionUtils.isNotEmpty(stages)) {\n for (PipelineStageModel pipelineStageModel : stages) {\n data.put(\"stages\", new ArrayList<>(Collections.singletonList(pipelineStageModel)));\n allStages.add(gson.toJson(data));\n }\n }\n List<String> strings = divideDataIntoEquals(allStages);\n for (String value : strings) {\n sendStagesInChunksOfPreDefinedSize(buildModel, allStages, value);\n }\n }\n\n private static void sendStagesInChunksOfPreDefinedSize(BuildModel buildModel, List<String> toBeSent, String data) {\n LOG.log(Level.INFO, \"Job Name - \" + buildModel.getName() + \", Build Number - \" + buildModel.getNumber() + \", Stage count is \" + toBeSent.size() +\n \", number of bytes is \" + data.length());\n LogSender.getInstance().sendLogs(data.getBytes());\n }\n\n private static String format(String data) {\n if (StringUtils.isNotEmpty(data)) {\n data = data.replace(\"{\", \"(\");\n return data.replace(\"}\", \")\");\n }\n return null;\n }\n}",
"public class SumoLogHandler extends Handler {\n\n private PluginDescriptorImpl pluginDescriptor;\n private Gson gson;\n private LogSenderHelper logSenderHelper;\n private LogRecordFormatter logRecordFormatter;\n private Level filterLevel = Level.parse(System.getProperty(SumoLogHandler.class.getName() + \".level\", \"INFO\"));\n\n public static SumoLogHandler getInstance() {\n return new SumoLogHandler();\n }\n\n public SumoLogHandler() {\n pluginDescriptor = PluginDescriptorImpl.getInstance();\n gson = new Gson();\n logRecordFormatter = new LogRecordFormatter();\n setFilter(new LogRecordFilter());\n setLevel(filterLevel);\n logSenderHelper = LogSenderHelper.getInstance();\n }\n\n @Override\n public void publish(LogRecord record) {\n try {\n if (!pluginDescriptor.isHandlerStarted()) {\n return;\n }\n if (!isLoggable(record)) {\n return;\n }\n if (pluginDescriptor.isPeriodicLogEnabled()) {\n String message = logRecordFormatter.formatRecord(record);\n logSenderHelper.sendLogsToPeriodicSourceCategory(message);\n }\n } catch (Exception exception) {\n Logger.getLogger(\"\").removeHandler(SumoLogHandler.getInstance());\n }\n }\n\n\n @Override\n public void flush() {\n //Send the data to sumo logic\n }\n\n @Override\n public void close() throws SecurityException {\n //close necessary things\n }\n\n private class LogRecordFormatter extends Formatter {\n\n @Override\n public String format(LogRecord record) {\n return formatMessage(record);\n }\n\n private String formatRecord(LogRecord record) {\n Map<String, Object> logMessage = new HashMap<>();\n logMessage.put(\"threadId\", record.getThreadID());\n logMessage.put(\"logType\", LogTypeEnum.JENKINS_LOG.getValue());\n logMessage.put(\"eventTime\", DATETIME_FORMATTER.format(new Date()));\n logMessage.put(\"logLevel\", record.getLevel().getName());\n logMessage.put(\"logMessage\", formatMessage(record));\n logMessage.put(\"logSource\", record.getLoggerName());\n if (record.getLevel().intValue() > Level.INFO.intValue() && record.getThrown() != null) {\n StringWriter sw = new StringWriter();\n PrintWriter pw = new PrintWriter(sw);\n record.getThrown().printStackTrace(pw);\n pw.close();\n logMessage.put(\"logStackTrace\", sw.toString());\n }\n return gson.toJson(logMessage);\n }\n }\n\n private static class LogRecordFilter implements Filter {\n @Override\n public boolean isLoggable(LogRecord record) {\n String logSource = record.getSourceClassName();\n String loggerName = record.getLoggerName();\n if (logSource == null || loggerName == null) {\n return false;\n }\n\n for (String name : skipLoggerNames) {\n if (loggerName.startsWith(name) || logSource.startsWith(name)) {\n return false;\n }\n }\n\n if (record.getThrown() != null) {\n StackTraceElement[] cause = record.getThrown().getStackTrace();\n for (StackTraceElement element : cause) {\n if (element.getClassName().equals(SumoLogHandler.class.getName())) {\n return false;\n }\n }\n }\n return true;\n }\n }\n}",
"public static final FastDateFormat DATETIME_FORMATTER\n = FastDateFormat.getInstance(\"yyyy-MM-dd HH:mm:ss,SSS ZZZZ\");"
] | import com.google.gson.Gson;
import com.sumologic.jenkins.jenkinssumologicplugin.constants.EventSourceEnum;
import com.sumologic.jenkins.jenkinssumologicplugin.constants.LogTypeEnum;
import com.sumologic.jenkins.jenkinssumologicplugin.metrics.SumoMetricDataPublisher;
import com.sumologic.jenkins.jenkinssumologicplugin.model.PluginConfiguration;
import com.sumologic.jenkins.jenkinssumologicplugin.sender.LogSender;
import com.sumologic.jenkins.jenkinssumologicplugin.sender.LogSenderHelper;
import com.sumologic.jenkins.jenkinssumologicplugin.utility.SumoLogHandler;
import hudson.Extension;
import hudson.ExtensionList;
import hudson.init.Initializer;
import hudson.init.TermMilestone;
import hudson.init.Terminator;
import hudson.model.AbstractProject;
import hudson.remoting.Channel;
import hudson.tasks.BuildStepDescriptor;
import hudson.tasks.Publisher;
import hudson.util.FormValidation;
import hudson.util.Secret;
import jenkins.model.Jenkins;
import jenkins.security.SlaveToMasterCallable;
import jenkins.util.Timer;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.http.StatusLine;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.logging.Handler;
import java.util.logging.Logger;
import static com.sumologic.jenkins.jenkinssumologicplugin.constants.SumoConstants.DATETIME_FORMATTER;
import static hudson.init.InitMilestone.JOB_LOADED; | package com.sumologic.jenkins.jenkinssumologicplugin;
/**
* Sumo Logic plugin for Jenkins model.
* Provides options to parametrize plugin.
* <p>
* Created by deven on 7/8/15.
* Contributors: lukasz, Sourabh Jain
*/
@Extension
public final class PluginDescriptorImpl extends BuildStepDescriptor<Publisher> {
private Secret url;
private transient SumoMetricDataPublisher sumoMetricDataPublisher;
private static LogSenderHelper logSenderHelper = null;
private String queryPortal;
private String sourceCategory;
private String metricDataPrefix;
private boolean auditLogEnabled;
private boolean keepOldConfigData;
private boolean metricDataEnabled;
private boolean periodicLogEnabled;
private boolean jobStatusLogEnabled;
private boolean jobConsoleLogEnabled;
private boolean scmLogEnabled;
public PluginDescriptorImpl() {
super(SumoBuildNotifier.class);
load();
sumoMetricDataPublisher = new SumoMetricDataPublisher();
if (metricDataEnabled && metricDataPrefix != null) {
getSumoMetricDataPublisher().stopReporter();
getSumoMetricDataPublisher().publishMetricData(metricDataPrefix);
}
if (!metricDataEnabled) {
getSumoMetricDataPublisher().stopReporter();
}
setLogSenderHelper(LogSenderHelper.getInstance());
}
private static void setLogSenderHelper(LogSenderHelper logSenderHelper) {
PluginDescriptorImpl.logSenderHelper = logSenderHelper;
}
public static PluginDescriptorImpl getInstance() {
return (PluginDescriptorImpl) Jenkins.get().getDescriptor(SumoBuildNotifier.class);
}
public static PluginConfiguration getPluginConfiguration() {
Channel channel = Channel.current();
if (channel != null) {
try {
return channel.call(new PluginConfigurationFromMain());
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
PluginDescriptorImpl pluginDescriptor = (PluginDescriptorImpl) Jenkins.get().getDescriptor(SumoBuildNotifier.class);
assert pluginDescriptor != null;
return new PluginConfiguration(pluginDescriptor);
}
@Override
public boolean isApplicable(Class<? extends AbstractProject> aClass) {
return true;
}
@Override
public String getDisplayName() {
return "Sumo Logic build logger";
}
@Override
public boolean configure(StaplerRequest req, JSONObject formData) throws FormException {
boolean configOk = super.configure(req, formData);
url = Secret.fromString(formData.getString("url"));
queryPortal = StringUtils.isNotEmpty(formData.getString("queryPortal")) ? formData.getString("queryPortal") : "service.sumologic.com";
sourceCategory = StringUtils.isNotEmpty(formData.getString("sourceCategory")) ? formData.getString("sourceCategory") : "jenkinsSourceCategory";
metricDataPrefix = StringUtils.isNotEmpty(formData.getString("metricDataPrefix")) ? formData.getString("metricDataPrefix") : "jenkinsMetricDataPrefix";
auditLogEnabled = formData.getBoolean("auditLogEnabled");
metricDataEnabled = formData.getBoolean("metricDataEnabled");
periodicLogEnabled = formData.getBoolean("periodicLogEnabled");
jobStatusLogEnabled = formData.getBoolean("jobStatusLogEnabled");
jobConsoleLogEnabled = formData.getBoolean("jobConsoleLogEnabled");
scmLogEnabled = formData.getBoolean("scmLogEnabled");
keepOldConfigData = formData.getBoolean("keepOldConfigData");
save();
if (metricDataEnabled && metricDataPrefix != null) {
getSumoMetricDataPublisher().stopReporter();
getSumoMetricDataPublisher().publishMetricData(metricDataPrefix);
}
if (!metricDataEnabled) {
getSumoMetricDataPublisher().stopReporter();
}
return configOk;
}
@Terminator(after = TermMilestone.STARTED)
@Restricted(NoExternalUse.class)
public static void shutdown() {
PluginDescriptorImpl pluginDescriptor = checkIfPluginInUse();
pluginDescriptor.getSumoMetricDataPublisher().stopReporter();
| Logger.getLogger("").removeHandler(SumoLogHandler.getInstance()); | 6 |
msokolov/lux | src/test/java/lux/junit/QueryTestCase.java | [
"public class QueryStats {\n /**\n * the number of documents that matched the lucene query. If XPath was executed (there wasn't\n * a short-circuited eval of some sort), this number of XML documents will have been retrieved\n * from the database and processed.\n */\n public int docCount;\n \n /**\n * time spent collecting results (parsing and computing xpath, mostly), in nanoseconds\n */\n public long collectionTime;\n \n /*\n * total time to evaluate the query and produce results, in nanoseconds\n */\n public long totalTime;\n \n /**\n * A description of the work done prior to collection; usu. the Lucene Query generated from the XPath and used to retrieve a set of candidate\n * documents for evaluation.\n */\n public String query;\n \n /**\n * A record of the query's facts. If multiple queries were evaluated, the facts are combined\n * using bitwise AND.\n */\n public long queryFacts;\n \n /**\n * time spent retrieving and parsing documents\n */\n public long retrievalTime;\n\n public String optimizedQuery;\n\n public XQuery optimizedXQuery;\n \n @Override\n public String toString () {\n return String.format(\"%s: %dms %d docs, %dms docread\", \n query == null ? \"\" : query.substring(0, Math.min(20,query.length())),\n totalTime/1000000, docCount, retrievalTime/1000000\n );\n }\n\n}",
"public class SearchExtractor extends ExpressionVisitorBase {\n private ArrayList<MockQuery> queries = new ArrayList<MockQuery>();\n \n public List<MockQuery> getQueries () {\n \treturn queries;\n }\n \n @Override\n public FunCall visit (FunCall funcall) {\n if (funcall.getName().equals (FunCall.LUX_SEARCH)\n || funcall.getName().equals (FunCall.LUX_COUNT) \n || funcall.getName().equals (FunCall.LUX_EXISTS)) \n {\n AbstractExpression queryArg = funcall.getSubs()[0];\n queries.add( new MockQuery (queryArg, funcall.getReturnType()));\n }\n return funcall;\n }\n \n}",
"public abstract class AbstractExpression implements Visitable {\n \n protected AbstractExpression sup; // the enclosing (parent) expression, if any\n protected AbstractExpression subs[]; // enclosed (child) expressions, or a 0-length array, or null (do we need to make this consistent?)\n\n public enum Type {\n PATH_EXPRESSION, PATH_STEP, PREDICATE, BINARY_OPERATION, SET_OPERATION,\n LITERAL, ROOT, DOT, FUNCTION_CALL, SEQUENCE, UNARY_MINUS, SUBSEQUENCE,\n LET, VARIABLE, COMPUTED_ELEMENT, ELEMENT, ATTRIBUTE, TEXT, FLWOR, CONDITIONAL, COMMENT,\n DOCUMENT_CONSTRUCTOR, PROCESSING_INSTRUCTION, SATISFIES, INSTANCE_OF, CASTABLE, TREAT\n }\n\n private final Type type;\n \n protected AbstractExpression (Type type) {\n this.type = type;\n }\n\n /** Most types will correspond one-one\n * with a subclass of AbstractExpression, but this\n * enumerated value provides an integer equivalent that should be\n * useful for efficient switch operations, encoding and the like.\n * TODO: determine if this is just a waste of time; we could be using instanceof?\n * @return the type of this expression\n */\n public Type getType () {\n return type;\n }\n \n public void acceptSubs (ExpressionVisitor visitor) {\n for (int i = 0; i < subs.length && !visitor.isDone(); i++) {\n int j = visitor.isReverse() ? (subs.length-i-1) : i;\n AbstractExpression sub = subs[j].accept (visitor);\n if (sub != subs[j]) {\n subs[j]= sub;\n }\n }\n }\n \n /**\n * @return the super (containing) expression, or null if this is the outermost expression in its tree\n */\n public AbstractExpression getSuper() {\n return sup;\n }\n\n /**\n * @return the sub-expressions of this expression.\n */\n public AbstractExpression [] getSubs() {\n return subs;\n }\n \n protected void setSubs (AbstractExpression ... subExprs) {\n subs = subExprs;\n for (AbstractExpression sub : subs) {\n sub.sup = this;\n }\n }\n\n /** Each subclass must implement the toString(StringBuilder) method by\n * appending itself as a syntatically valid XPath/XQuery expression in\n * the given buffer.\n * @param buf the buffer to append to\n */\n public abstract void toString(StringBuilder buf);\n\n @Override\n public String toString() {\n StringBuilder buf = new StringBuilder();\n toString (buf);\n return buf.toString();\n }\n\n /**\n * @return the root of this expression: this will either be a Root(/), a function returning document nodes, \n * or null.\n */\n public AbstractExpression getRoot () {\n return null; \n }\n \n /**\n * @return whether this expression is a Root or another expression that introduces\n * a new query scope, such as a PathExpression beginning with a Root (/), or a subsequence\n * of another absolute expression. This method returns false, supplying the common default.\n */\n public boolean isAbsolute() {\n return getRoot() != null;\n }\n \n /**\n * @return whether this expression is proven to return results in document order. This method \n * returns true iff all its subs return true, or it has none. Warning: incorrect results may occur if \n * document-ordering is falsely asserted.\n */\n public boolean isDocumentOrdered() {\n if (subs != null) {\n for (AbstractExpression sub : subs) {\n if (!sub.isDocumentOrdered())\n return false;\n }\n }\n return true;\n }\n \n /** \n * If this has absolute subexpressions, replace them with the replacement expression\n * (see {@link Root#replaceRoot(AbstractExpression)}\n * @param replacement the expression to use in place of '/'\n * @return this \n */\n public AbstractExpression replaceRoot(AbstractExpression replacement) {\n if (subs != null) {\n for (int i = 0; i < subs.length; i++) {\n AbstractExpression replaced = subs[i].replaceRoot(replacement);\n if (replaced != subs[i]) {\n subs[i] = replaced;\n }\n }\n }\n return this;\n }\n \n /**\n * append the sub-expression to the buffer, wrapping it in parentheses if its precedence is\n * lower than or equal to this expression's. We need parens when precedence is equal because\n * otherwise operations simply group left or right, but we have the actual grouping encoded \n * in the expression tree and need to preserve that.\n * \n * Note: we can't just blindly wrap everything in parentheses because parens have special meaning\n * in some XPath expressions where they can introduce document-ordering.\n * \n * @param buf the buffer to append to\n * @param sub the sub-expression\n */\n protected void appendSub(StringBuilder buf, AbstractExpression sub) {\n if (sub.getPrecedence() <= getPrecedence()) {\n buf.append ('(');\n sub.toString(buf);\n buf.append (')'); \n } else {\n sub.toString(buf);\n }\n }\n \n /**\n * @return the head of this expression; ie the leftmost path sub-expression, which is just this \n * expression (except for PathExpressions).\n */\n public AbstractExpression getHead() {\n return this;\n }\n \n /**\n * @return the tail of this expression; ie everything after the head is removed, which is null \n * unless this is a PathExpression {@link PathExpression#getTail}.\n */\n public AbstractExpression getTail() {\n return null;\n }\n\n /**\n * This method is called by the optimizer in order to determine an element or attribute QName (or wildcard) against which \n * some expression is being compared, in order to generate an appropriate text query.\n * @return the rightmost path step in the context of this expression.\n */\n public AbstractExpression getLastContextStep () {\n return this;\n }\n \n /**\n * If this expression depends \"directly\" on a variable, return that variable's binding context: a for or let clause,\n * or a global variable definition. This recurses through variables, so if there are aliases it retrieves the ultimate\n * context. We need to define directly dependent precisely; what it's used for is to determine with an order by \n * expression is dependent on a for-variable, and ultimately whether an order by optimization can be applied. \n * @return the binding context of the variable on which this expression depends, or null\n */\n public VariableContext getBindingContext () {\n return null;\n }\n\n /**\n * @return a number indicating the *outer* precedence of this expression.\n * Expressions with lower precedence numbers have lower\n * precedence, ie bind more loosely, than expressions with higher\n * precedence. Expressions with no sub-expressions are assigned a high\n * precedence. Complex expressions can be seen as having an inner and an outer\n * precedence; for example function call expressions behave as a comma with regard \n * to their sub-expressions, the arguments, and like parentheses to their enclosing expression.\n */\n public abstract int getPrecedence ();\n\n /**\n * @param other another expression\n * @return whether the two expressions are of the same type and share the same local properties\n */\n public boolean equivalent (AbstractExpression other) {\n if (other == this) {\n return true;\n }\n if (other == null) {\n return false;\n }\n if (! (getClass().isAssignableFrom(other.getClass()))) {\n return false;\n }\n return propEquals ((AbstractExpression) other);\n }\n\n /**\n * @param other another expression\n * @return whether this expression is query-geq (fgreater-than-or-equal) to the other, in the sense\n * that for all contexts c, exists(other|c) => exists(this|c). In particular, this implementation tests that \n * the two expressions are of the same type and have local properties consistent with geq, by calling\n * propGreaterEqual.\n */\n public boolean geq (AbstractExpression other) {\n if (other == this) {\n return true;\n }\n if (other == null) {\n return false;\n }\n if (! (getClass().isAssignableFrom(other.getClass()))) {\n return false;\n }\n return propGreaterEqual ((AbstractExpression) other);\n }\n \n /**\n \tTraverse downwards, comparing with fromExpr for equivalence until one bottoms out,\n \tignoring fromExpr (since it has already been checked).\n \t@param fromExpr\n \t@param fieldExpr\n \t@return whether fieldExpr >= queryExpr\n */\n public boolean matchDown (AbstractExpression fieldExpr, AbstractExpression fromExpr) {\n \tif (fieldExpr == fromExpr) {\n \t\treturn true;\n \t}\n \tif (! fieldExpr.geq(this)) {\n \t\t// if fieldExpr does not encompass this at least formally, it is too restrictive\n \t\treturn false;\n\t\t}\n\t\t// all of queryExpr's subs *must* return a value (for a\n\t\t// non-empty result), so a necessary condition for fieldExpr\n\t\t// >= queryExpr is that every sub of fieldExpr match *some*\n\t\t// sub of queryExpr\n\t\tAbstractExpression[] fsubs = fieldExpr.getSubs();\n\t\tif (fsubs == null) {\n\t\t\treturn subs == null || subs.length == 0 || isRestrictive();\n\t\t}\n\t\tAbstractExpression qsubMatched = null;\n\t\tOUTER: for (AbstractExpression fsub : fsubs) {\n\t\t\tif (fsub == fromExpr) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tfor (AbstractExpression sub : subs) {\n\t\t\t\tif (sub.matchDown(fsub, null)) {\n\t\t\t\t\tqsubMatched = sub;\n\t\t\t\t\tcontinue OUTER;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// no equivalent sub found\n\t\t\treturn false;\n\t\t}\n\t\tif (!isRestrictive()) {\n\t\t\t// at least one of queryExpr's children must return a value, so\n\t\t\t// in addition it is necessary that every child of queryExpr be\n\t\t\t// matched by some child of fieldExpr\n\t\t\tOUTER: for (AbstractExpression sub : subs) {\n\t\t\t\tif (sub == qsubMatched) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tfor (AbstractExpression fsub : fsubs) {\n\t\t\t\t\tif (sub.matchDown(fsub, null)) {\n\t\t\t\t\t\tcontinue OUTER;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n\n /**\n * @return a hashcode that is consistent with {@link #equivalent(AbstractExpression)}\n */\n int equivHash () {\n return type.ordinal();\n }\n \n /**\n * @param oex another expression\n * @return whether the other expression and this one have all the same local properties\n */\n protected boolean propEquals (AbstractExpression oex) {\n return (oex.getType() == type);\n }\n \n /**\n * @param oex another expression of the same type as this\n * @return whether the expressions' properties imply: <code>this ge oex</code>\n */\n public boolean propGreaterEqual (AbstractExpression oex) {\n return propEquals(oex);\n }\n \n public boolean deepEquals (AbstractExpression oex) {\n \tif (! equivalent(oex)) {\n \t\treturn false;\n \t}\n if (subs == oex.subs) {\n \treturn true;\n }\n if (subs == null || oex.subs == null) {\n \treturn false;\n }\n if (subs.length != oex.subs.length) {\n \treturn false;\n }\n for (int i = 0; i < subs.length; i++) {\n \tif (! (subs[i].deepEquals(oex.subs[i]))) {\n \t\treturn false;\n \t}\n }\n return true;\n }\n\n /**\n * An expression is restrictive when any empty sub implies the expression is empty.\n * In other words, restrictive expressions only return results when all of their \n * subs are non-empty. Eg: and, intersect, predicate, path step.\n * @return whether this expression is restrictive\n */\n public boolean isRestrictive () {\n return false;\n }\n\n}",
"public abstract class ExpressionVisitorBase extends ExpressionVisitor {\n \n /**\n * This method is called by every visit() method in this class. \n * Subclasses may extend this convenience method in order to provide a default behavior for all\n * expressions for which they don't provide an explicit visit() override.\n * @param expr an expression to visit\n * @return the expression\n */\n protected AbstractExpression visitDefault (AbstractExpression expr) {\n return expr;\n }\n \n protected AbstractExpression visitSubs (AbstractExpression expr) {\n for (int i = 0; i < expr.getSubs().length; i++) {\n AbstractExpression sub = expr.getSubs()[i].accept(this);\n if (sub != expr.getSubs()[i]) {\n expr.getSubs()[i] = sub;\n }\n }\n return expr;\n }\n\n @Override\n public AbstractExpression visit(AttributeConstructor attributeConstructor) {\n return visitDefault (attributeConstructor);\n }\n\n @Override\n public AbstractExpression visit(BinaryOperation op) {\n return visitDefault (op);\n }\n \n @Override\n public AbstractExpression visit(CastableExpression cast) {\n return visitDefault(cast);\n }\n \n\n @Override\n public AbstractExpression visit(CommentConstructor comment) {\n return visitDefault (comment);\n }\n \n @Override\n public AbstractExpression visit(ComputedElementConstructor element) {\n return visitDefault (element);\n }\n\n @Override\n public AbstractExpression visit(Conditional cond) {\n return visitDefault (cond);\n }\n \n @Override\n public AbstractExpression visit(DocumentConstructor documentConstructor) {\n return visitDefault (documentConstructor);\n }\n\n @Override\n public AbstractExpression visit(Dot dot) {\n return visitDefault (dot);\n }\n\n @Override\n public AbstractExpression visit(ElementConstructor elementConstructor) {\n return visitDefault (elementConstructor);\n }\n\n @Override\n public AbstractExpression visit(FLWOR flwor) {\n return visitDefault (flwor);\n }\n\n @Override\n public ForClause visit (ForClause forClause) {\n return forClause;\n }\n\n @Override\n public AbstractExpression visit(FunCall func) {\n return visitDefault (func);\n }\n \n @Override\n public AbstractExpression visit(FunctionDefinition func) {\n return visitDefault (func);\n }\n\n @Override\n public AbstractExpression visit(InstanceOf expr) {\n return visitDefault (expr);\n }\n\n @Override\n public AbstractExpression visit(Let let) {\n return visitDefault (let);\n }\n\n @Override\n public LetClause visit (LetClause letClause) {\n return letClause;\n }\n\n @Override\n public AbstractExpression visit(LiteralExpression literal) {\n return visitDefault (literal);\n }\n\n @Override\n public OrderByClause visit (OrderByClause orderByClause) {\n return orderByClause;\n }\n\n @Override\n public AbstractExpression visit(PathExpression path) {\n return visitDefault (path);\n }\n \n @Override\n public AbstractExpression visit(PathStep step) {\n return visitDefault (step);\n }\n\n @Override\n public AbstractExpression visit(Predicate predicate) {\n return visitDefault (predicate);\n }\n \n @Override\n public AbstractExpression visit(ProcessingInstructionConstructor pi) {\n return visitDefault (pi);\n }\n\n @Override\n public AbstractExpression visit(Root root) {\n return visitDefault (root);\n }\n \n @Override\n public AbstractExpression visit(Satisfies satisfies) {\n return visitDefault (satisfies);\n }\n\n @Override\n public AbstractExpression visit(Sequence seq) {\n return visitDefault (seq);\n }\n \n @Override\n public AbstractExpression visit(Subsequence subseq) {\n return visitDefault (subseq);\n }\n \n @Override\n public AbstractExpression visit(TreatAs treat) {\n return visitDefault(treat);\n }\n \n @Override\n public AbstractExpression visit(TextConstructor textConstructor) {\n return visitDefault (textConstructor);\n }\n \n @Override\n public AbstractExpression visit(UnaryMinus unaryMinus) {\n return visitDefault (unaryMinus);\n }\n\n @Override\n public AbstractExpression visit(Variable var) {\n return visitDefault (var);\n }\n\n @Override\n public WhereClause visit (WhereClause whereClause) {\n return whereClause;\n }\n\n}",
"public class FunCall extends AbstractExpression {\n\n public static final String LUX_NAMESPACE = lux.Evaluator.LUX_NAMESPACE;\n \n private final QName name;\n private final ValueType returnType;\n\n public FunCall (QName name, ValueType returnType, AbstractExpression ... arguments) {\n super (Type.FUNCTION_CALL);\n this.name = name;\n setSubs (arguments);\n this.returnType = returnType;\n }\n \n public void setArguments (AbstractExpression ... args) {\n setSubs (args);\n }\n \n @Override\n public void toString(StringBuilder buf) {\n buf.append (name);\n buf.append ('(');\n if (subs.length == 1) {\n buf.append (subs[0]);\n } \n else if (subs.length > 1) {\n subs[0].toString(buf); \n }\n for (int i = 1; i < subs.length; i++) {\n buf.append (',');\n subs[i].toString(buf);\n }\n buf.append (')');\n }\n \n public QName getName() {\n return name;\n }\n \n /**\n * @return 100; the outer precedence.\n */\n @Override public int getPrecedence () {\n return 100;\n }\n\n public static final QName LUX_SEARCH = new QName (LUX_NAMESPACE, \"search\", \"lux\");\n public static final QName LUX_COUNT = new QName (LUX_NAMESPACE, \"count\", \"lux\");\n public static final QName LUX_EXISTS = new QName (LUX_NAMESPACE, \"exists\", \"lux\");\n public static final QName LUX_KEY = new QName (LUX_NAMESPACE, \"key\", \"lux\");\n public static final QName LUX_FIELD_VALUES = new QName (LUX_NAMESPACE, \"field-values\", \"lux\");\n \n public static final String FN_NAMESPACE = \"http://www.w3.org/2005/xpath-functions\";\n public static final QName FN_ROOT = new QName (FN_NAMESPACE, \"root\", \"fn\");\n public static final QName FN_LAST = new QName (FN_NAMESPACE, \"last\", \"fn\");\n public static final QName FN_DATA = new QName (FN_NAMESPACE, \"data\", \"fn\");\n public static final QName FN_UNORDERED = new QName (FN_NAMESPACE, \"unordered\", \"fn\");\n public static final QName FN_SUBSEQUENCE = new QName (FN_NAMESPACE, \"subsequence\", \"fn\");\n public static final QName FN_COUNT = new QName (FN_NAMESPACE, \"count\", \"fn\");\n public static final QName FN_EXISTS = new QName (FN_NAMESPACE, \"exists\", \"fn\");\n public static final QName FN_NOT = new QName (FN_NAMESPACE, \"not\", \"fn\");\n public static final QName FN_EMPTY = new QName (FN_NAMESPACE, \"empty\", \"fn\");\n public static final QName FN_COLLECTION = new QName (FN_NAMESPACE, \"collection\", \"fn\");\n public static final QName FN_STRING_JOIN = new QName (FN_NAMESPACE, \"string-join\", \"fn\");\n public static final QName FN_CONTAINS = new QName(FN_NAMESPACE, \"contains\", \"fn\");\n public static final QName FN_MIN = new QName(FN_NAMESPACE, \"min\", \"fn\");\n public static final QName FN_MAX = new QName(FN_NAMESPACE, \"max\", \"fn\");\n\n public static final String LOCAL_NAMESPACE = \"http://www.w3.org/2005/xquery-local-functions\";\n public static final String XS_NAMESPACE = \"http://www.w3.org/2001/XMLSchema\"; \n \n // represent last() in Subsequence(foo, last()); ie foo[last()].\n public static final FunCall LastExpression = new FunCall (FN_LAST, ValueType.VALUE);\n \n @Override\n public AbstractExpression accept(ExpressionVisitor visitor) {\n super.acceptSubs(visitor);\n return visitor.visit(this);\n }\n\n public ValueType getReturnType() {\n return returnType;\n }\n \n @Override\n public boolean isDocumentOrdered () {\n if (returnType.isAtomic) {\n return false;\n }\n if (name.getNamespaceURI().equals(LUX_NAMESPACE)) {\n if (name.getLocalPart().equals(\"search\")) {\n // if we are returning results ordered by docid, that is document ordered already\n if (getSubs().length > 1) {\n AbstractExpression sortExpr = getSubs()[1];\n if (sortExpr instanceof LiteralExpression) {\n if (((LiteralExpression)sortExpr).getValue().equals (FieldRole.LUX_DOCID)) {\n return true;\n }\n }\n }\n // ordered some other way\n return false;\n }\n }\n if (name.getNamespaceURI().equals(FN_NAMESPACE)) {\n if (name.getLocalPart().equals (\"reverse\") || name.getLocalPart().equals(\"unordered\")) {\n return false;\n }\n if (name.getLocalPart().equals(\"root\")) {\n return false;\n }\n return super.isDocumentOrdered();\n }\n return false;\n }\n\n /**\n * @return for \"transparent\" functions that return their argument, like\n * data() and typecasts, the argument's rightmost subexpression (last\n * context step) is returned. For other functions, the function\n * expression itself is returned.\n */\n @Override\n public AbstractExpression getLastContextStep () {\n if (name.getNamespaceURI().equals(XS_NAMESPACE) ||\n (name.getNamespaceURI().equals(FN_NAMESPACE) && \n name.getLocalPart().equals(\"data\"))) {\n return subs[0].getLastContextStep();\n }\n return this;\n }\n \n @Override\n public AbstractExpression getRoot () {\n if (name.equals(LUX_SEARCH)) {\n return this;\n }\n if (name.equals(FN_UNORDERED) || name.equals(FN_SUBSEQUENCE)) {\n return getSubs()[0].getRoot();\n }\n return null;\n }\n\n @Override\n public boolean propEquals (AbstractExpression other) {\n return name.equals(((FunCall) other).name) &&\n \t\treturnType.equals(((FunCall) other).returnType);\n }\n \n @Override\n public int equivHash () {\n \treturn 43 + returnType.ordinal() + name.hashCode();\n }\n\n @Override\n public boolean isRestrictive () {\n return (name.equals(FunCall.FN_ROOT) || name.equals(FunCall.FN_DATA) || name.equals(FunCall.FN_EXISTS));\n }\n\n}",
"public class LiteralExpression extends AbstractExpression {\n \n private final Object value;\n private final ValueType valueType;\n \n public LiteralExpression (Object value, ValueType valueType) {\n super(Type.LITERAL);\n this.value = value;\n this.valueType = valueType;\n }\n\n public LiteralExpression (Object value) {\n super(Type.LITERAL);\n this.value = value;\n if (value != null) {\n valueType = computeType (value);\n } else {\n valueType = ValueType.VALUE;\n }\n }\n\n public static final LiteralExpression EMPTY = new LiteralExpression (\"()\", ValueType.EMPTY);\n public static final LiteralExpression ONE = new LiteralExpression (1L);\n public static final LiteralExpression TRUE = new LiteralExpression (true);\n \n private static ValueType computeType (Object value) {\n if (value instanceof String) {\n return ValueType.STRING;\n } else if (value instanceof Integer || value instanceof Long) {\n return ValueType.INTEGER;\n } else if (value instanceof Double) {\n return ValueType.DOUBLE;\n } else if (value instanceof Float) {\n return ValueType.FLOAT;\n } else if (value instanceof BigDecimal) {\n return ValueType.DECIMAL;\n } else if (value instanceof Boolean) {\n return ValueType.BOOLEAN;\n } else if (value instanceof QName) {\n \treturn ValueType.QNAME;\n }\n throw new LuxException (\"unsupported java object type: \" + value.getClass().getSimpleName());\n }\n \n /**\n * @return 100\n */\n @Override public int getPrecedence () {\n return 100;\n }\n\n public ValueType getValueType () {\n return valueType;\n }\n\n public Object getValue() {\n return value;\n }\n \n /**\n * renders the literal as parseable XQuery. Note that \n */\n @Override\n public void toString(StringBuilder buf) {\n if (value == null) {\n buf.append (\"()\");\n return;\n }\n switch (valueType) {\n case UNTYPED_ATOMIC:\n buf.append (\"xs:untypedAtomic(\");\n quoteString (value.toString(), buf);\n buf.append (')');\n break;\n \n case STRING:\n quoteString (value.toString(), buf);\n break;\n \n case BOOLEAN:\n buf.append (\"fn:\").append(value).append(\"()\");\n break;\n \n case FLOAT:\n Float f = (Float) value;\n if (f.isInfinite()) {\n if (f > 0)\n buf.append (\"xs:float('INF')\");\n else\n buf.append (\"xs:float('-INF')\");\n }\n else if (f.isNaN()) {\n buf.append (\"xs:float('NaN')\");\n }\n else {\n buf.append (\"xs:float(\").append(f).append(')');\n }\n break;\n \n case DOUBLE:\n Double d = (Double) value;\n if (d.isInfinite()) {\n if (d > 0)\n buf.append (\"xs:double('INF')\");\n else\n buf.append (\"xs:double('-INF')\");\n }\n else if (d.isNaN()) {\n buf.append (\"xs:double('NaN')\");\n }\n else {\n buf.append (\"xs:double(\").append(d).append(')');\n }\n break;\n\n case DECIMAL: \n buf.append(\"xs:decimal(\").append (((BigDecimal)value).toPlainString()).append(\")\");\n break;\n \n case HEX_BINARY:\n buf.append(\"xs:hexBinary(\\\"\");\n appendHex(buf, (byte[])value);\n buf.append(\"\\\")\");\n break;\n \n case BASE64_BINARY:\n buf.append(\"xs:base64Binary(\\\"\");\n buf.append(DatatypeConverter.printBase64Binary((byte[])value));\n buf.append(\"\\\")\");\n break;\n \n case DATE:\n case DATE_TIME:\n case TIME:\n case DAY:\n case MONTH:\n case MONTH_DAY:\n case YEAR:\n case YEAR_MONTH:\n case DAY_TIME_DURATION:\n case YEAR_MONTH_DURATION:\n buf.append(valueType.name).append(\"(\\\"\").append(value).append(\"\\\")\");\n break;\n \n case QNAME:\n buf.append(\"fn:QName(\");\n quoteString(((QName)value).getNamespaceURI(), buf);\n buf.append (\",\\\"\");\n ((QName)value).toString(buf);\n buf.append(\"\\\")\");\n break;\n \n case INT:\n buf.append(valueType.name).append(\"(\").append(value).append(\")\");\n break;\n \n case ATOMIC:\n default:\n // rely on the object's toString method - is it only xs:int and its ilk that do this?\n buf.append (value);\n }\n }\n\n private static char hexdigits[] = new char[] { '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F' };\n\n private void appendHex(StringBuilder buf, byte[] bytes) {\n for (byte b : bytes) {\n int b1 = ((b & 0xF0) >> 4);\n buf.append (hexdigits[b1]);\n int b2 = b & 0xF;\n buf.append (hexdigits[b2]);\n }\n }\n \n /**\n * Append the string to the buffer, with characters escaped appropriately for XML (and XQuery) text.\n * The characters \", &, <, >, {, }, and \\r are replaced with character entities or numeric character references.\n * @param s the appended string\n * @param buf the buffer appended to\n */\n public static void escapeText (String s, StringBuilder buf) {\n for (char c : s.toCharArray()) {\n switch (c) {\n case '{' : buf.append(\"{\"); break;\n case '}' : buf.append(\"}\"); break;\n //case '\"': buf.append (\"\\\"\\\"\"); break;\n case '>': buf.append (\">\"); break;\n case '<': buf.append (\"<\"); break;\n case '\"': buf.append (\""\"); break;\n case '&': buf.append (\"&\"); break;\n case '\\r': buf.append(\"
\"); break; // XML line ending normalization removes these unless they come in as character references\n default: buf.append (c);\n }\n } \n }\n \n /**\n * Append the string to the buffer, escaped as in {@link #escapeText(String, StringBuilder)}, surrounded\n * by double quotes (\").\n * @param s the appended string\n * @param buf the buffer appended to\n */\n public static void quoteString(String s, StringBuilder buf) {\n buf.append ('\"');\n escapeText (s, buf);\n buf.append ('\"');\n }\n\n @Override\n public AbstractExpression accept(ExpressionVisitor visitor) {\n return visitor.visit(this);\n }\n \n @Override \n public boolean propEquals (AbstractExpression other) {\n \treturn value.equals(((LiteralExpression)other).value) &&\n \t\t\tvalueType.equals(((LiteralExpression)other).valueType);\n }\n \n @Override\n public int equivHash () {\n return value.hashCode() + valueType.ordinal();\n }\n}"
] | import static org.junit.Assert.*;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import lux.Compiler;
import lux.Evaluator;
import lux.QueryStats;
import lux.XdmResultSet;
import lux.exception.LuxException;
import lux.support.SearchExtractor;
import lux.xpath.AbstractExpression;
import lux.xpath.ExpressionVisitorBase;
import lux.xpath.FunCall;
import lux.xpath.LiteralExpression;
import lux.xquery.XQuery;
import net.sf.saxon.expr.XPathContext;
import net.sf.saxon.expr.sort.CodepointCollator;
import net.sf.saxon.expr.sort.GenericAtomicComparer;
import net.sf.saxon.functions.DeepEqual;
import net.sf.saxon.s9api.Axis;
import net.sf.saxon.s9api.XdmNode;
import net.sf.saxon.trans.XPathException;
import org.apache.commons.lang.StringUtils;
import org.junit.Ignore; | package lux.junit;
@Ignore
class QueryTestCase {
private final String name;
private final String query;
private final QueryTestResult expectedResult;
QueryTestCase (String name, String query, QueryTestResult expected) {
this.name = name;
this.query = query;
this.expectedResult = expected;
}
public XdmResultSet evaluate (Evaluator eval) {
Compiler compiler = eval.getCompiler(); | QueryStats stats = new QueryStats(); | 0 |
Spade-Editor/Spade | src/heroesgrave/spade/image/change/doc/NewLayer.java | [
"public class Document\n{\n\tpublic static int MAX_DIMENSION = 4096;\n\t\n\tprivate LinkedList<IDocChange> changes = new LinkedList<IDocChange>();\n\tprivate LinkedList<IDocChange> reverted = new LinkedList<IDocChange>();\n\t\n\tprivate int width, height;\n\tprivate File file;\n\tprivate Metadata info;\n\tprivate Layer root, current;\n\tprivate History history;\n\t\n\tprivate IChange previewChange;\n\tpublic int lowestChange;\n\t\n\tprivate boolean initialised;\n\tpublic boolean repaint;\n\t\n\tprivate ArrayList<Layer> flatmap = new ArrayList<Layer>();\n\t\n\tprivate Document()\n\t{\n\t\tthis.info = new Metadata();\n\t\tthis.history = new History(this);\n\t}\n\t\n\tpublic Document(int width, int height)\n\t{\n\t\tthis();\n\t\tthis.width = width;\n\t\tthis.height = height;\n\t\t\n\t\tthis.current = this.root = new Layer(this, new RawImage(width, height), new Metadata());\n\t\tthis.flatmap.clear();\n\t\troot.constructFlatMap(flatmap);\n\t\tinitialised = true;\n\t}\n\t\n\tpublic static Document loadFromFile(File f)\n\t{\n\t\tDocument doc = new Document();\n\t\tdoc.file = f;\n\t\tif(!ImageImporter.loadImage(f.getAbsolutePath(), doc))\n\t\t\treturn null;\n\t\tdoc.flatmap.clear();\n\t\tdoc.root.constructFlatMap(doc.flatmap);\n\t\tdoc.initialised = true;\n\t\treturn doc;\n\t}\n\t\n\tpublic void reconstructFlatmap()\n\t{\n\t\tif(!initialised)\n\t\t\treturn;\n\t\tSpade.main.gui.layers.redrawTree();\n\t\tthis.flatmap.clear();\n\t\troot.constructFlatMap(flatmap);\n\t}\n\t\n\tpublic History getHistory()\n\t{\n\t\treturn history;\n\t}\n\t\n\tpublic Layer getRoot()\n\t{\n\t\treturn root;\n\t}\n\t\n\tpublic Layer getCurrent()\n\t{\n\t\treturn current;\n\t}\n\t\n\tpublic void setRoot(Layer root)\n\t{\n\t\tthis.current = this.root = root;\n\t\tthis.reconstructFlatmap();\n\t}\n\t\n\tpublic boolean setCurrent(Layer current)\n\t{\n\t\tif(this.current == current)\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t\tthis.current = current;\n\t\tSpade.main.gui.layers.select(current);\n\t\treturn true;\n\t}\n\t\n\tpublic Metadata getMetadata()\n\t{\n\t\treturn info;\n\t}\n\t\n\tpublic void resize(int width, int height)\n\t{\n\t\tthis.width = width;\n\t\tthis.height = height;\n\t\tthis.allChanged();\n\t\tSpade.main.gui.canvas.resized(width, height);\n\t}\n\t\n\tpublic void save()\n\t{\n\t\tsave(false);\n\t}\n\t\n\tpublic void save(boolean panic)\n\t{\n\t\tfinal String fileName = this.file.getAbsolutePath();\n\t\t\n\t\tString extension = \"\";\n\t\t\n\t\tint i = fileName.lastIndexOf('.');\n\t\t\n\t\tif(i > 0)\n\t\t{\n\t\t\textension = fileName.substring(i + 1);\n\t\t}\n\t\t\n\t\tfinal ImageExporter exporter = ImageExporter.get(extension);\n\t\t\n\t\tfinal Document doc = this;\n\t\t\n\t\ttry\n\t\t{\n\t\t\texporter.save(doc, new File(fileName));\n\t\t\thistory.save();\n\t\t\tSpade.main.gui.checkButtonNames();\n\t\t}\n\t\tcatch(Exception e)\n\t\t{\n\t\t\tif(!panic)\n\t\t\t\tPopup.showException(\"Error Saving Document\", e, \"This error occured while saving the file \" + file\n\t\t\t\t\t\t+ \". It may work if you try again, but if not, we apologise. Report the bug to get it fixed as soon as possible\");\n\t\t\telse\n\t\t\t\tPopup.showException(\"Error Saving Document\", e, \"This error occured while saving the file \" + file\n\t\t\t\t\t\t+ \" after a crash. Sadly, we cannot recover from this.\");\n\t\t\treturn;\n\t\t}\n\t}\n\t\n\tpublic String getDir()\n\t{\n\t\tif(file != null)\n\t\t\treturn this.file.getParent();\n\t\telse\n\t\t\treturn System.getProperty(\"user.dir\");\n\t}\n\t\n\tpublic int getWidth()\n\t{\n\t\treturn width;\n\t}\n\t\n\tpublic int getHeight()\n\t{\n\t\treturn height;\n\t}\n\t\n\tpublic ArrayList<Layer> getFlatMap()\n\t{\n\t\treturn flatmap;\n\t}\n\t\n\t/*\n\t * This should only be called when loading an image. I need to find another way to do this.\n\t */\n\tpublic void setDimensions(int width, int height)\n\t{\n\t\tthis.width = width;\n\t\tthis.height = height;\n\t}\n\t\n\tpublic BufferedImage getRenderedImage()\n\t{\n\t\tBufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);\n\t\t{\n\t\t\tGraphics2D g = image.createGraphics();\n\t\t\tfor(Layer l : flatmap)\n\t\t\t{\n\t\t\t\tl.render(g);\n\t\t\t}\n\t\t\tg.dispose();\n\t\t}\n\t\treturn image;\n\t}\n\t\n\tpublic void preview(IChange change)\n\t{\n\t\tthis.previewChange = change;\n\t\tthis.repaint();\n\t}\n\t\n\tpublic void applyPreview()\n\t{\n\t\tthis.getCurrent().addChange(previewChange);\n\t\tthis.previewChange = null;\n\t\tthis.repaint();\n\t}\n\t\n\tpublic void changed(Layer layer)\n\t{\n\t\tif(!initialised)\n\t\t\treturn;\n\t\tSpade.main.gui.checkButtonNames();\n\t\tlowestChange = Math.min(lowestChange, flatmap.indexOf(layer));\n\t\tthis.repaint();\n\t}\n\t\n\tpublic void allChanged()\n\t{\n\t\tlowestChange = 0;\n\t\tthis.repaint();\n\t}\n\t\n\tpublic IChange getPreview()\n\t{\n\t\treturn previewChange;\n\t}\n\t\n\tpublic void setFile(File file)\n\t{\n\t\tthis.file = file;\n\t}\n\t\n\tpublic File getFile()\n\t{\n\t\treturn file;\n\t}\n\t\n\tpublic void addChange(IDocChange change)\n\t{\n\t\thistory.addChange(-1);\n\t\tchanges.push(change);\n\t\tchange.apply(this);\n\t\tthis.allChanged();\n\t}\n\t\n\tpublic void addChangeSilent(IDocChange change)\n\t{\n\t\tchanges.push(change);\n\t\tchange.apply(this);\n\t\tthis.allChanged();\n\t}\n\t\n\tpublic void revertChange()\n\t{\n\t\tif(changes.isEmpty())\n\t\t{\n\t\t\treturn;\n\t\t}\n\t\tIDocChange change = changes.pop();\n\t\treverted.push(change);\n\t\tchange.revert(this);\n\t\tthis.allChanged();\n\t}\n\t\n\tpublic void repeatChange()\n\t{\n\t\tif(reverted.isEmpty())\n\t\t{\n\t\t\treturn;\n\t\t}\n\t\tIDocChange change = reverted.pop();\n\t\tchanges.push(change);\n\t\tchange.repeat(this);\n\t\tthis.allChanged();\n\t}\n\t\n\tpublic boolean saved()\n\t{\n\t\treturn this.file != null && this.history.isSaved();\n\t}\n\t\n\tpublic void repaint()\n\t{\n\t\trepaint = true;\n\t\tSpade.main.gui.repaint();\n\t}\n\t\n\tpublic void setMetadata(Metadata info)\n\t{\n\t\tthis.info = info;\n\t}\n}",
"@SuppressWarnings(\"serial\")\npublic class Layer extends DefaultMutableTreeNode\n{\n\tprivate Document doc;\n\tprivate FreezeBuffer buffer;\n\tprivate Metadata info;\n\tprivate BlendMode blend;\n\tprivate boolean floating, visible;\n\t\n\tpublic Layer(Document doc, Metadata info)\n\t{\n\t\tthis(doc, new RawImage(doc.getWidth(), doc.getHeight()), info);\n\t}\n\t\n\tpublic Layer(Document doc, RawImage image, Metadata info)\n\t{\n\t\tsuper(info.getOrSet(\"name\", \"New Layer\"));\n\t\tthis.doc = doc;\n\t\tthis.buffer = new FreezeBuffer(image);\n\t\tthis.info = info;\n\t\tthis.blend = BlendMode.getBlendMode(info.getOrSet(\"blend\", \"Normal\"));\n\t}\n\t\n\tpublic void updateMetadata()\n\t{\n\t\tBlendMode newMode = BlendMode.getBlendMode(info.get(\"blend\"));\n\t\tif(newMode != blend)\n\t\t{\n\t\t\tblend = newMode;\n\t\t\tdoc.repaint = true;\n\t\t}\n\t\tString newName = info.get(\"name\");\n\t\tif(!newName.equals(this.getUserObject()))\n\t\t{\n\t\t\tthis.setUserObject(newName);\n\t\t\tSpade.main.gui.layers.redrawTree();\n\t\t}\n\t}\n\t\n\tpublic Layer getParentLayer()\n\t{\n\t\treturn (Layer) super.getParent();\n\t}\n\t\n\tpublic void setVisible(boolean visible)\n\t{\n\t\tthis.visible = visible;\n\t}\n\t\n\tpublic void addLayer(Layer l)\n\t{\n\t\tsuper.add(l);\n\t\tdoc.reconstructFlatmap();\n\t\tdoc.changed(this);\n\t}\n\t\n\tpublic void addLayer(Layer l, int index)\n\t{\n\t\tsuper.insert(l, index);\n\t\tdoc.reconstructFlatmap();\n\t\tdoc.changed(this);\n\t}\n\t\n\tpublic int removeLayer(Layer l)\n\t{\n\t\tint index = super.getIndex(l);\n\t\tsuper.remove(l);\n\t\tdoc.reconstructFlatmap();\n\t\tdoc.changed(this);\n\t\treturn index;\n\t}\n\t\n\tpublic int getWidth()\n\t{\n\t\treturn doc.getWidth();\n\t}\n\t\n\tpublic int getHeight()\n\t{\n\t\treturn doc.getHeight();\n\t}\n\t\n\tpublic Metadata getMetadata()\n\t{\n\t\treturn info;\n\t}\n\t\n\tpublic void render(Graphics2D g)\n\t{\n\t\tif(!visible)\n\t\t\treturn;\n\t\tg.setComposite(blend);\n\t\tg.drawImage(this.buffer.getFront(), 0, 0, null);\n\t}\n\t\n\tpublic void constructFlatMap(ArrayList<Layer> flatmap)\n\t{\n\t\tflatmap.add(this);\n\t\t\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tEnumeration<Layer> children = this.children();\n\t\twhile(children.hasMoreElements())\n\t\t{\n\t\t\t((Layer) children.nextElement()).constructFlatMap(flatmap);\n\t\t}\n\t}\n\t\n\tpublic void addChange(IChange change)\n\t{\n\t\tdoc.getHistory().addChange(doc.getFlatMap().indexOf(this));\n\t\tbuffer.addChange(change);\n\t\tdoc.changed(this);\n\t\tif(change instanceof IMaskChange)\n\t\t{\n\t\t\tSpade.main.gui.canvas.maskChanged();\n\t\t}\n\t}\n\t\n\tpublic Document getDocument()\n\t{\n\t\treturn doc;\n\t}\n\t\n\tpublic void revertChange()\n\t{\n\t\tif(buffer.revertChange() instanceof IMaskChange)\n\t\t{\n\t\t\tSpade.main.gui.canvas.maskChanged();\n\t\t}\n\t\tdoc.changed(this);\n\t}\n\t\n\tpublic void repeatChange()\n\t{\n\t\tif(buffer.repeatChange() instanceof IMaskChange)\n\t\t{\n\t\t\tSpade.main.gui.canvas.maskChanged();\n\t\t}\n\t\tdoc.changed(this);\n\t}\n\t\n\tpublic void addChangeSilent(IChange change)\n\t{\n\t\tbuffer.addChange(change);\n\t\tdoc.changed(this);\n\t\tif(change instanceof IMaskChange)\n\t\t{\n\t\t\tSpade.main.gui.canvas.maskChanged();\n\t\t}\n\t}\n\t\n\tpublic BlendMode getBlendMode()\n\t{\n\t\treturn blend;\n\t}\n\t\n\tpublic RawImage getImage()\n\t{\n\t\treturn buffer.getImage();\n\t}\n\t\n\tpublic BufferedImage getBufferedImage()\n\t{\n\t\treturn buffer.getFront();\n\t}\n\t\n\tpublic Layer floating()\n\t{\n\t\tthis.floating = true;\n\t\treturn this;\n\t}\n\t\n\tpublic boolean isFloating()\n\t{\n\t\treturn this.floating;\n\t}\n}",
"public final class RawImage\n{\n\tprivate static int[] TMP;\n\t\n\tpublic static enum MaskMode\n\t{\n\t\tREP, ADD, SUB, XOR, AND;\n\t\t\n\t\tpublic boolean transform(boolean bool)\n\t\t{\n\t\t\tswitch(this)\n\t\t\t{\n\t\t\t\tcase REP:\n\t\t\t\tcase ADD:\n\t\t\t\t\treturn true;\n\t\t\t\tcase SUB:\n\t\t\t\t\treturn false;\n\t\t\t\tcase XOR:\n\t\t\t\t\treturn !bool;\n\t\t\t\tcase AND:\n\t\t\t\t\treturn bool;\n\t\t\t}\n\t\t\tthrow new IllegalStateException(\"Unreachable\");\n\t\t}\n\t}\n\t\n\tprivate int[] buffer;\n\tpublic final int width, height;\n\t\n\tprivate boolean[] mask;\n\t\n\tpublic RawImage(int width, int height)\n\t{\n\t\tthis.width = width;\n\t\tthis.height = height;\n\t\tthis.buffer = new int[width * height];\n\t}\n\t\n\tpublic RawImage(int width, int height, int[] buffer)\n\t{\n\t\tthis.width = width;\n\t\tthis.height = height;\n\t\tif(buffer.length != width * height)\n\t\t\tthrow new IllegalArgumentException(\"Buffer length must be `width*height`\");\n\t\tthis.buffer = buffer;\n\t}\n\t\n\tpublic RawImage(int width, int height, int[] buffer, boolean[] mask)\n\t{\n\t\tthis.width = width;\n\t\tthis.height = height;\n\t\tif(buffer.length != width * height || buffer.length != mask.length)\n\t\t\tthrow new IllegalArgumentException(\"Buffer length must be `width*height`\");\n\t\tthis.buffer = buffer;\n\t\tthis.mask = mask;\n\t}\n\t\n\t// Returns or allocates a temporary buffer with a size of at least width*height.\n\tprivate static int[] get_tmp(int width, int height)\n\t{\n\t\tif(TMP == null || TMP.length < width * height)\n\t\t{\n\t\t\tTMP = new int[width * height];\n\t\t}\n\t\treturn TMP;\n\t}\n\t\n\tpublic void move(int dx, int dy)\n\t{\n\t\tfinal int offset = dx + dy * width;\n\t\tif(Math.abs(dx) >= width || Math.abs(dy) >= height)\n\t\t{\n\t\t\tthis.fill(0); // Fill, not clear, so the mask is respected.\n\t\t\treturn;\n\t\t}\n\t\telse if(offset == 0)\n\t\t\treturn;\n\t\t\n\t\tint[] tmp = get_tmp(width, height);\n\t\t\n\t\tint src = 0;\n\t\tint dst = offset;\n\t\tif(offset < 0)\n\t\t{\n\t\t\tsrc = -offset;\n\t\t\tdst = 0;\n\t\t}\n\t\tfinal int len = buffer.length - (src + dst);\n\t\t\n\t\t// Copy whole buffer to tmp.\n\t\tSystem.arraycopy(buffer, 0, tmp, 0, buffer.length);\n\t\t\n\t\t// Copy back from tmp\n\t\tif(mask == null)\n\t\t{\n\t\t\t// Do x-axis bounds clipping.\n\t\t\tif(dx < 0)\n\t\t\t{\n\t\t\t\tfor(int y = 0; y < height; y++)\n\t\t\t\t{\n\t\t\t\t\tArrays.fill(tmp, y * width, y * width - dx, 0);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(dx > 0)\n\t\t\t{\n\t\t\t\tfor(int y = 1; y <= height; y++)\n\t\t\t\t{\n\t\t\t\t\tArrays.fill(tmp, y * width - dx, y * width, 0);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\t// Do the actual copying.\n\t\t\tSystem.arraycopy(tmp, src, buffer, dst, len);\n\t\t\t\n\t\t\t// Do y-axis bounds clipping.\n\t\t\tArrays.fill(buffer, 0, dst, 0); // Cut out top.\n\t\t\tArrays.fill(buffer, buffer.length - src, buffer.length, 0); // Cut out bottom\n\t\t}\n\t\telse\n\t\t{\n\t\t\tthis.fill(0); // Clear the old pixels. Only necessary when mask is enabled.\n\t\t\t\n\t\t\t// First translate the mask.\n\t\t\tSystem.arraycopy(mask, src, mask, dst, len);\n\t\t\t// Then do bounds clipping.\n\t\t\tArrays.fill(mask, 0, dst, false); // Cut out top.\n\t\t\tArrays.fill(mask, buffer.length - src, buffer.length, false); // Cut out bottom\n\t\t\tif(dx < 0) // Cut out whatever side.\n\t\t\t{\n\t\t\t\tfor(int y = 1; y <= height; y++)\n\t\t\t\t{\n\t\t\t\t\tArrays.fill(mask, y * width + dx, y * width, false);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse if(dx > 0)\n\t\t\t{\n\t\t\t\tfor(int y = 0; y < height; y++)\n\t\t\t\t{\n\t\t\t\t\tArrays.fill(mask, y * width, y * width + dx, false);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\t// Now we can copy the data back, if it's not masked out.\n\t\t\tfor(int i = 0; i < len; i++)\n\t\t\t{\n\t\t\t\tif(mask[dst + i])\n\t\t\t\t\tbuffer[dst + i] = tmp[src + i];\n\t\t\t}\n\t\t}\n\t}\n\t\n\t// Drawing functions\n\t\n\tpublic void drawLine(int x1, int y1, final int x2, final int y2, final int c)\n\t{\n\t\tfinal int dx = Math.abs(x2 - x1);\n\t\tfinal int dy = Math.abs(y2 - y1);\n\t\tfinal int sx = (x1 < x2) ? 1 : -1;\n\t\tfinal int sy = (y1 < y2) ? 1 : -1;\n\t\tint err = dx - dy;\n\t\tdo\n\t\t{\n\t\t\tdrawPixelChecked(x1, y1, c);\n\t\t\tfinal int e2 = 2 * err;\n\t\t\tif(e2 > -dy)\n\t\t\t{\n\t\t\t\terr = err - dy;\n\t\t\t\tx1 = x1 + sx;\n\t\t\t}\n\t\t\tif(e2 < dx)\n\t\t\t{\n\t\t\t\terr = err + dx;\n\t\t\t\ty1 = y1 + sy;\n\t\t\t}\n\t\t}\n\t\twhile(!(x1 == x2 && y1 == y2));\n\t\tdrawPixelChecked(x2, y2, c);\n\t}\n\t\n\tpublic void drawRect(int x1, int y1, int x2, int y2, final int c)\n\t{\n\t\t// Do the clamping once at the start so we don't have to perform checks when drawing the pixel.\n\t\tx1 = MathUtils.clamp(x1, 0, width - 1);\n\t\tx2 = MathUtils.clamp(x2, 0, width - 1);\n\t\ty1 = MathUtils.clamp(y1, 0, height - 1);\n\t\ty2 = MathUtils.clamp(y2, 0, height - 1);\n\t\t\n\t\tif(mask == null)\n\t\t{\n\t\t\t// top\n\t\t\tfinal int ix = y1 * width;\n\t\t\tArrays.fill(buffer, ix + x1, ix + x2 + 1, c);\n\t\t\t\n\t\t\t// bottom\n\t\t\tfinal int jx = y2 * width;\n\t\t\tArrays.fill(buffer, jx + x1, jx + x2 + 1, c);\n\t\t\t\n\t\t\tfor(int i = y1 + 1; i < y2; i++)\n\t\t\t{\n\t\t\t\tsetPixel(x1, i, c);\n\t\t\t\tsetPixel(x2, i, c);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// top\n\t\t\tfinal int ix = y1 * width;\n\t\t\tfor(int k = ix + x1; k < ix + x2 + 1; k++)\n\t\t\t{\n\t\t\t\tif(mask[k])\n\t\t\t\t\tbuffer[k] = c;\n\t\t\t}\n\t\t\t\n\t\t\t// bottom\n\t\t\tfinal int jx = y2 * width;\n\t\t\tfor(int k = jx + x1; k < jx + x2 + 1; k++)\n\t\t\t{\n\t\t\t\tif(mask[k])\n\t\t\t\t\tbuffer[k] = c;\n\t\t\t}\n\t\t\t\n\t\t\tfor(int i = y1 + 1; i < y2; i++)\n\t\t\t{\n\t\t\t\tdrawPixel(x1, i, c);\n\t\t\t\tdrawPixel(x2, i, c);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic void fillRect(int x1, int y1, int x2, int y2, int c)\n\t{\n\t\tx1 = MathUtils.clamp(x1, 0, width - 1);\n\t\tx2 = MathUtils.clamp(x2, 0, width - 1);\n\t\ty1 = MathUtils.clamp(y1, 0, height - 1);\n\t\ty2 = MathUtils.clamp(y2, 0, height - 1);\n\t\t\n\t\tif(mask == null)\n\t\t{\n\t\t\tfor(; y1 <= y2; y1++)\n\t\t\t{\n\t\t\t\tfinal int k = y1 * width;\n\t\t\t\tArrays.fill(buffer, k + x1, k + x2 + 1, c);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tfor(; y1 <= y2; y1++)\n\t\t\t{\n\t\t\t\tfinal int offset = y1 * width;\n\t\t\t\tfor(int k = offset + x1; k < offset + x2 + 1; k++)\n\t\t\t\t{\n\t\t\t\t\tif(mask[k])\n\t\t\t\t\t\tbuffer[k] = c;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic void drawPixel(int x, int y, int c)\n\t{\n\t\tfinal int loc = index(x, y);\n\t\tif(mask == null || mask[loc])\n\t\t{\n\t\t\tbuffer[loc] = c;\n\t\t}\n\t}\n\t\n\tpublic void drawPixelChecked(int x, int y, int c)\n\t{\n\t\tif(x < 0 || y < 0 || x >= width || y >= height)\n\t\t\treturn;\n\t\tfinal int loc = index(x, y);\n\t\tif(mask == null || mask[loc])\n\t\t{\n\t\t\tbuffer[loc] = c;\n\t\t}\n\t}\n\t\n\tpublic void fill(int c)\n\t{\n\t\tif(mask == null)\n\t\t{\n\t\t\tthis.clear(c);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tfor(int i = 0; i < buffer.length; i++)\n\t\t\t{\n\t\t\t\tif(mask[i])\n\t\t\t\t\tbuffer[i] = c;\n\t\t\t}\n\t\t}\n\t}\n\t\n\t// Mask Manipulation\n\t\n\tpublic void fillMask(MaskMode mode)\n\t{\n\t\tif(this.mask == null)\n\t\t\treturn;\n\t\tswitch(mode)\n\t\t{\n\t\t\tcase REP:\n\t\t\tcase ADD:\n\t\t\t\tArrays.fill(mask, true);\n\t\t\t\tbreak;\n\t\t\tcase SUB:\n\t\t\t\tArrays.fill(mask, false);\n\t\t\t\tbreak;\n\t\t\tcase XOR:\n\t\t\t\tfor(int i = 0; i < mask.length; i++)\n\t\t\t\t\tmask[i] = !mask[i];\n\t\t\t\tbreak;\n\t\t\tcase AND:\n\t\t\t\tbreak;\n\t\t}\n\t}\n\t\n\tpublic void maskRect(int x1, int y1, int x2, int y2, MaskMode mode)\n\t{\n\t\tx1 = MathUtils.clamp(x1, 0, width - 1);\n\t\tx2 = MathUtils.clamp(x2, 0, width - 1);\n\t\ty1 = MathUtils.clamp(y1, 0, height - 1);\n\t\ty2 = MathUtils.clamp(y2, 0, height - 1);\n\t\t\n\t\tswitch(mode)\n\t\t{\n\t\t\tcase REP:\n\t\t\t\tthis.fillMask(MaskMode.SUB);\n\t\t\tcase ADD:\n\t\t\t\tfor(; y1 <= y2; y1++)\n\t\t\t\t{\n\t\t\t\t\tfinal int k = y1 * width;\n\t\t\t\t\tArrays.fill(mask, k + x1, k + x2 + 1, true);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase SUB:\n\t\t\t\tfor(; y1 <= y2; y1++)\n\t\t\t\t{\n\t\t\t\t\tfinal int k = y1 * width;\n\t\t\t\t\tArrays.fill(mask, k + x1, k + x2 + 1, false);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase XOR:\n\t\t\t\tfor(; y1 <= y2; y1++)\n\t\t\t\t{\n\t\t\t\t\tfinal int offset = y1 * width;\n\t\t\t\t\tfor(int k = offset + x1; k < offset + x2 + 1; k++)\n\t\t\t\t\t{\n\t\t\t\t\t\tmask[k] = !mask[k];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase AND:\n\t\t\t\t// Before Rectangle\n\t\t\t\tfinal int offset = y1 * width + x1;\n\t\t\t\tArrays.fill(mask, 0, offset, false);\n\t\t\t\t\n\t\t\t\t// After Rectangle\n\t\t\t\tfinal int offset2 = y2 * width + x2 + 1;\n\t\t\t\tArrays.fill(mask, offset2, mask.length, false);\n\t\t\t\t\n\t\t\t\t// Within Rectangle\n\t\t\t\tfinal int onstep = x2 - x1 + 1;\n\t\t\t\tfinal int offstep = width - onstep;\n\t\t\t\t\n\t\t\t\tfor(int i = offset + onstep; i < offset2; i += width)\n\t\t\t\t\tArrays.fill(mask, i, i + offstep, false);\n\t\t\t\tbreak;\n\t\t}\n\t}\n\t\n\tpublic void setMaskEnabled(boolean enabled)\n\t{\n\t\tif(enabled)\n\t\t{\n\t\t\tif(mask == null)\n\t\t\t\tmask = new boolean[buffer.length];\n\t\t}\n\t\telse if(mask != null)\n\t\t{\n\t\t\tmask = null;\n\t\t}\n\t}\n\t\n\tpublic void toggleMask()\n\t{\n\t\tif(mask == null)\n\t\t{\n\t\t\tmask = new boolean[buffer.length];\n\t\t}\n\t\telse\n\t\t{\n\t\t\tmask = null;\n\t\t}\n\t}\n\t\n\tpublic boolean[] copyMask()\n\t{\n\t\treturn mask == null ? null : Arrays.copyOf(mask, mask.length);\n\t}\n\t\n\tpublic boolean[] borrowMask()\n\t{\n\t\treturn mask;\n\t}\n\t\n\tpublic void setMask(boolean[] mask)\n\t{\n\t\tthis.mask = mask;\n\t}\n\t\n\t// Buffer Manipulation\n\t\n\tpublic void clear(int c)\n\t{\n\t\tArrays.fill(buffer, c);\n\t}\n\t\n\tpublic void setPixel(int x, int y, int c)\n\t{\n\t\tbuffer[index(x, y)] = c;\n\t}\n\t\n\tpublic int getPixel(int x, int y)\n\t{\n\t\treturn buffer[index(x, y)];\n\t}\n\t\n\tpublic int getIndex(int x, int y)\n\t{\n\t\treturn index(x, y);\n\t}\n\t\n\tprivate int index(int x, int y)\n\t{\n\t\treturn y * width + x;\n\t}\n\t\n\tpublic int[] copyBuffer()\n\t{\n\t\treturn Arrays.copyOf(buffer, buffer.length);\n\t}\n\t\n\tpublic int[] borrowBuffer()\n\t{\n\t\treturn buffer;\n\t}\n\t\n\tpublic void setBuffer(int[] buffer)\n\t{\n\t\tthis.buffer = buffer;\n\t}\n\t\n\t// Create a RawImage which has direct access to the pixels of the BufferedImage.\n\t// This could be quite unreliable.\n\tpublic static RawImage unwrapBufferedImage(BufferedImage image)\n\t{\n\t\treturn new RawImage(image.getWidth(), image.getHeight(), ((DataBufferInt) image.getRaster().getDataBuffer()).getData());\n\t}\n\t\n\tpublic static RawImage fromBufferedImage(BufferedImage image)\n\t{\n\t\treturn new RawImage(image.getWidth(), image.getHeight(), image.getRGB(0, 0, image.getWidth(), image.getHeight(), null, 0, image.getWidth()));\n\t}\n\t\n\tpublic BufferedImage toBufferedImage()\n\t{\n\t\tBufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);\n\t\timage.setRGB(0, 0, width, height, buffer, 0, width);\n\t\treturn image;\n\t}\n\t\n\tpublic static RawImage copyOf(RawImage image)\n\t{\n\t\tif(image.mask == null)\n\t\t\treturn new RawImage(image.width, image.height, image.copyBuffer());\n\t\treturn new RawImage(image.width, image.height, image.copyBuffer(), image.copyMask());\n\t}\n\t\n\tpublic void copyRegion(RawImage image)\n\t{\n\t\tif(image == this)\n\t\t\treturn;\n\t\tif(this.buffer.length != image.buffer.length)\n\t\t\tthrow new RuntimeException(\"Cannot copy from a different sized RawImage\");\n\t\t\n\t\tif(this.mask == null)\n\t\t{\n\t\t\tSystem.arraycopy(image.buffer, 0, buffer, 0, buffer.length);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tfor(int i = 0; i < buffer.length; i++)\n\t\t\t{\n\t\t\t\tif(mask[i])\n\t\t\t\t\tthis.buffer[i] = image.buffer[i];\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic void copyFrom(RawImage image, boolean withMask)\n\t{\n\t\tif(image == this)\n\t\t\treturn;\n\t\tif(this.buffer.length != image.buffer.length)\n\t\t\tthrow new RuntimeException(\"Cannot copy from a different sized RawImage\");\n\t\tSystem.arraycopy(image.buffer, 0, buffer, 0, buffer.length);\n\t\tif(withMask)\n\t\t{\n\t\t\tif(image.mask == null)\n\t\t\t\tthis.mask = null;\n\t\t\telse if(this.mask == null)\n\t\t\t\tthis.mask = Arrays.copyOf(image.mask, image.mask.length);\n\t\t\telse\n\t\t\t\tSystem.arraycopy(image.mask, 0, mask, 0, mask.length);\n\t\t}\n\t}\n\t\n\tpublic void copyMaskFrom(RawImage image)\n\t{\n\t\tif(image == this)\n\t\t\treturn;\n\t\t\n\t\tif(image.mask == null)\n\t\t\tthis.mask = null;\n\t\telse if(this.mask == null)\n\t\t\tthis.mask = Arrays.copyOf(image.mask, image.mask.length);\n\t\telse if(this.mask.length != image.mask.length)\n\t\t\tthrow new RuntimeException(\"Cannot copy from a different sized RawImage\");\n\t\telse\n\t\t\tSystem.arraycopy(image.mask, 0, mask, 0, mask.length);\n\t}\n\t\n\tpublic void dispose()\n\t{\n\t\tbuffer = null;\n\t\tmask = null;\n\t}\n\t\n\tpublic boolean isMaskEnabled()\n\t{\n\t\treturn mask != null;\n\t}\n}",
"public interface IDocChange\n{\n\tpublic void apply(Document doc);\n\t\n\tpublic void revert(Document doc);\n\t\n\tpublic void repeat(Document doc);\n}",
"public class ClearMaskChange implements IEditChange, IMaskChange, Serialised\n{\n\tpublic ClearMaskChange()\n\t{\n\t\t\n\t}\n\t\n\t@Override\n\tpublic void apply(RawImage image)\n\t{\n\t\timage.setMaskEnabled(false);\n\t}\n\t\n\t@Override\n\tpublic ClearMaskChange encode()\n\t{\n\t\treturn this;\n\t}\n\t\n\t@Override\n\tpublic ClearMaskChange decode()\n\t{\n\t\treturn this;\n\t}\n\t\n\t@Override\n\tpublic void write(DataOutputStream out) throws IOException\n\t{\n\t}\n\t\n\t@Override\n\tpublic void read(DataInputStream in) throws IOException\n\t{\n\t}\n}",
"public class Spade\n{\n\tpublic static final String REPO_URL = \"https://github.com/Spade-Editor/Spade\";\n\t\n\t// Major.Minor + optional letter for releases. The letter is for tiny revisions, such as fixing bugs that slipped through.\n\t// Major.Minor-RC.# for Release Candidates (builds that may be promoted to releases).\n\t// Major.Minor-Beta for beta builds.\n\t// Major.Minor-Alpha for alpha builds.\n\t// Major.Minor-Dev for development builds.\n\t// Eg: 1.3b is the 2nd revision of version 1.3\n\t\n\t// Stable for stable post-1.0 versions\n\t// Beta for new completed features.\n\t// Development for under-development new features.\n\t\n\tpublic static final String VERSION_STRING = \"0.17.0-dev\";\n\tpublic static final Version VERSION = Version.parse(VERSION_STRING);\n\tpublic static final String RELEASED = \"13-03-2015\";\n\t\n\t/* Add/Remove the stars on the following lines to change the build type string.\n\t//*/public static final String BUILD_TYPE = \"Development\";\n\t//*/public static final String BUILD_TYPE = \"Alpha\"; // I don't know if we'll ever use alphas.\n\t//*/public static final String BUILD_TYPE = \"Beta\";\n\t//*/public static final String BUILD_TYPE = \"Release Candidate\";\n\t//*/public static final String BUILD_TYPE = \"Stable\";\n\t\n\tpublic static boolean debug, localPlugins = true, globalPlugins = true;\n\tpublic static Spade main = new Spade();\n\tpublic static URL questionMarkURL = Spade.class.getResource(\"/res/icons/questionmark.png\");\n\t\n\tpublic GUIManager gui;\n\tpublic PluginManager pluginManager;\n\t\n\tprivate Document document;\n\t\n\tpublic Tool currentTool;\n\t\n\tpublic Tools tools;\n\tpublic Effects effects;\n\t\n\tpublic static int leftColour = 0xff000000;\n\tpublic static int rightColour = 0xffffffff;\n\t\n\tprivate static HashMap<Character, Tool> toolMap = new HashMap<Character, Tool>();\n\t\n\tprivate static HashMap<Character, Effect> effectMap = new HashMap<Character, Effect>();\n\t\n\tpublic void launch(final ArrayList<File> toOpen) throws InvocationTargetException, InterruptedException\n\t{\n\t\tpluginManager = PluginManager.instance;\n\t\t\n\t\tHistoryIO.init();\n\t\t\n\t\t// Order is important. Prefer local (./spade) plugins to global (~/.spade/plugins).\n\t\tif(localPlugins)\n\t\t\tpluginManager.addPluginDirectory(new File(IOUtils.assemblePath(IOUtils.jarDir(), \"plugins\")));\n\t\tif(globalPlugins)\n\t\t\tpluginManager.addPluginDirectory(new File(IOUtils.assemblePath(System.getProperty(\"user.home\"), \".spade\", \"plugins\")));\n\t\tpluginManager.loadPluginFiles();\n\t\t\n\t\ttools = new Tools();\n\t\teffects = new Effects();\n\t\t\n\t\tSwingUtilities.invokeAndWait(new Runnable()\n\t\t{\n\t\t\t@Override\n\t\t\tpublic void run()\n\t\t\t{\n\t\t\t\t// Try to catch everything and recover enough to save.\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tgui = new GUIManager();\n\t\t\t\t\tgui.init();\n\t\t\t\t\t\n\t\t\t\t\tsetLeftColour(0xff000000, false);\n\t\t\t\t\tsetRightColour(0xffffffff, false);\n\t\t\t\t\t\n\t\t\t\t\ttools.init();\n\t\t\t\t\teffects.init(); // Doesn't actually do anything\n\t\t\t\t\tpluginManager.loadPlugins();\n\t\t\t\t\tsetTool(currentTool);\n\t\t\t\t\tfor(File f : toOpen)\n\t\t\t\t\t{\n\t\t\t\t\t\tif(debug)\n\t\t\t\t\t\t\tSystem.out.println(\"Opening File \" + f.getPath());\n\t\t\t\t\t\tDocument d = Document.loadFromFile(f);\n\t\t\t\t\t\tif(d != null)\n\t\t\t\t\t\t\tSpade.addDocument(d);\n\t\t\t\t\t}\n\t\t\t\t\tArrayList<Document> documents = gui.getDocuments();\n\t\t\t\t\tif(!documents.isEmpty())\n\t\t\t\t\t\tSpade.setDocument(documents.get(0));\n\t\t\t\t\t\n\t\t\t\t\tgui.frame.requestFocus();\n\t\t\t\t}\n\t\t\t\tcatch(Exception e)\n\t\t\t\t{\n\t\t\t\t\tpanic(e);\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n\t\n\tpublic static void newImage(final int width, final int height)\n\t{\n\t\tDocument doc = new Document(width, height);\n\t\tSpade.addDocument(doc);\n\t\tSpade.setDocument(doc);\n\t}\n\t\n\tpublic static void addTool(Character key, Tool tool)\n\t{\n\t\ttoolMap.put(Character.toLowerCase(key), tool);\n\t}\n\t\n\tpublic static Tool getTool(Character key)\n\t{\n\t\treturn toolMap.get(Character.toLowerCase(key));\n\t}\n\t\n\tpublic static void addEffect(Character key, Effect op)\n\t{\n\t\teffectMap.put(Character.toLowerCase(key), op);\n\t}\n\t\n\tpublic static Effect getEffect(Character key)\n\t{\n\t\treturn effectMap.get(Character.toLowerCase(key));\n\t}\n\t\n\tpublic static boolean setTool(Tool tool)\n\t{\n\t\tif(main.currentTool == tool)\n\t\t\treturn false;\n\t\tInput.CTRL = false;\n\t\tInput.ALT = false;\n\t\tInput.SHIFT = false;\n\t\tmain.currentTool = tool;\n\t\tmain.tools.toolbox.setSelected(tool);\n\t\treturn true;\n\t}\n\t\n\tpublic static boolean save(Document doc)\n\t{\n\t\tif(doc == null)\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t\tif(doc.getFile() != null)\n\t\t{\n\t\t\tdoc.save();\n\t\t\treturn true;\n\t\t}\n\t\telse\n\t\t\treturn saveAs(doc);\n\t}\n\t\n\tpublic static boolean saveAs(Document doc)\n\t{\n\t\tif(doc == null)\n\t\t{\n\t\t\treturn false;\n\t\t}\n\t\tWebFileChooser chooser = new WebFileChooser(doc.getDir());\n\t\tchooser.setFileSelectionMode(WebFileChooser.FILES_ONLY);\n\t\tchooser.setAcceptAllFileFilterUsed(false);\n\t\t\n\t\tImageExporter.addAllExporters(chooser);\n\t\t\n\t\tFileFilter allFilter = new FileFilter()\n\t\t{\n\t\t\t@Override\n\t\t\tpublic boolean accept(File f)\n\t\t\t{\n\t\t\t\tif(f.isDirectory())\n\t\t\t\t\treturn true;\n\t\t\t\tString fileName = f.getAbsolutePath();\n\t\t\t\tint i = fileName.lastIndexOf('.');\n\t\t\t\tif(i < 0)\n\t\t\t\t\treturn false;\n\t\t\t\t\n\t\t\t\treturn ImageExporter.get(fileName.substring(i + 1)) != null;\n\t\t\t}\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic String getDescription()\n\t\t\t{\n\t\t\t\treturn \"All supported import formats\";\n\t\t\t}\n\t\t};\n\t\tchooser.setFileFilter(allFilter);\n\t\t\n\t\tint returned = chooser.showSaveDialog(new WebDialog(main.gui.frame, \"Save Image\"));\n\t\t\n\t\tif(returned == WebFileChooser.APPROVE_OPTION)\n\t\t{\n\t\t\t// FIXME: The filechooser doesn't seem to change the filter to the one the user selected.\n\t\t\t// It always seems to fall through to the else branch.\n\t\t\tif(chooser.getFileFilter() instanceof ImageExporter)\n\t\t\t{\n\t\t\t\tImageExporter format = (ImageExporter) chooser.getFileFilter();\n\t\t\t\tFile file = chooser.getSelectedFile();\n\t\t\t\t\n\t\t\t\tString fileName = file.getAbsolutePath();\n\t\t\t\t\n\t\t\t\tif(fileName.endsWith(\".\" + format.getFileExtension()))\n\t\t\t\t{\n\t\t\t\t\t// Do nothing.\n\t\t\t\t\tdoc.setFile(file);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\t// Put the format at the end of the File-Name!\n\t\t\t\t\tfileName += \".\" + format.getFileExtension();\n\t\t\t\t\tdoc.setFile(new File(fileName));\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tFile file = chooser.getSelectedFile();\n\t\t\t\tif(!allFilter.accept(file))\n\t\t\t\t{\n\t\t\t\t\tfile = new File(file.getAbsolutePath() + \".png\");\n\t\t\t\t}\n\t\t\t\tdoc.setFile(file);\n\t\t\t}\n\t\t\t\n\t\t\tif(doc == main.document)\n\t\t\t\tmain.gui.setTitle(doc.getFile().getName());\n\t\t\tdoc.save();\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tpublic void setLeftColour(int c, boolean checked)\n\t{\n\t\tif(!checked)\n\t\t{\n\t\t\tgui.chooser.setColour(c, this, true);\n\t\t}\n\t\tSpade.leftColour = c;\n\t}\n\t\n\tpublic int getLeftColour()\n\t{\n\t\treturn Spade.leftColour;\n\t}\n\t\n\tpublic void setRightColour(int c, boolean checked)\n\t{\n\t\tif(!checked)\n\t\t{\n\t\t\tgui.chooser.setColour(c, this, false);\n\t\t}\n\t\tSpade.rightColour = c;\n\t}\n\t\n\tpublic int getRightColour()\n\t{\n\t\treturn Spade.rightColour;\n\t}\n\t\n\t/**\n\t * @param mouseButton The mouse-button to get the color for.\n\t * @return The color assigned to the given MouseButton.\n\t */\n\tpublic int getColor(int mouseButton)\n\t{\n\t\t// BUTTON1 (LEFT): left\n\t\t// BUTTON2 (MIDDLE): Color.BLACK\n\t\t// BUTTON3 (RIGHT): right\n\t\treturn mouseButton == MouseEvent.BUTTON1 ? Spade.leftColour : (mouseButton == MouseEvent.BUTTON3 ? Spade.rightColour : 0xFF000000);\n\t}\n\t\n\tpublic static void launchWithPlugins(String[] args, Plugin... plugins)\n\t{\n\t\tfor(Plugin p : plugins)\n\t\t{\n\t\t\tif(p.getInfo() == null)\n\t\t\t{\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\tBufferedReader in = new BufferedReader(new InputStreamReader(p.getClass().getResourceAsStream(\"/plugin.info\")));\n\t\t\t\t\tp.setInfo(PluginManager.loadPluginInfo(in));\n\t\t\t\t}\n\t\t\t\tcatch(IOException e)\n\t\t\t\t{\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\t\t\t}\n\t\t\tp.getInfo().set(\"location\", \"Class: \" + p.getClass().getCanonicalName());\n\t\t\tPluginManager.instance.registerPlugin(p);\n\t\t}\n\t\tlaunch(args);\n\t}\n\t\n\tpublic static void launch(String[] args)\n\t{\n\t\tIOUtils.setMainClass(Spade.class);\n\t\t\n\t\tArrayList<File> open = new ArrayList<File>();\n\t\t\n\t\tSystem.setProperty(\"DlafClassName\", \"\");\n\t\t\n\t\tStringBuilder argsDebug = new StringBuilder();\n\t\t\n\t\t// Go through ALL the arguments and...\n\t\tfor(String arg : args)\n\t\t{\n\t\t\targsDebug.append(\"Picked up argument: \" + arg + \"\\n\");\n\t\t\t\n\t\t\tif(arg.equals(\"-v\"))\n\t\t\t{\n\t\t\t\t// Print version string and exit.\n\t\t\t\tSystem.out.println(VERSION);\n\t\t\t\tSystem.exit(0);\n\t\t\t}\n\t\t\telse if(arg.equals(\"--version\"))\n\t\t\t{\n\t\t\t\t// Print detailed version info and exit.\n\t\t\t\tSystem.out.println(\"Spade v\" + VERSION);\n\t\t\t\tSystem.out.println(\"Version Released: \" + RELEASED);\n\t\t\t\tSystem.out.println(\"Built Type: \" + BUILD_TYPE);\n\t\t\t\tSystem.exit(0);\n\t\t\t}\n\t\t\telse if(arg.equals(\"--print-jar-path\"))\n\t\t\t{\n\t\t\t\t// Print the absolute path of the jar and exit.\n\t\t\t\tSystem.out.println(IOUtils.jarPath());\n\t\t\t\tSystem.exit(0);\n\t\t\t}\n\t\t\telse if(arg.equals(\"--show-memory-watcher\"))\n\t\t\t{\n\t\t\t\t// ...If the arguments contain the DmemoryWatcherFlag flag, set the property to true to enable the MemoryWatcher.\n\t\t\t\tSystem.setProperty(\"DmemoryWatcherFlag\", \"true\");\n\t\t\t}\n\t\t\telse if(arg.startsWith(\"--look-and-feel=\"))\n\t\t\t{\n\t\t\t\tSystem.setProperty(\"DlafClassName\", arg.substring(16));\n\t\t\t}\n\t\t\telse if(arg.equals(\"--debug\"))\n\t\t\t{\n\t\t\t\tdebug = true;\n\t\t\t}\n\t\t\telse if(arg.equals(\"--no-global-plugins\"))\n\t\t\t{\n\t\t\t\tglobalPlugins = false;\n\t\t\t}\n\t\t\telse if(arg.equals(\"--no-local-plugins\"))\n\t\t\t{\n\t\t\t\tlocalPlugins = false;\n\t\t\t}\n\t\t\telse if(arg.equals(\"--help\"))\n\t\t\t{\n\t\t\t\tSystem.out.println(\"Spade v\" + VERSION);\n\t\t\t\tSystem.out.println(\"Version Released: \" + RELEASED);\n\t\t\t\tSystem.out.println(\"Built Type: \" + BUILD_TYPE);\n\t\t\t\tSystem.out.println();\n\t\t\t\tSystem.out.println(\"Copyright 2013-2014 HeroesGrave and Other Spade Developers\");\n\t\t\t\tSystem.out.println();\n\t\t\t\tSystem.out.println(\"For more info, to report issues, make suggestions, or contribute\");\n\t\t\t\tSystem.out.println(\"please visit \" + REPO_URL);\n\t\t\t\tSystem.out.println();\n\t\t\t\tSystem.out.println(\"Command-Line Options:\");\n\t\t\t\tSystem.out.println();\n\t\t\t\tSystem.out.println(\" Information:\");\n\t\t\t\tSystem.out.println(\" --help: Print this text and exit\");\n\t\t\t\tSystem.out.println(\" -v Print the raw version id and exit\");\n\t\t\t\tSystem.out.println(\" --version Print more detailed version info and exit\");\n\t\t\t\tSystem.out.println();\n\t\t\t\tSystem.out.println(\" Plugin Settings:\");\n\t\t\t\tSystem.out.println(\" --no-local-plugins Disable Local Plugins (./plugins/)\");\n\t\t\t\tSystem.out.println(\" --no-global-plugins Disable Global Plugins (~/.spade/.plugins/)\");\n\t\t\t\tSystem.out.println();\n\t\t\t\tSystem.out.println(\" UI Settings:\");\n\t\t\t\tSystem.out.println(\" --look-and-feel=[LAF] Specify the 'Look And Feel' to use\");\n\t\t\t\tSystem.out.println(\" --show-memory-watcher Enable the memory usage watcher\");\n\t\t\t\tSystem.out.println();\n\t\t\t\tSystem.out.println(\" Debug Switches:\");\n\t\t\t\tSystem.out.println(\" --debug Enable debugging messages\");\n\t\t\t\tSystem.out.println(\" --debug-timings Print rendering times\");\n\t\t\t\tSystem.out.println();\n\t\t\t\tSystem.out.println(\"Any other arguments will be read as files to open on startup.\");\n\t\t\t\tSystem.exit(0);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tFile f = new File(arg);\n\t\t\t\t\n\t\t\t\tif(f.exists() && f.isFile() && !f.isHidden())\n\t\t\t\t{\n\t\t\t\t\topen.add(f);\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\t/// XXX: Expand here by adding more debugging options and system flags!\n\t\t}\n\t\t\n\t\tif(debug)\n\t\t\tSystem.out.println(argsDebug);\n\t\t\n\t\t// Try to catch all exceptions and recover enough to save\n\t\ttry\n\t\t{\n\t\t\t// Finally Launch Spade!\n\t\t\tmain.launch(open);\n\t\t}\n\t\tcatch(Exception e)\n\t\t{\n\t\t\tpanic(e);\n\t\t}\n\t}\n\t\n\tpublic static Version getVersion()\n\t{\n\t\treturn VERSION;\n\t}\n\t\n\tpublic static void addDocument(Document doc)\n\t{\n\t\tmain.gui.addDocument(doc);\n\t}\n\t\n\tpublic static void setDocument(Document doc)\n\t{\n\t\tmain.document = doc;\n\t\tmain.gui.setDocument(main.document);\n\t}\n\t\n\tpublic static Document getDocument()\n\t{\n\t\treturn main.document;\n\t}\n\t\n\tpublic static void closeAllDocuments()\n\t{\n\t\tSpade.closeDocument(Spade.getDocument(), new Callback()\n\t\t{\n\t\t\t@Override\n\t\t\tpublic void callback()\n\t\t\t{\n\t\t\t\tSpade.closeAllDocuments();\n\t\t\t}\n\t\t});\n\t}\n\t\n\tpublic static void closeDocument(Document doc)\n\t{\n\t\tcloseDocument(doc, new Callback()\n\t\t{\n\t\t\t@Override\n\t\t\tpublic void callback()\n\t\t\t{\n\t\t\t}\n\t\t});\n\t}\n\t\n\tpublic static void closeDocument(final Document doc, final Callback callback)\n\t{\n\t\tif(main.gui.getDocuments().isEmpty())\n\t\t{\n\t\t\tSpade.close();\n\t\t}\n\t\tfinal int index = main.gui.getDocuments().indexOf(doc);\n\t\tmain.gui.tryRemove(doc, new Callback()\n\t\t{\n\t\t\t@Override\n\t\t\tpublic void callback()\n\t\t\t{\n\t\t\t\tArrayList<Document> documents = main.gui.getDocuments();\n\t\t\t\tif(main.gui.getDocuments().isEmpty())\n\t\t\t\t{\n\t\t\t\t\tsetDocument(null);\n\t\t\t\t}\n\t\t\t\tif(doc == main.document)\n\t\t\t\t{\n\t\t\t\t\tif(index == 0)\n\t\t\t\t\t\tsetDocument(documents.get(0));\n\t\t\t\t\telse\n\t\t\t\t\t\tsetDocument(documents.get(index - 1));\n\t\t\t\t}\n\t\t\t\tcallback.callback();\n\t\t\t}\n\t\t});\n\t}\n\t\n\tpublic static void close()\n\t{\n\t\tUserPreferences.savePrefs(main.gui.frame, main.gui.chooser, main.gui.layers);\n\t\tmain.pluginManager.dispose();\n\t\tmain.gui.frame.dispose();\n\t\tSystem.exit(0);\n\t}\n\t\n\tpublic static String getDir()\n\t{\n\t\tif(main.document != null)\n\t\t\treturn main.document.getDir();\n\t\treturn System.getProperty(\"user.dir\");\n\t}\n\t\n\tpublic static void panic(Exception e)\n\t{\n\t\ttry {\n\t\t\tArrayList<Document> documents = main.gui.getDocuments();\n\t\t\tfor(Document doc : documents)\n\t\t\t{\n\t\t\t\tFile f = doc.getFile();\n\t\t\t\tif(f == null)\n\t\t\t\t\tcontinue;\n\t\t\t\tString name = \"~\" + f.getName() + \".bck\";\n\t\t\t\tint i = 0;\n\t\t\t\twhile(f.exists())\n\t\t\t\t{\n\t\t\t\t\tf = new File(f.getParentFile(), name + \".\" + i++);\n\t\t\t\t}\n\t\t\t\tdoc.setFile(f);\n\t\t\t\tdoc.save(true);\n\t\t\t}\n\t\t\tmain.pluginManager.dispose();\n\t\t\tmain.gui.frame.dispose();\n\t\t}\n\t\tcatch(Exception e2)\n\t\t{\n\t\t\te2.printStackTrace();\n\t\t\tSystem.err.println(\"Exception encountered while handling an exception!\\nYou will not go to space today.\\nOriginal Error:\");\n\t\t\te.printStackTrace();\n\t\t\tSystem.exit(-1);\n\t\t}\n\t\tPopup.showException(\"Spade has crashed\", e, \"\");\n\t\tSystem.exit(-1);\n\t}\n}",
"public class Metadata\n{\n\tprivate HashMap<String, String> metadata = new HashMap<String, String>();\n\t\n\tpublic String set(String key, String value)\n\t{\n\t\treturn metadata.put(key, value);\n\t}\n\t\n\tpublic String remove(String key)\n\t{\n\t\treturn metadata.remove(key);\n\t}\n\t\n\tpublic String get(String key)\n\t{\n\t\treturn metadata.get(key);\n\t}\n\t\n\tpublic String getOr(String key, String def)\n\t{\n\t\tString ret = metadata.get(key);\n\t\treturn ret != null ? ret : def;\n\t}\n\t\n\tpublic String getOrSet(String key, String def)\n\t{\n\t\tString ret = metadata.get(key);\n\t\tif(ret == null)\n\t\t{\n\t\t\tthis.set(key, def);\n\t\t\treturn def;\n\t\t}\n\t\treturn ret;\n\t}\n\t\n\tpublic boolean has(String key)\n\t{\n\t\treturn metadata.containsKey(key);\n\t}\n\t\n\tpublic int size()\n\t{\n\t\treturn metadata.size();\n\t}\n\t\n\tpublic Set<Entry<String, String>> getEntries()\n\t{\n\t\treturn metadata.entrySet();\n\t}\n}"
] | import heroesgrave.spade.image.Document;
import heroesgrave.spade.image.Layer;
import heroesgrave.spade.image.RawImage;
import heroesgrave.spade.image.change.IDocChange;
import heroesgrave.spade.image.change.edit.ClearMaskChange;
import heroesgrave.spade.main.Spade;
import heroesgrave.utils.misc.Metadata; | // {LICENSE}
/*
* Copyright 2013-2015 HeroesGrave and other Spade developers.
*
* This file is part of Spade
*
* Spade 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 heroesgrave.spade.image.change.doc;
public class NewLayer implements IDocChange
{
private Layer layer, parent;
private int index = -1;
private RawImage image;
private String name;
private boolean floating;
public NewLayer(Layer parent)
{
this(parent, prepareImage(parent));
}
private static RawImage prepareImage(Layer parent)
{
RawImage image = new RawImage(parent.getWidth(), parent.getHeight());
image.copyMaskFrom(parent.getImage());
return image;
}
public NewLayer(Layer parent, RawImage image)
{
this(parent, image, "New Layer");
}
public NewLayer(Layer parent, RawImage image, String name)
{
this.parent = parent;
this.image = image;
this.name = name;
}
public NewLayer floating()
{
this.floating = true;
return this;
}
| public void apply(Document doc) | 0 |
EndlessCodeGroup/RPGInventory | src/main/java/ru/endlesscode/rpginventory/pet/CooldownTimer.java | [
"public class RPGInventory extends PluginLifecycle {\n private static RPGInventory instance;\n\n private Permission perms;\n private Economy economy;\n\n private BukkitLevelSystem.Provider levelSystemProvider;\n private BukkitClassSystem.Provider classSystemProvider;\n\n private FileLanguage language;\n private boolean placeholderApiHooked = false;\n private boolean myPetHooked = false;\n private ResourcePackModule resourcePackModule = null;\n\n public static RPGInventory getInstance() {\n return instance;\n }\n\n public static FileLanguage getLanguage() {\n return instance.language;\n }\n\n public static Permission getPermissions() {\n return instance.perms;\n }\n\n public static Economy getEconomy() {\n return instance.economy;\n }\n\n @Contract(pure = true)\n public static boolean economyConnected() {\n return instance.economy != null;\n }\n\n @Contract(pure = true)\n public static boolean isPlaceholderApiHooked() {\n return instance.placeholderApiHooked;\n }\n\n @Contract(pure = true)\n public static boolean isMyPetHooked() {\n return instance.myPetHooked;\n }\n\n public static BukkitLevelSystem getLevelSystem(@NotNull Player player) {\n return instance.levelSystemProvider.getSystem(player);\n }\n\n public static BukkitClassSystem getClassSystem(@NotNull Player player) {\n return instance.classSystemProvider.getSystem(player);\n }\n\n @Nullable\n public static ResourcePackModule getResourcePackModule() {\n return instance.resourcePackModule;\n }\n\n @Override\n public void init() {\n instance = this;\n Log.init(this.getLogger());\n Config.init(this);\n }\n\n @Override\n public void onLoad() {\n if (checkMimic()) {\n getServer()\n .getServicesManager()\n .register(BukkitItemsRegistry.class, new RPGInventoryItemsRegistry(), this, ServicePriority.High);\n }\n }\n\n @Override\n public void onEnable() {\n if (!initMimicSystems()) {\n return;\n }\n\n loadConfigs();\n Serialization.registerTypes();\n\n if (!this.checkRequirements()) {\n this.getPluginLoader().disablePlugin(this);\n return;\n }\n\n PluginManager pm = this.getServer().getPluginManager();\n\n // Hook Placeholder API\n if (pm.isPluginEnabled(\"PlaceholderAPI\")) {\n new StringUtils.Placeholders().register();\n placeholderApiHooked = true;\n Log.i(\"Placeholder API hooked!\");\n } else {\n placeholderApiHooked = false;\n }\n\n loadModules();\n\n this.loadPlayers();\n this.startMetrics();\n\n // Enable commands\n this.getCommand(\"rpginventory\")\n .setExecutor(new TrackedCommandExecutor(new RPGInventoryCommandExecutor(), getReporter()));\n\n this.checkUpdates(null);\n }\n\n private boolean initMimicSystems() {\n boolean isMimicFound = checkMimic();\n if (isMimicFound) {\n ServicesManager servicesManager = getServer().getServicesManager();\n this.levelSystemProvider = servicesManager.load(BukkitLevelSystem.Provider.class);\n Log.i(\"Level system ''{0}'' found.\", this.levelSystemProvider.getId());\n this.classSystemProvider = servicesManager.load(BukkitClassSystem.Provider.class);\n Log.i(\"Class system ''{0}'' found.\", this.classSystemProvider.getId());\n } else {\n Log.s(\"Mimic is required for RPGInventory to use levels and classes from other RPG plugins!\");\n Log.s(\"Download it from SpigotMC: https://www.spigotmc.org/resources/82515/\");\n getServer().getPluginManager().disablePlugin(this);\n }\n return isMimicFound;\n }\n\n void reload() {\n // Unload\n saveData();\n removeListeners();\n\n // Load\n loadConfigs();\n loadModules();\n loadPlayers();\n }\n\n private void loadConfigs() {\n this.updateConfig();\n Config.reload();\n language = new FileLanguage(this);\n }\n\n private void loadModules() {\n PluginManager pm = getServer().getPluginManager();\n\n // Hook MyPet\n if (pm.isPluginEnabled(\"MyPet\") && MyPetManager.init(this)) {\n myPetHooked = true;\n Log.i(\"MyPet used as pet system\");\n } else {\n myPetHooked = false;\n Log.i(PetManager.init(this) ? \"Pet system is enabled\" : \"Pet system isn''t loaded\");\n }\n\n // Load modules\n Log.i(CraftManager.init(this) ? \"Craft extensions is enabled\" : \"Craft extensions isn''t loaded\");\n Log.i(InventoryLocker.init(this) ? \"Inventory lock system is enabled\" : \"Inventory lock system isn''t loaded\");\n Log.i(ItemManager.init(this) ? \"Item system is enabled\" : \"Item system isn''t loaded\");\n Log.i(BackpackManager.init(this) ? \"Backpack system is enabled\" : \"Backpack system isn''t loaded\");\n\n // Registering other listeners\n pm.registerEvents(new ArmorEquipListener(), this);\n pm.registerEvents(new HandSwapListener(), this);\n pm.registerEvents(new PlayerListener(), this);\n pm.registerEvents(new WorldListener(), this);\n\n if (SlotManager.instance().getElytraSlot() != null) {\n pm.registerEvents(new ElytraListener(), this);\n }\n this.resourcePackModule = ResourcePackModule.init(this);\n }\n\n private void removeListeners() {\n ProtocolLibrary.getProtocolManager().removePacketListeners(this);\n HandlerList.unregisterAll(this);\n }\n\n private boolean checkMimic() {\n if (getServer().getPluginManager().getPlugin(\"Mimic\") == null) {\n return false;\n } else if (MimicApiLevel.checkApiLevel(MimicApiLevel.VERSION_0_6)) {\n return true;\n } else {\n Log.w(\"At least Mimic 0.6.1 required for RPGInventory.\");\n return false;\n }\n }\n\n private boolean checkRequirements() {\n // Check if plugin is enabled\n if (!Config.getConfig().getBoolean(\"enabled\")) {\n Log.w(\"RPGInventory is disabled in the config!\");\n return false;\n }\n\n // Check version compatibility\n if (VersionHandler.isNotSupportedVersion()) {\n Log.w(\"This version of RPG Inventory is not tested with \\\"{0}\\\"!\", Bukkit.getBukkitVersion());\n } else if (VersionHandler.isExperimentalSupport()) {\n Log.w(\"Support of {0} is experimental! Use RPGInventory with caution.\", Bukkit.getBukkitVersion());\n }\n\n // Check dependencies\n if (this.setupPermissions()) {\n Log.i(\"Permissions hooked: {0}\", perms.getName());\n } else {\n Log.s(\"Permissions not found!\");\n return false;\n }\n\n if (this.setupEconomy()) {\n Log.i(\"Economy hooked: {0}\", economy.getName());\n } else {\n Log.w(\"Economy not found!\");\n }\n\n return InventoryManager.init(this) && SlotManager.init();\n }\n\n @Override\n public void onDisable() {\n saveData();\n }\n\n private void saveData() {\n BackpackManager.saveBackpacks();\n this.savePlayers();\n }\n\n private void startMetrics() {\n new Metrics(holder, 4210);\n }\n\n private void savePlayers() {\n if (this.getServer().getOnlinePlayers().size() == 0) {\n return;\n }\n\n Log.i(\"Saving players inventories...\");\n for (Player player : this.getServer().getOnlinePlayers()) {\n InventoryManager.unloadPlayerInventory(player);\n }\n }\n\n private void loadPlayers() {\n if (this.getServer().getOnlinePlayers().size() == 0) {\n return;\n }\n\n Log.i(\"Loading players inventories...\");\n for (Player player : this.getServer().getOnlinePlayers()) {\n InventoryManager.loadPlayerInventory(player);\n }\n }\n\n private boolean setupPermissions() {\n RegisteredServiceProvider<Permission> permissionProvider = getServer().getServicesManager().getRegistration(Permission.class);\n if (permissionProvider != null) {\n perms = permissionProvider.getProvider();\n }\n\n return perms != null;\n }\n\n private boolean setupEconomy() {\n RegisteredServiceProvider<Economy> rsp = this.getServer().getServicesManager().getRegistration(Economy.class);\n if (rsp != null) {\n economy = rsp.getProvider();\n }\n\n return economy != null;\n }\n\n public void checkUpdates(@Nullable final Player player) {\n if (!Config.getConfig().getBoolean(\"check-update\")) {\n return;\n }\n\n new TrackedBukkitRunnable() {\n @Override\n public void run() {\n Updater updater = new Updater(RPGInventory.instance, Updater.UpdateType.NO_DOWNLOAD);\n if (updater.getResult() == Updater.UpdateResult.UPDATE_AVAILABLE) {\n String[] lines = {\n StringUtils.coloredLine(\"&3=================&b[&eRPGInventory&b]&3===================\"),\n StringUtils.coloredLine(\"&6New version available: &a\" + updater.getLatestName() + \"&6!\"),\n StringUtils.coloredLine(updater.getDescription()),\n StringUtils.coloredLine(\"&6Changelog: &e\" + updater.getInfoLink()),\n StringUtils.coloredLine(\"&6Download it on &eSpigotMC&6!\"),\n StringUtils.coloredLine(\"&3==================================================\")\n };\n\n for (String line : lines) {\n if (player == null) {\n StringUtils.coloredConsole(line);\n } else {\n PlayerUtils.sendMessage(player, line);\n }\n }\n }\n }\n }.runTaskAsynchronously(RPGInventory.getInstance());\n }\n\n private void updateConfig() {\n final Version version = Version.parseVersion(this.getDescription().getVersion());\n\n if (!Config.getConfig().contains(\"version\")) {\n Config.getConfig().set(\"version\", version.toString());\n Config.save();\n return;\n }\n\n final Version configVersion = Version.parseVersion(Config.getConfig().getString(\"version\"));\n if (version.compareTo(configVersion) > 0) {\n ConfigUpdater.update(configVersion);\n Config.getConfig().set(\"version\", null);\n Config.getConfig().set(\"version\", version.toString());\n Config.save();\n }\n }\n\n @NotNull\n public Path getDataPath() {\n return getDataFolder().toPath();\n }\n}",
"public class InventoryManager {\n static final String TITLE = RPGInventory.getLanguage().getMessage(\"title\");\n private static final Map<UUID, PlayerWrapper> INVENTORIES = new HashMap<>();\n\n private static ItemStack FILL_SLOT = null;\n private static Reporter reporter;\n\n private InventoryManager() {\n }\n\n public static boolean init(@NotNull RPGInventory instance) {\n reporter = instance.getReporter();\n\n try {\n Texture texture = Texture.parseTexture(Config.getConfig().getString(\"fill\"));\n InventoryManager.FILL_SLOT = texture.getItemStack();\n ItemMeta meta = InventoryManager.FILL_SLOT.getItemMeta();\n if (meta != null) {\n meta.setDisplayName(\" \");\n InventoryManager.FILL_SLOT.setItemMeta(meta);\n }\n } catch (Exception e) {\n reporter.report(\"Error on InventoryManager initialization\", e);\n return false;\n }\n\n // Register events\n instance.getServer().getPluginManager().registerEvents(new InventoryListener(), instance);\n return true;\n }\n\n @SuppressWarnings(\"BooleanMethodIsAlwaysInverted\")\n public static boolean validateUpdate(Player player, ActionType actionType, @NotNull Slot slot, ItemStack item) {\n return actionType == ActionType.GET || actionType == ActionType.DROP\n || actionType == ActionType.SET && slot.isValidItem(item)\n && ItemManager.allowedForPlayer(player, item, true);\n }\n\n @NotNull\n public static ItemStack getFillSlot() {\n return InventoryManager.FILL_SLOT;\n }\n\n public static boolean validatePet(Player player, InventoryAction action, @Nullable ItemStack currentItem, @NotNull ItemStack cursor) {\n ActionType actionType = ActionType.getTypeOfAction(action);\n\n if (ItemUtils.isNotEmpty(currentItem)\n && (actionType == ActionType.GET || action == InventoryAction.SWAP_WITH_CURSOR || actionType == ActionType.DROP)\n && PetManager.getCooldown(currentItem) > 0) {\n return false;\n }\n\n if (actionType == ActionType.SET) {\n if (PetType.isPetItem(cursor) && ItemManager.allowedForPlayer(player, cursor, true)) {\n PetEquipEvent event = new PetEquipEvent(player, cursor);\n RPGInventory.getInstance().getServer().getPluginManager().callEvent(event);\n\n if (event.isCancelled()) {\n return false;\n }\n\n PetManager.respawnPet(event.getPlayer(), event.getPetItem());\n return true;\n }\n } else if (actionType == ActionType.GET || actionType == ActionType.DROP) {\n PetUnequipEvent event = new PetUnequipEvent(player);\n RPGInventory.getInstance().getServer().getPluginManager().callEvent(event);\n PetManager.despawnPet(event.getPlayer());\n return true;\n }\n\n return false;\n }\n\n public static boolean validateArmor(Player player, InventoryAction action, @NotNull Slot slot, ItemStack item) {\n ActionType actionType = ActionType.getTypeOfAction(action);\n return actionType != ActionType.OTHER && (actionType != ActionType.SET || slot.isValidItem(item))\n && ItemManager.allowedForPlayer(player, item, true);\n }\n\n public static void updateShieldSlot(@NotNull Player player, @NotNull Inventory inventory, @NotNull Slot slot, int slotId,\n InventoryType.SlotType slotType, InventoryAction action,\n ItemStack currentItem, @NotNull ItemStack cursor) {\n ActionType actionType = ActionType.getTypeOfAction(action);\n if (actionType == ActionType.GET) {\n if (slot.isCup(currentItem)) {\n return;\n }\n\n if (slotType == InventoryType.SlotType.QUICKBAR && InventoryAPI.isRPGInventory(inventory)) {\n inventory.setItem(slot.getSlotId(), slot.getCup());\n } else {\n player.getEquipment().setItemInOffHand(new ItemStack(Material.AIR));\n }\n } else if (actionType == ActionType.SET) {\n if (slot.isCup(currentItem)) {\n currentItem = null;\n action = InventoryAction.PLACE_ALL;\n }\n\n if (slotType == InventoryType.SlotType.QUICKBAR && InventoryAPI.isRPGInventory(inventory)) {\n inventory.setItem(slot.getSlotId(), cursor);\n } else {\n player.getEquipment().setItemInOffHand(cursor);\n }\n }\n\n InventoryManager.updateInventory(player, inventory, slotId, slotType, action, currentItem, cursor);\n }\n\n public static void updateQuickSlot(@NotNull Player player, @NotNull Inventory inventory, @NotNull Slot slot, int slotId,\n InventoryType.SlotType slotType, InventoryAction action,\n ItemStack currentItem, ItemStack cursor) {\n ActionType actionType = ActionType.getTypeOfAction(action);\n if (actionType == ActionType.GET) {\n if (slot.isCup(currentItem)) {\n return;\n }\n\n if (player.getInventory().getHeldItemSlot() == slot.getQuickSlot()) {\n InventoryUtils.heldFreeSlot(player, slot.getQuickSlot(), InventoryUtils.SearchType.NEXT);\n }\n\n if (slotType == InventoryType.SlotType.QUICKBAR && InventoryAPI.isRPGInventory(inventory)) {\n inventory.setItem(slot.getSlotId(), slot.getCup());\n } else {\n player.getInventory().setItem(slot.getQuickSlot(), slot.getCup());\n }\n\n action = InventoryAction.SWAP_WITH_CURSOR;\n cursor = slot.getCup();\n } else if (actionType == ActionType.SET) {\n if (slot.isCup(currentItem)) {\n currentItem = null;\n action = InventoryAction.PLACE_ALL;\n }\n\n if (slotType == InventoryType.SlotType.QUICKBAR && InventoryAPI.isRPGInventory(inventory)) {\n inventory.setItem(slot.getSlotId(), cursor);\n } else {\n player.getInventory().setItem(slot.getQuickSlot(), cursor);\n }\n }\n\n InventoryManager.updateInventory(player, inventory, slotId, slotType, action, currentItem, cursor);\n }\n\n public static void updateArmor(@NotNull Player player, @NotNull Inventory inventory, @NotNull Slot slot, int slotId, InventoryAction action, ItemStack currentItem, @NotNull ItemStack cursor) {\n ActionType actionType = ActionType.getTypeOfAction(action);\n\n EntityEquipment equipment = player.getEquipment();\n assert equipment != null;\n\n // Equip armor\n if (actionType == ActionType.SET || action == InventoryAction.UNKNOWN) {\n switch (slot.getName()) {\n case \"helmet\":\n InventoryManager.updateInventory(player, inventory, slotId, action, currentItem, cursor);\n equipment.setHelmet(inventory.getItem(slotId));\n break;\n case \"chestplate\":\n InventoryManager.updateInventory(player, inventory, slotId, action, currentItem, cursor);\n equipment.setChestplate(inventory.getItem(slotId));\n break;\n case \"leggings\":\n InventoryManager.updateInventory(player, inventory, slotId, action, currentItem, cursor);\n equipment.setLeggings(inventory.getItem(slotId));\n break;\n case \"boots\":\n InventoryManager.updateInventory(player, inventory, slotId, action, currentItem, cursor);\n equipment.setBoots(inventory.getItem(slotId));\n break;\n }\n } else if (actionType == ActionType.GET || actionType == ActionType.DROP) { // Unequip armor\n InventoryManager.updateInventory(player, inventory, slotId, action, currentItem, cursor);\n\n switch (slot.getName()) {\n case \"helmet\":\n equipment.setHelmet(null);\n break;\n case \"chestplate\":\n equipment.setChestplate(null);\n break;\n case \"leggings\":\n equipment.setLeggings(null);\n break;\n case \"boots\":\n equipment.setBoots(null);\n break;\n }\n }\n }\n\n public static void syncArmor(PlayerWrapper playerWrapper) {\n Player player = (Player) playerWrapper.getPlayer();\n Inventory inventory = playerWrapper.getInventory();\n SlotManager sm = SlotManager.instance();\n EntityEquipment equipment = player.getEquipment();\n assert equipment != null;\n\n if (ArmorType.HELMET.getSlot() != -1) {\n ItemStack helmet = equipment.getHelmet();\n Slot helmetSlot = sm.getSlot(ArmorType.HELMET.getSlot(), InventoryType.SlotType.CONTAINER);\n inventory.setItem(ArmorType.HELMET.getSlot(), (ItemUtils.isEmpty(helmet))\n && helmetSlot != null ? helmetSlot.getCup() : helmet);\n }\n\n if (ArmorType.CHESTPLATE.getSlot() != -1) {\n ItemStack savedChestplate = playerWrapper.getSavedChestplate();\n ItemStack chestplate = savedChestplate == null ? equipment.getChestplate() : savedChestplate;\n Slot chestplateSlot = sm.getSlot(ArmorType.CHESTPLATE.getSlot(), InventoryType.SlotType.CONTAINER);\n inventory.setItem(ArmorType.CHESTPLATE.getSlot(), (ItemUtils.isEmpty(chestplate))\n && chestplateSlot != null ? chestplateSlot.getCup() : chestplate);\n }\n\n if (ArmorType.LEGGINGS.getSlot() != -1) {\n ItemStack leggings = equipment.getLeggings();\n Slot leggingsSlot = sm.getSlot(ArmorType.LEGGINGS.getSlot(), InventoryType.SlotType.CONTAINER);\n inventory.setItem(ArmorType.LEGGINGS.getSlot(), (ItemUtils.isEmpty(leggings))\n && leggingsSlot != null ? leggingsSlot.getCup() : leggings);\n }\n\n if (ArmorType.BOOTS.getSlot() != -1) {\n ItemStack boots = equipment.getBoots();\n Slot bootsSlot = sm.getSlot(ArmorType.BOOTS.getSlot(), InventoryType.SlotType.CONTAINER);\n inventory.setItem(ArmorType.BOOTS.getSlot(), (ItemUtils.isEmpty(boots))\n && bootsSlot != null ? bootsSlot.getCup() : boots);\n }\n }\n\n public static void syncQuickSlots(PlayerWrapper playerWrapper) {\n Player player = (Player) playerWrapper.getPlayer();\n for (Slot quickSlot : SlotManager.instance().getQuickSlots()) {\n playerWrapper.getInventory().setItem(quickSlot.getSlotId(), player.getInventory().getItem(quickSlot.getQuickSlot()));\n }\n }\n\n public static void syncInfoSlots(PlayerWrapper playerWrapper) {\n final Player player = (Player) playerWrapper.getPlayer();\n for (Slot infoSlot : SlotManager.instance().getInfoSlots()) {\n ItemStack cup = infoSlot.getCup();\n if (ItemUtils.isEmpty(cup)) {\n continue;\n }\n\n ItemMeta meta = cup.getItemMeta();\n if (meta != null) {\n List<String> lore = meta.getLore();\n if (lore == null) {\n lore = new ArrayList<>();\n }\n\n for (int i = 0; i < lore.size(); i++) {\n String line = lore.get(i);\n lore.set(i, StringUtils.setPlaceholders(player, line));\n }\n\n meta.setLore(lore);\n cup.setItemMeta(meta);\n }\n playerWrapper.getInventory().setItem(infoSlot.getSlotId(), cup);\n }\n\n player.updateInventory();\n }\n\n public static void syncShieldSlot(@NotNull PlayerWrapper playerWrapper) {\n Slot slot = SlotManager.instance().getShieldSlot();\n if (slot == null) {\n return;\n }\n\n Player player = (Player) playerWrapper.getPlayer();\n ItemStack itemInHand = player.getEquipment().getItemInOffHand();\n playerWrapper.getInventory().setItem(slot.getSlotId(), ItemUtils.isEmpty(itemInHand) ? slot.getCup() : itemInHand);\n }\n\n private static void updateInventory(\n @NotNull Player player,\n @NotNull Inventory inventory,\n int slot,\n InventoryAction action,\n ItemStack currentItem,\n @NotNull ItemStack cursor\n ) {\n InventoryManager.updateInventory(player, inventory, slot, InventoryType.SlotType.CONTAINER, action, currentItem, cursor);\n }\n\n private static void updateInventory(\n @NotNull Player player,\n @NotNull Inventory inventory,\n int slot,\n InventoryType.SlotType slotType,\n InventoryAction action,\n ItemStack currentItem,\n @NotNull ItemStack cursorItem\n ) {\n if (ActionType.getTypeOfAction(action) == ActionType.DROP) {\n return;\n }\n\n if (action == InventoryAction.PLACE_ALL) {\n if (ItemUtils.isEmpty(currentItem)) {\n currentItem = cursorItem.clone();\n } else {\n currentItem.setAmount(currentItem.getAmount() + cursorItem.getAmount());\n }\n\n cursorItem = null;\n } else if (action == InventoryAction.PLACE_ONE) {\n if (ItemUtils.isEmpty(currentItem)) {\n currentItem = cursorItem.clone();\n currentItem.setAmount(1);\n cursorItem.setAmount(cursorItem.getAmount() - 1);\n } else if (currentItem.getMaxStackSize() < currentItem.getAmount() + 1) {\n currentItem.setAmount(currentItem.getAmount() + 1);\n cursorItem.setAmount(cursorItem.getAmount() - 1);\n }\n } else if (action == InventoryAction.PLACE_SOME) {\n cursorItem.setAmount(currentItem.getMaxStackSize() - currentItem.getAmount());\n currentItem.setAmount(currentItem.getMaxStackSize());\n } else if (action == InventoryAction.SWAP_WITH_CURSOR) {\n ItemStack tempItem = cursorItem.clone();\n cursorItem = currentItem.clone();\n currentItem = tempItem;\n } else if (action == InventoryAction.PICKUP_ALL) {\n cursorItem = currentItem.clone();\n currentItem = null;\n } else if (action == InventoryAction.PICKUP_HALF) {\n ItemStack item = currentItem.clone();\n if (currentItem.getAmount() % 2 == 0) {\n item.setAmount(item.getAmount() / 2);\n currentItem = item.clone();\n cursorItem = item.clone();\n } else {\n currentItem = item.clone();\n currentItem.setAmount(item.getAmount() / 2);\n cursorItem = item.clone();\n cursorItem.setAmount(item.getAmount() / 2 + 1);\n }\n } else if (action == InventoryAction.MOVE_TO_OTHER_INVENTORY) {\n player.getInventory().addItem(currentItem);\n currentItem = null;\n }\n\n if (slotType == InventoryType.SlotType.QUICKBAR) {\n if (slot < 9) { // Exclude shield\n player.getInventory().setItem(slot, currentItem);\n }\n } else {\n inventory.setItem(slot, currentItem);\n }\n\n player.setItemOnCursor(cursorItem);\n player.updateInventory();\n }\n\n static void lockEmptySlots(Player player) {\n lockEmptySlots(INVENTORIES.get(player.getUniqueId()).getInventory());\n }\n\n public static void lockEmptySlots(Inventory inventory) {\n for (int i = 0; i < inventory.getSize(); i++) {\n Slot slot = SlotManager.instance().getSlot(i, InventoryType.SlotType.CONTAINER);\n if (slot == null) {\n inventory.setItem(i, FILL_SLOT);\n } else if (ItemUtils.isEmpty(inventory.getItem(i))) {\n inventory.setItem(i, slot.getCup());\n }\n }\n }\n\n static void unlockEmptySlots(Player player) {\n Inventory inventory = INVENTORIES.get(player.getUniqueId()).getInventory();\n\n for (int i = 0; i < inventory.getSize(); i++) {\n Slot slot = SlotManager.instance().getSlot(i, InventoryType.SlotType.CONTAINER);\n if (slot == null || slot.isCup(inventory.getItem(i))) {\n inventory.setItem(i, null);\n }\n }\n }\n\n public static boolean isQuickSlot(int slot) {\n return getQuickSlot(slot) != null;\n }\n\n @Nullable\n public static Slot getQuickSlot(int slot) {\n for (Slot quickSlot : SlotManager.instance().getQuickSlots()) {\n if (slot == quickSlot.getQuickSlot()) {\n return quickSlot;\n }\n }\n\n return null;\n }\n\n static void lockQuickSlots(@NotNull Player player) {\n for (Slot quickSlot : SlotManager.instance().getQuickSlots()) {\n int slotId = quickSlot.getQuickSlot();\n\n if (ItemUtils.isEmpty(player.getInventory().getItem(slotId))) {\n player.getInventory().setItem(slotId, quickSlot.getCup());\n }\n\n if (player.getInventory().getHeldItemSlot() == slotId) {\n if (quickSlot.isCup(player.getInventory().getItem(slotId))) {\n InventoryUtils.heldFreeSlot(player, slotId, InventoryUtils.SearchType.NEXT);\n }\n }\n }\n }\n\n static void unlockQuickSlots(@NotNull Player player) {\n for (Slot quickSlot : SlotManager.instance().getQuickSlots()) {\n int slotId = quickSlot.getQuickSlot();\n if (quickSlot.isCup(player.getInventory().getItem(slotId))) {\n player.getInventory().setItem(slotId, null);\n }\n }\n }\n\n public static boolean isNewPlayer(@NotNull Player player) {\n Path dataFolder = RPGInventory.getInstance().getDataFolder().toPath();\n return Files.notExists(dataFolder.resolve(\"inventories/\" + player.getUniqueId() + \".inv\"));\n }\n\n public static void loadPlayerInventory(Player player) {\n if (!InventoryManager.isAllowedWorld(player.getWorld())) {\n InventoryManager.INVENTORIES.remove(player.getUniqueId());\n return;\n }\n\n try {\n Path dataFolder = RPGInventory.getInstance().getDataPath();\n Path folder = dataFolder.resolve(\"inventories\");\n Files.createDirectories(folder);\n\n // Load inventory from file\n Path file = folder.resolve(player.getUniqueId() + \".inv\");\n\n PlayerWrapper playerWrapper = null;\n if (Files.exists(file)) {\n playerWrapper = Serialization.loadPlayerOrNull(player, file);\n if (playerWrapper == null) {\n Log.s(\"Error on loading {0}''s inventory.\", player.getName());\n Log.s(\"Will be created new inventory. Old file was renamed.\");\n }\n }\n\n if (playerWrapper == null) {\n playerWrapper = new PlayerWrapper(player);\n playerWrapper.setBuyedSlots(0);\n }\n\n PlayerInventoryLoadEvent.Pre event = new PlayerInventoryLoadEvent.Pre(player);\n RPGInventory.getInstance().getServer().getPluginManager().callEvent(event);\n\n if (event.isCancelled()) {\n return;\n }\n\n InventoryManager.INVENTORIES.put(player.getUniqueId(), playerWrapper);\n\n InventoryLocker.lockSlots(player);\n PetManager.initPlayer(player);\n\n RPGInventory.getInstance().getServer().getPluginManager().callEvent(new PlayerInventoryLoadEvent.Post(player));\n } catch (IOException e) {\n reporter.report(\"Error on inventory load\", e);\n }\n }\n\n public static void unloadPlayerInventory(@NotNull Player player) {\n if (!InventoryManager.playerIsLoaded(player)) {\n return;\n }\n\n InventoryManager.INVENTORIES.get(player.getUniqueId()).onUnload();\n savePlayerInventory(player);\n InventoryLocker.unlockSlots(player);\n\n InventoryManager.INVENTORIES.remove(player.getUniqueId());\n\n RPGInventory.getInstance().getServer().getPluginManager().callEvent(new PlayerInventoryUnloadEvent.Post(player));\n }\n\n public static void savePlayerInventory(@NotNull Player player) {\n if (!InventoryManager.playerIsLoaded(player)) {\n return;\n }\n\n PlayerWrapper playerWrapper = InventoryManager.INVENTORIES.get(player.getUniqueId());\n try {\n Path dataFolder = RPGInventory.getInstance().getDataPath();\n Path folder = dataFolder.resolve(\"inventories\");\n Files.createDirectories(folder);\n\n Path file = folder.resolve(player.getUniqueId() + \".inv\");\n Files.deleteIfExists(file);\n\n Serialization.save(playerWrapper.createSnapshot(), file);\n } catch (IOException | NullPointerException e) {\n Log.w(e, \"Error on inventory save\");\n }\n }\n\n @NotNull\n public static PlayerWrapper get(@NotNull OfflinePlayer player) {\n PlayerWrapper playerWrapper = InventoryManager.INVENTORIES.get(player.getUniqueId());\n if (playerWrapper == null) {\n throw new IllegalStateException(player.getName() + \"'s inventory should be initialized!\");\n }\n\n return playerWrapper;\n }\n\n @SuppressWarnings(\"BooleanMethodIsAlwaysInverted\")\n public static boolean isQuickEmptySlot(@Nullable ItemStack item) {\n for (Slot quickSlot : SlotManager.instance().getQuickSlots()) {\n if (quickSlot.isCup(item)) {\n return true;\n }\n }\n\n return false;\n }\n\n public static boolean isFilledSlot(@Nullable ItemStack item) {\n return InventoryManager.FILL_SLOT.equals(item);\n }\n\n public static boolean isEmptySlot(@Nullable ItemStack item) {\n for (Slot slot : SlotManager.instance().getSlots()) {\n if (slot.isCup(item)) {\n return true;\n }\n }\n\n return false;\n }\n\n @Contract(\"null -> false\")\n public static boolean playerIsLoaded(@Nullable AnimalTamer player) {\n return player != null && InventoryManager.INVENTORIES.containsKey(player.getUniqueId());\n }\n\n public static boolean isAllowedWorld(@NotNull World world) {\n List<String> list = Config.getConfig().getStringList(\"worlds.list\");\n\n ListType listType = SafeEnums.valueOf(ListType.class, Config.getConfig().getString(\"worlds.mode\"), \"list type\");\n if (listType != null) {\n switch (listType) {\n case BLACKLIST:\n return !list.contains(world.getName());\n case WHITELIST:\n return list.contains(world.getName());\n }\n }\n\n return true;\n }\n\n public static boolean buySlot(@NotNull Player player, PlayerWrapper playerWrapper, Slot slot) {\n double cost = slot.getCost();\n\n if (!playerWrapper.isPreparedToBuy(slot)) {\n PlayerUtils.sendMessage(player, RPGInventory.getLanguage().getMessage(\"error.buyable\", slot.getCost()));\n playerWrapper.prepareToBuy(slot);\n return false;\n }\n\n if (!PlayerUtils.checkMoney(player, cost) || !RPGInventory.getEconomy().withdrawPlayer(player, cost).transactionSuccess()) {\n return false;\n }\n\n playerWrapper.setBuyedSlots(slot.getName());\n PlayerUtils.sendMessage(player, RPGInventory.getLanguage().getMessage(\"message.buyed\"));\n\n return true;\n }\n\n public static void initPlayer(@NotNull final Player player, boolean skipJoinMessage) {\n ResourcePackModule rpModule = RPGInventory.getResourcePackModule();\n if (rpModule != null) {\n rpModule.loadResourcePack(player, skipJoinMessage);\n } else {\n if (!skipJoinMessage) {\n EffectUtils.showDefaultJoinMessage(player);\n }\n InventoryManager.loadPlayerInventory(player);\n }\n\n if (RPGInventory.getPermissions().has(player, \"rpginventory.admin\")) {\n RPGInventory.getInstance().checkUpdates(player);\n }\n }\n\n private enum ListType {\n BLACKLIST, WHITELIST\n }\n}",
"public class Slot {\n\n public static final int SHIELD_RAW_SLOT_ID = 45;\n private static final int SHIELD_SLOT_ID = 40;\n\n private final String name;\n @NotNull\n private final SlotType slotType;\n\n private final List<String> allowed = new ArrayList<>();\n private final List<String> denied = new ArrayList<>();\n\n @NotNull\n private final List<Integer> slotIds;\n @NotNull\n private final ItemStack cup;\n private final int requiredLevel;\n private final int cost;\n private final int quickSlot;\n private final boolean drop;\n\n public Slot(String name, @NotNull SlotType slotType, @NotNull ConfigurationSection config) {\n this.name = name;\n\n this.slotType = slotType;\n final List<Integer> slotList = config.getIntegerList(\"slot\");\n this.slotIds = slotList.isEmpty() ? Collections.singletonList(config.getInt(\"slot\")) : slotList;\n this.requiredLevel = config.getInt(\"cost.required-level\", 0);\n this.cost = config.getInt(\"cost.money\", 0);\n this.drop = config.getBoolean(\"drop\", true);\n\n int quickSlot = config.contains(\"quickbar\") ? InventoryUtils.getQuickSlot(config.getInt(\"quickbar\")) : -1;\n if (slotType == SlotType.SHIELD) {\n quickSlot = SHIELD_SLOT_ID;\n } else if (slotType != SlotType.ACTIVE && quickSlot == -1 || !slotType.isAllowQuick() || slotIds.size() > 1) {\n if (config.contains(\"quickbar\")) {\n Log.w(\"Option \\\"quickbar\\\" is ignored for slot \\\"{0}\\\"!\", name);\n }\n quickSlot = -1;\n }\n this.quickSlot = quickSlot;\n\n if (slotType.isReadItemList()) {\n for (String item : config.getStringList(\"items\")) {\n if (item.startsWith(\"-\")) {\n this.denied.add(item.substring(1));\n } else {\n this.allowed.add(item);\n }\n }\n } else {\n if (config.contains(\"items\")) {\n Log.w(\"Option \\\"items\\\" is ignored for slot \\\"{0}\\\"!\", name);\n }\n\n if (slotType == SlotType.ELYTRA) {\n this.allowed.add(\"ELYTRA\");\n }\n }\n\n // Setup cup slot\n Texture texture = Texture.parseTexture(config.getString(\"holder.item\"));\n ItemStack cup = texture.getItemStack();\n ItemMeta meta = cup.getItemMeta();\n if (meta != null) {\n meta.setDisplayName(config.contains(\"holder.name\") ? StringUtils.coloredLine(config.getString(\"holder.name\")) : \"[Holder name missing]\");\n meta.setLore(config.contains(\"holder.lore\") ? StringUtils.coloredLines(config.getStringList(\"holder.lore\")) : Collections.singletonList(\"[Holder lore missing]\"));\n cup.setItemMeta(meta);\n }\n this.cup = cup;\n }\n\n private static boolean searchItem(List<String> materialList, @NotNull ItemStack itemStack) {\n for (String material : materialList) {\n String[] data = material.split(\":\");\n\n if (material.equals(\"ALL\")) {\n return true;\n }\n\n if (!itemStack.getType().name().equals(data[0])) {\n continue;\n }\n\n if (data.length > 1) {\n String[] borders = data[1].split(\"-\");\n int itemTextureData = ItemUtils.getTextureData(itemStack);\n\n if (borders.length == 1 && itemTextureData != Integer.parseInt(data[1])) {\n continue;\n } else if (borders.length == 2) {\n int min = Integer.parseInt(borders[0]);\n int max = Integer.parseInt(borders[1]);\n\n if (min > max) {\n int temp = max;\n max = min;\n min = temp;\n }\n\n if (itemTextureData < min || itemTextureData > max) {\n continue;\n }\n }\n }\n\n return true;\n }\n\n return false;\n }\n\n @NotNull\n public ItemStack getCup() {\n return this.cup.clone();\n }\n\n public boolean isCup(@Nullable ItemStack itemStack) {\n return this.cup.equals(itemStack);\n }\n\n boolean containsSlot(int slot) {\n return this.slotIds.contains(slot);\n }\n\n public boolean isValidItem(@Nullable ItemStack itemStack) {\n return ItemUtils.isNotEmpty(itemStack) && !this.isDenied(itemStack) && this.isAllowed(itemStack);\n }\n\n public boolean isFree() {\n return this.cost == 0;\n }\n\n public List<String> getAllowedItems() {\n return allowed;\n }\n\n public List<String> getDeniedItems() {\n return denied;\n }\n\n boolean itemListIsEmpty() {\n return this.allowed.isEmpty() && this.denied.isEmpty();\n }\n\n private boolean isDenied(@NotNull ItemStack item) {\n return searchItem(this.denied, item);\n }\n\n private boolean isAllowed(@NotNull ItemStack item) {\n return searchItem(this.allowed, item);\n }\n\n @NotNull\n public SlotType getSlotType() {\n return slotType;\n }\n\n public String getName() {\n return name;\n }\n\n public int getRequiredLevel() {\n return requiredLevel;\n }\n\n public int getSlotId() {\n return slotIds.get(0);\n }\n\n public int getQuickSlot() {\n return this.quickSlot;\n }\n\n public boolean isQuick() {\n return this.quickSlot != -1 && this.slotType != SlotType.SHIELD;\n }\n\n @NotNull\n public List<Integer> getSlotIds() {\n return slotIds;\n }\n\n public int getCost() {\n return cost;\n }\n\n public boolean isDrop() {\n return drop;\n }\n\n @SuppressWarnings(\"unused\")\n public enum SlotType {\n GENERIC(true, true, false, true),\n ACTION(false, true, false, false),\n PET(false, false, true, false),\n ARMOR(false, false, false, true),\n ACTIVE(true, false, false, true),\n BACKPACK(true, false, false, false),\n PASSIVE(true, true, false, true),\n SHIELD(false, false, true, true),\n ELYTRA(false, false, true, false),\n INFO(false, false, false, false);\n\n private final boolean allowQuick;\n private final boolean allowMultiSlots;\n private final boolean unique;\n private final boolean readItemList;\n\n SlotType(boolean allowQuick, boolean allowMultiSlots, boolean unique, boolean readItemList) {\n this.allowQuick = allowQuick;\n this.allowMultiSlots = allowMultiSlots;\n this.unique = unique;\n this.readItemList = readItemList;\n }\n\n public boolean isAllowQuick() {\n return allowQuick;\n }\n\n public boolean isAllowMultiSlots() {\n return allowMultiSlots;\n }\n\n public boolean isUnique() {\n return unique;\n }\n\n public boolean isReadItemList() {\n return readItemList;\n }\n }\n}",
"public class SlotManager {\n\n private static final String CONFIG_NAME = \"slots.yml\";\n\n @Nullable\n private static SlotManager slotManager = null;\n\n private final List<Slot> slots = new ArrayList<>();\n\n @NotNull\n private final Path slotsFile;\n @NotNull\n private final FileConfiguration slotsConfig;\n\n private SlotManager() {\n this.slotsFile = RPGInventory.getInstance().getDataPath().resolve(CONFIG_NAME);\n if (Files.notExists(slotsFile)) {\n RPGInventory.getInstance().saveResource(CONFIG_NAME, false);\n }\n\n this.slotsConfig = YamlConfiguration.loadConfiguration(slotsFile.toFile());\n\n @Nullable final ConfigurationSection slots = this.slotsConfig.getConfigurationSection(\"slots\");\n if (slots == null) {\n Log.s(\"Section ''slots'' not found in {0}\", CONFIG_NAME);\n return;\n }\n\n for (String slotName : slots.getKeys(false)) {\n final ConfigurationSection slotConfiguration = slots.getConfigurationSection(slotName);\n assert slotConfiguration != null;\n\n Slot.SlotType slotType = SafeEnums.valueOfOrDefault(Slot.SlotType.class, slotConfiguration.getString(\"type\"), Slot.SlotType.GENERIC, \"slot type\");\n Slot slot;\n if (slotType == Slot.SlotType.ACTION) {\n slot = new ActionSlot(slotName, slotConfiguration);\n } else {\n slot = new Slot(slotName, slotType, slotConfiguration);\n }\n\n if (this.validateSlot(slot)) {\n this.slots.add(slot);\n } else {\n Log.w(\"Slot \\\"{0}\\\" was not been added.\", slot.getName());\n }\n }\n }\n\n public static boolean init() {\n try {\n SlotManager.slotManager = new SlotManager();\n } catch (Exception e) {\n Log.w(e, \"Failed to initialize SlotManager\");\n return false;\n }\n\n return true;\n }\n\n @NotNull\n public static SlotManager instance() {\n return Objects.requireNonNull(SlotManager.slotManager, \"Plugin is not initialized yet\");\n }\n\n private boolean validateSlot(Slot slot) {\n if (slot.getSlotType().isReadItemList() && slot.itemListIsEmpty()) {\n Log.w(\"Slot with type {0} must contains list of allowed items\", slot.getSlotType());\n }\n\n if (!validateItems(slot.getAllowedItems()) || !validateItems(slot.getDeniedItems())) {\n return false;\n }\n\n if (!slot.getSlotType().isAllowMultiSlots() && slot.getSlotIds().size() > 1) {\n Log.w(\"Slot with type {0} can not contain more than one slotId\", slot.getSlotType());\n return false;\n }\n\n for (int slotId : slot.getSlotIds()) {\n if (slotId < 0 || slotId > 53) {\n Log.w(\"Slot IDs should be in range 0..53, but it was {0}\", slotId);\n return false;\n }\n }\n\n for (Slot existingSlot : this.slots) {\n for (int slotId : slot.getSlotIds()) {\n if (existingSlot.getSlotIds().contains(slotId)) {\n Log.w(\"Slot {0} is occupied by {1}\", slotId, existingSlot.getName());\n return false;\n }\n }\n\n if (slot.isQuick() && existingSlot.isQuick()) {\n int slotId = slot.getQuickSlot();\n int existingSlotId = existingSlot.getQuickSlot();\n if (slotId == existingSlotId) {\n Log.w(\"Quickbar slot {0} is occupied by {1}\", slotId, existingSlot.getName());\n return false;\n }\n }\n\n if (slot.getSlotType().isUnique() && slot.getSlotType() == existingSlot.getSlotType()) {\n Log.w(\"You can not create more then one slot with type {0}!\", slot.getSlotType());\n return false;\n }\n }\n\n return true;\n }\n\n private boolean validateItems(List<String> itemsPatterns) {\n for (String itemPattern : itemsPatterns) {\n if (!itemPattern.matches(\"^[\\\\w_]+(:\\\\d+(-\\\\d)?)?$\")) {\n Log.w(\"Allowed and denied items should fit to pattern ''[string]:[number]-[number]''\");\n Log.w(\"But it was: {0}\", itemPattern);\n return false;\n }\n }\n return true;\n }\n\n @Nullable\n public Slot getSlot(String name) {\n for (Slot slot : this.slots) {\n if (slot.getName().equalsIgnoreCase(name)) {\n return slot;\n }\n }\n\n return null;\n }\n\n @Nullable\n public Slot getSlot(int slotId, InventoryType.SlotType slotType) {\n for (Slot slot : this.slots) {\n if (slotType == InventoryType.SlotType.QUICKBAR) {\n if ((slot.isQuick() || slot.getSlotType() == Slot.SlotType.SHIELD) && slot.getQuickSlot() == slotId) {\n return slot;\n }\n } else if (slot.containsSlot(slotId)) {\n return slot;\n }\n }\n\n return null;\n }\n\n @NotNull\n public List<Slot> getQuickSlots() {\n List<Slot> quickSlots = new ArrayList<>();\n for (Slot slot : this.slots) {\n if (slot.isQuick()) {\n quickSlots.add(slot);\n }\n }\n\n return quickSlots;\n }\n\n @NotNull\n public List<Slot> getPassiveSlots() {\n List<Slot> passiveSlots = new ArrayList<>();\n for (Slot slot : this.slots) {\n final Slot.SlotType type = slot.getSlotType();\n if (type == Slot.SlotType.PASSIVE || type == Slot.SlotType.BACKPACK || type == Slot.SlotType.ELYTRA) {\n passiveSlots.add(slot);\n }\n }\n\n return passiveSlots;\n }\n\n @NotNull\n public List<Slot> getActiveSlots() {\n List<Slot> activeSlots = new ArrayList<>();\n for (Slot slot : this.slots) {\n if (slot.getSlotType() == Slot.SlotType.ACTIVE) {\n activeSlots.add(slot);\n }\n }\n\n return activeSlots;\n }\n\n @NotNull\n public List<Slot> getArmorSlots() {\n List<Slot> armorSlots = new ArrayList<>(4);\n for (Slot slot : this.slots) {\n if (slot.getSlotType() == Slot.SlotType.ARMOR) {\n armorSlots.add(slot);\n }\n }\n\n return armorSlots;\n }\n\n @NotNull\n public List<Slot> getInfoSlots() {\n List<Slot> infoSlots = new ArrayList<>();\n for (Slot slot : this.slots) {\n if (slot.getSlotType() == Slot.SlotType.INFO) {\n infoSlots.add(slot);\n }\n }\n\n return infoSlots;\n }\n\n @NotNull\n public List<Slot> getSlots() {\n return this.slots;\n }\n\n @Nullable\n public Slot getPetSlot() {\n for (Slot slot : this.slots) {\n if (slot.getSlotType() == Slot.SlotType.PET) {\n return slot;\n }\n }\n\n return null;\n }\n\n @Nullable\n public Slot getShieldSlot() {\n for (Slot slot : this.slots) {\n if (slot.getSlotType() == Slot.SlotType.SHIELD) {\n return slot;\n }\n }\n\n return null;\n }\n\n @Nullable\n public Slot getBackpackSlot() {\n for (Slot slot : this.slots) {\n if (slot.getSlotType() == Slot.SlotType.BACKPACK) {\n return slot;\n }\n }\n\n return null;\n }\n\n @Nullable\n public Slot getElytraSlot() {\n for (Slot slot : this.slots) {\n if (slot.getSlotType() == Slot.SlotType.ELYTRA) {\n return slot;\n }\n }\n\n return null;\n }\n\n public void saveDefaults() {\n try {\n this.slotsConfig.save(this.slotsFile.toFile());\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n}",
"public class ItemUtils {\n public static final String ENTITY_TAG = \"EntityTag\";\n\n public static final String BACKPACK_UID_TAG = \"backpack.uid\";\n public static final String BACKPACK_TAG = \"backpack.id\";\n public static final String ITEM_TAG = \"rpginv.id\";\n public static final String FOOD_TAG = \"food.id\";\n public static final String PET_TAG = \"pet.id\";\n\n @NotNull\n public static ItemStack setTag(ItemStack item, @NotNull String tag, @NotNull String value) {\n ItemStack bukkitItem = toBukkitItemStack(item);\n if (isEmpty(bukkitItem)) {\n return bukkitItem;\n }\n\n NbtCompound nbt = NbtFactoryMirror.fromItemCompound(bukkitItem);\n if (!nbt.containsKey(tag)) {\n nbt.put(tag, value);\n }\n NbtFactoryMirror.setItemTag(bukkitItem, nbt);\n\n return bukkitItem;\n }\n\n @NotNull\n public static String getTag(@NotNull ItemStack item, @NotNull String tag) {\n return getTag(item, tag, \"\");\n }\n\n @NotNull\n @SuppressWarnings(\"WeakerAccess\")\n public static String getTag(@NotNull ItemStack item, @NotNull String tag, @NotNull String defaultValue) {\n final ItemStack bukkitItem = toBukkitItemStack(item);\n if (isEmpty(bukkitItem)) {\n return \"\";\n }\n\n NbtCompound nbt = NbtFactoryMirror.fromItemCompound(bukkitItem);\n return nbt.containsKey(tag) ? nbt.getString(tag) : defaultValue;\n }\n\n @Contract(\"null, _ -> false\")\n public static boolean hasTag(@Nullable ItemStack originalItem, String tag) {\n if (isEmpty(originalItem) || !originalItem.hasItemMeta()) {\n return false;\n }\n\n ItemStack item = toBukkitItemStack(originalItem.clone());\n if (isEmpty(item)) {\n return false;\n }\n\n NbtCompound nbt = NbtFactoryMirror.fromItemCompound(item);\n return nbt.containsKey(tag);\n }\n\n public static boolean isItemHasDurability(ItemStack item) {\n return item.getType().getMaxDurability() > 0;\n }\n\n @NotNull\n public static ItemStack[] syncItems(ItemStack[] items) {\n for (int i = 0; i < items.length; i++) {\n items[i] = ItemUtils.syncItem(items[i]);\n }\n\n return items;\n }\n\n @NotNull\n @Contract(\"null -> !null\")\n private static ItemStack syncItem(@Nullable ItemStack item) {\n if (ItemUtils.isEmpty(item)) {\n return new ItemStack(Material.AIR);\n }\n\n int itemTextureData = getTextureData(item);\n int amount = item.getAmount();\n int foundTextureData;\n if (CustomItem.isCustomItem(item)) {\n CustomItem custom = ItemManager.getCustomItem(item);\n\n if (custom == null) {\n return new ItemStack(Material.AIR);\n }\n\n foundTextureData = custom.getTextureData();\n item = ItemManager.getItem(ItemUtils.getTag(item, ItemUtils.ITEM_TAG));\n } else if (BackpackManager.isBackpack(item)) {\n BackpackType type = BackpackManager.getBackpackType(ItemUtils.getTag(item, ItemUtils.BACKPACK_TAG));\n\n if (type == null) {\n return new ItemStack(Material.AIR);\n }\n\n foundTextureData = type.getTextureData();\n\n String bpUID = ItemUtils.getTag(item, ItemUtils.BACKPACK_UID_TAG);\n if (!bpUID.isEmpty()) {\n ItemUtils.setTag(item, ItemUtils.BACKPACK_UID_TAG, bpUID);\n }\n } else if (PetType.isPetItem(item)) {\n PetType petType = PetManager.getPetFromItem(item);\n if (petType == null) {\n return new ItemStack(Material.AIR);\n }\n foundTextureData = petType.getTextureData();\n\n long deathTime = PetManager.getDeathTime(item);\n double health = PetManager.getHealth(item, petType.getHealth());\n\n item = petType.getSpawnItem();\n PetManager.saveDeathTime(item, deathTime);\n PetManager.saveHealth(item, health);\n } else if (PetFood.isFoodItem(item)) {\n PetFood food = PetManager.getFoodFromItem(item);\n if (food == null) {\n return new ItemStack(Material.AIR);\n }\n foundTextureData = food.getTextureData();\n\n item = food.getFoodItem();\n } else {\n return item;\n }\n\n setTextureData(item, foundTextureData == -1 ? itemTextureData : foundTextureData);\n item.setAmount(amount);\n return item;\n }\n\n public static int getTextureData(@NotNull ItemStack itemStack) {\n ItemMeta meta = itemStack.getItemMeta();\n if (meta == null) {\n return 0;\n }\n\n int data;\n if (Config.texturesType == TexturesType.DAMAGE) {\n data = ((Damageable) meta).getDamage();\n } else if (meta.hasCustomModelData()) {\n data = meta.getCustomModelData();\n } else {\n data = 0;\n }\n return data;\n }\n\n private static void setTextureData(@NotNull ItemStack itemStack, int data) {\n ItemMeta meta = itemStack.getItemMeta();\n if (meta != null) {\n if (Config.texturesType == TexturesType.DAMAGE) {\n ((Damageable) meta).setDamage(data);\n } else {\n meta.setCustomModelData(data);\n }\n itemStack.setItemMeta(meta);\n }\n }\n\n @Contract(\"null -> true\")\n public static boolean isEmpty(@Nullable ItemStack item) {\n return item == null || item.getType() == Material.AIR;\n }\n\n @Contract(\"null -> false\")\n public static boolean isNotEmpty(@Nullable ItemStack item) {\n return item != null && item.getType() != Material.AIR;\n }\n\n @NotNull\n public static ItemStack toBukkitItemStack(ItemStack item) {\n return MinecraftReflection.getBukkitItemStack(item);\n }\n}"
] | import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.scheduler.BukkitRunnable;
import ru.endlesscode.rpginventory.RPGInventory;
import ru.endlesscode.rpginventory.inventory.InventoryManager;
import ru.endlesscode.rpginventory.inventory.slot.Slot;
import ru.endlesscode.rpginventory.inventory.slot.SlotManager;
import ru.endlesscode.rpginventory.utils.ItemUtils;
import java.util.Objects; | /*
* This file is part of RPGInventory.
* Copyright (C) 2015-2017 Osip Fatkullin
*
* RPGInventory 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.
*
* RPGInventory 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 RPGInventory. If not, see <http://www.gnu.org/licenses/>.
*/
package ru.endlesscode.rpginventory.pet;
/**
* Created by OsipXD on 27.08.2015
* It is part of the RpgInventory.
* All rights reserved 2014 - 2016 © «EndlessCode Group»
*/
@Deprecated
class CooldownTimer extends BukkitRunnable {
private final Player player;
private final ItemStack petItem;
@Deprecated
public CooldownTimer(Player player, ItemStack petItem) {
this.player = player;
this.petItem = petItem;
}
@Override
public void run() {
if (!InventoryManager.playerIsLoaded(this.player)) {
this.cancel();
return;
}
Inventory inventory = InventoryManager.get(this.player).getInventory();
final boolean playerIsAlive = !this.player.isOnline() || this.player.isDead();
final boolean playerHasNotPetItem = inventory.getItem(PetManager.getPetSlotId()) == null;
if (playerIsAlive || !PetManager.isEnabled() || playerHasNotPetItem) {
this.cancel();
return;
}
int cooldown = PetManager.getCooldown(this.petItem);
if (cooldown > 1) {
ItemStack item = this.petItem.clone();
if (cooldown < 60) {
item.setAmount(cooldown);
}
ItemMeta itemMeta = item.getItemMeta();
if (itemMeta != null) {
itemMeta.setDisplayName(itemMeta.getDisplayName()
+ RPGInventory.getLanguage().getMessage("pet.cooldown", cooldown));
PetManager.addGlow(itemMeta);
item.setItemMeta(itemMeta);
}
String itemTag = ItemUtils.getTag(this.petItem, ItemUtils.PET_TAG);
if (itemTag.isEmpty()) { | Slot petSlot = Objects.requireNonNull(SlotManager.instance().getPetSlot(), "Pet slot can't be null!"); | 2 |
firepick1/FireBOM | src/main/java/org/firepick/firebom/bom/BOM.java | [
"public interface IPartComparable extends Comparable<IPartComparable> {\n Part getPart();\n}",
"public interface IRefreshableProxy {\n\n /**\n * Synchronize proxy with remote resource\n */\n void refresh();\n\n /**\n * A newly constructed proxy is not fresh until it is refreshed.\n * Freshness lasts until a refresh timeout. Unsampled proxies stay fresh\n * forever.\n * @return true if proxy has been recently refreshed or never sampled\n */\n boolean isFresh();\n\n /**\n * Use the information provided by the proxy. Frequently sampled proxies should be\n * refreshed more often than rarely sampled proxies. Sampling a proxy affects its\n * freshness as well as the refresh interval.\n */\n void sample();\n\n /**\n * A resolved proxy is one that has been successfully refreshed at least once in its\n * lifetime.\n * @return\n */\n boolean isResolved();\n\n /**\n * Return age since last refresh or construction.\n * @return\n */\n long getAge();\n\n}",
"public class RefreshableTimer implements IRefreshableProxy, Serializable {\n private long minRefreshInterval;\n private long lastRefreshMillis;\n private long lastSampleMillis;\n private double sensitivity;\n private boolean isResolved;\n private long samplesSinceRefresh;\n private long sampleInterval;\n\n public RefreshableTimer() {\n this(0.8d);\n }\n\n public RefreshableTimer(double sensitivity) {\n if (sensitivity < 0 || 1 < sensitivity) {\n throw new IllegalArgumentException(\"sensitivity must be between [0..1]\");\n }\n this.sensitivity = sensitivity;\n this.lastRefreshMillis = System.currentTimeMillis();\n this.lastSampleMillis = lastRefreshMillis;\n }\n\n public void refresh() {\n lastRefreshMillis = System.currentTimeMillis();\n samplesSinceRefresh = 0;\n isResolved = true;\n }\n\n public void sample() {\n samplesSinceRefresh++;\n long nowMillis = System.currentTimeMillis();\n long msElapsed = nowMillis - lastSampleMillis;\n if (isResolved()) {\n sampleInterval =(long)(getSensitivity() * msElapsed + (1 - getSensitivity()) * sampleInterval);\n } else {\n sampleInterval = Math.max(1, msElapsed);\n }\n lastSampleMillis = nowMillis;\n }\n\n public boolean isFresh() {\n long refreshInterval = getRefreshInterval();\n long ageDiff = refreshInterval - getAge();\n return isResolved() && ageDiff >= 0;\n }\n\n public double getSensitivity() {\n return sensitivity;\n }\n\n public long getSamplesSinceRefresh() {\n return samplesSinceRefresh;\n }\n\n public boolean isResolved() {\n return isResolved;\n }\n\n protected RefreshableTimer setResolved(boolean value) {\n isResolved = value;\n return this;\n }\n\n public long getAge() {\n return System.currentTimeMillis() - lastRefreshMillis;\n }\n\n public long getRefreshInterval() {\n Long value = getSampleInterval();\n return Math.max(getMinRefreshInterval(), value);\n }\n\n public long getSampleInterval() {\n return sampleInterval;\n }\n\n public long getMinRefreshInterval() {\n return minRefreshInterval;\n }\n\n public RefreshableTimer setMinRefreshInterval(long minRefreshInterval) {\n this.minRefreshInterval = minRefreshInterval;\n return this;\n }\n}",
"public class ApplicationLimitsException extends ProxyResolutionException {\n public ApplicationLimitsException(String message) {\n super(message);\n }\n\n @SuppressWarnings(\"unused\")\n public ApplicationLimitsException(String message, Exception e) {\n super(message, e);\n }\n}",
"public class Part implements IPartComparable, Serializable, IRefreshableProxy {\n private static Logger logger = LoggerFactory.getLogger(Part.class);\n private static Pattern startLink = Pattern.compile(\"<a[^>]*href=\\\"\");\n private static Pattern endLink = Pattern.compile(\"\\\"\");\n protected List<String> sourceList;\n protected List<PartUsage> requiredParts;\n private PartUsage sourcePartUsage;\n private String id;\n private String title;\n private String titleCategory;\n private String vendor;\n private String project;\n private URL url;\n private String contentHash;\n private Double packageCost;\n private Double packageUnits;\n private RefreshableTimer refreshableTimer;\n private RuntimeException refreshException;\n private boolean isResolved;\n private Lock refreshLock = new ReentrantLock();\n\n public Part() {\n this(PartFactory.getInstance());\n }\n\n public Part(PartFactory partFactory) {\n this.requiredParts = new ArrayList<PartUsage>();\n this.refreshableTimer = new RefreshableTimer();\n if (partFactory != null) {\n setMinRefeshInterval(partFactory.getMinRefreshInterval());\n }\n }\n\n public Part(PartFactory partFactory, URL url, CachedUrlResolver urlResolver) {\n this(partFactory);\n setUrl(url);\n }\n\n public synchronized String getId() {\n String value = id;\n if (value == null) {\n if (sourcePartUsage != null && sourcePartUsage.getPart().isResolved()) {\n value = sourcePartUsage.getPart().getId();\n }\n }\n if (value == null && getRefreshException() != null) {\n value = \"ERROR\";\n }\n return value;\n }\n\n public synchronized Part setId(String id) {\n this.id = id;\n return this;\n }\n\n public URL getUrl() {\n return url;\n }\n\n public synchronized Part setUrl(URL url) {\n this.url = normalizeUrl(url);\n return this;\n }\n\n public URL normalizeUrl(URL url) {\n return url;\n }\n\n public synchronized URL getSourceUrl() {\n if (sourcePartUsage == null) {\n return url;\n }\n return sourcePartUsage.getPart().getUrl();\n }\n\n public synchronized double getPackageCost() {\n double cost = 0;\n\n if (packageCost == null) {\n if (sourcePartUsage != null && sourcePartUsage.getPart().isResolved()) {\n cost = sourcePartUsage.getCost();\n logger.debug(\"packageCost {} += {}\", id, cost);\n }\n for (PartUsage partUsage : requiredParts) {\n double partCost = partUsage.getQuantity() * partUsage.getPart().getUnitCost();\n logger.debug(\"packageCost {} += {} {}\", new Object[]{id, partUsage.getPart().getId(), partCost});\n cost += partCost;\n }\n } else {\n cost = packageCost;\n }\n\n return cost;\n }\n\n public synchronized Part setPackageCost(Double packageCost) {\n this.packageCost = packageCost;\n return this;\n }\n\n public synchronized double getPackageUnits() {\n double units = 1;\n if (packageUnits == null) {\n if (sourcePartUsage != null) {\n units = 1; // this part is abstract, so package units is always 1\n }\n } else {\n units = packageUnits;\n }\n return units;\n }\n\n public synchronized Part setPackageUnits(Double packageUnits) {\n if (packageUnits != null && packageUnits <= 0) {\n throw new IllegalArgumentException(\"package units cannot be zero or negative: \" + packageUnits);\n }\n this.packageUnits = packageUnits;\n return this;\n }\n\n public synchronized double getUnitCost() {\n return getPackageCost() / getPackageUnits();\n }\n\n protected List<String> parseListItemStrings(String ul) throws IOException {\n List<String> result = new ArrayList<String>();\n String[] liParts = ul.split(\"</li>\");\n for (String li : liParts) {\n String[] items = li.split(\"<li>\");\n result.add(items[1]);\n }\n return result;\n }\n\n protected URL parseLink(String value) throws MalformedURLException {\n String urlString = PartFactory.getInstance().scrapeText(value, startLink, endLink);\n try {\n return new URL(getUrl(), urlString);\n }\n catch (MalformedURLException e) {\n throw new MalformedURLException(value);\n }\n }\n\n protected Double parseQuantity(String value, Double defaultValue) {\n Double result = defaultValue;\n\n String[] phrases = value.split(\"\\\\(\");\n if (phrases.length > 1) {\n String quantity = phrases[phrases.length - 1].split(\"\\\\)\")[0];\n try {\n String[] fraction = quantity.split(\"/\");\n if (fraction.length > 1) {\n double numerator = Double.parseDouble(fraction[0]);\n double denominator = Double.parseDouble(fraction[1]);\n result = numerator / denominator;\n } else {\n result = Double.parseDouble(quantity);\n }\n }\n catch (NumberFormatException e) {\n // parenthetical text, not a quantity\n }\n }\n\n return result;\n }\n\n public synchronized String getTitle() {\n String value = title;\n if (value == null) {\n if (getRefreshException() != null) {\n value = getRefreshException().getMessage();\n } else if (sourcePartUsage != null && sourcePartUsage.getPart().isResolved()) {\n value = sourcePartUsage.getPart().getTitle();\n } else {\n value = getId();\n }\n }\n return value;\n }\n\n public synchronized Part setTitle(String title) {\n this.title = title == null ? null : title.trim();\n return this;\n }\n\n @Override\n public Part getPart() {\n return this;\n }\n\n @Override\n public int compareTo(IPartComparable that) {\n Part thatPart = that.getPart();\n URL url1 = getUrl();\n URL url2 = thatPart.getUrl();\n int cmp = url1.toString().compareTo(url2.toString());\n return cmp;\n }\n\n public synchronized String getVendor() {\n if (vendor == null) {\n if (sourcePartUsage != null && sourcePartUsage.getPart().isResolved()) {\n return sourcePartUsage.getVendor();\n } else {\n return getUrl().getHost();\n }\n }\n return vendor;\n }\n\n public synchronized Part setVendor(String vendor) {\n this.vendor = vendor;\n return this;\n }\n\n public synchronized List<PartUsage> getRequiredParts() {\n return Collections.unmodifiableList(requiredParts);\n }\n\n public synchronized String getProject() {\n return project == null ? getVendor() : project;\n }\n\n public synchronized Part setProject(String project) {\n this.project = project;\n return this;\n }\n\n /**\n * A simple assembly that consists solely of its constituent required parts.\n * Simple asseblies have no individual cost.\n *\n * @return true if this is an assembly\n */\n public boolean isAssembly() {\n return requiredParts.size() > 0;\n }\n\n public boolean isVendorPart() {\n return sourcePartUsage == null && requiredParts.size() == 0;\n }\n\n /**\n * An abstract part is one that defines the function of a part and\n * provides one or more sources for that part. Think of this as a \"hardware interface or api\"\n *\n * @return\n */\n public boolean isAbstractPart() {\n return sourcePartUsage != null;\n }\n\n @Override\n public final void refresh() {\n if (isFresh() && getAge() < getMinRefeshInterval() && getRefreshException() == null) {\n return; // avoid busy work\n }\n synchronized (refreshLock) {\n try {\n long msStart = System.currentTimeMillis();\n setRefreshException(null);\n refreshFromRemote();\n long msElapsed = System.currentTimeMillis() - msStart;\n validate(this, null);\n isResolved = true;\n logger.info(\"refreshed {} {} {}x{} {} {}ms\", new Object[]{id, packageCost, packageUnits, title, url, msElapsed});\n refreshableTimer.refresh();\n }\n catch (Exception e) {\n throw createRefreshException(e);\n }\n }\n }\n\n private RuntimeException createRefreshException(Exception e) {\n logger.warn(\"Could not refresh part {}\", getUrl(), e);\n if (e != getRefreshException()) {\n if (e instanceof ProxyResolutionException) {\n setRefreshException((ProxyResolutionException) e);\n } else {\n ProxyResolutionException proxyResolutionException = new ProxyResolutionException(e);\n setRefreshException(proxyResolutionException);\n }\n }\n\n // The refresh exception may be temporary, so the proxy is treated as \"fresh and resolved with error\"\n isResolved = true;\n sourceList = null;\n sourcePartUsage = null;\n requiredParts.clear();\n refreshableTimer.refresh();\n\n return getRefreshException();\n }\n\n public Part refreshAll() {\n refresh();\n for (PartUsage partUsage : requiredParts) {\n Part part = partUsage.getPart();\n part.refreshAll();\n }\n if (sourcePartUsage != null) {\n sourcePartUsage.getPart().refresh();\n }\n refresh();\n\n return this;\n }\n\n private void validate(Part part, Part rootPart) {\n if (part == rootPart) {\n rootPart.setRefreshException(new CyclicReferenceException(\"Cyclic part reference detected: \" + url));\n throw getRefreshException();\n } else if (rootPart == null) {\n rootPart = part;\n }\n if (part.sourcePartUsage != null) {\n validate(part.sourcePartUsage.getPart(), rootPart);\n }\n for (PartUsage partUsage : part.requiredParts) {\n validate(partUsage.getPart(), rootPart);\n }\n }\n\n protected void refreshFromRemote() throws Exception {\n String content = PartFactory.getInstance().urlTextContent(getUrl());\n refreshFromRemoteContent(content);\n }\n\n protected void refreshFromRemoteContent(String content) throws Exception {\n throw new RuntimeException(\"Not impelemented\");\n }\n\n @Override\n public synchronized boolean isFresh() {\n return refreshableTimer.isFresh();\n }\n\n public boolean isFresh(boolean deep) {\n if (!isFresh()) {\n logger.info(\"stale1 {}\", getUrl());\n return false;\n }\n if (deep) {\n if (sourcePartUsage != null && !sourcePartUsage.getPart().isFresh()) {\n logger.info(\"stale2 {}\", sourcePartUsage.getPart().getUrl());\n return false;\n }\n for (PartUsage partUsage : requiredParts) {\n Part part = partUsage.getPart();\n if (!part.isFresh()) {\n logger.info(\"stale3 {}\", part.getUrl());\n return false;\n }\n }\n }\n\n return true;\n }\n\n @Override\n public synchronized void sample() {\n refreshableTimer.sample();\n }\n\n public synchronized long getRefreshInterval() {\n return refreshableTimer.getRefreshInterval();\n }\n\n public synchronized long getAge() {\n return refreshableTimer.getAge();\n }\n\n @Override\n public String toString() {\n return getId() + \" \" + getUrl().toString();\n }\n\n public Part getSourcePart() {\n if (sourcePartUsage == null) {\n return null;\n }\n return sourcePartUsage.getPart();\n }\n\n public synchronized PartUsage getSourcePartUsage() {\n return sourcePartUsage;\n }\n\n public synchronized Part setSourcePartUsage(PartUsage sourcePartUsage) {\n this.sourcePartUsage = sourcePartUsage;\n return this;\n }\n\n public RuntimeException getRefreshException() {\n return refreshException;\n }\n\n public void setRefreshException(RuntimeException refreshException) {\n this.refreshException = refreshException;\n }\n\n public long getMinRefeshInterval() {\n return refreshableTimer.getMinRefreshInterval();\n }\n\n public void setMinRefeshInterval(long minRefeshInterval) {\n refreshableTimer.setMinRefreshInterval(minRefeshInterval);\n }\n\n public boolean isResolved() {\n return isResolved;\n }\n\n public String getContentHash() {\n return contentHash;\n }\n\n public String getTitleCategory() {\n return titleCategory;\n }\n\n public synchronized void setTitleCategory(String titleCategory) {\n this.titleCategory = titleCategory==null ? null : titleCategory.trim();\n }\n}",
"public class PartFactory implements Iterable<Part>, Runnable {\n public static long MIN_REFRESH_INTERVAL = 10000;\n private static Logger logger = LoggerFactory.getLogger(PartFactory.class);\n private static Thread worker;\n private static ConcurrentLinkedQueue<Part> refreshQueue = new ConcurrentLinkedQueue<Part>();\n private static PartFactory partFactory;\n private CachedUrlResolver urlResolver;\n private String accept;\n private String language;\n private String userAgent;\n private long urlRequests;\n private long networkRequests;\n private long minRefreshInterval = MIN_REFRESH_INTERVAL;\n\n protected PartFactory() {\n this(Locale.getDefault());\n }\n\n protected PartFactory(Locale locale) {\n this.urlResolver = new CachedUrlResolver(locale);\n }\n\n public static PartFactory getInstance() {\n if (partFactory == null) {\n partFactory = new PartFactory();\n }\n return partFactory;\n }\n\n public static String scrapeText(String value, Pattern start, Pattern end) {\n String result;\n Matcher startMatcher = start.matcher(value);\n if (!startMatcher.find()) {\n return null;\n }\n int iStart = startMatcher.end();\n\n Matcher endMatcher = end.matcher(value);\n if (!endMatcher.find(iStart)) {\n return null;\n }\n int iEnd = endMatcher.start();\n result = value.substring(iStart, iEnd);\n result = result.replaceAll(\"\\\\\\\\\\\"\", \"\\\"\");\n\n return result;\n }\n\n public static int estimateQuantity(double packageCost, double unitCost) {\n double highCost = unitCost + .005;\n double lowCost = unitCost - .005;\n int highQuantity = (int) Math.floor(packageCost / lowCost);\n int lowQuantity = (int) Math.ceil(packageCost / highCost);\n\n if (highQuantity == lowQuantity) {\n return highQuantity;\n }\n if (highQuantity == lowQuantity + 1) {\n return highQuantity % 2 == 0 ? highQuantity : lowQuantity; // even number is more likely\n }\n return (int) Math.round(packageCost / unitCost);\n }\n\n public List<Part> getRefreshQueue() {\n List<Part> list = new ArrayList<Part>();\n for (Part part : refreshQueue) {\n list.add(part);\n }\n return Collections.unmodifiableList(list);\n }\n\n public String urlTextContent(URL url) throws IOException {\n return urlResolver.get(url);\n }\n\n private Ehcache getCache(String name) {\n return CacheManager.getInstance().addCacheIfAbsent(name);\n }\n\n public Part createPart(URL url) {\n return createPart(url, urlResolver);\n }\n\n public Part createPart(URL url, CachedUrlResolver urlResolver) {\n Element cacheElement = getCache(\"org.firepick.firebom.part.Part\").get(url);\n Part part;\n if (cacheElement == null) {\n String host = url.getHost();\n part = createPartForHost(url, host, urlResolver);\n cacheElement = new Element(url, part);\n getCache(\"org.firepick.firebom.part.Part\").put(cacheElement);\n refreshQueue.add(part);\n } else {\n part = (Part) cacheElement.getObjectValue();\n part.sample();\n if (!part.isFresh() && !refreshQueue.contains(part)) {\n refreshQueue.add(part);\n }\n }\n if (worker == null) {\n worker = new Thread(this);\n worker.start();\n }\n return part;\n }\n\n private Part createPartForHost(URL url, String host, CachedUrlResolver urlResolver) {\n Part part;\n if (\"www.shapeways.com\".equalsIgnoreCase(host)) {\n part = new ShapewaysPart(this, url, urlResolver);\n } else if (\"shpws.me\".equalsIgnoreCase(host)) {\n part = new ShapewaysPart(this, url, urlResolver);\n } else if (\"www.mcmaster.com\".equalsIgnoreCase(host)) {\n part = new McMasterCarrPart(this, url, urlResolver);\n } else if (\"github.com\".equalsIgnoreCase(host)) {\n part = new GitHubPart(this, url, urlResolver);\n } else if (\"us.misumi-ec.com\".equalsIgnoreCase(host)) {\n part = new MisumiPart(this, url, urlResolver);\n } else if (\"www.inventables.com\".equalsIgnoreCase(host)) {\n part = new InventablesPart(this, url, urlResolver);\n } else if (\"www.ponoko.com\".equalsIgnoreCase(host)) {\n part = new PonokoPart(this, url, urlResolver);\n } else if (\"www.amazon.com\".equalsIgnoreCase(host)) {\n part = new AmazonPart(this, url, urlResolver);\n } else if (\"trinitylabs.com\".equalsIgnoreCase(host)) {\n part = new TrinityLabsPart(this, url, urlResolver);\n } else if (\"mock\".equalsIgnoreCase(host)) {\n part = new MockPart(this, url, urlResolver);\n } else if (\"www.sparkfun.com\".equalsIgnoreCase(host)) {\n part = new SparkfunPart(this, url, urlResolver);\n } else if (\"www.adafruit.com\".equalsIgnoreCase(host)) {\n part = new AdafruitPart(this, url, urlResolver);\n } else if (\"www.digikey.com\".equalsIgnoreCase(host)) {\n part = new DigiKeyPart(this, url, urlResolver);\n } else if (\"synthetos.myshopify.com\".equalsIgnoreCase(host)) {\n part = new SynthetosPart(this, url, urlResolver);\n } else {\n part = new HtmlPart(this, url, urlResolver);\n }\n return part;\n }\n\n @Override\n public ListIterator<Part> iterator() {\n Ehcache cache = getCache(\"org.firepick.firebom.part.Part\");\n return new CacheIterator(cache);\n }\n\n @Override\n public void run() {\n while (refreshQueue.size() > 0) {\n Part part = refreshQueue.poll();\n if (part != null && !part.isFresh()) {\n try {\n part.refresh();\n }\n catch (Exception e) {\n if (e != part.getRefreshException()) {\n throw new ProxyResolutionException(\"Uncaught exception\", e);\n }\n }\n }\n }\n worker = null;\n }\n\n public long getMinRefreshInterval() {\n return minRefreshInterval;\n }\n\n public PartFactory setMinRefreshInterval(long minRefreshInterval) {\n this.minRefreshInterval = minRefreshInterval;\n return this;\n }\n\n public class CacheIterator implements ListIterator<Part> {\n ListIterator<URL> listIterator;\n Ehcache ehcache;\n\n public CacheIterator(Ehcache ehcache) {\n this.listIterator = ehcache.getKeys().listIterator();\n this.ehcache = ehcache;\n }\n\n @Override\n public boolean hasNext() {\n return listIterator.hasNext();\n }\n\n @Override\n public Part next() {\n return (Part) ehcache.get(listIterator.next()).getObjectValue();\n }\n\n @Override\n public boolean hasPrevious() {\n return listIterator.hasPrevious();\n }\n\n @Override\n public Part previous() {\n return (Part) ehcache.get(listIterator.previous()).getObjectValue();\n }\n\n @Override\n public int nextIndex() {\n return listIterator.nextIndex();\n }\n\n @Override\n public int previousIndex() {\n return listIterator.previousIndex();\n }\n\n @Override\n public void remove() {\n throw new UnsupportedOperationException();\n }\n\n @Override\n public void set(Part part) {\n throw new UnsupportedOperationException();\n }\n\n @Override\n public void add(Part part) {\n throw new UnsupportedOperationException();\n }\n }\n}",
"public interface IColumnDescription<T> extends Cloneable {\n String getTitle();\n String getId();\n Format getFormat();\n int getItemIndex();\n IAggregator<T> getAggregator();\n}",
"public interface IRelation extends Iterable<IRow> {\n List<IColumnDescription> describeColumns();\n long getRowCount();\n}",
"public interface IRow {\n IRelation getRelation();\n Object item(int index);\n}"
] | import java.util.concurrent.ConcurrentSkipListSet;
import org.firepick.firebom.IPartComparable;
import org.firepick.firebom.IRefreshableProxy;
import org.firepick.firebom.RefreshableTimer;
import org.firepick.firebom.exception.ApplicationLimitsException;
import org.firepick.firebom.part.Part;
import org.firepick.firebom.part.PartFactory;
import org.firepick.relation.IColumnDescription;
import org.firepick.relation.IRelation;
import org.firepick.relation.IRow;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.URL;
import java.util.*; | package org.firepick.firebom.bom;
/*
BOM.java
Copyright (C) 2013 Karl Lew <[email protected]>. All rights reserved.
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.
*/
public class BOM implements IRelation, IRefreshableProxy {
public final static String UNRESOLVED = "(Processing...)";
private static Logger logger = LoggerFactory.getLogger(BOM.class);
private List<IColumnDescription> columnDescriptions;
private ConcurrentSkipListSet<IPartComparable> rows = new ConcurrentSkipListSet<IPartComparable>();
private int maximumParts;
private Map<BOMColumn, BOMColumnDescription> columnMap = new HashMap<BOMColumn, BOMColumnDescription>();
private URL url;
private String title;
private RefreshableTimer refreshableTimer = new RefreshableTimer(); | private Part rootPart; | 4 |
ktisha/Crucible4IDEA | src/com/jetbrains/crucible/ui/toolWindow/CruciblePanel.java | [
"public class CrucibleManager {\n private final Project myProject;\n private final Map<String, CrucibleSession> mySessions = new HashMap<String, CrucibleSession>();\n\n private static final Logger LOG = Logger.getInstance(CrucibleManager.class.getName());\n\n // implicitly constructed by pico container\n @SuppressWarnings(\"UnusedDeclaration\")\n private CrucibleManager(@NotNull final Project project) {\n myProject = project;\n }\n\n public static CrucibleManager getInstance(@NotNull final Project project) {\n return ServiceManager.getService(project, CrucibleManager.class);\n }\n\n @Nullable\n public List<BasicReview> getReviewsForFilter(@NotNull final CrucibleFilter filter) {\n try {\n final CrucibleSession session = getSession();\n if (session != null) {\n return session.getReviewsForFilter(filter);\n }\n }\n catch (IOException e) {\n LOG.warn(e.getMessage());\n UiUtils.showBalloon(myProject, CrucibleBundle.message(\"crucible.connection.error.message.$0\", e.getMessage()), MessageType.ERROR);\n }\n catch (CrucibleApiException e) {\n LOG.warn(e.getMessage());\n UiUtils.showBalloon(myProject, CrucibleBundle.message(\"crucible.connection.error.message.$0\", e.getMessage()), MessageType.ERROR);\n }\n return null;\n }\n\n @Nullable\n public Review getDetailsForReview(@NotNull final String permId) {\n try {\n final CrucibleSession session = getSession();\n if (session != null) {\n return session.getDetailsForReview(permId);\n }\n }\n catch (CrucibleApiException e) {\n LOG.warn(e.getMessage());\n UiUtils.showBalloon(myProject, CrucibleBundle.message(\"crucible.connection.error.message.$0\", e.getMessage()), MessageType.ERROR);\n\n }\n catch (IOException e) {\n LOG.warn(e.getMessage());\n UiUtils.showBalloon(myProject, CrucibleBundle.message(\"crucible.connection.error.message.$0\", e.getMessage()), MessageType.ERROR);\n }\n return null;\n }\n\n @Nullable\n public Comment postComment(@NotNull final Comment comment, boolean isGeneral, String reviewId) {\n try {\n final CrucibleSession session = getSession();\n if (session != null) {\n return session.postComment(comment, isGeneral, reviewId);\n }\n }\n catch (CrucibleApiException e) {\n LOG.warn(e.getMessage());\n UiUtils.showBalloon(myProject, CrucibleBundle.message(\"crucible.connection.error.message.$0\", e.getMessage()), MessageType.ERROR);\n }\n return null;\n }\n\n public void completeReview(String reviewId) {\n try {\n final CrucibleSession session = getSession();\n if (session != null) {\n session.completeReview(reviewId);\n }\n }\n catch (CrucibleApiException e) {\n LOG.warn(e.getMessage());\n UiUtils.showBalloon(myProject, CrucibleBundle.message(\"crucible.connection.error.message.$0\", e.getMessage()), MessageType.ERROR);\n }\n }\n\n @Nullable\n public CrucibleSession getSession() throws CrucibleApiException {\n final CrucibleSettings crucibleSettings = CrucibleSettings.getInstance();\n final String serverUrl = crucibleSettings.SERVER_URL;\n final String username = crucibleSettings.USERNAME;\n if (StringUtil.isEmptyOrSpaces(serverUrl) || StringUtil.isEmptyOrSpaces(username)) {\n UiUtils.showBalloon(myProject, CrucibleBundle.message(\"crucible.define.host.username\"), MessageType.ERROR);\n return null;\n }\n try {\n new URL(serverUrl);\n }\n catch (MalformedURLException e) {\n UiUtils.showBalloon(myProject, CrucibleBundle.message(\"crucible.wrong.host\"), MessageType.ERROR);\n return null;\n }\n String key = serverUrl + username + crucibleSettings.getPassword();\n CrucibleSession session = mySessions.get(key);\n if (session == null) {\n session = new CrucibleSessionImpl(myProject);\n session.login();\n mySessions.put(key, session);\n try {\n session.fillRepoHash();\n }\n catch (IOException e) {\n LOG.warn(e.getMessage());\n }\n }\n return session;\n }\n\n public Map<String,VirtualFile> getRepoHash() {\n try {\n final CrucibleSession session = getSession();\n if (session != null) {\n return session.getRepoHash();\n }\n }\n catch (CrucibleApiException e) {\n LOG.warn(e.getMessage());\n }\n return Collections.emptyMap();\n }\n\n public void publishComment(@NotNull Review review, @NotNull Comment comment) throws IOException, CrucibleApiException {\n CrucibleSession session = getSession();\n if (session != null) {\n session.publishComment(review, comment);\n }\n }\n}",
"public class Review extends BasicReview {\n private final List<Comment> myGeneralComments = new ArrayList<Comment>();\n private final List<Comment> myComments = new ArrayList<Comment>();\n\n private final Set<ReviewItem> myItems = new HashSet<ReviewItem>();\n\n public Review(@NotNull final String id, @NotNull final User author,\n @Nullable final User moderator) {\n super(id, author, moderator);\n }\n\n public void addGeneralComment(@NotNull Comment generalComment) {\n myGeneralComments.add(generalComment);\n }\n\n public void addComment(@NotNull Comment comment) {\n myComments.add(comment);\n }\n\n @NotNull\n public List<Comment> getGeneralComments() {\n return myGeneralComments;\n }\n\n @NotNull\n public List<Comment> getComments() {\n return myComments;\n }\n\n @NotNull\n public Set<ReviewItem> getReviewItems() {\n return myItems;\n }\n\n public void addReviewItem(@NotNull final ReviewItem item) {\n myItems.add(item);\n }\n\n @Nullable\n public String getPathById(@NotNull final String id) {\n for (ReviewItem item : myItems) {\n if (item.getId().equals(id))\n return item.getPath();\n }\n return null;\n }\n\n @Nullable\n public String getIdByPath(@NotNull final String path, Project project) {\n final Map<String,VirtualFile> hash = CrucibleManager.getInstance(project).getRepoHash();\n\n for (ReviewItem item : myItems) {\n final String repo = item.getRepo();\n final String root = hash.containsKey(repo) ? hash.get(repo).getPath() : project.getBasePath();\n String relativePath = FileUtil.getRelativePath(new File(Objects.requireNonNull(root)), new File(path));\n if (FileUtil.pathsEqual(relativePath, item.getPath())) {\n return item.getId();\n }\n }\n return null;\n }\n\n public boolean isInPatch(@NotNull Comment comment) {\n final String reviewItemId = comment.getReviewItemId();\n return null != ContainerUtil.find(myItems, new Condition<ReviewItem>() {\n @Override\n public boolean value(ReviewItem item) {\n return item.getId().equalsIgnoreCase(reviewItemId) && item.isPatch();\n }\n });\n }\n}",
"public class ReviewItem {\n\n private String myId;\n private String myPath;\n private String myRepo;\n private Set<String> myRevisions = new HashSet<String>();\n\n public ReviewItem(@NotNull final String id, @NotNull final String path, @Nullable final String repo) {\n myId = id;\n myPath = path;\n myRepo = repo;\n }\n\n @NotNull\n public List<CommittedChangeList> loadChangeLists(@NotNull Project project, @NotNull AbstractVcs vcsFor,\n @NotNull Set<String> loadedRevisions, FilePath path) throws VcsException {\n final Set<String> revisions = getRevisions();\n List<CommittedChangeList> changeLists = new ArrayList<CommittedChangeList>();\n for (String revision : revisions) {\n if (!loadedRevisions.contains(revision)) {\n final VcsRevisionNumber revisionNumber = vcsFor.parseRevisionNumber(revision);\n if (revisionNumber != null) {\n final CommittedChangeList changeList = VcsUtils.loadRevisions(project, revisionNumber, path);\n if (changeList != null) changeLists.add(changeList);\n }\n loadedRevisions.add(revision);\n }\n }\n return changeLists;\n }\n\n @NotNull\n public String getRepo() {\n return myRepo;\n }\n\n @NotNull\n public String getPath() {\n return myPath;\n }\n\n @NotNull\n public String getId() {\n return myId;\n }\n\n public void addRevision(@NotNull final String revision) {\n myRevisions.add(revision);\n }\n\n @NotNull\n public Set<String> getRevisions() {\n return myRevisions;\n }\n\n public boolean isPatch() {\n return false;\n }\n}",
"public class DescriptionCellRenderer extends DefaultTableCellRenderer {\n public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,\n int row, int column) {\n JLabel label = (JLabel)super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);\n final String text = label.getText();\n label.setToolTipText(\"<html>\" + text + \"</html>\");\n return label;\n }\n}",
"public class DetailsPanel extends SimpleToolWindowPanel {\n\n private static final String GENERAL_COMMENTS_VISIBILITY_PROPERTY = \"CodeReview.GeneralComments.Visible\";\n private static final String COMMITS_COMMENTS_SPLITTER_PROPERTY = \"CodeReview.CommitsCommentsSplitter.Proportion\";\n\n private final Project myProject;\n private final Review myReview;\n private final CrucibleSettings myCrucibleSettings = CrucibleSettings.getInstance();\n private ChangesBrowser myChangesBrowser;\n private JBTable myCommitsTable;\n private DefaultTableModel myCommitsModel;\n private JTree myGeneralComments;\n private JPanel myCommentsPane;\n\n public DetailsPanel(@NotNull final Project project, @NotNull final Review review) {\n super(false);\n myProject = project;\n myReview = review;\n\n final Splitter splitter = new Splitter(false, 0.7f);\n final JPanel mainTable = createMainTable();\n splitter.setFirstComponent(mainTable);\n\n final JComponent repoBrowser = createRepositoryBrowserDetails();\n splitter.setSecondComponent(repoBrowser);\n\n setContent(splitter);\n\n myChangesBrowser.getDiffAction().registerCustomShortcutSet(CommonShortcuts.getDiff(), myCommitsTable);\n\n myCommentsPane.setVisible(PropertiesComponent.getInstance().getBoolean(GENERAL_COMMENTS_VISIBILITY_PROPERTY, false));\n }\n\n // Make changes available for diff action\n @Nullable\n public Object getData(@NonNls String dataId) {\n TypeSafeDataProviderAdapter adapter = new TypeSafeDataProviderAdapter(myChangesBrowser);\n Object data = adapter.getData(dataId);\n return data != null ? data : super.getData(dataId);\n }\n\n public void updateCommitsList(final @NotNull List<CommittedChangeList> changeLists) {\n for (CommittedChangeList committedChangeList : changeLists) {\n myCommitsModel.addRow(new Object[]{committedChangeList, committedChangeList.getCommitterName(), committedChangeList.getCommitDate()});\n }\n\n if (myCommitsTable.getRowCount() > 0) {\n myCommitsTable.setRowSelectionInterval(0, 0);\n }\n }\n\n public void setBusy(boolean busy) {\n myCommitsTable.setPaintBusy(busy);\n }\n\n @NotNull\n private JPanel createMainTable() {\n final JPanel commitsPane = createCommitsPane();\n\n myCommentsPane = createCommentsPane();\n\n final JBSplitter splitter = new JBSplitter(true, 0.5f);\n splitter.setSplitterProportionKey(COMMITS_COMMENTS_SPLITTER_PROPERTY);\n splitter.setFirstComponent(commitsPane);\n splitter.setSecondComponent(myCommentsPane);\n myCommentsPane.setVisible(false);\n return splitter;\n }\n\n @NotNull\n private JPanel createCommentsPane() {\n myGeneralComments = GeneralCommentsTree.create(myProject, myReview);\n return installActions();\n }\n\n @NotNull\n private JPanel installActions() {\n final DefaultActionGroup actionGroup = new DefaultActionGroup();\n final AddCommentAction addCommentAction = new AddCommentAction(myReview, null, null,\n CrucibleBundle.message(\"crucible.add.comment\"), false);\n addCommentAction.setContextComponent(myGeneralComments);\n actionGroup.add(addCommentAction);\n\n final AddCommentAction replyToCommentAction = new AddCommentAction(myReview, null, null,\n CrucibleBundle.message(\"crucible.reply\"), true);\n replyToCommentAction.setContextComponent(myGeneralComments);\n actionGroup.add(replyToCommentAction);\n\n final ActionPopupMenu actionPopupMenu = ActionManager.getInstance().createActionPopupMenu(CrucibleBundle.message(\"crucible.main.name\"),\n actionGroup);\n final JPopupMenu popupMenu = actionPopupMenu.getComponent();\n myGeneralComments.setComponentPopupMenu(popupMenu);\n\n final Border border = IdeBorderFactory.createTitledBorder(CrucibleBundle.message(\"crucible.general.comments\"), false);\n final ToolbarDecorator decorator = ToolbarDecorator.createDecorator(myGeneralComments).\n setToolbarPosition(ActionToolbarPosition.LEFT);\n decorator.addExtraAction(addCommentAction);\n decorator.addExtraAction(replyToCommentAction);\n\n final JPanel decoratedPanel = decorator.createPanel();\n decoratedPanel.setBorder(border);\n return decoratedPanel;\n }\n\n @NotNull\n private JPanel createCommitsPane() {\n @SuppressWarnings(\"UseOfObsoleteCollectionType\")\n final Vector<String> commitColumnNames = new Vector<String>();\n commitColumnNames.add(CrucibleBundle.message(\"crucible.commit\"));\n commitColumnNames.add(CrucibleBundle.message(\"crucible.author\"));\n commitColumnNames.add(CrucibleBundle.message(\"crucible.date\"));\n\n //noinspection UseOfObsoleteCollectionType\n myCommitsModel = new DefaultTableModel(new Vector(), commitColumnNames) {\n @Override\n public boolean isCellEditable(int row, int column) {\n return false;\n }\n\n @Override\n public Class<?> getColumnClass(int columnIndex) {\n if (columnIndex == 0) return CommittedChangeList.class;\n if (columnIndex == 2) return Date.class;\n return String.class;\n }\n };\n\n myCommitsTable = new JBTable(myCommitsModel) {\n @Override\n public TableCellRenderer getCellRenderer(int row, int column) {\n if (column == myCommitsTable.getColumnModel().getColumnIndex(CrucibleBundle.message(\"crucible.commit\"))) {\n return new MyCommitsCellRenderer();\n }\n return super.getCellRenderer(row, column);\n }\n };\n myCommitsTable.setStriped(true);\n myCommitsTable.setAutoCreateRowSorter(true);\n myCommitsTable.setExpandableItemsEnabled(false);\n setUpColumnWidths(myCommitsTable);\n\n final ToolbarDecorator decorator = ToolbarDecorator.createDecorator(myCommitsTable).setToolbarPosition(ActionToolbarPosition.LEFT);\n\n if (myReview.isReviewer(new User(myCrucibleSettings.USERNAME)) && \"Review\".equals(myReview.getState())) {\n decorator.addExtraAction(new CompleteReviewAction(myReview, CrucibleBundle.message(\"crucible.complete.review\")));\n }\n decorator.addExtraAction(new ShowGeneralCommentsAction());\n decorator.addExtraAction(new OpenInBrowserAction());\n\n return decorator.createPanel();\n }\n\n public static void setUpColumnWidths(@NotNull final JBTable table) {\n final TableColumnModel columnModel = table.getColumnModel();\n columnModel.getColumn(0).setMinWidth(400); //message\n columnModel.getColumn(0).setPreferredWidth(400); //message\n columnModel.getColumn(1).setMinWidth(200); //Author\n columnModel.getColumn(1).setMaxWidth(200); //Author\n columnModel.getColumn(2).setMinWidth(130); //Date\n columnModel.getColumn(2).setMaxWidth(130); //Date\n }\n\n @NotNull\n private JComponent createRepositoryBrowserDetails() {\n myChangesBrowser = new MyChangesBrowser(myProject);\n\n myChangesBrowser.getDiffAction().registerCustomShortcutSet(CommonShortcuts.getDiff(), myCommitsTable);\n myChangesBrowser.getViewer().setBorder(IdeBorderFactory.createBorder(SideBorder.LEFT | SideBorder.TOP));\n\n myCommitsTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {\n @Override\n public void valueChanged(ListSelectionEvent e) {\n final int[] indices = myCommitsTable.getSelectedRows();\n List<Change> changes = new ArrayList<Change>();\n for (int i : indices) {\n changes.addAll(((CommittedChangeList)myCommitsModel.getValueAt(i, 0)).getChanges());\n }\n myChangesBrowser.setChangesToDisplay(changes);\n }\n });\n return myChangesBrowser;\n }\n\n\n static class MyCommitsCellRenderer extends DefaultTableCellRenderer {\n\n @Override\n public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {\n final Component orig = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);\n final Color bg = orig.getBackground();\n if (value instanceof CommittedChangeList) {\n final String text = ((CommittedChangeList)value).getName();\n\n setText(\"<html>\" + text + \"</html>\");\n setToolTipText(text);\n }\n setBackground(bg);\n setBorder(BorderFactory.createLineBorder(bg));\n return this;\n }\n }\n\n class MyChangesBrowser extends ChangesBrowser {\n public MyChangesBrowser(Project project) {\n super(project, Collections.<CommittedChangeList>emptyList(),\n Collections.<Change>emptyList(), null, false, false, null,\n ChangesBrowser.MyUseCase.COMMITTED_CHANGES, null);\n }\n\n protected void buildToolBar(final DefaultActionGroup toolBarGroup) {\n super.buildToolBar(toolBarGroup);\n toolBarGroup.add(new ShowDiffWithLocalAction());\n final OpenRepositoryVersionAction action = new OpenRepositoryVersionAction();\n toolBarGroup.add(action);\n\n final ActionGroup group = (ActionGroup)ActionManager.getInstance().getAction(\"RepositoryChangesBrowserToolbar\");\n final AnAction[] actions = group.getChildren(null);\n for (AnAction anAction : actions) {\n toolBarGroup.add(anAction);\n }\n }\n\n @Override\n public void calcData(DataKey key, DataSink sink) {\n if (key == VcsDataKeys.SELECTED_CHANGES) {\n final List<Change> list = myViewer.getSelectedChanges();\n sink.put(VcsDataKeys.SELECTED_CHANGES, list.toArray(new Change[list.size()]));\n }\n super.calcData(key, sink);\n }\n\n @Override\n protected void updateDiffContext(@NotNull ShowDiffContext context) {\n context.putChainContext(CrucibleUserDataKeys.REVIEW, myReview);\n }\n }\n\n private class ShowGeneralCommentsAction extends AnActionButton {\n public ShowGeneralCommentsAction() {\n super(CrucibleBundle.message(\"crucible.show.general.comments\"), CrucibleBundle.message(\"crucible.show.general.comments\"),\n AllIcons.Actions.Preview);\n }\n\n @Override\n public void actionPerformed(AnActionEvent e) {\n boolean visibility = !myCommentsPane.isVisible();\n myCommentsPane.setVisible(visibility);\n PropertiesComponent.getInstance().setValue(GENERAL_COMMENTS_VISIBILITY_PROPERTY, Boolean.toString(visibility));\n }\n }\n\n private class OpenInBrowserAction extends AnActionButton {\n public OpenInBrowserAction() {\n super(CrucibleBundle.message(\"crucible.open.in.browser\"), CrucibleBundle.message(\"crucible.open.in.browser\"),\n AllIcons.Nodes.PpWeb);\n }\n\n @Override\n public void actionPerformed(@NotNull AnActionEvent event) {\n String serverUrl = myCrucibleSettings.SERVER_URL;\n BrowserUtil.open(serverUrl + \"/cru/\" + myReview.getPermaId());\n }\n }\n}",
"public class CrucibleRootNode extends SimpleNode {\n private static final String NAME = \"All My Reviews\";\n private final CrucibleReviewModel myReviewModel;\n private final List<SimpleNode> myChildren = new ArrayList<SimpleNode>();\n\n public CrucibleRootNode(@NotNull final CrucibleReviewModel reviewModel) {\n myReviewModel = reviewModel;\n addChildren();\n }\n\n @NotNull\n public String toString() {\n return NAME;\n }\n\n @Override\n public SimpleNode[] getChildren() {\n if (myChildren.isEmpty()) {\n addChildren();\n }\n return myChildren.toArray(new SimpleNode[myChildren.size()]);\n }\n\n private void addChildren() {\n for (CrucibleFilter filter : CrucibleFilter.values()) {\n myChildren.add(new CrucibleFilterNode(myReviewModel, filter));\n }\n }\n}",
"public class CrucibleTreeModel extends DefaultTreeModel {\n\n public CrucibleTreeModel() {\n super(new DefaultMutableTreeNode(), false);\n }\n}",
"public class CrucibleBundle {\n private static Reference<ResourceBundle> ourBundle;\n\n @NonNls\n private static final String BUNDLE = \"com.jetbrains.crucible.utils.CrucibleBundle\";\n\n private CrucibleBundle() {}\n\n public static String message(@PropertyKey(resourceBundle = BUNDLE)String key, Object... params) {\n return AbstractBundle.message(getBundle(), key, params);\n }\n\n private static ResourceBundle getBundle() {\n ResourceBundle bundle = null;\n if (ourBundle != null) bundle = ourBundle.get();\n if (bundle == null) {\n bundle = ResourceBundle.getBundle(BUNDLE);\n ourBundle = new SoftReference<ResourceBundle>(bundle);\n }\n return bundle;\n }\n}"
] | import com.intellij.ide.util.treeView.AbstractTreeBuilder;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.SimpleToolWindowPanel;
import com.intellij.openapi.vcs.AbstractVcs;
import com.intellij.openapi.vcs.LocalFilePath;
import com.intellij.openapi.vcs.ProjectLevelVcsManager;
import com.intellij.openapi.vcs.VcsException;
import com.intellij.openapi.vcs.versionBrowser.CommittedChangeList;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.openapi.wm.ToolWindowManager;
import com.intellij.ui.JBSplitter;
import com.intellij.ui.ScrollPaneFactory;
import com.intellij.ui.content.Content;
import com.intellij.ui.content.ContentFactory;
import com.intellij.ui.content.ContentManager;
import com.intellij.ui.table.JBTable;
import com.intellij.ui.treeStructure.SimpleTree;
import com.intellij.ui.treeStructure.SimpleTreeStructure;
import com.intellij.vcsUtil.VcsUtil;
import com.jetbrains.crucible.connection.CrucibleManager;
import com.jetbrains.crucible.model.Review;
import com.jetbrains.crucible.model.ReviewItem;
import com.jetbrains.crucible.ui.DescriptionCellRenderer;
import com.jetbrains.crucible.ui.toolWindow.details.DetailsPanel;
import com.jetbrains.crucible.ui.toolWindow.tree.CrucibleRootNode;
import com.jetbrains.crucible.ui.toolWindow.tree.CrucibleTreeModel;
import com.jetbrains.crucible.utils.CrucibleBundle;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import javax.swing.table.TableColumnModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
import javax.swing.tree.DefaultTreeModel;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.*; | package com.jetbrains.crucible.ui.toolWindow;
/**
* User: ktisha
* <p/>
* Main code review panel
*/
public class CruciblePanel extends SimpleToolWindowPanel {
private static final Logger LOG = Logger.getInstance(CruciblePanel.class.getName());
private final Project myProject;
private final CrucibleReviewModel myReviewModel;
private final JBTable myReviewTable;
public CrucibleReviewModel getReviewModel() {
return myReviewModel;
}
public CruciblePanel(@NotNull final Project project) {
super(false);
myProject = project;
final JBSplitter splitter = new JBSplitter(false, 0.2f);
myReviewModel = new CrucibleReviewModel(project);
myReviewTable = new JBTable(myReviewModel);
myReviewTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
myReviewTable.setStriped(true);
myReviewTable.setExpandableItemsEnabled(false);
final TableColumnModel columnModel = myReviewTable.getColumnModel(); | columnModel.getColumn(1).setCellRenderer(new DescriptionCellRenderer()); | 3 |
Beloumi/PeaFactory | src/peafactory/gui/TextTypePanel.java | [
"public final class PeaFactory {\n\n\t// i18n: \t\n\tprivate static String language; \n\tprivate static Locale currentLocale;\n\tprivate static Locale defaultLocale = Locale.getDefault();\n\tprivate static ResourceBundle languageBundle;\n\tpublic static final Charset UTF_8 = Charset.forName(\"UTF-8\");\n\t\n\tprivate static String os = null;\n\n\tprivate static MainView frame;\n\t\n\tprivate static String version = \"Peafactory version 0.0\";\n\t\n\tprivate final static String packagePathName = \"cologne\" + File.separator + \"eck\" + File.separator + \"peafactory\";\n\t\n\t// default algos:\n\tprivate static final KeyDerivation DEFAULT_KDF = new CatenaKDF();\n\tprivate static final Digest DEFAULT_HASH = new SkeinDigest(512, 512);\n\tprivate static final BlockCipher DEFAULT_CIPHER = new TwofishEngine();\n\t\n\tpublic static void main(String[] args) throws MalformedURLException {\t\t\n\t\t\n\t\tos = System.getProperty(\"os.name\");\n\t\t\n\t\tboolean testMode = false;\n\t\tif (args.length > 0) {\n\t\t\tif (args[0] != null) {\n\t\t\t\tif(args[0].equals(\"-r\")){\n\t\t\t\t\tSystem.out.println(\"Rescue mode only works for PEAs, not for PeaFactory...\");\n\t\t\t\t} else if(args[0].equals(\"-t\")){\n\t\t\t\t\tSystem.out.println(\"#####---TEST MODE---#####\");\n\t\t\t\t\ttestMode = true;\n\t\t\t\t} else {\n\t\t\t\t\tSystem.out.println(\"Unknown argument: \" + args[0]);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (testMode == true) {\n\t\t\t\n\t\t\tnew TestMode().runInTestMode();\n\t\t}\n\t\t\n\t\t// i18n: \n\t language = defaultLocale.getLanguage(); // get default language\n\t currentLocale = new Locale(language); // set default language as language\n\n\t //File file = new File(\"src\" + File.separator + \"config\" + File.separator + \"i18n\");\n\t File file = new File(\"config\" + File.separator + \"i18n\"); \n\t URL[] urls = {file.toURI().toURL()}; \n\t ClassLoader loader = new URLClassLoader(urls); \n\t languageBundle = ResourceBundle.getBundle(\"LanguagesBundle\", currentLocale, loader); \n \n\t // DEFAULT HASH FUNCTION: \n\t if (HashStuff.getHashAlgo() == null) { // needed for RandomPasswordDialog\n\t \tHashStuff.setHashAlgo( DEFAULT_HASH );\n\t }\n\t\tEventQueue.invokeLater(new Runnable() {\n\t\t\tpublic void run() {\n\t\t\t\ttry {\t\t\n\t\t\t\t\t\n\t\t\t\t\tPswDialogView.setUI();\n\t\t\t\t\t\n\t\t\t\t\t// select the kind of pea\n\t\t\t\t\tProjectSelection proj = new ProjectSelection();\n\t\t\t\t\tproj.setLocation( 100, 100 );\n\t\t\t\t\tproj.setVisible(true);\n\n\t\t\t\t\tframe = MainView.getInstance();\n\n\t\t\t\t} catch (Exception e) {\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n\t\n\tpublic final static void createFile() {\n\n\t\t//=====================\n\t\t// initialize (order!)\n\t\t//\n\t if (HashStuff.getHashAlgo() == null) {\n\t \tHashStuff.setHashAlgo( DEFAULT_HASH );// default\n\t }\n\t if (CipherStuff.isBound() == true){\n\t \tAttachments.generateAndSetProgramRandomBytes();\n\t \tAttachments.generateAndSetFileIdentifier();\t\n\t\t\tKeyDerivation.setSalt(Attachments.getProgramRandomBytes() );\n\t } else {\n\t \t// use default values for fileIdentifier and programRandomBytes\n\t \t// calculate default salt and update via setAttachedSalt: \n\t \t// xor the salt with attachedSalt (will be attached to the content)\n\t \tAttachments.setFileIdentifier(\"PFACTORY\".getBytes(UTF_8)); // 8 byte\n\t \t// 129 byte string to initialize the salt: \n\t \tString fixedSaltString = \"PEAFACTORY - PRODUCTION OF PASSWORD ENCRYPTED ARCHIVES - FIXED STRING USED TO INITIALIZE THE SALT FOR THE KEY DERIVATION FUNCTION\";\n\t \tString saltString = fixedSaltString.substring(0, KeyDerivation.getSaltSize() );\n\t \tAttachments.setProgramRandomBytes(saltString.getBytes(UTF_8));\n\t\t\tKeyDerivation.setSalt(saltString.getBytes(UTF_8));\n\n\t\t byte[] attachedSalt = new RandomStuff().createRandomBytes(Attachments.getProgramRandomBytesSize());\n\t\t KeyDerivation.setAttachedAndUpdateSalt(attachedSalt);\n\t }\n\t \n\t // DEFAULT CIPHER ALGO: \n\t if (CipherStuff.getCipherAlgo() == null) {\n\t \tCipherStuff.setCipherAlgo( DEFAULT_CIPHER );\n\t }\n\t // DEFAULT KEY DERIVATION FUNCTION\n\t if (KeyDerivation.getKdf() == null) {\n\t \tKeyDerivation.setKdf( DEFAULT_KDF );\n\t }\n\n\t\t//======================================\n\t\t// get password from pswField and check:\n\t\t//\n\t\tchar[] pswInputChars = MainView.getPsw();\t\n\t\tMainView.resetPsw();\n\t\tchar[] pswInputChars2 = MainView.getPsw2();\n\t\tMainView.resetPsw2();\n\t\t\n\t\tif ( ( pswInputChars2.length == 0) && ( pswInputChars.length != 0)) {\n\t\t\tJOptionPane.showMessageDialog(null, languageBundle.getString(\"password2_is_null\"), null, JOptionPane.PLAIN_MESSAGE);\n\t\t\treturn;\n\t\t} else if (pswInputChars.length != pswInputChars2.length){\n\t\t\tJOptionPane.showMessageDialog(null, languageBundle.getString(\"different_password\"), null, JOptionPane.PLAIN_MESSAGE);\n\t\t\treturn;\n\t\t}\n\t\tboolean pswEqual = true;\n\t\t// prevent timing attacks: \n\t\tfor (int i = 0; i < pswInputChars.length; i++) {\n\t\t\tif (pswInputChars[i] != pswInputChars2[i]) {\n\t\t\t\tpswEqual = false;\n\t\t\t}\n\t\t}\t\t\n\t\tif (pswEqual == false) {\n\t\t\tJOptionPane.showMessageDialog(null, languageBundle.getString(\"different_password\"), null, JOptionPane.PLAIN_MESSAGE);\n\t\t\treturn;\n\t\t}\n\n\t\t\n\t\tint inputLength = pswInputChars.length;\n\n\t\tArrays.fill(pswInputChars2, '\\0');\t\t\n\t\t// Warning for insecure password\n\t\tif ((inputLength == 0) && (MainView.isBlankPea() == false)) {\n\t\t\t// allow null-passwords with warning\n\t\t\tJOptionPane.showMessageDialog(frame,\n\t\t\t\t\tlanguageBundle.getString(\"no_password_warning\"),\n\t\t\t\t\"Warning\",\n\t\t\t\tJOptionPane.WARNING_MESSAGE);\n\t\t\tpswInputChars = \"no password\".toCharArray();\n\n\t\t} else if (inputLength < 12 && MainView.isBlankPea() == false) {\n\t\t\tJOptionPane.showMessageDialog(null, languageBundle.getString(\"short_password_warning\"), null, JOptionPane.PLAIN_MESSAGE);\n\t\t}\n\n\t\t//=============\n\t\t// derive key: \n\t\t//\t\n\t\tbyte[] keyMaterial = null;\n\t\t\n\t\tif (MainView.isBlankPea() == false) {// if true: no need to derive key\n\t\t\tkeyMaterial = PswDialogBase.deriveKeyFromPsw(pswInputChars);\n\t\t\t\n\t\t\tif (keyMaterial == null) {\n\t\t\t\tJOptionPane.showMessageDialog(frame,\n\t\t\t\t\t\tlanguageBundle.getString(\"program_bug\")\n\t\t\t\t\t\t+ \": \\n (keyMaterial is null)\",\n\t\t\t\t\t\"Error\",\n\t\t\t\t\tJOptionPane.ERROR_MESSAGE);\n\t\t\t\treturn;\n\t\t\t}\t\t\n\t\t}\n\t\tMainView.progressBar.setValue(35);\n\t\tMainView.progressBar.paint(MainView.progressBar.getGraphics());\n\t\t\t\n\t\t//=================\n\t\t// generate jar file:\n\t\t//\n\t\t//long start = System.currentTimeMillis(); // Startpunkt\n\n\t\tnew JarStuff().generateJarFile(keyMaterial);\n\t\t\n\t\t//System.out.println(\"generateJarFile - Zeit in ms: \\n\" + (System.currentTimeMillis() - start));//Messpunkt\n\t\t\n\t\tString fileOrDirectory = (MainView.getOpenedFileName() == null) ? languageBundle.getString(\"directory\") : languageBundle.getString(\"file\");\n\t\tif (MainView.isBlankPea() == true) {\n\t\t\tfileOrDirectory = languageBundle.getString(\"directory\"); // for all peas\n\t\t}\n\t\tif (DataType.getCurrentType() instanceof FileType) {\n\t\t\tfileOrDirectory = languageBundle.getString(\"file\");\n\t\t}\n\t\tString peaFileName = JarStuff.getJarFileName().substring(0, (JarStuff.getJarFileName().length() - 4)); // extract \".jar\"\n\t\tString peaPath = System.getProperty(\"user.dir\") + File.separator + \"peas\";\n\t\t\n\t\t// show informations about created pea:\n\t\tint input = JOptionPane.showConfirmDialog(frame,\n\t\t\t\tlanguageBundle.getString(\"new_pea_info\") + \"\\n\"\n\t\t\t\t+ DataType.getCurrentType().getDescription() + \"\\n\\n\"\n\t\t\t\t+ languageBundle.getString(\"new_pea_type_info\") + \" \"\n\t\t\t\t+ fileOrDirectory + \" \\n \"\n\t\t\t\t+ \" - \" + peaFileName + \" -\\n\"\n\t\t\t\t+ languageBundle.getString(\"new_pea_location_info\") + \"\\n \"\n\t\t\t\t+ \" \" + peaPath + \"\\n\\n\"\n\t\t\t\t+ languageBundle.getString(\"open_directory\") + \"\\n \",\n\t\t\t\"Pea info\",\n\t\t\t\t JOptionPane.YES_NO_OPTION);\n\t\t\n\t\tif (input == JOptionPane.YES_OPTION) { // 0 \n\t\t\t\n\t\t\tString error = OperatingSystemStuff.openFileManager(peaPath);\n\t\t\t\n\t\t\tif (error != null) {\n\t\t\t\tJOptionPane.showMessageDialog(frame,\n\t\t\t\t\t\tlanguageBundle.getString(\"desktop_error\")\n\t\t\t\t\t\t+ \"\\n\\n \" + error,\n\t\t\t\t\t\tlanguageBundle.getString(\"error\"),\n\t\t\t\t\t\tJOptionPane.ERROR_MESSAGE);\n\t\t\t}\n\t\t} else { // do not open folder peas:\n\t\t\t//\n\t\t}\n\t}\n\t\n\t//=========================\n\t// Helper functions:\n\t\n\t// set new language, locale, ResourceBundle\n\tpublic final static void setI18n(String newLanguage){\n \n // get ResourceBundle\n\t File file = new File(\"config\" + File.separator + \"i18n\"); \n\t URL url = null;\n\t\ttry {\n\t\t\turl = file.toURI().toURL();\n\t\t} catch (MalformedURLException e) {\n\t\t\tSystem.err.println(\"PeaFactory: Missing Language files.\");\n\t\t\t// TODO Auto-generated catch block\n\t\t\te.printStackTrace();\n\t\t} \n\t URL[] urls = {url};\n\t ClassLoader loader = new URLClassLoader(urls); \n\t ResourceBundle newLanguageBundle = ResourceBundle.getBundle(\"LanguagesBundle\", new Locale(newLanguage), loader); \n\n\t\t// set variables:\n\t language = newLanguage;\n\t currentLocale = new Locale(newLanguage);\n\t languageBundle = newLanguageBundle;\n\n\t\tMainView.updateFrame();\n\t}\n\n\t// ==============================================================================================\n\t// Getter & Setter\n\t//\n\tpublic final static String getLanguage() {\n\t\treturn language;\n\t}\n\tpublic final static ResourceBundle getLanguagesBundle(){\n\t\treturn languageBundle;\n\t}\n\tpublic final static String getPackagePath() {\n\t\treturn packagePathName;\n\t}\n\tpublic final static boolean isFrameInstantiated() {\n\t\tif (frame == null) {\n\t\t\treturn false;\n\t\t} else {\n\t\t\treturn true;\n\t\t}\n\t}\n\tpublic final static Charset getCharset() {\n\t\treturn UTF_8;\n\t}\n\tpublic final static String getOS() {\n\t\treturn os;\n\t}\n\tpublic final static MainView getFrame() {\n\t\treturn frame;\n\t}\n\tpublic final static KeyDerivation getDefaultKDF() {\n\t\treturn DEFAULT_KDF;\n\t}\n\tpublic static BlockCipher getDefaultCipher() {\n\t\treturn DEFAULT_CIPHER;\n\t}\n\tpublic static Digest getDefaultHash() {\n\t\treturn DEFAULT_HASH;\n\t}\n\n\t/**\n\t * @return the version\n\t */\n\tpublic static String getVersion() {\n\t\treturn version;\n\t}\n}",
"public final class EditorType extends DataType {\n\t\n\tprivate static byte[] serializedDoc = null;\n\t\n\t// used in TextTypePanel to display text from selected file\n\tpublic final static String readStringFromRTFFile(File file) {\n\t\t\n\t\tString text = \"\";\t\t\n\t\tDocument doc = new DefaultStyledDocument();\n\t\t\n\t\t// get text and store in doc\n\t\tRTFEditorKit kit = new RTFEditorKit();\t\n FileInputStream in; \n try {\n in = new FileInputStream(file.getAbsolutePath() ); \n kit.read(in, doc, 0); \n in.close();\n } catch (FileNotFoundException e) {\n \tSystem.err.println(\"EditorType: \" + e);\n \treturn null;\n } catch (IOException e){\n \tSystem.err.println(\"EditorType: \" + e);\n \treturn null;\n } catch (BadLocationException e){\n \tSystem.err.println(\"EditorType: \" + e);\n \treturn null;\n } \n try {\n \ttext = doc.getText(0, doc.getLength() );\n\n\t\t} catch (BadLocationException e1) {\n\t\t\tSystem.err.println(\"EditorType: \" + e1);\n\t\t\treturn null;\n\t\t}\t \n\t\t\n\t\treturn text;\n\t}\n\t\t\n\n\n\t@Override\n\tpublic void processData(byte[] keyMaterial) {\n\t\t\n\t\t//-----------------------------\n\t\t// get plainBytes: \n\t\t// 1. TextTypePanel - open file: read plainBytes from MainView.getOpenedFileName()\n\t\t// 2. TextTypePanel - new file: read plainBytes from text area\n\t\t// 3. TextTypePanel - copy from opened file: read plainBytes from serializedDoc\n\t\t// 4. TextTypePanel - no file: read plainBytes from text area\n\t\tbyte[] plainBytes = null;\n\t\t\n\t\tif (MainView.getOpenedFileName() != null) { // use external file\n\t\t\tif (MainView.getOpenedFileName().endsWith(\".rtf\") || MainView.getOpenedFileName().endsWith(\".RTF\")) {\n\t\t\t\t// do not get text from text area but from file:\n\t\t\t\tplainBytes = ReadResources.readExternFile(MainView.getOpenedFileName());\n\t\t\t\t\n\t\t\t\tif (new String(plainBytes, PeaFactory.getCharset()).equals(\"\\n\")) { // new selected file\n\t\t\t\t\t// get text from text area \n\t\t\t\t\tString text = new String(TextTypePanel.getText());\n\n\t\t\t\t\tTextTypePanel.resetText();\n\t\t\t\t\tDefaultStyledDocument doc = string2document(text);\n\t\t\t\t\tplainBytes = document2bytes(doc);\n\t\t\t\t}\n\t\t\t} else { // text file, content displayed in MainView:\n\t\t\t\tchar[] textChars = TextTypePanel.getText();\n\t\t\t\tTextTypePanel.resetText();\n\t\t\t\tDefaultStyledDocument doc = string2document(new String(textChars));\n\t\t\t\tplainBytes = document2bytes(doc);\n\t\t\t}\n\t\t} else { // internal file\n\t\t\t\n\t\t\tif (serializedDoc != null) { // copy of external file (was set in MainView)\n\t\t\t\t\n\t\t\t\tplainBytes = serializedDoc;\n\t\t\t\t\n\t\t\t} else {\n\t\t\t\tchar[] textChars = TextTypePanel.getText();\n\t\t\t\tTextTypePanel.resetText();\n\t\t\t\tDefaultStyledDocument doc = string2document(new String(textChars));\n\t\t\t\tplainBytes = document2bytes(doc);\n\t\t\t}\n\t\t}\n \n //byte[] cipherBytes = CipherStuff.getInstance().encrypt(plainBytes, keyMaterial, false);\n\t\tbyte[] cipherBytes = null;\n\t\tif (MainView.isBlankPea() == true){\n\t\t\t// String that indicates uninitialized file\n\t\t\tcipherBytes = \"uninitializedFile\".getBytes(PeaFactory.getCharset());\n\t\t} else {\n\t\t\t// encrypted content\n\t\t\tcipherBytes = CipherStuff.getInstance().encrypt(plainBytes, keyMaterial, false);\n\t\t}\n \n\t\t\n\t\tif (MainView.getOpenedFileName() == null) {\n\t\t\t// get name of directory containing jar archive and resources\n\t\t\tString dirName = JarStuff.getJarFileName().substring(0, (JarStuff.getJarFileName().length() - 4)); // extract \".jar\"\n\n\t\t\t// store cipherBytes beside jar archive\n\t\t\tWriteResources.write(cipherBytes, \"text.lock\", \"peas\" + File.separator + dirName + File.separator + \"resources\");\n\n\t\t} else {\n\t\t\t// store cipherBytes in external file\n\t\t\tWriteResources.write(cipherBytes, MainView.getOpenedFileName(), null);\t\n\t\t}\n\t}\n\t\n\tprivate final DefaultStyledDocument string2document(String text) {\n\t\tDefaultStyledDocument doc = new DefaultStyledDocument();\t\t\t\n\n\t\tSimpleAttributeSet set = new SimpleAttributeSet();\n\t\ttry {\n\t\t\tdoc.insertString(0, text, set);\n\t\t} catch (BadLocationException e) {\n\t\t\tSystem.err.println(\"EditorType: \" + e);\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn doc;\n\t}\n\tprivate final byte[] document2bytes(DefaultStyledDocument doc) {\n\t\tbyte[] result = null;\n\n\t\t// StyledDoc to bytes:\n\t\tRTFEditorKit kit = new RTFEditorKit();\t\t\n\t\t\n ByteArrayOutputStream out; \n try {\n out = new ByteArrayOutputStream(); \n kit.write(out, doc, doc.getStartPosition().getOffset(), doc.getLength()); \n out.close();\n result = out.toByteArray(); \n } catch (IOException e){\n \tSystem.err.println(\"EditorType: \" + e);\n } catch (BadLocationException e){\n \tSystem.err.println(\"EditorType: \" + e);\n }\n return result;\n\t}\n\n\t@Override\n\tpublic String getDescription() {\t\n\t\treturn PeaFactory.getLanguagesBundle().getString(\"editor_description\");\n\t}\n\t@Override\n\tpublic String getTypeName() {\n\t\treturn \"editor\";\n\t}\n\t@Override\n\tpublic byte[] getData() {\n\t\treturn serializedDoc;\n\t}\n\t@Override\n\tpublic void setData(byte[] data) {\n\t\tserializedDoc = data;\t\t\n\t}\n}",
"public final class NotesType extends DataType {\n\n\tprivate static byte[] textBytes = null;\n\n\t@Override\n\tpublic void processData(byte[] keyMaterial) {\n\t\tbyte[] plainBytes = null;\n\t\t\n\n\t\tchar[] text = TextTypePanel.getText();\n\t\tTextTypePanel.resetText();\n\t\tplainBytes = Converter.chars2bytes(text);\n\t\tif (plainBytes.length > 0){\n\t\t\t\n\t\t\tZeroizer.zero(text);\n\t\t}\n\t\t\n\t\tbyte[] cipherBytes = null;\n\t\tif (MainView.isBlankPea() == true){\n\t\t\t// String that indicates uninitialized file\n\t\t\tcipherBytes = \"uninitializedFile\".getBytes(PeaFactory.getCharset());\n\t\t} else {\n\t\t\t// encrypted content\n\t\t\tcipherBytes = CipherStuff.getInstance().encrypt(plainBytes, keyMaterial, false);\n\t\t}\n\t\t\t\t\n\t\t\n\t\tif (MainView.getOpenedFileName() == null) {\n\t\t\t// get name of directory containing jar archive and resources\n\t\t\tString dirName = JarStuff.getJarFileName().substring(0, JarStuff.getJarFileName().length() - 4); // extract \".jar\"\n\n\t\t\t// store cipherBytes beside jar archive:\n\t\t\tWriteResources.write(cipherBytes, \"text.lock\", \"peas\" + File.separator + dirName + File.separator + \"resources\");\n\t\t\tZeroizer.zero(cipherBytes);\n\t\t} else {\n\t\t\t// overwrite external file with cipherBytes:\n\t\t\tWriteResources.write(cipherBytes, MainView.getOpenedFileName() , null);\t\t\n\t\t}\t\t\n\t}\n\n\t@Override\n\tpublic String getDescription() {\n\t\treturn PeaFactory.getLanguagesBundle().getString(\"notes_description\");\n\t}\n\n\t@Override\n\tpublic String getTypeName() {\n\t\treturn \"notes\";\n\t}\n\n\t@Override\n\tpublic byte[] getData() {\n\t\treturn textBytes;\n\t}\n\n\t@Override\n\tpublic void setData(byte[] data) {\n\t\ttextBytes = data;\t\t\n\t}\n}",
"public final class Converter {\n\t\n\tpublic final static int[] chars2ints( char[] input) {\n\t\tif (input == null) {\n\t\t\tSystem.err.println(\"Converter: input null (char -> int)\");\n\t\t\treturn null;\n\t\t}\n\t\tif (input.length %2 != 0) {\n\t\t\tSystem.err.println(\"Converter (char -> int): wrong size, must be even. Is padded.\");\n\t\t\tchar[] tmp = new char[input.length + 1];\n\t\t\tSystem.arraycopy(input, 0 ,tmp, 0, input.length);\n\t\t\ttmp[tmp.length - 1] = '\\0';\n\t\t}\n\t\tint[] result = new int[input.length / 2];\n\t\t\n\t\tfor (int i=0; i<result.length; i++) {\n\t\t\t//System.out.println(\" \" + ( (int)input[i*2]) + \" \" + (((int) (input[i*2+1]) << 16)));\n\t\t\tresult[i] = ( (int)input[i*2]) | (((int) (input[i*2+1]) << 16));\n\t\t}\n\t\treturn result;\n\t}\t\t\n\t// Converts char[] to byte[]\n\tpublic final static byte[] chars2bytes(char[] charArray) {\n\t\tif (charArray == null) {\n\t\t\tSystem.err.println(\"Converter: input null (char -> byte)\");\n\t\t\treturn null;\n\t\t}\n\t\tbyte[] result = Charset.forName(\"UTF-8\").encode(CharBuffer.wrap(charArray)).array();\n\t\treturn result;\n\t}\n\t// Converts byte[] to char[]\n\tpublic final static char[] bytes2chars(byte[] byteArray) {\t\t\n\t\t//ByteBuffer bbuff = ByteBuffer.allocate(byteArray.length);\n\t\tif (byteArray == null) {\n\t\t\tSystem.err.println(\"Converter: input null (byte -> char)\");\n\t\t\treturn null;\n\t\t}\t\t\n\t\tchar[] result = Charset.forName(\"UTF-8\").decode(ByteBuffer.wrap(byteArray)).array();\n\t\t\n\t\t// cut last null-bytes, appeared because of Charset/CharBuffer in bytes2chars for Linux\n\t\tint cutMarker;\n\t\tfor (cutMarker = result.length - 1; cutMarker > 0; cutMarker--) {\n\t\t\tif (result[cutMarker] != 0) break;\n\t\t}\n\t\tchar[] tmp = new char[cutMarker + 1];\n\t\tSystem.arraycopy(result, 0, tmp, 0, cutMarker + 1);\n\t\tZeroizer.zero(result);\n\t\tresult = tmp;\t\t\t\n\t\t\n\t\treturn result;\n\t}\n\n\t\n\t//===============================\n\t// BIG ENDIAN:\n\t\n\tpublic final static int[] bytes2intsBE( byte[] bytes) {\n\t\tif (bytes == null) {\n\t\t\tSystem.err.println(\"Converter: input null (byte -> int)\");\n\t\t\treturn null;\n\t\t}\n\t\tif (bytes.length % 4 != 0) {\n\t\t\tSystem.err.println(\"Converter bytes2int invalid length %4\");\n\t\t\tSystem.exit(1);\n\t\t}\n\t\tint[] result = new int[bytes.length/4];\n\t\tfor (int i = 0; i < result.length; i++) {\n\t\t\tresult[i] = ((bytes[i*4 ] & 0xFF) << 24) \n\t\t\t\t\t| ((bytes[i*4+1] & 0xFF) << 16) \n\t\t\t\t\t| ((bytes[i*4+2] & 0xFF) << 8) \n\t\t\t\t\t| (bytes[i*4+3] & 0xFF); \n\t\t}\n\t\treturn result;\n\t}\n\t\n\t/**\n\t * Convert an array of 8-bit signed values (Java: bytes) \n\t * into an array of 32-bit signed values (Java: int)\n\t * \n\t * @param bytes\t\tinput: array of 8-bit signed values to convert\n\t * @param inIndex\tindex at input to start\n\t * @param inLen\t\tnumber of bytes to convert\n\t * @param outIndex\tindex at output, to store the converted values\n\t * @return\t\t\toutput: array of 32-bit signed vales, \n\t * \t\t\t\t\tmust be larger than outIndex + inLen/4\n\t */\n\tpublic final static int[] bytes2intsBE( byte[] bytes, int inIndex, int inLen, int outIndex) {\n\t\tif (bytes == null) {\n\t\t\tSystem.err.println(\"Converter: input null (byte -> int)\");\n\t\t\treturn null;\n\t\t}\n\t\tif (bytes.length % 4 != 0) {\n\t\t\tSystem.err.println(\"Converter bytes2int invalid length %4\");\n\t\t\tSystem.exit(1);\n\t\t}\n\t\tint[] result = new int[bytes.length/4];\n\t\tfor (int i = 0; i < result.length; i++) {\n\t\t\tresult[i] = ((bytes[i*4 ] & 0xFF) << 24) \n\t\t\t\t\t| ((bytes[i*4+1] & 0xFF) << 16) \n\t\t\t\t\t| ((bytes[i*4+2] & 0xFF) << 8) \n\t\t\t\t\t| (bytes[i*4+3] & 0xFF); \n\t\t}\n\t\treturn result;\n\t}\n\t\n\tpublic final static byte[] ints2bytesBE(int[] ints) {\n\t\tif (ints == null) {\n\t\t\tSystem.err.println(\"Converter: input null (int -> byte)\");\n\t\t\treturn null;\n\t\t}\n\t\tbyte[] result = new byte[ints.length * 4];\n\t\tfor (int i = 0; i < ints.length; i++ ) {\n\t\t\tresult[i*4+3] = (byte) (ints[i]);\n\t\t\tresult[i*4+2] = (byte)(ints[i] >>> 8);\n\t\t\tresult[i*4+1] = (byte)(ints[i] >>> 16);\n\t\t\tresult[i*4] = (byte)(ints[i] >>> 24);\n\t\t}\t\t\n\t\treturn result;\n\t}\n\tpublic final static byte[] int2bytesBE(int input) {\n\n\t\tbyte[] result = new byte[4];\n\n\t\t\tresult[3] = (byte) (input);\n\t\t\tresult[2] = (byte)(input >>> 8);\n\t\t\tresult[1] = (byte)(input >>> 16);\n\t\t\tresult[0] = (byte)(input >>> 24);\n\t\t\n\t\treturn result;\n\t}\n\t\n\t\n\tpublic final static byte[] long2bytesBE(long longValue) {\n\t return new byte[] {\n\t (byte) (longValue >> 56),\n\t (byte) (longValue >> 48),\n\t (byte) (longValue >> 40),\n\t (byte) (longValue >> 32),\n\t (byte) (longValue >> 24),\n\t (byte) (longValue >> 16),\n\t (byte) (longValue >> 8),\n\t (byte) longValue\n\t };\n\t}\n\tpublic final static byte[] longs2bytesBE(long[] longArray) {\n\t\tbyte[] result = new byte[longArray.length * 8];\n\t\tfor (int i = 0; i < longArray.length; i++) {\n\t\t\tresult[i * 8 + 0] = (byte) (longArray[i] >>> 56);\n\t\t\tresult[i * 8 + 1] = (byte) (longArray[i] >>> 48);\n\t\t\tresult[i * 8 + 2] = (byte) (longArray[i] >>> 40);\n\t\t\tresult[i * 8 + 3] = (byte) (longArray[i] >>> 32);\n\t\t\tresult[i * 8 + 4] = (byte) (longArray[i] >>> 24);\n\t\t\tresult[i * 8 + 5] = (byte) (longArray[i] >>> 16);\n\t\t\tresult[i * 8 + 6] = (byte) (longArray[i] >>> 8);\n\t\t\tresult[i * 8 + 7] = (byte) (longArray[i] >>> 0);\n\t\t}\n\t return result;\n\t}\n\tpublic final static long bytes2longBE(byte[] byteArray) {\n\t\tif (byteArray.length != 8) {\n\t\t\tSystem.err.println(\"Converter bytes2long: invalid length\");\n\t\t\tSystem.exit(1);\n\t\t}\n\t return ((long)(byteArray[0] & 0xff) << 56) |\n\t ((long)(byteArray[1] & 0xff) << 48) |\n\t ((long)(byteArray[2] & 0xff) << 40) |\n\t ((long)(byteArray[3] & 0xff) << 32) |\n\t ((long)(byteArray[4] & 0xff) << 24) |\n\t ((long)(byteArray[5] & 0xff) << 16) |\n\t ((long)(byteArray[6] & 0xff) << 8) |\n\t ((long)(byteArray[7] & 0xff));\n\t}\n\tpublic final static long[] bytes2longsBE(byte[] byteArray) {\n\t\tif (byteArray.length % 8 != 0) {\n\t\t\tSystem.err.println(\"Converter bytes2long: invalid length: \" + byteArray.length);\n\t\t\tSystem.exit(1);\n\t\t}\n\t\tlong[] result = new long[byteArray.length / 8];\n\t\tfor (int i = 0; i < result.length; i++) {\n\t\t\tresult[i] = \n\t\t\t ((long)(byteArray[i * 8 + 0] & 0xff) << 56) |\n\t\t ((long)(byteArray[i * 8 + 1] & 0xff) << 48) |\n\t\t ((long)(byteArray[i * 8 + 2] & 0xff) << 40) |\n\t\t ((long)(byteArray[i * 8 + 3] & 0xff) << 32) |\n\t\t ((long)(byteArray[i * 8 + 4] & 0xff) << 24) |\n\t\t ((long)(byteArray[i * 8 + 5] & 0xff) << 16) |\n\t\t ((long)(byteArray[i * 8 + 6] & 0xff) << 8) |\n\t\t ((long)(byteArray[i * 8 + 7] & 0xff));\n\t\t}\n\t return result;\n\t}\n\tpublic final static long[] ints2longsBE(int[] intArray) {\n\t\tif (intArray.length % 2 != 0) {\n\t\t\tSystem.err.println(\"Converter ints2long: invalid length: \" + intArray.length);\n\t\t\tSystem.exit(1);\n\t\t}\n\t\tlong[] result = new long[intArray.length / 2];\n\t\tfor (int i = 0; i < result.length; i++) {\n\t\t\tresult[i] = (long) (intArray[i * 2 + 1] & 0x00000000FFFFFFFFL) \n\t\t\t\t\t| (long)intArray[i * 2 + 0] << 32;\n\t\t}\n\t return result;\n\t}\n\t\n\t//===============================\n\t// LITTLE ENDIAN:\n\tpublic final static int[] bytes2intsLE( byte[] bytes) {\n\t\tif (bytes == null) {\n\t\t\tSystem.err.println(\"Converter: input null (byte -> int)\");\n\t\t\treturn null;\n\t\t}\n\t\tif (bytes.length % 4 != 0) {\n\t\t\tSystem.err.println(\"Converter bytes2int invalid length %4\");\n\t\t\tSystem.exit(1);\n\t\t}\n\t\tint[] result = new int[bytes.length/4];\n\t\tfor (int i = 0; i < result.length; i++) {\n\t\t\tresult[i] = ((bytes[i*4+3 ] & 0xFF) << 24) \n\t\t\t\t\t| ((bytes[i*4+2] & 0xFF) << 16) \n\t\t\t\t\t| ((bytes[i*4+1] & 0xFF) << 8) \n\t\t\t\t\t| (bytes[i*4+0] & 0xFF); \n\t\t}\n\t\treturn result;\n\t}\n\tpublic final static byte[] ints2bytesLE(int[] ints) {\n\t\tif (ints == null) {\n\t\t\tSystem.err.println(\"Converter: input null (int -> byte)\");\n\t\t\treturn null;\n\t\t}\n\t\tbyte[] result = new byte[ints.length * 4];\n\t\tfor (int i = 0; i < ints.length; i++ ) {\n\t\t\tresult[i*4+0] = (byte) (ints[i]);\n\t\t\tresult[i*4+1] = (byte)(ints[i] >>> 8);\n\t\t\tresult[i*4+2] = (byte)(ints[i] >>> 16);\n\t\t\tresult[i*4+3] = (byte)(ints[i] >>> 24);\n\t\t}\t\t\n\t\treturn result;\n\t}\n\tpublic final static byte[] int2bytesLE(int input) {\n\n\t\tbyte[] result = new byte[4];\n\t\tresult[0] = (byte) (input);\n\t\tresult[1] = (byte)(input >>> 8);\n\t\tresult[2] = (byte)(input >>> 16);\n\t\tresult[3] = (byte)(input >>> 24);\t\n\t\treturn result;\n\t}\n\n\t\n\tpublic final static byte[] long2bytesLE(long longValue) {\n\t return new byte[] {\n\t (byte) (longValue),\n\t (byte) (longValue >> 8),\n\t (byte) (longValue >> 16),\n\t (byte) (longValue >> 24),\n\t (byte) (longValue >> 32),\n\t (byte) (longValue >> 40),\n\t (byte) (longValue >> 48),\n\t (byte) (longValue >> 56)\n\t };\n\t}\n\tpublic final static byte[] longs2bytesLE(long[] longArray) {\n\t\tbyte[] result = new byte[longArray.length * 8];\n\t\tfor (int i = 0; i < longArray.length; i++) {\n\t\t\tresult[i * 8 + 7] = (byte) (longArray[i] >>> 56);\n\t\t\tresult[i * 8 + 6] = (byte) (longArray[i] >>> 48);\n\t\t\tresult[i * 8 + 5] = (byte) (longArray[i] >>> 40);\n\t\t\tresult[i * 8 + 4] = (byte) (longArray[i] >>> 32);\n\t\t\tresult[i * 8 + 3] = (byte) (longArray[i] >>> 24);\n\t\t\tresult[i * 8 + 2] = (byte) (longArray[i] >>> 16);\n\t\t\tresult[i * 8 + 1] = (byte) (longArray[i] >>> 8);\n\t\t\tresult[i * 8 + 0] = (byte) (longArray[i] >>> 0);\n\t\t}\n\t return result;\n\t}\n\tpublic final static byte[] longs2intsLE(long[] longArray) {\n\t\tbyte[] result = new byte[longArray.length * 2];\n\t\tfor (int i = 0; i < longArray.length; i++) {\n\t\t\tresult[i * 2 + 1] = (byte) (longArray[i] >>> 32);\n\t\t\tresult[i * 2 + 0] = (byte) (longArray[i] >>> 0);\n\t\t}\n\t return result;\n\t}\n\tpublic final static long bytes2longLE(byte[] byteArray) {\n\t\tif (byteArray.length % 8 != 0) {\n\t\t\tSystem.err.println(\"Converter bytes2long: invalid length: \" + byteArray.length);\n\t\t\tSystem.exit(1);\n\t\t}\n\t return \n\t ((long)(byteArray[7] & 0xff) << 56) |\n\t ((long)(byteArray[6] & 0xff) << 48) |\n\t ((long)(byteArray[5] & 0xff) << 40) |\n\t ((long)(byteArray[4] & 0xff) << 32) |\n\t ((long)(byteArray[3] & 0xff) << 24) |\n\t ((long)(byteArray[2] & 0xff) << 16) |\n\t ((long)(byteArray[1] & 0xff) << 8) |\n\t ((long)(byteArray[0] & 0xff));\n\t}\n\tpublic final static long[] bytes2longsLE(byte[] byteArray) {\n\t\tif (byteArray.length % 8 != 0) {\n\t\t\tSystem.err.println(\"Converter bytes2long: invalid length\");\n\t\t\tSystem.exit(1);\n\t\t}\n\t\tlong[] result = new long[byteArray.length / 8];\n\t\tfor (int i = 0; i < result.length; i++) {\n\t\t\tresult[i] = \n\t\t\t ((long)(byteArray[i * 8 + 7] & 0xff) << 56) |\n\t\t ((long)(byteArray[i * 8 + 6] & 0xff) << 48) |\n\t\t ((long)(byteArray[i * 8 + 5] & 0xff) << 40) |\n\t\t ((long)(byteArray[i * 8 + 4] & 0xff) << 32) |\n\t\t ((long)(byteArray[i * 8 + 3] & 0xff) << 24) |\n\t\t ((long)(byteArray[i * 8 + 2] & 0xff) << 16) |\n\t\t ((long)(byteArray[i * 8 + 1] & 0xff) << 8) |\n\t\t ((long)(byteArray[i * 8 + 0] & 0xff));\n\t\t}\n\t return result;\n\t}\n\tpublic final static long[] ints2longsLE(int[] intArray) {\n\t\tif (intArray.length % 2 != 0) {\n\t\t\tSystem.err.println(\"Converter ints2long: invalid length: \" + intArray.length);\n\t\t\tSystem.exit(1);\n\t\t}\n\t\tlong[] result = new long[intArray.length / 2];\n\t\tfor (int i = 0; i < result.length; i++) {\n\t\t\tresult[i] = (long)intArray[i * 2 + 1] << 32 |\n\t\t\t\t\t(long) (intArray[i * 2 + 0] & 0x00000000FFFFFFFFL);\n\t\t}\n\t return result;\n\t}\n\t\n/*\tpublic final static byte[] swapBytes(byte[] byteArray) {\n\t\tbyte[] result = new byte[byteArray.length];\n\t\tint index = result.length -1;\n\t\tfor (int i = 0; i < byteArray.length; i++) {\n\t\t\tresult[index--] = byteArray[i];\n\t\t}\n\t\treturn result;\n\t}*/\n\t\n\tpublic final static long swapEndianOrder (long longValue) {\n\t\treturn\n\t\t\t((((long)longValue) << 56) & 0xff00000000000000L) | \n\t\t\t((((long)longValue) << 40) & 0x00ff000000000000L) | \n\t\t\t((((long)longValue) << 24) & 0x0000ff0000000000L) | \n\t\t\t((((long)longValue) << 8) & 0x000000ff00000000L) | \n\t\t\t((((long)longValue) >> 8) & 0x00000000ff000000L) | \n\t\t\t((((long)longValue) >> 24) & 0x0000000000ff0000L) | \n\t\t\t((((long)longValue) >> 40) & 0x000000000000ff00L) | \n\t\t\t((((long)longValue) >> 56) & 0x00000000000000ffL);\n\t}\n\tpublic final static int swapEndianOrder (int intValue) {\n\t\treturn\n\t\t\t((((int)intValue) << 24) & 0xff000000) | \n\t\t\t((((int)intValue) << 8) & 0x00ff0000) | \n\t\t\t((((int)intValue) >>> 8) & 0x0000ff00) | \n\t\t\t((((int)intValue) >>> 24) & 0x000000ff);\n\t}\n\t\n\t//==============================================\n\t// HEX STRINGS AND BYTE ARRAYS:\n\tpublic final static byte[] hex2bytes(String hexString) {\n\n\t\tbyte[] byteArray = new byte[hexString.length() / 2];// 2 Character = 1 Byte\n\t\t\tint len = hexString.length();\n\t\t\tif ( (len & 1) == 1){ // ungerade\n\t\t\t\tSystem.err.println(\"Illegal Argument (Function hexStringToBytes): HexString is not even\");\n\t\t\t\treturn byteArray; // return null-Array\n\t\t\t}\n\t\t\tfinal char [] hexCharArray = hexString.toCharArray ();// Umwandeln in char-Array\n\t\t\tfor (int i = 0; i < hexString.length(); i+=2) {\n\t\t\t\t// 1. char in hex <<4, 2. char in hex\n\t\t\t\tbyteArray[i / 2] = (byte) ((Character.digit (hexCharArray[i], 16) << 4) \n\t\t\t\t\t\t\t\t+ Character.digit (hexCharArray[i + 1], 16));\n\t\t\t}\t\t\n\t\t\treturn byteArray;\n\t}\n\t\n\tpublic final static char[] hexArray = \"0123456789ABCDEF\".toCharArray();\n\tpublic static String bytes2hex(byte[] bytes) {\n\t char[] hexChars = new char[bytes.length * 2];\n\t for ( int j = 0; j < bytes.length; j++ ) {\n\t int v = bytes[j] & 0xFF;\n\t hexChars[j * 2] = hexArray[v >>> 4];\n\t hexChars[j * 2 + 1] = hexArray[v & 0x0F];\n\t }\n\t return new String(hexChars);\n\t}\n\tprivate static final String HEXES = \"0123456789ABCDEF\";\n\tpublic static String getHex( byte [] raw ) {\n\t final StringBuilder hex = new StringBuilder( 2 * raw.length );\n\t for ( final byte b : raw ) {\n\t hex.append(HEXES.charAt((b & 0xF0) >> 4))\n\t .append(HEXES.charAt((b & 0x0F)));\n\t }\n\t return hex.toString();\n\t // oder: System.out.println(javax.xml.bind.DatatypeConverter.printHexBinary(bytes));\n\t}\n\t\n\t//===========================================\n\t// DOCUMENTS AND BYTE ARRAYS\n\tpublic final static byte[] serialize(DefaultStyledDocument dsd) {\n\n\t\tRTFEditorKit kit = new RTFEditorKit();\n\t\tByteArrayOutputStream out = new ByteArrayOutputStream();\n\t\ttry {\n\t\t\tkit.write( out, dsd, 0, dsd.getLength() );\n\t\t\tout.close();\n\t\t} catch (BadLocationException e) {\n\t\t\tSystem.err.println(\"Converter: \" + e);\n\t\t\te.printStackTrace();\n\t\t} catch (IOException e) {\n\t\t\tSystem.err.println(\"Converter: \" + e);\n\t\t\te.printStackTrace();\n\t\t} \n\t return out.toByteArray();\n\t}\n\tpublic final static DefaultStyledDocument deserialize(byte[] data) {\n\t\tRTFEditorKit kit = new RTFEditorKit();\n\t\tDefaultStyledDocument dsd = new DefaultStyledDocument();\n\t\tByteArrayInputStream in = new ByteArrayInputStream(data);\n\t\ttry {\n\t\t\tkit.read(in, dsd, 0);\n\t\t\tin.close();\n\t\t} catch (BadLocationException e) {\n\t\t\t// \n\t\t\tSystem.err.println(\"Converter deserialize: \"+ e.toString());\n\t\t\treturn null;\n\t\t\t//e.printStackTrace();\n\t\t\t//System.err.println(\"BadLocationException\");\n\t\t} catch (IOException e) {\n\n\t\t\tSystem.err.println(\"Converter deserialize: \"+ e.toString());\n\t\t\treturn null;\n\t\t\t//e.printStackTrace();\n\t\t}\t\t\n\t return dsd;\n\t}\n}",
"public final class ReadResources {\n\n\n public static byte[] readResourceFile( String fileName ) {\n \t\n \tbyte[] byteArray = null; // return value; \t\n \t\n \tClassLoader classLoader = Thread.currentThread().getContextClassLoader();\n \tif (classLoader == null) {\n \t classLoader = Class.class.getClassLoader();\n \t}\n \tif (classLoader == null) System.err.println(\"ReadResources: Classloader is null\");\n\n \tInputStream is = classLoader.getResourceAsStream(\"resources/\" + fileName);//\"resources/fileName\");\n \tif (is == null) {\n \t\tSystem.err.println(\"ReadResources:InputStream is is null\");\n \t\treturn null;\n \t}\n\n \t// Stream to write in buffer \n \t//buffer of baos automatically grows as data is written to it\n \tByteArrayOutputStream baos = new ByteArrayOutputStream();\n \tint bytesRead;\n \tbyte[] ioBuf = new byte[4096];\n \t try {\n\t\t\twhile ((bytesRead = is.read(ioBuf)) != -1) baos.write(ioBuf, 0, bytesRead);\t\t\t\n\t\t} catch (IOException e1) {\n\t\t\tSystem.err.println(\"ReadResources: \" + e1);\n\t\t\te1.printStackTrace();\n\t\t}\n \t \n \tif (is != null)\n\t\t\ttry {\n\t\t\t\tis.close();\n\t\t\t} catch (IOException e) {\n\t\t\t\tSystem.err.println(\"ReadResources: \" + e);\n\t\t\t\te.printStackTrace();\n\t\t\t}\n \t\n \t//System.out.println(\"baos vor fill: \" + baos.toString() );\n \tbyteArray = baos.toByteArray();\n \t\n \t// Fill buffer of baos with Zeros\n \tint bufferSize = baos.size();\n \tbaos.reset(); // count of internal buffer = 0\n \ttry {\n\t\t\tbaos.write(new byte[bufferSize]); // fill with Null-Bytes\n\t\t} catch (IOException e) {\n\t\t\tSystem.err.println(\"ReadResources: \" + e);\n\t\t\te.printStackTrace();\n\t\t}\n \t//System.out.println(\"baos nach fill: \" + baos.toString() );\n \treturn byteArray;\n \n }\n \n public static final byte[] getResourceFromJAR( String fileNameInJar){\n\n \tbyte[] result = null;\n\n \tURL url = ReadResources.class.getClassLoader().getResource(fileNameInJar);\t\n \t\n \tByteArrayOutputStream bais = new ByteArrayOutputStream();\n \tInputStream is = null;\n \ttry {\n \t\tis = url.openStream ();\n \t\tbyte[] buffer = new byte[4096]; \n \t\tint n;\n\n \t\twhile ( (n = is.read(buffer)) > 0 ) {\n \t\t\tbais.write(buffer, 0, n);\n \t\t}\n \t} catch (IOException ioe) {\n \t\tSystem.err.printf (\"ReadResources: getResourceFromJar failes: \" + url.toExternalForm());\n \t\tioe.printStackTrace ();\n \t} finally {\n \t\tif (is != null) { \n \t\t\ttry {\n \t\t\t\tis.close();\n \t\t\t} catch (IOException e) {\n \t\t\t\tSystem.err.println(\"ReadResources: \" + e);\n \t\t\t\te.printStackTrace();\n \t\t\t} \n \t\t}\n \t}\n \tresult = bais.toByteArray();// no need to clear: resource is encrypted\n \treturn result;\n }\n \n\n \n public static byte[] readExternFile(String fileName) {\n \t\n \tbyte[] byteArray = null; \t\n \t\n \tFile file = new File(fileName);\n \tif (checkFile(file) == false) {\n \t\treturn null;\n \t}\n \t\n \tint sizeOfFile = (int) file.length();\n \t\n \tFileInputStream fis = null;\n\t\ttry {\n\t\t\tfis = new FileInputStream( file );\n\t\t} catch (FileNotFoundException e1) {\n\t\t\tSystem.err.println(\"ReadResources: \" + e1);\n\t\t\te1.printStackTrace();\n\t\t}\n \tFileChannel chan = fis.getChannel( );\n \tByteBuffer bytebuff = ByteBuffer.allocateDirect( (int)file.length() );\n \tbyteArray = new byte[sizeOfFile];\n \t//long checkSum = 0L;\n \tint nRead, nGet;\n \ttry {\n\t\t\twhile ( (nRead=chan.read( bytebuff )) != -1 )\n\t\t\t{\n\t\t\t if ( nRead == 0 )\n\t\t\t continue;\n\t\t\t bytebuff.position( 0 );\n\t\t\t bytebuff.limit( nRead );\n\t\t\t while( bytebuff.hasRemaining( ) )\n\t\t\t {\n\t\t\t nGet = Math.min( bytebuff.remaining( ), sizeOfFile );\n\t\t\t bytebuff.get( byteArray, 0, nGet ); // fills byteArray with bytebuff\n\t\t\t }\n\t\t\t bytebuff.clear( );\n\t\t\t}\n\t\t} catch (IOException e1) {\n\t\t\tSystem.err.println(\"ReadResources: \" + e1);\n\t\t\te1.printStackTrace();\n\t\t}\n \t\n \tif (fis != null){\n \t\t\ttry {\n \t\t\t\tfis.close();\n \t\t\t} catch (IOException e) {\n \t\t\t\tSystem.err.println(\"ReadResources: FileInputStream close: \" + e.toString());\n \t\t\t\te.printStackTrace();\n \t\t\t}\n \t}\n \tbytebuff.clear();\n \t\n \treturn byteArray;\n }\n \n public final File[] list(File file) {\n \tint number = countDirectoryContent(file);\n \tFile[] content = new File[number];\n \tint i = 0;\n //System.out.println(file.getName());\n File[] children = file.listFiles();\n if (children != null) {\n for (File child : children) {\n \tcontent[i++] = child;\n list(child);\n }\n }\n return content;\n }\n\n \n\tprivate int fileNumber = 0;\n // number of containing files and sub-directories\n\tpublic final int countDirectoryContent(File file) {\n\n File[] children = file.listFiles();\n \n if (children != null) {\n \tfileNumber += children.length;\n for (File child : children) {\n \t//System.out.println(file.getName());\n \t//number++;\n \tif (child.isDirectory() ) {\n \t\tcountDirectoryContent(child);\n \t}\n }\n }\n return fileNumber;\n }\n\t\n\tpublic final static boolean checkFile(File file) {\n\t\t\n \tif (file.length() > Integer.MAX_VALUE) { // > int\n \t\tSystem.err.println(\"ReadResources: File is larger than size of int: \" + file.getAbsolutePath() );\n \t\treturn false;//new byte[0];\n \t}\n \tif (! file.exists()) {\n \t\tSystem.err.println(\"ReadResources: File does not exist: \" + file.getAbsolutePath());\n \t\treturn false;\n \t}\n \tif (! file.canRead() ) {\n \t\tSystem.err.println(\"ReadResources: Can not read file: \" + file.getAbsolutePath());\n \t\treturn false;\n \t}\n \tif ( file.isDirectory() ) {\n \t\tSystem.err.println(\"ReadResources: File is directory: \" + file.getAbsolutePath());\n \t\treturn false;\n \t}\n \tif (file.length() == 0) {\n \t\tSystem.err.println(\"ReadResources: File is empty: \" + file.getAbsolutePath());\n \t\treturn false;\n \t}\n \treturn true;\t\t\n\t}\n}",
"public final class WriteResources {\n\t\n\n\t\n\tpublic static void write(byte[] textBytes , String fileName, String dir) {\n\t\t\n\t\t//System.out.println(\"fileName: \" + fileName + \" dir: \" + dir);\n\t\t\n\t\tByteBuffer bytebuff = ByteBuffer.allocate( textBytes.length );\n\t\tbytebuff.clear();\n\t\tbytebuff.put( textBytes );\n\t\tbytebuff.flip();\n\t\t\n\t\tFileOutputStream fos = null;\n\t\tFileChannel chan = null;\n\n\t\tFile file = null;\n\t\tif ( dir == null) {\n\t\t\tfile = new File(fileName);\n\t\t} else {\n\t\t\tfileName = dir + java.io.File.separator+ fileName;\n\t\t\tfile = new File(fileName);\n\t\t}\n\t\tif (dir != null && ! new File(dir).exists()) {\n\t\t\tnew File(dir).mkdirs();\n\t\t}\n\t\tif ( ! file.exists() ) {\t\t\t\n\t\t\t//System.out.println(\"WriteResources: fileName: \" + fileName + \" file getName: \" + file.getPath() );\n\t\t\ttry {\n\t\t\t\tfile.createNewFile();\n\t\t\t} catch (IOException e) {\n\t\t\t\tSystem.err.println(\"WriteResources: can not create new file: \" + file.getPath());\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\n\t\t\n\t\ttry {\n\t\t\tfos = new FileOutputStream(file);\n\t\t\tchan = fos.getChannel();\n\t\t\twhile(bytebuff.hasRemaining()) {\n\t\t\t chan.write(bytebuff);\n\t\t\t}\t\t\n\t\t} catch (IOException ioe) {\t\t\t\n\t\t\tSystem.err.println(\"WriteResources: \" + ioe.toString() + \" \" + fileName);\n\t\t\tioe.printStackTrace();\n\t\t} \n\t\tif ( chan != null){\n\t\t\ttry {\n\t\t\t\tchan.close();\n\t\t\t} catch (IOException e) {\n\t\t\t\tSystem.err.println(\"WriteResources: \" + e.toString() + \" close() \" + fileName);\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t\tif ( fos != null) {\n\t\t\ttry {\n\t\t\t\tfos.close();\n\t\t\t} catch (IOException e) {\n\t\t\t\tSystem.err.println(\"WriteResources: \" + e);\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t\t// Message ausgeben, dass Datei geschrieben wurde\n\t\t//JOptionPane.showMessageDialog(null, \"Die Datei \" + fileName + \" wurde geschrieben.\");\t\n\t}\t\n\t\n\t\n\tpublic static void writeText(String text, String fileName) {\n\t\t//FileWriter fw = null;\n\t\tBufferedWriter buff = null;\n\t\ttry {\n\t\t\t // overwrites file if exists\n\t\t\tbuff = new BufferedWriter(new FileWriter(fileName));\n\t\t\tbuff.write(text);\n\t\t\t\n\t\t\t// Message ausgeben, dass Datei geschrieben wurde\n//\t\t\tJOptionPane.showMessageDialog(null, \"New file: \" + fileName);\n\t\t} catch (IOException ioe) {\n\t\t\tSystem.out.println(\"WriteResources: \" + ioe.getMessage());\n\t\t\tioe.printStackTrace();\n\t\t} finally {\n\t\t\tif (buff != null) {\n\t\t\t\ttry {\n\t\t\t\t\tbuff.close();\n\t\t\t\t} catch (IOException ioe) {\n\t\t\t\t\tSystem.out.println(\"WriteResources: \" + ioe.getMessage());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}"
] | import javax.swing.border.LineBorder;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.text.*;
import javax.swing.text.rtf.RTFEditorKit;
import cologne.eck.peafactory.PeaFactory;
import cologne.eck.peafactory.peagen.*;
import cologne.eck.peafactory.peas.editor_pea.EditorType;
import cologne.eck.peafactory.peas.note_pea.NotesType;
import cologne.eck.peafactory.tools.Converter;
import cologne.eck.peafactory.tools.ReadResources;
import cologne.eck.peafactory.tools.WriteResources;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.ResourceBundle;
import javax.swing.*; | package cologne.eck.peafactory.gui;
/*
* Peafactory - Production of Password Encryption Archives
* Copyright (C) 2015 Axel von dem Bruch
*
* This library 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 library 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.
* See: http://www.gnu.org/licenses/gpl-2.0.html
* You should have received a copy of the GNU General Public License
* along with this library.
*/
/**
* Panel to display and write text for text based peas.
* Displayed in MainView.
*/
@SuppressWarnings("serial")
public class TextTypePanel extends JPanel implements ActionListener {
private static JTextArea area;
private ResourceBundle languageBundle;
private TextTypePanel(ResourceBundle _languageBundle) {
this.setLayout( new BoxLayout(this, BoxLayout.Y_AXIS));
languageBundle = _languageBundle;
String openedFileName = MainView.getOpenedFileName();
DataType dataType = DataType.getCurrentType();
JPanel areaPanel = new JPanel();
areaPanel.setLayout(new BoxLayout(areaPanel, BoxLayout.Y_AXIS));
JPanel areaLabelPanel = new JPanel();
areaLabelPanel.setLayout(new BoxLayout(areaLabelPanel, BoxLayout.X_AXIS));
JLabel areaLabel = new JLabel(languageBundle.getString("area_label"));//("text to encrypt: ");
areaLabel.setPreferredSize(new Dimension(300,30));
areaLabelPanel.add(areaLabel);
areaLabelPanel.add(Box.createHorizontalGlue());
areaPanel.add(areaLabelPanel);
area = new JTextArea(30, 20);
area.setDragEnabled(true);
area.setEditable(true);
area.setLineWrap(true);
area.setWrapStyleWord(true);
area.setToolTipText(languageBundle.getString("tooltip_textarea"));
if (openedFileName != null) {
if (openedFileName.endsWith("txt")) {
byte[] clearBytes = ReadResources.readExternFile(openedFileName);
if (clearBytes == null){
clearBytes = "empty file".getBytes(PeaFactory.getCharset());
}
displayText(new String( Converter.bytes2chars(clearBytes) ) );
} else if (openedFileName.endsWith("rtf")) {
Document doc = new DefaultStyledDocument();
// get text and display in text area:
RTFEditorKit kit = new RTFEditorKit();
FileInputStream in;
try {
in = new FileInputStream(openedFileName);
kit.read(in, doc, 0);
in.close();
} catch (FileNotFoundException e) {
System.err.println("TextTypePanel: " + e);
JOptionPane.showMessageDialog(this,
"File " + openedFileName + " not found...\n." + e,
"Error",
JOptionPane.ERROR_MESSAGE);
return;
} catch (IOException e){
System.err.println("TextTypePanel: " + e);
JOptionPane.showMessageDialog(this,
"reading the file " + openedFileName + " failed (IOException)\n,"
+ e,
"Error",
JOptionPane.ERROR_MESSAGE);
return;
} catch (BadLocationException e){
System.err.println("TextTypePanel: " + e);
JOptionPane.showMessageDialog(this,
"Bad Location of file " + openedFileName + ".\n." + e,
"Error",
JOptionPane.ERROR_MESSAGE);
return;
}
try {
String text = doc.getText(0, doc.getLength() );
//System.out.println("text: " + text);
displayText(text);
} catch (BadLocationException e1) {
System.err.println("TextTypePanel: " + e1);
JOptionPane.showMessageDialog(this,
"Bad Location of text in file " + openedFileName + ".\n." + e1,
"Error",
JOptionPane.ERROR_MESSAGE);
return;
}
// modifications would not be saved, because document was set to EditorType
area.setEditable(false);
}
} else {
if (dataType.getData() != null) { // was set by open file
if (dataType instanceof NotesType) {
area.setText(new String(dataType.getData(), PeaFactory.getCharset()));
| } else if (dataType instanceof EditorType) { | 1 |
MindscapeHQ/raygun4android | provider/src/main/java/com/raygun/raygun4android/RaygunClient.java | [
"public class RaygunLogger {\n\n public static void d(String string) {\n if (string != null) {\n Timber.tag(RaygunSettings.LOGGING_TAG).d(string);\n }\n }\n\n public static void i(String string) {\n if (string != null) {\n Timber.tag(RaygunSettings.LOGGING_TAG).i(string);\n }\n }\n\n public static void w(String string) {\n if (string != null) {\n Timber.tag(RaygunSettings.LOGGING_TAG).w(string);\n }\n }\n\n public static void e(String string) {\n if (string != null) {\n Timber.tag(RaygunSettings.LOGGING_TAG).e(string);\n }\n }\n\n public static void v(String string) {\n if (string != null) {\n Timber.tag(RaygunSettings.LOGGING_TAG).v(string);\n }\n }\n\n public static void responseCode(int responseCode) {\n switch (responseCode) {\n case RaygunSettings.RESPONSE_CODE_ACCEPTED:\n RaygunLogger.d(\"Request succeeded\");\n break;\n case RaygunSettings.RESPONSE_CODE_BAD_MESSAGE:\n RaygunLogger.e(\"Bad message - could not parse the provided JSON. Check all fields are present, especially both occurredOn (ISO 8601 DateTime) and details { } at the top level\");\n break;\n case RaygunSettings.RESPONSE_CODE_INVALID_API_KEY:\n RaygunLogger.e(\"Invalid API Key - The value specified in the header X-ApiKey did not match with an application in Raygun\");\n break;\n case RaygunSettings.RESPONSE_CODE_LARGE_PAYLOAD:\n RaygunLogger.e(\"Request entity too large - The maximum size of a JSON payload is 128KB\");\n break;\n case RaygunSettings.RESPONSE_CODE_RATE_LIMITED:\n RaygunLogger.e(\"Too Many Requests - Plan limit exceeded for month or plan expired\");\n break;\n default:\n RaygunLogger.d(\"Response status code: \" + responseCode);\n\n }\n }\n\n}",
"public class TimberRaygunLoggerImplementation implements TimberRaygunLogger {\n\n public static void init() {\n if (Timber.treeCount() == 0) {\n Timber.plant(new Timber.DebugTree());\n }\n }\n}",
"public class RaygunBreadcrumbMessage {\n private String message;\n private String category;\n private int level;\n private String type = \"Manual\";\n private Map<String, Object> customData;\n private Long timestamp = System.currentTimeMillis();\n private String className;\n private String methodName;\n private Integer lineNumber;\n\n public static class Builder {\n private String message;\n private String category;\n private int level = RaygunBreadcrumbLevel.INFO.ordinal();\n private Map<String, Object> customData = new WeakHashMap<>();\n private String className;\n private String methodName;\n private Integer lineNumber;\n\n public Builder(String message) {\n this.message = message;\n }\n\n public Builder category(String category) {\n this.category = category;\n return this;\n }\n\n public Builder level(RaygunBreadcrumbLevel level) {\n this.level = level.ordinal();\n return this;\n }\n\n public Builder customData(Map<String, Object> customData) {\n this.customData = customData;\n return this;\n }\n\n public Builder className(String className) {\n this.className = className;\n return this;\n }\n\n public Builder methodName(String methodName) {\n this.methodName = methodName;\n return this;\n }\n\n public Builder lineNumber(Integer lineNumber) {\n this.lineNumber = lineNumber;\n return this;\n }\n\n public RaygunBreadcrumbMessage build() {\n return new RaygunBreadcrumbMessage(this);\n }\n }\n\n public String getMessage() {\n return message;\n }\n\n public String getCategory() {\n return category;\n }\n\n public RaygunBreadcrumbLevel getLevel() {\n return RaygunBreadcrumbLevel.values()[level];\n }\n\n public Map<String, Object> getCustomData() {\n return customData;\n }\n\n public String getClassName() {\n return className;\n }\n\n public String getMethodName() {\n return methodName;\n }\n\n public Integer getLineNumber() {\n return lineNumber;\n }\n\n private RaygunBreadcrumbMessage(Builder builder) {\n message = builder.message;\n category = builder.category;\n level = builder.level;\n customData = builder.customData;\n className = builder.className;\n methodName = builder.methodName;\n lineNumber = builder.lineNumber;\n }\n}",
"public class RaygunUserInfo {\n\n private Boolean isAnonymous;\n private String email;\n private String fullName;\n private String firstName;\n private String identifier;\n\n /**\n * Set the current user's info to be transmitted - any parameter can be null if the data is not available or you do not wish to send it.\n *\n * @param firstName The user's first name\n * @param fullName The user's full name - if setting the first name you should set this too\n * @param email User's email address\n * @param identifier Unique identifier for this user. Set this to the internal identifier you use to look up users,\n * or a correlation ID for anonymous users if you have one. It doesn't have to be unique, but we will treat\n * any duplicated values as the same user. If you use their email address here, pass it in as the 'emailAddress' parameter too.\n * If identifier is not set and/or null, a uuid will be assigned to this field.\n */\n public RaygunUserInfo(String identifier, String firstName, String fullName, String email) {\n if (isValidUser(identifier)) {\n this.firstName = firstName;\n this.fullName = fullName;\n this.email = email;\n } else {\n RaygunLogger.i(\"Ignored firstName, fullName and email because created user was deemed anonymous\");\n }\n }\n\n /**\n * Convenience constructor to be used if you only want to supply an identifier string for the user.\n *\n * @param identifier Unique identifier for this user. Set this to the internal identifier you use to look up users,\n * or a correlation ID for anonymous users if you have one. It doesn't have to be unique, but we will treat\n * any duplicated values as the same user. If you use their email address here, please use the full constructor and pass it\n * in as the 'emailAddress' parameter too.\n * If identifier is not set and/or null, a uuid will be assigned to this field.\n */\n public RaygunUserInfo(String identifier) {\n isValidUser(identifier);\n }\n\n public RaygunUserInfo() {\n this.identifier = RaygunNetworkUtils.getDeviceUuid(RaygunClient.getApplicationContext());\n this.isAnonymous = true;\n }\n\n public Boolean getIsAnonymous() {\n return this.isAnonymous;\n }\n\n public String getEmail() {\n return this.email;\n }\n\n public void setEmail(String email) {\n if (!getIsAnonymous()) {\n this.email = email;\n } else {\n RaygunLogger.i(\"Ignored email because current user was deemed anonymous\");\n }\n }\n\n public String getFullName() {\n return this.fullName;\n }\n\n public void setFullName(String fullName) {\n if (!getIsAnonymous()) {\n this.fullName = fullName;\n } else {\n RaygunLogger.i(\"Ignored fullName because current user was deemed anonymous\");\n }\n }\n\n public String getFirstName() {\n return this.firstName;\n }\n\n public void setFirstName(String firstName) {\n if (!getIsAnonymous()) {\n this.firstName = firstName;\n } else {\n RaygunLogger.i(\"Ignored firstName because current user was deemed anonymous\");\n }\n }\n\n public String getIdentifier() {\n return this.identifier;\n }\n\n private Boolean isValidUser(String identifier) {\n if (identifier == null || identifier.isEmpty()) {\n this.identifier = RaygunNetworkUtils.getDeviceUuid(RaygunClient.getApplicationContext());\n this.isAnonymous = true;\n RaygunLogger.i(\"Created anonymous user\");\n return false;\n } else {\n this.identifier = identifier;\n this.isAnonymous = false;\n return true;\n }\n }\n}",
"public class RaygunFileUtils {\n\n public static String getExtension(String filename) {\n if (filename == null) {\n return null;\n }\n int separator = Math.max(filename.lastIndexOf('/'), filename.lastIndexOf('\\\\'));\n int dotPos = filename.lastIndexOf(\".\");\n int index = separator > dotPos ? -1 : dotPos;\n if (index == -1) {\n return \"\";\n } else {\n return filename.substring(index + 1);\n }\n }\n\n public static void clearCachedReports(Context context) {\n synchronized(RaygunFileUtils.class) {\n final File[] fileList = context.getCacheDir().listFiles(new RaygunFileFilter());\n if (fileList != null) {\n for (File f : fileList) {\n if (RaygunFileUtils.getExtension(f.getName()).equalsIgnoreCase(RaygunSettings.DEFAULT_FILE_EXTENSION)) {\n if (!f.delete()) {\n RaygunLogger.w(\"Couldn't delete cached report (\" + f.getName() + \")\");\n }\n }\n }\n } else {\n RaygunLogger.e(\"Error in handling cached message from filesystem - could not get a list of files from cache dir\");\n }\n\n }\n }\n}"
] | import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import com.raygun.raygun4android.logging.RaygunLogger;
import com.raygun.raygun4android.logging.TimberRaygunLoggerImplementation;
import com.raygun.raygun4android.messages.crashreporting.RaygunBreadcrumbMessage;
import com.raygun.raygun4android.messages.shared.RaygunUserInfo;
import com.raygun.raygun4android.utils.RaygunFileUtils;
import java.util.List;
import java.util.Map;
import java.util.UUID; | package com.raygun.raygun4android;
/**
* The official Raygun provider for Android. This is the main class that provides functionality for
* automatically sending exceptions to the Raygun service.
*
* You should call init() on the static RaygunClient instance, passing in the application, instead
* of instantiating this class.
*/
public class RaygunClient {
private static String apiKey;
private static String version;
private static String appContextIdentifier;
private static RaygunUserInfo userInfo;
// During initialisation, either application or applicationContext will be set.
private static Application application;
private static Context applicationContext;
private static boolean crashReportingEnabled = false;
private static boolean RUMEnabled = false;
/**
* Initializes the Raygun client. This expects that you have placed the API key in your
* AndroidManifest.xml, in a meta-data element.
*
* @param application The Android application
*/
public static void init(Application application) {
init(application, null, null);
}
/**
* Initializes the Raygun client with your Android application and your Raygun API key. The version
* transmitted will be the value of the versionName attribute in your manifest element.
*
* @param application The Android application
* @param apiKey An API key that belongs to a Raygun application created in your dashboard
*/
public static void init(Application application, String apiKey) {
init(application, apiKey, null);
}
/**
* Initializes the Raygun client with an Android application context, your Raygun API key and the
* version of your application.
*
* This method is intended to be used by 3rd-party libraries such as Raygun for React Native or
* Raygun for Flutter etc.
*
* @param applicationContext The Android applicationContext
* @param apiKey An API key that belongs to a Raygun application created in your dashboard
* @param version The version of your application, format x.x.x.x, where x is a positive integer.
*/
public static void init(Context applicationContext, String apiKey, String version) {
RaygunClient.applicationContext = applicationContext;
sharedSetup(apiKey, version);
}
/**
* Initializes the Raygun client with your Android application, your Raygun API key, and the
* version of your application
*
* @param application The Android application
* @param apiKey An API key that belongs to a Raygun application created in your dashboard
* @param version The version of your application, format x.x.x.x, where x is a positive integer.
*/
public static void init(Application application, String apiKey, String version) {
RaygunClient.application = application;
sharedSetup(apiKey, version);
}
private static void sharedSetup(String apiKey, String version) {
TimberRaygunLoggerImplementation.init();
| RaygunLogger.d("Configuring Raygun4Android (v" + RaygunSettings.RAYGUN_CLIENT_VERSION + ")"); | 0 |
lrtdc/light_drtc | src/main/java/org/light/rtc/admin/AdminNodeKafkaRun.java | [
"@SuppressWarnings({\"cast\", \"rawtypes\", \"serial\", \"unchecked\"})\r\n@Generated(value = \"Autogenerated by Thrift Compiler (0.9.3)\", date = \"2016-03-16\")\r\npublic class TDssService {\r\n\r\n public interface Iface {\r\n\r\n public int addMqinfoToAdminQu(List<String> uLogs) throws org.apache.thrift.TException;\r\n\r\n public int rtcStats(List<String> userLogs) throws org.apache.thrift.TException;\r\n\r\n public int batchStats(int start, int size) throws org.apache.thrift.TException;\r\n\r\n public int getAdminNodeId() throws org.apache.thrift.TException;\r\n\r\n public int getHealthStatus() throws org.apache.thrift.TException;\r\n\r\n public int getJobStatus() throws org.apache.thrift.TException;\r\n\r\n }\r\n\r\n public interface AsyncIface {\r\n\r\n public void addMqinfoToAdminQu(List<String> uLogs, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException;\r\n\r\n public void rtcStats(List<String> userLogs, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException;\r\n\r\n public void batchStats(int start, int size, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException;\r\n\r\n public void getAdminNodeId(org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException;\r\n\r\n public void getHealthStatus(org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException;\r\n\r\n public void getJobStatus(org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException;\r\n\r\n }\r\n\r\n public static class Client extends org.apache.thrift.TServiceClient implements Iface {\r\n public static class Factory implements org.apache.thrift.TServiceClientFactory<Client> {\r\n public Factory() {}\r\n public Client getClient(org.apache.thrift.protocol.TProtocol prot) {\r\n return new Client(prot);\r\n }\r\n public Client getClient(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) {\r\n return new Client(iprot, oprot);\r\n }\r\n }\r\n\r\n public Client(org.apache.thrift.protocol.TProtocol prot)\r\n {\r\n super(prot, prot);\r\n }\r\n\r\n public Client(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TProtocol oprot) {\r\n super(iprot, oprot);\r\n }\r\n\r\n public int addMqinfoToAdminQu(List<String> uLogs) throws org.apache.thrift.TException\r\n {\r\n send_addMqinfoToAdminQu(uLogs);\r\n return recv_addMqinfoToAdminQu();\r\n }\r\n\r\n public void send_addMqinfoToAdminQu(List<String> uLogs) throws org.apache.thrift.TException\r\n {\r\n addMqinfoToAdminQu_args args = new addMqinfoToAdminQu_args();\r\n args.setULogs(uLogs);\r\n sendBase(\"addMqinfoToAdminQu\", args);\r\n }\r\n\r\n public int recv_addMqinfoToAdminQu() throws org.apache.thrift.TException\r\n {\r\n addMqinfoToAdminQu_result result = new addMqinfoToAdminQu_result();\r\n receiveBase(result, \"addMqinfoToAdminQu\");\r\n if (result.isSetSuccess()) {\r\n return result.success;\r\n }\r\n throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, \"addMqinfoToAdminQu failed: unknown result\");\r\n }\r\n\r\n public int rtcStats(List<String> userLogs) throws org.apache.thrift.TException\r\n {\r\n send_rtcStats(userLogs);\r\n return recv_rtcStats();\r\n }\r\n\r\n public void send_rtcStats(List<String> userLogs) throws org.apache.thrift.TException\r\n {\r\n rtcStats_args args = new rtcStats_args();\r\n args.setUserLogs(userLogs);\r\n sendBase(\"rtcStats\", args);\r\n }\r\n\r\n public int recv_rtcStats() throws org.apache.thrift.TException\r\n {\r\n rtcStats_result result = new rtcStats_result();\r\n receiveBase(result, \"rtcStats\");\r\n if (result.isSetSuccess()) {\r\n return result.success;\r\n }\r\n throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, \"rtcStats failed: unknown result\");\r\n }\r\n\r\n public int batchStats(int start, int size) throws org.apache.thrift.TException\r\n {\r\n send_batchStats(start, size);\r\n return recv_batchStats();\r\n }\r\n\r\n public void send_batchStats(int start, int size) throws org.apache.thrift.TException\r\n {\r\n batchStats_args args = new batchStats_args();\r\n args.setStart(start);\r\n args.setSize(size);\r\n sendBase(\"batchStats\", args);\r\n }\r\n\r\n public int recv_batchStats() throws org.apache.thrift.TException\r\n {\r\n batchStats_result result = new batchStats_result();\r\n receiveBase(result, \"batchStats\");\r\n if (result.isSetSuccess()) {\r\n return result.success;\r\n }\r\n throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, \"batchStats failed: unknown result\");\r\n }\r\n\r\n public int getAdminNodeId() throws org.apache.thrift.TException\r\n {\r\n send_getAdminNodeId();\r\n return recv_getAdminNodeId();\r\n }\r\n\r\n public void send_getAdminNodeId() throws org.apache.thrift.TException\r\n {\r\n getAdminNodeId_args args = new getAdminNodeId_args();\r\n sendBase(\"getAdminNodeId\", args);\r\n }\r\n\r\n public int recv_getAdminNodeId() throws org.apache.thrift.TException\r\n {\r\n getAdminNodeId_result result = new getAdminNodeId_result();\r\n receiveBase(result, \"getAdminNodeId\");\r\n if (result.isSetSuccess()) {\r\n return result.success;\r\n }\r\n throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, \"getAdminNodeId failed: unknown result\");\r\n }\r\n\r\n public int getHealthStatus() throws org.apache.thrift.TException\r\n {\r\n send_getHealthStatus();\r\n return recv_getHealthStatus();\r\n }\r\n\r\n public void send_getHealthStatus() throws org.apache.thrift.TException\r\n {\r\n getHealthStatus_args args = new getHealthStatus_args();\r\n sendBase(\"getHealthStatus\", args);\r\n }\r\n\r\n public int recv_getHealthStatus() throws org.apache.thrift.TException\r\n {\r\n getHealthStatus_result result = new getHealthStatus_result();\r\n receiveBase(result, \"getHealthStatus\");\r\n if (result.isSetSuccess()) {\r\n return result.success;\r\n }\r\n throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, \"getHealthStatus failed: unknown result\");\r\n }\r\n\r\n public int getJobStatus() throws org.apache.thrift.TException\r\n {\r\n send_getJobStatus();\r\n return recv_getJobStatus();\r\n }\r\n\r\n public void send_getJobStatus() throws org.apache.thrift.TException\r\n {\r\n getJobStatus_args args = new getJobStatus_args();\r\n sendBase(\"getJobStatus\", args);\r\n }\r\n\r\n public int recv_getJobStatus() throws org.apache.thrift.TException\r\n {\r\n getJobStatus_result result = new getJobStatus_result();\r\n receiveBase(result, \"getJobStatus\");\r\n if (result.isSetSuccess()) {\r\n return result.success;\r\n }\r\n throw new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.MISSING_RESULT, \"getJobStatus failed: unknown result\");\r\n }\r\n\r\n }\r\n public static class AsyncClient extends org.apache.thrift.async.TAsyncClient implements AsyncIface {\r\n public static class Factory implements org.apache.thrift.async.TAsyncClientFactory<AsyncClient> {\r\n private org.apache.thrift.async.TAsyncClientManager clientManager;\r\n private org.apache.thrift.protocol.TProtocolFactory protocolFactory;\r\n public Factory(org.apache.thrift.async.TAsyncClientManager clientManager, org.apache.thrift.protocol.TProtocolFactory protocolFactory) {\r\n this.clientManager = clientManager;\r\n this.protocolFactory = protocolFactory;\r\n }\r\n public AsyncClient getAsyncClient(org.apache.thrift.transport.TNonblockingTransport transport) {\r\n return new AsyncClient(protocolFactory, clientManager, transport);\r\n }\r\n }\r\n\r\n public AsyncClient(org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.async.TAsyncClientManager clientManager, org.apache.thrift.transport.TNonblockingTransport transport) {\r\n super(protocolFactory, clientManager, transport);\r\n }\r\n\r\n public void addMqinfoToAdminQu(List<String> uLogs, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException {\r\n checkReady();\r\n addMqinfoToAdminQu_call method_call = new addMqinfoToAdminQu_call(uLogs, resultHandler, this, ___protocolFactory, ___transport);\r\n this.___currentMethod = method_call;\r\n ___manager.call(method_call);\r\n }\r\n\r\n public static class addMqinfoToAdminQu_call extends org.apache.thrift.async.TAsyncMethodCall {\r\n private List<String> uLogs;\r\n public addMqinfoToAdminQu_call(List<String> uLogs, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException {\r\n super(client, protocolFactory, transport, resultHandler, false);\r\n this.uLogs = uLogs;\r\n }\r\n\r\n public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException {\r\n prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage(\"addMqinfoToAdminQu\", org.apache.thrift.protocol.TMessageType.CALL, 0));\r\n addMqinfoToAdminQu_args args = new addMqinfoToAdminQu_args();\r\n args.setULogs(uLogs);\r\n args.write(prot);\r\n prot.writeMessageEnd();\r\n }\r\n\r\n public int getResult() throws org.apache.thrift.TException {\r\n if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) {\r\n throw new IllegalStateException(\"Method call not finished!\");\r\n }\r\n org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array());\r\n org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport);\r\n return (new Client(prot)).recv_addMqinfoToAdminQu();\r\n }\r\n }\r\n\r\n public void rtcStats(List<String> userLogs, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException {\r\n checkReady();\r\n rtcStats_call method_call = new rtcStats_call(userLogs, resultHandler, this, ___protocolFactory, ___transport);\r\n this.___currentMethod = method_call;\r\n ___manager.call(method_call);\r\n }\r\n\r\n public static class rtcStats_call extends org.apache.thrift.async.TAsyncMethodCall {\r\n private List<String> userLogs;\r\n public rtcStats_call(List<String> userLogs, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException {\r\n super(client, protocolFactory, transport, resultHandler, false);\r\n this.userLogs = userLogs;\r\n }\r\n\r\n public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException {\r\n prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage(\"rtcStats\", org.apache.thrift.protocol.TMessageType.CALL, 0));\r\n rtcStats_args args = new rtcStats_args();\r\n args.setUserLogs(userLogs);\r\n args.write(prot);\r\n prot.writeMessageEnd();\r\n }\r\n\r\n public int getResult() throws org.apache.thrift.TException {\r\n if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) {\r\n throw new IllegalStateException(\"Method call not finished!\");\r\n }\r\n org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array());\r\n org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport);\r\n return (new Client(prot)).recv_rtcStats();\r\n }\r\n }\r\n\r\n public void batchStats(int start, int size, org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException {\r\n checkReady();\r\n batchStats_call method_call = new batchStats_call(start, size, resultHandler, this, ___protocolFactory, ___transport);\r\n this.___currentMethod = method_call;\r\n ___manager.call(method_call);\r\n }\r\n\r\n public static class batchStats_call extends org.apache.thrift.async.TAsyncMethodCall {\r\n private int start;\r\n private int size;\r\n public batchStats_call(int start, int size, org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException {\r\n super(client, protocolFactory, transport, resultHandler, false);\r\n this.start = start;\r\n this.size = size;\r\n }\r\n\r\n public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException {\r\n prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage(\"batchStats\", org.apache.thrift.protocol.TMessageType.CALL, 0));\r\n batchStats_args args = new batchStats_args();\r\n args.setStart(start);\r\n args.setSize(size);\r\n args.write(prot);\r\n prot.writeMessageEnd();\r\n }\r\n\r\n public int getResult() throws org.apache.thrift.TException {\r\n if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) {\r\n throw new IllegalStateException(\"Method call not finished!\");\r\n }\r\n org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array());\r\n org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport);\r\n return (new Client(prot)).recv_batchStats();\r\n }\r\n }\r\n\r\n public void getAdminNodeId(org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException {\r\n checkReady();\r\n getAdminNodeId_call method_call = new getAdminNodeId_call(resultHandler, this, ___protocolFactory, ___transport);\r\n this.___currentMethod = method_call;\r\n ___manager.call(method_call);\r\n }\r\n\r\n public static class getAdminNodeId_call extends org.apache.thrift.async.TAsyncMethodCall {\r\n public getAdminNodeId_call(org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException {\r\n super(client, protocolFactory, transport, resultHandler, false);\r\n }\r\n\r\n public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException {\r\n prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage(\"getAdminNodeId\", org.apache.thrift.protocol.TMessageType.CALL, 0));\r\n getAdminNodeId_args args = new getAdminNodeId_args();\r\n args.write(prot);\r\n prot.writeMessageEnd();\r\n }\r\n\r\n public int getResult() throws org.apache.thrift.TException {\r\n if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) {\r\n throw new IllegalStateException(\"Method call not finished!\");\r\n }\r\n org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array());\r\n org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport);\r\n return (new Client(prot)).recv_getAdminNodeId();\r\n }\r\n }\r\n\r\n public void getHealthStatus(org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException {\r\n checkReady();\r\n getHealthStatus_call method_call = new getHealthStatus_call(resultHandler, this, ___protocolFactory, ___transport);\r\n this.___currentMethod = method_call;\r\n ___manager.call(method_call);\r\n }\r\n\r\n public static class getHealthStatus_call extends org.apache.thrift.async.TAsyncMethodCall {\r\n public getHealthStatus_call(org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException {\r\n super(client, protocolFactory, transport, resultHandler, false);\r\n }\r\n\r\n public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException {\r\n prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage(\"getHealthStatus\", org.apache.thrift.protocol.TMessageType.CALL, 0));\r\n getHealthStatus_args args = new getHealthStatus_args();\r\n args.write(prot);\r\n prot.writeMessageEnd();\r\n }\r\n\r\n public int getResult() throws org.apache.thrift.TException {\r\n if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) {\r\n throw new IllegalStateException(\"Method call not finished!\");\r\n }\r\n org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array());\r\n org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport);\r\n return (new Client(prot)).recv_getHealthStatus();\r\n }\r\n }\r\n\r\n public void getJobStatus(org.apache.thrift.async.AsyncMethodCallback resultHandler) throws org.apache.thrift.TException {\r\n checkReady();\r\n getJobStatus_call method_call = new getJobStatus_call(resultHandler, this, ___protocolFactory, ___transport);\r\n this.___currentMethod = method_call;\r\n ___manager.call(method_call);\r\n }\r\n\r\n public static class getJobStatus_call extends org.apache.thrift.async.TAsyncMethodCall {\r\n public getJobStatus_call(org.apache.thrift.async.AsyncMethodCallback resultHandler, org.apache.thrift.async.TAsyncClient client, org.apache.thrift.protocol.TProtocolFactory protocolFactory, org.apache.thrift.transport.TNonblockingTransport transport) throws org.apache.thrift.TException {\r\n super(client, protocolFactory, transport, resultHandler, false);\r\n }\r\n\r\n public void write_args(org.apache.thrift.protocol.TProtocol prot) throws org.apache.thrift.TException {\r\n prot.writeMessageBegin(new org.apache.thrift.protocol.TMessage(\"getJobStatus\", org.apache.thrift.protocol.TMessageType.CALL, 0));\r\n getJobStatus_args args = new getJobStatus_args();\r\n args.write(prot);\r\n prot.writeMessageEnd();\r\n }\r\n\r\n public int getResult() throws org.apache.thrift.TException {\r\n if (getState() != org.apache.thrift.async.TAsyncMethodCall.State.RESPONSE_READ) {\r\n throw new IllegalStateException(\"Method call not finished!\");\r\n }\r\n org.apache.thrift.transport.TMemoryInputTransport memoryTransport = new org.apache.thrift.transport.TMemoryInputTransport(getFrameBuffer().array());\r\n org.apache.thrift.protocol.TProtocol prot = client.getProtocolFactory().getProtocol(memoryTransport);\r\n return (new Client(prot)).recv_getJobStatus();\r\n }\r\n }\r\n\r\n }\r\n\r\n public static class Processor<I extends Iface> extends org.apache.thrift.TBaseProcessor<I> implements org.apache.thrift.TProcessor {\r\n private static final Logger LOGGER = LoggerFactory.getLogger(Processor.class.getName());\r\n public Processor(I iface) {\r\n super(iface, getProcessMap(new HashMap<String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>>()));\r\n }\r\n\r\n protected Processor(I iface, Map<String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>> processMap) {\r\n super(iface, getProcessMap(processMap));\r\n }\r\n\r\n private static <I extends Iface> Map<String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>> getProcessMap(Map<String, org.apache.thrift.ProcessFunction<I, ? extends org.apache.thrift.TBase>> processMap) {\r\n processMap.put(\"addMqinfoToAdminQu\", new addMqinfoToAdminQu());\r\n processMap.put(\"rtcStats\", new rtcStats());\r\n processMap.put(\"batchStats\", new batchStats());\r\n processMap.put(\"getAdminNodeId\", new getAdminNodeId());\r\n processMap.put(\"getHealthStatus\", new getHealthStatus());\r\n processMap.put(\"getJobStatus\", new getJobStatus());\r\n return processMap;\r\n }\r\n\r\n public static class addMqinfoToAdminQu<I extends Iface> extends org.apache.thrift.ProcessFunction<I, addMqinfoToAdminQu_args> {\r\n public addMqinfoToAdminQu() {\r\n super(\"addMqinfoToAdminQu\");\r\n }\r\n\r\n public addMqinfoToAdminQu_args getEmptyArgsInstance() {\r\n return new addMqinfoToAdminQu_args();\r\n }\r\n\r\n protected boolean isOneway() {\r\n return false;\r\n }\r\n\r\n public addMqinfoToAdminQu_result getResult(I iface, addMqinfoToAdminQu_args args) throws org.apache.thrift.TException {\r\n addMqinfoToAdminQu_result result = new addMqinfoToAdminQu_result();\r\n result.success = iface.addMqinfoToAdminQu(args.uLogs);\r\n result.setSuccessIsSet(true);\r\n return result;\r\n }\r\n }\r\n\r\n public static class rtcStats<I extends Iface> extends org.apache.thrift.ProcessFunction<I, rtcStats_args> {\r\n public rtcStats() {\r\n super(\"rtcStats\");\r\n }\r\n\r\n public rtcStats_args getEmptyArgsInstance() {\r\n return new rtcStats_args();\r\n }\r\n\r\n protected boolean isOneway() {\r\n return false;\r\n }\r\n\r\n public rtcStats_result getResult(I iface, rtcStats_args args) throws org.apache.thrift.TException {\r\n rtcStats_result result = new rtcStats_result();\r\n result.success = iface.rtcStats(args.userLogs);\r\n result.setSuccessIsSet(true);\r\n return result;\r\n }\r\n }\r\n\r\n public static class batchStats<I extends Iface> extends org.apache.thrift.ProcessFunction<I, batchStats_args> {\r\n public batchStats() {\r\n super(\"batchStats\");\r\n }\r\n\r\n public batchStats_args getEmptyArgsInstance() {\r\n return new batchStats_args();\r\n }\r\n\r\n protected boolean isOneway() {\r\n return false;\r\n }\r\n\r\n public batchStats_result getResult(I iface, batchStats_args args) throws org.apache.thrift.TException {\r\n batchStats_result result = new batchStats_result();\r\n result.success = iface.batchStats(args.start, args.size);\r\n result.setSuccessIsSet(true);\r\n return result;\r\n }\r\n }\r\n\r\n public static class getAdminNodeId<I extends Iface> extends org.apache.thrift.ProcessFunction<I, getAdminNodeId_args> {\r\n public getAdminNodeId() {\r\n super(\"getAdminNodeId\");\r\n }\r\n\r\n public getAdminNodeId_args getEmptyArgsInstance() {\r\n return new getAdminNodeId_args();\r\n }\r\n\r\n protected boolean isOneway() {\r\n return false;\r\n }\r\n\r\n public getAdminNodeId_result getResult(I iface, getAdminNodeId_args args) throws org.apache.thrift.TException {\r\n getAdminNodeId_result result = new getAdminNodeId_result();\r\n result.success = iface.getAdminNodeId();\r\n result.setSuccessIsSet(true);\r\n return result;\r\n }\r\n }\r\n\r\n public static class getHealthStatus<I extends Iface> extends org.apache.thrift.ProcessFunction<I, getHealthStatus_args> {\r\n public getHealthStatus() {\r\n super(\"getHealthStatus\");\r\n }\r\n\r\n public getHealthStatus_args getEmptyArgsInstance() {\r\n return new getHealthStatus_args();\r\n }\r\n\r\n protected boolean isOneway() {\r\n return false;\r\n }\r\n\r\n public getHealthStatus_result getResult(I iface, getHealthStatus_args args) throws org.apache.thrift.TException {\r\n getHealthStatus_result result = new getHealthStatus_result();\r\n result.success = iface.getHealthStatus();\r\n result.setSuccessIsSet(true);\r\n return result;\r\n }\r\n }\r\n\r\n public static class getJobStatus<I extends Iface> extends org.apache.thrift.ProcessFunction<I, getJobStatus_args> {\r\n public getJobStatus() {\r\n super(\"getJobStatus\");\r\n }\r\n\r\n public getJobStatus_args getEmptyArgsInstance() {\r\n return new getJobStatus_args();\r\n }\r\n\r\n protected boolean isOneway() {\r\n return false;\r\n }\r\n\r\n public getJobStatus_result getResult(I iface, getJobStatus_args args) throws org.apache.thrift.TException {\r\n getJobStatus_result result = new getJobStatus_result();\r\n result.success = iface.getJobStatus();\r\n result.setSuccessIsSet(true);\r\n return result;\r\n }\r\n }\r\n\r\n }\r\n\r\n public static class AsyncProcessor<I extends AsyncIface> extends org.apache.thrift.TBaseAsyncProcessor<I> {\r\n private static final Logger LOGGER = LoggerFactory.getLogger(AsyncProcessor.class.getName());\r\n public AsyncProcessor(I iface) {\r\n super(iface, getProcessMap(new HashMap<String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase, ?>>()));\r\n }\r\n\r\n protected AsyncProcessor(I iface, Map<String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase, ?>> processMap) {\r\n super(iface, getProcessMap(processMap));\r\n }\r\n\r\n private static <I extends AsyncIface> Map<String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase,?>> getProcessMap(Map<String, org.apache.thrift.AsyncProcessFunction<I, ? extends org.apache.thrift.TBase, ?>> processMap) {\r\n processMap.put(\"addMqinfoToAdminQu\", new addMqinfoToAdminQu());\r\n processMap.put(\"rtcStats\", new rtcStats());\r\n processMap.put(\"batchStats\", new batchStats());\r\n processMap.put(\"getAdminNodeId\", new getAdminNodeId());\r\n processMap.put(\"getHealthStatus\", new getHealthStatus());\r\n processMap.put(\"getJobStatus\", new getJobStatus());\r\n return processMap;\r\n }\r\n\r\n public static class addMqinfoToAdminQu<I extends AsyncIface> extends org.apache.thrift.AsyncProcessFunction<I, addMqinfoToAdminQu_args, Integer> {\r\n public addMqinfoToAdminQu() {\r\n super(\"addMqinfoToAdminQu\");\r\n }\r\n\r\n public addMqinfoToAdminQu_args getEmptyArgsInstance() {\r\n return new addMqinfoToAdminQu_args();\r\n }\r\n\r\n public AsyncMethodCallback<Integer> getResultHandler(final AsyncFrameBuffer fb, final int seqid) {\r\n final org.apache.thrift.AsyncProcessFunction fcall = this;\r\n return new AsyncMethodCallback<Integer>() { \r\n public void onComplete(Integer o) {\r\n addMqinfoToAdminQu_result result = new addMqinfoToAdminQu_result();\r\n result.success = o;\r\n result.setSuccessIsSet(true);\r\n try {\r\n fcall.sendResponse(fb,result, org.apache.thrift.protocol.TMessageType.REPLY,seqid);\r\n return;\r\n } catch (Exception e) {\r\n LOGGER.error(\"Exception writing to internal frame buffer\", e);\r\n }\r\n fb.close();\r\n }\r\n public void onError(Exception e) {\r\n byte msgType = org.apache.thrift.protocol.TMessageType.REPLY;\r\n org.apache.thrift.TBase msg;\r\n addMqinfoToAdminQu_result result = new addMqinfoToAdminQu_result();\r\n {\r\n msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;\r\n msg = (org.apache.thrift.TBase)new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage());\r\n }\r\n try {\r\n fcall.sendResponse(fb,msg,msgType,seqid);\r\n return;\r\n } catch (Exception ex) {\r\n LOGGER.error(\"Exception writing to internal frame buffer\", ex);\r\n }\r\n fb.close();\r\n }\r\n };\r\n }\r\n\r\n protected boolean isOneway() {\r\n return false;\r\n }\r\n\r\n public void start(I iface, addMqinfoToAdminQu_args args, org.apache.thrift.async.AsyncMethodCallback<Integer> resultHandler) throws TException {\r\n iface.addMqinfoToAdminQu(args.uLogs,resultHandler);\r\n }\r\n }\r\n\r\n public static class rtcStats<I extends AsyncIface> extends org.apache.thrift.AsyncProcessFunction<I, rtcStats_args, Integer> {\r\n public rtcStats() {\r\n super(\"rtcStats\");\r\n }\r\n\r\n public rtcStats_args getEmptyArgsInstance() {\r\n return new rtcStats_args();\r\n }\r\n\r\n public AsyncMethodCallback<Integer> getResultHandler(final AsyncFrameBuffer fb, final int seqid) {\r\n final org.apache.thrift.AsyncProcessFunction fcall = this;\r\n return new AsyncMethodCallback<Integer>() { \r\n public void onComplete(Integer o) {\r\n rtcStats_result result = new rtcStats_result();\r\n result.success = o;\r\n result.setSuccessIsSet(true);\r\n try {\r\n fcall.sendResponse(fb,result, org.apache.thrift.protocol.TMessageType.REPLY,seqid);\r\n return;\r\n } catch (Exception e) {\r\n LOGGER.error(\"Exception writing to internal frame buffer\", e);\r\n }\r\n fb.close();\r\n }\r\n public void onError(Exception e) {\r\n byte msgType = org.apache.thrift.protocol.TMessageType.REPLY;\r\n org.apache.thrift.TBase msg;\r\n rtcStats_result result = new rtcStats_result();\r\n {\r\n msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;\r\n msg = (org.apache.thrift.TBase)new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage());\r\n }\r\n try {\r\n fcall.sendResponse(fb,msg,msgType,seqid);\r\n return;\r\n } catch (Exception ex) {\r\n LOGGER.error(\"Exception writing to internal frame buffer\", ex);\r\n }\r\n fb.close();\r\n }\r\n };\r\n }\r\n\r\n protected boolean isOneway() {\r\n return false;\r\n }\r\n\r\n public void start(I iface, rtcStats_args args, org.apache.thrift.async.AsyncMethodCallback<Integer> resultHandler) throws TException {\r\n iface.rtcStats(args.userLogs,resultHandler);\r\n }\r\n }\r\n\r\n public static class batchStats<I extends AsyncIface> extends org.apache.thrift.AsyncProcessFunction<I, batchStats_args, Integer> {\r\n public batchStats() {\r\n super(\"batchStats\");\r\n }\r\n\r\n public batchStats_args getEmptyArgsInstance() {\r\n return new batchStats_args();\r\n }\r\n\r\n public AsyncMethodCallback<Integer> getResultHandler(final AsyncFrameBuffer fb, final int seqid) {\r\n final org.apache.thrift.AsyncProcessFunction fcall = this;\r\n return new AsyncMethodCallback<Integer>() { \r\n public void onComplete(Integer o) {\r\n batchStats_result result = new batchStats_result();\r\n result.success = o;\r\n result.setSuccessIsSet(true);\r\n try {\r\n fcall.sendResponse(fb,result, org.apache.thrift.protocol.TMessageType.REPLY,seqid);\r\n return;\r\n } catch (Exception e) {\r\n LOGGER.error(\"Exception writing to internal frame buffer\", e);\r\n }\r\n fb.close();\r\n }\r\n public void onError(Exception e) {\r\n byte msgType = org.apache.thrift.protocol.TMessageType.REPLY;\r\n org.apache.thrift.TBase msg;\r\n batchStats_result result = new batchStats_result();\r\n {\r\n msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;\r\n msg = (org.apache.thrift.TBase)new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage());\r\n }\r\n try {\r\n fcall.sendResponse(fb,msg,msgType,seqid);\r\n return;\r\n } catch (Exception ex) {\r\n LOGGER.error(\"Exception writing to internal frame buffer\", ex);\r\n }\r\n fb.close();\r\n }\r\n };\r\n }\r\n\r\n protected boolean isOneway() {\r\n return false;\r\n }\r\n\r\n public void start(I iface, batchStats_args args, org.apache.thrift.async.AsyncMethodCallback<Integer> resultHandler) throws TException {\r\n iface.batchStats(args.start, args.size,resultHandler);\r\n }\r\n }\r\n\r\n public static class getAdminNodeId<I extends AsyncIface> extends org.apache.thrift.AsyncProcessFunction<I, getAdminNodeId_args, Integer> {\r\n public getAdminNodeId() {\r\n super(\"getAdminNodeId\");\r\n }\r\n\r\n public getAdminNodeId_args getEmptyArgsInstance() {\r\n return new getAdminNodeId_args();\r\n }\r\n\r\n public AsyncMethodCallback<Integer> getResultHandler(final AsyncFrameBuffer fb, final int seqid) {\r\n final org.apache.thrift.AsyncProcessFunction fcall = this;\r\n return new AsyncMethodCallback<Integer>() { \r\n public void onComplete(Integer o) {\r\n getAdminNodeId_result result = new getAdminNodeId_result();\r\n result.success = o;\r\n result.setSuccessIsSet(true);\r\n try {\r\n fcall.sendResponse(fb,result, org.apache.thrift.protocol.TMessageType.REPLY,seqid);\r\n return;\r\n } catch (Exception e) {\r\n LOGGER.error(\"Exception writing to internal frame buffer\", e);\r\n }\r\n fb.close();\r\n }\r\n public void onError(Exception e) {\r\n byte msgType = org.apache.thrift.protocol.TMessageType.REPLY;\r\n org.apache.thrift.TBase msg;\r\n getAdminNodeId_result result = new getAdminNodeId_result();\r\n {\r\n msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;\r\n msg = (org.apache.thrift.TBase)new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage());\r\n }\r\n try {\r\n fcall.sendResponse(fb,msg,msgType,seqid);\r\n return;\r\n } catch (Exception ex) {\r\n LOGGER.error(\"Exception writing to internal frame buffer\", ex);\r\n }\r\n fb.close();\r\n }\r\n };\r\n }\r\n\r\n protected boolean isOneway() {\r\n return false;\r\n }\r\n\r\n public void start(I iface, getAdminNodeId_args args, org.apache.thrift.async.AsyncMethodCallback<Integer> resultHandler) throws TException {\r\n iface.getAdminNodeId(resultHandler);\r\n }\r\n }\r\n\r\n public static class getHealthStatus<I extends AsyncIface> extends org.apache.thrift.AsyncProcessFunction<I, getHealthStatus_args, Integer> {\r\n public getHealthStatus() {\r\n super(\"getHealthStatus\");\r\n }\r\n\r\n public getHealthStatus_args getEmptyArgsInstance() {\r\n return new getHealthStatus_args();\r\n }\r\n\r\n public AsyncMethodCallback<Integer> getResultHandler(final AsyncFrameBuffer fb, final int seqid) {\r\n final org.apache.thrift.AsyncProcessFunction fcall = this;\r\n return new AsyncMethodCallback<Integer>() { \r\n public void onComplete(Integer o) {\r\n getHealthStatus_result result = new getHealthStatus_result();\r\n result.success = o;\r\n result.setSuccessIsSet(true);\r\n try {\r\n fcall.sendResponse(fb,result, org.apache.thrift.protocol.TMessageType.REPLY,seqid);\r\n return;\r\n } catch (Exception e) {\r\n LOGGER.error(\"Exception writing to internal frame buffer\", e);\r\n }\r\n fb.close();\r\n }\r\n public void onError(Exception e) {\r\n byte msgType = org.apache.thrift.protocol.TMessageType.REPLY;\r\n org.apache.thrift.TBase msg;\r\n getHealthStatus_result result = new getHealthStatus_result();\r\n {\r\n msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;\r\n msg = (org.apache.thrift.TBase)new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage());\r\n }\r\n try {\r\n fcall.sendResponse(fb,msg,msgType,seqid);\r\n return;\r\n } catch (Exception ex) {\r\n LOGGER.error(\"Exception writing to internal frame buffer\", ex);\r\n }\r\n fb.close();\r\n }\r\n };\r\n }\r\n\r\n protected boolean isOneway() {\r\n return false;\r\n }\r\n\r\n public void start(I iface, getHealthStatus_args args, org.apache.thrift.async.AsyncMethodCallback<Integer> resultHandler) throws TException {\r\n iface.getHealthStatus(resultHandler);\r\n }\r\n }\r\n\r\n public static class getJobStatus<I extends AsyncIface> extends org.apache.thrift.AsyncProcessFunction<I, getJobStatus_args, Integer> {\r\n public getJobStatus() {\r\n super(\"getJobStatus\");\r\n }\r\n\r\n public getJobStatus_args getEmptyArgsInstance() {\r\n return new getJobStatus_args();\r\n }\r\n\r\n public AsyncMethodCallback<Integer> getResultHandler(final AsyncFrameBuffer fb, final int seqid) {\r\n final org.apache.thrift.AsyncProcessFunction fcall = this;\r\n return new AsyncMethodCallback<Integer>() { \r\n public void onComplete(Integer o) {\r\n getJobStatus_result result = new getJobStatus_result();\r\n result.success = o;\r\n result.setSuccessIsSet(true);\r\n try {\r\n fcall.sendResponse(fb,result, org.apache.thrift.protocol.TMessageType.REPLY,seqid);\r\n return;\r\n } catch (Exception e) {\r\n LOGGER.error(\"Exception writing to internal frame buffer\", e);\r\n }\r\n fb.close();\r\n }\r\n public void onError(Exception e) {\r\n byte msgType = org.apache.thrift.protocol.TMessageType.REPLY;\r\n org.apache.thrift.TBase msg;\r\n getJobStatus_result result = new getJobStatus_result();\r\n {\r\n msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;\r\n msg = (org.apache.thrift.TBase)new org.apache.thrift.TApplicationException(org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage());\r\n }\r\n try {\r\n fcall.sendResponse(fb,msg,msgType,seqid);\r\n return;\r\n } catch (Exception ex) {\r\n LOGGER.error(\"Exception writing to internal frame buffer\", ex);\r\n }\r\n fb.close();\r\n }\r\n };\r\n }\r\n\r\n protected boolean isOneway() {\r\n return false;\r\n }\r\n\r\n public void start(I iface, getJobStatus_args args, org.apache.thrift.async.AsyncMethodCallback<Integer> resultHandler) throws TException {\r\n iface.getJobStatus(resultHandler);\r\n }\r\n }\r\n\r\n }\r\n\r\n public static class addMqinfoToAdminQu_args implements org.apache.thrift.TBase<addMqinfoToAdminQu_args, addMqinfoToAdminQu_args._Fields>, java.io.Serializable, Cloneable, Comparable<addMqinfoToAdminQu_args> {\r\n private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct(\"addMqinfoToAdminQu_args\");\r\n\r\n private static final org.apache.thrift.protocol.TField U_LOGS_FIELD_DESC = new org.apache.thrift.protocol.TField(\"uLogs\", org.apache.thrift.protocol.TType.LIST, (short)1);\r\n\r\n private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();\r\n static {\r\n schemes.put(StandardScheme.class, new addMqinfoToAdminQu_argsStandardSchemeFactory());\r\n schemes.put(TupleScheme.class, new addMqinfoToAdminQu_argsTupleSchemeFactory());\r\n }\r\n\r\n public List<String> uLogs; // required\r\n\r\n /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */\r\n public enum _Fields implements org.apache.thrift.TFieldIdEnum {\r\n U_LOGS((short)1, \"uLogs\");\r\n\r\n private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();\r\n\r\n static {\r\n for (_Fields field : EnumSet.allOf(_Fields.class)) {\r\n byName.put(field.getFieldName(), field);\r\n }\r\n }\r\n\r\n /**\r\n * Find the _Fields constant that matches fieldId, or null if its not found.\r\n */\r\n public static _Fields findByThriftId(int fieldId) {\r\n switch(fieldId) {\r\n case 1: // U_LOGS\r\n return U_LOGS;\r\n default:\r\n return null;\r\n }\r\n }\r\n\r\n /**\r\n * Find the _Fields constant that matches fieldId, throwing an exception\r\n * if it is not found.\r\n */\r\n public static _Fields findByThriftIdOrThrow(int fieldId) {\r\n _Fields fields = findByThriftId(fieldId);\r\n if (fields == null) throw new IllegalArgumentException(\"Field \" + fieldId + \" doesn't exist!\");\r\n return fields;\r\n }\r\n\r\n /**\r\n * Find the _Fields constant that matches name, or null if its not found.\r\n */\r\n public static _Fields findByName(String name) {\r\n return byName.get(name);\r\n }\r\n\r\n private final short _thriftId;\r\n private final String _fieldName;\r\n\r\n _Fields(short thriftId, String fieldName) {\r\n _thriftId = thriftId;\r\n _fieldName = fieldName;\r\n }\r\n\r\n public short getThriftFieldId() {\r\n return _thriftId;\r\n }\r\n\r\n public String getFieldName() {\r\n return _fieldName;\r\n }\r\n }\r\n\r\n // isset id assignments\r\n public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;\r\n static {\r\n Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);\r\n tmpMap.put(_Fields.U_LOGS, new org.apache.thrift.meta_data.FieldMetaData(\"uLogs\", org.apache.thrift.TFieldRequirementType.DEFAULT, \r\n new org.apache.thrift.meta_data.ListMetaData(org.apache.thrift.protocol.TType.LIST, \r\n new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))));\r\n metaDataMap = Collections.unmodifiableMap(tmpMap);\r\n org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(addMqinfoToAdminQu_args.class, metaDataMap);\r\n }\r\n\r\n public addMqinfoToAdminQu_args() {\r\n }\r\n\r\n public addMqinfoToAdminQu_args(\r\n List<String> uLogs)\r\n {\r\n this();\r\n this.uLogs = uLogs;\r\n }\r\n\r\n /**\r\n * Performs a deep copy on <i>other</i>.\r\n */\r\n public addMqinfoToAdminQu_args(addMqinfoToAdminQu_args other) {\r\n if (other.isSetULogs()) {\r\n List<String> __this__uLogs = new ArrayList<String>(other.uLogs);\r\n this.uLogs = __this__uLogs;\r\n }\r\n }\r\n\r\n public addMqinfoToAdminQu_args deepCopy() {\r\n return new addMqinfoToAdminQu_args(this);\r\n }\r\n\r\n @Override\r\n public void clear() {\r\n this.uLogs = null;\r\n }\r\n\r\n public int getULogsSize() {\r\n return (this.uLogs == null) ? 0 : this.uLogs.size();\r\n }\r\n\r\n public java.util.Iterator<String> getULogsIterator() {\r\n return (this.uLogs == null) ? null : this.uLogs.iterator();\r\n }\r\n\r\n public void addToULogs(String elem) {\r\n if (this.uLogs == null) {\r\n this.uLogs = new ArrayList<String>();\r\n }\r\n this.uLogs.add(elem);\r\n }\r\n\r\n public List<String> getULogs() {\r\n return this.uLogs;\r\n }\r\n\r\n public addMqinfoToAdminQu_args setULogs(List<String> uLogs) {\r\n this.uLogs = uLogs;\r\n return this;\r\n }\r\n\r\n public void unsetULogs() {\r\n this.uLogs = null;\r\n }\r\n\r\n /** Returns true if field uLogs is set (has been assigned a value) and false otherwise */\r\n public boolean isSetULogs() {\r\n return this.uLogs != null;\r\n }\r\n\r\n public void setULogsIsSet(boolean value) {\r\n if (!value) {\r\n this.uLogs = null;\r\n }\r\n }\r\n\r\n public void setFieldValue(_Fields field, Object value) {\r\n switch (field) {\r\n case U_LOGS:\r\n if (value == null) {\r\n unsetULogs();\r\n } else {\r\n setULogs((List<String>)value);\r\n }\r\n break;\r\n\r\n }\r\n }\r\n\r\n public Object getFieldValue(_Fields field) {\r\n switch (field) {\r\n case U_LOGS:\r\n return getULogs();\r\n\r\n }\r\n throw new IllegalStateException();\r\n }\r\n\r\n /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */\r\n public boolean isSet(_Fields field) {\r\n if (field == null) {\r\n throw new IllegalArgumentException();\r\n }\r\n\r\n switch (field) {\r\n case U_LOGS:\r\n return isSetULogs();\r\n }\r\n throw new IllegalStateException();\r\n }\r\n\r\n @Override\r\n public boolean equals(Object that) {\r\n if (that == null)\r\n return false;\r\n if (that instanceof addMqinfoToAdminQu_args)\r\n return this.equals((addMqinfoToAdminQu_args)that);\r\n return false;\r\n }\r\n\r\n public boolean equals(addMqinfoToAdminQu_args that) {\r\n if (that == null)\r\n return false;\r\n\r\n boolean this_present_uLogs = true && this.isSetULogs();\r\n boolean that_present_uLogs = true && that.isSetULogs();\r\n if (this_present_uLogs || that_present_uLogs) {\r\n if (!(this_present_uLogs && that_present_uLogs))\r\n return false;\r\n if (!this.uLogs.equals(that.uLogs))\r\n return false;\r\n }\r\n\r\n return true;\r\n }\r\n\r\n @Override\r\n public int hashCode() {\r\n List<Object> list = new ArrayList<Object>();\r\n\r\n boolean present_uLogs = true && (isSetULogs());\r\n list.add(present_uLogs);\r\n if (present_uLogs)\r\n list.add(uLogs);\r\n\r\n return list.hashCode();\r\n }\r\n\r\n @Override\r\n public int compareTo(addMqinfoToAdminQu_args other) {\r\n if (!getClass().equals(other.getClass())) {\r\n return getClass().getName().compareTo(other.getClass().getName());\r\n }\r\n\r\n int lastComparison = 0;\r\n\r\n lastComparison = Boolean.valueOf(isSetULogs()).compareTo(other.isSetULogs());\r\n if (lastComparison != 0) {\r\n return lastComparison;\r\n }\r\n if (isSetULogs()) {\r\n lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.uLogs, other.uLogs);\r\n if (lastComparison != 0) {\r\n return lastComparison;\r\n }\r\n }\r\n return 0;\r\n }\r\n\r\n public _Fields fieldForId(int fieldId) {\r\n return _Fields.findByThriftId(fieldId);\r\n }\r\n\r\n public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {\r\n schemes.get(iprot.getScheme()).getScheme().read(iprot, this);\r\n }\r\n\r\n public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {\r\n schemes.get(oprot.getScheme()).getScheme().write(oprot, this);\r\n }\r\n\r\n @Override\r\n public String toString() {\r\n StringBuilder sb = new StringBuilder(\"addMqinfoToAdminQu_args(\");\r\n boolean first = true;\r\n\r\n sb.append(\"uLogs:\");\r\n if (this.uLogs == null) {\r\n sb.append(\"null\");\r\n } else {\r\n sb.append(this.uLogs);\r\n }\r\n first = false;\r\n sb.append(\")\");\r\n return sb.toString();\r\n }\r\n\r\n public void validate() throws org.apache.thrift.TException {\r\n // check for required fields\r\n // check for sub-struct validity\r\n }\r\n\r\n private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {\r\n try {\r\n write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));\r\n } catch (org.apache.thrift.TException te) {\r\n throw new java.io.IOException(te);\r\n }\r\n }\r\n\r\n private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {\r\n try {\r\n read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));\r\n } catch (org.apache.thrift.TException te) {\r\n throw new java.io.IOException(te);\r\n }\r\n }\r\n\r\n private static class addMqinfoToAdminQu_argsStandardSchemeFactory implements SchemeFactory {\r\n public addMqinfoToAdminQu_argsStandardScheme getScheme() {\r\n return new addMqinfoToAdminQu_argsStandardScheme();\r\n }\r\n }\r\n\r\n private static class addMqinfoToAdminQu_argsStandardScheme extends StandardScheme<addMqinfoToAdminQu_args> {\r\n\r\n public void read(org.apache.thrift.protocol.TProtocol iprot, addMqinfoToAdminQu_args struct) throws org.apache.thrift.TException {\r\n org.apache.thrift.protocol.TField schemeField;\r\n iprot.readStructBegin();\r\n while (true)\r\n {\r\n schemeField = iprot.readFieldBegin();\r\n if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { \r\n break;\r\n }\r\n switch (schemeField.id) {\r\n case 1: // U_LOGS\r\n if (schemeField.type == org.apache.thrift.protocol.TType.LIST) {\r\n {\r\n org.apache.thrift.protocol.TList _list0 = iprot.readListBegin();\r\n struct.uLogs = new ArrayList<String>(_list0.size);\r\n String _elem1;\r\n for (int _i2 = 0; _i2 < _list0.size; ++_i2)\r\n {\r\n _elem1 = iprot.readString();\r\n struct.uLogs.add(_elem1);\r\n }\r\n iprot.readListEnd();\r\n }\r\n struct.setULogsIsSet(true);\r\n } else { \r\n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\r\n }\r\n break;\r\n default:\r\n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\r\n }\r\n iprot.readFieldEnd();\r\n }\r\n iprot.readStructEnd();\r\n\r\n // check for required fields of primitive type, which can't be checked in the validate method\r\n struct.validate();\r\n }\r\n\r\n public void write(org.apache.thrift.protocol.TProtocol oprot, addMqinfoToAdminQu_args struct) throws org.apache.thrift.TException {\r\n struct.validate();\r\n\r\n oprot.writeStructBegin(STRUCT_DESC);\r\n if (struct.uLogs != null) {\r\n oprot.writeFieldBegin(U_LOGS_FIELD_DESC);\r\n {\r\n oprot.writeListBegin(new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRING, struct.uLogs.size()));\r\n for (String _iter3 : struct.uLogs)\r\n {\r\n oprot.writeString(_iter3);\r\n }\r\n oprot.writeListEnd();\r\n }\r\n oprot.writeFieldEnd();\r\n }\r\n oprot.writeFieldStop();\r\n oprot.writeStructEnd();\r\n }\r\n\r\n }\r\n\r\n private static class addMqinfoToAdminQu_argsTupleSchemeFactory implements SchemeFactory {\r\n public addMqinfoToAdminQu_argsTupleScheme getScheme() {\r\n return new addMqinfoToAdminQu_argsTupleScheme();\r\n }\r\n }\r\n\r\n private static class addMqinfoToAdminQu_argsTupleScheme extends TupleScheme<addMqinfoToAdminQu_args> {\r\n\r\n @Override\r\n public void write(org.apache.thrift.protocol.TProtocol prot, addMqinfoToAdminQu_args struct) throws org.apache.thrift.TException {\r\n TTupleProtocol oprot = (TTupleProtocol) prot;\r\n BitSet optionals = new BitSet();\r\n if (struct.isSetULogs()) {\r\n optionals.set(0);\r\n }\r\n oprot.writeBitSet(optionals, 1);\r\n if (struct.isSetULogs()) {\r\n {\r\n oprot.writeI32(struct.uLogs.size());\r\n for (String _iter4 : struct.uLogs)\r\n {\r\n oprot.writeString(_iter4);\r\n }\r\n }\r\n }\r\n }\r\n\r\n @Override\r\n public void read(org.apache.thrift.protocol.TProtocol prot, addMqinfoToAdminQu_args struct) throws org.apache.thrift.TException {\r\n TTupleProtocol iprot = (TTupleProtocol) prot;\r\n BitSet incoming = iprot.readBitSet(1);\r\n if (incoming.get(0)) {\r\n {\r\n org.apache.thrift.protocol.TList _list5 = new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRING, iprot.readI32());\r\n struct.uLogs = new ArrayList<String>(_list5.size);\r\n String _elem6;\r\n for (int _i7 = 0; _i7 < _list5.size; ++_i7)\r\n {\r\n _elem6 = iprot.readString();\r\n struct.uLogs.add(_elem6);\r\n }\r\n }\r\n struct.setULogsIsSet(true);\r\n }\r\n }\r\n }\r\n\r\n }\r\n\r\n public static class addMqinfoToAdminQu_result implements org.apache.thrift.TBase<addMqinfoToAdminQu_result, addMqinfoToAdminQu_result._Fields>, java.io.Serializable, Cloneable, Comparable<addMqinfoToAdminQu_result> {\r\n private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct(\"addMqinfoToAdminQu_result\");\r\n\r\n private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField(\"success\", org.apache.thrift.protocol.TType.I32, (short)0);\r\n\r\n private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();\r\n static {\r\n schemes.put(StandardScheme.class, new addMqinfoToAdminQu_resultStandardSchemeFactory());\r\n schemes.put(TupleScheme.class, new addMqinfoToAdminQu_resultTupleSchemeFactory());\r\n }\r\n\r\n public int success; // required\r\n\r\n /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */\r\n public enum _Fields implements org.apache.thrift.TFieldIdEnum {\r\n SUCCESS((short)0, \"success\");\r\n\r\n private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();\r\n\r\n static {\r\n for (_Fields field : EnumSet.allOf(_Fields.class)) {\r\n byName.put(field.getFieldName(), field);\r\n }\r\n }\r\n\r\n /**\r\n * Find the _Fields constant that matches fieldId, or null if its not found.\r\n */\r\n public static _Fields findByThriftId(int fieldId) {\r\n switch(fieldId) {\r\n case 0: // SUCCESS\r\n return SUCCESS;\r\n default:\r\n return null;\r\n }\r\n }\r\n\r\n /**\r\n * Find the _Fields constant that matches fieldId, throwing an exception\r\n * if it is not found.\r\n */\r\n public static _Fields findByThriftIdOrThrow(int fieldId) {\r\n _Fields fields = findByThriftId(fieldId);\r\n if (fields == null) throw new IllegalArgumentException(\"Field \" + fieldId + \" doesn't exist!\");\r\n return fields;\r\n }\r\n\r\n /**\r\n * Find the _Fields constant that matches name, or null if its not found.\r\n */\r\n public static _Fields findByName(String name) {\r\n return byName.get(name);\r\n }\r\n\r\n private final short _thriftId;\r\n private final String _fieldName;\r\n\r\n _Fields(short thriftId, String fieldName) {\r\n _thriftId = thriftId;\r\n _fieldName = fieldName;\r\n }\r\n\r\n public short getThriftFieldId() {\r\n return _thriftId;\r\n }\r\n\r\n public String getFieldName() {\r\n return _fieldName;\r\n }\r\n }\r\n\r\n // isset id assignments\r\n private static final int __SUCCESS_ISSET_ID = 0;\r\n private byte __isset_bitfield = 0;\r\n public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;\r\n static {\r\n Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);\r\n tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData(\"success\", org.apache.thrift.TFieldRequirementType.DEFAULT, \r\n new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32)));\r\n metaDataMap = Collections.unmodifiableMap(tmpMap);\r\n org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(addMqinfoToAdminQu_result.class, metaDataMap);\r\n }\r\n\r\n public addMqinfoToAdminQu_result() {\r\n }\r\n\r\n public addMqinfoToAdminQu_result(\r\n int success)\r\n {\r\n this();\r\n this.success = success;\r\n setSuccessIsSet(true);\r\n }\r\n\r\n /**\r\n * Performs a deep copy on <i>other</i>.\r\n */\r\n public addMqinfoToAdminQu_result(addMqinfoToAdminQu_result other) {\r\n __isset_bitfield = other.__isset_bitfield;\r\n this.success = other.success;\r\n }\r\n\r\n public addMqinfoToAdminQu_result deepCopy() {\r\n return new addMqinfoToAdminQu_result(this);\r\n }\r\n\r\n @Override\r\n public void clear() {\r\n setSuccessIsSet(false);\r\n this.success = 0;\r\n }\r\n\r\n public int getSuccess() {\r\n return this.success;\r\n }\r\n\r\n public addMqinfoToAdminQu_result setSuccess(int success) {\r\n this.success = success;\r\n setSuccessIsSet(true);\r\n return this;\r\n }\r\n\r\n public void unsetSuccess() {\r\n __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __SUCCESS_ISSET_ID);\r\n }\r\n\r\n /** Returns true if field success is set (has been assigned a value) and false otherwise */\r\n public boolean isSetSuccess() {\r\n return EncodingUtils.testBit(__isset_bitfield, __SUCCESS_ISSET_ID);\r\n }\r\n\r\n public void setSuccessIsSet(boolean value) {\r\n __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __SUCCESS_ISSET_ID, value);\r\n }\r\n\r\n public void setFieldValue(_Fields field, Object value) {\r\n switch (field) {\r\n case SUCCESS:\r\n if (value == null) {\r\n unsetSuccess();\r\n } else {\r\n setSuccess((Integer)value);\r\n }\r\n break;\r\n\r\n }\r\n }\r\n\r\n public Object getFieldValue(_Fields field) {\r\n switch (field) {\r\n case SUCCESS:\r\n return getSuccess();\r\n\r\n }\r\n throw new IllegalStateException();\r\n }\r\n\r\n /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */\r\n public boolean isSet(_Fields field) {\r\n if (field == null) {\r\n throw new IllegalArgumentException();\r\n }\r\n\r\n switch (field) {\r\n case SUCCESS:\r\n return isSetSuccess();\r\n }\r\n throw new IllegalStateException();\r\n }\r\n\r\n @Override\r\n public boolean equals(Object that) {\r\n if (that == null)\r\n return false;\r\n if (that instanceof addMqinfoToAdminQu_result)\r\n return this.equals((addMqinfoToAdminQu_result)that);\r\n return false;\r\n }\r\n\r\n public boolean equals(addMqinfoToAdminQu_result that) {\r\n if (that == null)\r\n return false;\r\n\r\n boolean this_present_success = true;\r\n boolean that_present_success = true;\r\n if (this_present_success || that_present_success) {\r\n if (!(this_present_success && that_present_success))\r\n return false;\r\n if (this.success != that.success)\r\n return false;\r\n }\r\n\r\n return true;\r\n }\r\n\r\n @Override\r\n public int hashCode() {\r\n List<Object> list = new ArrayList<Object>();\r\n\r\n boolean present_success = true;\r\n list.add(present_success);\r\n if (present_success)\r\n list.add(success);\r\n\r\n return list.hashCode();\r\n }\r\n\r\n @Override\r\n public int compareTo(addMqinfoToAdminQu_result other) {\r\n if (!getClass().equals(other.getClass())) {\r\n return getClass().getName().compareTo(other.getClass().getName());\r\n }\r\n\r\n int lastComparison = 0;\r\n\r\n lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess());\r\n if (lastComparison != 0) {\r\n return lastComparison;\r\n }\r\n if (isSetSuccess()) {\r\n lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success);\r\n if (lastComparison != 0) {\r\n return lastComparison;\r\n }\r\n }\r\n return 0;\r\n }\r\n\r\n public _Fields fieldForId(int fieldId) {\r\n return _Fields.findByThriftId(fieldId);\r\n }\r\n\r\n public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {\r\n schemes.get(iprot.getScheme()).getScheme().read(iprot, this);\r\n }\r\n\r\n public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {\r\n schemes.get(oprot.getScheme()).getScheme().write(oprot, this);\r\n }\r\n\r\n @Override\r\n public String toString() {\r\n StringBuilder sb = new StringBuilder(\"addMqinfoToAdminQu_result(\");\r\n boolean first = true;\r\n\r\n sb.append(\"success:\");\r\n sb.append(this.success);\r\n first = false;\r\n sb.append(\")\");\r\n return sb.toString();\r\n }\r\n\r\n public void validate() throws org.apache.thrift.TException {\r\n // check for required fields\r\n // check for sub-struct validity\r\n }\r\n\r\n private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {\r\n try {\r\n write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));\r\n } catch (org.apache.thrift.TException te) {\r\n throw new java.io.IOException(te);\r\n }\r\n }\r\n\r\n private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {\r\n try {\r\n // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor.\r\n __isset_bitfield = 0;\r\n read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));\r\n } catch (org.apache.thrift.TException te) {\r\n throw new java.io.IOException(te);\r\n }\r\n }\r\n\r\n private static class addMqinfoToAdminQu_resultStandardSchemeFactory implements SchemeFactory {\r\n public addMqinfoToAdminQu_resultStandardScheme getScheme() {\r\n return new addMqinfoToAdminQu_resultStandardScheme();\r\n }\r\n }\r\n\r\n private static class addMqinfoToAdminQu_resultStandardScheme extends StandardScheme<addMqinfoToAdminQu_result> {\r\n\r\n public void read(org.apache.thrift.protocol.TProtocol iprot, addMqinfoToAdminQu_result struct) throws org.apache.thrift.TException {\r\n org.apache.thrift.protocol.TField schemeField;\r\n iprot.readStructBegin();\r\n while (true)\r\n {\r\n schemeField = iprot.readFieldBegin();\r\n if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { \r\n break;\r\n }\r\n switch (schemeField.id) {\r\n case 0: // SUCCESS\r\n if (schemeField.type == org.apache.thrift.protocol.TType.I32) {\r\n struct.success = iprot.readI32();\r\n struct.setSuccessIsSet(true);\r\n } else { \r\n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\r\n }\r\n break;\r\n default:\r\n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\r\n }\r\n iprot.readFieldEnd();\r\n }\r\n iprot.readStructEnd();\r\n\r\n // check for required fields of primitive type, which can't be checked in the validate method\r\n struct.validate();\r\n }\r\n\r\n public void write(org.apache.thrift.protocol.TProtocol oprot, addMqinfoToAdminQu_result struct) throws org.apache.thrift.TException {\r\n struct.validate();\r\n\r\n oprot.writeStructBegin(STRUCT_DESC);\r\n if (struct.isSetSuccess()) {\r\n oprot.writeFieldBegin(SUCCESS_FIELD_DESC);\r\n oprot.writeI32(struct.success);\r\n oprot.writeFieldEnd();\r\n }\r\n oprot.writeFieldStop();\r\n oprot.writeStructEnd();\r\n }\r\n\r\n }\r\n\r\n private static class addMqinfoToAdminQu_resultTupleSchemeFactory implements SchemeFactory {\r\n public addMqinfoToAdminQu_resultTupleScheme getScheme() {\r\n return new addMqinfoToAdminQu_resultTupleScheme();\r\n }\r\n }\r\n\r\n private static class addMqinfoToAdminQu_resultTupleScheme extends TupleScheme<addMqinfoToAdminQu_result> {\r\n\r\n @Override\r\n public void write(org.apache.thrift.protocol.TProtocol prot, addMqinfoToAdminQu_result struct) throws org.apache.thrift.TException {\r\n TTupleProtocol oprot = (TTupleProtocol) prot;\r\n BitSet optionals = new BitSet();\r\n if (struct.isSetSuccess()) {\r\n optionals.set(0);\r\n }\r\n oprot.writeBitSet(optionals, 1);\r\n if (struct.isSetSuccess()) {\r\n oprot.writeI32(struct.success);\r\n }\r\n }\r\n\r\n @Override\r\n public void read(org.apache.thrift.protocol.TProtocol prot, addMqinfoToAdminQu_result struct) throws org.apache.thrift.TException {\r\n TTupleProtocol iprot = (TTupleProtocol) prot;\r\n BitSet incoming = iprot.readBitSet(1);\r\n if (incoming.get(0)) {\r\n struct.success = iprot.readI32();\r\n struct.setSuccessIsSet(true);\r\n }\r\n }\r\n }\r\n\r\n }\r\n\r\n public static class rtcStats_args implements org.apache.thrift.TBase<rtcStats_args, rtcStats_args._Fields>, java.io.Serializable, Cloneable, Comparable<rtcStats_args> {\r\n private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct(\"rtcStats_args\");\r\n\r\n private static final org.apache.thrift.protocol.TField USER_LOGS_FIELD_DESC = new org.apache.thrift.protocol.TField(\"userLogs\", org.apache.thrift.protocol.TType.LIST, (short)1);\r\n\r\n private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();\r\n static {\r\n schemes.put(StandardScheme.class, new rtcStats_argsStandardSchemeFactory());\r\n schemes.put(TupleScheme.class, new rtcStats_argsTupleSchemeFactory());\r\n }\r\n\r\n public List<String> userLogs; // required\r\n\r\n /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */\r\n public enum _Fields implements org.apache.thrift.TFieldIdEnum {\r\n USER_LOGS((short)1, \"userLogs\");\r\n\r\n private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();\r\n\r\n static {\r\n for (_Fields field : EnumSet.allOf(_Fields.class)) {\r\n byName.put(field.getFieldName(), field);\r\n }\r\n }\r\n\r\n /**\r\n * Find the _Fields constant that matches fieldId, or null if its not found.\r\n */\r\n public static _Fields findByThriftId(int fieldId) {\r\n switch(fieldId) {\r\n case 1: // USER_LOGS\r\n return USER_LOGS;\r\n default:\r\n return null;\r\n }\r\n }\r\n\r\n /**\r\n * Find the _Fields constant that matches fieldId, throwing an exception\r\n * if it is not found.\r\n */\r\n public static _Fields findByThriftIdOrThrow(int fieldId) {\r\n _Fields fields = findByThriftId(fieldId);\r\n if (fields == null) throw new IllegalArgumentException(\"Field \" + fieldId + \" doesn't exist!\");\r\n return fields;\r\n }\r\n\r\n /**\r\n * Find the _Fields constant that matches name, or null if its not found.\r\n */\r\n public static _Fields findByName(String name) {\r\n return byName.get(name);\r\n }\r\n\r\n private final short _thriftId;\r\n private final String _fieldName;\r\n\r\n _Fields(short thriftId, String fieldName) {\r\n _thriftId = thriftId;\r\n _fieldName = fieldName;\r\n }\r\n\r\n public short getThriftFieldId() {\r\n return _thriftId;\r\n }\r\n\r\n public String getFieldName() {\r\n return _fieldName;\r\n }\r\n }\r\n\r\n // isset id assignments\r\n public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;\r\n static {\r\n Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);\r\n tmpMap.put(_Fields.USER_LOGS, new org.apache.thrift.meta_data.FieldMetaData(\"userLogs\", org.apache.thrift.TFieldRequirementType.DEFAULT, \r\n new org.apache.thrift.meta_data.ListMetaData(org.apache.thrift.protocol.TType.LIST, \r\n new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING))));\r\n metaDataMap = Collections.unmodifiableMap(tmpMap);\r\n org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(rtcStats_args.class, metaDataMap);\r\n }\r\n\r\n public rtcStats_args() {\r\n }\r\n\r\n public rtcStats_args(\r\n List<String> userLogs)\r\n {\r\n this();\r\n this.userLogs = userLogs;\r\n }\r\n\r\n /**\r\n * Performs a deep copy on <i>other</i>.\r\n */\r\n public rtcStats_args(rtcStats_args other) {\r\n if (other.isSetUserLogs()) {\r\n List<String> __this__userLogs = new ArrayList<String>(other.userLogs);\r\n this.userLogs = __this__userLogs;\r\n }\r\n }\r\n\r\n public rtcStats_args deepCopy() {\r\n return new rtcStats_args(this);\r\n }\r\n\r\n @Override\r\n public void clear() {\r\n this.userLogs = null;\r\n }\r\n\r\n public int getUserLogsSize() {\r\n return (this.userLogs == null) ? 0 : this.userLogs.size();\r\n }\r\n\r\n public java.util.Iterator<String> getUserLogsIterator() {\r\n return (this.userLogs == null) ? null : this.userLogs.iterator();\r\n }\r\n\r\n public void addToUserLogs(String elem) {\r\n if (this.userLogs == null) {\r\n this.userLogs = new ArrayList<String>();\r\n }\r\n this.userLogs.add(elem);\r\n }\r\n\r\n public List<String> getUserLogs() {\r\n return this.userLogs;\r\n }\r\n\r\n public rtcStats_args setUserLogs(List<String> userLogs) {\r\n this.userLogs = userLogs;\r\n return this;\r\n }\r\n\r\n public void unsetUserLogs() {\r\n this.userLogs = null;\r\n }\r\n\r\n /** Returns true if field userLogs is set (has been assigned a value) and false otherwise */\r\n public boolean isSetUserLogs() {\r\n return this.userLogs != null;\r\n }\r\n\r\n public void setUserLogsIsSet(boolean value) {\r\n if (!value) {\r\n this.userLogs = null;\r\n }\r\n }\r\n\r\n public void setFieldValue(_Fields field, Object value) {\r\n switch (field) {\r\n case USER_LOGS:\r\n if (value == null) {\r\n unsetUserLogs();\r\n } else {\r\n setUserLogs((List<String>)value);\r\n }\r\n break;\r\n\r\n }\r\n }\r\n\r\n public Object getFieldValue(_Fields field) {\r\n switch (field) {\r\n case USER_LOGS:\r\n return getUserLogs();\r\n\r\n }\r\n throw new IllegalStateException();\r\n }\r\n\r\n /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */\r\n public boolean isSet(_Fields field) {\r\n if (field == null) {\r\n throw new IllegalArgumentException();\r\n }\r\n\r\n switch (field) {\r\n case USER_LOGS:\r\n return isSetUserLogs();\r\n }\r\n throw new IllegalStateException();\r\n }\r\n\r\n @Override\r\n public boolean equals(Object that) {\r\n if (that == null)\r\n return false;\r\n if (that instanceof rtcStats_args)\r\n return this.equals((rtcStats_args)that);\r\n return false;\r\n }\r\n\r\n public boolean equals(rtcStats_args that) {\r\n if (that == null)\r\n return false;\r\n\r\n boolean this_present_userLogs = true && this.isSetUserLogs();\r\n boolean that_present_userLogs = true && that.isSetUserLogs();\r\n if (this_present_userLogs || that_present_userLogs) {\r\n if (!(this_present_userLogs && that_present_userLogs))\r\n return false;\r\n if (!this.userLogs.equals(that.userLogs))\r\n return false;\r\n }\r\n\r\n return true;\r\n }\r\n\r\n @Override\r\n public int hashCode() {\r\n List<Object> list = new ArrayList<Object>();\r\n\r\n boolean present_userLogs = true && (isSetUserLogs());\r\n list.add(present_userLogs);\r\n if (present_userLogs)\r\n list.add(userLogs);\r\n\r\n return list.hashCode();\r\n }\r\n\r\n @Override\r\n public int compareTo(rtcStats_args other) {\r\n if (!getClass().equals(other.getClass())) {\r\n return getClass().getName().compareTo(other.getClass().getName());\r\n }\r\n\r\n int lastComparison = 0;\r\n\r\n lastComparison = Boolean.valueOf(isSetUserLogs()).compareTo(other.isSetUserLogs());\r\n if (lastComparison != 0) {\r\n return lastComparison;\r\n }\r\n if (isSetUserLogs()) {\r\n lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.userLogs, other.userLogs);\r\n if (lastComparison != 0) {\r\n return lastComparison;\r\n }\r\n }\r\n return 0;\r\n }\r\n\r\n public _Fields fieldForId(int fieldId) {\r\n return _Fields.findByThriftId(fieldId);\r\n }\r\n\r\n public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {\r\n schemes.get(iprot.getScheme()).getScheme().read(iprot, this);\r\n }\r\n\r\n public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {\r\n schemes.get(oprot.getScheme()).getScheme().write(oprot, this);\r\n }\r\n\r\n @Override\r\n public String toString() {\r\n StringBuilder sb = new StringBuilder(\"rtcStats_args(\");\r\n boolean first = true;\r\n\r\n sb.append(\"userLogs:\");\r\n if (this.userLogs == null) {\r\n sb.append(\"null\");\r\n } else {\r\n sb.append(this.userLogs);\r\n }\r\n first = false;\r\n sb.append(\")\");\r\n return sb.toString();\r\n }\r\n\r\n public void validate() throws org.apache.thrift.TException {\r\n // check for required fields\r\n // check for sub-struct validity\r\n }\r\n\r\n private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {\r\n try {\r\n write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));\r\n } catch (org.apache.thrift.TException te) {\r\n throw new java.io.IOException(te);\r\n }\r\n }\r\n\r\n private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {\r\n try {\r\n read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));\r\n } catch (org.apache.thrift.TException te) {\r\n throw new java.io.IOException(te);\r\n }\r\n }\r\n\r\n private static class rtcStats_argsStandardSchemeFactory implements SchemeFactory {\r\n public rtcStats_argsStandardScheme getScheme() {\r\n return new rtcStats_argsStandardScheme();\r\n }\r\n }\r\n\r\n private static class rtcStats_argsStandardScheme extends StandardScheme<rtcStats_args> {\r\n\r\n public void read(org.apache.thrift.protocol.TProtocol iprot, rtcStats_args struct) throws org.apache.thrift.TException {\r\n org.apache.thrift.protocol.TField schemeField;\r\n iprot.readStructBegin();\r\n while (true)\r\n {\r\n schemeField = iprot.readFieldBegin();\r\n if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { \r\n break;\r\n }\r\n switch (schemeField.id) {\r\n case 1: // USER_LOGS\r\n if (schemeField.type == org.apache.thrift.protocol.TType.LIST) {\r\n {\r\n org.apache.thrift.protocol.TList _list8 = iprot.readListBegin();\r\n struct.userLogs = new ArrayList<String>(_list8.size);\r\n String _elem9;\r\n for (int _i10 = 0; _i10 < _list8.size; ++_i10)\r\n {\r\n _elem9 = iprot.readString();\r\n struct.userLogs.add(_elem9);\r\n }\r\n iprot.readListEnd();\r\n }\r\n struct.setUserLogsIsSet(true);\r\n } else { \r\n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\r\n }\r\n break;\r\n default:\r\n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\r\n }\r\n iprot.readFieldEnd();\r\n }\r\n iprot.readStructEnd();\r\n\r\n // check for required fields of primitive type, which can't be checked in the validate method\r\n struct.validate();\r\n }\r\n\r\n public void write(org.apache.thrift.protocol.TProtocol oprot, rtcStats_args struct) throws org.apache.thrift.TException {\r\n struct.validate();\r\n\r\n oprot.writeStructBegin(STRUCT_DESC);\r\n if (struct.userLogs != null) {\r\n oprot.writeFieldBegin(USER_LOGS_FIELD_DESC);\r\n {\r\n oprot.writeListBegin(new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRING, struct.userLogs.size()));\r\n for (String _iter11 : struct.userLogs)\r\n {\r\n oprot.writeString(_iter11);\r\n }\r\n oprot.writeListEnd();\r\n }\r\n oprot.writeFieldEnd();\r\n }\r\n oprot.writeFieldStop();\r\n oprot.writeStructEnd();\r\n }\r\n\r\n }\r\n\r\n private static class rtcStats_argsTupleSchemeFactory implements SchemeFactory {\r\n public rtcStats_argsTupleScheme getScheme() {\r\n return new rtcStats_argsTupleScheme();\r\n }\r\n }\r\n\r\n private static class rtcStats_argsTupleScheme extends TupleScheme<rtcStats_args> {\r\n\r\n @Override\r\n public void write(org.apache.thrift.protocol.TProtocol prot, rtcStats_args struct) throws org.apache.thrift.TException {\r\n TTupleProtocol oprot = (TTupleProtocol) prot;\r\n BitSet optionals = new BitSet();\r\n if (struct.isSetUserLogs()) {\r\n optionals.set(0);\r\n }\r\n oprot.writeBitSet(optionals, 1);\r\n if (struct.isSetUserLogs()) {\r\n {\r\n oprot.writeI32(struct.userLogs.size());\r\n for (String _iter12 : struct.userLogs)\r\n {\r\n oprot.writeString(_iter12);\r\n }\r\n }\r\n }\r\n }\r\n\r\n @Override\r\n public void read(org.apache.thrift.protocol.TProtocol prot, rtcStats_args struct) throws org.apache.thrift.TException {\r\n TTupleProtocol iprot = (TTupleProtocol) prot;\r\n BitSet incoming = iprot.readBitSet(1);\r\n if (incoming.get(0)) {\r\n {\r\n org.apache.thrift.protocol.TList _list13 = new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRING, iprot.readI32());\r\n struct.userLogs = new ArrayList<String>(_list13.size);\r\n String _elem14;\r\n for (int _i15 = 0; _i15 < _list13.size; ++_i15)\r\n {\r\n _elem14 = iprot.readString();\r\n struct.userLogs.add(_elem14);\r\n }\r\n }\r\n struct.setUserLogsIsSet(true);\r\n }\r\n }\r\n }\r\n\r\n }\r\n\r\n public static class rtcStats_result implements org.apache.thrift.TBase<rtcStats_result, rtcStats_result._Fields>, java.io.Serializable, Cloneable, Comparable<rtcStats_result> {\r\n private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct(\"rtcStats_result\");\r\n\r\n private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField(\"success\", org.apache.thrift.protocol.TType.I32, (short)0);\r\n\r\n private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();\r\n static {\r\n schemes.put(StandardScheme.class, new rtcStats_resultStandardSchemeFactory());\r\n schemes.put(TupleScheme.class, new rtcStats_resultTupleSchemeFactory());\r\n }\r\n\r\n public int success; // required\r\n\r\n /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */\r\n public enum _Fields implements org.apache.thrift.TFieldIdEnum {\r\n SUCCESS((short)0, \"success\");\r\n\r\n private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();\r\n\r\n static {\r\n for (_Fields field : EnumSet.allOf(_Fields.class)) {\r\n byName.put(field.getFieldName(), field);\r\n }\r\n }\r\n\r\n /**\r\n * Find the _Fields constant that matches fieldId, or null if its not found.\r\n */\r\n public static _Fields findByThriftId(int fieldId) {\r\n switch(fieldId) {\r\n case 0: // SUCCESS\r\n return SUCCESS;\r\n default:\r\n return null;\r\n }\r\n }\r\n\r\n /**\r\n * Find the _Fields constant that matches fieldId, throwing an exception\r\n * if it is not found.\r\n */\r\n public static _Fields findByThriftIdOrThrow(int fieldId) {\r\n _Fields fields = findByThriftId(fieldId);\r\n if (fields == null) throw new IllegalArgumentException(\"Field \" + fieldId + \" doesn't exist!\");\r\n return fields;\r\n }\r\n\r\n /**\r\n * Find the _Fields constant that matches name, or null if its not found.\r\n */\r\n public static _Fields findByName(String name) {\r\n return byName.get(name);\r\n }\r\n\r\n private final short _thriftId;\r\n private final String _fieldName;\r\n\r\n _Fields(short thriftId, String fieldName) {\r\n _thriftId = thriftId;\r\n _fieldName = fieldName;\r\n }\r\n\r\n public short getThriftFieldId() {\r\n return _thriftId;\r\n }\r\n\r\n public String getFieldName() {\r\n return _fieldName;\r\n }\r\n }\r\n\r\n // isset id assignments\r\n private static final int __SUCCESS_ISSET_ID = 0;\r\n private byte __isset_bitfield = 0;\r\n public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;\r\n static {\r\n Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);\r\n tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData(\"success\", org.apache.thrift.TFieldRequirementType.DEFAULT, \r\n new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32)));\r\n metaDataMap = Collections.unmodifiableMap(tmpMap);\r\n org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(rtcStats_result.class, metaDataMap);\r\n }\r\n\r\n public rtcStats_result() {\r\n }\r\n\r\n public rtcStats_result(\r\n int success)\r\n {\r\n this();\r\n this.success = success;\r\n setSuccessIsSet(true);\r\n }\r\n\r\n /**\r\n * Performs a deep copy on <i>other</i>.\r\n */\r\n public rtcStats_result(rtcStats_result other) {\r\n __isset_bitfield = other.__isset_bitfield;\r\n this.success = other.success;\r\n }\r\n\r\n public rtcStats_result deepCopy() {\r\n return new rtcStats_result(this);\r\n }\r\n\r\n @Override\r\n public void clear() {\r\n setSuccessIsSet(false);\r\n this.success = 0;\r\n }\r\n\r\n public int getSuccess() {\r\n return this.success;\r\n }\r\n\r\n public rtcStats_result setSuccess(int success) {\r\n this.success = success;\r\n setSuccessIsSet(true);\r\n return this;\r\n }\r\n\r\n public void unsetSuccess() {\r\n __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __SUCCESS_ISSET_ID);\r\n }\r\n\r\n /** Returns true if field success is set (has been assigned a value) and false otherwise */\r\n public boolean isSetSuccess() {\r\n return EncodingUtils.testBit(__isset_bitfield, __SUCCESS_ISSET_ID);\r\n }\r\n\r\n public void setSuccessIsSet(boolean value) {\r\n __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __SUCCESS_ISSET_ID, value);\r\n }\r\n\r\n public void setFieldValue(_Fields field, Object value) {\r\n switch (field) {\r\n case SUCCESS:\r\n if (value == null) {\r\n unsetSuccess();\r\n } else {\r\n setSuccess((Integer)value);\r\n }\r\n break;\r\n\r\n }\r\n }\r\n\r\n public Object getFieldValue(_Fields field) {\r\n switch (field) {\r\n case SUCCESS:\r\n return getSuccess();\r\n\r\n }\r\n throw new IllegalStateException();\r\n }\r\n\r\n /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */\r\n public boolean isSet(_Fields field) {\r\n if (field == null) {\r\n throw new IllegalArgumentException();\r\n }\r\n\r\n switch (field) {\r\n case SUCCESS:\r\n return isSetSuccess();\r\n }\r\n throw new IllegalStateException();\r\n }\r\n\r\n @Override\r\n public boolean equals(Object that) {\r\n if (that == null)\r\n return false;\r\n if (that instanceof rtcStats_result)\r\n return this.equals((rtcStats_result)that);\r\n return false;\r\n }\r\n\r\n public boolean equals(rtcStats_result that) {\r\n if (that == null)\r\n return false;\r\n\r\n boolean this_present_success = true;\r\n boolean that_present_success = true;\r\n if (this_present_success || that_present_success) {\r\n if (!(this_present_success && that_present_success))\r\n return false;\r\n if (this.success != that.success)\r\n return false;\r\n }\r\n\r\n return true;\r\n }\r\n\r\n @Override\r\n public int hashCode() {\r\n List<Object> list = new ArrayList<Object>();\r\n\r\n boolean present_success = true;\r\n list.add(present_success);\r\n if (present_success)\r\n list.add(success);\r\n\r\n return list.hashCode();\r\n }\r\n\r\n @Override\r\n public int compareTo(rtcStats_result other) {\r\n if (!getClass().equals(other.getClass())) {\r\n return getClass().getName().compareTo(other.getClass().getName());\r\n }\r\n\r\n int lastComparison = 0;\r\n\r\n lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess());\r\n if (lastComparison != 0) {\r\n return lastComparison;\r\n }\r\n if (isSetSuccess()) {\r\n lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success);\r\n if (lastComparison != 0) {\r\n return lastComparison;\r\n }\r\n }\r\n return 0;\r\n }\r\n\r\n public _Fields fieldForId(int fieldId) {\r\n return _Fields.findByThriftId(fieldId);\r\n }\r\n\r\n public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {\r\n schemes.get(iprot.getScheme()).getScheme().read(iprot, this);\r\n }\r\n\r\n public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {\r\n schemes.get(oprot.getScheme()).getScheme().write(oprot, this);\r\n }\r\n\r\n @Override\r\n public String toString() {\r\n StringBuilder sb = new StringBuilder(\"rtcStats_result(\");\r\n boolean first = true;\r\n\r\n sb.append(\"success:\");\r\n sb.append(this.success);\r\n first = false;\r\n sb.append(\")\");\r\n return sb.toString();\r\n }\r\n\r\n public void validate() throws org.apache.thrift.TException {\r\n // check for required fields\r\n // check for sub-struct validity\r\n }\r\n\r\n private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {\r\n try {\r\n write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));\r\n } catch (org.apache.thrift.TException te) {\r\n throw new java.io.IOException(te);\r\n }\r\n }\r\n\r\n private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {\r\n try {\r\n // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor.\r\n __isset_bitfield = 0;\r\n read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));\r\n } catch (org.apache.thrift.TException te) {\r\n throw new java.io.IOException(te);\r\n }\r\n }\r\n\r\n private static class rtcStats_resultStandardSchemeFactory implements SchemeFactory {\r\n public rtcStats_resultStandardScheme getScheme() {\r\n return new rtcStats_resultStandardScheme();\r\n }\r\n }\r\n\r\n private static class rtcStats_resultStandardScheme extends StandardScheme<rtcStats_result> {\r\n\r\n public void read(org.apache.thrift.protocol.TProtocol iprot, rtcStats_result struct) throws org.apache.thrift.TException {\r\n org.apache.thrift.protocol.TField schemeField;\r\n iprot.readStructBegin();\r\n while (true)\r\n {\r\n schemeField = iprot.readFieldBegin();\r\n if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { \r\n break;\r\n }\r\n switch (schemeField.id) {\r\n case 0: // SUCCESS\r\n if (schemeField.type == org.apache.thrift.protocol.TType.I32) {\r\n struct.success = iprot.readI32();\r\n struct.setSuccessIsSet(true);\r\n } else { \r\n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\r\n }\r\n break;\r\n default:\r\n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\r\n }\r\n iprot.readFieldEnd();\r\n }\r\n iprot.readStructEnd();\r\n\r\n // check for required fields of primitive type, which can't be checked in the validate method\r\n struct.validate();\r\n }\r\n\r\n public void write(org.apache.thrift.protocol.TProtocol oprot, rtcStats_result struct) throws org.apache.thrift.TException {\r\n struct.validate();\r\n\r\n oprot.writeStructBegin(STRUCT_DESC);\r\n if (struct.isSetSuccess()) {\r\n oprot.writeFieldBegin(SUCCESS_FIELD_DESC);\r\n oprot.writeI32(struct.success);\r\n oprot.writeFieldEnd();\r\n }\r\n oprot.writeFieldStop();\r\n oprot.writeStructEnd();\r\n }\r\n\r\n }\r\n\r\n private static class rtcStats_resultTupleSchemeFactory implements SchemeFactory {\r\n public rtcStats_resultTupleScheme getScheme() {\r\n return new rtcStats_resultTupleScheme();\r\n }\r\n }\r\n\r\n private static class rtcStats_resultTupleScheme extends TupleScheme<rtcStats_result> {\r\n\r\n @Override\r\n public void write(org.apache.thrift.protocol.TProtocol prot, rtcStats_result struct) throws org.apache.thrift.TException {\r\n TTupleProtocol oprot = (TTupleProtocol) prot;\r\n BitSet optionals = new BitSet();\r\n if (struct.isSetSuccess()) {\r\n optionals.set(0);\r\n }\r\n oprot.writeBitSet(optionals, 1);\r\n if (struct.isSetSuccess()) {\r\n oprot.writeI32(struct.success);\r\n }\r\n }\r\n\r\n @Override\r\n public void read(org.apache.thrift.protocol.TProtocol prot, rtcStats_result struct) throws org.apache.thrift.TException {\r\n TTupleProtocol iprot = (TTupleProtocol) prot;\r\n BitSet incoming = iprot.readBitSet(1);\r\n if (incoming.get(0)) {\r\n struct.success = iprot.readI32();\r\n struct.setSuccessIsSet(true);\r\n }\r\n }\r\n }\r\n\r\n }\r\n\r\n public static class batchStats_args implements org.apache.thrift.TBase<batchStats_args, batchStats_args._Fields>, java.io.Serializable, Cloneable, Comparable<batchStats_args> {\r\n private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct(\"batchStats_args\");\r\n\r\n private static final org.apache.thrift.protocol.TField START_FIELD_DESC = new org.apache.thrift.protocol.TField(\"start\", org.apache.thrift.protocol.TType.I32, (short)1);\r\n private static final org.apache.thrift.protocol.TField SIZE_FIELD_DESC = new org.apache.thrift.protocol.TField(\"size\", org.apache.thrift.protocol.TType.I32, (short)2);\r\n\r\n private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();\r\n static {\r\n schemes.put(StandardScheme.class, new batchStats_argsStandardSchemeFactory());\r\n schemes.put(TupleScheme.class, new batchStats_argsTupleSchemeFactory());\r\n }\r\n\r\n public int start; // required\r\n public int size; // required\r\n\r\n /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */\r\n public enum _Fields implements org.apache.thrift.TFieldIdEnum {\r\n START((short)1, \"start\"),\r\n SIZE((short)2, \"size\");\r\n\r\n private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();\r\n\r\n static {\r\n for (_Fields field : EnumSet.allOf(_Fields.class)) {\r\n byName.put(field.getFieldName(), field);\r\n }\r\n }\r\n\r\n /**\r\n * Find the _Fields constant that matches fieldId, or null if its not found.\r\n */\r\n public static _Fields findByThriftId(int fieldId) {\r\n switch(fieldId) {\r\n case 1: // START\r\n return START;\r\n case 2: // SIZE\r\n return SIZE;\r\n default:\r\n return null;\r\n }\r\n }\r\n\r\n /**\r\n * Find the _Fields constant that matches fieldId, throwing an exception\r\n * if it is not found.\r\n */\r\n public static _Fields findByThriftIdOrThrow(int fieldId) {\r\n _Fields fields = findByThriftId(fieldId);\r\n if (fields == null) throw new IllegalArgumentException(\"Field \" + fieldId + \" doesn't exist!\");\r\n return fields;\r\n }\r\n\r\n /**\r\n * Find the _Fields constant that matches name, or null if its not found.\r\n */\r\n public static _Fields findByName(String name) {\r\n return byName.get(name);\r\n }\r\n\r\n private final short _thriftId;\r\n private final String _fieldName;\r\n\r\n _Fields(short thriftId, String fieldName) {\r\n _thriftId = thriftId;\r\n _fieldName = fieldName;\r\n }\r\n\r\n public short getThriftFieldId() {\r\n return _thriftId;\r\n }\r\n\r\n public String getFieldName() {\r\n return _fieldName;\r\n }\r\n }\r\n\r\n // isset id assignments\r\n private static final int __START_ISSET_ID = 0;\r\n private static final int __SIZE_ISSET_ID = 1;\r\n private byte __isset_bitfield = 0;\r\n public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;\r\n static {\r\n Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);\r\n tmpMap.put(_Fields.START, new org.apache.thrift.meta_data.FieldMetaData(\"start\", org.apache.thrift.TFieldRequirementType.DEFAULT, \r\n new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32)));\r\n tmpMap.put(_Fields.SIZE, new org.apache.thrift.meta_data.FieldMetaData(\"size\", org.apache.thrift.TFieldRequirementType.DEFAULT, \r\n new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32)));\r\n metaDataMap = Collections.unmodifiableMap(tmpMap);\r\n org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(batchStats_args.class, metaDataMap);\r\n }\r\n\r\n public batchStats_args() {\r\n }\r\n\r\n public batchStats_args(\r\n int start,\r\n int size)\r\n {\r\n this();\r\n this.start = start;\r\n setStartIsSet(true);\r\n this.size = size;\r\n setSizeIsSet(true);\r\n }\r\n\r\n /**\r\n * Performs a deep copy on <i>other</i>.\r\n */\r\n public batchStats_args(batchStats_args other) {\r\n __isset_bitfield = other.__isset_bitfield;\r\n this.start = other.start;\r\n this.size = other.size;\r\n }\r\n\r\n public batchStats_args deepCopy() {\r\n return new batchStats_args(this);\r\n }\r\n\r\n @Override\r\n public void clear() {\r\n setStartIsSet(false);\r\n this.start = 0;\r\n setSizeIsSet(false);\r\n this.size = 0;\r\n }\r\n\r\n public int getStart() {\r\n return this.start;\r\n }\r\n\r\n public batchStats_args setStart(int start) {\r\n this.start = start;\r\n setStartIsSet(true);\r\n return this;\r\n }\r\n\r\n public void unsetStart() {\r\n __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __START_ISSET_ID);\r\n }\r\n\r\n /** Returns true if field start is set (has been assigned a value) and false otherwise */\r\n public boolean isSetStart() {\r\n return EncodingUtils.testBit(__isset_bitfield, __START_ISSET_ID);\r\n }\r\n\r\n public void setStartIsSet(boolean value) {\r\n __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __START_ISSET_ID, value);\r\n }\r\n\r\n public int getSize() {\r\n return this.size;\r\n }\r\n\r\n public batchStats_args setSize(int size) {\r\n this.size = size;\r\n setSizeIsSet(true);\r\n return this;\r\n }\r\n\r\n public void unsetSize() {\r\n __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __SIZE_ISSET_ID);\r\n }\r\n\r\n /** Returns true if field size is set (has been assigned a value) and false otherwise */\r\n public boolean isSetSize() {\r\n return EncodingUtils.testBit(__isset_bitfield, __SIZE_ISSET_ID);\r\n }\r\n\r\n public void setSizeIsSet(boolean value) {\r\n __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __SIZE_ISSET_ID, value);\r\n }\r\n\r\n public void setFieldValue(_Fields field, Object value) {\r\n switch (field) {\r\n case START:\r\n if (value == null) {\r\n unsetStart();\r\n } else {\r\n setStart((Integer)value);\r\n }\r\n break;\r\n\r\n case SIZE:\r\n if (value == null) {\r\n unsetSize();\r\n } else {\r\n setSize((Integer)value);\r\n }\r\n break;\r\n\r\n }\r\n }\r\n\r\n public Object getFieldValue(_Fields field) {\r\n switch (field) {\r\n case START:\r\n return getStart();\r\n\r\n case SIZE:\r\n return getSize();\r\n\r\n }\r\n throw new IllegalStateException();\r\n }\r\n\r\n /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */\r\n public boolean isSet(_Fields field) {\r\n if (field == null) {\r\n throw new IllegalArgumentException();\r\n }\r\n\r\n switch (field) {\r\n case START:\r\n return isSetStart();\r\n case SIZE:\r\n return isSetSize();\r\n }\r\n throw new IllegalStateException();\r\n }\r\n\r\n @Override\r\n public boolean equals(Object that) {\r\n if (that == null)\r\n return false;\r\n if (that instanceof batchStats_args)\r\n return this.equals((batchStats_args)that);\r\n return false;\r\n }\r\n\r\n public boolean equals(batchStats_args that) {\r\n if (that == null)\r\n return false;\r\n\r\n boolean this_present_start = true;\r\n boolean that_present_start = true;\r\n if (this_present_start || that_present_start) {\r\n if (!(this_present_start && that_present_start))\r\n return false;\r\n if (this.start != that.start)\r\n return false;\r\n }\r\n\r\n boolean this_present_size = true;\r\n boolean that_present_size = true;\r\n if (this_present_size || that_present_size) {\r\n if (!(this_present_size && that_present_size))\r\n return false;\r\n if (this.size != that.size)\r\n return false;\r\n }\r\n\r\n return true;\r\n }\r\n\r\n @Override\r\n public int hashCode() {\r\n List<Object> list = new ArrayList<Object>();\r\n\r\n boolean present_start = true;\r\n list.add(present_start);\r\n if (present_start)\r\n list.add(start);\r\n\r\n boolean present_size = true;\r\n list.add(present_size);\r\n if (present_size)\r\n list.add(size);\r\n\r\n return list.hashCode();\r\n }\r\n\r\n @Override\r\n public int compareTo(batchStats_args other) {\r\n if (!getClass().equals(other.getClass())) {\r\n return getClass().getName().compareTo(other.getClass().getName());\r\n }\r\n\r\n int lastComparison = 0;\r\n\r\n lastComparison = Boolean.valueOf(isSetStart()).compareTo(other.isSetStart());\r\n if (lastComparison != 0) {\r\n return lastComparison;\r\n }\r\n if (isSetStart()) {\r\n lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.start, other.start);\r\n if (lastComparison != 0) {\r\n return lastComparison;\r\n }\r\n }\r\n lastComparison = Boolean.valueOf(isSetSize()).compareTo(other.isSetSize());\r\n if (lastComparison != 0) {\r\n return lastComparison;\r\n }\r\n if (isSetSize()) {\r\n lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.size, other.size);\r\n if (lastComparison != 0) {\r\n return lastComparison;\r\n }\r\n }\r\n return 0;\r\n }\r\n\r\n public _Fields fieldForId(int fieldId) {\r\n return _Fields.findByThriftId(fieldId);\r\n }\r\n\r\n public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {\r\n schemes.get(iprot.getScheme()).getScheme().read(iprot, this);\r\n }\r\n\r\n public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {\r\n schemes.get(oprot.getScheme()).getScheme().write(oprot, this);\r\n }\r\n\r\n @Override\r\n public String toString() {\r\n StringBuilder sb = new StringBuilder(\"batchStats_args(\");\r\n boolean first = true;\r\n\r\n sb.append(\"start:\");\r\n sb.append(this.start);\r\n first = false;\r\n if (!first) sb.append(\", \");\r\n sb.append(\"size:\");\r\n sb.append(this.size);\r\n first = false;\r\n sb.append(\")\");\r\n return sb.toString();\r\n }\r\n\r\n public void validate() throws org.apache.thrift.TException {\r\n // check for required fields\r\n // check for sub-struct validity\r\n }\r\n\r\n private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {\r\n try {\r\n write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));\r\n } catch (org.apache.thrift.TException te) {\r\n throw new java.io.IOException(te);\r\n }\r\n }\r\n\r\n private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {\r\n try {\r\n // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor.\r\n __isset_bitfield = 0;\r\n read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));\r\n } catch (org.apache.thrift.TException te) {\r\n throw new java.io.IOException(te);\r\n }\r\n }\r\n\r\n private static class batchStats_argsStandardSchemeFactory implements SchemeFactory {\r\n public batchStats_argsStandardScheme getScheme() {\r\n return new batchStats_argsStandardScheme();\r\n }\r\n }\r\n\r\n private static class batchStats_argsStandardScheme extends StandardScheme<batchStats_args> {\r\n\r\n public void read(org.apache.thrift.protocol.TProtocol iprot, batchStats_args struct) throws org.apache.thrift.TException {\r\n org.apache.thrift.protocol.TField schemeField;\r\n iprot.readStructBegin();\r\n while (true)\r\n {\r\n schemeField = iprot.readFieldBegin();\r\n if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { \r\n break;\r\n }\r\n switch (schemeField.id) {\r\n case 1: // START\r\n if (schemeField.type == org.apache.thrift.protocol.TType.I32) {\r\n struct.start = iprot.readI32();\r\n struct.setStartIsSet(true);\r\n } else { \r\n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\r\n }\r\n break;\r\n case 2: // SIZE\r\n if (schemeField.type == org.apache.thrift.protocol.TType.I32) {\r\n struct.size = iprot.readI32();\r\n struct.setSizeIsSet(true);\r\n } else { \r\n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\r\n }\r\n break;\r\n default:\r\n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\r\n }\r\n iprot.readFieldEnd();\r\n }\r\n iprot.readStructEnd();\r\n\r\n // check for required fields of primitive type, which can't be checked in the validate method\r\n struct.validate();\r\n }\r\n\r\n public void write(org.apache.thrift.protocol.TProtocol oprot, batchStats_args struct) throws org.apache.thrift.TException {\r\n struct.validate();\r\n\r\n oprot.writeStructBegin(STRUCT_DESC);\r\n oprot.writeFieldBegin(START_FIELD_DESC);\r\n oprot.writeI32(struct.start);\r\n oprot.writeFieldEnd();\r\n oprot.writeFieldBegin(SIZE_FIELD_DESC);\r\n oprot.writeI32(struct.size);\r\n oprot.writeFieldEnd();\r\n oprot.writeFieldStop();\r\n oprot.writeStructEnd();\r\n }\r\n\r\n }\r\n\r\n private static class batchStats_argsTupleSchemeFactory implements SchemeFactory {\r\n public batchStats_argsTupleScheme getScheme() {\r\n return new batchStats_argsTupleScheme();\r\n }\r\n }\r\n\r\n private static class batchStats_argsTupleScheme extends TupleScheme<batchStats_args> {\r\n\r\n @Override\r\n public void write(org.apache.thrift.protocol.TProtocol prot, batchStats_args struct) throws org.apache.thrift.TException {\r\n TTupleProtocol oprot = (TTupleProtocol) prot;\r\n BitSet optionals = new BitSet();\r\n if (struct.isSetStart()) {\r\n optionals.set(0);\r\n }\r\n if (struct.isSetSize()) {\r\n optionals.set(1);\r\n }\r\n oprot.writeBitSet(optionals, 2);\r\n if (struct.isSetStart()) {\r\n oprot.writeI32(struct.start);\r\n }\r\n if (struct.isSetSize()) {\r\n oprot.writeI32(struct.size);\r\n }\r\n }\r\n\r\n @Override\r\n public void read(org.apache.thrift.protocol.TProtocol prot, batchStats_args struct) throws org.apache.thrift.TException {\r\n TTupleProtocol iprot = (TTupleProtocol) prot;\r\n BitSet incoming = iprot.readBitSet(2);\r\n if (incoming.get(0)) {\r\n struct.start = iprot.readI32();\r\n struct.setStartIsSet(true);\r\n }\r\n if (incoming.get(1)) {\r\n struct.size = iprot.readI32();\r\n struct.setSizeIsSet(true);\r\n }\r\n }\r\n }\r\n\r\n }\r\n\r\n public static class batchStats_result implements org.apache.thrift.TBase<batchStats_result, batchStats_result._Fields>, java.io.Serializable, Cloneable, Comparable<batchStats_result> {\r\n private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct(\"batchStats_result\");\r\n\r\n private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField(\"success\", org.apache.thrift.protocol.TType.I32, (short)0);\r\n\r\n private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();\r\n static {\r\n schemes.put(StandardScheme.class, new batchStats_resultStandardSchemeFactory());\r\n schemes.put(TupleScheme.class, new batchStats_resultTupleSchemeFactory());\r\n }\r\n\r\n public int success; // required\r\n\r\n /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */\r\n public enum _Fields implements org.apache.thrift.TFieldIdEnum {\r\n SUCCESS((short)0, \"success\");\r\n\r\n private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();\r\n\r\n static {\r\n for (_Fields field : EnumSet.allOf(_Fields.class)) {\r\n byName.put(field.getFieldName(), field);\r\n }\r\n }\r\n\r\n /**\r\n * Find the _Fields constant that matches fieldId, or null if its not found.\r\n */\r\n public static _Fields findByThriftId(int fieldId) {\r\n switch(fieldId) {\r\n case 0: // SUCCESS\r\n return SUCCESS;\r\n default:\r\n return null;\r\n }\r\n }\r\n\r\n /**\r\n * Find the _Fields constant that matches fieldId, throwing an exception\r\n * if it is not found.\r\n */\r\n public static _Fields findByThriftIdOrThrow(int fieldId) {\r\n _Fields fields = findByThriftId(fieldId);\r\n if (fields == null) throw new IllegalArgumentException(\"Field \" + fieldId + \" doesn't exist!\");\r\n return fields;\r\n }\r\n\r\n /**\r\n * Find the _Fields constant that matches name, or null if its not found.\r\n */\r\n public static _Fields findByName(String name) {\r\n return byName.get(name);\r\n }\r\n\r\n private final short _thriftId;\r\n private final String _fieldName;\r\n\r\n _Fields(short thriftId, String fieldName) {\r\n _thriftId = thriftId;\r\n _fieldName = fieldName;\r\n }\r\n\r\n public short getThriftFieldId() {\r\n return _thriftId;\r\n }\r\n\r\n public String getFieldName() {\r\n return _fieldName;\r\n }\r\n }\r\n\r\n // isset id assignments\r\n private static final int __SUCCESS_ISSET_ID = 0;\r\n private byte __isset_bitfield = 0;\r\n public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;\r\n static {\r\n Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);\r\n tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData(\"success\", org.apache.thrift.TFieldRequirementType.DEFAULT, \r\n new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32)));\r\n metaDataMap = Collections.unmodifiableMap(tmpMap);\r\n org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(batchStats_result.class, metaDataMap);\r\n }\r\n\r\n public batchStats_result() {\r\n }\r\n\r\n public batchStats_result(\r\n int success)\r\n {\r\n this();\r\n this.success = success;\r\n setSuccessIsSet(true);\r\n }\r\n\r\n /**\r\n * Performs a deep copy on <i>other</i>.\r\n */\r\n public batchStats_result(batchStats_result other) {\r\n __isset_bitfield = other.__isset_bitfield;\r\n this.success = other.success;\r\n }\r\n\r\n public batchStats_result deepCopy() {\r\n return new batchStats_result(this);\r\n }\r\n\r\n @Override\r\n public void clear() {\r\n setSuccessIsSet(false);\r\n this.success = 0;\r\n }\r\n\r\n public int getSuccess() {\r\n return this.success;\r\n }\r\n\r\n public batchStats_result setSuccess(int success) {\r\n this.success = success;\r\n setSuccessIsSet(true);\r\n return this;\r\n }\r\n\r\n public void unsetSuccess() {\r\n __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __SUCCESS_ISSET_ID);\r\n }\r\n\r\n /** Returns true if field success is set (has been assigned a value) and false otherwise */\r\n public boolean isSetSuccess() {\r\n return EncodingUtils.testBit(__isset_bitfield, __SUCCESS_ISSET_ID);\r\n }\r\n\r\n public void setSuccessIsSet(boolean value) {\r\n __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __SUCCESS_ISSET_ID, value);\r\n }\r\n\r\n public void setFieldValue(_Fields field, Object value) {\r\n switch (field) {\r\n case SUCCESS:\r\n if (value == null) {\r\n unsetSuccess();\r\n } else {\r\n setSuccess((Integer)value);\r\n }\r\n break;\r\n\r\n }\r\n }\r\n\r\n public Object getFieldValue(_Fields field) {\r\n switch (field) {\r\n case SUCCESS:\r\n return getSuccess();\r\n\r\n }\r\n throw new IllegalStateException();\r\n }\r\n\r\n /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */\r\n public boolean isSet(_Fields field) {\r\n if (field == null) {\r\n throw new IllegalArgumentException();\r\n }\r\n\r\n switch (field) {\r\n case SUCCESS:\r\n return isSetSuccess();\r\n }\r\n throw new IllegalStateException();\r\n }\r\n\r\n @Override\r\n public boolean equals(Object that) {\r\n if (that == null)\r\n return false;\r\n if (that instanceof batchStats_result)\r\n return this.equals((batchStats_result)that);\r\n return false;\r\n }\r\n\r\n public boolean equals(batchStats_result that) {\r\n if (that == null)\r\n return false;\r\n\r\n boolean this_present_success = true;\r\n boolean that_present_success = true;\r\n if (this_present_success || that_present_success) {\r\n if (!(this_present_success && that_present_success))\r\n return false;\r\n if (this.success != that.success)\r\n return false;\r\n }\r\n\r\n return true;\r\n }\r\n\r\n @Override\r\n public int hashCode() {\r\n List<Object> list = new ArrayList<Object>();\r\n\r\n boolean present_success = true;\r\n list.add(present_success);\r\n if (present_success)\r\n list.add(success);\r\n\r\n return list.hashCode();\r\n }\r\n\r\n @Override\r\n public int compareTo(batchStats_result other) {\r\n if (!getClass().equals(other.getClass())) {\r\n return getClass().getName().compareTo(other.getClass().getName());\r\n }\r\n\r\n int lastComparison = 0;\r\n\r\n lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess());\r\n if (lastComparison != 0) {\r\n return lastComparison;\r\n }\r\n if (isSetSuccess()) {\r\n lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success);\r\n if (lastComparison != 0) {\r\n return lastComparison;\r\n }\r\n }\r\n return 0;\r\n }\r\n\r\n public _Fields fieldForId(int fieldId) {\r\n return _Fields.findByThriftId(fieldId);\r\n }\r\n\r\n public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {\r\n schemes.get(iprot.getScheme()).getScheme().read(iprot, this);\r\n }\r\n\r\n public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {\r\n schemes.get(oprot.getScheme()).getScheme().write(oprot, this);\r\n }\r\n\r\n @Override\r\n public String toString() {\r\n StringBuilder sb = new StringBuilder(\"batchStats_result(\");\r\n boolean first = true;\r\n\r\n sb.append(\"success:\");\r\n sb.append(this.success);\r\n first = false;\r\n sb.append(\")\");\r\n return sb.toString();\r\n }\r\n\r\n public void validate() throws org.apache.thrift.TException {\r\n // check for required fields\r\n // check for sub-struct validity\r\n }\r\n\r\n private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {\r\n try {\r\n write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));\r\n } catch (org.apache.thrift.TException te) {\r\n throw new java.io.IOException(te);\r\n }\r\n }\r\n\r\n private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {\r\n try {\r\n // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor.\r\n __isset_bitfield = 0;\r\n read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));\r\n } catch (org.apache.thrift.TException te) {\r\n throw new java.io.IOException(te);\r\n }\r\n }\r\n\r\n private static class batchStats_resultStandardSchemeFactory implements SchemeFactory {\r\n public batchStats_resultStandardScheme getScheme() {\r\n return new batchStats_resultStandardScheme();\r\n }\r\n }\r\n\r\n private static class batchStats_resultStandardScheme extends StandardScheme<batchStats_result> {\r\n\r\n public void read(org.apache.thrift.protocol.TProtocol iprot, batchStats_result struct) throws org.apache.thrift.TException {\r\n org.apache.thrift.protocol.TField schemeField;\r\n iprot.readStructBegin();\r\n while (true)\r\n {\r\n schemeField = iprot.readFieldBegin();\r\n if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { \r\n break;\r\n }\r\n switch (schemeField.id) {\r\n case 0: // SUCCESS\r\n if (schemeField.type == org.apache.thrift.protocol.TType.I32) {\r\n struct.success = iprot.readI32();\r\n struct.setSuccessIsSet(true);\r\n } else { \r\n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\r\n }\r\n break;\r\n default:\r\n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\r\n }\r\n iprot.readFieldEnd();\r\n }\r\n iprot.readStructEnd();\r\n\r\n // check for required fields of primitive type, which can't be checked in the validate method\r\n struct.validate();\r\n }\r\n\r\n public void write(org.apache.thrift.protocol.TProtocol oprot, batchStats_result struct) throws org.apache.thrift.TException {\r\n struct.validate();\r\n\r\n oprot.writeStructBegin(STRUCT_DESC);\r\n if (struct.isSetSuccess()) {\r\n oprot.writeFieldBegin(SUCCESS_FIELD_DESC);\r\n oprot.writeI32(struct.success);\r\n oprot.writeFieldEnd();\r\n }\r\n oprot.writeFieldStop();\r\n oprot.writeStructEnd();\r\n }\r\n\r\n }\r\n\r\n private static class batchStats_resultTupleSchemeFactory implements SchemeFactory {\r\n public batchStats_resultTupleScheme getScheme() {\r\n return new batchStats_resultTupleScheme();\r\n }\r\n }\r\n\r\n private static class batchStats_resultTupleScheme extends TupleScheme<batchStats_result> {\r\n\r\n @Override\r\n public void write(org.apache.thrift.protocol.TProtocol prot, batchStats_result struct) throws org.apache.thrift.TException {\r\n TTupleProtocol oprot = (TTupleProtocol) prot;\r\n BitSet optionals = new BitSet();\r\n if (struct.isSetSuccess()) {\r\n optionals.set(0);\r\n }\r\n oprot.writeBitSet(optionals, 1);\r\n if (struct.isSetSuccess()) {\r\n oprot.writeI32(struct.success);\r\n }\r\n }\r\n\r\n @Override\r\n public void read(org.apache.thrift.protocol.TProtocol prot, batchStats_result struct) throws org.apache.thrift.TException {\r\n TTupleProtocol iprot = (TTupleProtocol) prot;\r\n BitSet incoming = iprot.readBitSet(1);\r\n if (incoming.get(0)) {\r\n struct.success = iprot.readI32();\r\n struct.setSuccessIsSet(true);\r\n }\r\n }\r\n }\r\n\r\n }\r\n\r\n public static class getAdminNodeId_args implements org.apache.thrift.TBase<getAdminNodeId_args, getAdminNodeId_args._Fields>, java.io.Serializable, Cloneable, Comparable<getAdminNodeId_args> {\r\n private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct(\"getAdminNodeId_args\");\r\n\r\n\r\n private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();\r\n static {\r\n schemes.put(StandardScheme.class, new getAdminNodeId_argsStandardSchemeFactory());\r\n schemes.put(TupleScheme.class, new getAdminNodeId_argsTupleSchemeFactory());\r\n }\r\n\r\n\r\n /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */\r\n public enum _Fields implements org.apache.thrift.TFieldIdEnum {\r\n;\r\n\r\n private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();\r\n\r\n static {\r\n for (_Fields field : EnumSet.allOf(_Fields.class)) {\r\n byName.put(field.getFieldName(), field);\r\n }\r\n }\r\n\r\n /**\r\n * Find the _Fields constant that matches fieldId, or null if its not found.\r\n */\r\n public static _Fields findByThriftId(int fieldId) {\r\n switch(fieldId) {\r\n default:\r\n return null;\r\n }\r\n }\r\n\r\n /**\r\n * Find the _Fields constant that matches fieldId, throwing an exception\r\n * if it is not found.\r\n */\r\n public static _Fields findByThriftIdOrThrow(int fieldId) {\r\n _Fields fields = findByThriftId(fieldId);\r\n if (fields == null) throw new IllegalArgumentException(\"Field \" + fieldId + \" doesn't exist!\");\r\n return fields;\r\n }\r\n\r\n /**\r\n * Find the _Fields constant that matches name, or null if its not found.\r\n */\r\n public static _Fields findByName(String name) {\r\n return byName.get(name);\r\n }\r\n\r\n private final short _thriftId;\r\n private final String _fieldName;\r\n\r\n _Fields(short thriftId, String fieldName) {\r\n _thriftId = thriftId;\r\n _fieldName = fieldName;\r\n }\r\n\r\n public short getThriftFieldId() {\r\n return _thriftId;\r\n }\r\n\r\n public String getFieldName() {\r\n return _fieldName;\r\n }\r\n }\r\n public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;\r\n static {\r\n Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);\r\n metaDataMap = Collections.unmodifiableMap(tmpMap);\r\n org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(getAdminNodeId_args.class, metaDataMap);\r\n }\r\n\r\n public getAdminNodeId_args() {\r\n }\r\n\r\n /**\r\n * Performs a deep copy on <i>other</i>.\r\n */\r\n public getAdminNodeId_args(getAdminNodeId_args other) {\r\n }\r\n\r\n public getAdminNodeId_args deepCopy() {\r\n return new getAdminNodeId_args(this);\r\n }\r\n\r\n @Override\r\n public void clear() {\r\n }\r\n\r\n public void setFieldValue(_Fields field, Object value) {\r\n switch (field) {\r\n }\r\n }\r\n\r\n public Object getFieldValue(_Fields field) {\r\n switch (field) {\r\n }\r\n throw new IllegalStateException();\r\n }\r\n\r\n /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */\r\n public boolean isSet(_Fields field) {\r\n if (field == null) {\r\n throw new IllegalArgumentException();\r\n }\r\n\r\n switch (field) {\r\n }\r\n throw new IllegalStateException();\r\n }\r\n\r\n @Override\r\n public boolean equals(Object that) {\r\n if (that == null)\r\n return false;\r\n if (that instanceof getAdminNodeId_args)\r\n return this.equals((getAdminNodeId_args)that);\r\n return false;\r\n }\r\n\r\n public boolean equals(getAdminNodeId_args that) {\r\n if (that == null)\r\n return false;\r\n\r\n return true;\r\n }\r\n\r\n @Override\r\n public int hashCode() {\r\n List<Object> list = new ArrayList<Object>();\r\n\r\n return list.hashCode();\r\n }\r\n\r\n @Override\r\n public int compareTo(getAdminNodeId_args other) {\r\n if (!getClass().equals(other.getClass())) {\r\n return getClass().getName().compareTo(other.getClass().getName());\r\n }\r\n\r\n int lastComparison = 0;\r\n\r\n return 0;\r\n }\r\n\r\n public _Fields fieldForId(int fieldId) {\r\n return _Fields.findByThriftId(fieldId);\r\n }\r\n\r\n public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {\r\n schemes.get(iprot.getScheme()).getScheme().read(iprot, this);\r\n }\r\n\r\n public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {\r\n schemes.get(oprot.getScheme()).getScheme().write(oprot, this);\r\n }\r\n\r\n @Override\r\n public String toString() {\r\n StringBuilder sb = new StringBuilder(\"getAdminNodeId_args(\");\r\n boolean first = true;\r\n\r\n sb.append(\")\");\r\n return sb.toString();\r\n }\r\n\r\n public void validate() throws org.apache.thrift.TException {\r\n // check for required fields\r\n // check for sub-struct validity\r\n }\r\n\r\n private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {\r\n try {\r\n write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));\r\n } catch (org.apache.thrift.TException te) {\r\n throw new java.io.IOException(te);\r\n }\r\n }\r\n\r\n private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {\r\n try {\r\n read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));\r\n } catch (org.apache.thrift.TException te) {\r\n throw new java.io.IOException(te);\r\n }\r\n }\r\n\r\n private static class getAdminNodeId_argsStandardSchemeFactory implements SchemeFactory {\r\n public getAdminNodeId_argsStandardScheme getScheme() {\r\n return new getAdminNodeId_argsStandardScheme();\r\n }\r\n }\r\n\r\n private static class getAdminNodeId_argsStandardScheme extends StandardScheme<getAdminNodeId_args> {\r\n\r\n public void read(org.apache.thrift.protocol.TProtocol iprot, getAdminNodeId_args struct) throws org.apache.thrift.TException {\r\n org.apache.thrift.protocol.TField schemeField;\r\n iprot.readStructBegin();\r\n while (true)\r\n {\r\n schemeField = iprot.readFieldBegin();\r\n if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { \r\n break;\r\n }\r\n switch (schemeField.id) {\r\n default:\r\n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\r\n }\r\n iprot.readFieldEnd();\r\n }\r\n iprot.readStructEnd();\r\n\r\n // check for required fields of primitive type, which can't be checked in the validate method\r\n struct.validate();\r\n }\r\n\r\n public void write(org.apache.thrift.protocol.TProtocol oprot, getAdminNodeId_args struct) throws org.apache.thrift.TException {\r\n struct.validate();\r\n\r\n oprot.writeStructBegin(STRUCT_DESC);\r\n oprot.writeFieldStop();\r\n oprot.writeStructEnd();\r\n }\r\n\r\n }\r\n\r\n private static class getAdminNodeId_argsTupleSchemeFactory implements SchemeFactory {\r\n public getAdminNodeId_argsTupleScheme getScheme() {\r\n return new getAdminNodeId_argsTupleScheme();\r\n }\r\n }\r\n\r\n private static class getAdminNodeId_argsTupleScheme extends TupleScheme<getAdminNodeId_args> {\r\n\r\n @Override\r\n public void write(org.apache.thrift.protocol.TProtocol prot, getAdminNodeId_args struct) throws org.apache.thrift.TException {\r\n TTupleProtocol oprot = (TTupleProtocol) prot;\r\n }\r\n\r\n @Override\r\n public void read(org.apache.thrift.protocol.TProtocol prot, getAdminNodeId_args struct) throws org.apache.thrift.TException {\r\n TTupleProtocol iprot = (TTupleProtocol) prot;\r\n }\r\n }\r\n\r\n }\r\n\r\n public static class getAdminNodeId_result implements org.apache.thrift.TBase<getAdminNodeId_result, getAdminNodeId_result._Fields>, java.io.Serializable, Cloneable, Comparable<getAdminNodeId_result> {\r\n private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct(\"getAdminNodeId_result\");\r\n\r\n private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField(\"success\", org.apache.thrift.protocol.TType.I32, (short)0);\r\n\r\n private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();\r\n static {\r\n schemes.put(StandardScheme.class, new getAdminNodeId_resultStandardSchemeFactory());\r\n schemes.put(TupleScheme.class, new getAdminNodeId_resultTupleSchemeFactory());\r\n }\r\n\r\n public int success; // required\r\n\r\n /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */\r\n public enum _Fields implements org.apache.thrift.TFieldIdEnum {\r\n SUCCESS((short)0, \"success\");\r\n\r\n private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();\r\n\r\n static {\r\n for (_Fields field : EnumSet.allOf(_Fields.class)) {\r\n byName.put(field.getFieldName(), field);\r\n }\r\n }\r\n\r\n /**\r\n * Find the _Fields constant that matches fieldId, or null if its not found.\r\n */\r\n public static _Fields findByThriftId(int fieldId) {\r\n switch(fieldId) {\r\n case 0: // SUCCESS\r\n return SUCCESS;\r\n default:\r\n return null;\r\n }\r\n }\r\n\r\n /**\r\n * Find the _Fields constant that matches fieldId, throwing an exception\r\n * if it is not found.\r\n */\r\n public static _Fields findByThriftIdOrThrow(int fieldId) {\r\n _Fields fields = findByThriftId(fieldId);\r\n if (fields == null) throw new IllegalArgumentException(\"Field \" + fieldId + \" doesn't exist!\");\r\n return fields;\r\n }\r\n\r\n /**\r\n * Find the _Fields constant that matches name, or null if its not found.\r\n */\r\n public static _Fields findByName(String name) {\r\n return byName.get(name);\r\n }\r\n\r\n private final short _thriftId;\r\n private final String _fieldName;\r\n\r\n _Fields(short thriftId, String fieldName) {\r\n _thriftId = thriftId;\r\n _fieldName = fieldName;\r\n }\r\n\r\n public short getThriftFieldId() {\r\n return _thriftId;\r\n }\r\n\r\n public String getFieldName() {\r\n return _fieldName;\r\n }\r\n }\r\n\r\n // isset id assignments\r\n private static final int __SUCCESS_ISSET_ID = 0;\r\n private byte __isset_bitfield = 0;\r\n public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;\r\n static {\r\n Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);\r\n tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData(\"success\", org.apache.thrift.TFieldRequirementType.DEFAULT, \r\n new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32)));\r\n metaDataMap = Collections.unmodifiableMap(tmpMap);\r\n org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(getAdminNodeId_result.class, metaDataMap);\r\n }\r\n\r\n public getAdminNodeId_result() {\r\n }\r\n\r\n public getAdminNodeId_result(\r\n int success)\r\n {\r\n this();\r\n this.success = success;\r\n setSuccessIsSet(true);\r\n }\r\n\r\n /**\r\n * Performs a deep copy on <i>other</i>.\r\n */\r\n public getAdminNodeId_result(getAdminNodeId_result other) {\r\n __isset_bitfield = other.__isset_bitfield;\r\n this.success = other.success;\r\n }\r\n\r\n public getAdminNodeId_result deepCopy() {\r\n return new getAdminNodeId_result(this);\r\n }\r\n\r\n @Override\r\n public void clear() {\r\n setSuccessIsSet(false);\r\n this.success = 0;\r\n }\r\n\r\n public int getSuccess() {\r\n return this.success;\r\n }\r\n\r\n public getAdminNodeId_result setSuccess(int success) {\r\n this.success = success;\r\n setSuccessIsSet(true);\r\n return this;\r\n }\r\n\r\n public void unsetSuccess() {\r\n __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __SUCCESS_ISSET_ID);\r\n }\r\n\r\n /** Returns true if field success is set (has been assigned a value) and false otherwise */\r\n public boolean isSetSuccess() {\r\n return EncodingUtils.testBit(__isset_bitfield, __SUCCESS_ISSET_ID);\r\n }\r\n\r\n public void setSuccessIsSet(boolean value) {\r\n __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __SUCCESS_ISSET_ID, value);\r\n }\r\n\r\n public void setFieldValue(_Fields field, Object value) {\r\n switch (field) {\r\n case SUCCESS:\r\n if (value == null) {\r\n unsetSuccess();\r\n } else {\r\n setSuccess((Integer)value);\r\n }\r\n break;\r\n\r\n }\r\n }\r\n\r\n public Object getFieldValue(_Fields field) {\r\n switch (field) {\r\n case SUCCESS:\r\n return getSuccess();\r\n\r\n }\r\n throw new IllegalStateException();\r\n }\r\n\r\n /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */\r\n public boolean isSet(_Fields field) {\r\n if (field == null) {\r\n throw new IllegalArgumentException();\r\n }\r\n\r\n switch (field) {\r\n case SUCCESS:\r\n return isSetSuccess();\r\n }\r\n throw new IllegalStateException();\r\n }\r\n\r\n @Override\r\n public boolean equals(Object that) {\r\n if (that == null)\r\n return false;\r\n if (that instanceof getAdminNodeId_result)\r\n return this.equals((getAdminNodeId_result)that);\r\n return false;\r\n }\r\n\r\n public boolean equals(getAdminNodeId_result that) {\r\n if (that == null)\r\n return false;\r\n\r\n boolean this_present_success = true;\r\n boolean that_present_success = true;\r\n if (this_present_success || that_present_success) {\r\n if (!(this_present_success && that_present_success))\r\n return false;\r\n if (this.success != that.success)\r\n return false;\r\n }\r\n\r\n return true;\r\n }\r\n\r\n @Override\r\n public int hashCode() {\r\n List<Object> list = new ArrayList<Object>();\r\n\r\n boolean present_success = true;\r\n list.add(present_success);\r\n if (present_success)\r\n list.add(success);\r\n\r\n return list.hashCode();\r\n }\r\n\r\n @Override\r\n public int compareTo(getAdminNodeId_result other) {\r\n if (!getClass().equals(other.getClass())) {\r\n return getClass().getName().compareTo(other.getClass().getName());\r\n }\r\n\r\n int lastComparison = 0;\r\n\r\n lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess());\r\n if (lastComparison != 0) {\r\n return lastComparison;\r\n }\r\n if (isSetSuccess()) {\r\n lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success);\r\n if (lastComparison != 0) {\r\n return lastComparison;\r\n }\r\n }\r\n return 0;\r\n }\r\n\r\n public _Fields fieldForId(int fieldId) {\r\n return _Fields.findByThriftId(fieldId);\r\n }\r\n\r\n public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {\r\n schemes.get(iprot.getScheme()).getScheme().read(iprot, this);\r\n }\r\n\r\n public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {\r\n schemes.get(oprot.getScheme()).getScheme().write(oprot, this);\r\n }\r\n\r\n @Override\r\n public String toString() {\r\n StringBuilder sb = new StringBuilder(\"getAdminNodeId_result(\");\r\n boolean first = true;\r\n\r\n sb.append(\"success:\");\r\n sb.append(this.success);\r\n first = false;\r\n sb.append(\")\");\r\n return sb.toString();\r\n }\r\n\r\n public void validate() throws org.apache.thrift.TException {\r\n // check for required fields\r\n // check for sub-struct validity\r\n }\r\n\r\n private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {\r\n try {\r\n write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));\r\n } catch (org.apache.thrift.TException te) {\r\n throw new java.io.IOException(te);\r\n }\r\n }\r\n\r\n private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {\r\n try {\r\n // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor.\r\n __isset_bitfield = 0;\r\n read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));\r\n } catch (org.apache.thrift.TException te) {\r\n throw new java.io.IOException(te);\r\n }\r\n }\r\n\r\n private static class getAdminNodeId_resultStandardSchemeFactory implements SchemeFactory {\r\n public getAdminNodeId_resultStandardScheme getScheme() {\r\n return new getAdminNodeId_resultStandardScheme();\r\n }\r\n }\r\n\r\n private static class getAdminNodeId_resultStandardScheme extends StandardScheme<getAdminNodeId_result> {\r\n\r\n public void read(org.apache.thrift.protocol.TProtocol iprot, getAdminNodeId_result struct) throws org.apache.thrift.TException {\r\n org.apache.thrift.protocol.TField schemeField;\r\n iprot.readStructBegin();\r\n while (true)\r\n {\r\n schemeField = iprot.readFieldBegin();\r\n if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { \r\n break;\r\n }\r\n switch (schemeField.id) {\r\n case 0: // SUCCESS\r\n if (schemeField.type == org.apache.thrift.protocol.TType.I32) {\r\n struct.success = iprot.readI32();\r\n struct.setSuccessIsSet(true);\r\n } else { \r\n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\r\n }\r\n break;\r\n default:\r\n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\r\n }\r\n iprot.readFieldEnd();\r\n }\r\n iprot.readStructEnd();\r\n\r\n // check for required fields of primitive type, which can't be checked in the validate method\r\n struct.validate();\r\n }\r\n\r\n public void write(org.apache.thrift.protocol.TProtocol oprot, getAdminNodeId_result struct) throws org.apache.thrift.TException {\r\n struct.validate();\r\n\r\n oprot.writeStructBegin(STRUCT_DESC);\r\n if (struct.isSetSuccess()) {\r\n oprot.writeFieldBegin(SUCCESS_FIELD_DESC);\r\n oprot.writeI32(struct.success);\r\n oprot.writeFieldEnd();\r\n }\r\n oprot.writeFieldStop();\r\n oprot.writeStructEnd();\r\n }\r\n\r\n }\r\n\r\n private static class getAdminNodeId_resultTupleSchemeFactory implements SchemeFactory {\r\n public getAdminNodeId_resultTupleScheme getScheme() {\r\n return new getAdminNodeId_resultTupleScheme();\r\n }\r\n }\r\n\r\n private static class getAdminNodeId_resultTupleScheme extends TupleScheme<getAdminNodeId_result> {\r\n\r\n @Override\r\n public void write(org.apache.thrift.protocol.TProtocol prot, getAdminNodeId_result struct) throws org.apache.thrift.TException {\r\n TTupleProtocol oprot = (TTupleProtocol) prot;\r\n BitSet optionals = new BitSet();\r\n if (struct.isSetSuccess()) {\r\n optionals.set(0);\r\n }\r\n oprot.writeBitSet(optionals, 1);\r\n if (struct.isSetSuccess()) {\r\n oprot.writeI32(struct.success);\r\n }\r\n }\r\n\r\n @Override\r\n public void read(org.apache.thrift.protocol.TProtocol prot, getAdminNodeId_result struct) throws org.apache.thrift.TException {\r\n TTupleProtocol iprot = (TTupleProtocol) prot;\r\n BitSet incoming = iprot.readBitSet(1);\r\n if (incoming.get(0)) {\r\n struct.success = iprot.readI32();\r\n struct.setSuccessIsSet(true);\r\n }\r\n }\r\n }\r\n\r\n }\r\n\r\n public static class getHealthStatus_args implements org.apache.thrift.TBase<getHealthStatus_args, getHealthStatus_args._Fields>, java.io.Serializable, Cloneable, Comparable<getHealthStatus_args> {\r\n private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct(\"getHealthStatus_args\");\r\n\r\n\r\n private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();\r\n static {\r\n schemes.put(StandardScheme.class, new getHealthStatus_argsStandardSchemeFactory());\r\n schemes.put(TupleScheme.class, new getHealthStatus_argsTupleSchemeFactory());\r\n }\r\n\r\n\r\n /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */\r\n public enum _Fields implements org.apache.thrift.TFieldIdEnum {\r\n;\r\n\r\n private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();\r\n\r\n static {\r\n for (_Fields field : EnumSet.allOf(_Fields.class)) {\r\n byName.put(field.getFieldName(), field);\r\n }\r\n }\r\n\r\n /**\r\n * Find the _Fields constant that matches fieldId, or null if its not found.\r\n */\r\n public static _Fields findByThriftId(int fieldId) {\r\n switch(fieldId) {\r\n default:\r\n return null;\r\n }\r\n }\r\n\r\n /**\r\n * Find the _Fields constant that matches fieldId, throwing an exception\r\n * if it is not found.\r\n */\r\n public static _Fields findByThriftIdOrThrow(int fieldId) {\r\n _Fields fields = findByThriftId(fieldId);\r\n if (fields == null) throw new IllegalArgumentException(\"Field \" + fieldId + \" doesn't exist!\");\r\n return fields;\r\n }\r\n\r\n /**\r\n * Find the _Fields constant that matches name, or null if its not found.\r\n */\r\n public static _Fields findByName(String name) {\r\n return byName.get(name);\r\n }\r\n\r\n private final short _thriftId;\r\n private final String _fieldName;\r\n\r\n _Fields(short thriftId, String fieldName) {\r\n _thriftId = thriftId;\r\n _fieldName = fieldName;\r\n }\r\n\r\n public short getThriftFieldId() {\r\n return _thriftId;\r\n }\r\n\r\n public String getFieldName() {\r\n return _fieldName;\r\n }\r\n }\r\n public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;\r\n static {\r\n Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);\r\n metaDataMap = Collections.unmodifiableMap(tmpMap);\r\n org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(getHealthStatus_args.class, metaDataMap);\r\n }\r\n\r\n public getHealthStatus_args() {\r\n }\r\n\r\n /**\r\n * Performs a deep copy on <i>other</i>.\r\n */\r\n public getHealthStatus_args(getHealthStatus_args other) {\r\n }\r\n\r\n public getHealthStatus_args deepCopy() {\r\n return new getHealthStatus_args(this);\r\n }\r\n\r\n @Override\r\n public void clear() {\r\n }\r\n\r\n public void setFieldValue(_Fields field, Object value) {\r\n switch (field) {\r\n }\r\n }\r\n\r\n public Object getFieldValue(_Fields field) {\r\n switch (field) {\r\n }\r\n throw new IllegalStateException();\r\n }\r\n\r\n /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */\r\n public boolean isSet(_Fields field) {\r\n if (field == null) {\r\n throw new IllegalArgumentException();\r\n }\r\n\r\n switch (field) {\r\n }\r\n throw new IllegalStateException();\r\n }\r\n\r\n @Override\r\n public boolean equals(Object that) {\r\n if (that == null)\r\n return false;\r\n if (that instanceof getHealthStatus_args)\r\n return this.equals((getHealthStatus_args)that);\r\n return false;\r\n }\r\n\r\n public boolean equals(getHealthStatus_args that) {\r\n if (that == null)\r\n return false;\r\n\r\n return true;\r\n }\r\n\r\n @Override\r\n public int hashCode() {\r\n List<Object> list = new ArrayList<Object>();\r\n\r\n return list.hashCode();\r\n }\r\n\r\n @Override\r\n public int compareTo(getHealthStatus_args other) {\r\n if (!getClass().equals(other.getClass())) {\r\n return getClass().getName().compareTo(other.getClass().getName());\r\n }\r\n\r\n int lastComparison = 0;\r\n\r\n return 0;\r\n }\r\n\r\n public _Fields fieldForId(int fieldId) {\r\n return _Fields.findByThriftId(fieldId);\r\n }\r\n\r\n public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {\r\n schemes.get(iprot.getScheme()).getScheme().read(iprot, this);\r\n }\r\n\r\n public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {\r\n schemes.get(oprot.getScheme()).getScheme().write(oprot, this);\r\n }\r\n\r\n @Override\r\n public String toString() {\r\n StringBuilder sb = new StringBuilder(\"getHealthStatus_args(\");\r\n boolean first = true;\r\n\r\n sb.append(\")\");\r\n return sb.toString();\r\n }\r\n\r\n public void validate() throws org.apache.thrift.TException {\r\n // check for required fields\r\n // check for sub-struct validity\r\n }\r\n\r\n private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {\r\n try {\r\n write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));\r\n } catch (org.apache.thrift.TException te) {\r\n throw new java.io.IOException(te);\r\n }\r\n }\r\n\r\n private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {\r\n try {\r\n read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));\r\n } catch (org.apache.thrift.TException te) {\r\n throw new java.io.IOException(te);\r\n }\r\n }\r\n\r\n private static class getHealthStatus_argsStandardSchemeFactory implements SchemeFactory {\r\n public getHealthStatus_argsStandardScheme getScheme() {\r\n return new getHealthStatus_argsStandardScheme();\r\n }\r\n }\r\n\r\n private static class getHealthStatus_argsStandardScheme extends StandardScheme<getHealthStatus_args> {\r\n\r\n public void read(org.apache.thrift.protocol.TProtocol iprot, getHealthStatus_args struct) throws org.apache.thrift.TException {\r\n org.apache.thrift.protocol.TField schemeField;\r\n iprot.readStructBegin();\r\n while (true)\r\n {\r\n schemeField = iprot.readFieldBegin();\r\n if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { \r\n break;\r\n }\r\n switch (schemeField.id) {\r\n default:\r\n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\r\n }\r\n iprot.readFieldEnd();\r\n }\r\n iprot.readStructEnd();\r\n\r\n // check for required fields of primitive type, which can't be checked in the validate method\r\n struct.validate();\r\n }\r\n\r\n public void write(org.apache.thrift.protocol.TProtocol oprot, getHealthStatus_args struct) throws org.apache.thrift.TException {\r\n struct.validate();\r\n\r\n oprot.writeStructBegin(STRUCT_DESC);\r\n oprot.writeFieldStop();\r\n oprot.writeStructEnd();\r\n }\r\n\r\n }\r\n\r\n private static class getHealthStatus_argsTupleSchemeFactory implements SchemeFactory {\r\n public getHealthStatus_argsTupleScheme getScheme() {\r\n return new getHealthStatus_argsTupleScheme();\r\n }\r\n }\r\n\r\n private static class getHealthStatus_argsTupleScheme extends TupleScheme<getHealthStatus_args> {\r\n\r\n @Override\r\n public void write(org.apache.thrift.protocol.TProtocol prot, getHealthStatus_args struct) throws org.apache.thrift.TException {\r\n TTupleProtocol oprot = (TTupleProtocol) prot;\r\n }\r\n\r\n @Override\r\n public void read(org.apache.thrift.protocol.TProtocol prot, getHealthStatus_args struct) throws org.apache.thrift.TException {\r\n TTupleProtocol iprot = (TTupleProtocol) prot;\r\n }\r\n }\r\n\r\n }\r\n\r\n public static class getHealthStatus_result implements org.apache.thrift.TBase<getHealthStatus_result, getHealthStatus_result._Fields>, java.io.Serializable, Cloneable, Comparable<getHealthStatus_result> {\r\n private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct(\"getHealthStatus_result\");\r\n\r\n private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField(\"success\", org.apache.thrift.protocol.TType.I32, (short)0);\r\n\r\n private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();\r\n static {\r\n schemes.put(StandardScheme.class, new getHealthStatus_resultStandardSchemeFactory());\r\n schemes.put(TupleScheme.class, new getHealthStatus_resultTupleSchemeFactory());\r\n }\r\n\r\n public int success; // required\r\n\r\n /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */\r\n public enum _Fields implements org.apache.thrift.TFieldIdEnum {\r\n SUCCESS((short)0, \"success\");\r\n\r\n private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();\r\n\r\n static {\r\n for (_Fields field : EnumSet.allOf(_Fields.class)) {\r\n byName.put(field.getFieldName(), field);\r\n }\r\n }\r\n\r\n /**\r\n * Find the _Fields constant that matches fieldId, or null if its not found.\r\n */\r\n public static _Fields findByThriftId(int fieldId) {\r\n switch(fieldId) {\r\n case 0: // SUCCESS\r\n return SUCCESS;\r\n default:\r\n return null;\r\n }\r\n }\r\n\r\n /**\r\n * Find the _Fields constant that matches fieldId, throwing an exception\r\n * if it is not found.\r\n */\r\n public static _Fields findByThriftIdOrThrow(int fieldId) {\r\n _Fields fields = findByThriftId(fieldId);\r\n if (fields == null) throw new IllegalArgumentException(\"Field \" + fieldId + \" doesn't exist!\");\r\n return fields;\r\n }\r\n\r\n /**\r\n * Find the _Fields constant that matches name, or null if its not found.\r\n */\r\n public static _Fields findByName(String name) {\r\n return byName.get(name);\r\n }\r\n\r\n private final short _thriftId;\r\n private final String _fieldName;\r\n\r\n _Fields(short thriftId, String fieldName) {\r\n _thriftId = thriftId;\r\n _fieldName = fieldName;\r\n }\r\n\r\n public short getThriftFieldId() {\r\n return _thriftId;\r\n }\r\n\r\n public String getFieldName() {\r\n return _fieldName;\r\n }\r\n }\r\n\r\n // isset id assignments\r\n private static final int __SUCCESS_ISSET_ID = 0;\r\n private byte __isset_bitfield = 0;\r\n public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;\r\n static {\r\n Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);\r\n tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData(\"success\", org.apache.thrift.TFieldRequirementType.DEFAULT, \r\n new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32)));\r\n metaDataMap = Collections.unmodifiableMap(tmpMap);\r\n org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(getHealthStatus_result.class, metaDataMap);\r\n }\r\n\r\n public getHealthStatus_result() {\r\n }\r\n\r\n public getHealthStatus_result(\r\n int success)\r\n {\r\n this();\r\n this.success = success;\r\n setSuccessIsSet(true);\r\n }\r\n\r\n /**\r\n * Performs a deep copy on <i>other</i>.\r\n */\r\n public getHealthStatus_result(getHealthStatus_result other) {\r\n __isset_bitfield = other.__isset_bitfield;\r\n this.success = other.success;\r\n }\r\n\r\n public getHealthStatus_result deepCopy() {\r\n return new getHealthStatus_result(this);\r\n }\r\n\r\n @Override\r\n public void clear() {\r\n setSuccessIsSet(false);\r\n this.success = 0;\r\n }\r\n\r\n public int getSuccess() {\r\n return this.success;\r\n }\r\n\r\n public getHealthStatus_result setSuccess(int success) {\r\n this.success = success;\r\n setSuccessIsSet(true);\r\n return this;\r\n }\r\n\r\n public void unsetSuccess() {\r\n __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __SUCCESS_ISSET_ID);\r\n }\r\n\r\n /** Returns true if field success is set (has been assigned a value) and false otherwise */\r\n public boolean isSetSuccess() {\r\n return EncodingUtils.testBit(__isset_bitfield, __SUCCESS_ISSET_ID);\r\n }\r\n\r\n public void setSuccessIsSet(boolean value) {\r\n __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __SUCCESS_ISSET_ID, value);\r\n }\r\n\r\n public void setFieldValue(_Fields field, Object value) {\r\n switch (field) {\r\n case SUCCESS:\r\n if (value == null) {\r\n unsetSuccess();\r\n } else {\r\n setSuccess((Integer)value);\r\n }\r\n break;\r\n\r\n }\r\n }\r\n\r\n public Object getFieldValue(_Fields field) {\r\n switch (field) {\r\n case SUCCESS:\r\n return getSuccess();\r\n\r\n }\r\n throw new IllegalStateException();\r\n }\r\n\r\n /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */\r\n public boolean isSet(_Fields field) {\r\n if (field == null) {\r\n throw new IllegalArgumentException();\r\n }\r\n\r\n switch (field) {\r\n case SUCCESS:\r\n return isSetSuccess();\r\n }\r\n throw new IllegalStateException();\r\n }\r\n\r\n @Override\r\n public boolean equals(Object that) {\r\n if (that == null)\r\n return false;\r\n if (that instanceof getHealthStatus_result)\r\n return this.equals((getHealthStatus_result)that);\r\n return false;\r\n }\r\n\r\n public boolean equals(getHealthStatus_result that) {\r\n if (that == null)\r\n return false;\r\n\r\n boolean this_present_success = true;\r\n boolean that_present_success = true;\r\n if (this_present_success || that_present_success) {\r\n if (!(this_present_success && that_present_success))\r\n return false;\r\n if (this.success != that.success)\r\n return false;\r\n }\r\n\r\n return true;\r\n }\r\n\r\n @Override\r\n public int hashCode() {\r\n List<Object> list = new ArrayList<Object>();\r\n\r\n boolean present_success = true;\r\n list.add(present_success);\r\n if (present_success)\r\n list.add(success);\r\n\r\n return list.hashCode();\r\n }\r\n\r\n @Override\r\n public int compareTo(getHealthStatus_result other) {\r\n if (!getClass().equals(other.getClass())) {\r\n return getClass().getName().compareTo(other.getClass().getName());\r\n }\r\n\r\n int lastComparison = 0;\r\n\r\n lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess());\r\n if (lastComparison != 0) {\r\n return lastComparison;\r\n }\r\n if (isSetSuccess()) {\r\n lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success);\r\n if (lastComparison != 0) {\r\n return lastComparison;\r\n }\r\n }\r\n return 0;\r\n }\r\n\r\n public _Fields fieldForId(int fieldId) {\r\n return _Fields.findByThriftId(fieldId);\r\n }\r\n\r\n public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {\r\n schemes.get(iprot.getScheme()).getScheme().read(iprot, this);\r\n }\r\n\r\n public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {\r\n schemes.get(oprot.getScheme()).getScheme().write(oprot, this);\r\n }\r\n\r\n @Override\r\n public String toString() {\r\n StringBuilder sb = new StringBuilder(\"getHealthStatus_result(\");\r\n boolean first = true;\r\n\r\n sb.append(\"success:\");\r\n sb.append(this.success);\r\n first = false;\r\n sb.append(\")\");\r\n return sb.toString();\r\n }\r\n\r\n public void validate() throws org.apache.thrift.TException {\r\n // check for required fields\r\n // check for sub-struct validity\r\n }\r\n\r\n private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {\r\n try {\r\n write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));\r\n } catch (org.apache.thrift.TException te) {\r\n throw new java.io.IOException(te);\r\n }\r\n }\r\n\r\n private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {\r\n try {\r\n // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor.\r\n __isset_bitfield = 0;\r\n read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));\r\n } catch (org.apache.thrift.TException te) {\r\n throw new java.io.IOException(te);\r\n }\r\n }\r\n\r\n private static class getHealthStatus_resultStandardSchemeFactory implements SchemeFactory {\r\n public getHealthStatus_resultStandardScheme getScheme() {\r\n return new getHealthStatus_resultStandardScheme();\r\n }\r\n }\r\n\r\n private static class getHealthStatus_resultStandardScheme extends StandardScheme<getHealthStatus_result> {\r\n\r\n public void read(org.apache.thrift.protocol.TProtocol iprot, getHealthStatus_result struct) throws org.apache.thrift.TException {\r\n org.apache.thrift.protocol.TField schemeField;\r\n iprot.readStructBegin();\r\n while (true)\r\n {\r\n schemeField = iprot.readFieldBegin();\r\n if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { \r\n break;\r\n }\r\n switch (schemeField.id) {\r\n case 0: // SUCCESS\r\n if (schemeField.type == org.apache.thrift.protocol.TType.I32) {\r\n struct.success = iprot.readI32();\r\n struct.setSuccessIsSet(true);\r\n } else { \r\n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\r\n }\r\n break;\r\n default:\r\n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\r\n }\r\n iprot.readFieldEnd();\r\n }\r\n iprot.readStructEnd();\r\n\r\n // check for required fields of primitive type, which can't be checked in the validate method\r\n struct.validate();\r\n }\r\n\r\n public void write(org.apache.thrift.protocol.TProtocol oprot, getHealthStatus_result struct) throws org.apache.thrift.TException {\r\n struct.validate();\r\n\r\n oprot.writeStructBegin(STRUCT_DESC);\r\n if (struct.isSetSuccess()) {\r\n oprot.writeFieldBegin(SUCCESS_FIELD_DESC);\r\n oprot.writeI32(struct.success);\r\n oprot.writeFieldEnd();\r\n }\r\n oprot.writeFieldStop();\r\n oprot.writeStructEnd();\r\n }\r\n\r\n }\r\n\r\n private static class getHealthStatus_resultTupleSchemeFactory implements SchemeFactory {\r\n public getHealthStatus_resultTupleScheme getScheme() {\r\n return new getHealthStatus_resultTupleScheme();\r\n }\r\n }\r\n\r\n private static class getHealthStatus_resultTupleScheme extends TupleScheme<getHealthStatus_result> {\r\n\r\n @Override\r\n public void write(org.apache.thrift.protocol.TProtocol prot, getHealthStatus_result struct) throws org.apache.thrift.TException {\r\n TTupleProtocol oprot = (TTupleProtocol) prot;\r\n BitSet optionals = new BitSet();\r\n if (struct.isSetSuccess()) {\r\n optionals.set(0);\r\n }\r\n oprot.writeBitSet(optionals, 1);\r\n if (struct.isSetSuccess()) {\r\n oprot.writeI32(struct.success);\r\n }\r\n }\r\n\r\n @Override\r\n public void read(org.apache.thrift.protocol.TProtocol prot, getHealthStatus_result struct) throws org.apache.thrift.TException {\r\n TTupleProtocol iprot = (TTupleProtocol) prot;\r\n BitSet incoming = iprot.readBitSet(1);\r\n if (incoming.get(0)) {\r\n struct.success = iprot.readI32();\r\n struct.setSuccessIsSet(true);\r\n }\r\n }\r\n }\r\n\r\n }\r\n\r\n public static class getJobStatus_args implements org.apache.thrift.TBase<getJobStatus_args, getJobStatus_args._Fields>, java.io.Serializable, Cloneable, Comparable<getJobStatus_args> {\r\n private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct(\"getJobStatus_args\");\r\n\r\n\r\n private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();\r\n static {\r\n schemes.put(StandardScheme.class, new getJobStatus_argsStandardSchemeFactory());\r\n schemes.put(TupleScheme.class, new getJobStatus_argsTupleSchemeFactory());\r\n }\r\n\r\n\r\n /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */\r\n public enum _Fields implements org.apache.thrift.TFieldIdEnum {\r\n;\r\n\r\n private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();\r\n\r\n static {\r\n for (_Fields field : EnumSet.allOf(_Fields.class)) {\r\n byName.put(field.getFieldName(), field);\r\n }\r\n }\r\n\r\n /**\r\n * Find the _Fields constant that matches fieldId, or null if its not found.\r\n */\r\n public static _Fields findByThriftId(int fieldId) {\r\n switch(fieldId) {\r\n default:\r\n return null;\r\n }\r\n }\r\n\r\n /**\r\n * Find the _Fields constant that matches fieldId, throwing an exception\r\n * if it is not found.\r\n */\r\n public static _Fields findByThriftIdOrThrow(int fieldId) {\r\n _Fields fields = findByThriftId(fieldId);\r\n if (fields == null) throw new IllegalArgumentException(\"Field \" + fieldId + \" doesn't exist!\");\r\n return fields;\r\n }\r\n\r\n /**\r\n * Find the _Fields constant that matches name, or null if its not found.\r\n */\r\n public static _Fields findByName(String name) {\r\n return byName.get(name);\r\n }\r\n\r\n private final short _thriftId;\r\n private final String _fieldName;\r\n\r\n _Fields(short thriftId, String fieldName) {\r\n _thriftId = thriftId;\r\n _fieldName = fieldName;\r\n }\r\n\r\n public short getThriftFieldId() {\r\n return _thriftId;\r\n }\r\n\r\n public String getFieldName() {\r\n return _fieldName;\r\n }\r\n }\r\n public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;\r\n static {\r\n Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);\r\n metaDataMap = Collections.unmodifiableMap(tmpMap);\r\n org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(getJobStatus_args.class, metaDataMap);\r\n }\r\n\r\n public getJobStatus_args() {\r\n }\r\n\r\n /**\r\n * Performs a deep copy on <i>other</i>.\r\n */\r\n public getJobStatus_args(getJobStatus_args other) {\r\n }\r\n\r\n public getJobStatus_args deepCopy() {\r\n return new getJobStatus_args(this);\r\n }\r\n\r\n @Override\r\n public void clear() {\r\n }\r\n\r\n public void setFieldValue(_Fields field, Object value) {\r\n switch (field) {\r\n }\r\n }\r\n\r\n public Object getFieldValue(_Fields field) {\r\n switch (field) {\r\n }\r\n throw new IllegalStateException();\r\n }\r\n\r\n /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */\r\n public boolean isSet(_Fields field) {\r\n if (field == null) {\r\n throw new IllegalArgumentException();\r\n }\r\n\r\n switch (field) {\r\n }\r\n throw new IllegalStateException();\r\n }\r\n\r\n @Override\r\n public boolean equals(Object that) {\r\n if (that == null)\r\n return false;\r\n if (that instanceof getJobStatus_args)\r\n return this.equals((getJobStatus_args)that);\r\n return false;\r\n }\r\n\r\n public boolean equals(getJobStatus_args that) {\r\n if (that == null)\r\n return false;\r\n\r\n return true;\r\n }\r\n\r\n @Override\r\n public int hashCode() {\r\n List<Object> list = new ArrayList<Object>();\r\n\r\n return list.hashCode();\r\n }\r\n\r\n @Override\r\n public int compareTo(getJobStatus_args other) {\r\n if (!getClass().equals(other.getClass())) {\r\n return getClass().getName().compareTo(other.getClass().getName());\r\n }\r\n\r\n int lastComparison = 0;\r\n\r\n return 0;\r\n }\r\n\r\n public _Fields fieldForId(int fieldId) {\r\n return _Fields.findByThriftId(fieldId);\r\n }\r\n\r\n public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {\r\n schemes.get(iprot.getScheme()).getScheme().read(iprot, this);\r\n }\r\n\r\n public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {\r\n schemes.get(oprot.getScheme()).getScheme().write(oprot, this);\r\n }\r\n\r\n @Override\r\n public String toString() {\r\n StringBuilder sb = new StringBuilder(\"getJobStatus_args(\");\r\n boolean first = true;\r\n\r\n sb.append(\")\");\r\n return sb.toString();\r\n }\r\n\r\n public void validate() throws org.apache.thrift.TException {\r\n // check for required fields\r\n // check for sub-struct validity\r\n }\r\n\r\n private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {\r\n try {\r\n write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));\r\n } catch (org.apache.thrift.TException te) {\r\n throw new java.io.IOException(te);\r\n }\r\n }\r\n\r\n private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {\r\n try {\r\n read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));\r\n } catch (org.apache.thrift.TException te) {\r\n throw new java.io.IOException(te);\r\n }\r\n }\r\n\r\n private static class getJobStatus_argsStandardSchemeFactory implements SchemeFactory {\r\n public getJobStatus_argsStandardScheme getScheme() {\r\n return new getJobStatus_argsStandardScheme();\r\n }\r\n }\r\n\r\n private static class getJobStatus_argsStandardScheme extends StandardScheme<getJobStatus_args> {\r\n\r\n public void read(org.apache.thrift.protocol.TProtocol iprot, getJobStatus_args struct) throws org.apache.thrift.TException {\r\n org.apache.thrift.protocol.TField schemeField;\r\n iprot.readStructBegin();\r\n while (true)\r\n {\r\n schemeField = iprot.readFieldBegin();\r\n if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { \r\n break;\r\n }\r\n switch (schemeField.id) {\r\n default:\r\n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\r\n }\r\n iprot.readFieldEnd();\r\n }\r\n iprot.readStructEnd();\r\n\r\n // check for required fields of primitive type, which can't be checked in the validate method\r\n struct.validate();\r\n }\r\n\r\n public void write(org.apache.thrift.protocol.TProtocol oprot, getJobStatus_args struct) throws org.apache.thrift.TException {\r\n struct.validate();\r\n\r\n oprot.writeStructBegin(STRUCT_DESC);\r\n oprot.writeFieldStop();\r\n oprot.writeStructEnd();\r\n }\r\n\r\n }\r\n\r\n private static class getJobStatus_argsTupleSchemeFactory implements SchemeFactory {\r\n public getJobStatus_argsTupleScheme getScheme() {\r\n return new getJobStatus_argsTupleScheme();\r\n }\r\n }\r\n\r\n private static class getJobStatus_argsTupleScheme extends TupleScheme<getJobStatus_args> {\r\n\r\n @Override\r\n public void write(org.apache.thrift.protocol.TProtocol prot, getJobStatus_args struct) throws org.apache.thrift.TException {\r\n TTupleProtocol oprot = (TTupleProtocol) prot;\r\n }\r\n\r\n @Override\r\n public void read(org.apache.thrift.protocol.TProtocol prot, getJobStatus_args struct) throws org.apache.thrift.TException {\r\n TTupleProtocol iprot = (TTupleProtocol) prot;\r\n }\r\n }\r\n\r\n }\r\n\r\n public static class getJobStatus_result implements org.apache.thrift.TBase<getJobStatus_result, getJobStatus_result._Fields>, java.io.Serializable, Cloneable, Comparable<getJobStatus_result> {\r\n private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct(\"getJobStatus_result\");\r\n\r\n private static final org.apache.thrift.protocol.TField SUCCESS_FIELD_DESC = new org.apache.thrift.protocol.TField(\"success\", org.apache.thrift.protocol.TType.I32, (short)0);\r\n\r\n private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();\r\n static {\r\n schemes.put(StandardScheme.class, new getJobStatus_resultStandardSchemeFactory());\r\n schemes.put(TupleScheme.class, new getJobStatus_resultTupleSchemeFactory());\r\n }\r\n\r\n public int success; // required\r\n\r\n /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */\r\n public enum _Fields implements org.apache.thrift.TFieldIdEnum {\r\n SUCCESS((short)0, \"success\");\r\n\r\n private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();\r\n\r\n static {\r\n for (_Fields field : EnumSet.allOf(_Fields.class)) {\r\n byName.put(field.getFieldName(), field);\r\n }\r\n }\r\n\r\n /**\r\n * Find the _Fields constant that matches fieldId, or null if its not found.\r\n */\r\n public static _Fields findByThriftId(int fieldId) {\r\n switch(fieldId) {\r\n case 0: // SUCCESS\r\n return SUCCESS;\r\n default:\r\n return null;\r\n }\r\n }\r\n\r\n /**\r\n * Find the _Fields constant that matches fieldId, throwing an exception\r\n * if it is not found.\r\n */\r\n public static _Fields findByThriftIdOrThrow(int fieldId) {\r\n _Fields fields = findByThriftId(fieldId);\r\n if (fields == null) throw new IllegalArgumentException(\"Field \" + fieldId + \" doesn't exist!\");\r\n return fields;\r\n }\r\n\r\n /**\r\n * Find the _Fields constant that matches name, or null if its not found.\r\n */\r\n public static _Fields findByName(String name) {\r\n return byName.get(name);\r\n }\r\n\r\n private final short _thriftId;\r\n private final String _fieldName;\r\n\r\n _Fields(short thriftId, String fieldName) {\r\n _thriftId = thriftId;\r\n _fieldName = fieldName;\r\n }\r\n\r\n public short getThriftFieldId() {\r\n return _thriftId;\r\n }\r\n\r\n public String getFieldName() {\r\n return _fieldName;\r\n }\r\n }\r\n\r\n // isset id assignments\r\n private static final int __SUCCESS_ISSET_ID = 0;\r\n private byte __isset_bitfield = 0;\r\n public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;\r\n static {\r\n Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);\r\n tmpMap.put(_Fields.SUCCESS, new org.apache.thrift.meta_data.FieldMetaData(\"success\", org.apache.thrift.TFieldRequirementType.DEFAULT, \r\n new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.I32)));\r\n metaDataMap = Collections.unmodifiableMap(tmpMap);\r\n org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(getJobStatus_result.class, metaDataMap);\r\n }\r\n\r\n public getJobStatus_result() {\r\n }\r\n\r\n public getJobStatus_result(\r\n int success)\r\n {\r\n this();\r\n this.success = success;\r\n setSuccessIsSet(true);\r\n }\r\n\r\n /**\r\n * Performs a deep copy on <i>other</i>.\r\n */\r\n public getJobStatus_result(getJobStatus_result other) {\r\n __isset_bitfield = other.__isset_bitfield;\r\n this.success = other.success;\r\n }\r\n\r\n public getJobStatus_result deepCopy() {\r\n return new getJobStatus_result(this);\r\n }\r\n\r\n @Override\r\n public void clear() {\r\n setSuccessIsSet(false);\r\n this.success = 0;\r\n }\r\n\r\n public int getSuccess() {\r\n return this.success;\r\n }\r\n\r\n public getJobStatus_result setSuccess(int success) {\r\n this.success = success;\r\n setSuccessIsSet(true);\r\n return this;\r\n }\r\n\r\n public void unsetSuccess() {\r\n __isset_bitfield = EncodingUtils.clearBit(__isset_bitfield, __SUCCESS_ISSET_ID);\r\n }\r\n\r\n /** Returns true if field success is set (has been assigned a value) and false otherwise */\r\n public boolean isSetSuccess() {\r\n return EncodingUtils.testBit(__isset_bitfield, __SUCCESS_ISSET_ID);\r\n }\r\n\r\n public void setSuccessIsSet(boolean value) {\r\n __isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __SUCCESS_ISSET_ID, value);\r\n }\r\n\r\n public void setFieldValue(_Fields field, Object value) {\r\n switch (field) {\r\n case SUCCESS:\r\n if (value == null) {\r\n unsetSuccess();\r\n } else {\r\n setSuccess((Integer)value);\r\n }\r\n break;\r\n\r\n }\r\n }\r\n\r\n public Object getFieldValue(_Fields field) {\r\n switch (field) {\r\n case SUCCESS:\r\n return getSuccess();\r\n\r\n }\r\n throw new IllegalStateException();\r\n }\r\n\r\n /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */\r\n public boolean isSet(_Fields field) {\r\n if (field == null) {\r\n throw new IllegalArgumentException();\r\n }\r\n\r\n switch (field) {\r\n case SUCCESS:\r\n return isSetSuccess();\r\n }\r\n throw new IllegalStateException();\r\n }\r\n\r\n @Override\r\n public boolean equals(Object that) {\r\n if (that == null)\r\n return false;\r\n if (that instanceof getJobStatus_result)\r\n return this.equals((getJobStatus_result)that);\r\n return false;\r\n }\r\n\r\n public boolean equals(getJobStatus_result that) {\r\n if (that == null)\r\n return false;\r\n\r\n boolean this_present_success = true;\r\n boolean that_present_success = true;\r\n if (this_present_success || that_present_success) {\r\n if (!(this_present_success && that_present_success))\r\n return false;\r\n if (this.success != that.success)\r\n return false;\r\n }\r\n\r\n return true;\r\n }\r\n\r\n @Override\r\n public int hashCode() {\r\n List<Object> list = new ArrayList<Object>();\r\n\r\n boolean present_success = true;\r\n list.add(present_success);\r\n if (present_success)\r\n list.add(success);\r\n\r\n return list.hashCode();\r\n }\r\n\r\n @Override\r\n public int compareTo(getJobStatus_result other) {\r\n if (!getClass().equals(other.getClass())) {\r\n return getClass().getName().compareTo(other.getClass().getName());\r\n }\r\n\r\n int lastComparison = 0;\r\n\r\n lastComparison = Boolean.valueOf(isSetSuccess()).compareTo(other.isSetSuccess());\r\n if (lastComparison != 0) {\r\n return lastComparison;\r\n }\r\n if (isSetSuccess()) {\r\n lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.success, other.success);\r\n if (lastComparison != 0) {\r\n return lastComparison;\r\n }\r\n }\r\n return 0;\r\n }\r\n\r\n public _Fields fieldForId(int fieldId) {\r\n return _Fields.findByThriftId(fieldId);\r\n }\r\n\r\n public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {\r\n schemes.get(iprot.getScheme()).getScheme().read(iprot, this);\r\n }\r\n\r\n public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {\r\n schemes.get(oprot.getScheme()).getScheme().write(oprot, this);\r\n }\r\n\r\n @Override\r\n public String toString() {\r\n StringBuilder sb = new StringBuilder(\"getJobStatus_result(\");\r\n boolean first = true;\r\n\r\n sb.append(\"success:\");\r\n sb.append(this.success);\r\n first = false;\r\n sb.append(\")\");\r\n return sb.toString();\r\n }\r\n\r\n public void validate() throws org.apache.thrift.TException {\r\n // check for required fields\r\n // check for sub-struct validity\r\n }\r\n\r\n private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {\r\n try {\r\n write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));\r\n } catch (org.apache.thrift.TException te) {\r\n throw new java.io.IOException(te);\r\n }\r\n }\r\n\r\n private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {\r\n try {\r\n // it doesn't seem like you should have to do this, but java serialization is wacky, and doesn't call the default constructor.\r\n __isset_bitfield = 0;\r\n read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));\r\n } catch (org.apache.thrift.TException te) {\r\n throw new java.io.IOException(te);\r\n }\r\n }\r\n\r\n private static class getJobStatus_resultStandardSchemeFactory implements SchemeFactory {\r\n public getJobStatus_resultStandardScheme getScheme() {\r\n return new getJobStatus_resultStandardScheme();\r\n }\r\n }\r\n\r\n private static class getJobStatus_resultStandardScheme extends StandardScheme<getJobStatus_result> {\r\n\r\n public void read(org.apache.thrift.protocol.TProtocol iprot, getJobStatus_result struct) throws org.apache.thrift.TException {\r\n org.apache.thrift.protocol.TField schemeField;\r\n iprot.readStructBegin();\r\n while (true)\r\n {\r\n schemeField = iprot.readFieldBegin();\r\n if (schemeField.type == org.apache.thrift.protocol.TType.STOP) { \r\n break;\r\n }\r\n switch (schemeField.id) {\r\n case 0: // SUCCESS\r\n if (schemeField.type == org.apache.thrift.protocol.TType.I32) {\r\n struct.success = iprot.readI32();\r\n struct.setSuccessIsSet(true);\r\n } else { \r\n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\r\n }\r\n break;\r\n default:\r\n org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);\r\n }\r\n iprot.readFieldEnd();\r\n }\r\n iprot.readStructEnd();\r\n\r\n // check for required fields of primitive type, which can't be checked in the validate method\r\n struct.validate();\r\n }\r\n\r\n public void write(org.apache.thrift.protocol.TProtocol oprot, getJobStatus_result struct) throws org.apache.thrift.TException {\r\n struct.validate();\r\n\r\n oprot.writeStructBegin(STRUCT_DESC);\r\n if (struct.isSetSuccess()) {\r\n oprot.writeFieldBegin(SUCCESS_FIELD_DESC);\r\n oprot.writeI32(struct.success);\r\n oprot.writeFieldEnd();\r\n }\r\n oprot.writeFieldStop();\r\n oprot.writeStructEnd();\r\n }\r\n\r\n }\r\n\r\n private static class getJobStatus_resultTupleSchemeFactory implements SchemeFactory {\r\n public getJobStatus_resultTupleScheme getScheme() {\r\n return new getJobStatus_resultTupleScheme();\r\n }\r\n }\r\n\r\n private static class getJobStatus_resultTupleScheme extends TupleScheme<getJobStatus_result> {\r\n\r\n @Override\r\n public void write(org.apache.thrift.protocol.TProtocol prot, getJobStatus_result struct) throws org.apache.thrift.TException {\r\n TTupleProtocol oprot = (TTupleProtocol) prot;\r\n BitSet optionals = new BitSet();\r\n if (struct.isSetSuccess()) {\r\n optionals.set(0);\r\n }\r\n oprot.writeBitSet(optionals, 1);\r\n if (struct.isSetSuccess()) {\r\n oprot.writeI32(struct.success);\r\n }\r\n }\r\n\r\n @Override\r\n public void read(org.apache.thrift.protocol.TProtocol prot, getJobStatus_result struct) throws org.apache.thrift.TException {\r\n TTupleProtocol iprot = (TTupleProtocol) prot;\r\n BitSet incoming = iprot.readBitSet(1);\r\n if (incoming.get(0)) {\r\n struct.success = iprot.readI32();\r\n struct.setSuccessIsSet(true);\r\n }\r\n }\r\n }\r\n\r\n }\r\n\r\n}\r",
"public interface StreamLogParser {\n\t/**\n\t * 自定义实现:从指定队列dataQu中,获取指定数目curNum的单条日志信息, \n\t * 加工成每条信息类似: {uid:设备ID或通行证ID,data:{view:{docIds},collect:{docIds}}}形式的信息列表\n\t * @param dataQu\n\t * @param curNum\n\t * @return\n\t */\n\tList<String> parseLogs(ConcurrentLinkedQueue<String> dataQu, int curNum);\n}",
"public class KafkaMqCollect extends MqConsumer{\n\t\n\tprivate ConsumerConnector consumer;\n\t\n\tpublic KafkaMqCollect(){\n\t\tsuper();\n\t\tthis.init();\n\t}\n\t\n\tpublic void init(){\n\t\tProperties props = new Properties();\n props.put(\"zookeeper.connect\", Constants.kfZkServers);\n props.put(\"group.id\", Constants.kfGroupId);\n props.put(\"auto.offset.reset\", Constants.kfAutoOffsetReset);\n props.put(\"zookeeper.session.timeout.ms\", \"4000\");\n props.put(\"zookeeper.sync.time.ms\", \"200\");\n props.put(\"auto.commit.interval.ms\", \"1000\");\n props.put(\"serializer.class\", \"kafka.serializer.StringEncoder\");\n ConsumerConfig config = new ConsumerConfig(props);\n consumer = Consumer.createJavaConsumerConnector(config);\n\t}\n\t\n\tpublic void collectMq(){\n\t\tMap<String, Integer> topicCountMap = new HashMap<String, Integer>();\n topicCountMap.put(Constants.kfTopic, new Integer(1));\n \n StringDecoder keyDecoder = new StringDecoder(new VerifiableProperties());\n StringDecoder valueDecoder = new StringDecoder(new VerifiableProperties());\n \n Map<String, List<KafkaStream<String, String>>> consumerMap =\n consumer.createMessageStreams(topicCountMap,keyDecoder,valueDecoder);\n \n KafkaStream<String, String> stream = consumerMap.get(Constants.kfTopic).get(0);\n ConsumerIterator<String, String> it = stream.iterator();\n MessageAndMetadata<String, String> msgMeta;\n while (it.hasNext()){\n \tmsgMeta = it.next();\n \tsuper.mqTimer.parseMqText(msgMeta.key(), msgMeta.message());\n \t//System.out.println(msgMeta.key()+\"\\t\"+msgMeta.message());\n }\n\t}\n\n//\tpublic static void main(String[] args) {\n//\t\tKafkaMqCollect kmc = new KafkaMqCollect();\n//\t\tkmc.collectMq();\n//\t}\n\n}",
"public class RtdcAdminService implements Iface {\n\n\t@Override\n\tpublic int addMqinfoToAdminQu(List<String> uLogs) throws TException {\n\t\tboolean rt = AdminNodeTimer.addSteamData(uLogs);\n\t\tif(rt)\n\t\t\treturn 1;\n\t\telse\n\t\t\treturn 0;\n\t}\n\n\t@Override\n\tpublic int rtcStats(List<String> userLogs) throws TException {\n\t\t\n\t\treturn 0;\n\t}\n\n\t@Override\n\tpublic int batchStats(int start, int size) throws TException {\n\t\t// TODO Auto-generated method stub\n\t\treturn 0;\n\t}\n\n\t@Override\n\tpublic int getAdminNodeId() throws TException {\n\t\t\n\t\treturn 0;\n\t}\n\n\t@Override\n\tpublic int getHealthStatus() throws TException {\n\t\treturn 1;\n\t}\n\n\t@Override\n\tpublic int getJobStatus() throws TException {\n\t\t// TODO Auto-generated method stub\n\t\treturn 0;\n\t}\n\n}",
"public class AdminNodeTimer extends TimerTask{\r\n\tprotected FileUtil fu = new FileUtil();\r\n\tprotected static ConcurrentLinkedQueue<String> dataQu = new ConcurrentLinkedQueue<String>();\r\n\tprivate static TreeMap<Long,Integer> delayTaskIdDataNums = new TreeMap<Long,Integer>();\r\n\tprotected static ConcurrentLinkedQueue<List<String>> memDelayQu = new ConcurrentLinkedQueue<List<String>>();\r\n\tprivate static int minBathJobStatus = 0;\r\n\tprivate static StreamLogParser slp;\r\n\tprivate AdminNodeService ans = new AdminNodeService();\r\n\tprivate long timerNum = 0;\r\n\t\r\n\tpublic static void setStreamLogParser(StreamLogParser streamLogParser){\r\n\t\tslp = streamLogParser;\r\n\t}\r\n\t\r\n\tpublic static boolean addSteamData(List<String> uLogs){\r\n\t\treturn dataQu.addAll(uLogs);\r\n\t}\r\n\t\r\n\tpublic static int getJobStatus(){\r\n\t\treturn minBathJobStatus;\r\n\t}\r\n\t\r\n\t@Override\r\n\tpublic void run() {\r\n\t\tint curLogNum = dataQu.size();\r\n\t\tSystem.out.println(ConfigProperty.getCurDateTime()+\" curLogNum : \"+curLogNum);\r\n\t\tif(curLogNum>0){\r\n\t\t\tList<String> userActionList = slp.parseLogs(dataQu, curLogNum);\r\n\t\t\tint memDelayTaskNum = memDelayQu.size();\r\n\t\t\tif(minBathJobStatus==0){\r\n\t\t\t\tif(memDelayTaskNum>0){\r\n\t\t\t\t\tans.setUserActions(memDelayQu.poll());\r\n\t\t\t\t\tnew Thread(new AdminConsole()).start();\r\n\t\t\t\t\tif(memDelayTaskNum<Constants.maxDelayTaskNum){\r\n\t\t\t\t\t\tif(delayTaskIdDataNums.size()>0){\r\n\t\t\t\t\t\t\twhile(memDelayQu.size()<Constants.maxDelayTaskNum && delayTaskIdDataNums.size()>0){\r\n\t\t\t\t\t\t\t\tString taskFile = Constants.delayTaskDir + delayTaskIdDataNums.pollFirstEntry().getKey() + Constants.delayTaskFileSurfix;\r\n\t\t\t\t\t\t\t\tList<String> rtJsonList = fu.readActions(taskFile);\r\n\t\t\t\t\t\t\t\tif(rtJsonList!=null){\r\n\t\t\t\t\t\t\t\t\tmemDelayQu.add(rtJsonList);\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\tfu.delActionFile(taskFile);\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tif(memDelayQu.size()<Constants.maxDelayTaskNum){\r\n\t\t\t\t\t\t\tmemDelayQu.add(userActionList);\r\n\t\t\t\t\t\t}else{\r\n\t\t\t\t\t\t\tlong rtNum = ans.getCurrentTime();\r\n\t\t\t\t\t\t\tdelayTaskIdDataNums.put(rtNum, curLogNum);\r\n\t\t\t\t\t\t\tfu.writeActions(userActionList, Constants.delayTaskDir+rtNum+Constants.delayTaskFileSurfix);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}else{\r\n\t\t\t\t\t\tlong rtNum = ans.getCurrentTime();\r\n\t\t\t\t\t\tdelayTaskIdDataNums.put(rtNum, curLogNum);\r\n\t\t\t\t\t\tfu.writeActions(userActionList, Constants.delayTaskDir+rtNum+Constants.delayTaskFileSurfix);\r\n\t\t\t\t\t}\r\n\t\t\t\t}else{\r\n\t\t\t\t\tans.setUserActions(userActionList);\r\n\t\t\t\t\tnew Thread(new AdminConsole()).start();\r\n\t\t\t\t}\r\n\t\t\t}else{\r\n\t\t\t\tif(memDelayTaskNum<Constants.maxDelayTaskNum){\r\n\t\t\t\t\tmemDelayQu.add(userActionList);\r\n\t\t\t\t}else{\r\n\t\t\t\t\tlong rtNum = ans.getCurrentTime();\r\n\t\t\t\t\tdelayTaskIdDataNums.put(rtNum, curLogNum);\r\n\t\t\t\t\tfu.writeActions(userActionList, Constants.delayTaskDir+rtNum+Constants.delayTaskFileSurfix);\r\n\t\t\t\t}\r\n\t\t\t\tSystem.out.println(ConfigProperty.getCurDateTime()+\" 上次计算任务还没有结束\");\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tif(++timerNum%100==0){\r\n\t\t\tSystem.out.println(\"分布式计算任务周期频率更新 \" +timerNum);\r\n\t\t\tSystem.gc();\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic void reRun(){\r\n\t\tif(memDelayQu.size()>0){\r\n\t\t\tSystem.out.println(\"AdminNodeTimer reRun method ......\"+memDelayQu.size());\r\n\t\t\tans.setUserActions(memDelayQu.poll());\r\n\t\t\tnew Thread(new AdminConsole()).start();\r\n\t\t\tif(delayTaskIdDataNums.size()>0){\r\n\t\t\t\tString taskFile = Constants.delayTaskDir + delayTaskIdDataNums.pollFirstEntry().getKey() + Constants.delayTaskFileSurfix;\r\n\t\t\t\tList<String> rtJsonList = fu.readActions(taskFile);\r\n\t\t\t\tif(rtJsonList!=null){\r\n\t\t\t\t\tmemDelayQu.add(rtJsonList);\r\n\t\t\t\t}\r\n\t\t\t\tfu.delActionFile(taskFile); \r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\r\n\tprotected class AdminConsole implements Runnable{\r\n\t\t\r\n\t\t@Override\r\n\t\tpublic void run() {\r\n\t\t\tminBathJobStatus = 1;\r\n\t\t\ttry{\r\n\t\t\t\tans.run();\r\n\t\t\t} catch (Exception e) {\r\n\t\t\t\tSystem.err.println(\"分布式计算任务管理服务错误: \"+e.getMessage());\r\n\t\t\t}\r\n\t\t\tminBathJobStatus = 0;\r\n\t\t\treRun();\r\n\t\t}\r\n\t}\r\n\r\n}\r",
"public class ConfigProperty {\r\n\t\r\n\tprivate static Properties dbProps;\r\n\t\r\n\tprivate static synchronized void init_prop(){\r\n\t\tdbProps = new Properties();\t\r\n\t\tString path = ConfigProperty.class.getClassLoader().getResource(\"\").getPath();\r\n\t\tpath = path.replaceAll(\"%20\", \" \");\r\n\t\tInputStream fileinputstream = null;\r\n\t\ttry {\r\n\t\t\tfileinputstream = new FileInputStream(path+\"rtc_conf.properties\");\r\n\t\t} catch (FileNotFoundException e) {\r\n\t\t\te.printStackTrace();\r\n\t\t}\r\n\t\ttry {\r\n\t\t\tdbProps.load(fileinputstream);\r\n\t\t} catch (IOException e) {\r\n\t\t\te.printStackTrace();\r\n\t\t\tSystem.err.println(\"不能读取数据库配置文件, 请确保rtc_conf.properties在CLASSPATH指定的路径中!\");\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic static Properties getProps(){\r\n\t\tif(dbProps==null)\r\n\t\t\tinit_prop();\r\n\t\treturn dbProps;\r\n\t}\r\n\t\r\n\tpublic static String getCurDateTime() {\r\n\t\tSimpleDateFormat df = new SimpleDateFormat(\"yyyyMMddHHmmss\");//\"yyyyMMddHHmmss\"\r\n\t\treturn df.format(new Date());\r\n\t}\r\n\t\r\n\tpublic static void main(String[] args) {\r\n\t\tSystem.out.println(ConfigProperty.getProps().getProperty(\"cluterName\"));\r\n\t\tSystem.out.println(ConfigProperty.getProps().getProperty(\"clusterHosts\"));\r\n\t\tSystem.out.println(ConfigProperty.getProps().getProperty(\"serverPort\"));\r\n\t\t\r\n\t\tSystem.out.println(\"=============================================\");\r\n\t\t\r\n\t\tSystem.out.println(ConfigProperty.getProps().getProperty(\"minThreadNum\"));\r\n\t\tSystem.out.println(ConfigProperty.getProps().getProperty(\"maxThreadNum\"));\r\n\t\t\r\n\t}\r\n\t\r\n}\r",
"public class Constants {\n\t// es cluster config\n\tpublic static String esClusterName = ConfigProperty.getProps().getProperty(\"cluterName\");\n\tpublic static String esClusterHosts = ConfigProperty.getProps().getProperty(\"clusterHosts\");\n\t\n\t//rabbitmq config\n\tpublic final static String mqHost = ConfigProperty.getProps().getProperty(\"mq.host\");\n\tpublic final static int mqPort = Integer.parseInt(ConfigProperty.getProps().getProperty(\"mq.port\"));\n\tpublic final static String mqUser = ConfigProperty.getProps().getProperty(\"mq.user\");\n\tpublic final static String mqPswd = ConfigProperty.getProps().getProperty(\"mq.pswd\");\n\tpublic final static String mqVhost = ConfigProperty.getProps().getProperty(\"mq.vhost\");\n\tpublic final static String mqExchange = ConfigProperty.getProps().getProperty(\"mq.exchange\");\n\tpublic final static String mqClickKey = ConfigProperty.getProps().getProperty(\"mq.clickRoutKey\");\n\tpublic final static String mqClickFirstQu = ConfigProperty.getProps().getProperty(\"mq.clickQueue1\");\n\tpublic final static String mqClickSecondQu = ConfigProperty.getProps().getProperty(\"mq.clickQueue2\");\n\t\n\t//kafka config\n\tpublic final static String kfZkServers = ConfigProperty.getProps().getProperty(\"kfZkServers\");\n\tpublic final static String kfGroupId = ConfigProperty.getProps().getProperty(\"kfGroupId\");\n\tpublic final static String kfAutoOffsetReset = ConfigProperty.getProps().getProperty(\"kfAutoOffsetReset\");\n\tpublic final static String kfTopic = ConfigProperty.getProps().getProperty(\"kfTopic\");\n\t\n\t//Timer config (unit : seconds)\n\tpublic final static int mqDoBatchTimer = Integer.parseInt(ConfigProperty.getProps().getProperty(\"mqDoBatchTimer\"));\n\t\n\t//AdminNode hosts and ports for DataCollectNode using\n\tpublic final static String adminNodeHosts = ConfigProperty.getProps().getProperty(\"adminNodeHosts\");\n\t\n\t//AdminNode server port\n\tpublic final static int adminNodePort = Integer.parseInt(ConfigProperty.getProps().getProperty(\"adminNodePort\"));\n\t\n\t//JobNode hosts and ports for AdminNode using\n\tpublic final static String jobNodeHosts = ConfigProperty.getProps().getProperty(\"jobNodeHosts\");\n\t\n\t//JobNode server port\n\tpublic final static int jobNodePort = Integer.parseInt(ConfigProperty.getProps().getProperty(\"jobNodePort\"));\n\t\n\t//rtc timer\n\tpublic final static int rtcPeriodSeconds = Integer.parseInt(ConfigProperty.getProps().getProperty(\"rtcPeriodSeconds\"));\n\t\n\tpublic final static int adminNodeId = Integer.parseInt(ConfigProperty.getProps().getProperty(\"adminNodeId\"));\n\t\n\tpublic final static int minJobBatchNum = Integer.parseInt(ConfigProperty.getProps().getProperty(\"minJobBatchNum\"));\n\tpublic final static int atomJobBatchNum = Integer.parseInt(ConfigProperty.getProps().getProperty(\"atomJobBatchNum\"));\n\t\n\t//redis cluster config\n\tpublic final static String redisHosts = ConfigProperty.getProps().getProperty(\"redisHosts\");\n\tpublic final static String redisPswd = ConfigProperty.getProps().getProperty(\"redisPswd\");\n\t\n\tpublic final static String delayTaskDir = ConfigProperty.getProps().getProperty(\"delayTaskDir\");\n\tpublic final static String delayTaskFileSurfix = ConfigProperty.getProps().getProperty(\"delayTaskFileSurfix\");\n\tpublic final static int maxDelayTaskNum = Integer.parseInt(ConfigProperty.getProps().getProperty(\"maxDelayTaskNum\"));\n\t\n}"
] | import java.util.Timer;
import org.apache.thrift.protocol.TCompactProtocol;
import org.apache.thrift.server.TServer;
import org.apache.thrift.server.TThreadPoolServer;
import org.apache.thrift.transport.TServerSocket;
import org.apache.thrift.transport.TServerTransport;
import org.apache.thrift.transport.TTransportException;
import org.light.rtc.api.TDssService;
import org.light.rtc.base.StreamLogParser;
import org.light.rtc.mq.KafkaMqCollect;
import org.light.rtc.service.RtdcAdminService;
import org.light.rtc.timer.AdminNodeTimer;
import org.light.rtc.util.ConfigProperty;
import org.light.rtc.util.Constants; | package org.light.rtc.admin;
public class AdminNodeKafkaRun {
/**
* your self defending function for parsing your data stream logs
* @param slp
*/
public void setSteamParser(StreamLogParser slp){
AdminNodeTimer.setStreamLogParser(slp);
}
private class DataCollect implements Runnable{
@Override
public void run() {
KafkaMqCollect kmc = new KafkaMqCollect();
kmc.collectMq();
}
}
public void run(){
this.adminJobTImer();
new Thread(new DataCollect()).start();
RtdcAdminService rss = new RtdcAdminService();
TDssService.Processor<RtdcAdminService> tp = new TDssService.Processor<RtdcAdminService>(rss);
TServerTransport serverTransport = null;
try {
serverTransport = new TServerSocket(Constants.adminNodePort);
} catch (TTransportException e) {
e.printStackTrace();
}
TThreadPoolServer.Args tArgs = new TThreadPoolServer.Args(serverTransport);
tArgs.maxWorkerThreads(1000);
tArgs.minWorkerThreads(10);
tArgs.processor(tp);
TCompactProtocol.Factory portFactory = new TCompactProtocol.Factory();
tArgs.protocolFactory(portFactory);
TServer tServer = new TThreadPoolServer(tArgs); | System.out.println(ConfigProperty.getCurDateTime()+"......轻量级实时计算框架任务管理节点(通过Kafka整合CN)服务启动......"); | 5 |
elixsr/FwdPortForwardingApp | app/src/main/java/com/elixsr/portforwarder/ui/rules/EditRuleActivity.java | [
"public class FwdApplication extends MultiDexApplication {\n\n private static final String TAG = \"FwdApplication\";\n private Tracker mTracker;\n\n /**\n * Gets the default {@link Tracker} for this {@link Application}.\n *\n * @return tracker\n */\n synchronized public Tracker getDefaultTracker() {\n if (mTracker == null) {\n GoogleAnalytics analytics = GoogleAnalytics.getInstance(this);\n // To enable debug logging use: adb shell setprop log.tag.GAv4 DEBUG\n\n if (BuildConfig.DEBUG) {\n mTracker = analytics.newTracker(R.xml.analytics_debug);\n } else {\n mTracker = analytics.newTracker(R.xml.analytics);\n }\n mTracker.enableAutoActivityTracking(true);\n }\n return mTracker;\n }\n\n\n}",
"public class RuleContract {\n\n public RuleContract() {\n }\n\n /* Inner class that defines the table contents */\n public static abstract class RuleEntry implements BaseColumns {\n public static final String TABLE_NAME = \"rule\";\n public static final String COLUMN_NAME_RULE_ID = \"rule_id\";\n public static final String COLUMN_NAME_NAME = \"name\";\n public static final String COLUMN_NAME_IS_TCP = \"is_tcp\";\n public static final String COLUMN_NAME_IS_UDP = \"is_udp\";\n public static final String COLUMN_NAME_FROM_INTERFACE_NAME = \"from_interface_name\";\n public static final String COLUMN_NAME_FROM_PORT = \"from_port\";\n public static final String COLUMN_NAME_TARGET_IP_ADDRESS = \"target_ip_address\";\n public static final String COLUMN_NAME_TARGET_PORT = \"target_port\";\n public static final String COLUMN_NAME_IS_ENABLED = \"is_enabled\";\n }\n}",
"public class RuleModel implements Serializable {\n\n private static final String TAG = \"RuleModel\";\n\n @Expose(serialize = false, deserialize = false)\n private long id;\n\n @Expose\n private boolean isTcp;\n\n @Expose\n private boolean isUdp;\n\n @Expose\n private String name;\n\n //TODO: create a class? - worth the effort?\n private String fromInterfaceName;\n\n @Expose\n private int fromPort;\n\n @Expose\n private InetSocketAddress target;\n\n private boolean isEnabled = true;\n\n // Null constructor - for object building\n public RuleModel() {\n\n }\n\n public RuleModel(boolean isTcp, boolean isUdp, String name, String fromInterfaceName, int fromPort, InetSocketAddress target) {\n this.isTcp = isTcp;\n this.isUdp = isUdp;\n this.name = name;\n this.fromInterfaceName = fromInterfaceName;\n this.fromPort = fromPort;\n this.target = target;\n }\n\n public RuleModel(boolean isTcp, boolean isUdp, String name, String fromInterfaceName, int fromPort, String targetIp, int targetPort) {\n this(isTcp, isUdp, name, fromInterfaceName, fromPort, new InetSocketAddress(targetIp, targetPort));\n }\n\n public long getId() {\n return id;\n }\n\n public void setId(long id) {\n this.id = id;\n }\n\n public boolean isTcp() {\n return isTcp;\n }\n\n public void setIsTcp(boolean isTcp) {\n this.isTcp = isTcp;\n }\n\n public boolean isUdp() {\n return isUdp;\n }\n\n public void setIsUdp(boolean isUdp) {\n this.isUdp = isUdp;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getFromInterfaceName() {\n return fromInterfaceName;\n }\n\n public void setFromInterfaceName(String fromInterfaceName) {\n this.fromInterfaceName = fromInterfaceName;\n }\n\n public int getFromPort() {\n return fromPort;\n }\n\n public void setFromPort(int fromPort) {\n this.fromPort = fromPort;\n }\n\n public InetSocketAddress getTarget() {\n return target;\n }\n\n public void setTarget(InetSocketAddress target) {\n this.target = target;\n }\n\n public String protocolToString() {\n return RuleHelper.getRuleProtocolFromModel(this);\n }\n\n /**\n * Return a string of the target IPv4 address\n *\n * @return the IPv4 address as a String\n */\n public String getTargetIpAddress() {\n return this.target.getAddress().getHostAddress();\n }\n\n /**\n * Return the target port as an integer\n *\n * @return the target port integer.\n */\n public int getTargetPort() {\n return this.target.getPort();\n }\n\n /**\n * Validate all data held within the model.\n * <p/>\n * Validation rules: <ul> <li>Name should not be null & greater than 0 characters</li>\n * <li>Either TCP or UDP should be true</li> <li>From Interface should not be null & greater\n * than 0 characters</li> <li>From port should be greater than minimum port and smaller than\n * max</li> <li>Target port should be greater than minimum port and smaller than max </li\n * <li>Target IP address should not be null & greater than 0 characters</li> </ul>\n *\n * @return true if valid, false if not valid.\n */\n public boolean isValid() {\n\n // Ensure the rule has a name\n if (name == null || name.length() <= 0) {\n return false;\n }\n\n // It must either be one or the other, or even both\n if (!isTcp && !isUdp) {\n return false;\n }\n\n if (fromInterfaceName == null || fromInterfaceName.length() <= 0) {\n return false;\n }\n\n if (fromPort < RuleHelper.MIN_PORT_VALUE || fromPort > RuleHelper.MAX_PORT_VALUE) {\n return false;\n }\n\n try {\n // Ensure that the value is greater than the minimum, and smaller than max\n if (getTargetPort() <= 0 || getTargetPort() < RuleHelper.TARGET_MIN_PORT || getTargetPort() > RuleHelper.MAX_PORT_VALUE) {\n return false;\n }\n } catch (NullPointerException e) {\n Log.e(TAG, \"Target object was null.\", e);\n return false;\n }\n\n\n // The new rule activity should take care of IP address validation\n if (getTargetIpAddress() == null || name.length() <= 0) {\n return false;\n }\n\n return true;\n\n }\n\n public boolean isEnabled() {\n return isEnabled;\n }\n\n public void setEnabled(boolean enabled) {\n isEnabled = enabled;\n }\n}",
"public class RuleDbHelper extends SQLiteOpenHelper {\n // If you change the database schema, you must increment the database version.\n public static final int DATABASE_VERSION = 3;\n public static final String DATABASE_NAME = \"Rule.db\";\n\n private static final String TEXT_TYPE = \" TEXT\";\n private static final String INTEGER_TYPE = \" INTEGER\";\n private static final String COMMA_SEP = \",\";\n private static final String SQL_CREATE_ENTRIES =\n \"CREATE TABLE \" + RuleContract.RuleEntry.TABLE_NAME + \" (\" +\n RuleContract.RuleEntry.COLUMN_NAME_RULE_ID + \" INTEGER PRIMARY KEY,\" +\n RuleContract.RuleEntry.COLUMN_NAME_NAME + TEXT_TYPE + COMMA_SEP +\n RuleContract.RuleEntry.COLUMN_NAME_IS_TCP + INTEGER_TYPE + COMMA_SEP +\n RuleContract.RuleEntry.COLUMN_NAME_IS_UDP + INTEGER_TYPE + COMMA_SEP +\n RuleContract.RuleEntry.COLUMN_NAME_FROM_INTERFACE_NAME + TEXT_TYPE + COMMA_SEP +\n RuleContract.RuleEntry.COLUMN_NAME_FROM_PORT + INTEGER_TYPE + COMMA_SEP +\n RuleContract.RuleEntry.COLUMN_NAME_TARGET_IP_ADDRESS + TEXT_TYPE + COMMA_SEP +\n RuleContract.RuleEntry.COLUMN_NAME_TARGET_PORT + INTEGER_TYPE + COMMA_SEP +\n RuleContract.RuleEntry.COLUMN_NAME_IS_ENABLED + INTEGER_TYPE +\n \" )\";\n\n private static final String SQL_DELETE_ENTRIES =\n \"DROP TABLE IF EXISTS \" + RuleContract.RuleEntry.TABLE_NAME;\n\n private static final String DATABASE_ALTER_RULES_1 = String.format(\"ALTER TABLE %s ADD COLUMN %s int default 1;\",\n RuleContract.RuleEntry.TABLE_NAME, RuleContract.RuleEntry.COLUMN_NAME_IS_ENABLED);\n\n public RuleDbHelper(Context context) {\n super(context, DATABASE_NAME, null, DATABASE_VERSION);\n }\n\n public void onCreate(SQLiteDatabase db) {\n db.execSQL(SQL_CREATE_ENTRIES);\n }\n\n @Override\n public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {\n\n if (oldVersion < 3) {\n db.execSQL(DATABASE_ALTER_RULES_1);\n }\n\n }\n\n public static String[] generateAllRowsSelection() {\n String[] projection = {\n RuleContract.RuleEntry.COLUMN_NAME_RULE_ID,\n RuleContract.RuleEntry.COLUMN_NAME_NAME,\n RuleContract.RuleEntry.COLUMN_NAME_IS_TCP,\n RuleContract.RuleEntry.COLUMN_NAME_IS_UDP,\n RuleContract.RuleEntry.COLUMN_NAME_FROM_INTERFACE_NAME,\n RuleContract.RuleEntry.COLUMN_NAME_FROM_PORT + TEXT_TYPE,\n RuleContract.RuleEntry.COLUMN_NAME_TARGET_IP_ADDRESS,\n RuleContract.RuleEntry.COLUMN_NAME_TARGET_PORT,\n RuleContract.RuleEntry.COLUMN_NAME_IS_ENABLED\n };\n\n return projection;\n }\n}",
"public class MainActivity extends BaseActivity {\n\n private static final String TAG = \"MainActivity\";\n private static final String FORWARDING_MANAGER_KEY = \"ForwardingManager\";\n private static final String FORWARDING_SERVICE_KEY = \"ForwardingService\";\n\n private List<RuleModel> ruleModels;\n private static RuleListAdapter ruleListAdapter;\n\n private RecyclerView mRecyclerView;\n private RecyclerView.Adapter mAdapter;\n private RecyclerView.LayoutManager mLayoutManager;\n\n\n private ForwardingManager forwardingManager;\n private CoordinatorLayout coordinatorLayout;\n private FloatingActionButton fab;\n\n private Intent forwardingServiceIntent;\n private RuleDao ruleDao;\n private PercentRelativeLayout mRuleListEmptyView;\n private Tracker tracker;\n\n private FirebaseAnalytics mFirebaseAnalytics;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n\n this.forwardingManager = ForwardingManager.getInstance();\n\n setContentView(R.layout.activity_main);\n setSupportActionBar(getActionBarToolbar());\n // getActionBarToolbar().setTitle(R.string.app_tag);\n getActionBarToolbar().setTitle(\"\");\n getSupportActionBar().setDisplayShowHomeEnabled(true);\n getSupportActionBar().setIcon(R.drawable.ic_nav_logo);\n\n // Obtain the FirebaseAnalytics instance.\n mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);\n\n // Determine if this is first start - and whether to show app intro\n onFirstStart();\n\n final Intent newRuleIntent = new Intent(this, NewRuleActivity.class);\n\n // Move to the new rule activity\n this.fab = (FloatingActionButton) findViewById(R.id.fab);\n fab.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n startActivity(newRuleIntent);\n }\n });\n\n // Hide the fab if forwarding is enabled\n // the user should not be able to add/delete rules\n if (this.forwardingManager.isEnabled()) {\n //if the forwarding service is enabled, then we should ensure not to show the fab\n fab.hide();\n } else {\n fab.show();\n }\n\n // Get all models from the data store\n ruleDao = new RuleDao(new RuleDbHelper(this));\n ruleModels = ruleDao.getAllRuleModels();\n\n // Set up rule list and empty view\n mRecyclerView = (RecyclerView) findViewById(R.id.rule_recycler_view);\n mRuleListEmptyView = (PercentRelativeLayout) findViewById(R.id.rule_list_empty_view);\n\n // Use this setting to improve performance if you know that changes\n // In content do not change the layout size of the RecyclerView\n mRecyclerView.setHasFixedSize(true);\n\n // Use a linear layout manager\n mLayoutManager = new LinearLayoutManager(this);\n mRecyclerView.setLayoutManager(mLayoutManager);\n\n // Specify an adapter (see also next example)\n ruleListAdapter = new RuleListAdapter(ruleModels, forwardingManager, getApplicationContext());\n mRecyclerView.setAdapter(ruleListAdapter);\n\n // Store the coordinator layout for snackbar\n coordinatorLayout = (CoordinatorLayout) findViewById(R.id.main_coordinator_layout);\n\n\n forwardingServiceIntent = new Intent(this, ForwardingService.class);\n\n\n /*\n Service stuff\n */\n\n // Handle intents\n IntentFilter mStatusIntentFilter = new IntentFilter(\n ForwardingService.BROADCAST_ACTION);\n\n // Instantiates a new ForwardingServiceResponseReceiver\n ForwardingServiceResponseReceiver forwardingServiceResponseReceiver =\n new ForwardingServiceResponseReceiver();\n\n // Registers the ForwardingServiceResponseReceiver and its intent filters\n LocalBroadcastManager.getInstance(this).registerReceiver(\n forwardingServiceResponseReceiver,\n mStatusIntentFilter);\n\n // Get tracker.\n tracker = ((FwdApplication) this.getApplication()).getDefaultTracker();\n\n Log.i(TAG, \"Finished onCreate\");\n }\n\n @Override\n public void onResume() {\n super.onResume();\n this.ruleModels.clear();\n this.ruleModels.addAll(ruleDao.getAllRuleModels());\n this.ruleListAdapter.notifyDataSetChanged();\n invalidateOptionsMenu();\n\n // Decide whether to show the rule list or the empty view\n if (this.ruleModels.isEmpty()) {\n mRecyclerView.setVisibility(View.GONE);\n mRuleListEmptyView.setVisibility(View.VISIBLE);\n } else {\n mRecyclerView.setVisibility(View.VISIBLE);\n mRuleListEmptyView.setVisibility(View.GONE);\n }\n }\n\n @Override\n protected void onStart() {\n super.onStart();\n }\n\n @Override\n public boolean onCreateOptionsMenu(Menu menu) {\n // Inflate the menu; this adds items to the action bar if it is present.\n getMenuInflater().inflate(R.menu.menu_main, menu);\n\n menu.findItem(R.id.action_toggle_forwarding).setTitle(generateForwardingActionMenuText(forwardingManager.isEnabled()));\n\n // Setup the start forwarding button\n MenuItem toggleForwarding = menu.findItem(R.id.action_toggle_forwarding);\n\n int enabledRuleModels = 0;\n\n for (RuleModel ruleModel : ruleModels) {\n if (ruleModel.isEnabled()) {\n ++enabledRuleModels;\n }\n }\n\n // It should not be able to start if there are no rules\n if (enabledRuleModels <= 0) {\n toggleForwarding.setVisible(false);\n } else {\n toggleForwarding.setVisible(true);\n }\n\n return true;\n }\n\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n // Handle action bar item clicks here. The action bar will\n // automatically handle clicks on the Home/Up button, so long\n // as you specify a parent activity in AndroidManifest.xml.\n int id = item.getItemId();\n\n switch (id) {\n case R.id.action_settings:\n Intent prefIntent = new Intent(this, SettingsActivity.class);\n startActivity(prefIntent);\n break;\n case R.id.action_toggle_forwarding:\n handleForwardingButton(item);\n break;\n case R.id.action_help:\n Intent helpActivityIntent = new Intent(this, HelpActivity.class);\n startActivity(helpActivityIntent);\n break;\n }\n\n return super.onOptionsItemSelected(item);\n }\n\n private void handleForwardingButton(MenuItem item) {\n\n\n if (!forwardingManager.isEnabled()) {\n // startPortForwarding();\n\n Snackbar.make(this.coordinatorLayout, R.string.snackbar_port_forwarding_started_text, Snackbar.LENGTH_LONG)\n .setAction(\"Stop\", null).show();\n\n fab.hide();\n\n startService(forwardingServiceIntent);\n } else {\n // Stop forwarding\n fab.show();\n\n Snackbar.make(this.coordinatorLayout, R.string.snackbar_port_forwarding_stopped_text, Snackbar.LENGTH_LONG).show();\n\n stopService(forwardingServiceIntent);\n }\n\n Log.i(TAG, \"Forwarding Enabled: \" + forwardingManager.isEnabled());\n item.setTitle(generateForwardingActionMenuText(forwardingManager.isEnabled()));\n }\n\n\n private String generateForwardingActionMenuText(boolean forwardingFlag) {\n if (forwardingFlag) {\n return this.getString(R.string.action_stop_forwarding);\n }\n return this.getString(R.string.action_start_forwarding);\n\n }\n\n @Override\n protected void onSaveInstanceState(Bundle outState) {\n super.onSaveInstanceState(outState);\n\n outState.putSerializable(FORWARDING_MANAGER_KEY, this.forwardingManager);\n }\n\n @Override\n protected void onDestroy() {\n super.onDestroy();\n\n // stopService(forwardingServiceIntent);\n Log.i(TAG, \"Destroyed\");\n }\n\n // Broadcast receiver for receiving status updates from the IntentService\n private class ForwardingServiceResponseReceiver extends BroadcastReceiver {\n // Prevents instantiation\n private ForwardingServiceResponseReceiver() {\n }\n\n // Called when the BroadcastReceiver gets an Intent it's registered to receive\n @Override\n public void onReceive(Context context, Intent intent) {\n /*\n * Handle Intents here.\n */\n\n if (intent.getExtras().containsKey(ForwardingService.PORT_FORWARD_SERVICE_STATE)) {\n Log.i(TAG, \"Response from ForwardingService, Forwarding status has changed.\");\n Log.i(TAG, \"Forwarding status has changed to \" + String.valueOf(intent.getExtras().getBoolean(ForwardingService.PORT_FORWARD_SERVICE_STATE)));\n invalidateOptionsMenu();\n }\n\n if (intent.getExtras().containsKey(ForwardingService.PORT_FORWARD_SERVICE_ERROR_MESSAGE)) {\n\n Toast.makeText(context, intent.getExtras().getString(ForwardingService.PORT_FORWARD_SERVICE_ERROR_MESSAGE),\n Toast.LENGTH_SHORT).show();\n Snackbar.make(coordinatorLayout, R.string.snackbar_port_forwarding_stopped_text, Snackbar.LENGTH_SHORT).show();\n fab.show();\n\n }\n }\n }\n\n @Override\n public void onBackPressed() {\n super.onBackPressed();\n\n finish();\n }\n\n private void onFirstStart() {\n // Declare a new thread to do a preference check\n Thread t = new Thread(new Runnable() {\n @Override\n public void run() {\n // Initialize SharedPreferences\n SharedPreferences getPrefs = PreferenceManager\n .getDefaultSharedPreferences(getBaseContext());\n\n // Create a new boolean and preference and set it to true\n boolean isFirstStart = getPrefs.getBoolean(\"firstStart\", true);\n\n // If the activity has never started before...\n if (isFirstStart) {\n\n // Launch app intro\n Intent i = new Intent(MainActivity.this, MainIntro.class);\n startActivity(i);\n\n // Make a new preferences editor\n SharedPreferences.Editor e = getPrefs.edit();\n\n // Edit preference to make it false because we don't want this to run again\n e.putBoolean(\"firstStart\", false);\n\n // Apply changes\n e.apply();\n }\n }\n });\n\n // Start the thread\n t.start();\n }\n}",
"public class RuleHelper {\n\n public static final String RULE_MODEL_ID = \"RuleModelId\";\n\n /**\n * The minimum from port value.\n * <p>\n * This is a result of not having root permissions.\n */\n public static final int MIN_PORT_VALUE = 1024;\n\n /**\n * The minimum target port value.\n */\n public static final int TARGET_MIN_PORT = 1;\n\n /**\n * The maximum from and target port value.\n */\n public static final int MAX_PORT_VALUE = 65535;\n\n /**\n * Convert a {@link RuleModel} object to a {@link ContentValues} object.\n *\n * @param ruleModel The {@link RuleModel} object to be converted.\n * @return a {@link ContentValues} object based off the input {@link RuleModel} object.\n */\n public static ContentValues ruleModelToContentValues(RuleModel ruleModel) {\n\n // Create a new map of values, where column names are the keys\n ContentValues contentValues = new ContentValues();\n contentValues.put(RuleContract.RuleEntry.COLUMN_NAME_NAME, ruleModel.getName());\n contentValues.put(RuleContract.RuleEntry.COLUMN_NAME_IS_TCP, ruleModel.isTcp());\n contentValues.put(RuleContract.RuleEntry.COLUMN_NAME_IS_UDP, ruleModel.isUdp());\n contentValues.put(RuleContract.RuleEntry.COLUMN_NAME_FROM_INTERFACE_NAME, ruleModel.getFromInterfaceName());\n contentValues.put(RuleContract.RuleEntry.COLUMN_NAME_FROM_PORT, ruleModel.getFromPort());\n contentValues.put(RuleContract.RuleEntry.COLUMN_NAME_TARGET_IP_ADDRESS, ruleModel.getTargetIpAddress());\n contentValues.put(RuleContract.RuleEntry.COLUMN_NAME_TARGET_PORT, ruleModel.getTargetPort());\n contentValues.put(RuleContract.RuleEntry.COLUMN_NAME_IS_ENABLED, ruleModel.isEnabled());\n\n return contentValues;\n }\n\n /**\n * Convert a {@link Cursor} object to a {@link RuleModel} object.\n *\n * @param cursor The {@link Cursor} object to be converted.\n * @return a {@link RuleModel} based off the input {@link Cursor}\n */\n public static RuleModel cursorToRuleModel(Cursor cursor) {\n\n RuleModel ruleModel = new RuleModel();\n ruleModel.setId(cursor.getLong(0));\n ruleModel.setName(cursor.getString(1));\n\n //dirty conversion hack\n ruleModel.setIsTcp(cursor.getInt(2) != 0);\n ruleModel.setIsUdp(cursor.getInt(3) != 0);\n ruleModel.setFromInterfaceName(cursor.getString(4));\n ruleModel.setFromPort(cursor.getInt(5));\n ruleModel.setTarget(new InetSocketAddress(cursor.getString(6), cursor.getInt(7)));\n ruleModel.setEnabled(cursor.getInt(8) != 0);\n\n return ruleModel;\n }\n\n /**\n * Function to find the relevant Protocol based of a {@link RuleModel} object.\n *\n * @param ruleModel The source {@link RuleModel} object.\n * @return A String describing the protocol. Can be; \"TCP\", \"UDP\" or \"BOTH\".\n */\n public static String getRuleProtocolFromModel(RuleModel ruleModel) {\n\n String result = \"\";\n\n if (ruleModel.isTcp()) {\n result = NetworkHelper.TCP;\n }\n\n if (ruleModel.isUdp()) {\n result = NetworkHelper.UDP;\n }\n\n if (ruleModel.isTcp() && ruleModel.isUdp()) {\n result = NetworkHelper.BOTH;\n }\n\n return result;\n }\n}"
] | import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TextInputEditText;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import com.elixsr.core.common.widgets.SwitchBar;
import com.elixsr.portforwarder.FwdApplication;
import com.elixsr.portforwarder.R;
import com.elixsr.portforwarder.db.RuleContract;
import com.elixsr.portforwarder.models.RuleModel;
import com.elixsr.portforwarder.db.RuleDbHelper;
import com.elixsr.portforwarder.ui.MainActivity;
import com.elixsr.portforwarder.util.RuleHelper;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import com.google.firebase.analytics.FirebaseAnalytics; | /*
* Fwd: the port forwarding app
* Copyright (C) 2016 Elixsr Ltd
*
* 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 com.elixsr.portforwarder.ui.rules;
/**
* Created by Niall McShane on 02/03/2016.
*/
public class EditRuleActivity extends BaseRuleActivity {
private static final String TAG = "EditRuleActivity";
private static final String NO_RULE_ID_FOUND_LOG_MESSAGE = "No ID was supplied to EditRuleActivity";
private static final String NO_RULE_ID_FOUND_TOAST_MESSAGE = "Could not locate rule";
private static final String ACTION_DELETE = "Delete";
private static final String LABEL_DELETE_RULE = "Delete Rule";
private static final String LABEL_UPDATE_RULE = "Rule Updated";
private FirebaseAnalytics mFirebaseAnalytics;
private RuleModel ruleModel;
private long ruleModelId;
private SQLiteDatabase db;
private Tracker tracker;
private SwitchBar switchBar;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// If we can't locate the id, then we can't continue | if (!getIntent().getExtras().containsKey(RuleHelper.RULE_MODEL_ID)) { | 5 |
weiboad/fiery | server/src/main/java/org/weiboad/ragnar/server/search/IndexSearchSharderManager.java | [
"@Component\n@ConfigurationProperties(prefix = \"fiery\")\npublic class FieryConfig {\n\n private int keepdataday;\n\n private String dbpath;\n\n private String indexpath;\n\n private Boolean kafkaenable;\n\n private String kafkaserver;\n\n private String kafkagroupid;\n\n private String mailfrom;\n\n public String getMailfrom() {\n return mailfrom;\n }\n\n public void setMailfrom(String mailfrom) {\n this.mailfrom = mailfrom;\n }\n\n public String getMailto() {\n return mailto;\n }\n\n public void setMailto(String mailto) {\n this.mailto = mailto;\n }\n\n private String mailto;\n\n public String getKafkagroupid() {\n return kafkagroupid;\n }\n\n public void setKafkagroupid(String kafkagroupid) {\n this.kafkagroupid = kafkagroupid;\n }\n\n public Boolean getKafkaenable() {\n return kafkaenable;\n }\n\n public void setKafkaenable(Boolean kafkaenable) {\n this.kafkaenable = kafkaenable;\n }\n\n public String getKafkaserver() {\n return kafkaserver;\n }\n\n public void setKafkaserver(String kafkaserver) {\n this.kafkaserver = kafkaserver;\n }\n\n public String getKafkatopic() {\n return kafkatopic;\n }\n\n public void setKafkatopic(String kafkatopic) {\n this.kafkatopic = kafkatopic;\n }\n\n private String kafkatopic;\n\n public String getDbpath() {\n return dbpath;\n }\n\n public void setDbpath(String dbpath) {\n this.dbpath = dbpath;\n }\n\n public String getIndexpath() {\n return indexpath;\n }\n\n public void setIndexpath(String indexpath) {\n this.indexpath = indexpath;\n }\n\n public int getKeepdataday() {\n return keepdataday;\n }\n\n public void setKeepdataday(int keepdataday) {\n this.keepdataday = keepdataday;\n }\n}",
"public class MetaLog {\n\n\n public String version = \"\";\n public String rpcid = \"\";\n public String traceid = \"\";\n public Double time = 0d;\n public Double time_raw = 0D;\n public Date time_date = new Date(0);\n\n public Float elapsed_ms = 0.0F;\n public String perf_on = \"\";\n public String ip = \"\";\n public String rt_type = \"\";\n public String uid = \"\";\n public String url = \"\";\n public String param = \"\";\n public String httpcode = \"\";\n public String project = \"\";\n //public Map<String, String> extra = new Map<String, String>();\n\n public Date getTime_date() {\n return time_date;\n }\n\n public void setTime_date(Date time_date) {\n this.time_date = time_date;\n }\n\n public String getVersion() {\n return version;\n }\n\n public void setVersion(String version) {\n if (version != null) {\n this.version = version;\n } else {\n this.version = \"\";\n }\n }\n\n public String getRpcid() {\n return rpcid;\n }\n\n public void setRpcid(String rpcid) {\n this.rpcid = rpcid;\n }\n\n public String getTraceid() {\n return traceid;\n }\n\n public void setTraceid(String traceid) {\n this.traceid = traceid;\n }\n\n public Double getTime() {\n return time;\n }\n\n public void setTime(Double time) {\n this.time = time;\n this.time_raw = time;\n this.time_date = new Date(time.longValue() * 1000l);\n }\n\n public Float getElapsed_ms() {\n return elapsed_ms;\n }\n\n public void setElapsed_ms(Float elapsed_ms) {\n this.elapsed_ms = elapsed_ms;\n }\n\n public String getPerf_on() {\n return perf_on;\n }\n\n public void setPerf_on(String perf_on) {\n this.perf_on = perf_on;\n }\n\n public String getIp() {\n return ip;\n }\n\n public void setIp(String ip) {\n this.ip = ip;\n }\n\n public String getRt_type() {\n return rt_type;\n }\n\n public void setRt_type(String rt_type) {\n this.rt_type = rt_type;\n }\n\n public String getUid() {\n return uid;\n }\n\n public void setUid(String uid) {\n this.uid = uid;\n }\n\n public String getUrl() {\n return url;\n }\n\n public void setUrl(String url) {\n this.url = url;\n }\n\n public String getParam() {\n return param;\n }\n\n public void setParam(String param) {\n this.param = param;\n }\n\n public String getHttpcode() {\n return httpcode;\n }\n\n public void setHttpcode(String httpcode) {\n this.httpcode = httpcode;\n }\n\n public String getProject() {\n return project;\n }\n\n public void setProject(String project) {\n this.project = project;\n }\n\n public Double getTime_raw() {\n return time_raw;\n }\n\n public void setTime_raw(Double time_raw) {\n this.time_raw = time_raw;\n this.time = time_raw;\n this.time_date = new Date(time_raw.longValue() * 1000l);\n }\n/*\n public Map<String, String> getExtra() {\n return extra;\n }\n\n public String getExtraStr() {\n return extra.toString();\n }\n\n public void setExtra(Map<String, String> extra) {\n this.extra = extra;\n }*/\n\n public Document gDoc() {\n Document doc = new Document();\n Field version = new TextField(\"version\", getVersion(), Field.Store.YES);\n Field rpcid = new StringField(\"rpcid\", getRpcid(), Field.Store.YES);\n Field traceid = new StringField(\"traceid\", getTraceid(), Field.Store.YES);\n\n Field time = new DoubleDocValuesField(\"time\", getTime());\n Field timeDouble = new DoublePoint(\"time\", getTime());\n Field timeRaw = new StoredField(\"time_raw\", getTime());\n\n //Field timestamp = new LongPoint(\"timestamp\", lastModified);\n Field elapsed = new DoubleDocValuesField(\"elapsed_ms\", getElapsed_ms());\n Field elapsedRaw = new StoredField(\"elapsed_ms_raw\", getElapsed_ms());\n Field elapsedDouble = new DoublePoint(\"elapsed_ms\", getElapsed_ms());\n\n Field perf_on = new TextField(\"perf_on\", getPerf_on(), Field.Store.YES);\n Field ip = new TextField(\"ip\", getIp(), Field.Store.YES);\n Field rt_type = new TextField(\"rt_type\", getRt_type(), Field.Store.YES);\n Field uid = new StringField(\"uid\", getUid(), Field.Store.YES);\n Field url = new TextField(\"url\", getUrl(), Field.Store.YES);\n Field urlraw = new SortedDocValuesField(\"urlraw\", new BytesRef(getUrl()));\n Field param = new TextField(\"param\", getParam(), Field.Store.YES);\n Field httpcode = new TextField(\"httpcode\", getHttpcode(), Field.Store.YES);\n Field project = new TextField(\"project\", getProject(), Field.Store.YES);\n //todo:extra没有做处理\n //Field extra = new StringField(\"param\", getExtraStr(), Field.Store.YES);\n\n doc.add(version);\n doc.add(rpcid);\n doc.add(traceid);\n doc.add(time);\n doc.add(timeRaw);\n doc.add(timeDouble);\n\n //doc.add(timestamp);\n doc.add(elapsed);\n doc.add(elapsedRaw);\n doc.add(elapsedDouble);\n\n doc.add(perf_on);\n doc.add(ip);\n doc.add(rt_type);\n doc.add(uid);\n doc.add(url);\n doc.add(urlraw);\n doc.add(param);\n doc.add(httpcode);\n doc.add(project);\n //doc.add(extra);\n\n return doc;\n }\n\n public void init(Document doc) {\n version = doc.get(\"version\");\n rpcid = doc.get(\"rpcid\");\n traceid = doc.get(\"traceid\");\n try {\n setTime(Double.parseDouble((doc.get(\"time\"))));\n } catch (Exception e) {\n setTime(0d);\n }\n\n try {\n setTime_raw(Double.parseDouble((doc.get(\"time_raw\"))));\n } catch (Exception e) {\n setTime_raw(0d);\n }\n try {\n setElapsed_ms(Float.parseFloat(doc.get(\"elapsed_ms_raw\")));\n } catch (Exception e) {\n setElapsed_ms(0f);\n }\n perf_on = doc.get(\"perf_on\");\n ip = doc.get(\"ip\");\n rt_type = doc.get(\"rt_type\");\n uid = doc.get(\"uid\");\n url = doc.get(\"url\");\n param = doc.get(\"param\");\n httpcode = doc.get(\"httpcode\");\n project = doc.get(\"project\");\n\n //IndexableField extrafield doc.getField(\"extra\");\n //extra = doc.get(\"extra\");\n\n }\n}",
"public class ResponseJson {\n public int code = 0;\n public String msg = \"OK\";\n public long totalcount = 0;\n public List<MetaLog> result = new ArrayList<>();\n\n\n public int getCode() {\n return code;\n }\n\n public void setCode(int code) {\n this.code = code;\n }\n\n public String getMsg() {\n return msg;\n }\n\n public void setMsg(String msg) {\n this.msg = msg;\n }\n\n public List<MetaLog> getResult() {\n return result;\n }\n\n public void setResult(List<MetaLog> result) {\n this.result = result;\n }\n\n public long getTotalcount() {\n return totalcount;\n }\n\n public void setTotalcount(long totalcount) {\n this.totalcount = totalcount;\n }\n}",
"public class DateTimeHelper {\n\n public static String TimeStamp2Date(String timestampString, String formats) {\n Long timestamp = Long.parseLong(timestampString) * 1000;\n String date = new java.text.SimpleDateFormat(formats).format(new java.util.Date(timestamp));\n return date;\n }\n\n public static long getBeforeDay(int day) {\n return (System.currentTimeMillis() / 1000) - day * 24 * 3600;\n }\n\n //获取今天0点 timestamp\n public static long getTimesMorning(Long timestamp) {\n Calendar cal = Calendar.getInstance();\n cal.setTimeInMillis(timestamp * 1000);\n cal.set(Calendar.HOUR_OF_DAY, 0);\n cal.set(Calendar.SECOND, 0);\n cal.set(Calendar.MINUTE, 0);\n cal.set(Calendar.MILLISECOND, 0);\n return (int) (cal.getTimeInMillis() / 1000);\n }\n\n //获取小时整数 timestamp\n public static long getHourTime(Long timestamp) {\n Calendar cal = Calendar.getInstance();\n cal.setTimeInMillis(timestamp * 1000);\n cal.set(Calendar.SECOND, 0);\n cal.set(Calendar.MINUTE, 0);\n cal.set(Calendar.MILLISECOND, 0);\n return (int) (cal.getTimeInMillis() / 1000);\n }\n\n //获取小时 timestamp\n public static long getHour(Long timestamp) {\n Calendar cal = Calendar.getInstance();\n cal.setTimeInMillis(timestamp * 1000);\n return (cal.get(Calendar.HOUR_OF_DAY));\n }\n\n //获取当前时间\n public static long getCurrentTime() {\n return System.currentTimeMillis() / 1000;\n }\n\n public static List<String> getDateTimeListForPage(int keepday) {\n List<String> timelist = new ArrayList<>();\n\n long timestamp = getCurrentTime();\n long moringTime = getTimesMorning(timestamp);\n\n for (int interDay = 0; interDay < keepday; interDay++) {\n timelist.add(\n DateTimeHelper.TimeStamp2Date(String.valueOf(moringTime - (24 * 60 * 60) * interDay), \"yyyy-MM-dd\"));\n }\n return timelist;\n }\n\n}",
"public class FileUtil {\n\n //递归删除空目录,但是不删除文件\n public static boolean deleteDir(String dirpath) {\n\n //prevent the wrong path make the server down\n if (dirpath.trim().equals(\"/\") || dirpath.trim().equals(\"\\\\\")) {\n return false;\n }\n\n File dir = new File(dirpath);\n if (dir.isDirectory()) {\n String[] children = dir.list();\n //递归删除目录中的子目录\n for (int i = 0; i < children.length; i++) {\n boolean success = deleteDir(dir + \"/\" + children[i]);\n if (!success) {\n return false;\n }\n }\n }\n // 目录此时为空,可以删除\n return dir.delete();\n }\n\n //list the sub folder list\n public static HashMap<String, String> subFolderList(String path) throws IOException {\n\n HashMap<String, String> result = new HashMap<>();\n\n File file = new File(path);\n if (file.exists()) {\n File[] files = file.listFiles();\n for (File file2 : files) {\n if (file2.isDirectory()) {\n result.put(file2.getName(), file2.getCanonicalPath());\n }\n }\n }\n return result;\n }\n}"
] | import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.cn.smart.SmartChineseAnalyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.MultiReader;
import org.apache.lucene.search.*;
import org.apache.lucene.store.FSDirectory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.weiboad.ragnar.server.config.FieryConfig;
import org.weiboad.ragnar.server.struct.MetaLog;
import org.weiboad.ragnar.server.struct.ResponseJson;
import org.weiboad.ragnar.server.util.DateTimeHelper;
import org.weiboad.ragnar.server.util.FileUtil;
import java.nio.file.Paths;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap; | package org.weiboad.ragnar.server.search;
@Component
@Scope("singleton")
public class IndexSearchSharderManager {
private Logger log;
@Autowired
private FieryConfig fieryConfig;
//init
private ConcurrentHashMap<String, Analyzer> analyzerList = new ConcurrentHashMap<>();
//Directory
private ConcurrentHashMap<String, FSDirectory> directorList = new ConcurrentHashMap<>();
//reader
private ConcurrentHashMap<String, DirectoryReader> readerList = new ConcurrentHashMap<>();
private MultiReader allInOneReader;
//searcher
private IndexSearcher searcher;
//init flag
private int isinit = 0;
//group searcher
//private GroupingSearch groupsearch;
public IndexSearchSharderManager() {
log = LoggerFactory.getLogger(IndexSearchSharderManager.class);
}
public Map<String, Map<String, String>> getSearchIndexInfo() {
Map<String, Map<String, String>> result = new LinkedHashMap<>();
for (Map.Entry<String, DirectoryReader> e : readerList.entrySet()) {
String dbname = e.getKey();
DirectoryReader diskReader = e.getValue();
Map<String, String> indexInfo = new LinkedHashMap<>();
indexInfo.put("count", diskReader.numDocs() + "");
result.put(dbname, indexInfo);
}
return result;
}
public int getIndexedDocCount() {
if (allInOneReader != null) {
return allInOneReader.numDocs();
}
return 0;
}
public ResponseJson searchByQuery(Long timestamp, Query query, int start, long limit, Sort sort) {
String timeSharder = String.valueOf(DateTimeHelper.getTimesMorning(timestamp));
ResponseJson responeJson = new ResponseJson();
//ignore the out of date search
if (timestamp > DateTimeHelper.getBeforeDay(fieryConfig.getKeepdataday()) && timestamp <= DateTimeHelper.getCurrentTime()) {
//fixed the index not load
if (!readerList.containsKey(timeSharder)) {
log.info("index not loaded:" + timeSharder);
boolean loadRet = this.openIndex(timeSharder, fieryConfig.getIndexpath() + "/" + timeSharder);
if(!loadRet){
responeJson.setMsg( "error load index");
responeJson.setCode (232);
return responeJson;
}
}
| ArrayList<MetaLog> metalist = new ArrayList<MetaLog>(); | 1 |
jenkinsci/github-plugin | src/test/java/org/jenkinsci/plugins/github/webhook/WebhookManagerTest.java | [
"public class GitHubPushTrigger extends Trigger<Job<?, ?>> implements GitHubTrigger {\n\n @DataBoundConstructor\n public GitHubPushTrigger() {\n }\n\n /**\n * Called when a POST is made.\n */\n @Deprecated\n public void onPost() {\n onPost(GitHubTriggerEvent.create()\n .build()\n );\n }\n\n /**\n * Called when a POST is made.\n */\n public void onPost(String triggeredByUser) {\n onPost(GitHubTriggerEvent.create()\n .withOrigin(SCMEvent.originOf(Stapler.getCurrentRequest()))\n .withTriggeredByUser(triggeredByUser)\n .build()\n );\n }\n\n /**\n * Called when a POST is made.\n */\n public void onPost(final GitHubTriggerEvent event) {\n if (Objects.isNull(job)) {\n return; // nothing to do\n }\n\n Job<?, ?> currentJob = notNull(job, \"Job can't be null\");\n\n final String pushBy = event.getTriggeredByUser();\n DescriptorImpl d = getDescriptor();\n d.checkThreadPoolSizeAndUpdateIfNecessary();\n d.queue.execute(new Runnable() {\n private boolean runPolling() {\n try {\n StreamTaskListener listener = new StreamTaskListener(getLogFileForJob(currentJob));\n\n try {\n PrintStream logger = listener.getLogger();\n\n long start = System.currentTimeMillis();\n logger.println(\"Started on \" + DateFormat.getDateTimeInstance().format(new Date()));\n if (event.getOrigin() != null) {\n logger.format(\"Started by event from %s on %tc%n\", event.getOrigin(), event.getTimestamp());\n }\n SCMTriggerItem item = SCMTriggerItems.asSCMTriggerItem(currentJob);\n if (null == item) {\n throw new IllegalStateException(\"Job is not an SCMTriggerItem: \" + currentJob);\n }\n boolean result = item.poll(listener).hasChanges();\n logger.println(\"Done. Took \" + Util.getTimeSpanString(System.currentTimeMillis() - start));\n if (result) {\n logger.println(\"Changes found\");\n } else {\n logger.println(\"No changes\");\n }\n return result;\n } catch (Error e) {\n e.printStackTrace(listener.error(\"Failed to record SCM polling\"));\n LOGGER.error(\"Failed to record SCM polling\", e);\n throw e;\n } catch (RuntimeException e) {\n e.printStackTrace(listener.error(\"Failed to record SCM polling\"));\n LOGGER.error(\"Failed to record SCM polling\", e);\n throw e;\n } finally {\n listener.close();\n }\n } catch (IOException e) {\n LOGGER.error(\"Failed to record SCM polling\", e);\n }\n return false;\n }\n\n public void run() {\n if (runPolling()) {\n GitHubPushCause cause;\n try {\n cause = new GitHubPushCause(getLogFileForJob(currentJob), pushBy);\n } catch (IOException e) {\n LOGGER.warn(\"Failed to parse the polling log\", e);\n cause = new GitHubPushCause(pushBy);\n }\n\n if (asParameterizedJobMixIn(currentJob).scheduleBuild(cause)) {\n LOGGER.info(\"SCM changes detected in \" + currentJob.getFullName()\n + \". Triggering #\" + currentJob.getNextBuildNumber());\n } else {\n LOGGER.info(\"SCM changes detected in \" + currentJob.getFullName()\n + \". Job is already in the queue\");\n }\n }\n }\n });\n }\n\n /**\n * Returns the file that records the last/current polling activity.\n */\n public File getLogFile() {\n try {\n return getLogFileForJob(notNull(job, \"Job can't be null!\"));\n } catch (IOException ex) {\n throw new RuntimeException(ex);\n }\n }\n\n /**\n * Returns the file that records the last/current polling activity.\n */\n private File getLogFileForJob(@NonNull Job job) throws IOException {\n return new File(job.getRootDir(), \"github-polling.log\");\n }\n\n /**\n * @deprecated Use {@link GitHubRepositoryNameContributor#parseAssociatedNames(AbstractProject)}\n */\n @Deprecated\n public Set<GitHubRepositoryName> getGitHubRepositories() {\n return Collections.emptySet();\n }\n\n @Override\n public void start(Job<?, ?> project, boolean newInstance) {\n super.start(project, newInstance);\n if (newInstance && GitHubPlugin.configuration().isManageHooks()) {\n registerHooks();\n }\n }\n\n /**\n * Tries to register hook for current associated job.\n * Do this lazily to avoid blocking the UI thread.\n * Useful for using from groovy scripts.\n *\n * @since 1.11.2\n */\n public void registerHooks() {\n GitHubWebHook.get().registerHookFor(job);\n }\n\n @Override\n public void stop() {\n if (job == null) {\n return;\n }\n\n if (GitHubPlugin.configuration().isManageHooks()) {\n Cleaner cleaner = Cleaner.get();\n if (cleaner != null) {\n cleaner.onStop(job);\n }\n }\n }\n\n @Override\n public Collection<? extends Action> getProjectActions() {\n if (job == null) {\n return Collections.emptyList();\n }\n\n return Collections.singleton(new GitHubWebHookPollingAction());\n }\n\n @Override\n public DescriptorImpl getDescriptor() {\n return (DescriptorImpl) super.getDescriptor();\n }\n\n /**\n * Action object for {@link Project}. Used to display the polling log.\n */\n public final class GitHubWebHookPollingAction implements Action {\n public Job<?, ?> getOwner() {\n return job;\n }\n\n public String getIconFileName() {\n return \"clipboard.png\";\n }\n\n public String getDisplayName() {\n return \"GitHub Hook Log\";\n }\n\n public String getUrlName() {\n return \"GitHubPollLog\";\n }\n\n public String getLog() throws IOException {\n return Util.loadFile(getLogFileForJob(job));\n }\n\n /**\n * Writes the annotated log to the given output.\n *\n * @since 1.350\n */\n public void writeLogTo(XMLOutput out) throws IOException {\n new AnnotatedLargeText<GitHubWebHookPollingAction>(getLogFileForJob(job), Charsets.UTF_8, true, this)\n .writeHtmlTo(0, out.asWriter());\n }\n }\n\n @Extension\n @Symbol(\"githubPush\")\n public static class DescriptorImpl extends TriggerDescriptor {\n private final transient SequentialExecutionQueue queue =\n new SequentialExecutionQueue(Executors.newSingleThreadExecutor(threadFactory()));\n\n private transient String hookUrl;\n\n private transient List<Credential> credentials;\n\n @Inject\n private transient GitHubHookRegisterProblemMonitor monitor;\n\n @Inject\n private transient SCMTrigger.DescriptorImpl scmTrigger;\n\n private transient int maximumThreads = Integer.MIN_VALUE;\n\n public DescriptorImpl() {\n checkThreadPoolSizeAndUpdateIfNecessary();\n }\n\n /**\n * Update the {@link java.util.concurrent.ExecutorService} instance.\n */\n /*package*/\n synchronized void checkThreadPoolSizeAndUpdateIfNecessary() {\n if (scmTrigger != null) {\n int count = scmTrigger.getPollingThreadCount();\n if (maximumThreads != count) {\n maximumThreads = count;\n queue.setExecutors(\n (count == 0\n ? Executors.newCachedThreadPool(threadFactory())\n : Executors.newFixedThreadPool(maximumThreads, threadFactory())));\n }\n }\n }\n\n @Override\n public boolean isApplicable(Item item) {\n return item instanceof Job && SCMTriggerItems.asSCMTriggerItem(item) != null\n && item instanceof ParameterizedJobMixIn.ParameterizedJob;\n }\n\n @Override\n public String getDisplayName() {\n return \"GitHub hook trigger for GITScm polling\";\n }\n\n /**\n * True if Jenkins should auto-manage hooks.\n *\n * @deprecated Use {@link GitHubPluginConfig#isManageHooks()} instead\n */\n @Deprecated\n public boolean isManageHook() {\n return GitHubPlugin.configuration().isManageHooks();\n }\n\n /**\n * Returns the URL that GitHub should post.\n *\n * @deprecated use {@link GitHubPluginConfig#getHookUrl()} instead\n */\n @Deprecated\n public URL getHookUrl() throws GHPluginConfigException {\n return GitHubPlugin.configuration().getHookUrl();\n }\n\n /**\n * @return null after migration\n * @deprecated use {@link GitHubPluginConfig#getConfigs()} instead.\n */\n @Deprecated\n public List<Credential> getCredentials() {\n return credentials;\n }\n\n /**\n * Used only for migration\n *\n * @return null after migration\n * @deprecated use {@link GitHubPluginConfig#getHookUrl()}\n */\n @Deprecated\n public URL getDeprecatedHookUrl() {\n if (isEmpty(hookUrl)) {\n return null;\n }\n try {\n return new URL(hookUrl);\n } catch (MalformedURLException e) {\n LOGGER.warn(\"Malformed hook url skipped while migration ({})\", e.getMessage());\n return null;\n }\n }\n\n /**\n * Used to cleanup after migration\n */\n public void clearDeprecatedHookUrl() {\n this.hookUrl = null;\n }\n\n /**\n * Used to cleanup after migration\n */\n public void clearCredentials() {\n this.credentials = null;\n }\n\n /**\n * @deprecated use {@link GitHubPluginConfig#isOverrideHookUrl()}\n */\n @Deprecated\n public boolean hasOverrideURL() {\n return GitHubPlugin.configuration().isOverrideHookUrl();\n }\n\n /**\n * Uses global xstream to enable migration alias used in\n * {@link Migrator#enableCompatibilityAliases()}\n */\n @Override\n protected XmlFile getConfigFile() {\n return new XmlFile(Jenkins.XSTREAM2, super.getConfigFile().getFile());\n }\n\n public static DescriptorImpl get() {\n return Trigger.all().get(DescriptorImpl.class);\n }\n\n public static boolean allowsHookUrlOverride() {\n return ALLOW_HOOKURL_OVERRIDE;\n }\n\n private static ThreadFactory threadFactory() {\n return new NamingThreadFactory(Executors.defaultThreadFactory(), \"GitHubPushTrigger\");\n }\n\n /**\n * Checks that repo defined in this item is not in administrative monitor as failed to be registered.\n * If that so, shows warning with some instructions\n *\n * @param item - to check against. Should be not null and have at least one repo defined\n *\n * @return warning or empty string\n * @since 1.17.0\n */\n @SuppressWarnings(\"unused\")\n @Restricted(NoExternalUse.class) // invoked from Stapler\n public FormValidation doCheckHookRegistered(@AncestorInPath Item item) {\n Preconditions.checkNotNull(item, \"Item can't be null if wants to check hook in monitor\");\n\n if (!item.hasPermission(Item.CONFIGURE)) {\n return FormValidation.ok();\n }\n\n Collection<GitHubRepositoryName> repos = GitHubRepositoryNameContributor.parseAssociatedNames(item);\n\n for (GitHubRepositoryName repo : repos) {\n if (monitor.isProblemWith(repo)) {\n return FormValidation.warning(\n org.jenkinsci.plugins.github.Messages.github_trigger_check_method_warning_details(\n repo.getUserName(), repo.getRepositoryName(), repo.getHost()\n ));\n }\n }\n\n return FormValidation.ok();\n }\n }\n\n /**\n * Set to false to prevent the user from overriding the hook URL.\n */\n public static final boolean ALLOW_HOOKURL_OVERRIDE = !Boolean.getBoolean(\n GitHubPushTrigger.class.getName() + \".disableOverride\"\n );\n\n private static final Logger LOGGER = LoggerFactory.getLogger(GitHubPushTrigger.class);\n}",
"public class GitHubRepositoryName {\n\n private static final Logger LOGGER = LoggerFactory.getLogger(GitHubRepositoryName.class);\n\n private static final Pattern[] URL_PATTERNS = {\n /**\n * The first set of patterns extract the host, owner and repository names\n * from URLs that include a '.git' suffix, removing the suffix from the\n * repository name.\n */\n Pattern.compile(\".+@(.+):([^/]+)/([^/]+)\\\\.git(?:/)?\"),\n Pattern.compile(\"https?://[^/]+@([^/]+)/([^/]+)/([^/]+)\\\\.git(?:/)?\"),\n Pattern.compile(\"https?://([^/]+)/([^/]+)/([^/]+)\\\\.git(?:/)?\"),\n Pattern.compile(\"git://([^/]+)/([^/]+)/([^/]+)\\\\.git(?:/)?\"),\n Pattern.compile(\"(?:git\\\\+)?ssh://(?:.+@)?([^/]+)/([^/]+)/([^/]+)\\\\.git(?:/)?\"),\n /**\n * The second set of patterns extract the host, owner and repository names\n * from all other URLs. Note that these patterns must be processed *after*\n * the first set, to avoid any '.git' suffix that may be present being included\n * in the repository name.\n */\n Pattern.compile(\".+@(.+):([^/]+)/([^/]+)/?\"),\n Pattern.compile(\"https?://[^/]+@([^/]+)/([^/]+)/([^/]+)/?\"),\n Pattern.compile(\"https?://([^/]+)/([^/]+)/([^/]+)/?\"),\n Pattern.compile(\"git://([^/]+)/([^/]+)/([^/]+)/?\"),\n Pattern.compile(\"(?:git\\\\+)?ssh://(?:.+@)?([^/]+)/([^/]+)/([^/]+)/?\"),\n };\n\n /**\n * Create {@link GitHubRepositoryName} from URL\n *\n * @param url repo url. Can be null\n *\n * @return parsed {@link GitHubRepositoryName} or null if it cannot be parsed from the specified URL\n */\n @CheckForNull\n public static GitHubRepositoryName create(String url) {\n LOGGER.debug(\"Constructing from URL {}\", url);\n for (Pattern p : URL_PATTERNS) {\n Matcher m = p.matcher(trimToEmpty(url));\n if (m.matches()) {\n LOGGER.debug(\"URL matches {}\", m);\n GitHubRepositoryName ret = new GitHubRepositoryName(m.group(1), m.group(2), m.group(3));\n LOGGER.debug(\"Object is {}\", ret);\n return ret;\n }\n }\n LOGGER.debug(\"Could not match URL {}\", url);\n return null;\n }\n\n /**\n * @param projectProperty project property to extract url. Can be null\n *\n * @return parsed as {@link GitHubRepositoryName} object url to GitHub project\n * @see #create(String)\n * @since 1.14.1\n */\n @CheckForNull\n public static GitHubRepositoryName create(GithubProjectProperty projectProperty) {\n if (projectProperty == null) {\n return null;\n }\n\n return GitHubRepositoryName.create(projectProperty.getProjectUrlStr());\n }\n\n\n @SuppressWarnings(\"visibilitymodifier\")\n public final String host;\n @SuppressWarnings(\"visibilitymodifier\")\n public final String userName;\n @SuppressWarnings(\"visibilitymodifier\")\n public final String repositoryName;\n\n public GitHubRepositoryName(String host, String userName, String repositoryName) {\n this.host = host;\n this.userName = userName;\n this.repositoryName = repositoryName;\n }\n\n public String getHost() {\n return host;\n }\n\n public String getUserName() {\n return userName;\n }\n\n public String getRepositoryName() {\n return repositoryName;\n }\n\n /**\n * Resolves this name to the actual reference by {@link GHRepository}\n *\n * Shortcut for {@link #resolve(Predicate)} with always true predicate\n * ({@link Predicates#alwaysTrue()}) as argument\n */\n public Iterable<GHRepository> resolve() {\n return resolve(Predicates.<GitHubServerConfig>alwaysTrue());\n }\n\n /**\n * Resolves this name to the actual reference by {@link GHRepository}.\n *\n * Since the system can store multiple credentials,\n * and only some of them might be able to see this name in question,\n * this method uses {@link org.jenkinsci.plugins.github.config.GitHubPluginConfig#findGithubConfig(Predicate)}\n * and attempt to find the right credential that can\n * access this repository.\n *\n * Any predicate as argument will be combined with {@link GitHubServerConfig#withHost(String)} to find only\n * corresponding for this repo name authenticated github repository\n *\n * This method walks multiple repositories for each credential that can access the repository. Depending on\n * what you are trying to do with the repository, you might have to keep trying until a {@link GHRepository}\n * with suitable permission is returned.\n *\n * @param predicate helps to filter only useful for resolve {@link GitHubServerConfig}s\n *\n * @return iterable with lazy login process for getting authenticated repos\n * @since 1.13.0\n */\n public Iterable<GHRepository> resolve(Predicate<GitHubServerConfig> predicate) {\n return from(GitHubPlugin.configuration().findGithubConfig(and(withHost(host), predicate)))\n .transform(toGHRepository(this))\n .filter(notNull());\n }\n\n /**\n * Variation of {@link #resolve()} method that just returns the first valid repository object.\n *\n * This is useful if the caller only relies on the read access to the repository and doesn't need to\n * walk possible candidates.\n */\n @CheckForNull\n public GHRepository resolveOne() {\n return from(resolve()).first().orNull();\n }\n\n /**\n * Does this repository match the repository referenced in the given {@link GHCommitPointer}?\n */\n public boolean matches(GHCommitPointer commit) {\n final GHUser user;\n try {\n user = commit.getUser();\n } catch (IOException ex) {\n LOGGER.debug(\"Failed to extract user from commit \" + commit, ex);\n return false;\n }\n\n return userName.equals(user.getLogin())\n && repositoryName.equals(commit.getRepository().getName())\n && host.equals(commit.getRepository().getHtmlUrl().getHost());\n }\n\n /**\n * Does this repository match the repository referenced in the given {@link GHCommitPointer}?\n */\n public boolean matches(GHRepository repo) throws IOException {\n return userName.equals(repo.getOwner().getLogin()) // TODO: use getOwnerName\n && repositoryName.equals(repo.getName())\n && host.equals(repo.getHtmlUrl().getHost());\n }\n\n @Override\n public boolean equals(Object obj) {\n return EqualsBuilder.reflectionEquals(this, obj);\n }\n\n @Override\n public int hashCode() {\n return new HashCodeBuilder().append(host).append(userName).append(repositoryName).build();\n }\n\n @Override\n public String toString() {\n return new ToStringBuilder(this, SHORT_PREFIX_STYLE)\n .append(\"host\", host).append(\"username\", userName).append(\"repository\", repositoryName).build();\n }\n\n private static Function<GitHub, GHRepository> toGHRepository(final GitHubRepositoryName repoName) {\n return new NullSafeFunction<GitHub, GHRepository>() {\n @Override\n protected GHRepository applyNullSafe(@NonNull GitHub gitHub) {\n try {\n return gitHub.getRepository(format(\"%s/%s\", repoName.getUserName(), repoName.getRepositoryName()));\n } catch (IOException e) {\n LOGGER.warn(\"Failed to obtain repository {}\", this, e);\n return null;\n }\n }\n };\n }\n}",
"public class GitHubPlugin extends Plugin {\n /**\n * Launched before plugin starts\n * Adds alias for {@link GitHubPlugin} to simplify resulting xml.\n */\n public static void addXStreamAliases() {\n Migrator.enableCompatibilityAliases();\n Migrator.enableAliases();\n }\n\n /**\n * Launches migration after all extensions have been augmented as we need to ensure that the credentials plugin\n * has been initialized.\n * We need ensure that migrator will run after xstream aliases will be added.\n * @see <a href=\"https://issues.jenkins-ci.org/browse/JENKINS-36446\">JENKINS-36446</a>\n */\n @Initializer(after = InitMilestone.EXTENSIONS_AUGMENTED, before = InitMilestone.JOB_LOADED)\n public static void runMigrator() throws Exception {\n new Migrator().migrate();\n }\n\n @Override\n public void start() throws Exception {\n addXStreamAliases();\n }\n\n /**\n * Shortcut method for getting instance of {@link GitHubPluginConfig}.\n *\n * @return configuration of plugin\n */\n @NonNull\n public static GitHubPluginConfig configuration() {\n return defaultIfNull(\n GitHubPluginConfig.all().get(GitHubPluginConfig.class),\n GitHubPluginConfig.EMPTY_CONFIG\n );\n }\n}",
"public class GitHubServerConfig extends AbstractDescribableImpl<GitHubServerConfig> {\n private static final Logger LOGGER = LoggerFactory.getLogger(GitHubServerConfig.class);\n\n /**\n * Common prefixes that we should remove when inferring a {@link #name}.\n *\n * @since 1.28.0\n */\n private static final String[] COMMON_PREFIX_HOSTNAMES = {\n \"git.\",\n \"github.\",\n \"vcs.\",\n \"scm.\",\n \"source.\"\n };\n /**\n * Because of {@link GitHub} hide this const from external use we need to store it here\n */\n public static final String GITHUB_URL = \"https://api.github.com\";\n\n /**\n * The name to display for the public GitHub service.\n *\n * @since 1.28.0\n */\n private static final String PUBLIC_GITHUB_NAME = \"GitHub\";\n\n /**\n * Used as default token value if no any creds found by given credsId.\n */\n private static final String UNKNOWN_TOKEN = \"UNKNOWN_TOKEN\";\n /**\n * Default value in MB for client cache size\n *\n * @see #getClientCacheSize()\n */\n public static final int DEFAULT_CLIENT_CACHE_SIZE_MB = 20;\n\n /**\n * The optional display name of this server.\n */\n @CheckForNull\n private String name;\n private String apiUrl = GITHUB_URL;\n private boolean manageHooks = true;\n private final String credentialsId;\n\n /**\n * @see #getClientCacheSize()\n * @see #setClientCacheSize(int)\n */\n private int clientCacheSize = DEFAULT_CLIENT_CACHE_SIZE_MB;\n\n /**\n * To avoid creation of new one on every login with this config\n */\n private transient GitHub cachedClient;\n\n @DataBoundConstructor\n public GitHubServerConfig(String credentialsId) {\n this.credentialsId = credentialsId;\n }\n\n /**\n * Sets the optional display name.\n * @param name the optional display name.\n */\n @DataBoundSetter\n public void setName(@CheckForNull String name) {\n this.name = Util.fixEmptyAndTrim(name);\n }\n\n /**\n * Set the API endpoint.\n *\n * @param apiUrl custom url if GH. Default value will be used in case of custom is unchecked or value is blank\n */\n @DataBoundSetter\n public void setApiUrl(String apiUrl) {\n this.apiUrl = defaultIfBlank(apiUrl, GITHUB_URL);\n }\n\n /**\n * This server config will be used to manage GH Hooks if true\n *\n * @param manageHooks false to ignore this config on hook auto-management\n */\n @DataBoundSetter\n public void setManageHooks(boolean manageHooks) {\n this.manageHooks = manageHooks;\n }\n\n /**\n * This method was introduced to hide custom api url under checkbox, but now UI simplified to show url all the time\n * see jenkinsci/github-plugin/pull/112 for more details\n *\n * @param customApiUrl ignored\n *\n * @deprecated simply remove usage of this method, it ignored now. Should be removed after 20 sep 2016.\n */\n @Deprecated\n public void setCustomApiUrl(boolean customApiUrl) {\n }\n\n /**\n * Gets the optional display name of this server.\n *\n * @return the optional display name of this server, may be empty or {@code null} but best effort is made to ensure\n * that it has some meaningful text.\n * @since 1.28.0\n */\n public String getName() {\n return name;\n }\n\n /**\n * Gets the formatted display name (which will always include the api url)\n *\n * @return the formatted display name.\n * @since 1.28.0\n */\n public String getDisplayName() {\n String gitHubName = getName();\n boolean isGitHubCom = StringUtils.isBlank(apiUrl) || GITHUB_URL.equals(apiUrl);\n if (StringUtils.isBlank(gitHubName)) {\n gitHubName = isGitHubCom ? PUBLIC_GITHUB_NAME : SCMName.fromUrl(apiUrl, COMMON_PREFIX_HOSTNAMES);\n }\n String gitHubUrl = isGitHubCom ? \"https://github.com\" : StringUtils.removeEnd(apiUrl, \"/api/v3\");\n return StringUtils.isBlank(gitHubName)\n ? gitHubUrl\n : Messages.GitHubServerConfig_displayName(gitHubName, gitHubUrl);\n }\n\n public String getApiUrl() {\n return apiUrl;\n }\n\n public boolean isManageHooks() {\n return manageHooks;\n }\n\n public String getCredentialsId() {\n return credentialsId;\n }\n\n /**\n * Capacity of cache for GitHub client in MB.\n *\n * Defaults to 20 MB\n *\n * @since 1.14.0\n */\n public int getClientCacheSize() {\n return clientCacheSize;\n }\n\n /**\n * @param clientCacheSize capacity of cache for GitHub client in MB, set to <= 0 to turn off this feature\n */\n @DataBoundSetter\n public void setClientCacheSize(int clientCacheSize) {\n this.clientCacheSize = clientCacheSize;\n }\n\n /**\n * @return cached GH client or null\n */\n protected synchronized GitHub getCachedClient() {\n return cachedClient;\n }\n\n /**\n * Used by {@link org.jenkinsci.plugins.github.config.GitHubServerConfig.ClientCacheFunction}\n *\n * @param cachedClient updated client. Maybe null to invalidate cache\n */\n protected synchronized void setCachedClient(GitHub cachedClient) {\n this.cachedClient = cachedClient;\n }\n\n /**\n * Checks GH url for equality to default api url\n *\n * @param apiUrl should be not blank and not equal to default url to return true\n *\n * @return true if url not blank and not equal to default\n */\n public static boolean isUrlCustom(String apiUrl) {\n return isNotBlank(apiUrl) && !GITHUB_URL.equals(apiUrl);\n }\n\n /**\n * Converts server config to authorized GH instance. If login process is not successful it returns null\n *\n * @return function to convert config to gh instance\n * @see org.jenkinsci.plugins.github.config.GitHubServerConfig.ClientCacheFunction\n */\n @CheckForNull\n public static Function<GitHubServerConfig, GitHub> loginToGithub() {\n return new ClientCacheFunction();\n }\n\n /**\n * Extracts token from secret found by {@link #secretFor(String)}\n * Returns {@link #UNKNOWN_TOKEN} if no any creds secret found with this id.\n *\n * @param credentialsId id to find creds\n *\n * @return token from creds or default non empty string\n */\n @NonNull\n public static String tokenFor(String credentialsId) {\n return secretFor(credentialsId).or(new Supplier<Secret>() {\n @Override\n public Secret get() {\n return Secret.fromString(UNKNOWN_TOKEN);\n }\n }).getPlainText();\n }\n\n /**\n * Tries to find {@link StringCredentials} by id and returns secret from it.\n *\n * @param credentialsId id to find creds\n *\n * @return secret from creds or empty optional\n */\n @NonNull\n public static Optional<Secret> secretFor(String credentialsId) {\n List<StringCredentials> creds = filter(\n lookupCredentials(StringCredentials.class,\n Jenkins.getInstance(), ACL.SYSTEM,\n Collections.<DomainRequirement>emptyList()),\n withId(trimToEmpty(credentialsId))\n );\n\n return FluentIterableWrapper.from(creds)\n .transform(new NullSafeFunction<StringCredentials, Secret>() {\n @Override\n protected Secret applyNullSafe(@NonNull StringCredentials input) {\n return input.getSecret();\n }\n }).first();\n }\n\n /**\n * Returns true if given host is part of stored (or default if blank) api url\n *\n * For example:\n * withHost(api.github.com).apply(config for ~empty~) = true\n * withHost(api.github.com).apply(config for api.github.com) = true\n * withHost(api.github.com).apply(config for github.company.com) = false\n *\n * @param host host to find in api url\n *\n * @return predicate to match against {@link GitHubServerConfig}\n */\n public static Predicate<GitHubServerConfig> withHost(final String host) {\n return new NullSafePredicate<GitHubServerConfig>() {\n @Override\n protected boolean applyNullSafe(@NonNull GitHubServerConfig github) {\n return defaultIfEmpty(github.getApiUrl(), GITHUB_URL).contains(host);\n }\n };\n }\n\n /**\n * Returns true if config can be used in hooks managing\n *\n * @return predicate to match against {@link GitHubServerConfig}\n */\n public static Predicate<GitHubServerConfig> allowedToManageHooks() {\n return new NullSafePredicate<GitHubServerConfig>() {\n @Override\n protected boolean applyNullSafe(@NonNull GitHubServerConfig github) {\n return github.isManageHooks();\n }\n };\n }\n\n @Extension\n public static class DescriptorImpl extends Descriptor<GitHubServerConfig> {\n\n @Override\n public String getDisplayName() {\n return \"GitHub Server\";\n }\n\n @SuppressWarnings(\"unused\")\n public ListBoxModel doFillCredentialsIdItems(@QueryParameter String apiUrl,\n @QueryParameter String credentialsId) {\n if (!Jenkins.getInstance().hasPermission(Jenkins.ADMINISTER)) {\n return new StandardListBoxModel().includeCurrentValue(credentialsId);\n }\n return new StandardListBoxModel()\n .includeEmptyValue()\n .includeMatchingAs(ACL.SYSTEM,\n Jenkins.getInstance(),\n StringCredentials.class,\n fromUri(defaultIfBlank(apiUrl, GITHUB_URL)).build(),\n CredentialsMatchers.always()\n );\n }\n\n @RequirePOST\n @Restricted(DoNotUse.class) // WebOnly\n @SuppressWarnings(\"unused\")\n public FormValidation doVerifyCredentials(\n @QueryParameter String apiUrl,\n @QueryParameter String credentialsId) throws IOException {\n Jenkins.getActiveInstance().checkPermission(Jenkins.ADMINISTER);\n\n GitHubServerConfig config = new GitHubServerConfig(credentialsId);\n config.setApiUrl(apiUrl);\n config.setClientCacheSize(0);\n GitHub gitHub = new GitHubLoginFunction().apply(config);\n\n try {\n if (gitHub != null && gitHub.isCredentialValid()) {\n return FormValidation.ok(\"Credentials verified for user %s, rate limit: %s\",\n gitHub.getMyself().getLogin(), gitHub.getRateLimit().remaining);\n } else {\n return FormValidation.error(\"Failed to validate the account\");\n }\n } catch (IOException e) {\n return FormValidation.error(e, \"Failed to validate the account\");\n }\n }\n\n @SuppressWarnings(\"unused\")\n public FormValidation doCheckApiUrl(@QueryParameter String value) {\n try {\n new URL(value);\n } catch (MalformedURLException e) {\n return FormValidation.error(\"Malformed GitHub url (%s)\", e.getMessage());\n }\n\n if (GITHUB_URL.equals(value)) {\n return FormValidation.ok();\n }\n\n if (value.endsWith(\"/api/v3\") || value.endsWith(\"/api/v3/\")) {\n return FormValidation.ok();\n }\n\n return FormValidation.warning(\"GitHub Enterprise API URL ends with \\\"/api/v3\\\"\");\n }\n }\n\n /**\n * Function to get authorized GH client and cache it in config\n * has {@link #loginToGithub()} static factory\n */\n private static class ClientCacheFunction extends NullSafeFunction<GitHubServerConfig, GitHub> {\n @Override\n protected GitHub applyNullSafe(@NonNull GitHubServerConfig github) {\n if (github.getCachedClient() == null) {\n github.setCachedClient(new GitHubLoginFunction().apply(github));\n }\n return github.getCachedClient();\n }\n }\n}",
"public static void storeSecretIn(GitHubPluginConfig config, final String secretText) {\n final StringCredentialsImpl credentials = new StringCredentialsImpl(\n CredentialsScope.GLOBAL,\n UUID.randomUUID().toString(),\n null,\n Secret.fromString(secretText)\n );\n\n ACL.impersonate(ACL.SYSTEM, new Runnable() {\n @Override\n public void run() {\n try {\n new SystemCredentialsProvider.StoreImpl().addCredentials(\n Domain.global(),\n credentials\n );\n\n } catch (IOException e) {\n LOGGER.error(\"Unable to set hook secret\", e);\n }\n }\n });\n\n config.setHookSecretConfigs(Collections.singletonList(new HookSecretConfig(credentials.getId())));\n}",
"public static WebhookManager forHookUrl(URL endpoint) {\n return new WebhookManager(endpoint);\n}"
] | import com.cloudbees.jenkins.GitHubPushTrigger;
import com.cloudbees.jenkins.GitHubRepositoryName;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import hudson.model.FreeStyleProject;
import hudson.model.Item;
import hudson.plugins.git.GitSCM;
import org.jenkinsci.plugins.github.GitHubPlugin;
import org.jenkinsci.plugins.github.config.GitHubServerConfig;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.jvnet.hudson.test.Issue;
import org.jvnet.hudson.test.JenkinsRule;
import org.jvnet.hudson.test.WithoutJenkins;
import org.kohsuke.github.GHEvent;
import org.kohsuke.github.GHHook;
import org.kohsuke.github.GHRepository;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.runners.MockitoJUnitRunner;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collections;
import java.util.EnumSet;
import java.util.Map;
import static com.google.common.collect.ImmutableList.copyOf;
import static com.google.common.collect.Lists.asList;
import static com.google.common.collect.Lists.newArrayList;
import static org.hamcrest.Matchers.hasEntry;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import static org.jenkinsci.plugins.github.test.HookSecretHelper.storeSecretIn;
import static org.jenkinsci.plugins.github.webhook.WebhookManager.forHookUrl;
import static org.junit.Assert.assertThat;
import static org.kohsuke.github.GHEvent.CREATE;
import static org.kohsuke.github.GHEvent.PULL_REQUEST;
import static org.kohsuke.github.GHEvent.PUSH;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyBoolean;
import static org.mockito.Matchers.anyListOf;
import static org.mockito.Matchers.anySetOf;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.argThat;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; |
verify(manager, times(1)).serviceWebhookFor(HOOK_ENDPOINT);
verify(manager, never()).webhookFor(HOOK_ENDPOINT);
verify(manager, times(1)).fetchHooks();
}
@Test
@WithoutJenkins
public void shouldMatchAdminAccessWhenTrue() throws Exception {
when(repo.hasAdminAccess()).thenReturn(true);
assertThat("has admin access", manager.withAdminAccess().apply(repo), is(true));
}
@Test
@WithoutJenkins
public void shouldMatchAdminAccessWhenFalse() throws Exception {
when(repo.hasAdminAccess()).thenReturn(false);
assertThat("has no admin access", manager.withAdminAccess().apply(repo), is(false));
}
@Test
@WithoutJenkins
public void shouldMatchWebHook() {
when(repo.hasAdminAccess()).thenReturn(false);
GHHook hook = hook(HOOK_ENDPOINT, PUSH);
assertThat("webhook has web name and url prop", manager.webhookFor(HOOK_ENDPOINT).apply(hook), is(true));
}
@Test
@WithoutJenkins
public void shouldNotMatchOtherUrlWebHook() {
when(repo.hasAdminAccess()).thenReturn(false);
GHHook hook = hook(ANOTHER_HOOK_ENDPOINT, PUSH);
assertThat("webhook has web name and another url prop",
manager.webhookFor(HOOK_ENDPOINT).apply(hook), is(false));
}
@Test
public void shouldMergeEventsOnRegisterNewAndDeleteOldOnes() throws IOException {
doReturn(newArrayList(repo)).when(nonactive).resolve(any(Predicate.class));
when(repo.hasAdminAccess()).thenReturn(true);
Predicate<GHHook> del = spy(Predicate.class);
when(manager.deleteWebhook()).thenReturn(del);
GHHook hook = hook(HOOK_ENDPOINT, CREATE);
GHHook prhook = hook(HOOK_ENDPOINT, PULL_REQUEST);
when(repo.getHooks()).thenReturn(newArrayList(hook, prhook));
manager.createHookSubscribedTo(copyOf(newArrayList(PUSH))).apply(nonactive);
verify(del, times(2)).apply(any(GHHook.class));
verify(manager).createWebhook(HOOK_ENDPOINT, EnumSet.copyOf(newArrayList(CREATE, PULL_REQUEST, PUSH)));
}
@Test
public void shouldNotReplaceAlreadyRegisteredHook() throws IOException {
doReturn(newArrayList(repo)).when(nonactive).resolve(any(Predicate.class));
when(repo.hasAdminAccess()).thenReturn(true);
GHHook hook = hook(HOOK_ENDPOINT, PUSH);
when(repo.getHooks()).thenReturn(newArrayList(hook));
manager.createHookSubscribedTo(copyOf(newArrayList(PUSH))).apply(nonactive);
verify(manager, never()).deleteWebhook();
verify(manager, never()).createWebhook(any(URL.class), anySetOf(GHEvent.class));
}
@Test
@Issue( "JENKINS-62116" )
public void shouldNotReplaceAlreadyRegisteredHookWithMoreEvents() throws IOException {
doReturn(newArrayList(repo)).when(nonactive).resolve(any(Predicate.class));
when(repo.hasAdminAccess()).thenReturn(true);
GHHook hook = hook(HOOK_ENDPOINT, PUSH, CREATE);
when(repo.getHooks()).thenReturn(newArrayList(hook));
manager.createHookSubscribedTo(copyOf(newArrayList(PUSH))).apply(nonactive);
verify(manager, never()).deleteWebhook();
verify(manager, never()).createWebhook(any(URL.class), anySetOf(GHEvent.class));
}
@Test
public void shouldNotAddPushEventByDefaultForProjectWithoutTrigger() throws IOException {
FreeStyleProject project = jenkins.createFreeStyleProject();
project.setScm(GIT_SCM);
manager.registerFor((Item)project).run();
verify(manager, never()).createHookSubscribedTo(anyListOf(GHEvent.class));
}
@Test
public void shouldAddPushEventByDefault() throws IOException {
FreeStyleProject project = jenkins.createFreeStyleProject();
project.addTrigger(new GitHubPushTrigger());
project.setScm(GIT_SCM);
manager.registerFor((Item)project).run();
verify(manager).createHookSubscribedTo(newArrayList(PUSH));
}
@Test
public void shouldReturnNullOnGettingEmptyEventsListToSubscribe() throws IOException {
doReturn(newArrayList(repo)).when(active).resolve(any(Predicate.class));
when(repo.hasAdminAccess()).thenReturn(true);
assertThat("empty events list not allowed to be registered",
forHookUrl(HOOK_ENDPOINT)
.createHookSubscribedTo(Collections.<GHEvent>emptyList()).apply(active), nullValue());
}
@Test
public void shouldSelectOnlyHookManagedCreds() {
GitHubServerConfig conf = new GitHubServerConfig("");
conf.setManageHooks(false); | GitHubPlugin.configuration().getConfigs().add(conf); | 2 |
legobmw99/Allomancy | src/main/java/com/legobmw99/allomancy/modules/powers/PowersSetup.java | [
"public class ClientEventHandler {\n\n\n private final Minecraft mc = Minecraft.getInstance();\n\n private final Set<Entity> metal_entities = new HashSet<>();\n private final Set<MetalBlockBlob> metal_blobs = new HashSet<>();\n private final Set<Player> nearby_allomancers = new HashSet<>();\n\n private int tickOffset = 0;\n\n @OnlyIn(Dist.CLIENT)\n @SubscribeEvent\n public void onClientTick(final TickEvent.ClientTickEvent event) {\n // Run once per tick, only if in game, and only if there is a player\n if (event.phase == TickEvent.Phase.END && !this.mc.isPaused() && this.mc.player != null && this.mc.player.isAlive()) {\n\n Player player = this.mc.player;\n player.getCapability(AllomancerCapability.PLAYER_CAP).ifPresent(data -> {\n if (!data.isUninvested()) {\n // Duralumin makes you move much quicker and reach much further\n int force_multiplier = data.isEnhanced() ? 4 : 1;\n int dist_modifier = data.isEnhanced() ? 2 : 1;\n\n // Handle our input-based powers\n if (this.mc.options.keyAttack.isDown()) {\n // Ray trace 20 blocks (or 40 if enhanced)\n var trace = ClientUtils.getMouseOverExtended(20F * dist_modifier);\n // All iron pulling powers\n if (data.isBurning(Metal.IRON)) {\n if (trace != null) {\n if (trace.getType() == HitResult.Type.ENTITY && PowerUtils.isEntityMetal(((EntityHitResult) trace).getEntity())) {\n Network.sendToServer(new TryPushPullEntity(((EntityHitResult) trace).getEntity().getId(), PowerUtils.PULL * force_multiplier));\n }\n\n if (trace.getType() == HitResult.Type.BLOCK) {\n BlockPos bp = ((BlockHitResult) trace).getBlockPos();\n if (PowerUtils.isBlockStateMetal(this.mc.level.getBlockState(bp)) ||\n (player.getMainHandItem().getItem() == CombatSetup.COIN_BAG.get() && player.isCrouching())) {\n Network.sendToServer(new TryPushPullBlock(bp, PowerUtils.PULL * force_multiplier));\n }\n }\n }\n }\n // All zinc powers\n if (data.isBurning(Metal.ZINC)) {\n Entity entity;\n if ((trace != null) && (trace.getType() == HitResult.Type.ENTITY)) {\n entity = ((EntityHitResult) trace).getEntity();\n if (entity instanceof PathfinderMob) {\n Network.sendToServer(new ChangeEmotionPacket(entity.getId(), true));\n }\n }\n }\n }\n if (this.mc.options.keyUse.isDown()) {\n // Ray trace 20 blocks (or 40 if enhanced)\n var trace = ClientUtils.getMouseOverExtended(20F * dist_modifier);\n // All steel pushing powers\n if (data.isBurning(Metal.STEEL)) {\n\n if (trace != null) {\n if (trace.getType() == HitResult.Type.ENTITY && PowerUtils.isEntityMetal(((EntityHitResult) trace).getEntity())) {\n Network.sendToServer(new TryPushPullEntity(((EntityHitResult) trace).getEntity().getId(), PowerUtils.PUSH * force_multiplier));\n }\n\n if (trace.getType() == HitResult.Type.BLOCK) {\n BlockPos bp = ((BlockHitResult) trace).getBlockPos();\n if (PowerUtils.isBlockStateMetal(this.mc.level.getBlockState(bp)) ||\n (player.getMainHandItem().getItem() == CombatSetup.COIN_BAG.get() && player.isCrouching())) {\n Network.sendToServer(new TryPushPullBlock(bp, PowerUtils.PUSH * force_multiplier));\n }\n }\n }\n }\n // All brass powers\n if (data.isBurning(Metal.BRASS)) {\n Entity entity;\n if ((trace != null) && (trace.getType() == HitResult.Type.ENTITY)) {\n entity = ((EntityHitResult) trace).getEntity();\n if (entity instanceof PathfinderMob) {\n Network.sendToServer(new ChangeEmotionPacket(entity.getId(), false));\n }\n }\n }\n\n if (data.isBurning(Metal.NICROSIL)) {\n if ((trace != null) && (trace.getType() == HitResult.Type.ENTITY)) {\n Entity entity = ((EntityHitResult) trace).getEntity();\n if (entity instanceof Player) {\n Network.sendToServer(new UpdateEnhancedPacket(true, entity.getId()));\n }\n }\n }\n }\n\n this.tickOffset = (this.tickOffset + 1) % 2;\n\n if (this.tickOffset == 0) {\n // Populate the metal lists\n this.metal_blobs.clear();\n this.metal_entities.clear();\n if (data.isBurning(Metal.IRON) || data.isBurning(Metal.STEEL)) {\n int max = PowersConfig.max_metal_detection.get();\n BlockPos negative = player.blockPosition().offset(-max, -max, -max);\n BlockPos positive = player.blockPosition().offset(max, max, max);\n\n // Add metal entities to metal list\n this.metal_entities.addAll(\n player.level.getEntitiesOfClass(Entity.class, new AABB(negative, positive), e -> PowerUtils.isEntityMetal(e) && !e.equals(player)));\n\n // Add metal blobs to metal list\n var blocks = BlockPos.betweenClosedStream(negative, positive);\n blocks.filter(bp -> PowerUtils.isBlockStateMetal(player.level.getBlockState(bp))).forEach(bp -> {\n var matches = this.metal_blobs.stream().filter(mbl -> mbl.isMatch(bp)).collect(Collectors.toSet());\n switch (matches.size()) {\n case 0 -> // new blob\n this.metal_blobs.add(new MetalBlockBlob(bp));\n case 1 -> // add to existing blob\n matches.stream().findAny().get().add(bp);\n default -> { // this block serves as a bridge between (possibly many) existing blobs\n this.metal_blobs.removeAll(matches);\n MetalBlockBlob mbb = matches.stream().reduce(null, MetalBlockBlob::merge);\n mbb.add(bp);\n this.metal_blobs.add(mbb);\n }\n }\n\n });\n\n }\n // Populate our list of nearby allomancy users\n this.nearby_allomancers.clear();\n if (data.isBurning(Metal.BRONZE) && (data.isEnhanced() || !data.isBurning(Metal.COPPER))) {\n // Add metal burners to a list\n BlockPos negative = player.blockPosition().offset(-30, -30, -30);\n BlockPos positive = player.blockPosition().offset(30, 30, 30);\n var nearby_players = player.level.getEntitiesOfClass(Player.class, new AABB(negative, positive), entity -> entity != null && entity != player);\n\n\n for (Player otherPlayer : nearby_players) {\n\n boolean cont = otherPlayer.getCapability(AllomancerCapability.PLAYER_CAP).map(otherData -> {\n if (otherData.isBurning(Metal.COPPER) && (!data.isEnhanced() || otherData.isEnhanced())) {\n return false;\n }\n for (Metal mt : Metal.values()) {\n if (otherData.isBurning(mt)) {\n this.nearby_allomancers.add(otherPlayer);\n break;\n }\n }\n return true;\n }).orElse(true);\n\n if (!cont) {\n break;\n }\n }\n }\n }\n }\n });\n }\n }\n\n\n @OnlyIn(Dist.CLIENT)\n @SubscribeEvent\n public void onKeyInput(final InputEvent.KeyInputEvent event) {\n if (event.getAction() == GLFW.GLFW_PRESS) {\n acceptInput();\n }\n }\n\n @OnlyIn(Dist.CLIENT)\n @SubscribeEvent\n public void onMouseInput(final InputEvent.MouseInputEvent event) {\n if (event.getAction() == GLFW.GLFW_PRESS) {\n acceptInput();\n }\n }\n\n /**\n * Handles either mouse or button presses for the mod's keybinds\n */\n private void acceptInput() {\n\n boolean extras = PowersClientSetup.enable_more_keybinds && Arrays.stream(PowersClientSetup.powers).anyMatch(KeyMapping::isDown);\n\n if (PowersClientSetup.burn.isDown() || extras) {\n Player player = this.mc.player;\n if (this.mc.screen == null) {\n if (player == null || !this.mc.isWindowActive()) {\n return;\n }\n\n player.getCapability(AllomancerCapability.PLAYER_CAP).ifPresent(data -> {\n if (extras) { // try one of the extra keybinds\n for (int i = 0; i < PowersClientSetup.powers.length; i++) {\n if (PowersClientSetup.powers[i].isDown()) {\n ClientUtils.toggleBurn(Metal.getMetal(i), data);\n }\n }\n\n } else { // normal keypress\n\n int num_powers = data.getPowerCount();\n\n if (num_powers == 0) {\n return;\n } else if (num_powers == 1) {\n ClientUtils.toggleBurn(data.getPowers()[0], data);\n } else {\n this.mc.setScreen(new MetalSelectScreen());\n }\n }\n });\n }\n\n }\n\n if (PowersClientSetup.hud.isDown()) {\n PowersConfig.enable_overlay.set(!PowersConfig.enable_overlay.get());\n }\n\n }\n\n @OnlyIn(Dist.CLIENT)\n @SubscribeEvent\n public void onRenderGameOverlay(RenderGameOverlayEvent event) {\n\n if (!PowersConfig.enable_overlay.get() && !(this.mc.screen instanceof MetalSelectScreen)) {\n return;\n }\n if (event.isCancelable() || event.getType() != ElementType.LAYER) {\n return;\n }\n if (!this.mc.isWindowActive() || !this.mc.player.isAlive()) {\n return;\n }\n if (this.mc.screen != null && !(this.mc.screen instanceof ChatScreen) && !(this.mc.screen instanceof MetalSelectScreen)) {\n return;\n }\n\n MetalOverlay.drawMetalOverlay(event.getMatrixStack());\n }\n\n @OnlyIn(Dist.CLIENT)\n @SubscribeEvent\n public void onRenderWorldLast(RenderLevelLastEvent event) {\n\n Player player = this.mc.player;\n if (player == null || !player.isAlive() || this.mc.options.getCameraType().isMirrored()) {\n return;\n }\n\n player.getCapability(AllomancerCapability.PLAYER_CAP).ifPresent(data -> {\n\n if (data.isUninvested()) {\n return;\n }\n RenderSystem.setShader(GameRenderer::getRendertypeLinesShader);\n RenderSystem.disableTexture();\n RenderSystem.disableDepthTest();\n RenderSystem.depthMask(false);\n RenderSystem.disableCull();\n RenderSystem.enableBlend();\n RenderSystem.disablePolygonOffset();\n RenderSystem.defaultBlendFunc();\n\n\n PoseStack stack = event.getPoseStack();\n stack.pushPose();\n Vec3 view = this.mc.cameraEntity.getEyePosition(event.getPartialTick());\n stack.translate(-view.x, -view.y, -view.z);\n RenderSystem.applyModelViewMatrix();\n\n double rho = 1;\n float theta = (float) ((this.mc.player.getViewYRot(event.getPartialTick()) + 90) * Math.PI / 180);\n float phi = Mth.clamp((float) ((this.mc.player.getViewXRot(event.getPartialTick()) + 90) * Math.PI / 180), 0.0001F, 3.14F);\n\n\n Vec3 playervec = view.add(rho * Mth.sin(phi) * Mth.cos(theta), rho * Mth.cos(phi) - 0.35F, rho * Mth.sin(phi) * Mth.sin(theta));\n\n /*********************************************\n * IRON AND STEEL LINES *\n *********************************************/\n\n\n if ((data.isBurning(Metal.IRON) || data.isBurning(Metal.STEEL))) {\n for (Entity entity : this.metal_entities) {\n ClientUtils.drawMetalLine(stack, playervec, entity.position(), 1.5F, 0F, 0.6F, 1F);\n }\n\n for (MetalBlockBlob mb : this.metal_blobs) {\n ClientUtils.drawMetalLine(stack, playervec, mb.getCenter(), Mth.clamp(0.3F + mb.size() * 0.4F, 0.5F, 7.5F), 0F, 0.6F, 1F);\n }\n }\n\n /*********************************************\n * BRONZE LINES *\n *********************************************/\n if ((data.isBurning(Metal.BRONZE) && (data.isEnhanced() || !data.isBurning(Metal.COPPER)))) {\n for (Player playerEntity : this.nearby_allomancers) {\n ClientUtils.drawMetalLine(stack, playervec, playerEntity.position(), 5.0F, 0.7F, 0.15F, 0.15F);\n }\n }\n\n /*********************************************\n * GOLD AND ELECTRUM LINES *\n *********************************************/\n if (data.isBurning(Metal.GOLD)) {\n ResourceKey<Level> deathDim = data.getDeathDim();\n if (deathDim != null && player.level.dimension() == deathDim) {\n ClientUtils.drawMetalLine(stack, playervec, Vec3.atCenterOf(data.getDeathLoc()), 3.0F, 0.9F, 0.85F, 0.0F);\n }\n }\n if (data.isBurning(Metal.ELECTRUM)) {\n ResourceKey<Level> spawnDim = data.getSpawnDim();\n if (spawnDim == null && player.level.dimension() == Level.OVERWORLD) { // overworld, no spawn --> use world spawn\n BlockPos spawnLoc = new BlockPos(player.level.getLevelData().getXSpawn(), player.level.getLevelData().getYSpawn(), player.level.getLevelData().getZSpawn());\n ClientUtils.drawMetalLine(stack, playervec, Vec3.atCenterOf(spawnLoc), 3.0F, 0.7F, 0.8F, 0.2F);\n\n } else if (spawnDim != null && player.level.dimension() == spawnDim) {\n ClientUtils.drawMetalLine(stack, playervec, Vec3.atCenterOf(data.getSpawnLoc()), 3.0F, 0.7F, 0.8F, 0.2F);\n }\n }\n\n stack.popPose();\n RenderSystem.applyModelViewMatrix();\n\n RenderSystem.disableBlend();\n RenderSystem.enablePolygonOffset();\n RenderSystem.enableDepthTest();\n RenderSystem.depthMask(true);\n RenderSystem.enableCull();\n RenderSystem.enableTexture();\n\n });\n }\n\n @OnlyIn(Dist.CLIENT)\n @SubscribeEvent\n public void onSound(PlaySoundEvent event) {\n\n Player player = this.mc.player;\n SoundInstance sound = event.getSound();\n if ((player == null) || (sound == null) || !player.isAlive()) {\n return;\n }\n\n player.getCapability(AllomancerCapability.PLAYER_CAP).ifPresent(data -> {\n double motionX, motionY, motionZ, magnitude;\n\n if (data.isBurning(Metal.TIN)) {\n\n magnitude = Math.sqrt(player.position().distanceToSqr(sound.getX(), sound.getY(), sound.getZ()));\n\n if (((magnitude) > 25) || ((magnitude) < 3)) {\n return;\n }\n Vec3 vec = player.position();\n double posX = vec.x(), posY = vec.y(), posZ = vec.z();\n // Spawn sound particles\n String soundName = sound.getLocation().toString();\n if (soundName.contains(\"entity\") || soundName.contains(\"step\")) {\n motionX = ((posX - (event.getSound().getX() + .5)) * -0.7) / magnitude;\n motionY = ((posY - (event.getSound().getY() + .2)) * -0.7) / magnitude;\n motionZ = ((posZ - (event.getSound().getZ() + .5)) * -0.7) / magnitude;\n this.mc.particleEngine.createParticle(new SoundParticleData(sound.getSource()), posX + (Math.sin(Math.toRadians(player.getYHeadRot())) * -.7d), posY + .2,\n posZ + (Math.cos(Math.toRadians(player.getYHeadRot())) * .7d), motionX, motionY, motionZ);\n }\n }\n });\n }\n}",
"public class PowersClientSetup {\n public static final DeferredRegister<ParticleType<?>> PARTICLES = DeferredRegister.create(ForgeRegistries.PARTICLE_TYPES, Allomancy.MODID);\n public static final RegistryObject<ParticleType<SoundParticleData>> SOUND_PARTICLE_TYPE = PARTICLES.register(\"sound_particle\",\n () -> new ParticleType<>(true, SoundParticleData.DESERIALIZER) {\n @Override\n public Codec<SoundParticleData> codec() {\n return null;\n }\n });\n @OnlyIn(Dist.CLIENT)\n public static KeyMapping hud;\n\n @OnlyIn(Dist.CLIENT)\n public static KeyMapping burn;\n\n public static boolean enable_more_keybinds;\n\n @OnlyIn(Dist.CLIENT)\n public static KeyMapping[] powers;\n\n public static void initKeyBindings() {\n burn = new KeyMapping(\"key.burn\", GLFW.GLFW_KEY_V, \"key.categories.allomancy\");\n hud = new KeyMapping(\"key.hud\", GLFW.GLFW_KEY_UNKNOWN, \"key.categories.allomancy\");\n ClientRegistry.registerKeyBinding(burn);\n ClientRegistry.registerKeyBinding(hud);\n\n enable_more_keybinds = PowersConfig.enable_more_keybinds.get();\n\n if (enable_more_keybinds) {\n powers = new KeyMapping[Metal.values().length];\n for (int i = 0; i < powers.length; i++) {\n powers[i] = new KeyMapping(\"metals.\" + Metal.getMetal(i).name().toLowerCase(), GLFW.GLFW_KEY_UNKNOWN, \"key.categories.allomancy\");\n ClientRegistry.registerKeyBinding(powers[i]);\n }\n }\n\n }\n\n public static void register() {\n PARTICLES.register(FMLJavaModLoadingContext.get().getModEventBus());\n }\n\n @SubscribeEvent(priority = EventPriority.LOWEST)\n public static void registerParticle(ParticleFactoryRegisterEvent event) {\n Allomancy.LOGGER.info(\"Allomancy: Registering custom particles\");\n Minecraft.getInstance().particleEngine.register(PowersClientSetup.SOUND_PARTICLE_TYPE.get(), SoundParticle.Factory::new);\n }\n\n}",
"public class AllomancyPowerCommand {\n\n private static final DynamicCommandExceptionType ERROR_CANT_ADD = new DynamicCommandExceptionType(s -> new TranslatableComponent(\"commands.allomancy.err_add\", s));\n private static final DynamicCommandExceptionType ERROR_CANT_REMOVE = new DynamicCommandExceptionType(s -> new TranslatableComponent(\"commands.allomancy.err_remove\", s));\n\n private static Predicate<CommandSourceStack> permissions(int level) {\n return (player) -> player.hasPermission(level);\n }\n\n private static Collection<ServerPlayer> sender(CommandContext<CommandSourceStack> ctx) throws CommandSyntaxException {\n return Collections.singleton(ctx.getSource().getPlayerOrException());\n }\n\n private static Collection<ServerPlayer> target(CommandContext<CommandSourceStack> ctx) throws CommandSyntaxException {\n return EntityArgument.getPlayers(ctx, \"targets\");\n }\n\n\n public static void register(CommandDispatcher<CommandSourceStack> dispatcher) {\n\n LiteralArgumentBuilder<CommandSourceStack> root = Commands.literal(\"allomancy\").requires(permissions(0));\n root.then(Commands\n .literal(\"get\")\n .requires(permissions(0))\n .executes(ctx -> handleMultiPlayer(ctx, sender(ctx), AllomancyPowerCommand::getPowers))\n .then(Commands.argument(\"targets\", EntityArgument.players()).executes(ctx -> handleMultiPlayer(ctx, target(ctx), AllomancyPowerCommand::getPowers))));\n\n root.then(Commands\n .literal(\"add\")\n .requires(permissions(2))\n .then(Commands\n .argument(\"type\", AllomancyPowerType.INSTANCE)\n .executes(ctx -> handleMultiPlayer(ctx, sender(ctx), AllomancyPowerCommand::addPower))\n .then(Commands\n .argument(\"targets\", EntityArgument.players())\n .executes(ctx -> handleMultiPlayer(ctx, target(ctx), AllomancyPowerCommand::addPower)))));\n\n root.then(Commands\n .literal(\"remove\")\n .requires(permissions(2))\n .then(Commands\n .argument(\"type\", AllomancyPowerType.INSTANCE)\n .executes(ctx -> handleMultiPlayer(ctx, sender(ctx), AllomancyPowerCommand::removePower))\n .then(Commands\n .argument(\"targets\", EntityArgument.players())\n .executes(ctx -> handleMultiPlayer(ctx, target(ctx), AllomancyPowerCommand::removePower)))));\n\n\n LiteralCommandNode<CommandSourceStack> command = dispatcher.register(root);\n\n dispatcher.register(Commands.literal(\"ap\").requires(permissions(0)).redirect(command));\n }\n\n\n /**\n * Abstraction to handle possibly multiple players\n *\n * @param ctx Command context\n * @param players Collection of players\n * @param toApply Function to apply to all players or sender\n * @return The number of players successfully applied to\n * @throws CommandSyntaxException\n */\n private static int handleMultiPlayer(CommandContext<CommandSourceStack> ctx,\n Collection<ServerPlayer> players,\n CheckedBiCon<CommandContext<CommandSourceStack>, ServerPlayer> toApply) throws CommandSyntaxException {\n int i = 0;\n\n for (ServerPlayer p : players) {\n toApply.accept(ctx, p);\n i++;\n }\n\n return i;\n }\n\n private static void getPowers(CommandContext<CommandSourceStack> ctx, ServerPlayer player) {\n StringBuilder powers = new StringBuilder();\n player.getCapability(AllomancerCapability.PLAYER_CAP).ifPresent(data -> {\n if (data.isMistborn()) {\n powers.append(\"all\");\n } else if (data.isUninvested()) {\n powers.append(\"none\");\n } else {\n for (Metal mt : Metal.values()) {\n if (data.hasPower(mt)) {\n if (powers.isEmpty()) {\n powers.append(mt.getName());\n } else {\n powers.append(\", \").append(mt.getName());\n }\n }\n }\n }\n });\n ctx.getSource().sendSuccess(new TranslatableComponent(\"commands.allomancy.getpowers\", player.getDisplayName(), powers.toString()), true);\n }\n\n private static void addPower(CommandContext<CommandSourceStack> ctx, ServerPlayer player) throws CommandSyntaxException {\n handlePowerChange(ctx, player, IAllomancerData::setMistborn, data -> Predicate.not(data::hasPower), mt -> (data -> data.addPower(mt)), ERROR_CANT_ADD::create,\n \"commands.allomancy.addpower\");\n }\n\n private static void removePower(CommandContext<CommandSourceStack> ctx, ServerPlayer player) throws CommandSyntaxException {\n handlePowerChange(ctx, player, IAllomancerData::setUninvested, (data) -> data::hasPower, (mt) -> (data -> data.revokePower(mt)), ERROR_CANT_REMOVE::create,\n \"commands.allomancy.removepower\");\n }\n\n /**\n * Function abstraction for both add and remove\n *\n * @param ctx The command context\n * @param player The player\n * @param all Function to call with 'all' type, either setMistborn or setUninvested\n * @param filterFunction Either data -> data.hasMetal or its inverse\n * @param single Either metal -> data.addPower or its inverse\n * @param exception Function to create an exception\n * @param success String used when successful\n * @throws CommandSyntaxException\n */\n private static void handlePowerChange(CommandContext<CommandSourceStack> ctx,\n ServerPlayer player,\n NonNullConsumer<IAllomancerData> all,\n Function<IAllomancerData, Predicate<Metal>> filterFunction,\n Function<Metal, NonNullConsumer<IAllomancerData>> single,\n Function<String, CommandSyntaxException> exception,\n String success) throws CommandSyntaxException {\n\n String type = ctx.getArgument(\"type\", String.class);\n\n if (type.equalsIgnoreCase(\"all\")) {\n player.getCapability(AllomancerCapability.PLAYER_CAP).ifPresent(all);\n } else {\n Predicate<Metal> filter = player.getCapability(AllomancerCapability.PLAYER_CAP).map(filterFunction::apply).orElse((m) -> false);\n\n if (type.equalsIgnoreCase(\"random\")) {\n List<Metal> metalList = Arrays.asList(Metal.values());\n Collections.shuffle(metalList);\n Metal mt = metalList.stream().filter(filter).findFirst().orElseThrow(() -> exception.apply(type));\n player.getCapability(AllomancerCapability.PLAYER_CAP).ifPresent(single.apply(mt));\n } else {\n Metal mt = Metal.valueOf(type.toUpperCase());\n if (filter.test(mt)) {\n player.getCapability(AllomancerCapability.PLAYER_CAP).ifPresent(single.apply(mt));\n } else {\n throw exception.apply(type);\n }\n }\n }\n Network.sync(player);\n\n ctx.getSource().sendSuccess(new TranslatableComponent(success, player.getDisplayName(), type), true);\n\n }\n\n\n @FunctionalInterface\n private interface CheckedBiCon<T, U> {\n void accept(T t, U u) throws CommandSyntaxException;\n }\n\n}",
"public class AllomancyPowerType implements ArgumentType<String> {\n\n public static final AllomancyPowerType INSTANCE = new AllomancyPowerType();\n private static final Set<String> types = Arrays.stream(Metal.values()).map(Metal::getName).collect(Collectors.toSet());\n private static final DynamicCommandExceptionType unknown_power = new DynamicCommandExceptionType(o -> new TranslatableComponent(\"commands.allomancy.unrecognized\", o));\n\n static {\n types.add(\"all\");\n types.add(\"random\");\n }\n\n @Override\n public String parse(StringReader reader) throws CommandSyntaxException {\n String in = reader.readUnquotedString();\n if (types.contains(in)) {\n return in;\n }\n throw unknown_power.create(in);\n }\n\n @Override\n public <S> CompletableFuture<Suggestions> listSuggestions(CommandContext<S> context, SuggestionsBuilder builder) {\n return SharedSuggestionProvider.suggest(types, builder).toCompletableFuture();\n }\n\n @Override\n public Collection<String> getExamples() {\n return types;\n }\n}",
"public class AllomancerCapability {\n\n public static final Capability<IAllomancerData> PLAYER_CAP = CapabilityManager.get(new CapabilityToken<>() {\n });\n\n public static final ResourceLocation IDENTIFIER = new ResourceLocation(Allomancy.MODID, \"allomancy_data\");\n\n public static void registerCapability(final RegisterCapabilitiesEvent event) {\n event.register(IAllomancerData.class);\n }\n\n}"
] | import com.legobmw99.allomancy.modules.powers.client.ClientEventHandler;
import com.legobmw99.allomancy.modules.powers.client.PowersClientSetup;
import com.legobmw99.allomancy.modules.powers.command.AllomancyPowerCommand;
import com.legobmw99.allomancy.modules.powers.command.AllomancyPowerType;
import com.legobmw99.allomancy.modules.powers.data.AllomancerCapability;
import net.minecraft.commands.synchronization.ArgumentTypes;
import net.minecraft.commands.synchronization.EmptyArgumentSerializer;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.RegisterCommandsEvent;
import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent;
import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent; | package com.legobmw99.allomancy.modules.powers;
public class PowersSetup {
public static void clientInit(final FMLClientSetupEvent e) {
MinecraftForge.EVENT_BUS.register(new ClientEventHandler());
PowersClientSetup.initKeyBindings();
}
public static void registerCommands(final RegisterCommandsEvent e) { | AllomancyPowerCommand.register(e.getDispatcher()); | 2 |
tesseract4java/tesseract4java | ocrevalUAtion/src/main/java/eu/digitisation/langutils/TermFrequency.java | [
"public class WarningException extends Exception {\n private static final long serialVersionUID = 1L;\n\n /**\n * Default constructor\n * @param message\n */\n public WarningException(String message) {\n super(message);\n }\n}",
"public class Messages {\n\n // private static final Logger logger = Logger.getLogger(\"ApplicationLog\");\n\n static {\n // try {\n // URI uri = Messages.class.getProtectionDomain()\n // .getCodeSource().getLocation().toURI();\n // String dir = new File(uri.getPath()).getParent();\n // File file = new File(dir, \"ocrevaluation.log\");\n //\n // addFile(file);\n // Messages.info(\"Logfile is \" + file);\n //\n // // while debugging\n // if (java.awt.Desktop.isDesktopSupported()) {\n // addFrame();\n // }\n // } catch (SecurityException ex) {\n // Messages.info(Messages.class.getName() + \": \" + ex);\n // } catch (URISyntaxException ex) {\n // Logger.getLogger(Messages.class.getName()).log(Level.SEVERE, null,\n // ex);\n // }\n }\n\n public static void addFile(File file) {\n // try {\n // FileHandler fh = new FileHandler(file.getAbsolutePath());\n // fh.setFormatter(new LogFormatter());\n // logger.addHandler(fh);\n // } catch (IOException ex) {\n // Messages.info(Messages.class.getName() + \": \" + ex);\n // }\n }\n\n public static void addFrame() {\n // Only while debugging\n // LogFrameHandler lfh = new LogFrameHandler();\n // lfh.setFormatter(new LogFormatter());\n // logger.addHandler(lfh);\n }\n\n public static void info(String s) {\n // logger.info(s);\n }\n\n public static void warning(String s) {\n // logger.warning(s);\n }\n\n public static void severe(String s) {\n // logger.severe(s);\n }\n}",
"public class CharFilter extends HashMap<String, String> {\n\n private static final long serialVersionUID = 1L;\n boolean compatibility; // Unicode compatibility mode\n\n /**\n * Default constructor\n */\n public CharFilter() {\n super();\n this.compatibility = false;\n }\n\n /**\n * Default constructor\n *\n * @param compatibility\n * the Unicode compatibility mode (true means activated)\n * @param file\n * a CSV file with one transformation per line, each line\n * contains two Unicode hex sequences (and comments) separated\n * with commas\n */\n public CharFilter(boolean compatibility, File file) {\n super();\n this.compatibility = compatibility;\n addFilter(file);\n }\n\n /**\n * Default constructor\n *\n * @param compatibility\n * the Unicode compatibility mode (true means activated)\n */\n public CharFilter(boolean compatibility) {\n super();\n this.compatibility = compatibility;\n }\n\n /**\n * Constructor that inherits all entries of the given source map.\n * \n * @param compatibility\n * @param source\n */\n public CharFilter(boolean compatibility, Map<String, String> source) {\n super(source.size());\n this.compatibility = compatibility;\n this.putAll(source);\n }\n\n /**\n * Load the transformation map from a CSV file: one transformation per line,\n * each line contains two Unicode hex sequences (and comments) separated\n * with commas\n *\n * @param file\n * the CSV file (or directory with CSV files) with the equivalent\n * sequences\n */\n public CharFilter(File file) {\n this.compatibility = false;\n addFilter(file);\n }\n\n /**\n * Add files to filter\n *\n * @param file\n * the CSV file (or directory with CSV files) with the equivalent\n * sequences\n */\n public final void addFilter(File file) {\n if (file.isDirectory()) {\n String[] filenames = file.list(new ExtensionFilter(\".csv\"));\n for (String filename : filenames) {\n addCSV(new File(filename));\n }\n } else if (file.isFile()) {\n addCSV(file);\n }\n }\n\n /**\n * Add the equivalences contained in a CSV file\n *\n * @param file\n * the CSV file\n */\n private void addCSV(File file) {\n try {\n BufferedReader reader = new BufferedReader(new FileReader(file));\n while (reader.ready()) {\n String line = reader.readLine();\n String[] tokens = line.split(\"([,;\\t])\");\n if (tokens.length > 1) { // allow comments in line\n String key = UnicodeReader.codepointsToString(tokens[0]);\n String value = UnicodeReader.codepointsToString(tokens[1]);\n put(key, value);\n } else {\n throw new IOException(\"Wrong line\" + line\n + \" at file \" + file);\n }\n }\n reader.close();\n } catch (IOException ex) {\n\n }\n }\n\n /**\n * Add the equivalences in CSV format\n *\n * @param reader\n * a BufferedReader with CSV lines\n */\n public void addCSV(BufferedReader reader) {\n try {\n while (reader.ready()) {\n String line = reader.readLine();\n String[] tokens = line.split(\"([,;\\t])\");\n if (tokens.length > 1) { // allow comments in line\n String key = UnicodeReader.codepointsToString(tokens[0]);\n String value = UnicodeReader.codepointsToString(tokens[1]);\n put(key, value);\n System.out.println(key + \", \" + value);\n } else {\n throw new IOException(\"Wrong CSV line\" + line);\n }\n }\n reader.close();\n } catch (IOException ex) {\n Messages.info(CharFilter.class.getName() + \": \" + ex);\n }\n }\n\n /**\n * Set the compatibility mode\n *\n * @param compatibility\n * the compatibility mode\n */\n public void setCompatibility(boolean compatibility) {\n this.compatibility = compatibility;\n }\n\n /**\n * Find all occurrences of characters in a sequence and substitute them with\n * the replacement specified by the transformation map. Remark: No\n * replacement priority is guaranteed in case of overlapping matches.\n *\n * @param s\n * the string to be transformed\n * @return a new string with all the transformations performed\n */\n public String translate(String s) {\n String r = compatibility\n ? StringNormalizer.compatible(s)\n : StringNormalizer.composed(s);\n for (Map.Entry<String, String> entry : entrySet()) {\n r = r.replaceAll(entry.getKey(), entry.getValue());\n }\n return r;\n }\n\n /**\n * Converts the contents of a file into a CharSequence\n *\n * @param file\n * the input file\n * @return the file content as a CharSequence\n */\n public CharSequence toCharSequence(File file) {\n try {\n FileInputStream input = new FileInputStream(file);\n FileChannel channel = input.getChannel();\n java.nio.ByteBuffer buffer = channel.map(\n FileChannel.MapMode.READ_ONLY, 0, channel.size());\n return java.nio.charset.Charset.forName(\"utf-8\").newDecoder()\n .decode(buffer);\n } catch (IOException ex) {\n Messages.info(CharFilter.class.getName() + \": \" + ex);\n }\n return null;\n }\n\n /**\n * Translate all characters according to the transformation map\n *\n * @param infile\n * the input file\n * @param outfile\n * the file where the output must be written\n */\n public void translate(File infile, File outfile) {\n try {\n FileWriter writer = new FileWriter(outfile);\n String input = toCharSequence(infile).toString();\n String output = translate(input);\n\n writer.write(output);\n writer.flush();\n writer.close();\n } catch (IOException ex) {\n Messages.info(CharFilter.class.getName() + \": \" + ex);\n }\n }\n\n /**\n * Translate (in place) all characters according to the transformation map\n *\n * @param file\n * the input file\n *\n */\n public void translate(File file) {\n try {\n FileWriter writer = new FileWriter(file);\n String input = toCharSequence(file).toString();\n String output = translate(input);\n\n writer.write(output);\n writer.flush();\n writer.close();\n } catch (IOException ex) {\n Messages.info(CharFilter.class.getName() + \": \" + ex);\n }\n\n }\n}",
"public class StringNormalizer {\n\n final static java.text.Normalizer.Form decomposed = java.text.Normalizer.Form.NFD;\n final static java.text.Normalizer.Form composed = java.text.Normalizer.Form.NFC;\n static final java.text.Normalizer.Form compatible = java.text.Normalizer.Form.NFKC;\n\n /**\n * Reduce whitespace (including line and paragraph separators)\n *\n * @param s\n * a string.\n * @return The string with simple spaces between words.\n */\n public static String reduceWS(String s) {\n return s.replaceAll(\"-\\n\", \"\").replaceAll(\n \"(\\\\p{Space}|\\u2028|\\u2029)+\", \" \").trim();\n }\n\n /**\n * @param s\n * a string\n * @return the canonical representation of the string.\n */\n public static String composed(String s) {\n return java.text.Normalizer.normalize(s, composed);\n }\n\n /**\n * @param s\n * a string\n * @return the canonical representation of the string with normalized\n * compatible characters.\n */\n public static String compatible(String s) {\n return java.text.Normalizer.normalize(s, compatible);\n }\n\n /**\n * @param s\n * a string\n * @return the string with all diacritics removed.\n */\n public static String removeDiacritics(String s) {\n return java.text.Normalizer.normalize(s, decomposed)\n .replaceAll(\"\\\\p{InCombiningDiacriticalMarks}+\", \"\");\n }\n\n /**\n * @param s\n * a string\n * @return the string with all punctuation symbols removed.\n */\n public static String removePunctuation(String s) {\n return s.replaceAll(\"\\\\p{P}+\", \"\");\n }\n\n /**\n * @param s\n * a string\n * @return the string with leading and trailing whitespace and punctuation\n * symbols removed.\n */\n public static String trim(String s) {\n return s.replaceAll(\"^(\\\\p{P}|\\\\p{Space})+\", \"\")\n .replaceAll(\"(\\\\p{P}|\\\\p{Space})+$\", \"\");\n }\n\n /**\n *\n * @param s\n * the input string\n * @param ignoreCase\n * true if case is irrelevant\n * @param ignoreDiacritics\n * true if diacritics are irrelevant\n * @param ignorePunctuation\n * true if punctuation is irrelevant\n * @return the canonical representation for comparison\n */\n public static String canonical(String s,\n boolean ignoreCase,\n boolean ignoreDiacritics,\n boolean ignorePunctuation) {\n\n String res = (ignorePunctuation) ? removePunctuation(s) : s;\n if (ignoreCase) {\n if (ignoreDiacritics) {\n return StringNormalizer.removeDiacritics(res).toLowerCase();\n } else {\n return res.toLowerCase();\n }\n } else if (ignoreDiacritics) {\n return StringNormalizer.removeDiacritics(res);\n } else {\n return res;\n }\n }\n\n /**\n * Remove everything except for letters (with diacritics), numbers and\n * spaces\n *\n * @param s\n * a string\n * @return the string with only letters, numbers, spaces and diacritics.\n */\n public static String strip(String s) {\n return s.replaceAll(\"[^\\\\p{L}\\\\p{M}\\\\p{N}\\\\p{Space}]\", \"\");\n }\n\n /**\n * @param s\n * a string\n * @return the string with characters <, >, &, \" escaped\n */\n public static String encode(String s) {\n StringBuilder result = new StringBuilder();\n for (Character c : s.toCharArray()) {\n if (c.equals('<')) {\n result.append(\"<\");\n } else if (c.equals('>')) {\n result.append(\">\");\n } else if (c.equals('\"')) {\n result.append(\""\");\n } else if (c.equals('&')) {\n result.append(\"&\");\n } else {\n result.append(c);\n }\n }\n return result.toString();\n }\n}",
"public class Text {\n\n StringBuilder builder;\n static int maxlen;\n Charset encoding;\n XPathFilter filter;\n\n static {\n Properties props = Settings.properties();\n maxlen = Integer.parseInt(props.getProperty(\"maxlen\", \"0\").trim());\n Messages.info(\"max length of text set to \" + maxlen);\n try {\n File inclusions = new File(\"inclusions.txt\");\n File exclusions = new File(\"exclusions.txt\");\n XPathFilter filter = inclusions.exists()\n ? new XPathFilter(inclusions, exclusions)\n : null;\n } catch (IOException ex) {\n Messages.info(Text.class.getName() + \": \" + ex);\n } catch (XPathExpressionException ex) {\n Messages.info(Text.class.getName() + \": \" + ex);\n }\n }\n\n /**\n * Create TextContent from file\n *\n * @param file\n * the input file\n * @param encoding\n * the text encoding for text files (optional; can be null)\n * @param filter\n * XPAthFilter for XML files (extracts textual content from\n * selected elements)\n * @throws eu.digitisation.input.WarningException\n * @throws eu.digitisation.input.SchemaLocationException\n */\n public Text(File file, Charset encoding, XPathFilter filter)\n throws WarningException, SchemaLocationException {\n\n builder = new StringBuilder();\n this.encoding = encoding;\n this.filter = filter;\n\n try {\n FileType type = FileType.valueOf(file);\n switch (type) {\n case PAGE:\n readPageFile(file);\n break;\n case TEXT:\n readTextFile(file);\n break;\n case FR10:\n readFR10File(file);\n break;\n case HOCR:\n readHOCRFile(file);\n break;\n case ALTO:\n readALTOFile(file);\n break;\n default:\n throw new WarningException(\"Unsupported file format (\"\n + type + \" format) for file \"\n + file.getName());\n }\n } catch (eu.digitisation.input.SchemaLocationException ex) {\n throw ex;\n } catch (IOException ex) {\n Messages.info(Text.class.getName() + \": \" + ex);\n }\n builder.trimToSize();\n }\n\n /**\n * Create Text from file\n *\n * @param file\n * the input file\n * @throws eu.digitisation.input.WarningException\n * <<<<<<< HEAD\n * @throws eu.digitisation.input.SchemaLocationException\n * ======= >>>>>>> wip\n */\n public Text(File file)\n throws WarningException, SchemaLocationException {\n this(file, null, null);\n }\n\n /**\n * Constructor only for debugging purposes\n *\n * @param s\n * @throws eu.digitisation.input.WarningException\n */\n public Text(String s) throws WarningException {\n builder = new StringBuilder();\n encoding = Charset.forName(\"utf8\");\n add(s);\n }\n\n /**\n * The length of the stored text\n *\n * @return the length of the stored text\n */\n public int length() {\n return builder.length();\n }\n\n /**\n * The content as a string\n *\n * @return the text a String\n */\n @Override\n public String toString() {\n return builder.toString();\n }\n\n /**\n * The content as a string\n *\n * @param filter\n * a CharFilter\n * @return the text after the application of the filter\n */\n public String toString(CharFilter filter) {\n return filter == null\n ? builder.toString()\n : filter.translate(builder.toString());\n }\n\n /**\n * Add content after normalization of whitespace and composition of\n * diacritics\n *\n * @param s\n * input text\n */\n private void add(String s) throws WarningException {\n String reduced = StringNormalizer.reduceWS(s);\n if (reduced.length() > 0) {\n String canonical = StringNormalizer.composed(reduced);\n if (builder.length() > 0) {\n builder.append(' ');\n }\n builder.append(canonical);\n if (maxlen > 0 && builder.length() > maxlen) {\n throw new WarningException(\"Text length limited to \"\n + maxlen + \" characters\");\n }\n }\n }\n\n private Document loadXMLFile(File file) {\n Document doc = DocumentParser.parse(file);\n String xmlEncoding = doc.getXmlEncoding();\n\n if (xmlEncoding != null) {\n encoding = Charset.forName(xmlEncoding);\n Messages.info(\"XML file \" + file.getName() + \" encoding is \"\n + encoding);\n } else {\n if (encoding == null) {\n encoding = Encoding.detect(file);\n }\n Messages.info(\"No encoding declaration in \"\n + file + \". Using \" + encoding);\n }\n return doc;\n }\n\n /**\n * Read textual content and collapse whitespace: contiguous spaces are\n * considered a single one\n *\n * @param file\n * the input text file\n */\n private void readTextFile(File file) throws WarningException {\n // guess encoding if none is provided\n if (encoding == null) {\n encoding = Encoding.detect(file);\n }\n Messages.info(\"Text file \" + file.getName() + \" encoding is \"\n + encoding);\n\n // read content\n try {\n FileInputStream fis = new FileInputStream(file);\n InputStreamReader isr = new InputStreamReader(fis, encoding);\n BufferedReader reader = new BufferedReader(isr);\n final StringBuilder completeText = new StringBuilder();\n\n String line = null;\n while ((line = reader.readLine()) != null) {\n completeText.append(line.trim());\n completeText.append('\\n');\n }\n add(completeText.toString());\n reader.close();\n } catch (IOException ex) {\n Messages.info(Text.class.getName() + \": \" + ex);\n }\n }\n\n /**\n * Reads textual content in a PAGE element of type TextRegion\n *\n * @param region\n * the TextRegion element\n */\n private void readPageTextRegion(Element region) throws IOException,\n WarningException {\n NodeList nodes = region.getChildNodes();\n for (int n = 0; n < nodes.getLength(); ++n) {\n Node node = nodes.item(n);\n if (node.getNodeName().equals(\"TextEquiv\")) {\n String text = node.getTextContent();\n add(text);\n }\n }\n }\n\n /**\n * Reads textual content in PAGE XML document. By default selects all\n * TextREgion elements\n *\n * @param file\n * the input XML file\n */\n private void readPageFile(File file) throws IOException, WarningException {\n Document doc = loadXMLFile(file);\n Document sorted = SortPageXML.isSorted(doc) ? doc\n : SortPageXML.sorted(doc);\n List<Element> regions = (filter == null)\n ? new ElementList(sorted.getElementsByTagName(\"TextRegion\"))\n : filter.selectElements(sorted);\n\n for (int r = 0; r < regions.size(); ++r) {\n Element region = regions.get(r);\n readPageTextRegion(region);\n }\n }\n\n /**\n * Reads textual content from FR10 XML paragraph\n *\n * @param oar\n * the paragraph (par) element\n */\n private void readFR10Par(Element par) throws WarningException {\n NodeList lines = par.getElementsByTagName(\"line\");\n for (int nline = 0; nline < lines.getLength(); ++nline) {\n Element line = (Element) lines.item(nline);\n StringBuilder text = new StringBuilder();\n NodeList formattings = line.getElementsByTagName(\"formatting\");\n for (int nform = 0; nform < formattings.getLength(); ++nform) {\n Element formatting = (Element) formattings.item(nform);\n NodeList charParams = formatting.getElementsByTagName(\"charParams\");\n for (int nchar = 0; nchar < charParams.getLength(); ++nchar) {\n Element charParam = (Element) charParams.item(nchar);\n String content = charParam.getTextContent();\n if (content.length() > 0) {\n text.append(content);\n } else {\n text.append(' ');\n }\n }\n }\n add(text.toString());\n }\n }\n\n /**\n * Reads textual content from FR10 XML file\n *\n * @param file\n * the input XML file\n */\n private void readFR10File(File file) throws WarningException {\n Document doc = loadXMLFile(file);\n\n List<Element> pars = (filter == null)\n ? new ElementList(doc.getElementsByTagName(\"par\"))\n : filter.selectElements(doc);\n\n for (int npar = 0; npar < pars.size(); ++npar) {\n Element par = pars.get(npar);\n readFR10Par(par);\n }\n }\n\n /**\n * Reads textual content from HOCR HTML file\n *\n * @param file\n * the input HTML file\n */\n private void readHOCRFile(File file) throws WarningException {\n try {\n org.jsoup.nodes.Document doc = org.jsoup.Jsoup.parse(file, null);\n Charset htmlEncoding = doc.outputSettings().charset();\n\n if (htmlEncoding == null) {\n encoding = Encoding.detect(file);\n Messages.warning(\"No charset declaration in \"\n + file + \". Using \" + encoding);\n } else {\n encoding = htmlEncoding;\n Messages.info(\"HTML file \" + file\n + \" encoding is \" + encoding);\n }\n\n for (org.jsoup.nodes.Element e : doc.body().select(\n \"*[class=ocr_line\")) {\n String text = e.text();\n add(text);\n\n }\n } catch (IOException ex) {\n Messages.info(Text.class.getName() + \": \" + ex);\n }\n }\n\n /**\n * Reads textual content in ALTO XML element of type TextLine\n *\n * @param file\n * the input ALTO file\n */\n private void readALTOTextLine(Element line) throws WarningException {\n NodeList strings = line.getElementsByTagName(\"String\");\n\n for (int nstring = 0; nstring < strings.getLength(); ++nstring) {\n Element string = (Element) strings.item(nstring);\n String text = string.getAttribute(\"CONTENT\");\n add(text);\n }\n\n }\n\n /**\n * Reads textual content from ALTO XML file\n *\n * @param file\n * the input ALTO file\n */\n private void readALTOFile(File file) throws WarningException {\n Document doc = loadXMLFile(file);\n NodeList lines = doc.getElementsByTagName(\"TextLine\");\n\n for (int nline = 0; nline < lines.getLength(); ++nline) {\n Element line = (Element) lines.item(nline);\n readALTOTextLine(line);\n }\n }\n\n /**\n * Extract text content (under the filtered elements)\n *\n * @throws java.io.IOException\n */\n public static void main(String[] args) throws IOException,\n WarningException, XPathExpressionException, SchemaLocationException {\n if (args.length < 1 | args[0].equals(\"-h\")) {\n System.err.println(\"usage: Text xmlfile [xpathfile] [xpathfile]\");\n } else {\n File xmlfile = new File(args[0]);\n File inclusions = args.length > 1 ? new File(args[1]) : null;\n File exclusions = args.length > 2 ? new File(args[2]) : null;\n XPathFilter filter = (inclusions == null)\n ? null\n : new XPathFilter(inclusions, exclusions);\n\n Text text = new Text(xmlfile, null, filter);\n System.out.println(text);\n }\n }\n}",
"public class WordScanner {\n\n static Pattern pattern;\n Matcher matcher;\n BufferedReader reader;\n\n static {\n StringBuilder builder = new StringBuilder();\n builder.append(\"(\");\n builder.append(\"(\\\\p{L}+([-\\\\x26'+/@·.]\\\\p{L}+)*)\");\n builder.append(\"|\");\n builder.append(\"([\\\\p{Nd}\\\\p{Nl}\\\\p{No}]+([-',./][\\\\p{Nd}\\\\p{Nl}\\\\p{No}]+)*[%‰]?)\");\n builder.append(\")\");\n pattern = Pattern.compile(builder.toString());\n }\n\n /**\n * Open an InputStream for scanning\n *\n * @param is the InputStream\n * @param encoding the character encoding (e.g., UTF-8).\n * @param regex the regular expression for words\n * @throws IOException\n */\n public WordScanner(InputStream is, Charset encoding, String regex)\n throws IOException {\n InputStreamReader isr = new InputStreamReader(is, encoding);\n\n if (regex != null) {\n pattern = Pattern.compile(regex);\n }\n\n reader = new BufferedReader(isr);\n if (reader.ready()) {\n matcher = pattern.matcher(reader.readLine());\n } else {\n matcher = pattern.matcher(\"\");\n }\n }\n\n /**\n * Open an InputStream for scanning\n *\n * @param is the InputStream\n * @param encoding the character encoding (e.g., UTF-8).\n * @throws IOException\n */\n public WordScanner(InputStream is, Charset encoding)\n throws IOException {\n this(is, encoding, null);\n }\n\n /**\n * Open file with specific encoding for scanning.\n *\n * @param file the input file.\n * @param encoding the encoding (e.g., UTF-8).\n * @param regex the regular expression for words\n * @throws java.io.IOException\n */\n public WordScanner(File file, Charset encoding, String regex)\n throws IOException {\n this(new FileInputStream(file), encoding, regex);\n }\n\n /**\n * Open file with specific encoding for scanning.\n *\n * @param file the input file.\n * @param encoding the encoding (e.g., UTF-8).\n * @throws java.io.IOException\n */\n public WordScanner(File file, Charset encoding)\n throws IOException {\n this(new FileInputStream(file), encoding);\n }\n\n /**\n * Open a file for scanning.\n *\n * @param file the input file.\n * @throws java.io.IOException\n */\n public WordScanner(File file, String regex)\n throws IOException {\n this(file, Encoding.detect(file), regex);\n }\n\n /**\n * Open a string for scanning\n *\n * @param s the input string to be tokenized\n * @param regex the regular expression for words\n * @throws IOException\n */\n public WordScanner(String s, String regex) throws IOException {\n this(new ByteArrayInputStream(s.getBytes(\"UTF-8\")),\n Charset.forName(\"UTF-8\"), regex);\n }\n\n /**\n * Open a string for scanning\n *\n * @param s the input string to be tokenized\n * @throws IOException\n */\n public WordScanner(String s) throws IOException {\n this(new ByteArrayInputStream(s.getBytes(\"UTF-8\")),\n Charset.forName(\"UTF-8\"));\n }\n\n /**\n *\n * @param file the input file to be processed\n * @param regex the regular expression for words\n * @return a StringBuilder with the file content\n * @throws java.io.IOException\n */\n public static StringBuilder scanToStringBuilder(File file, String regex)\n throws IOException {\n StringBuilder builder = new StringBuilder();\n WordScanner scanner = new WordScanner(file, regex);\n String word;\n\n while ((word = scanner.nextWord()) != null) {\n builder.append(' ').append(word);\n }\n return builder;\n }\n\n /**\n * Returns the next word in file.\n *\n * @return the next word in the scanned file\n * @throws java.io.IOException\n */\n public String nextWord()\n throws IOException {\n String res = null;\n while (res == null) {\n if (matcher.find()) {\n res = matcher.group(0);\n } else if (reader.ready()) {\n matcher = pattern.matcher(reader.readLine());\n } else {\n break;\n }\n }\n return res;\n }\n\n /**\n * Sample main.\n *\n * @param args\n */\n public static void main(String[] args) {\n WordScanner scanner;\n\n for (String arg : args) {\n try {\n String word;\n File file = new File(arg);\n scanner = new WordScanner(file, \"[^\\\\p{Space}]+\");\n while ((word = scanner.nextWord()) != null) {\n System.out.println(word);\n }\n } catch (IOException ex) {\n System.err.println(ex);\n }\n }\n }\n}"
] | import eu.digitisation.input.SchemaLocationException;
import eu.digitisation.input.WarningException;
import eu.digitisation.log.Messages;
import eu.digitisation.math.Counter;
import eu.digitisation.text.CharFilter;
import eu.digitisation.text.StringNormalizer;
import eu.digitisation.text.Text;
import eu.digitisation.text.WordScanner;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map; | /*
* Copyright (C) 2013 Universidad de Alicante
*
* 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 eu.digitisation.langutils;
/**
* Compute term frequencies in a collection
*
* @author R.C.C
*/
public class TermFrequency extends Counter<String> {
private static final long serialVersionUID = 1L;
private CharFilter filter;
/**
* Default constructor
*/
public TermFrequency() {
filter = null;
}
/**
* Basic constructor
*
* @param filter a CharFilter implementing character equivalences
*/
public TermFrequency(CharFilter filter) {
this.filter = filter;
}
/**
* Add CharFilter
*
* @param file a CSV file with character equivalences
*/
public void addFilter(File file) {
if (filter == null) {
filter = new CharFilter(file);
} else {
filter.addFilter(file);
}
}
/**
* Extract words from a file
*
* @param dir the input file or directory
* @throws eu.digitisation.input.WarningException
* @throws eu.digitisation.input.SchemaLocationException
*/
public void add(File dir) throws WarningException, SchemaLocationException {
if (dir.isDirectory()) {
addFiles(dir.listFiles());
} else {
File[] files = {dir};
addFiles(files);
}
}
/**
* Extract words from a file
*
* @param file an input files
* @throws eu.digitisation.input.WarningException
* @throws eu.digitisation.input.SchemaLocationException
*/
public void addFile(File file) throws WarningException, SchemaLocationException {
try {
Text content = new Text(file); | WordScanner scanner = new WordScanner(content.toString(), | 5 |
doanduyhai/killrvideo-java | src/main/java/killrvideo/service/RatingsService.java | [
"public static final String mergeStackTrace(Throwable throwable) {\n StringJoiner joiner = new StringJoiner(\"\\n\\t\", \"\\n\", \"\\n\");\n joiner.add(throwable.getMessage());\n Arrays.asList(throwable.getStackTrace())\n .forEach(stackTraceElement -> joiner.add(stackTraceElement.toString()));\n\n return joiner.toString();\n}",
"public interface Schema {\n\n /** Core KeySpace. */\n String KEYSPACE = \"killrvideo\";\n \n /** Table Names in Keyspace previously defined. */\n String TABLENAME_COMMENTS_BY_USER = \"comments_by_user\";\n String TABLENAME_COMMENTS_BY_VIDEO = \"comments_by_video\";\n \n String TABLENAME_ENCODING_JOBS_NOTIFICATION = \"encoding_job_notifications\";\n String TABLENAME_LATEST_VIDEOS = \"latest_videos\";\n \n String TABLENAME_USERS = \"users\";\n String TABLENAME_USER_CREDENTIALS = \"user_credentials\";\n String TABLENAME_USER_VIDEOS = \"user_videos\";\n \n String TABLENAME_VIDEOS = \"videos\";\n String TABLENAME_VIDEOS_RATINGS = \"video_ratings\";\n String TABLENAME_VIDEOS_RATINGS_BYUSER = \"video_ratings_by_user\";\n\n String TABLENAME_PLAYBACK_STATS = \"video_playback_stats\";\n \n String TABLENAME_VIDEO_RECOMMENDATIONS = \"video_recommendations\";\n String TABLENAME_VIDEO_RECOMMENDATIONS_BYVIDEO = \"video_recommendations_by_video\";\n \n}",
"@Table(keyspace = Schema.KEYSPACE, name = Schema.TABLENAME_VIDEOS_RATINGS)\npublic class VideoRating implements Serializable {\n\n /** Serial. */\n private static final long serialVersionUID = -8874199914791405808L;\n\n @PartitionKey\n private UUID videoid;\n\n @Column(name = \"rating_counter\")\n private Long ratingCounter;\n\n @Column(name = \"rating_total\")\n private Long ratingTotal;\n\n /**\n * Mapping to generated GPRC beans.\n */\n public GetRatingResponse toRatingResponse() {\n return GetRatingResponse.newBuilder()\n .setVideoId(TypeConverter.uuidToUuid(videoid))\n .setRatingsCount(Optional.ofNullable(ratingCounter).orElse(0L))\n .setRatingsTotal(Optional.ofNullable(ratingTotal).orElse(0L))\n .build();\n }\n\n /**\n * Getter for attribute 'videoid'.\n *\n * @return\n * current value of 'videoid'\n */\n public UUID getVideoid() {\n return videoid;\n }\n\n /**\n * Setter for attribute 'videoid'.\n * @param videoid\n * \t\tnew value for 'videoid '\n */\n public void setVideoid(UUID videoid) {\n this.videoid = videoid;\n }\n\n /**\n * Getter for attribute 'ratingCounter'.\n *\n * @return\n * current value of 'ratingCounter'\n */\n public Long getRatingCounter() {\n return ratingCounter;\n }\n\n /**\n * Setter for attribute 'ratingCounter'.\n * @param ratingCounter\n * \t\tnew value for 'ratingCounter '\n */\n public void setRatingCounter(Long ratingCounter) {\n this.ratingCounter = ratingCounter;\n }\n\n /**\n * Getter for attribute 'ratingTotal'.\n *\n * @return\n * current value of 'ratingTotal'\n */\n public Long getRatingTotal() {\n return ratingTotal;\n }\n\n /**\n * Setter for attribute 'ratingTotal'.\n * @param ratingTotal\n * \t\tnew value for 'ratingTotal '\n */\n public void setRatingTotal(Long ratingTotal) {\n this.ratingTotal = ratingTotal;\n }\n\n}",
"@Table(keyspace = Schema.KEYSPACE, name = Schema.TABLENAME_VIDEOS_RATINGS_BYUSER)\npublic class VideoRatingByUser implements Serializable {\n\n /** Serial. */\n private static final long serialVersionUID = 7124040203261999049L;\n\n @PartitionKey\n private UUID videoid;\n\n @ClusteringColumn\n private UUID userid;\n\n @Column\n private int rating;\n\n /**\n * Default constructor (reflection)\n */\n public VideoRatingByUser() {}\n\n /**\n * Constructor with all parameters.\n */\n public VideoRatingByUser(UUID videoid, UUID userid, int rating) {\n this.videoid = videoid;\n this.userid = userid;\n this.rating = rating;\n }\n\n /**\n * Mapping to generated GPRC beans.\n */\n public GetUserRatingResponse toUserRatingResponse() {\n return GetUserRatingResponse\n .newBuilder()\n .setUserId(TypeConverter.uuidToUuid(userid))\n .setVideoId(TypeConverter.uuidToUuid(videoid))\n .setRating(rating)\n .build();\n }\n\n /**\n * Getter for attribute 'videoid'.\n *\n * @return\n * current value of 'videoid'\n */\n public UUID getVideoid() {\n return videoid;\n }\n\n /**\n * Setter for attribute 'videoid'.\n * @param videoid\n * \t\tnew value for 'videoid '\n */\n public void setVideoid(UUID videoid) {\n this.videoid = videoid;\n }\n\n /**\n * Getter for attribute 'userid'.\n *\n * @return\n * current value of 'userid'\n */\n public UUID getUserid() {\n return userid;\n }\n\n /**\n * Setter for attribute 'userid'.\n * @param userid\n * \t\tnew value for 'userid '\n */\n public void setUserid(UUID userid) {\n this.userid = userid;\n }\n\n /**\n * Getter for attribute 'rating'.\n *\n * @return\n * current value of 'rating'\n */\n public int getRating() {\n return rating;\n }\n\n /**\n * Setter for attribute 'rating'.\n * @param rating\n * \t\tnew value for 'rating '\n */\n public void setRating(int rating) {\n this.rating = rating;\n }\n \n}",
"public class CassandraMutationError {\n\n /**\n * Failed Protobuf requests.\n */\n public final GeneratedMessageV3 request;\n \n /**\n * Related exception in code.\n */\n public final Throwable throwable;\n\n /**\n * Default constructor.\n */\n public CassandraMutationError(GeneratedMessageV3 request, Throwable throwable) {\n this.request = request;\n this.throwable = throwable;\n }\n\n /**\n * Display as an error message.\n */\n public String buildErrorLog() {\n StringBuilder builder = new StringBuilder();\n builder.append(request.toString()).append(\"\\n\");\n builder.append(throwable.getMessage()).append(\"\\n\");\n builder.append(ExceptionUtils.mergeStackTrace(throwable));\n return builder.toString();\n }\n}",
"public class FutureUtils {\n\n /**\n * Hide constructor.\n */\n private FutureUtils() {}\n \n /**\n * This is a utility class that converts ListenableFuture objects into CompletableFuture,\n * creates a callback, and returns CompletableFuture\n * @param listenableFuture\n * @param <T>\n * @return CompletableFuture\n */\n public static <T> CompletableFuture<T> buildCompletableFuture(final ListenableFuture<T> listenableFuture) {\n\n //create an instance of CompletableFuture\n CompletableFuture<T> completable = new CompletableFuture<T>() {\n @Override\n public boolean cancel(boolean mayInterruptIfRunning) {\n // propagate cancel to the listenable future\n boolean result = listenableFuture.cancel(mayInterruptIfRunning);\n super.cancel(mayInterruptIfRunning);\n return result;\n }\n };\n\n // add callback\n Futures.addCallback(listenableFuture, new FutureCallback<T>() {\n @Override\n public void onSuccess(T result) {\n completable.complete(result);\n }\n\n @Override\n public void onFailure(Throwable t) {\n completable.completeExceptionally(t);\n }\n });\n return completable;\n }\n}",
"public class TypeConverter {\n\n public static Timestamp instantToTimeStamp(Instant instant) {\n return Timestamp.newBuilder()\n .setSeconds(instant.getEpochSecond())\n .setNanos(instant.getNano()).build();\n }\n \n public static Timestamp epochTimeToTimeStamp(long epoch) {\n return Timestamp.newBuilder().setSeconds(epoch).build();\n }\n\n public static Timestamp dateToTimestamp(Date date) {\n return instantToTimeStamp(date.toInstant());\n }\n\n public static Date dateFromTimestamp(Timestamp timestamp) {\n return Date.from(Instant.ofEpochSecond(timestamp.getSeconds()));\n }\n\n public static TimeUuid uuidToTimeUuid(UUID uuid) {\n return TimeUuid.newBuilder()\n .setValue(uuid.toString())\n .build();\n }\n\n public static Uuid uuidToUuid(UUID uuid) {\n return Uuid.newBuilder()\n .setValue(uuid.toString())\n .build();\n }\n\n /**\n * This method is useful when debugging as an easy way to get a traversal\n * string to use in gremlin or DSE Studio from bytecode.\n * @param traversal\n * @return\n */\n public static String bytecodeToTraversalString(KillrVideoTraversal<Vertex, Vertex> traversal) {\n return org.apache.tinkerpop.gremlin.groovy.jsr223.GroovyTranslator.of(\"g\").translate(traversal.getBytecode());\n }\n}",
"@Service\npublic class KillrVideoInputValidator {\n\n /** Logger to class. */\n private static final Logger LOGGER = LoggerFactory.getLogger(KillrVideoInputValidator.class);\n \n /**\n * Valid inputs.\n *\n * @param request\n * current request\n * @param streamObserve\n * Stream to publish error.\n * @return\n * if valid\n */\n public boolean isValid(CommentOnVideoRequest request, StreamObserver<?> streamObserver) {\n StringBuilder errorMessage = initErrorString(request);\n boolean isValid = \n notEmpty(!request.hasUserId() || isBlank(request.getUserId().getValue()), \"userId\", \"video request\",errorMessage) &&\n notEmpty(!request.hasVideoId() || isBlank(request.getVideoId().getValue()), \"videoId\", \"video request\",errorMessage) &&\n notEmpty(!request.hasCommentId() || isBlank(request.getCommentId().getValue()), \"commentId\", \"video request\",errorMessage) &&\n notEmpty(isBlank(request.getComment()), \"comment\", \"video request\",errorMessage);\n return validate(streamObserver, errorMessage, isValid);\n }\n\n /**\n * Valid inputs.\n *\n * @param request\n * current request\n * @param streamObserve\n * Stream to publish error.\n * @return\n * if valid\n */\n public boolean isValid(GetUserCommentsRequest request, StreamObserver<?> streamObserver) {\n final StringBuilder errorMessage = initErrorString(request);\n boolean isValid = \n notEmpty(!request.hasUserId() || isBlank(request.getUserId().getValue()), \"userId\", \"comment request\",errorMessage) &&\n positive(request.getPageSize() <= 0, \"page size\", \"comment request\",errorMessage);\n return validate(streamObserver, errorMessage, isValid);\n }\n\n \n \n public boolean isValid(GetVideoCommentsRequest request, StreamObserver<?> streamObserver) {\n final StringBuilder errorMessage = initErrorString(request);\n boolean isValid = true;\n\n if (!request.hasVideoId() || isBlank(request.getVideoId().getValue())) {\n errorMessage.append(\"\\t\\tvideo id should be provided for get video comment request\\n\");\n isValid = false;\n }\n\n if (request.getPageSize() <= 0) {\n errorMessage.append(\"\\t\\tpage size should be strictly positive for get video comment request\");\n isValid = false;\n }\n\n return validate(streamObserver, errorMessage, isValid);\n }\n\n public boolean isValid(RateVideoRequest request, StreamObserver<?> streamObserver) {\n final StringBuilder errorMessage = initErrorString(request);\n boolean isValid = true;\n\n if (!request.hasVideoId() || isBlank(request.getVideoId().getValue())) {\n errorMessage.append(\"\\t\\tvideo id should be provided for rate video request\\n\");\n isValid = false;\n }\n\n if (!request.hasUserId() || isBlank(request.getUserId().getValue())) {\n errorMessage.append(\"\\t\\tuser id should be provided for rate video request\");\n isValid = false;\n }\n return validate(streamObserver, errorMessage, isValid);\n }\n\n public boolean isValid(GetRatingRequest request, StreamObserver<?> streamObserver) {\n final StringBuilder errorMessage = initErrorString(request);\n boolean isValid = true;\n\n if (!request.hasVideoId() || isBlank(request.getVideoId().getValue())) {\n errorMessage.append(\"\\t\\tvideo id should be provided for get video rating request\\n\");\n isValid = false;\n }\n\n return validate(streamObserver, errorMessage, isValid);\n }\n\n public boolean isValid(GetUserRatingRequest request, StreamObserver<?> streamObserver) {\n final StringBuilder errorMessage = initErrorString(request);\n boolean isValid = true;\n\n if (!request.hasVideoId() || isBlank(request.getVideoId().getValue())) {\n errorMessage.append(\"\\t\\tvideo id should be provided for get user rating request\\n\");\n isValid = false;\n }\n\n if (!request.hasUserId() || isBlank(request.getUserId().getValue())) {\n errorMessage.append(\"\\t\\tuser id should be provided for get user rating request\\n\");\n isValid = false;\n }\n\n return validate(streamObserver, errorMessage, isValid);\n }\n\n public boolean isValid(SearchVideosRequest request, StreamObserver<?> streamObserver) {\n final StringBuilder errorMessage = initErrorString(request);\n boolean isValid = true;\n\n if (isBlank(request.getQuery())) {\n errorMessage.append(\"\\t\\tquery string should be provided for search videos request\\n\");\n isValid = false;\n }\n\n if (request.getPageSize() <= 0) {\n errorMessage.append(\"\\t\\tpage size should be strictly positive for search videos request\\n\");\n isValid = false;\n }\n\n return validate(streamObserver, errorMessage, isValid);\n }\n\n public boolean isValid(GetQuerySuggestionsRequest request, StreamObserver<?> streamObserver) {\n final StringBuilder errorMessage = initErrorString(request);\n boolean isValid = true;\n\n if (isBlank(request.getQuery())) {\n errorMessage.append(\"\\t\\tquery string should be provided for get video suggestions request\\n\");\n isValid = false;\n }\n\n if (request.getPageSize() <= 0) {\n errorMessage.append(\"\\t\\tpage size should be strictly positive for get video suggestions request\\n\");\n isValid = false;\n }\n\n return validate(streamObserver, errorMessage, isValid);\n }\n\n public boolean isValid(RecordPlaybackStartedRequest request, StreamObserver<?> streamObserver) {\n final StringBuilder errorMessage = initErrorString(request);\n boolean isValid = true;\n\n if (request.getVideoId() == null || isBlank(request.getVideoId().getValue())) {\n errorMessage.append(\"\\t\\tvideo id should be provided for record playback started request\\n\");\n isValid = false;\n }\n\n return validate(streamObserver, errorMessage, isValid);\n }\n\n public boolean isValid(GetNumberOfPlaysRequest request, StreamObserver<?> streamObserver) {\n final StringBuilder errorMessage = initErrorString(request);\n boolean isValid = true;\n\n if (request.getVideoIdsCount() <= 0) {\n errorMessage.append(\"\\t\\tvideo ids should be provided for get number of plays request\\n\");\n isValid = false;\n }\n\n if (request.getVideoIdsCount() > 20) {\n errorMessage.append(\"\\t\\tcannot do a get more than 20 videos at once for get number of plays request\\n\");\n isValid = false;\n }\n\n for (CommonTypes.Uuid uuid : request.getVideoIdsList()) {\n if (uuid == null || isBlank(uuid.getValue())) {\n errorMessage.append(\"\\t\\tprovided UUID values cannot be null or blank for get number of plays request\\n\");\n isValid = false;\n }\n }\n\n return validate(streamObserver, errorMessage, isValid);\n }\n\n public boolean isValid(GetRelatedVideosRequest request, StreamObserver<?> streamObserver) {\n final StringBuilder errorMessage = initErrorString(request);\n boolean isValid = true;\n\n if (request.getVideoId() == null || isBlank(request.getVideoId().getValue())) {\n errorMessage.append(\"\\t\\tvideo id should be provided for get related videos request\\n\");\n isValid = false;\n }\n\n return validate(streamObserver, errorMessage, isValid);\n }\n\n public boolean isValid(CreateUserRequest request, StreamObserver<?> streamObserver) {\n final StringBuilder errorMessage = initErrorString(request);\n boolean isValid = true;\n\n if (request.getUserId() == null || isBlank(request.getUserId().getValue())) {\n errorMessage.append(\"\\t\\tuser id should be provided for create user request\\n\");\n isValid = false;\n }\n\n if (isBlank(request.getPassword())) {\n errorMessage.append(\"\\t\\tpassword should be provided for create user request\\n\");\n isValid = false;\n }\n\n if (isBlank(request.getEmail())) {\n errorMessage.append(\"\\t\\temail should be provided for create user request\\n\");\n isValid = false;\n }\n return validate(streamObserver, errorMessage, isValid);\n }\n\n public boolean isValid(VerifyCredentialsRequest request, StreamObserver<?> streamObserver) {\n final StringBuilder errorMessage = initErrorString(request);\n boolean isValid = true;\n\n if (isBlank(request.getEmail())) {\n errorMessage.append(\"\\t\\temail should be provided for verify credentials request\\n\");\n isValid = false;\n }\n\n if (isBlank(request.getPassword())) {\n errorMessage.append(\"\\t\\tpassword should be provided for verify credentials request\\n\");\n isValid = false;\n }\n\n return validate(streamObserver, errorMessage, isValid);\n }\n\n public boolean isValid(GetUserProfileRequest request, StreamObserver<?> streamObserver) {\n final StringBuilder errorMessage = initErrorString(request);\n boolean isValid = true;\n\n\n if (request.getUserIdsCount() > 20) {\n errorMessage.append(\"\\t\\tcannot get more than 20 user profiles at once for get user profile request\\n\");\n isValid = false;\n }\n\n for (CommonTypes.Uuid uuid : request.getUserIdsList()) {\n if (uuid == null || isBlank(uuid.getValue())) {\n errorMessage.append(\"\\t\\tprovided UUID values cannot be null or blank for get user profile request\\n\");\n isValid = false;\n }\n }\n\n return validate(streamObserver, errorMessage, isValid);\n }\n\n public boolean isValid(SubmitUploadedVideoRequest request, StreamObserver<?> streamObserver) {\n final StringBuilder errorMessage = initErrorString(request);\n boolean isValid = true;\n\n if (request.getVideoId() == null || isBlank(request.getVideoId().getValue())) {\n errorMessage.append(\"\\t\\tvideo id should be provided for submit uploaded video request\\n\");\n isValid = false;\n }\n\n if (request.getUserId() == null || isBlank(request.getUserId().getValue())) {\n errorMessage.append(\"\\t\\tuser id should be provided for submit uploaded video request\\n\");\n isValid = false;\n }\n\n if (isBlank(request.getName())) {\n errorMessage.append(\"\\t\\tvideo name should be provided for submit uploaded video request\\n\");\n isValid = false;\n }\n\n if (isBlank(request.getDescription())) {\n errorMessage.append(\"\\t\\tvideo description should be provided for submit uploaded video request\\n\");\n isValid = false;\n }\n\n if (request.getTagsList() == null || CollectionUtils.isEmpty(request.getTagsList())) {\n errorMessage.append(\"\\t\\tvideo tags list should be provided for submit uploaded video request\\n\");\n isValid = false;\n }\n\n if (isBlank(request.getUploadUrl())) {\n errorMessage.append(\"\\t\\tvideo upload url should be provided for submit uploaded video request\\n\");\n isValid = false;\n }\n\n return validate(streamObserver, errorMessage, isValid);\n }\n\n public boolean isValid(SubmitYouTubeVideoRequest request, StreamObserver<?> streamObserver) {\n final StringBuilder errorMessage = initErrorString(request);\n boolean isValid = true;\n\n if (request.getVideoId() == null || isBlank(request.getVideoId().getValue())) {\n errorMessage.append(\"\\t\\tvideo id should be provided for submit youtube video request\\n\");\n isValid = false;\n }\n\n if (request.getUserId() == null || isBlank(request.getUserId().getValue())) {\n errorMessage.append(\"\\t\\tuser id should be provided for submit youtube video request\\n\");\n isValid = false;\n }\n\n if (isBlank(request.getName())) {\n errorMessage.append(\"\\t\\tvideo name should be provided for submit youtube video request\\n\");\n isValid = false;\n }\n\n if (isBlank(request.getDescription())) {\n errorMessage.append(\"\\t\\tvideo description should be provided for submit youtube video request\\n\");\n isValid = false;\n }\n\n if (isBlank(request.getYouTubeVideoId())) {\n errorMessage.append(\"\\t\\tvideo youtube id should be provided for submit youtube video request\\n\");\n isValid = false;\n }\n\n return validate(streamObserver, errorMessage, isValid);\n }\n\n public boolean isValid(GetVideoRequest request, StreamObserver<?> streamObserver) {\n final StringBuilder errorMessage = initErrorString(request);\n boolean isValid = true;\n\n if (request.getVideoId() == null || isBlank(request.getVideoId().getValue())) {\n errorMessage.append(\"\\t\\tvideo id should be provided for submit youtube video request\\n\");\n isValid = false;\n }\n return validate(streamObserver, errorMessage, isValid);\n }\n\n public boolean isValid(GetVideoPreviewsRequest request, StreamObserver<?> streamObserver) {\n final StringBuilder errorMessage = initErrorString(request);\n boolean isValid = true;\n\n\n if (request.getVideoIdsCount() >= 20) {\n errorMessage.append(\"\\t\\tcannot get more than 20 videos at once for get video previews request\\n\");\n isValid = false;\n }\n\n for (CommonTypes.Uuid uuid : request.getVideoIdsList()) {\n if (uuid == null || isBlank(uuid.getValue())) {\n errorMessage.append(\"\\t\\tprovided UUID values cannot be null or blank for get video previews request\\n\");\n isValid = false;\n }\n }\n\n return validate(streamObserver, errorMessage, isValid);\n }\n\n\n public boolean isValid(GetLatestVideoPreviewsRequest request, StreamObserver<?> streamObserver) {\n final StringBuilder errorMessage = initErrorString(request);\n boolean isValid = true;\n\n if (request.getPageSize() <= 0) {\n errorMessage.append(\"\\t\\tpage size should be strictly positive for get latest preview video request\\n\");\n isValid = false;\n }\n\n return validate(streamObserver, errorMessage, isValid);\n }\n\n public boolean isValid(GetUserVideoPreviewsRequest request, StreamObserver<?> streamObserver) {\n final StringBuilder errorMessage = initErrorString(request);\n boolean isValid = true;\n\n if (request.getUserId() == null || isBlank(request.getUserId().getValue())) {\n errorMessage.append(\"\\t\\tuser id should be provided for get user video previews request\\n\");\n isValid = false;\n }\n\n if (request.getPageSize() <= 0) {\n errorMessage.append(\"\\t\\tpage size should be strictly positive for get user video previews request\\n\");\n isValid = false;\n }\n\n return validate(streamObserver, errorMessage, isValid);\n }\n\n private StringBuilder initErrorString(Object request) {\n return new StringBuilder(\"Validation error for '\" + request.toString() + \"' : \\n\");\n }\n \n /**\n * Deduplicate condition evaluation\n * @param assertion\n * current condition\n * @param fieldName\n * fieldName to evaluate\n * @param request\n * GRPC reauest\n * @param errorMessage\n * concatenation of error messages\n * @return\n */\n private boolean notEmpty(boolean assertion, String fieldName, String request, StringBuilder errorMessage) {\n if (assertion) {\n errorMessage.append(\"\\t\\t\");\n errorMessage.append(fieldName);\n errorMessage.append(\"should be provided for comment on \");\n errorMessage.append(request);\n errorMessage.append(\"\\n\");\n }\n return !assertion;\n }\n \n private boolean positive(boolean assertion, String fieldName, String request, StringBuilder errorMessage) {\n if (assertion) {\n errorMessage.append(\"\\t\\t\");\n errorMessage.append(fieldName);\n errorMessage.append(\"should be strictly positive for \");\n errorMessage.append(request);\n errorMessage.append(\"\\n\");\n }\n return !assertion;\n }\n\n private boolean validate(StreamObserver<?> streamObserver, StringBuilder errorMessage, boolean isValid) {\n if (isValid) {\n return true;\n } else {\n final String description = errorMessage.toString();\n LOGGER.error(description);\n streamObserver.onError(Status.INVALID_ARGUMENT.withDescription(description).asRuntimeException());\n streamObserver.onCompleted();\n return false;\n }\n }\n\n}"
] | import static killrvideo.utils.ExceptionUtils.mergeStackTrace;
import java.time.Instant;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import com.datastax.driver.core.BoundStatement;
import com.datastax.driver.core.ConsistencyLevel;
import com.datastax.driver.core.PreparedStatement;
import com.datastax.driver.core.querybuilder.QueryBuilder;
import com.datastax.driver.dse.DseSession;
import com.datastax.driver.mapping.Mapper;
import com.datastax.driver.mapping.MappingManager;
import com.google.common.eventbus.EventBus;
import io.grpc.Status;
import io.grpc.stub.StreamObserver;
import killrvideo.entity.Schema;
import killrvideo.entity.VideoRating;
import killrvideo.entity.VideoRatingByUser;
import killrvideo.events.CassandraMutationError;
import killrvideo.ratings.RatingsServiceGrpc.RatingsServiceImplBase;
import killrvideo.ratings.RatingsServiceOuterClass.GetRatingRequest;
import killrvideo.ratings.RatingsServiceOuterClass.GetRatingResponse;
import killrvideo.ratings.RatingsServiceOuterClass.GetUserRatingRequest;
import killrvideo.ratings.RatingsServiceOuterClass.GetUserRatingResponse;
import killrvideo.ratings.RatingsServiceOuterClass.RateVideoRequest;
import killrvideo.ratings.RatingsServiceOuterClass.RateVideoResponse;
import killrvideo.ratings.events.RatingsEvents.UserRatedVideo;
import killrvideo.utils.FutureUtils;
import killrvideo.utils.TypeConverter;
import killrvideo.validation.KillrVideoInputValidator; | package killrvideo.service;
@Service
//public class RatingsService extends AbstractRatingsService {
public class RatingsService extends RatingsServiceImplBase {
private static final Logger LOGGER = LoggerFactory.getLogger(RatingsService.class);
@Inject
MappingManager manager;
@Inject
Mapper<VideoRating> videoRatingMapper;
@Inject
Mapper<VideoRatingByUser> videoRatingByUserMapper;
@Inject
DseSession dseSession;
@Inject
EventBus eventBus;
@Inject
KillrVideoInputValidator validator;
private String videoRatingsTableName;
private PreparedStatement rateVideo_updateRatingPrepared;
@PostConstruct
public void init(){
videoRatingsTableName = videoRatingMapper.getTableMetadata().getName();
rateVideo_updateRatingPrepared = dseSession.prepare(
QueryBuilder
.update(Schema.KEYSPACE, videoRatingsTableName)
.with(QueryBuilder.incr("rating_counter"))
.and(QueryBuilder.incr("rating_total", QueryBuilder.bindMarker()))
.where(QueryBuilder.eq("videoid", QueryBuilder.bindMarker()))
).setConsistencyLevel(ConsistencyLevel.LOCAL_QUORUM);
}
@Override
public void rateVideo(RateVideoRequest request, StreamObserver<RateVideoResponse> responseObserver) {
LOGGER.debug("-----Start rate video request-----");
if (!validator.isValid(request, responseObserver)) {
return;
}
final Instant time = Instant.now();
final UUID videoId = UUID.fromString(request.getVideoId().getValue());
final UUID userId = UUID.fromString(request.getUserId().getValue());
final Integer rating = request.getRating();
/**
* Increment rating_counter by 1
* Increment rating_total by amount of rating
*/
BoundStatement counterUpdateStatement = rateVideo_updateRatingPrepared.bind()
.setLong("rating_total", rating)
.setUUID("videoid", videoId);
/**
* Here, instead of using logged batch, we can insert both mutations asynchronously
* In case of error, we log the request into the mutation error log for replay later
* by another micro-service
*
* Something else to notice is I am using both a prepared statement with executeAsync()
* and a call to the mapper's saveAsync() methods. I could have kept things uniform
* and stuck with both prepared/bind statements, but I wanted to illustrate the combination
* and use the mapper for the second statement because it is a simple save operation with no
* options, increments, etc... A key point is in the case you see below both statements are actually
* prepared, the first one I did manually in a more traditional sense and in the second one the
* mapper will prepare the statement for you automagically.
*/
CompletableFuture
.allOf(
FutureUtils.buildCompletableFuture(dseSession.executeAsync(counterUpdateStatement)),
FutureUtils.buildCompletableFuture(videoRatingByUserMapper
.saveAsync(new VideoRatingByUser(videoId, userId, rating)))
)
.handle((rs, ex) -> {
if (ex == null) {
/**
* This eventBus.post() call will make its way to the SuggestedVideoService
* class to handle adding data to our graph recommendation engine
*/
eventBus.post(UserRatedVideo.newBuilder()
.setVideoId(request.getVideoId())
.setUserId(request.getUserId())
.setRating(request.getRating())
.setRatingTimestamp(TypeConverter.instantToTimeStamp(time))
.build());
responseObserver.onNext(RateVideoResponse.newBuilder().build());
responseObserver.onCompleted();
LOGGER.debug("End rate video request");
} else { | LOGGER.error("Exception rating video : " + mergeStackTrace(ex)); | 0 |
Kickflip/kickflip-android-sdk | sdk/src/main/java/io/kickflip/sdk/fragment/GlassBroadcastFragment.java | [
"public class Kickflip {\n public static final String TAG = \"Kickflip\";\n private static Context sContext;\n private static String sClientKey;\n private static String sClientSecret;\n\n private static KickflipApiClient sKickflip;\n\n // Per-Stream settings\n private static SessionConfig sSessionConfig; // Absolute path to root storage location\n private static BroadcastListener sBroadcastListener;\n\n /**\n * Register with Kickflip, creating a new user identity per app installation.\n *\n * @param context the host application's {@link android.content.Context}\n * @param key your Kickflip Client Key\n * @param secret your Kickflip Client Secret\n * @return a {@link io.kickflip.sdk.api.KickflipApiClient} used to perform actions on behalf of a\n * {@link io.kickflip.sdk.api.json.User}.\n */\n public static KickflipApiClient setup(Context context, String key, String secret) {\n return setup(context, key, secret, null);\n }\n\n /**\n * Register with Kickflip, creating a new user identity per app installation.\n *\n * @param context the host application's {@link android.content.Context}\n * @param key your Kickflip Client Key\n * @param secret your Kickflip Client Secret\n * @param cb A callback to be invoked when Kickflip user credentials are available.\n * @return a {@link io.kickflip.sdk.api.KickflipApiClient} used to perform actions on behalf of\n * a {@link io.kickflip.sdk.api.json.User}.\n */\n public static KickflipApiClient setup(Context context, String key, String secret, KickflipCallback cb) {\n sContext = context;\n setApiCredentials(key, secret);\n return getApiClient(context, cb);\n }\n\n private static void setApiCredentials(String key, String secret) {\n sClientKey = key;\n sClientSecret = secret;\n }\n\n /**\n * Start {@link io.kickflip.sdk.activity.BroadcastActivity}. This Activity\n * facilitates control over a single live broadcast.\n * <p/>\n * <b>Must be called after {@link Kickflip#setup(android.content.Context, String, String)} or\n * {@link Kickflip#setup(android.content.Context, String, String, io.kickflip.sdk.api.KickflipCallback)}.</b>\n *\n * @param host the host {@link android.app.Activity} initiating this action\n * @param listener an optional {@link io.kickflip.sdk.av.BroadcastListener} to be notified on\n * broadcast events\n */\n public static void startBroadcastActivity(Activity host, BroadcastListener listener) {\n checkNotNull(listener, host.getString(R.string.error_no_broadcastlistener));\n if (sSessionConfig == null) {\n setupDefaultSessionConfig();\n }\n checkNotNull(sClientKey);\n checkNotNull(sClientSecret);\n sBroadcastListener = listener;\n Intent broadcastIntent = new Intent(host, BroadcastActivity.class);\n broadcastIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);\n host.startActivity(broadcastIntent);\n }\n\n public static void startGlassBroadcastActivity(Activity host, BroadcastListener listener) {\n checkNotNull(listener, host.getString(R.string.error_no_broadcastlistener));\n if (sSessionConfig == null) {\n setupDefaultSessionConfig();\n }\n checkNotNull(sClientKey);\n checkNotNull(sClientSecret);\n sBroadcastListener = listener;\n Log.i(TAG, \"startGlassBA ready? \" + readyToBroadcast());\n Intent broadcastIntent = new Intent(host, GlassBroadcastActivity.class);\n broadcastIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);\n host.startActivity(broadcastIntent);\n }\n\n /**\n * Start {@link io.kickflip.sdk.activity.MediaPlayerActivity}. This Activity\n * facilitates playing back a Kickflip broadcast.\n * <p/>\n * <b>Must be called after {@link Kickflip#setup(android.content.Context, String, String)} or\n * {@link Kickflip#setup(android.content.Context, String, String, io.kickflip.sdk.api.KickflipCallback)}.</b>\n *\n * @param host the host {@link android.app.Activity} initiating this action\n * @param streamUrl a path of format https://kickflip.io/<stream_id> or https://xxx.xxx/xxx.m3u8\n * @param newTask Whether this Activity should be started as part of a new task. If so, when this Activity finishes\n * the host application will be concluded.\n */\n public static void startMediaPlayerActivity(Activity host, String streamUrl, boolean newTask) {\n Intent playbackIntent = new Intent(host, MediaPlayerActivity.class);\n playbackIntent.putExtra(\"mediaUrl\", streamUrl);\n if (newTask) {\n playbackIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);\n }\n host.startActivity(playbackIntent);\n }\n\n /**\n * Convenience method for attaching the current reverse geocoded device location to a given\n * {@link io.kickflip.sdk.api.json.Stream}\n *\n * @param context the host application {@link android.content.Context}\n * @param stream the {@link io.kickflip.sdk.api.json.Stream} to attach location to\n * @param eventBus an {@link com.google.common.eventbus.EventBus} to be notified of the complete action\n */\n public static void addLocationToStream(final Context context, final Stream stream, final EventBus eventBus) {\n DeviceLocation.getLastKnownLocation(context, false, new DeviceLocation.LocationResult() {\n @Override\n public void gotLocation(Location location) {\n stream.setLatitude(location.getLatitude());\n stream.setLongitude(location.getLongitude());\n\n try {\n Geocoder geocoder = new Geocoder(context);\n Address address = geocoder.getFromLocation(location.getLatitude(),\n location.getLongitude(), 1).get(0);\n stream.setCity(address.getLocality());\n stream.setCountry(address.getCountryName());\n stream.setState(address.getAdminArea());\n if (eventBus != null) {\n eventBus.post(new StreamLocationAddedEvent());\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n });\n\n }\n\n /**\n * Get the {@link io.kickflip.sdk.av.BroadcastListener} to be notified on broadcast events.\n */\n public static BroadcastListener getBroadcastListener() {\n return sBroadcastListener;\n }\n\n /**\n * Set a {@link io.kickflip.sdk.av.BroadcastListener} to be notified on broadcast events.\n *\n * @param listener a {@link io.kickflip.sdk.av.BroadcastListener}\n */\n public static void setBroadcastListener(BroadcastListener listener) {\n sBroadcastListener = listener;\n }\n\n /**\n * Get the provided Kickflip Client Key\n *\n * @return the provided Kickflip Client Key\n */\n public static String getApiKey() {\n return sClientKey;\n }\n\n /**\n * Get the provided Kickflip Client Secret\n *\n * @return the provided Kickflip Client Secret\n */\n public static String getApiSecret() {\n return sClientSecret;\n }\n\n /**\n * Return the {@link io.kickflip.sdk.av.SessionConfig} responsible for configuring this broadcast.\n *\n * @return the {@link io.kickflip.sdk.av.SessionConfig} responsible for configuring this broadcast.\n * @hide\n */\n public static SessionConfig getSessionConfig() {\n return sSessionConfig;\n }\n\n /**\n * Clear the current SessionConfig, marking it as in use by a Broadcaster.\n * This is typically safe to do after constructing a Broadcaster, as it will\n * hold reference.\n *\n * @hide\n */\n public static void clearSessionConfig() {\n Log.i(TAG, \"Clearing SessionConfig\");\n sSessionConfig = null;\n }\n\n /**\n * Set the {@link io.kickflip.sdk.av.SessionConfig} responsible for configuring this broadcast.\n *\n * @param config the {@link io.kickflip.sdk.av.SessionConfig} responsible for configuring this broadcast.\n */\n public static void setSessionConfig(SessionConfig config) {\n sSessionConfig = config;\n }\n\n /**\n * Check whether credentials required for broadcast are provided\n *\n * @return true if credentials required for broadcast are provided. false otherwise\n */\n public static boolean readyToBroadcast() {\n return sClientKey != null && sClientSecret != null && sSessionConfig != null;\n }\n\n /**\n * Return whether the given Uri belongs to the kickflip.io authority.\n *\n * @param uri uri to test\n * @return true if the uri is of the kickflip.io authority.\n */\n public static boolean isKickflipUrl(Uri uri) {\n return uri != null && uri.getAuthority().contains(\"kickflip.io\");\n }\n\n /**\n * Given a Kickflip.io url, return the stream id.\n * <p/>\n * e.g: https://kickflip.io/39df392c-4afe-4bf5-9583-acccd8212277/ returns\n * \"39df392c-4afe-4bf5-9583-acccd8212277\"\n *\n * @param uri the uri to test\n * @return the last path segment of the given uri, corresponding to the Kickflip {@link Stream#mStreamId}\n */\n public static String getStreamIdFromKickflipUrl(Uri uri) {\n if (uri == null) throw new IllegalArgumentException(\"uri cannot be null\");\n return uri.getLastPathSegment().toString();\n }\n\n /**\n * Create a new instance of the KickflipApiClient if one hasn't\n * yet been created, or the provided API keys don't match\n * the existing client.\n *\n * @param context the context of the host application\n * @return\n */\n public static KickflipApiClient getApiClient(Context context) {\n return getApiClient(context, null);\n }\n\n /**\n * Create a new instance of the KickflipApiClient if one hasn't\n * yet been created, or the provided API keys don't match\n * the existing client.\n *\n * @param context the context of the host application\n * @param callback an optional callback to be notified with the Kickflip user\n * corresponding to the provided API keys.\n * @return\n */\n public static KickflipApiClient getApiClient(Context context, KickflipCallback callback) {\n checkNotNull(sClientKey);\n checkNotNull(sClientSecret);\n if (sKickflip == null || !sKickflip.getConfig().getClientId().equals(sClientKey)) {\n sKickflip = new KickflipApiClient(context, sClientKey, sClientSecret, callback);\n } else if (callback != null) {\n callback.onSuccess(sKickflip.getActiveUser());\n }\n return sKickflip;\n }\n\n private static void setupDefaultSessionConfig() {\n Log.i(TAG, \"Setting default SessonConfig\");\n checkNotNull(sContext);\n String outputLocation = new File(sContext.getFilesDir(), \"index.m3u8\").getAbsolutePath();\n Kickflip.setSessionConfig(new SessionConfig.Builder(outputLocation)\n .withVideoBitrate(100 * 1000)\n .withPrivateVisibility(false)\n .withLocation(true)\n .withVideoResolution(720, 480)\n .build());\n }\n\n /**\n * Returns whether the current device is running Android 4.4, KitKat, or newer\n *\n * KitKat is required for certain Kickflip features like Adaptive bitrate streaming\n */\n public static boolean isKitKat() {\n return Build.VERSION.SDK_INT >= 19;\n }\n\n}",
"public class Broadcaster extends AVRecorder {\n private static final String TAG = \"Broadcaster\";\n private static final boolean VERBOSE = false;\n private static final int MIN_BITRATE = 3 * 100 * 1000; // 300 kbps\n private final String VOD_FILENAME = \"vod.m3u8\";\n private Context mContext;\n private KickflipApiClient mKickflip;\n private User mUser;\n private HlsStream mStream;\n private HlsFileObserver mFileObserver;\n private S3BroadcastManager mS3Manager;\n private ArrayDeque<Pair<String, File>> mUploadQueue;\n private SessionConfig mConfig;\n private BroadcastListener mBroadcastListener;\n private EventBus mEventBus;\n private boolean mReadyToBroadcast; // Kickflip user registered and endpoint ready\n private boolean mSentBroadcastLiveEvent;\n private int mVideoBitrate;\n private File mManifestSnapshotDir; // Directory where manifest snapshots are stored\n private File mVodManifest; // VOD HLS Manifest containing complete history\n private int mNumSegmentsWritten;\n private int mLastRealizedBandwidthBytesPerSec; // Bandwidth snapshot for adapting bitrate\n private boolean mDeleteAfterUploading; // Should recording files be deleted as they're uploaded?\n private ObjectMetadata mS3ManifestMeta;\n\n\n /**\n * Construct a Broadcaster with Session settings and Kickflip credentials\n *\n * @param context the host application {@link android.content.Context}.\n * @param config the Session configuration. Specifies bitrates, resolution etc.\n * @param CLIENT_ID the Client ID available from your Kickflip.io dashboard.\n * @param CLIENT_SECRET the Client Secret available from your Kickflip.io dashboard.\n */\n public Broadcaster(Context context, SessionConfig config, String CLIENT_ID, String CLIENT_SECRET) throws IOException {\n super(config);\n checkArgument(CLIENT_ID != null && CLIENT_SECRET != null);\n init();\n mContext = context;\n mConfig = config;\n mConfig.getMuxer().setEventBus(mEventBus);\n mVideoBitrate = mConfig.getVideoBitrate();\n if (VERBOSE) Log.i(TAG, \"Initial video bitrate : \" + mVideoBitrate);\n mManifestSnapshotDir = new File(mConfig.getOutputPath().substring(0, mConfig.getOutputPath().lastIndexOf(\"/\") + 1), \"m3u8\");\n mManifestSnapshotDir.mkdir();\n mVodManifest = new File(mManifestSnapshotDir, VOD_FILENAME);\n writeEventManifestHeader(mConfig.getHlsSegmentDuration());\n\n String watchDir = config.getOutputDirectory().getAbsolutePath();\n mFileObserver = new HlsFileObserver(watchDir, mEventBus);\n mFileObserver.startWatching();\n if (VERBOSE) Log.i(TAG, \"Watching \" + watchDir);\n\n mReadyToBroadcast = false;\n mKickflip = Kickflip.setup(context, CLIENT_ID, CLIENT_SECRET, new KickflipCallback() {\n @Override\n public void onSuccess(Response response) {\n User user = (User) response;\n mUser = user;\n if (VERBOSE) Log.i(TAG, \"Got storage credentials \" + response);\n }\n\n @Override\n public void onError(KickflipException error) {\n Log.e(TAG, \"Failed to get storage credentials\" + error.toString());\n if (mBroadcastListener != null)\n mBroadcastListener.onBroadcastError(error);\n }\n });\n }\n\n private void init() {\n mDeleteAfterUploading = true;\n mLastRealizedBandwidthBytesPerSec = 0;\n mNumSegmentsWritten = 0;\n mSentBroadcastLiveEvent = false;\n mEventBus = new EventBus(\"Broadcaster\");\n mEventBus.register(this);\n }\n\n /**\n * Set whether local recording files be deleted after successful upload. Default is true.\n * <p/>\n * Must be called before recording begins. Otherwise this method has no effect.\n *\n * @param doDelete whether local recording files be deleted after successful upload.\n */\n public void setDeleteLocalFilesAfterUpload(boolean doDelete) {\n if (!isRecording()) {\n mDeleteAfterUploading = doDelete;\n }\n }\n\n /**\n * Set a Listener to be notified of basic Broadcast events relevant to\n * updating a broadcasting UI.\n * e.g: Broadcast begun, went live, stopped, or encountered an error.\n * <p/>\n * See {@link io.kickflip.sdk.av.BroadcastListener}\n *\n * @param listener\n */\n public void setBroadcastListener(BroadcastListener listener) {\n mBroadcastListener = listener;\n }\n\n /**\n * Set an {@link com.google.common.eventbus.EventBus} to be notified\n * of events between {@link io.kickflip.sdk.av.Broadcaster},\n * {@link io.kickflip.sdk.av.HlsFileObserver}, {@link io.kickflip.sdk.api.s3.S3BroadcastManager}\n * e.g: A HLS MPEG-TS segment or .m3u8 Manifest was written to disk, or uploaded.\n * See a list of events in {@link io.kickflip.sdk.event}\n *\n * @return\n */\n public EventBus getEventBus() {\n return mEventBus;\n }\n\n /**\n * Start broadcasting.\n * <p/>\n * Must be called after {@link Broadcaster#setPreviewDisplay(io.kickflip.sdk.view.GLCameraView)}\n */\n @Override\n public void startRecording() {\n super.startRecording();\n mKickflip.startStream(mConfig.getStream(), new KickflipCallback() {\n @Override\n public void onSuccess(Response response) {\n mCamEncoder.requestThumbnailOnDeltaFrameWithScaling(10, 1);\n Log.i(TAG, \"got StartStreamResponse\");\n checkArgument(response instanceof HlsStream, \"Got unexpected StartStream Response\");\n onGotStreamResponse((HlsStream) response);\n }\n\n @Override\n public void onError(KickflipException error) {\n Log.w(TAG, \"Error getting start stream response! \" + error);\n }\n });\n }\n\n private void onGotStreamResponse(HlsStream stream) {\n mStream = stream;\n if (mConfig.shouldAttachLocation()) {\n Kickflip.addLocationToStream(mContext, mStream, mEventBus);\n }\n mStream.setTitle(mConfig.getTitle());\n mStream.setDescription(mConfig.getDescription());\n mStream.setExtraInfo(mConfig.getExtraInfo());\n mStream.setIsPrivate(mConfig.isPrivate());\n if (VERBOSE) Log.i(TAG, \"Got hls start stream \" + stream);\n mS3Manager = new S3BroadcastManager(this,\n new BasicSessionCredentials(mStream.getAwsKey(), mStream.getAwsSecret(), mStream.getToken()));\n mS3Manager.setRegion(mStream.getRegion());\n mS3Manager.addRequestInterceptor(mS3RequestInterceptor);\n mReadyToBroadcast = true;\n submitQueuedUploadsToS3();\n mEventBus.post(new BroadcastIsBufferingEvent());\n if (mBroadcastListener != null) {\n mBroadcastListener.onBroadcastStart();\n }\n }\n\n /**\n * Check if the broadcast has gone live\n *\n * @return\n */\n public boolean isLive() {\n return mSentBroadcastLiveEvent;\n }\n\n /**\n * Stop broadcasting and release resources.\n * After this call this Broadcaster can no longer be used.\n */\n @Override\n public void stopRecording() {\n super.stopRecording();\n mSentBroadcastLiveEvent = false;\n if (mStream != null) {\n if (VERBOSE) Log.i(TAG, \"Stopping Stream\");\n mKickflip.stopStream(mStream, new KickflipCallback() {\n @Override\n public void onSuccess(Response response) {\n if (VERBOSE) Log.i(TAG, \"Got stop stream response \" + response);\n }\n\n @Override\n public void onError(KickflipException error) {\n Log.w(TAG, \"Error getting stop stream response! \" + error);\n }\n });\n }\n }\n\n /**\n * A .ts file was written in the recording directory.\n * <p/>\n * Use this opportunity to verify the segment is of expected size\n * given the target bitrate\n * <p/>\n * Called on a background thread\n */\n @Subscribe\n public void onSegmentWritten(HlsSegmentWrittenEvent event) {\n try {\n File hlsSegment = event.getSegment();\n queueOrSubmitUpload(keyForFilename(hlsSegment.getName()), hlsSegment);\n if (isKitKat() && mConfig.isAdaptiveBitrate() && isRecording()) {\n // Adjust bitrate to match expected filesize\n long actualSegmentSizeBytes = hlsSegment.length();\n long expectedSizeBytes = ((mConfig.getAudioBitrate() / 8) + (mVideoBitrate / 8)) * mConfig.getHlsSegmentDuration();\n float filesizeRatio = actualSegmentSizeBytes / (float) expectedSizeBytes;\n if (VERBOSE)\n Log.i(TAG, \"OnSegmentWritten. Segment size: \" + (actualSegmentSizeBytes / 1000) + \"kB. ratio: \" + filesizeRatio);\n if (filesizeRatio < .7) {\n if (mLastRealizedBandwidthBytesPerSec != 0) {\n // Scale bitrate while not exceeding available bandwidth\n float scaledBitrate = mVideoBitrate * (1 / filesizeRatio);\n float bandwidthBitrate = mLastRealizedBandwidthBytesPerSec * 8;\n mVideoBitrate = (int) Math.min(scaledBitrate, bandwidthBitrate);\n } else {\n // Scale bitrate to match expected fileSize\n mVideoBitrate *= (1 / filesizeRatio);\n }\n if (VERBOSE) Log.i(TAG, \"Scaling video bitrate to \" + mVideoBitrate + \" bps\");\n adjustVideoBitrate(mVideoBitrate);\n }\n }\n } catch (Exception ex) {\n ex.printStackTrace();\n }\n }\n\n /**\n * An S3 .ts segment upload completed.\n * <p/>\n * Use this opportunity to adjust bitrate based on the bandwidth\n * measured during this segment's transmission.\n * <p/>\n * Called on a background thread\n */\n private void onSegmentUploaded(S3UploadEvent uploadEvent) {\n if (mDeleteAfterUploading) {\n boolean deletedFile = uploadEvent.getFile().delete();\n if (VERBOSE)\n Log.i(TAG, \"Deleting uploaded segment. \" + uploadEvent.getFile().getAbsolutePath() + \" Succcess: \" + deletedFile);\n }\n try {\n if (isKitKat() && mConfig.isAdaptiveBitrate() && isRecording()) {\n mLastRealizedBandwidthBytesPerSec = uploadEvent.getUploadByteRate();\n // Adjust video encoder bitrate per bandwidth of just-completed upload\n if (VERBOSE) {\n Log.i(TAG, \"Bandwidth: \" + (mLastRealizedBandwidthBytesPerSec / 1000.0) + \" kBps. Encoder: \" + ((mVideoBitrate + mConfig.getAudioBitrate()) / 8) / 1000.0 + \" kBps\");\n }\n if (mLastRealizedBandwidthBytesPerSec < (((mVideoBitrate + mConfig.getAudioBitrate()) / 8))) {\n // The new bitrate is equal to the last upload bandwidth, never inferior to MIN_BITRATE, nor superior to the initial specified bitrate\n mVideoBitrate = Math.max(Math.min(mLastRealizedBandwidthBytesPerSec * 8, mConfig.getVideoBitrate()), MIN_BITRATE);\n if (VERBOSE) {\n Log.i(TAG, String.format(\"Adjusting video bitrate to %f kBps. Bandwidth: %f kBps\",\n mVideoBitrate / (8 * 1000.0), mLastRealizedBandwidthBytesPerSec / 1000.0));\n }\n adjustVideoBitrate(mVideoBitrate);\n }\n }\n } catch (Exception e) {\n Log.i(TAG, \"OnSegUpload excep\");\n e.printStackTrace();\n }\n }\n\n /**\n * A .m3u8 file was written in the recording directory.\n * <p/>\n * Called on a background thread\n */\n @Subscribe\n public void onManifestUpdated(HlsManifestWrittenEvent e) {\n if (!isRecording()) {\n if (Kickflip.getBroadcastListener() != null) {\n if (VERBOSE) Log.i(TAG, \"Sending onBroadcastStop\");\n Kickflip.getBroadcastListener().onBroadcastStop();\n }\n }\n if (VERBOSE) Log.i(TAG, \"onManifestUpdated. Last segment? \" + !isRecording());\n // Copy m3u8 at this moment and queue it to uploading\n // service\n final File copy = new File(mManifestSnapshotDir, e.getManifestFile().getName()\n .replace(\".m3u8\", \"_\" + mNumSegmentsWritten + \".m3u8\"));\n try {\n if (VERBOSE)\n Log.i(TAG, \"Copying \" + e.getManifestFile().getAbsolutePath() + \" to \" + copy.getAbsolutePath());\n FileUtils.copy(e.getManifestFile(), copy);\n queueOrSubmitUpload(keyForFilename(\"index.m3u8\"), copy);\n appendLastManifestEntryToEventManifest(copy, !isRecording());\n } catch (IOException e1) {\n Log.e(TAG, \"Failed to copy manifest file. Upload of this manifest cannot proceed. Stream will have a discontinuity!\");\n e1.printStackTrace();\n }\n\n mNumSegmentsWritten++;\n }\n\n /**\n * An S3 .m3u8 upload completed.\n * <p/>\n * Called on a background thread\n */\n private void onManifestUploaded(S3UploadEvent uploadEvent) {\n if (mDeleteAfterUploading) {\n if (VERBOSE) Log.i(TAG, \"Deleting \" + uploadEvent.getFile().getAbsolutePath());\n uploadEvent.getFile().delete();\n String uploadUrl = uploadEvent.getDestinationUrl();\n if (uploadUrl.substring(uploadUrl.lastIndexOf(File.separator) + 1).equals(\"vod.m3u8\")) {\n if (VERBOSE) Log.i(TAG, \"Deleting \" + mConfig.getOutputDirectory());\n mFileObserver.stopWatching();\n FileUtils.deleteDirectory(mConfig.getOutputDirectory());\n }\n }\n if (!mSentBroadcastLiveEvent) {\n mEventBus.post(new BroadcastIsLiveEvent(((HlsStream) mStream).getKickflipUrl()));\n mSentBroadcastLiveEvent = true;\n if (mBroadcastListener != null)\n mBroadcastListener.onBroadcastLive(mStream);\n }\n }\n\n /**\n * A thumbnail was written in the recording directory.\n * <p/>\n * Called on a background thread\n */\n @Subscribe\n public void onThumbnailWritten(ThumbnailWrittenEvent e) {\n try {\n queueOrSubmitUpload(keyForFilename(\"thumb.jpg\"), e.getThumbnailFile());\n } catch (Exception ex) {\n Log.i(TAG, \"Error writing thumbanil\");\n ex.printStackTrace();\n }\n }\n\n /**\n * A thumbnail upload completed.\n * <p/>\n * Called on a background thread\n */\n private void onThumbnailUploaded(S3UploadEvent uploadEvent) {\n if (mDeleteAfterUploading) uploadEvent.getFile().delete();\n if (mStream != null) {\n mStream.setThumbnailUrl(uploadEvent.getDestinationUrl());\n sendStreamMetaData();\n }\n }\n\n @Subscribe\n public void onStreamLocationAdded(StreamLocationAddedEvent event) {\n sendStreamMetaData();\n }\n\n @Subscribe\n public void onDeadEvent(DeadEvent e) {\n if (VERBOSE) Log.i(TAG, \"DeadEvent \");\n }\n\n\n @Subscribe\n public void onMuxerFinished(MuxerFinishedEvent e) {\n // TODO: Broadcaster uses AVRecorder reset()\n // this seems better than nulling and recreating Broadcaster\n // since it should be usable as a static object for\n // bg recording\n }\n\n private void sendStreamMetaData() {\n if (mStream != null) {\n mKickflip.setStreamInfo(mStream, null);\n }\n }\n\n /**\n * Construct an S3 Key for a given filename\n *\n */\n private String keyForFilename(String fileName) {\n return mStream.getAwsS3Prefix() + fileName;\n }\n\n /**\n * Handle an upload, either submitting to the S3 client\n * or queueing for submission once credentials are ready\n *\n * @param key destination key\n * @param file local file\n */\n private void queueOrSubmitUpload(String key, File file) {\n if (mReadyToBroadcast) {\n submitUpload(key, file);\n } else {\n if (VERBOSE) Log.i(TAG, \"queueing \" + key + \" until S3 Credentials available\");\n queueUpload(key, file);\n }\n }\n\n /**\n * Queue an upload for later submission to S3\n *\n * @param key destination key\n * @param file local file\n */\n private void queueUpload(String key, File file) {\n if (mUploadQueue == null)\n mUploadQueue = new ArrayDeque<>();\n mUploadQueue.add(new Pair<>(key, file));\n }\n\n /**\n * Submit all queued uploads to the S3 client\n */\n private void submitQueuedUploadsToS3() {\n if (mUploadQueue == null) return;\n for (Pair<String, File> pair : mUploadQueue) {\n submitUpload(pair.first, pair.second);\n }\n }\n\n private void submitUpload(final String key, final File file) {\n submitUpload(key, file, false);\n }\n\n private void submitUpload(final String key, final File file, boolean lastUpload) {\n mS3Manager.queueUpload(mStream.getAwsS3Bucket(), key, file, lastUpload);\n }\n\n /**\n * An S3 Upload completed.\n * <p/>\n * Called on a background thread\n */\n public void onS3UploadComplete(S3UploadEvent uploadEvent) {\n if (VERBOSE) Log.i(TAG, \"Upload completed for \" + uploadEvent.getDestinationUrl());\n if (uploadEvent.getDestinationUrl().contains(\".m3u8\")) {\n onManifestUploaded(uploadEvent);\n } else if (uploadEvent.getDestinationUrl().contains(\".ts\")) {\n onSegmentUploaded(uploadEvent);\n } else if (uploadEvent.getDestinationUrl().contains(\".jpg\")) {\n onThumbnailUploaded(uploadEvent);\n }\n }\n\n public SessionConfig getSessionConfig() {\n return mConfig;\n }\n\n private void writeEventManifestHeader(int targetDuration) {\n FileUtils.writeStringToFile(\n String.format(\"#EXTM3U\\n\" +\n \"#EXT-X-PLAYLIST-TYPE:VOD\\n\" +\n \"#EXT-X-VERSION:3\\n\" +\n \"#EXT-X-MEDIA-SEQUENCE:0\\n\" +\n \"#EXT-X-TARGETDURATION:%d\\n\", targetDuration + 1),\n mVodManifest, false\n );\n }\n\n private void appendLastManifestEntryToEventManifest(File sourceManifest, boolean lastEntry) {\n String result = FileUtils.tail2(sourceManifest, lastEntry ? 3 : 2);\n FileUtils.writeStringToFile(result, mVodManifest, true);\n if (lastEntry) {\n submitUpload(keyForFilename(\"vod.m3u8\"), mVodManifest, true);\n if (VERBOSE) Log.i(TAG, \"Queued master manifest \" + mVodManifest.getAbsolutePath());\n }\n }\n\n S3BroadcastManager.S3RequestInterceptor mS3RequestInterceptor = new S3BroadcastManager.S3RequestInterceptor() {\n @Override\n public void interceptRequest(PutObjectRequest request) {\n if (request.getKey().contains(\"index.m3u8\")) {\n if (mS3ManifestMeta == null) {\n mS3ManifestMeta = new ObjectMetadata();\n mS3ManifestMeta.setCacheControl(\"max-age=0\");\n }\n request.setMetadata(mS3ManifestMeta);\n }\n }\n };\n\n}",
"public class BroadcastIsBufferingEvent extends BroadcastEvent {\n}",
"public class BroadcastIsLiveEvent extends BroadcastEvent {\n\n private String mWatchUrl;\n\n public BroadcastIsLiveEvent(String watchurl) {\n super();\n mWatchUrl = watchurl;\n }\n\n public String getWatchUrl(){\n return mWatchUrl;\n }\n\n}",
"public class GLCameraEncoderView extends GLCameraView {\n private static final String TAG = \"GLCameraEncoderView\";\n\n protected CameraEncoder mCameraEncoder;\n\n public GLCameraEncoderView(Context context) {\n super(context);\n }\n\n public GLCameraEncoderView(Context context, AttributeSet attrs) {\n super(context, attrs);\n }\n\n public void setCameraEncoder(CameraEncoder encoder){\n mCameraEncoder = encoder;\n setCamera(mCameraEncoder.getCamera());\n }\n\n @Override\n public boolean onTouchEvent(MotionEvent ev) {\n if(mScaleGestureDetector != null){\n mScaleGestureDetector.onTouchEvent(ev);\n }\n if(mCameraEncoder != null && ev.getPointerCount() == 1 && (ev.getAction() == MotionEvent.ACTION_MOVE)){\n mCameraEncoder.handleCameraPreviewTouchEvent(ev);\n }else if(mCameraEncoder != null && ev.getPointerCount() == 1 && (ev.getAction() == MotionEvent.ACTION_DOWN)){\n mCameraEncoder.handleCameraPreviewTouchEvent(ev);\n }\n return true;\n }\n\n\n}"
] | import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.TextView;
import com.google.common.eventbus.Subscribe;
import java.io.IOException;
import io.kickflip.sdk.Kickflip;
import io.kickflip.sdk.R;
import io.kickflip.sdk.av.Broadcaster;
import io.kickflip.sdk.event.BroadcastIsBufferingEvent;
import io.kickflip.sdk.event.BroadcastIsLiveEvent;
import io.kickflip.sdk.view.GLCameraEncoderView; | package io.kickflip.sdk.fragment;
/**
* This is a drop-in broadcasting fragment.
* Currently, only one BroadcastFragment may be instantiated at a time by
* design of {@link io.kickflip.sdk.av.Broadcaster}.
*/
public class GlassBroadcastFragment extends Fragment {
private static final String TAG = "GlassBroadcastFragment";
private static final boolean VERBOSE = false;
private static GlassBroadcastFragment mFragment;
private static Broadcaster mBroadcaster; // Make static to survive Fragment re-creation | private GLCameraEncoderView mCameraView; | 4 |
TeamAmeriFrance/Guide-API | src/main/java/amerifrance/guideapi/api/IPage.java | [
"public class Book {\n\n private static final String GUITEXLOC = \"guideapi:textures/gui/\";\n\n private List<CategoryAbstract> categories = Lists.newArrayList();\n private String title = \"item.GuideBook.name\";\n private String header = title;\n private String itemName = title;\n private String author;\n private ResourceLocation pageTexture = new ResourceLocation(GUITEXLOC + \"book_colored.png\");\n private ResourceLocation outlineTexture = new ResourceLocation(GUITEXLOC + \"book_greyscale.png\");\n private boolean customModel;\n private Color color = new Color(171, 70, 30);\n private boolean spawnWithBook;\n private ResourceLocation registryName;\n private CreativeTabs creativeTab = CreativeTabs.MISC;\n\n /**\n * @deprecated see {@link BookBinder}. To be made package private in 1.13.\n */\n @Deprecated\n public Book(List<CategoryAbstract> categoryList, String title, String header, String displayName, String author, ResourceLocation pageTexture, ResourceLocation outlineTexture, boolean customModel, Color color, boolean spawnWithBook, ResourceLocation registryName, CreativeTabs creativeTab) {\n this.categories = categoryList;\n this.title = title;\n this.header = header;\n this.itemName = displayName;\n this.author = author;\n this.pageTexture = pageTexture;\n this.outlineTexture = outlineTexture;\n this.customModel = customModel;\n this.color = color;\n this.spawnWithBook = spawnWithBook;\n this.registryName = registryName;\n this.creativeTab = creativeTab;\n }\n\n /**\n * @deprecated see {@link BookBinder}. To be removed in 1.13.\n */\n @Deprecated\n public Book() {\n }\n\n public List<CategoryAbstract> getCategoryList() {\n return this.categories;\n }\n\n public String getTitle() {\n return this.title;\n }\n\n public String getItemName() {\n return this.itemName;\n }\n\n public String getHeader() {\n return this.header;\n }\n\n public String getAuthor() {\n return this.author;\n }\n\n public ResourceLocation getPageTexture() {\n return this.pageTexture;\n }\n\n public ResourceLocation getOutlineTexture() {\n return this.outlineTexture;\n }\n\n public boolean hasCustomModel() {\n return this.customModel;\n }\n\n public Color getColor() {\n return this.color;\n }\n\n public boolean shouldSpawnWithBook() {\n return this.spawnWithBook;\n }\n\n public ResourceLocation getRegistryName() {\n return this.registryName;\n }\n\n public CreativeTabs getCreativeTab() {\n return this.creativeTab;\n }\n\n /**\n * @deprecated see {@link #getItemName()}. To be removed in 1.13.\n */\n @Deprecated\n public String getDisplayName() {\n return this.itemName;\n }\n\n /**\n * @deprecated see {@link #getHeader()}. To be removed in 1.13.\n */\n @Deprecated\n public String getWelcomeMessage() {\n return this.header;\n }\n\n /**\n * @deprecated see {@link #hasCustomModel()}. To be removed in 1.13.\n */\n @Deprecated\n public boolean isCustomModel() {\n return this.customModel;\n }\n\n /**\n * @deprecated see {@link #shouldSpawnWithBook()}. To be removed in 1.13.\n */\n @Deprecated\n public boolean isSpawnWithBook() {\n return this.spawnWithBook;\n }\n\n /**\n * @deprecated see {@link BookBinder#addCategory(CategoryAbstract)}. To be removed in 1.13.\n */\n @Deprecated\n public void setCategoryList(List<CategoryAbstract> categoryList) {\n this.categories = categoryList;\n }\n\n /**\n * @deprecated see {@link BookBinder#setGuideTitle(String)}. To be removed in 1.13.\n */\n @Deprecated\n public void setTitle(String title) {\n this.title = title;\n }\n\n /**\n * @deprecated see {@link BookBinder#setHeader(String)}. To be removed in 1.13.\n */\n @Deprecated\n public void setWelcomeMessage(String header) {\n this.header = header;\n }\n\n /**\n * @deprecated see {@link BookBinder#setItemName(String)}. To be removed in 1.13.\n */\n @Deprecated\n public void setDisplayName(String displayName) {\n this.itemName = displayName;\n }\n\n /**\n * @deprecated see {@link BookBinder#setAuthor(String)}. To be removed in 1.13.\n */\n @Deprecated\n public void setAuthor(String author) {\n this.author = author;\n }\n\n /**\n * @deprecated see {@link BookBinder#setSpawnWithBook()}. To be removed in 1.13.\n */\n @Deprecated\n public void setSpawnWithBook(boolean spawnWithBook) {\n this.spawnWithBook = spawnWithBook;\n }\n\n /**\n * @deprecated see {@link BookBinder#setPageTexture(ResourceLocation)}. To be removed in 1.13.\n */\n @Deprecated\n public void setPageTexture(ResourceLocation pageTexture) {\n this.pageTexture = pageTexture;\n }\n\n /**\n * @deprecated see {@link BookBinder#setOutlineTexture(ResourceLocation)}. To be removed in 1.13.\n */\n @Deprecated\n public void setOutlineTexture(ResourceLocation outlineTexture) {\n this.outlineTexture = outlineTexture;\n }\n\n /**\n * @deprecated see {@link BookBinder#setHasCustomModel()}. To be removed in 1.13.\n */\n @Deprecated\n public void setCustomModel(boolean customModel) {\n this.customModel = customModel;\n }\n\n /**\n * @deprecated see {@link BookBinder#setColor(int)}. To be removed in 1.13.\n */\n @Deprecated\n public void setColor(Color color) {\n this.color = color;\n }\n\n /**\n * @deprecated see {@link BookBinder#BookBinder(ResourceLocation)}. To be removed in 1.13.\n */\n @Deprecated\n public void setRegistryName(ResourceLocation registryName) {\n this.registryName = registryName;\n }\n\n /**\n * @deprecated see {@link BookBinder#setCreativeTab(CreativeTabs)}. To be removed in 1.13.\n */\n @Deprecated\n public void setCreativeTab(CreativeTabs creativeTab) {\n this.creativeTab = creativeTab;\n }\n\n /**\n * @deprecated see {@link BookBinder#addCategory(CategoryAbstract)}. To be removed in 1.13.\n *\n * @param category - Add this category\n */\n @Deprecated\n public void addCategory(CategoryAbstract category) {\n this.categories.add(category);\n }\n\n /**\n * @deprecated see {@link BookBinder}. To be removed in 1.13.\n *\n * @param category - Remove this category\n */\n @Deprecated\n public void removeCategory(CategoryAbstract category) {\n this.categories.remove(category);\n }\n\n /**\n * @deprecated see {@link BookBinder#addCategory(CategoryAbstract)}. To be removed in 1.13.\n *\n * @param categories - Add these categories\n */\n @Deprecated\n public void addCategoryList(List<CategoryAbstract> categories) {\n this.categories.addAll(categories);\n }\n\n /**\n * @deprecated see {@link BookBinder}. To be removed in 1.13.\n *\n * @param categories - Remove these categories\n */\n @Deprecated\n public void removeCategoryList(List<CategoryAbstract> categories) {\n this.categories.removeAll(categories);\n }\n\n /**\n * @deprecated localize yourself with {@link #getTitle()}. To be removed in 1.13.\n *\n * @return - Localized book title\n */\n @Deprecated\n public String getLocalizedBookTitle() {\n return TextHelper.localizeEffect(getTitle());\n }\n\n /**\n * @deprecated localize yourself with {@link #getHeader()}. To be removed in 1.13.\n *\n * @return - Localized welcome message\n */\n @Deprecated\n public String getLocalizedWelcomeMessage() {\n return TextHelper.localizeEffect(getHeader());\n }\n\n /**\n * @deprecated localize yourself with {@link #getDisplayName()}. To be removed in 1.13.\n *\n * @return - Localized item display name\n */\n @Deprecated\n public String getLocalizedDisplayName() {\n return TextHelper.localize(getDisplayName());\n }\n\n @Override\n public String toString() {\n return new ToStringBuilder(this)\n .append(\"categoryList\", Joiner.on(\", \").join(categories))\n .append(\"title\", title)\n .append(\"header\", header)\n .append(\"itemName\", itemName)\n .append(\"author\", author)\n .append(\"pageTexture\", pageTexture)\n .append(\"outlineTexture\", outlineTexture)\n .append(\"customModel\", customModel)\n .append(\"color\", color)\n .append(\"spawnWithBook\", spawnWithBook)\n .append(\"registryName\", registryName)\n .append(\"creativeTab\", creativeTab)\n .toString();\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n\n Book book = (Book) o;\n\n return getRegistryName().equals(book.getRegistryName());\n\n }\n\n @Override\n public int hashCode() {\n return getRegistryName().hashCode();\n }\n}",
"public abstract class CategoryAbstract {\n\n public final Map<ResourceLocation, EntryAbstract> entries;\n public final String name;\n private String keyBase;\n\n public CategoryAbstract(Map<ResourceLocation, EntryAbstract> entries, String name) {\n this.entries = entries;\n this.name = name;\n }\n\n public CategoryAbstract(String name) {\n this(Maps.<ResourceLocation, EntryAbstract>newLinkedHashMap(), name);\n }\n\n /**\n * Adds an entry to this category.\n *\n * @param key - The key of the entry to add.\n * @param entry - The entry to add.\n */\n public void addEntry(ResourceLocation key, EntryAbstract entry) {\n entries.put(key, entry);\n }\n\n /**\n * Adds an entry to this category.\n * <p>\n * Shorthand of {@link #addEntry(ResourceLocation, EntryAbstract)}. Requires {@link #withKeyBase(String)} to have been called.\n *\n * @param key - The key of the entry to add.\n * @param entry - The entry to add.\n */\n public void addEntry(String key, EntryAbstract entry) {\n if (Strings.isNullOrEmpty(keyBase))\n throw new RuntimeException(\"keyBase in category with name '\" + name + \"' must be set.\");\n\n addEntry(new ResourceLocation(keyBase, key), entry);\n }\n\n public void removeEntry(ResourceLocation key) {\n entries.remove(key);\n }\n\n public void addEntries(Map<ResourceLocation, EntryAbstract> entries) {\n this.entries.putAll(entries);\n }\n\n public void removeEntries(List<ResourceLocation> keys) {\n for (ResourceLocation key : keys)\n if (entries.containsKey(key))\n entries.remove(key);\n }\n\n /**\n * Obtains an entry from this category.\n * <p>\n * This <i>can</i> be null, however it is not marked as nullable to avoid annoying IDE warnings. I am making the\n * assumption that this will only be called while creating the book and thus the caller knows it exists.\n * <p>\n * If you are calling at any other time, make sure to nullcheck this.\n *\n * @param key - The key of the entry to obtain.\n * @return the found entry.\n */\n public EntryAbstract getEntry(ResourceLocation key) {\n return entries.get(key);\n }\n\n /**\n * Obtains an entry from this category.\n * <p>\n * Shorthand of {@link #getEntry(ResourceLocation)}. Requires {@link #withKeyBase(String)} to have been called.\n * <p>\n * This <i>can</i> be null, however it is not marked as nullable to avoid annoying IDE warnings. I am making the\n * assumption that this will only be called while creating the book and thus the caller knows it exists.\n * <p>\n * If you are calling at any other time, make sure to nullcheck this.\n *\n * @param key - The key of the entry to obtain.\n * @return the found entry.\n */\n public EntryAbstract getEntry(String key) {\n if (Strings.isNullOrEmpty(keyBase))\n throw new RuntimeException(\"keyBase in category with name '\" + name + \"' must be set.\");\n\n return getEntry(new ResourceLocation(keyBase, key));\n }\n\n /**\n * Sets the domain to use for all ResourceLocation keys passed through {@link #getEntry(String)} and\n * {@link #addEntry(String, EntryAbstract)}\n * <p>\n * Required in order to use those.\n *\n * @param keyBase - The base domain for this entry.\n * @return self for chaining.\n */\n public CategoryAbstract withKeyBase(String keyBase) {\n this.keyBase = keyBase;\n return this;\n }\n\n /**\n * Obtains a localized copy of this category's name.\n *\n * @return a localized copy of this category's name.\n */\n public String getLocalizedName() {\n return TextHelper.localizeEffect(name);\n }\n\n public List<String> getTooltip() {\n return Lists.newArrayList(getLocalizedName());\n }\n\n @SideOnly(Side.CLIENT)\n public abstract void draw(Book book, int categoryX, int categoryY, int categoryWidth, int categoryHeight, int mouseX, int mouseY, GuiBase guiBase, boolean drawOnLeft, RenderItem renderItem);\n\n @SideOnly(Side.CLIENT)\n public abstract void drawExtras(Book book, int categoryX, int categoryY, int categoryWidth, int categoryHeight, int mouseX, int mouseY, GuiBase guiBase, boolean drawOnLeft, RenderItem renderItem);\n\n public abstract boolean canSee(EntityPlayer player, ItemStack bookStack);\n\n @SideOnly(Side.CLIENT)\n public abstract void onLeftClicked(Book book, int mouseX, int mouseY, EntityPlayer player, ItemStack bookStack);\n\n @SideOnly(Side.CLIENT)\n public abstract void onRightClicked(Book book, int mouseX, int mouseY, EntityPlayer player, ItemStack bookStack);\n\n @SideOnly(Side.CLIENT)\n public abstract void onInit(Book book, GuiHome guiHome, EntityPlayer player, ItemStack bookStack);\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n\n CategoryAbstract that = (CategoryAbstract) o;\n if (entries != null ? !entries.equals(that.entries) : that.entries != null) return false;\n if (name != null ? !name.equals(that.name) : that.name != null)\n return false;\n\n return true;\n }\n\n @Override\n public int hashCode() {\n int result = entries != null ? entries.hashCode() : 0;\n result = 31 * result + (name != null ? name.hashCode() : 0);\n return result;\n }\n}",
"public abstract class EntryAbstract {\n\n public final List<IPage> pageList;\n public final String name;\n public boolean unicode;\n\n public EntryAbstract(List<IPage> pageList, String name, boolean unicode) {\n this.pageList = pageList;\n this.name = name;\n this.unicode = unicode;\n }\n\n public EntryAbstract(List<IPage> pageList, String name) {\n this(pageList, name, false);\n }\n\n public EntryAbstract(String name, boolean unicode) {\n this(Lists.<IPage>newArrayList(), name, unicode);\n }\n\n public EntryAbstract(String name) {\n this(name, false);\n }\n\n public void addPage(IPage page) {\n this.pageList.add(page);\n }\n\n public void removePage(IPage page) {\n this.pageList.remove(page);\n }\n\n public void addPageList(List<IPage> pages) {\n this.pageList.addAll(pages);\n }\n\n public void removePageList(List<IPage> pages) {\n this.pageList.removeAll(pages);\n }\n\n public String getLocalizedName() {\n return TextHelper.localizeEffect(name);\n }\n\n @SideOnly(Side.CLIENT)\n public abstract void draw(Book book, CategoryAbstract category, int entryX, int entryY, int entryWidth, int entryHeight, int mouseX, int mouseY, GuiBase guiBase, FontRenderer renderer);\n\n @SideOnly(Side.CLIENT)\n public abstract void drawExtras(Book book, CategoryAbstract category, int entryX, int entryY, int entryWidth, int entryHeight, int mouseX, int mouseY, GuiBase guiBase, FontRenderer renderer);\n\n public abstract boolean canSee(EntityPlayer player, ItemStack bookStack);\n\n @SideOnly(Side.CLIENT)\n public abstract void onLeftClicked(Book book, CategoryAbstract category, int mouseX, int mouseY, EntityPlayer player, GuiCategory guiCategory);\n\n @SideOnly(Side.CLIENT)\n public abstract void onRightClicked(Book book, CategoryAbstract category, int mouseX, int mouseY, EntityPlayer player, GuiCategory guiCategory);\n\n @SideOnly(Side.CLIENT)\n public abstract void onInit(Book book, CategoryAbstract category, GuiCategory guiCategory, EntityPlayer player, ItemStack bookStack);\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n\n EntryAbstract that = (EntryAbstract) o;\n if (pageList != null ? !pageList.equals(that.pageList) : that.pageList != null) return false;\n if (name != null ? !name.equals(that.name) : that.name != null)\n return false;\n\n return true;\n }\n\n @Override\n public int hashCode() {\n int result = pageList != null ? pageList.hashCode() : 0;\n result = 31 * result + (name != null ? name.hashCode() : 0);\n return result;\n }\n}",
"public class GuiBase extends GuiScreen {\n\n public int guiLeft, guiTop;\n public int xSize = 192;\n public int ySize = 192;\n public EntityPlayer player;\n public ItemStack bookStack;\n public float publicZLevel;\n\n public GuiBase(EntityPlayer player, ItemStack bookStack) {\n this.player = player;\n this.bookStack = bookStack;\n this.publicZLevel = zLevel;\n }\n\n @Override\n public boolean doesGuiPauseGame() {\n return false;\n }\n\n @Override\n public void keyTyped(char typedChar, int keyCode) {\n if (keyCode == Keyboard.KEY_ESCAPE || keyCode == this.mc.gameSettings.keyBindInventory.getKeyCode()) {\n this.mc.displayGuiScreen(null);\n this.mc.setIngameFocus();\n }\n }\n\n public void drawTexturedModalRectWithColor(int x, int y, int textureX, int textureY, int width, int height, Color color) {\n pushMatrix();\n enableBlend();\n blendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);\n float f = 0.00390625F;\n float f1 = 0.00390625F;\n disableLighting();\n color((float) color.getRed() / 255F, (float) color.getGreen() / 255F, (float) color.getBlue() / 255F);\n Tessellator tessellator = Tessellator.getInstance();\n tessellator.getBuffer().begin(7, DefaultVertexFormats.POSITION_TEX);\n tessellator.getBuffer().pos((double) (x), (double) (y + height), (double) this.zLevel).tex((double) ((float) (textureX) * f), (double) ((float) (textureY + height) * f1)).endVertex();\n tessellator.getBuffer().pos((double) (x + width), (double) (y + height), (double) this.zLevel).tex((double) ((float) (textureX + width) * f), (double) ((float) (textureY + height) * f1)).endVertex();\n tessellator.getBuffer().pos((double) (x + width), (double) (y), (double) this.zLevel).tex((double) ((float) (textureX + width) * f), (double) ((float) (textureY) * f1)).endVertex();\n tessellator.getBuffer().pos((double) (x), (double) (y), (double) this.zLevel).tex((double) ((float) (textureX) * f), (double) ((float) (textureY) * f1)).endVertex();\n tessellator.draw();\n disableBlend();\n popMatrix();\n }\n\n @Override\n public void drawCenteredString(FontRenderer fontRendererObj, String string, int x, int y, int color) {\n RenderHelper.disableStandardItemLighting();\n fontRendererObj.drawString(string, x - fontRendererObj.getStringWidth(string) / 2, y, color);\n RenderHelper.disableStandardItemLighting();\n }\n\n public void drawCenteredStringWithShadow(FontRenderer fontRendererObj, String string, int x, int y, int color) {\n super.drawCenteredString(fontRendererObj, string, x, y, color);\n }\n\n @Override\n public void drawTexturedModalRect(int x, int y, int textureX, int textureY, int width, int height) {\n pushMatrix();\n color(1.0F, 1.0F, 1.0F, 1.0F);\n super.drawTexturedModalRect(x, y, textureX, textureY, width, height);\n popMatrix();\n }\n\n @Override\n public void drawHoveringText(List<String> list, int x, int y, FontRenderer font) {\n disableLighting();\n RenderHelper.disableStandardItemLighting();\n super.drawHoveringText(list, x, y, font);\n RenderHelper.enableStandardItemLighting();\n enableLighting();\n }\n\n @Override\n public void drawHoveringText(List<String> list, int x, int y) {\n disableLighting();\n RenderHelper.disableStandardItemLighting();\n super.drawHoveringText(list, x, y);\n RenderHelper.enableStandardItemLighting();\n enableLighting();\n }\n\n @Override\n public void renderToolTip(ItemStack stack, int x, int y) {\n super.renderToolTip(stack, x, y);\n }\n\n @Override\n public void onGuiClosed() {\n super.onGuiClosed();\n }\n}",
"public class GuiEntry extends GuiBase {\n\n public ResourceLocation outlineTexture;\n public ResourceLocation pageTexture;\n public Book book;\n public CategoryAbstract category;\n public EntryAbstract entry;\n public List<PageWrapper> pageWrapperList = new ArrayList<PageWrapper>();\n public ButtonBack buttonBack;\n public ButtonNext buttonNext;\n public ButtonPrev buttonPrev;\n public ButtonSearch buttonSearch;\n public int pageNumber;\n\n public GuiEntry(Book book, CategoryAbstract category, EntryAbstract entry, EntityPlayer player, ItemStack bookStack) {\n super(player, bookStack);\n this.book = book;\n this.category = category;\n this.entry = entry;\n this.pageTexture = book.getPageTexture();\n this.outlineTexture = book.getOutlineTexture();\n this.pageNumber = 0;\n }\n\n @Override\n public void initGui() {\n super.initGui();\n entry.onInit(book, category, null, player, bookStack);\n this.buttonList.clear();\n this.pageWrapperList.clear();\n\n guiLeft = (this.width - this.xSize) / 2;\n guiTop = (this.height - this.ySize) / 2;\n\n this.buttonList.add(buttonBack = new ButtonBack(0, guiLeft + xSize / 6, guiTop, this));\n this.buttonList.add(buttonNext = new ButtonNext(1, guiLeft + 4 * xSize / 6, guiTop + 5 * ySize / 6, this));\n this.buttonList.add(buttonPrev = new ButtonPrev(2, guiLeft + xSize / 5, guiTop + 5 * ySize / 6, this));\n this.buttonList.add(buttonSearch = new ButtonSearch(3, (guiLeft + xSize / 6) - 25, guiTop + 5, this));\n\n for (IPage page : this.entry.pageList) {\n page.onInit(book, category, entry, player, bookStack, this);\n pageWrapperList.add(new PageWrapper(this, book, category, entry, page, guiLeft, guiTop, player, this.fontRenderer, bookStack));\n }\n }\n\n @Override\n public void drawScreen(int mouseX, int mouseY, float renderPartialTicks) {\n Minecraft.getMinecraft().getTextureManager().bindTexture(pageTexture);\n drawTexturedModalRect(guiLeft, guiTop, 0, 0, xSize, ySize);\n Minecraft.getMinecraft().getTextureManager().bindTexture(outlineTexture);\n drawTexturedModalRectWithColor(guiLeft, guiTop, 0, 0, xSize, ySize, book.getColor());\n\n pageNumber = MathHelper.clamp(pageNumber, 0, pageWrapperList.size() - 1);\n\n if (pageNumber < pageWrapperList.size()) {\n if (pageWrapperList.get(pageNumber).canPlayerSee()) {\n pageWrapperList.get(pageNumber).draw(mouseX, mouseY, this);\n pageWrapperList.get(pageNumber).drawExtras(mouseX, mouseY, this);\n }\n }\n\n drawCenteredString(fontRenderer, String.format(\"%d/%d\", pageNumber + 1, pageWrapperList.size()), guiLeft + xSize / 2, guiTop + 5 * ySize / 6, 0);\n drawCenteredStringWithShadow(fontRenderer, entry.getLocalizedName(), guiLeft + xSize / 2, guiTop - 10, Color.WHITE.getRGB());\n\n buttonPrev.visible = pageNumber != 0;\n buttonNext.visible = pageNumber != pageWrapperList.size() - 1 && !pageWrapperList.isEmpty();\n\n super.drawScreen(mouseX, mouseY, renderPartialTicks);\n }\n\n @Override\n public void mouseClicked(int mouseX, int mouseY, int typeofClick) throws IOException {\n super.mouseClicked(mouseX, mouseY, typeofClick);\n for (PageWrapper wrapper : this.pageWrapperList) {\n if (wrapper.isMouseOnWrapper(mouseX, mouseY) && wrapper.canPlayerSee()) {\n if (typeofClick == 0) {\n pageWrapperList.get(pageNumber).page.onLeftClicked(book, category, entry, mouseX, mouseY, player, this);\n }\n if (typeofClick == 1) {\n pageWrapperList.get(pageNumber).page.onRightClicked(book, category, entry, mouseX, mouseY, player, this);\n }\n }\n }\n\n if (typeofClick == 1) {\n this.mc.displayGuiScreen(new GuiCategory(book, category, player, bookStack, entry));\n }\n }\n\n @Override\n public void handleMouseInput() throws IOException {\n super.handleMouseInput();\n\n int movement = Mouse.getEventDWheel();\n if (movement < 0)\n nextPage();\n else if (movement > 0)\n prevPage();\n }\n\n @Override\n public void keyTyped(char typedChar, int keyCode) {\n super.keyTyped(typedChar, keyCode);\n if (keyCode == Keyboard.KEY_BACK || keyCode == this.mc.gameSettings.keyBindUseItem.getKeyCode())\n this.mc.displayGuiScreen(new GuiCategory(book, category, player, bookStack, entry));\n if ((keyCode == Keyboard.KEY_UP || keyCode == Keyboard.KEY_RIGHT) && pageNumber + 1 < pageWrapperList.size())\n nextPage();\n if ((keyCode == Keyboard.KEY_DOWN || keyCode == Keyboard.KEY_LEFT) && pageNumber > 0)\n prevPage();\n }\n\n @Override\n public void actionPerformed(GuiButton button) {\n if (button.id == 0)\n this.mc.displayGuiScreen(new GuiCategory(book, category, player, bookStack, entry));\n else if (button.id == 1 && pageNumber + 1 < pageWrapperList.size())\n nextPage();\n else if (button.id == 2 && pageNumber > 0)\n prevPage();\n else if (button.id == 3)\n this.mc.displayGuiScreen(new GuiSearch(book, player, bookStack, this));\n }\n\n @Override\n public void onGuiClosed() {\n super.onGuiClosed();\n\n ResourceLocation key = null;\n for (Map.Entry<ResourceLocation, EntryAbstract> mapEntry : category.entries.entrySet())\n if (mapEntry.getValue().equals(entry))\n key = mapEntry.getKey();\n\n if (key != null)\n PacketHandler.INSTANCE.sendToServer(new PacketSyncEntry(book.getCategoryList().indexOf(category), key, pageNumber));\n }\n\n public void nextPage() {\n if (pageNumber != pageWrapperList.size() - 1 && !pageWrapperList.isEmpty())\n pageNumber++;\n }\n\n public void prevPage() {\n if (pageNumber != 0)\n pageNumber--;\n }\n}"
] | import amerifrance.guideapi.api.impl.Book;
import amerifrance.guideapi.api.impl.abstraction.CategoryAbstract;
import amerifrance.guideapi.api.impl.abstraction.EntryAbstract;
import amerifrance.guideapi.gui.GuiBase;
import amerifrance.guideapi.gui.GuiEntry;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly; | package amerifrance.guideapi.api;
public interface IPage {
@SideOnly(Side.CLIENT)
void draw(Book book, CategoryAbstract category, EntryAbstract entry, int guiLeft, int guiTop, int mouseX, int mouseY, GuiBase guiBase, FontRenderer fontRendererObj);
@SideOnly(Side.CLIENT)
void drawExtras(Book book, CategoryAbstract category, EntryAbstract entry, int guiLeft, int guiTop, int mouseX, int mouseY, GuiBase guiBase, FontRenderer fontRendererObj);
| boolean canSee(Book book, CategoryAbstract category, EntryAbstract entry, EntityPlayer player, ItemStack bookStack, GuiEntry guiEntry); | 4 |
iLexiconn/Magister.java | src/main/java/net/ilexiconn/magister/handler/ELOHandler.java | [
"public class Magister {\n public static final String VERSION = \"0.1.2\";\n\n public static final int SESSION_TIMEOUT = 1200000;\n\n public Gson gson = new GsonBuilder()\n .registerTypeAdapter(Profile.class, new ProfileAdapter())\n .registerTypeAdapter(Study[].class, new StudyAdapter())\n .registerTypeAdapter(Subject[].class, new SubjectAdapter())\n .create();\n\n public School school;\n public SchoolUrl schoolUrl;\n public User user;\n\n public Version version;\n public Session session;\n public Profile profile;\n public Subject[] subjects;\n public Study[] studies;\n public Study currentStudy;\n\n protected long loginTime = 0L;\n\n private List<IHandler> handlerList = new ArrayList<IHandler>();\n\n protected Magister() {\n handlerList.add(new GradeHandler(this));\n handlerList.add(new PresenceHandler(this));\n handlerList.add(new ContactHandler(this));\n handlerList.add(new MessageHandler(this));\n handlerList.add(new AppointmentHandler(this));\n handlerList.add(new ELOHandler(this));\n }\n\n /**\n * Create a new {@link Magister} instance by logging in. Will return null if login fails.\n *\n * @param school the {@link School} instance. Can't be null.\n * @param username the username of the profile. Can't be null.\n * @param password the password of the profile. Can't be null.\n * @return the new {@link Magister} instance, null if login fails.\n * @throws IOException if there is no active internet connection.\n * @throws ParseException if parsing the date fails.\n * @throws InvalidParameterException if one of the arguments is null.\n */\n public static Magister login(School school, String username, String password) throws IOException, ParseException, InvalidParameterException {\n if (school == null || username == null || username.isEmpty() || password == null || password.isEmpty()) {\n throw new InvalidParameterException(\"Parameters can't be null or empty!\");\n }\n Magister magister = new Magister();\n AndroidUtil.checkAndroid();\n magister.school = school;\n SchoolUrl url = magister.schoolUrl = new SchoolUrl(school);\n magister.version = magister.gson.fromJson(HttpUtil.httpGet(url.getVersionUrl()), Version.class);\n magister.user = new User(username, password, true);\n magister.logout();\n Map<String, String> nameValuePairMap = magister.gson.fromJson(magister.gson.toJson(magister.user), new TypeToken<Map<String, String>>() {\n }.getType());\n magister.session = magister.gson.fromJson(HttpUtil.httpPost(url.getSessionUrl(), nameValuePairMap), Session.class);\n if (!magister.session.state.equals(\"active\")) {\n LogUtil.printError(\"Invalid credentials\", new InvalidParameterException());\n return null;\n }\n magister.loginTime = System.currentTimeMillis();\n magister.profile = magister.gson.fromJson(HttpUtil.httpGet(url.getAccountUrl()), Profile.class);\n magister.studies = magister.gson.fromJson(HttpUtil.httpGet(url.getStudiesUrl(magister.profile.id)), Study[].class);\n Date now = new Date();\n for (Study study : magister.studies) {\n if (study.endDate.before(now)) {\n magister.currentStudy = study;\n }\n }\n if (magister.currentStudy != null) {\n magister.subjects = magister.getSubjectsOfStudy(magister.currentStudy);\n }\n return magister;\n }\n\n /**\n * Refresh the session of this magister instance by logging in again.\n *\n * @return the current session.\n * @throws IOException if there is no active internet connection.\n */\n public Session login() throws IOException {\n logout();\n Map<String, String> nameValuePairMap = gson.fromJson(gson.toJson(user), new TypeToken<Map<String, String>>() {\n }.getType());\n session = gson.fromJson(HttpUtil.httpPost(schoolUrl.getSessionUrl(), nameValuePairMap), Session.class);\n loginTime = System.currentTimeMillis();\n return session;\n }\n\n /**\n * Logout the current session. You have to wait a few seconds before logging in again.\n *\n * @throws IOException if there is no active internet connection.\n */\n public void logout() throws IOException {\n HttpUtil.httpDelete(schoolUrl.getCurrentSessionUrl());\n loginTime = 0L;\n }\n\n /**\n * Check if the current session is still active.\n *\n * @return true if the current session is still active.\n */\n public boolean isExpired() {\n return loginTime + (SESSION_TIMEOUT - 1000) < System.currentTimeMillis();\n }\n\n /**\n * Check if this user has the following privilege.\n *\n * @param privilege the privilege name.\n * @return true if the profile has the privilege.\n */\n public boolean hasPrivilege(String privilege) {\n for (Privilege p : profile.privileges) {\n if (p.name.equals(privilege)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Get the current profile picture in the default size.\n *\n * @return the current profile picture in the default size.\n * @throws IOException if there is no active internet connection.\n */\n public ImageContainer getImage() throws IOException {\n return getImage(42, 64, false);\n }\n\n /**\n * Get the current profile picture.\n *\n * @param width the width.\n * @param height the height.\n * @param crop true if not in default ratio.\n * @return the current profile picture.\n * @throws IOException if there is no active internet connection.\n */\n public ImageContainer getImage(int width, int height, boolean crop) throws IOException {\n String url = school.url + \"/api/personen/\" + profile.id + \"/foto\" + (width != 42 || height != 64 || crop ? \"?width=\" + width + \"&height=\" + height + \"&crop=\" + crop : \"\");\n HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection();\n connection.setRequestMethod(\"GET\");\n connection.setRequestProperty(\"Cookie\", HttpUtil.getCurrentCookies());\n connection.connect();\n try {\n return new ImageContainer(connection.getInputStream());\n } catch (ClassNotFoundException e) {\n LogUtil.printError(\"Unable to load image class.\", e);\n return null;\n }\n }\n\n /**\n * Change the password of the current profile.\n *\n * @param oldPassword the current password.\n * @param newPassword the new password.\n * @param newPassword2 the new password.\n * @return a String with the response. 'Successful' if the password changed successfully.\n * @throws IOException if there is no active internet connection.\n * @throws InvalidParameterException if one of the parameters is null or empty, or when the two new passwords aren't\n * the same.\n * @throws PrivilegeException if the profile doesn't have the privilege to perform this action.\n * @deprecated use the password handler instead.\n */\n @Deprecated\n public String changePassword(String oldPassword, String newPassword, String newPassword2) throws IOException, InvalidParameterException, PrivilegeException {\n return getHandler(Handler.PASSWORD).changePassword(oldPassword, newPassword, newPassword2);\n }\n\n public Subject[] getSubjectsOfStudy(Study study) throws IOException {\n return gson.fromJson(HttpUtil.httpGet(schoolUrl.getApiUrl() + \"personen/\" + profile.id + \"/aanmeldingen/\" + study.id + \"/vakken\"), Subject[].class);\n }\n\n /**\n * Get a handler instance from this magister instance.\n *\n * @param type the class of the handler.\n * @param <T> the handler class type.\n * @return the {@link IHandler} instance, null if it can't be found.\n * @throws PrivilegeException if the profile doesn't have the privilege to perform this action.\n */\n public <T extends IHandler> T getHandler(Class<T> type) throws PrivilegeException {\n for (IHandler handler : handlerList) {\n if (handler.getClass() == type) {\n if (!hasPrivilege(handler.getPrivilege())) {\n throw new PrivilegeException();\n }\n return type.cast(handler);\n }\n }\n return null;\n }\n\n public <T extends IHandler> T getHandler(Handler<T> handler) {\n for (IHandler h : handlerList) {\n if (h.getClass() == handler.getHandler()) {\n if (!hasPrivilege(h.getPrivilege())) {\n throw new PrivilegeException();\n }\n return handler.getHandler().cast(h);\n }\n }\n return null;\n }\n}",
"public class ArrayAdapter<T> extends TypeAdapter<T[]> {\n public Gson gson = GsonUtil.getGson();\n public Class<T> cls;\n public Class<? extends T[]> clsArray;\n\n public ArrayAdapter(Class<T> cls, Class<? extends T[]> clsArray) {\n this.cls = cls;\n this.clsArray = clsArray;\n }\n\n @Override\n public void write(JsonWriter out, T[] value) throws IOException {\n throw new UnsupportedOperationException(\"Not implemented\");\n }\n\n @Override\n public T[] read(JsonReader in) throws IOException {\n JsonObject object = gson.getAdapter(JsonElement.class).read(in).getAsJsonObject();\n if (object.has(\"Items\")) {\n JsonArray array = object.get(\"Items\").getAsJsonArray();\n ArrayList<T> list = new ArrayList<T>();\n for (JsonElement element : array) {\n list.add(gson.fromJson(element, cls));\n }\n return Arrays.copyOf(list.toArray(), list.size(), clsArray);\n } else {\n T t = gson.fromJson(object, cls);\n return (T[]) new Object[]{t};\n }\n }\n}",
"public class SingleStudyGuideAdapter extends TypeAdapter<SingleStudyGuide> {\n public Gson gson = GsonUtil.getGson();\n\n @Override\n public void write(JsonWriter out, SingleStudyGuide value) throws IOException {\n throw new UnsupportedOperationException(\"Not implemented\");\n }\n\n @Override\n public SingleStudyGuide read(JsonReader in) throws IOException {\n JsonObject object = gson.getAdapter(JsonElement.class).read(in).getAsJsonObject();\n SingleStudyGuide studyGuide = gson.fromJson(object, SingleStudyGuide.class);\n JsonArray array = object.get(\"Onderdelen\").getAsJsonObject().get(\"Items\").getAsJsonArray();\n List<StudyGuideItem> studyGuideItemList = new ArrayList<StudyGuideItem>();\n for (JsonElement element : array) {\n studyGuideItemList.add(gson.fromJson(element, StudyGuideItem.class));\n }\n studyGuide.items = studyGuideItemList.toArray(new StudyGuideItem[studyGuideItemList.size()]);\n return studyGuide;\n }\n}",
"public class SingleStudyGuide implements Serializable {\n @SerializedName(\"Id\")\n public int id;\n\n @SerializedName(\"Links\")\n public Link[] links;\n\n @SerializedName(\"Van\")\n public String from;\n\n @SerializedName(\"TotEnMet\")\n public String to;\n\n @SerializedName(\"Titel\")\n public String title;\n\n @SerializedName(\"IsZichtbaar\")\n public boolean isVisible;\n\n @SerializedName(\"InLeerlingArchief\")\n public boolean isArchived;\n\n @SerializedName(\"VakCodes\")\n public String[] courses;\n\n public StudyGuideItem[] items;\n}",
"public class Source implements Serializable {\n @SerializedName(\"Id\")\n public int id;\n\n @SerializedName(\"Links\")\n public Link[] links;\n\n @SerializedName(\"BronSoort\")\n public int sourceType;\n\n @SerializedName(\"Naam\")\n public String name;\n\n @SerializedName(\"Referentie\")\n public int reference;\n\n //Uri\n\n @SerializedName(\"Grootte\")\n public int size;\n\n @SerializedName(\"Privilege\")\n public int privelege;\n\n @SerializedName(\"Type\")\n public int type;\n\n @SerializedName(\"ContentType\")\n public String contentType;\n\n //GewijzigdOp\n\n //GeplaatstDoor\n\n //GemaaktOp\n\n @SerializedName(\"FileBlobId\")\n public int fileBlobId;\n\n @SerializedName(\"ParentId\")\n public int parentId;\n\n @SerializedName(\"UniqueId\")\n public String uniqueId;\n\n @SerializedName(\"Volgnr\")\n public int followId;\n\n @SerializedName(\"ModuleSoort\")\n public int moduleType;\n}",
"public class StudyGuide implements Serializable {\n @SerializedName(\"Id\")\n public int id;\n\n @SerializedName(\"Links\")\n public Link[] links;\n\n @SerializedName(\"Van\")\n public String from;\n\n @SerializedName(\"TotEnMet\")\n public String to;\n\n @SerializedName(\"VakCodes\")\n public String[] courses;\n\n @SerializedName(\"Titel\")\n public String title;\n\n @SerializedName(\"InLeerlingArchief\")\n public boolean isArchived;\n}",
"public class GsonUtil {\n private static Gson gson = new Gson();\n private static JsonParser parser = new JsonParser();\n\n public static Gson getGson() {\n return gson;\n }\n\n public static JsonElement getFromJson(String json, String key) {\n return parser.parse(json).getAsJsonObject().get(key);\n }\n\n public static Gson getGsonWithAdapter(Class<?> type, TypeAdapter<?> adapter) {\n Map<Class<?>, TypeAdapter<?>> map = new HashMap<Class<?>, TypeAdapter<?>>();\n map.put(type, adapter);\n return getGsonWithAdapters(map);\n }\n\n public static Gson getGsonWithAdapters(Map<Class<?>, TypeAdapter<?>> map) {\n GsonBuilder builder = new GsonBuilder();\n for (Map.Entry<Class<?>, TypeAdapter<?>> entry : map.entrySet()) {\n builder.registerTypeAdapter(entry.getKey(), entry.getValue());\n }\n return builder.create();\n }\n}",
"public class HttpUtil {\n private static CookieManager cookieManager = new CookieManager();\n\n public static InputStreamReader httpDelete(String url) throws IOException {\n HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection();\n connection.setRequestMethod(\"DELETE\");\n connection.setRequestProperty(\"Cookie\", getCurrentCookies());\n connection.setRequestProperty(\"Content-Type\", \"application/x-www-form-urlencoded\");\n connection.connect();\n storeCookies(connection);\n return new InputStreamReader(connection.getInputStream());\n }\n\n public static InputStreamReader httpPut(String url, String json) throws IOException {\n HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection();\n connection.setDoOutput(true);\n connection.setRequestMethod(\"POST\");\n connection.setRequestProperty(\"Cookie\", getCurrentCookies());\n connection.setRequestProperty(\"Content-Type\", \"application/json\");\n byte[] data_url = json.getBytes(\"UTF-8\");\n DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());\n outputStream.write(data_url);\n outputStream.flush();\n outputStream.close();\n storeCookies(connection);\n return new InputStreamReader(connection.getInputStream());\n }\n\n public static InputStreamReader httpPost(String url, Map<String, String> data) throws IOException {\n HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection();\n connection.setDoOutput(true);\n connection.setRequestMethod(\"POST\");\n connection.setRequestProperty(\"Cookie\", getCurrentCookies());\n connection.setRequestProperty(\"Content-Type\", \"application/x-www-form-urlencoded\");\n byte[] data_url = convertToDataString(data).getBytes(\"UTF-8\");\n DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());\n outputStream.write(data_url);\n outputStream.flush();\n outputStream.close();\n storeCookies(connection);\n return new InputStreamReader(connection.getInputStream());\n }\n\n public static InputStreamReader httpPostRaw(String url, String json) throws IOException {\n HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection();\n connection.setDoOutput(true);\n connection.setRequestMethod(\"POST\");\n connection.setRequestProperty(\"Cookie\", getCurrentCookies());\n connection.setRequestProperty(\"Content-Type\", \"application/json\");\n byte[] data_url = json.getBytes(\"UTF-8\");\n DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());\n outputStream.write(data_url);\n outputStream.flush();\n outputStream.close();\n storeCookies(connection);\n return new InputStreamReader(connection.getInputStream());\n }\n\n public static InputStreamReader httpPostFile(Magister m, File file) throws IOException {\n HttpsURLConnection connection = (HttpsURLConnection) new URL(m.school.url + \"/api/file\").openConnection();\n\n String boundary = Long.toHexString(System.currentTimeMillis());\n String lineEnd = \"\\r\\n\";\n String twoHyphens = \"--\";\n\n connection.setRequestMethod(\"POST\");\n connection.setRequestProperty(\"Cookie\", HttpUtil.getCurrentCookies());\n connection.setRequestProperty(\"Connection\", \"Keep-Alive\");\n connection.setRequestProperty(\"Cache-Control\", \"no-cache\");\n connection.setRequestProperty(\"Content-Type\", \"multipart/form-data;boundary=\" + boundary);\n connection.setDoOutput(true);\n connection.setUseCaches(false);\n\n DataOutputStream dos = new DataOutputStream(connection.getOutputStream());\n FileInputStream fis = new FileInputStream(file);\n\n dos.writeBytes(twoHyphens + boundary + lineEnd);\n dos.writeBytes(\"Content-Disposition: form-data; name=\\\"file\\\";\" + \" filename=\\\"\" + file.getName() + \"\\\"\" + lineEnd);\n dos.writeBytes(lineEnd);\n\n int bytesAvailable = fis.available();\n int bufferSize = Math.min(bytesAvailable, 1024);\n byte[] buffer = new byte[bufferSize];\n int bytesRead = fis.read(buffer, 0, bufferSize);\n\n while (bytesRead > 0) {\n dos.write(buffer, 0, bufferSize);\n bytesAvailable = fis.available();\n bufferSize = Math.min(bytesAvailable, 1024);\n bytesRead = fis.read(buffer, 0, bufferSize);\n }\n\n dos.writeBytes(lineEnd);\n dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);\n\n fis.close();\n dos.flush();\n dos.close();\n return new InputStreamReader(connection.getInputStream());\n }\n\n public static InputStreamReader httpGet(String url) throws IOException {\n HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection();\n connection.setRequestMethod(\"GET\");\n connection.setRequestProperty(\"Cookie\", getCurrentCookies());\n if (AndroidUtil.getAndroidSupportCache()) {\n connection.setUseCaches(true);\n }\n connection.connect();\n storeCookies(connection);\n return new InputStreamReader(connection.getInputStream());\n }\n\n public static File httpGetFile(String url, File downloadDir) throws IOException {\n HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection();\n connection.setRequestMethod(\"GET\");\n connection.setRequestProperty(\"Cookie\", getCurrentCookies());\n if (AndroidUtil.getAndroidSupportCache()) {\n connection.setUseCaches(true);\n }\n String disposition = connection.getHeaderField(\"Content-Disposition\");\n String fileName = disposition.substring(disposition.indexOf(\"filename=\") + 10, disposition.length() - 1);\n File target = new File(downloadDir.getPath() + \"\\\\\" + fileName);\n copyFileUsingStream(connection.getInputStream(), target);\n connection.connect();\n storeCookies(connection);\n return target.getAbsoluteFile();\n }\n\n private static void copyFileUsingStream(InputStream is, File dest) throws IOException {\n if (is == null || dest == null) {\n return;\n }\n OutputStream os = null;\n try {\n os = new FileOutputStream(dest);\n byte[] buffer = new byte[1024];\n int length;\n while ((length = is.read(buffer)) > 0) {\n os.write(buffer, 0, length);\n }\n } finally {\n is.close();\n if (os != null) {\n os.close();\n }\n }\n }\n\n private static void storeCookies(HttpURLConnection connection) {\n Map<String, List<String>> headers = connection.getHeaderFields();\n List<String> cookies = headers.get(\"Set-Cookie\");\n if (cookies != null) {\n for (String cookie : cookies) {\n cookieManager.getCookieStore().add(null, HttpCookie.parse(cookie).get(0));\n }\n }\n }\n\n public static String getCurrentCookies() {\n String result = \"\";\n for (HttpCookie cookie : cookieManager.getCookieStore().getCookies()) {\n result = result.concat(cookie.toString() + \";\");\n }\n return result;\n }\n\n private static String convertToDataString(Map<String, String> data) throws UnsupportedEncodingException {\n StringBuilder builder = new StringBuilder();\n for (Map.Entry entry : data.entrySet()) {\n builder.append(URLEncoder.encode(entry.getKey().toString(), \"UTF-8\")).append(\"=\").append(URLEncoder.encode(entry.getValue().toString(), \"UTF-8\")).append(\"&\");\n }\n String result = builder.toString();\n return result.length() > 0 ? result.substring(0, result.length() - 1) : \"\";\n }\n\n public static String convertInputStreamReaderToString(InputStreamReader r) throws IOException {\n BufferedReader reader = new BufferedReader(r);\n StringBuilder responseBuilder = new StringBuilder();\n String line;\n while ((line = reader.readLine()) != null) {\n responseBuilder.append(line);\n }\n return responseBuilder.toString();\n }\n}"
] | import net.ilexiconn.magister.container.SingleStudyGuide;
import net.ilexiconn.magister.container.Source;
import net.ilexiconn.magister.container.StudyGuide;
import net.ilexiconn.magister.util.GsonUtil;
import net.ilexiconn.magister.util.HttpUtil;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import net.ilexiconn.magister.Magister;
import net.ilexiconn.magister.adapter.ArrayAdapter;
import net.ilexiconn.magister.adapter.SingleStudyGuideAdapter; | /*
* Copyright (c) 2015 iLexiconn
*
* 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 net.ilexiconn.magister.handler;
public class ELOHandler implements IHandler {
public Gson gson; | private Magister magister; | 0 |
michelelacorte/SwipeableCard | app/src/main/java/it/michelelacorte/exampleswipeablecard/MainActivity.java | [
"@SuppressWarnings(\"unused\")\npublic class CustomCardAnimation {\n private Context mContext;\n private CardView mCardView;\n private int mStartCardPosition;\n private long mDuration = 500;\n\n /**\n * Public constructor for set-up animation\n * @param context Context\n * @param card CardView reference\n * @param startCardPosition int which rapresent initial card height\n */\n public CustomCardAnimation(Context context, CardView card, int startCardPosition)\n {\n if(card == null)\n {\n throw new IllegalArgumentException(\"CardView can not be null, please check it!\");\n }\n if(context == null)\n {\n throw new IllegalArgumentException(\"Context can not be null, please check it!\");\n }\n if(startCardPosition <= 0)\n {\n throw new IllegalArgumentException(\"Start Card Position can not be <= 0, please check it!\");\n }\n this.mCardView = card;\n this.mContext = context;\n this.mStartCardPosition = startCardPosition;\n animationCustomCardStart();\n }\n\n /**\n * Public constructor for set-up animation\n * @param context Context\n * @param card CardView\n * @param startCardPosition int for Start Card Position\n * @param duration Duration of animation\n */\n public CustomCardAnimation(Context context, CardView card, int startCardPosition, long duration)\n {\n if(card == null)\n {\n throw new IllegalArgumentException(\"CardView can not be null, please check it!\");\n }\n if(context == null)\n {\n throw new IllegalArgumentException(\"Context can not be null, please check it!\");\n }\n if(startCardPosition <= 0)\n {\n throw new IllegalArgumentException(\"Start Card Position can not be <= 0, please check it!\");\n }\n this.mCardView = card;\n this.mContext = context;\n this.mStartCardPosition = startCardPosition;\n this.mDuration = duration;\n animationCustomCardStart();\n }\n /**\n * Start animation and set card at start position\n * Do not modify this!\n */\n @TargetApi(14)\n private void animationCustomCardStart()\n {\n final int height = getScreenSize(mContext);\n new CountDownTimer(300, 1) {\n public void onTick(long millisUntilFinished) {\n mCardView.setTranslationY(height - ((int)(mStartCardPosition * 1.7)));\n }\n\n public void onFinish() {\n mCardView.setTranslationY(height - ((int)(mStartCardPosition * 1.7)));\n }\n }.start();\n }\n\n /**\n * Down animation\n * Do not modify this!\n */\n @TargetApi(14)\n public void animationCustomCardDown()\n {\n final int height = getScreenSize(mContext);\n new CountDownTimer(1, 1) {\n public void onTick(long millisUntilFinished) {\n }\n\n public void onFinish() {\n mCardView.animate()\n .translationY(height - ((int) (mStartCardPosition * 1.7)))\n .setDuration(mDuration).start();\n }\n }.start();\n }\n\n /**\n * Up animation\n * Do not modify this!\n */\n @TargetApi(14)\n public void animationCustomCardUp()\n {\n final int height = getScreenSize(mContext);\n new CountDownTimer(1, 1) {\n public void onTick(long millisUntilFinished) {\n }\n\n public void onFinish() {\n mCardView.animate()\n .translationY(height - (mCardView.getHeight() + mStartCardPosition))\n .setDuration(mDuration).start();\n }\n }.start();\n }\n\n /**\n * Get Size of Screen (Height)\n * @param context Context\n * @return height of screen\n */\n private int getScreenSize(Context context)\n {\n WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);\n Display display = wm.getDefaultDisplay();\n Point size = new Point();\n display.getSize(size);\n return size.y;\n }\n}",
"@SuppressWarnings(\"unused\")\npublic class OptionView {\n private int mColorTitle;\n private int mMenuItem;\n private String mTitle;\n private String mText;\n private String mSubTitle;\n private int mImage;\n private int mToolbarColor;\n private boolean isMenuItem = false;\n private boolean isImage = false;\n private boolean isText = true;\n private boolean isSubTitle = false;\n private boolean isSwipeLeftRight = false;\n private Toolbar.OnMenuItemClickListener mToolbarListener;\n private long mDuration = 500;\n private float mCardRadius = 4f;\n private static OptionView optionView = null;\n private OptionViewAdditional optionViewAdditional = null;\n private double latitude;\n private double longitude;\n private String markerTitle;\n private boolean isStreetName = true;\n private boolean TYPE_CARD_NORMAL = false;\n private boolean TYPE_CARD_MAPS = false;\n private boolean TYPE_CARD_CREDIT = false;\n private boolean multipleMarker = false;\n private boolean singleMarker = false;\n private String[] markerTitleArray;\n private LatLng[] latLngArray;\n private int[] markerIconArray;\n private List<LatLng> latLngList = new ArrayList<>();\n private List<String> markerTitleList = new ArrayList<>();\n private List<Integer> markerIconList = new ArrayList<>();\n private int markerIcon;\n private float mapsZoom = 0;\n private boolean autoAnimation = true;\n private int intCvv;\n private String cvv;\n private String dateYear;\n private String cardHolderName;\n private String rawCardNumber;\n private boolean createCreditCard = false;\n private AppCompatActivity activity;\n\n public OptionView(CreditCard creditCard)\n {\n if(creditCard.mColorTitle == 0)\n {\n Log.e(\"ColorTitle\", \"Impossible to set Color Title to 0, default value BLACK is set! Please Check it\");\n mColorTitle = android.R.color.black;\n }else {\n mColorTitle = creditCard.mColorTitle;\n }\n if(creditCard.mTitle == null)\n {\n Log.e(\"Title\", \"Impossible to set Title to null, default value empty string is set! Please Check it\");\n mTitle = \"\";\n }else {\n mTitle = creditCard.mTitle;\n }\n if(creditCard.mToolbarColor == 0)\n {\n Log.e(\"ToolbarColor\", \"Impossible to set Toolbar Color to 0, default value transparent is set! Please Check it\");\n mToolbarColor = android.R.color.transparent;\n\n }else {\n mToolbarColor = creditCard.mToolbarColor;\n }\n mMenuItem = creditCard.mMenuItem;\n mSubTitle = creditCard.mSubTitle;\n mToolbarListener = creditCard.mToolbarListener;\n isMenuItem = creditCard.isMenuItem;\n isSubTitle = creditCard.isSubTitle;\n isSwipeLeftRight = creditCard.isSwipeLeftRight;\n mDuration = creditCard.mDuration;\n optionViewAdditional = creditCard.optionViewAdditional;\n mCardRadius = creditCard.mCardRadius;\n autoAnimation = creditCard.autoAnimation;\n intCvv = creditCard.intCvv;\n cvv = creditCard.cvv;\n dateYear = creditCard.dateYear;\n cardHolderName = creditCard.cardHolderName;\n rawCardNumber = creditCard.rawCardNumber;\n activity = creditCard.activity;\n createCreditCard = creditCard.createCard;\n TYPE_CARD_CREDIT = true;\n TYPE_CARD_MAPS = false;\n TYPE_CARD_NORMAL = false;\n }\n\n /**\n * Public constructor for set option to Swipeable Card (Maps Mode).\n */\n public OptionView(MapsCard mapsCard)\n {\n if(mapsCard.mColorTitle == 0)\n {\n Log.e(\"ColorTitle\", \"Impossible to set Color Title to 0, default value BLACK is set! Please Check it\");\n mColorTitle = android.R.color.black;\n }else {\n mColorTitle = mapsCard.mColorTitle;\n }\n if(mapsCard.mTitle == null)\n {\n Log.e(\"Title\", \"Impossible to set Title to null, default value empty string is set! Please Check it\");\n mTitle = \"\";\n }else {\n mTitle = mapsCard.mTitle;\n }\n if(mapsCard.mToolbarColor == 0)\n {\n Log.e(\"ToolbarColor\", \"Impossible to set Toolbar Color to 0, default value transparent is set! Please Check it\");\n mToolbarColor = android.R.color.transparent;\n\n }else {\n mToolbarColor = mapsCard.mToolbarColor;\n }\n mMenuItem = mapsCard.mMenuItem;\n mText = mapsCard.mText;\n mSubTitle = mapsCard.mSubTitle;\n mImage = mapsCard.mImage;\n mToolbarListener = mapsCard.mToolbarListener;\n isText = mapsCard.isText;\n isImage = mapsCard.isImage;\n isMenuItem = mapsCard.isMenuItem;\n isSubTitle = mapsCard.isSubTitle;\n isSwipeLeftRight = mapsCard.isSwipeLeftRight;\n mDuration = mapsCard.mDuration;\n optionViewAdditional = mapsCard.optionViewAdditional;\n mCardRadius = mapsCard.mCardRadius;\n latitude = mapsCard.latitude;\n longitude = mapsCard.longitude;\n latLngArray = mapsCard.latLngArray;\n markerTitleArray = mapsCard.markerTitleArray;\n latLngList = new ArrayList<>(mapsCard.latLngList);\n markerTitleList = new ArrayList<>(mapsCard.markerTitleList);\n markerTitle = mapsCard.markerTitle;\n isStreetName = mapsCard.isStreetName;\n singleMarker = mapsCard.singleMarker;\n multipleMarker = mapsCard.multipleMarker;\n markerIcon = mapsCard.markerIcon;\n markerIconArray = mapsCard.markerIconArray;\n markerIconList = mapsCard.markerIconList;\n mapsZoom = mapsCard.mZoom;\n autoAnimation = mapsCard.autoAnimation;\n TYPE_CARD_MAPS = true;\n TYPE_CARD_NORMAL = false;\n TYPE_CARD_CREDIT = false;\n }\n\n /**\n * Public constructor for set option to Swipeable Card (Normal Mode).\n */\n public OptionView(NormalCard normalCard)\n {\n if(normalCard.mColorTitle == 0)\n {\n Log.e(\"ColorTitle\", \"Impossible to set Color Title to 0, default value BLACK is set! Please Check it\");\n mColorTitle = android.R.color.black;\n }else {\n mColorTitle = normalCard.mColorTitle;\n }\n if(normalCard.mTitle == null)\n {\n Log.e(\"Title\", \"Impossible to set Title to null, default value empty string is set! Please Check it\");\n mTitle = \"\";\n }else {\n mTitle = normalCard.mTitle;\n }\n if(normalCard.mToolbarColor == 0)\n {\n Log.e(\"ToolbarColor\", \"Impossible to set Toolbar Color to 0, default value transparent is set! Please Check it\");\n mToolbarColor = android.R.color.transparent;\n\n }else {\n mToolbarColor = normalCard.mToolbarColor;\n }\n mMenuItem = normalCard.mMenuItem;\n mText = normalCard.mText;\n mSubTitle = normalCard.mSubTitle;\n mImage = normalCard.mImage;\n mToolbarListener = normalCard.mToolbarListener;\n isText = normalCard.isText;\n isImage = normalCard.isImage;\n isMenuItem = normalCard.isMenuItem;\n isSubTitle = normalCard.isSubTitle;\n isSwipeLeftRight = normalCard.isSwipeLeftRight;\n mDuration = normalCard.mDuration;\n optionViewAdditional = normalCard.optionViewAdditional;\n mCardRadius = normalCard.mCardRadius;\n autoAnimation = normalCard.autoAnimation;\n TYPE_CARD_NORMAL = true;\n TYPE_CARD_MAPS = false;\n TYPE_CARD_CREDIT = false;\n }\n\n /**\n * Public class Builder for setting up Swipeable Card.\n */\n public static class Builder{\n\n public NormalCard normalCard()\n {\n return new NormalCard();\n }\n public MapsCard mapsCard()\n {\n return new MapsCard();\n }\n public CreditCard creditCard() {\n return new CreditCard();\n }\n }\n\n /**\n * Get toolbarListener of Swipeable Card.\n * @return OnMenuItemClickListener item\n */\n public Toolbar.OnMenuItemClickListener getToolbarListener() {\n return mToolbarListener;\n }\n\n /**\n * Get Toolbar Color of Swipeable Card.\n * @return int of color\n */\n public int getColorToolbar() {\n return mToolbarColor;\n }\n\n /**\n * Get Sub Title of Swipeable Card.\n * @return String of sub title\n */\n public String getSubTitle() {\n return mSubTitle;\n }\n\n /**\n * Get Text of Swipeable Card.\n * @return Text string of Swipeable Card\n */\n public String getText() {\n return mText;\n }\n\n /**\n * Get Image of Swipeable Card.\n * @return Integer image of Swipeable Card\n */\n public int getImage() {\n return mImage;\n }\n\n /**\n * Get Title of Swipeable Card.\n * @return String of title\n */\n public String getTitle() {\n return mTitle;\n }\n\n /**\n * Get Menu Item of Swipeable Card.\n * @return Integer of menu item\n */\n public int getMenuItem()\n {\n return mMenuItem;\n }\n\n /**\n * Get color of toolbar Title.\n * @return Integer of color title\n */\n public int getColorTitle()\n {\n return mColorTitle;\n }\n\n /**\n * Set OptionView in case of single swipeable card.\n * @param optionViews A series of OptionView\n */\n public static void setOptionView(@NotNull OptionView optionViews)\n {\n optionView = optionViews;\n }\n\n /**\n * Get OptionView.\n * @return OptionView type\n */\n @NotNull\n public static OptionView getOptionView()\n {\n return optionView;\n }\n\n /**\n * Get Animation duration\n * @return long representing the duration\n */\n public long getDuration()\n {\n return mDuration;\n }\n\n /**\n * Get card radius\n * @return float representing card radius\n */\n public float getCardRadius() {\n return mCardRadius;\n }\n\n /**\n * Get Optional View\n * @return OptionViewAdditional for custom item\n */\n @NotNull\n public OptionViewAdditional getOptionViewAdditional() {\n return optionViewAdditional;\n }\n\n /**\n * Method to check if Swipe to dismiss is set from user.\n */\n public boolean isSwipeToDismiss()\n {\n return isSwipeLeftRight;\n }\n /**\n * Method to check if Menu Item is set from user.\n */\n public boolean isMenuItem()\n {\n return isMenuItem;\n }\n /**\n * Method to check if Image is set from user.\n */\n public boolean isImage()\n {\n return isImage;\n }\n /**\n * Method to check if Text is set from user.\n */\n public boolean isText()\n {\n return isText;\n }\n /**\n * Method to check if Sub Title is set from user.\n */\n public boolean isSubTitle()\n {\n return isSubTitle;\n }\n\n /**\n * Get Latitude\n * @return latitude\n */\n public double getLatitude() {\n return latitude;\n }\n\n /**\n * Get longitude\n * @return longitude\n */\n public double getLongitude() {\n return longitude;\n }\n\n /**\n * Get boolean to know if Normal Card is set\n * @return boolean TYPE_CARD_NORMAL\n */\n public boolean isTypeCardNormal() {\n return TYPE_CARD_NORMAL;\n }\n\n /**\n * Get boolean to know if Maps Card is set\n * @return boolean TYPE_CARD_MAPS\n */\n public boolean isTypeCardMaps() {\n return TYPE_CARD_MAPS;\n }\n\n /**\n * Get boolean to know is Credit Card is set\n * @return boolean TYPE_CARD_CREDIT\n */\n public boolean isTypeCardCredit() {\n return TYPE_CARD_CREDIT;\n }\n\n /**\n * Get LatLng array\n * @return LatLng[]\n */\n public LatLng[] getLatLngArray() {\n return latLngArray;\n }\n\n /**\n * Get marker title\n * @return String markerTitle\n */\n public String getMarkerTitle() {\n return markerTitle;\n }\n\n /**\n * Get boolean isStreetName to know if street name is set\n * @return boolean isStreetName\n */\n public boolean isStreetName() {\n return isStreetName;\n }\n\n /**\n * Get boolean isMultipleMarker to know if multiple marker mode is used\n * @return boolean multipleMarker\n */\n public boolean isMultipleMarker() {\n return multipleMarker;\n }\n\n /**\n * Get boolean isSingleMarker to know if single marker mode is used\n * @return boolean singleMarker\n */\n public boolean isSingleMarker() {\n return singleMarker;\n }\n\n /**\n * Get marker title array\n * @return String[] markerTitleArray\n */\n public String[] getMarkerTitleArray() {\n return markerTitleArray;\n }\n\n /**\n * Get LatLng list of marker\n * @return List latlngList\n */\n public List<LatLng> getLatLngList() {\n return latLngList;\n }\n\n /**\n * Get String list of marker title\n * @return List markerTitleList\n */\n public List<String> getMarkerTitleList() {\n return markerTitleList;\n }\n\n /**\n * Get int of marker icon\n * @return int markerIcon\n */\n public int getMarkerIcon() {\n return markerIcon;\n }\n\n /**\n * Get int array of marker icon\n * @return int[] markerIconArray\n */\n public int[] getMarkerIconArray() {\n return markerIconArray;\n }\n\n /**\n * Get integer list of marker icon\n * @return List markerIconlist\n */\n public List<Integer> getMarkerIconList() {\n return markerIconList;\n }\n\n /**\n * Get zoom of camera maps\n * @return float mapsZoom\n */\n public float getMapsZoom() {\n return mapsZoom;\n }\n\n /**\n * Get boolean if auto animation is present\n * @return boolean autoAnimation\n */\n public boolean isAutoAnimation() {\n return autoAnimation;\n }\n\n /**\n * Get int CVV of Credit Card\n * @return int intCvv\n */\n public int getIntCvv() {\n return intCvv;\n }\n\n /**\n * Get String CVV of Credit Card\n * @return String cvv\n */\n public String getCvv() {\n return cvv;\n }\n\n /**\n * Get String of Date/Year of Credit Card\n * @return String dateYear\n */\n public String getDateYear() {\n return dateYear;\n }\n\n /**\n * Get String credit card name\n * @return String cardHolderName\n */\n public String getCardHolderName() {\n return cardHolderName;\n }\n\n /**\n * Get credit card number\n * @return String rawCardNumber\n */\n public String getRawCardNumber() {\n return rawCardNumber;\n }\n\n /**\n * Get boolean if create credit card is set\n * @return boolean createCreditCard\n */\n public boolean isCreateCreditCard() {\n return createCreditCard;\n }\n\n\n /**\n * Get activity\n * @return AppCompatActivity activity\n */\n public AppCompatActivity getActivity() {\n return activity;\n }\n\n /**\n * Credit Card mode\n */\n public static class CreditCard implements Card{\n private int mColorTitle;\n private int mMenuItem;\n private String mTitle;\n private String mSubTitle;\n private int mToolbarColor;\n private boolean isMenuItem = false;\n private boolean isSubTitle = false;\n private boolean isSwipeLeftRight = false;\n private Toolbar.OnMenuItemClickListener mToolbarListener;\n private long mDuration = 500;\n private float mCardRadius = 4f;\n private boolean autoAnimation = true;\n private OptionViewAdditional optionViewAdditional;\n private int intCvv;\n private String cvv;\n private String dateYear;\n private String cardHolderName;\n private String rawCardNumber;\n private AppCompatActivity activity;\n private boolean createCard = false;\n\n /**\n * Set Credit Card creation\n * @param activity AppCompatActivity\n */\n public CreditCard setCardCreation(AppCompatActivity activity)\n {\n this.activity = activity;\n createCard = true;\n return this;\n }\n\n /**\n * Set Credit Card cvv\n * @param cvv int\n */\n public CreditCard setCVV(int cvv)\n {\n intCvv = cvv;\n return this;\n }\n\n /**\n * Set Credit Card cvv\n * @param cvv String\n */\n public CreditCard setCVV(String cvv)\n {\n this.cvv = cvv;\n return this;\n }\n\n /**\n * Set Credit Card expiry\n * @param dateYear String\n */\n public CreditCard setCardExpiry(@Nullable String dateYear)\n {\n this.dateYear = dateYear;\n return this;\n }\n\n /**\n * Set Credit Card holder name\n * @param cardHolderName String\n */\n public CreditCard setCardHolderName(@Nullable String cardHolderName)\n {\n this.cardHolderName = cardHolderName;\n return this;\n }\n\n /**\n * Set Credit Card Number\n * @param cardNumber String\n */\n public CreditCard setCardNumber(@Nullable String cardNumber)\n {\n this.rawCardNumber = cardNumber;\n return this;\n }\n\n /**\n * Set auto animation of SwipeableCard\n * @param autoAnimation boolean auto animation, default true\n */\n @Override\n public CreditCard setAutoAnimation(boolean autoAnimation)\n {\n this.autoAnimation = autoAnimation;\n return this;\n }\n /**\n * Swipe to dismiss (left-right) animation for card, default false\n * @param isSwipe boolean\n */\n @Override\n public CreditCard setSwipeToDismiss(boolean isSwipe)\n {\n isSwipeLeftRight = isSwipe;\n return this;\n }\n\n /**\n * Set radius of SwipeableCard\n * @param radius float rapresent radius\n */\n @Override\n public CreditCard setCardRadius(float radius)\n {\n if(radius <= 0)\n {\n Log.e(\"CardRadius\", \"Impossible to set Card Radius lower than 0! Please Check it\");\n }\n else {\n mCardRadius = radius;\n }\n return this;\n }\n\n /**\n * Set additional item with OptionViewAdditional.Builder() constructor\n * @param option OptionViewAdditional\n */\n @Override\n public CreditCard setAdditionalItem(@NotNull OptionViewAdditional option)\n {\n optionViewAdditional = option;\n return this;\n }\n\n /**\n * Set animation duration for up and down Swipeable Card\n * @param durationInMillis representing the duration\n */\n @Override\n public CreditCard setDuration(long durationInMillis)\n {\n if(durationInMillis <= 0)\n {\n Log.e(\"Duration\", \"Impossible to set Duration lower than 0! Please Check it\");\n }\n else {\n mDuration = durationInMillis;\n }\n return this;\n }\n\n /**\n * Toolbar Listener for set own listener with own option to menu item.\n * @param toolbarListener An listener thath implements OnMenuItemClickListener(..)\n */\n @Override\n public CreditCard toolbarListener(@NotNull Toolbar.OnMenuItemClickListener toolbarListener)\n {\n mToolbarListener = toolbarListener;\n return this;\n }\n\n /**\n * Color Title of Swipeable Card, default is BLACK.\n * @param colorTitle A color for Title of Swipeable Card\n */\n @Override\n public CreditCard colorTitle(@ColorRes int colorTitle) {\n mColorTitle = colorTitle;\n return this;\n }\n\n /**\n * Menu Item for set custom menu item to Swipeable Card.\n * @param menuItem An int from R.menu class.\n */\n @Override\n public CreditCard menuItem(@AnyRes int menuItem) {\n\n if(menuItem == 0)\n {\n Log.e(\"MenuItem\", \"Impossible to set Menu Item to 0! Please Check it\");\n }\n else {\n mMenuItem = menuItem;\n isMenuItem = true;\n }\n return this;\n }\n\n /**\n * Set up your Title to Swipeable Card.\n * @param title String for Swipeable Card Title\n */\n @Override\n public CreditCard title(@NotNull String title) {\n mTitle = title;\n return this;\n }\n\n /**\n * Set sub title of Swipeable Card\n * @param subTitle String for sub title of Swipeable Card\n */\n @Override\n public CreditCard subTitle(@NotNull String subTitle) {\n mSubTitle = subTitle;\n isSubTitle = true;\n return this;\n }\n\n /**\n * Toolbar Color of Swipeable Card.\n * @param toolbarColor Resource integer which describe color\n */\n @Override\n public CreditCard toolbarColor(@ColorRes int toolbarColor) {\n\n if(toolbarColor == 0)\n {\n Log.e(\"ToolbarColor\", \"Impossible to set Toolbar Color to 0, default value transparent is set! Please Check it\");\n mToolbarColor = android.R.color.transparent;\n }\n else {\n mToolbarColor = toolbarColor;\n }\n return this;\n }\n\n /**\n * Public builder to set OptionView class with custom option.\n */\n @Override\n public OptionView build() {\n return new OptionView(this);\n }\n }\n\n /**\n * Maps Card mode\n */\n @SuppressWarnings(\"unused\")\n public static class MapsCard implements Card{\n private int mColorTitle;\n private int mMenuItem;\n private String mTitle;\n private String mText;\n private String mSubTitle;\n private int mImage;\n private int mToolbarColor;\n private boolean isMenuItem = false;\n private boolean isImage = false;\n private boolean isText = true;\n private boolean isSubTitle = false;\n private boolean isSwipeLeftRight = false;\n private Toolbar.OnMenuItemClickListener mToolbarListener;\n private long mDuration = 500;\n private float mCardRadius = 4f;\n private OptionViewAdditional optionViewAdditional;\n private float mZoom = 0;\n private boolean autoAnimation = true;\n\n /*\n Single Marker\n */\n private double latitude;\n private double longitude;\n private String markerTitle;\n private int markerIcon;\n private boolean isStreetName = true;\n private boolean singleMarker = false;\n /*\n Multiple Marker Array\n */\n private LatLng[] latLngArray;\n private String[] markerTitleArray;\n private int[] markerIconArray;\n /*\n Multiple Marker List\n */\n private List<LatLng> latLngList = new ArrayList<>();\n private List<String> markerTitleList = new ArrayList<>();\n private List<Integer> markerIconList = new ArrayList<>();\n private boolean multipleMarker = false;\n\n /**\n * Set auto animation of SwipeableCard\n * @param autoAnimation boolean auto animation, default true\n */\n @Override\n public MapsCard setAutoAnimation(boolean autoAnimation)\n {\n this.autoAnimation = autoAnimation;\n return this;\n }\n\n /**\n * Set location of maps\n * @param latLngs List list of LatLng point for marker\n * @param titles List list title of marker\n */\n public MapsCard setLocation(List<LatLng> latLngs, List<String> titles)\n {\n multipleMarker = true;\n singleMarker = false;\n latLngList = new ArrayList<>(latLngs);\n markerTitleList = new ArrayList<>(titles);\n return this;\n }\n\n\n /**\n * Set location of maps\n * @param latLngs List list of LatLng point for marker\n * @param titles List list title of marker\n * @param icon List ex. drawable icon\n */\n public MapsCard setLocation(List<LatLng> latLngs, List<String> titles, List<Integer> icon)\n {\n multipleMarker = true;\n singleMarker = false;\n latLngList = latLngs;\n markerTitleList = titles;\n markerIconList = icon;\n return this;\n }\n\n /**\n * Set location of maps\n * @param latLngs Array of LatLng\n * @param titles Array titles for marker\n */\n public MapsCard setLocation(LatLng[] latLngs, @NotNull String ... titles)\n {\n multipleMarker = true;\n singleMarker = false;\n latLngArray = latLngs;\n markerTitleArray = titles;\n return this;\n }\n\n /**\n * Set location of maps\n * @param latLngs Array of LatLng\n * @param titles Array titles for marker\n * @param icon Array of icon for makrer\n */\n public MapsCard setLocation(LatLng[] latLngs, @NotNull String[] titles, @DrawableRes int ... icon)\n {\n multipleMarker = true;\n singleMarker = false;\n latLngArray = latLngs;\n markerTitleArray = titles;\n markerIconArray = icon;\n return this;\n }\n\n /**\n * Set location of maps\n * @param latLngs Array of LatLng\n */\n public MapsCard setLocation(LatLng ... latLngs)\n {\n multipleMarker = true;\n singleMarker = false;\n latLngArray = latLngs;\n return this;\n }\n\n /**\n * Set location of maps\n * @param latLngs Array of LatLng\n * @param icon Array of icon for makrer\n */\n public MapsCard setLocation(LatLng[] latLngs, @DrawableRes int ... icon)\n {\n multipleMarker = true;\n singleMarker = false;\n latLngArray = latLngs;\n markerIconArray = icon;\n return this;\n }\n\n /**\n * Set location of maps\n * @param lat double describe latitude\n * @param lon double describe longitude\n */\n public MapsCard setLocation(double lat, double lon)\n {\n singleMarker = true;\n multipleMarker = false;\n latitude = lat;\n longitude = lon;\n return this;\n }\n\n /**\n * Set location of maps\n * @param lat double describe latitude\n * @param lon double describe longitude\n * @param title string title of marker\n */\n public MapsCard setLocation(double lat, double lon, @NotNull String title)\n {\n singleMarker = true;\n multipleMarker = false;\n latitude = lat;\n longitude = lon;\n markerTitle = title;\n return this;\n }\n\n /**\n * Set location of maps\n * @param lat double describe latitude\n * @param lon double describe longitude\n * @param icon int rapresent icon of marker\n */\n public MapsCard setLocation(double lat, double lon, @DrawableRes int icon)\n {\n singleMarker = true;\n multipleMarker = false;\n latitude = lat;\n longitude = lon;\n markerIcon = icon;\n return this;\n }\n\n /**\n * Set location of maps\n * @param lat double describe latitude\n * @param lon double describe longitude\n * @param title string title of marker\n * @param icon int rapresent icon of marker\n * @return MapsCard\n */\n public MapsCard setLocation(double lat, double lon, @NotNull String title, @DrawableRes int icon)\n {\n singleMarker = true;\n multipleMarker = false;\n latitude = lat;\n longitude = lon;\n markerTitle = title;\n markerIcon = icon;\n return this;\n }\n\n /**\n * Set zoom for maps, default 10f\n * @param zoom float for zoom level\n */\n public MapsCard setZoom(float zoom)\n {\n mZoom = zoom;\n return this;\n }\n\n /**\n * Show street name, works on a single marker, default false\n * @param isStreetName boolean\n */\n public MapsCard withStreetName(boolean isStreetName)\n {\n this.isStreetName = isStreetName;\n return this;\n }\n\n /**\n * Swipe to dismiss (left-right) animation for card, default false\n * @param isSwipe boolean\n */\n @Override\n public MapsCard setSwipeToDismiss(boolean isSwipe)\n {\n isSwipeLeftRight = isSwipe;\n return this;\n }\n\n /**\n * Set radius of SwipeableCard\n * @param radius float rapresent radius\n */\n @Override\n public MapsCard setCardRadius(float radius)\n {\n if(radius <= 0)\n {\n Log.e(\"CardRadius\", \"Impossible to set Card Radius lower than 0! Please Check it\");\n }\n else {\n mCardRadius = radius;\n }\n return this;\n }\n\n /**\n * Set additional item with OptionViewAdditional.Builder() constructor\n * @param option OptionViewAdditional\n */\n @Override\n public MapsCard setAdditionalItem(@NotNull OptionViewAdditional option)\n {\n optionViewAdditional = option;\n return this;\n }\n\n /**\n * Set animation duration for up and down Swipeable Card\n * @param durationInMillis representing the duration\n */\n @Override\n public MapsCard setDuration(long durationInMillis)\n {\n if(durationInMillis <= 0)\n {\n Log.e(\"Duration\", \"Impossible to set Duration lower than 0! Please Check it\");\n }\n else {\n mDuration = durationInMillis;\n }\n return this;\n }\n\n /**\n * Toolbar Listener for set own listener with own option to menu item.\n * @param toolbarListener An listener thath implements OnMenuItemClickListener(..)\n */\n @Override\n public MapsCard toolbarListener(@NotNull Toolbar.OnMenuItemClickListener toolbarListener)\n {\n mToolbarListener = toolbarListener;\n return this;\n }\n\n /**\n * Color Title of Swipeable Card, default is BLACK.\n * @param colorTitle A color for Title of Swipeable Card\n */\n @Override\n public MapsCard colorTitle(@ColorRes int colorTitle) {\n mColorTitle = colorTitle;\n return this;\n }\n\n /**\n * Menu Item for set custom menu item to Swipeable Card.\n * @param menuItem An int from R.menu class.\n */\n @Override\n public MapsCard menuItem(@AnyRes int menuItem) {\n\n if(menuItem == 0)\n {\n Log.e(\"MenuItem\", \"Impossible to set Menu Item to 0! Please Check it\");\n }\n else {\n mMenuItem = menuItem;\n isMenuItem = true;\n }\n return this;\n }\n\n /**\n * Set up your Title to Swipeable Card.\n * @param title String for Swipeable Card Title\n */\n @Override\n public MapsCard title(@NotNull String title) {\n mTitle = title;\n return this;\n }\n\n /**\n * Set sub title of Swipeable Card\n * @param subTitle String for sub title of Swipeable Card\n */\n @Override\n public MapsCard subTitle(@NotNull String subTitle) {\n mSubTitle = subTitle;\n isSubTitle = true;\n return this;\n }\n\n /**\n * Toolbar Color of Swipeable Card.\n * @param toolbarColor Resource integer which describe color\n */\n @Override\n public MapsCard toolbarColor(@ColorRes int toolbarColor) {\n\n if(toolbarColor == 0)\n {\n Log.e(\"ToolbarColor\", \"Impossible to set Toolbar Color to 0, default value transparent is set! Please Check it\");\n mToolbarColor = android.R.color.transparent;\n }\n else {\n mToolbarColor = toolbarColor;\n }\n return this;\n }\n\n /**\n * Public builder to set OptionView class with custom option.\n */\n @Override\n public OptionView build() {\n return new OptionView(this);\n }\n\n }\n\n /**\n * Normal Card Mode\n */\n public static class NormalCard implements Card{\n private int mColorTitle;\n private int mMenuItem;\n private String mTitle;\n private String mText;\n private String mSubTitle;\n private int mImage;\n private int mToolbarColor;\n private boolean isMenuItem = false;\n private boolean isImage = false;\n private boolean isText = true;\n private boolean isSubTitle = false;\n private boolean isSwipeLeftRight = false;\n private Toolbar.OnMenuItemClickListener mToolbarListener;\n private long mDuration = 500;\n private float mCardRadius = 4f;\n private boolean autoAnimation = true;\n private OptionViewAdditional optionViewAdditional;\n\n /**\n * Set auto animation of SwipeableCard\n * @param autoAnimation boolean auto animation, default true\n */\n @Override\n public NormalCard setAutoAnimation(boolean autoAnimation)\n {\n this.autoAnimation = autoAnimation;\n return this;\n }\n /**\n * Swipe to dismiss (left-right) animation for card, default false\n * @param isSwipe boolean\n */\n @Override\n public NormalCard setSwipeToDismiss(boolean isSwipe)\n {\n isSwipeLeftRight = isSwipe;\n return this;\n }\n\n /**\n * Set radius of SwipeableCard\n * @param radius float rapresent radius\n */\n @Override\n public NormalCard setCardRadius(float radius)\n {\n if(radius <= 0)\n {\n Log.e(\"CardRadius\", \"Impossible to set Card Radius lower than 0! Please Check it\");\n }\n else {\n mCardRadius = radius;\n }\n return this;\n }\n\n /**\n * Set additional item with OptionViewAdditional.Builder() constructor\n * @param option OptionViewAdditional\n */\n @Override\n public NormalCard setAdditionalItem(@NotNull OptionViewAdditional option)\n {\n optionViewAdditional = option;\n return this;\n }\n\n /**\n * Set animation duration for up and down Swipeable Card\n * @param durationInMillis representing the duration\n */\n @Override\n public NormalCard setDuration(long durationInMillis)\n {\n if(durationInMillis <= 0)\n {\n Log.e(\"Duration\", \"Impossible to set Duration lower than 0! Please Check it\");\n }\n else {\n mDuration = durationInMillis;\n }\n return this;\n }\n\n /**\n * Toolbar Listener for set own listener with own option to menu item.\n * @param toolbarListener An listener thath implements OnMenuItemClickListener(..)\n */\n @Override\n public NormalCard toolbarListener(@NotNull Toolbar.OnMenuItemClickListener toolbarListener)\n {\n mToolbarListener = toolbarListener;\n return this;\n }\n\n /**\n * Color Title of Swipeable Card, default is BLACK.\n * @param colorTitle A color for Title of Swipeable Card\n */\n @Override\n public NormalCard colorTitle(@ColorRes int colorTitle) {\n mColorTitle = colorTitle;\n return this;\n }\n\n /**\n * Menu Item for set custom menu item to Swipeable Card.\n * @param menuItem An int from R.menu class.\n */\n @Override\n public NormalCard menuItem(@AnyRes int menuItem) {\n\n if(menuItem == 0)\n {\n Log.e(\"MenuItem\", \"Impossible to set Menu Item to 0! Please Check it\");\n }\n else {\n mMenuItem = menuItem;\n isMenuItem = true;\n }\n return this;\n }\n\n /**\n * Set up your Title to Swipeable Card.\n * @param title String for Swipeable Card Title\n */\n @Override\n public NormalCard title(@NotNull String title) {\n mTitle = title;\n return this;\n }\n\n /**\n * Set text on content of Swipeable Card.\n * @param text String for content of Swipeable Card.\n */\n public NormalCard text(@NotNull String text) {\n mText = text;\n isImage = false;\n isText = true;\n return this;\n }\n\n /**\n * Set sub title of Swipeable Card\n * @param subTitle String for sub title of Swipeable Card\n */\n @Override\n public NormalCard subTitle(@NotNull String subTitle) {\n mSubTitle = subTitle;\n isSubTitle = true;\n return this;\n }\n\n /**\n * Image for Swipeable Card.\n * @param image Resource integer which describe image\n */\n public NormalCard image(@DrawableRes int image) {\n mImage = image;\n isImage = true;\n isText = false;\n return this;\n }\n\n /**\n * Toolbar Color of Swipeable Card.\n * @param toolbarColor Resource integer which describe color\n */\n @Override\n public NormalCard toolbarColor(@ColorRes int toolbarColor) {\n\n if(toolbarColor == 0)\n {\n Log.e(\"ToolbarColor\", \"Impossible to set Toolbar Color to 0, default value transparent is set! Please Check it\");\n mToolbarColor = android.R.color.transparent;\n }\n else {\n mToolbarColor = toolbarColor;\n }\n return this;\n }\n\n /**\n * Public builder to set OptionView class with custom option.\n */\n @Override\n public OptionView build() {\n return new OptionView(this);\n }\n }\n\n}",
"public class OptionViewAdditional {\n /**\n * Customizable Icon and Text\n */\n private int mIconBtn1;\n private int mIconBtn2;\n private int mIconBtn3;\n private String mTextBtn1;\n private String mTextBtn2;\n private boolean isIconBtn1 = false;\n private boolean isIconBtn2 = false;\n private boolean isIconBtn3 = false;\n private boolean isTextBtn1 = false;\n private boolean isTextBtn2 = false;\n private int mTextColorBtn1;\n private int mTextColorBtn2;\n private float mTextSizeBtn1;\n private float mTextSizeBtn2;\n private int mFabBackgroundColor;\n private int mFabIcon;\n /*\n Listener\n */\n private View.OnClickListener mOnClickListenerIconBtn1;\n private View.OnClickListener mOnClickListenerIconBtn2;\n private View.OnClickListener mOnClickListenerIconBtn3;\n private View.OnClickListener mOnClickListenerTextBtn1;\n private View.OnClickListener mOnClickListenerTextBtn2;\n private View.OnClickListener mOnClickListenerFab;\n\n public OptionViewAdditional(@NotNull Builder builder) {\n /**\n * Customizable Icon and Text\n */\n mIconBtn1 = builder.mIconBtn1;\n mIconBtn2 = builder.mIconBtn2;\n mIconBtn3 = builder.mIconBtn3;\n mTextBtn1 = builder.mTextBtn1;\n mTextBtn2 = builder.mTextBtn2;\n isTextBtn1 = builder.isTextBtn1;\n isTextBtn2 = builder.isTextBtn2;\n isIconBtn1 = builder.isIconBtn1;\n isIconBtn2 = builder.isIconBtn2;\n isIconBtn3 = builder.isIconBtn3;\n mFabBackgroundColor = builder.mFabBackgroundColor;\n mFabIcon = builder.mFabIcon;\n /*\n Listener\n */\n if(builder.mOnClickListenerFab == null)\n {\n Log.w(\"ListenerFab\", \"Listener is not set!\");\n }else\n {\n mOnClickListenerFab = builder.mOnClickListenerFab;\n }\n if(builder.mOnClickListenerIconBtn1 == null)\n {\n Log.w(\"ListenerIconButton1\", \"Listener is not set!\");\n }else\n {\n mOnClickListenerIconBtn1 = builder.mOnClickListenerIconBtn1;\n }\n\n if(builder.mOnClickListenerIconBtn2 == null)\n {\n Log.w(\"ListenerIconButton2\", \"Listener is not set!\");\n }else\n {\n mOnClickListenerIconBtn2 = builder.mOnClickListenerIconBtn2;\n }\n\n if(builder.mOnClickListenerIconBtn3 == null)\n {\n Log.w(\"ListenerIconButton3\", \"Listener is not set!\");\n }else\n {\n mOnClickListenerIconBtn3 = builder.mOnClickListenerIconBtn3;\n }\n if(builder.mOnClickListenerTextBtn1 == null)\n {\n Log.w(\"ListenerTextButton1\", \"Listener is not set!\");\n }else\n {\n mOnClickListenerTextBtn1 = builder.mOnClickListenerTextBtn1;\n }\n if(builder.mOnClickListenerTextBtn2 == null)\n {\n Log.w(\"ListenerTextButton2\", \"Listener is not set!\");\n }else\n {\n mOnClickListenerTextBtn2 = builder.mOnClickListenerTextBtn2;\n }\n\n\n if(builder.mTextSizeBtn1 == 0) {\n Log.e(\"TextSizeButton1\", \"Impossible to set Text Size to 0, default value 15sp is set! Please Check it\");\n mTextSizeBtn1 = 15f;\n }\n else\n {\n mTextSizeBtn1 = builder.mTextSizeBtn1;\n }\n if(builder.mTextSizeBtn2 == 0) {\n Log.e(\"TextSizeButton2\", \"Impossible to set Text Size to 0, default value 15sp is set! Please Check it\");\n mTextSizeBtn2 = 15f;\n }\n else\n {\n mTextSizeBtn2 = builder.mTextSizeBtn2;\n }\n if(builder.mTextColorBtn1 == 0)\n {\n Log.e(\"TextColorButton1\", \"Impossible to set Text Color Button to 0, default value black is set! Please Check it\");\n mTextColorBtn1 = android.R.color.black;\n\n }else {\n mTextColorBtn1 = builder.mTextColorBtn1;\n }\n if(builder.mTextColorBtn2 == 0)\n {\n Log.e(\"TextColorButton2\", \"Impossible to set Text Color Button to 0, default value black is set! Please Check it\");\n mTextColorBtn2 = android.R.color.black;\n\n }else {\n mTextColorBtn2 = builder.mTextColorBtn2;\n }\n }\n\n public static class Builder {\n /**\n * Customizable Icon and Text\n */\n private int mIconBtn1;\n private int mIconBtn2;\n private int mIconBtn3;\n private String mTextBtn1;\n private String mTextBtn2;\n private boolean isIconBtn1 = false;\n private boolean isIconBtn2 = false;\n private boolean isIconBtn3 = false;\n private boolean isTextBtn1 = false;\n private boolean isTextBtn2 = false;\n private int mTextColorBtn1;\n private int mTextColorBtn2;\n private float mTextSizeBtn1;\n private float mTextSizeBtn2;\n /*\n Listener\n */\n private View.OnClickListener mOnClickListenerIconBtn1;\n private View.OnClickListener mOnClickListenerIconBtn2;\n private View.OnClickListener mOnClickListenerIconBtn3;\n private View.OnClickListener mOnClickListenerTextBtn1;\n private View.OnClickListener mOnClickListenerTextBtn2;\n private View.OnClickListener mOnClickListenerFab;\n private int mFabBackgroundColor;\n private int mFabIcon;\n\n /**\n * Set OnClickListener for Fab Button\n * @param listener OnClickListener\n */\n public Builder setOnClickListenerFab(@NotNull View.OnClickListener listener)\n {\n mOnClickListenerFab = listener;\n return this;\n }\n\n /**\n * Set Fab Icon\n * @param icon int\n */\n public Builder setFabIcon(@DrawableRes int icon)\n {\n if(icon <= 0)\n {\n Log.e(\"FabIcon\", \"Impossible to set Fab Icon Resource lower than 0! Please Check it\");\n }\n else {\n mFabIcon = icon;\n }\n return this;\n }\n\n\n /**\n * Set Fab Color\n * @param color int\n */\n public Builder setFabColor(@ColorRes int color)\n {\n if(color <= 0)\n {\n Log.e(\"FabColor\", \"Impossible to set Fab Color lower than 0! Please Check it\");\n mFabBackgroundColor = android.R.color.transparent;\n }\n else {\n mFabBackgroundColor = color;\n }\n return this;\n }\n\n /**\n * Set OnClickListener for Text Button\n * @param listeners OnClickListener interface\n */\n public Builder setOnClickListenerTextButton(@NotNull View.OnClickListener... listeners)\n {\n if(listeners.length > 2)\n {\n Log.e(\"ListenerTextButton\", \"Impossible to set Listener Button value more than 2! Please Check it\");\n throw new IllegalArgumentException(\"Impossible to set Listener Icon Button value more than 2! Please Check it\");\n }\n if(listeners.length > 0)\n {\n if(listeners[0] == null) {\n Log.e(\"ListenerTextButton\", \"Impossible to set Listener Text Button to null! Please Check it\");\n }\n else{\n mOnClickListenerTextBtn1 = listeners[0];\n }\n }\n if(listeners.length > 1)\n {\n if(listeners[1] == null) {\n Log.e(\"ListenerTextButton\", \"Impossible to set Listener Text Button to null! Please Check it\");\n }\n else{\n mOnClickListenerTextBtn2 = listeners[1];\n }\n }\n return this;\n }\n\n /**\n * Set OnClickListener for Icon Button\n * @param listeners OnClickListener interface\n */\n public Builder setOnClickListenerIconButton(@NotNull View.OnClickListener... listeners)\n {\n if(listeners.length > 3)\n {\n Log.e(\"ListenerIconButton\", \"Impossible to set Listener Button value more than 3! Please Check it\");\n throw new IllegalArgumentException(\"Impossible to set Listener Icon Button value more than 2! Please Check it\");\n }\n if(listeners.length > 0)\n {\n if(listeners[0] == null) {\n Log.e(\"ListenerIconButton\", \"Impossible to set Listener Icon Button to null! Please Check it\");\n }\n else{\n mOnClickListenerIconBtn1 = listeners[0];\n }\n }\n if(listeners.length > 1)\n {\n if(listeners[1] == null) {\n Log.e(\"ListenerIconButton\", \"Impossible to set Listener Icon Button to null! Please Check it\");\n }\n else{\n mOnClickListenerIconBtn2 = listeners[1];\n }\n }\n if(listeners.length > 2)\n {\n if(listeners[2] == null) {\n Log.e(\"ListenerIconButton\", \"Impossible to set Listener Icon Button to null! Please Check it\");\n }\n else{\n mOnClickListenerIconBtn3 = listeners[1];\n }\n }\n return this;\n }\n\n /**\n * Set Text Size\n * @param size float\n */\n public Builder textSize(float... size)\n {\n if(size.length > 2)\n {\n Log.e(\"TextSizeButton\", \"Impossible to set Text Size value more than 2! Please Check it\");\n throw new IllegalArgumentException(\"Impossible to set Text Size value more than 2! Please Check it\");\n }\n if(size.length > 0)\n {\n if(size[0] == 0) {\n Log.e(\"TextSizeButton\", \"Impossible to set Text Size to 0, default value 15sp is set! Please Check it\");\n mTextSizeBtn1 = 15f;\n }\n else\n {\n mTextSizeBtn1 = size[0];\n }\n }\n if(size.length > 1)\n {\n if(size[1] == 0) {\n Log.e(\"TextSizeButton\", \"Impossible to set Text Size to 0, default value 15sp is set! Please Check it\");\n mTextSizeBtn2 = 15f;\n }\n else {\n mTextSizeBtn2 = size[1];\n }\n }\n return this;\n }\n\n /**\n * Set Text Color of Button Text\n * @param color int\n */\n public Builder textColorButton(@ColorRes int... color)\n {\n if(color.length > 2)\n {\n Log.e(\"TextColorButton\", \"Impossible to set Text Color Button value more than 2! Please Check it\");\n throw new IllegalArgumentException(\"Impossible to set Text Color Button value more than 2! Please Check it\");\n }\n if(color.length > 0)\n {\n if(color[0] == 0) {\n Log.e(\"TextColorButton\", \"Impossible to set Text Color Button to 0, default value black is set! Please Check it\");\n mTextColorBtn1 = android.R.color.black;\n }\n else{\n mTextColorBtn1 = color[0];\n }\n }\n if(color.length > 1)\n {\n if(color[1] == 0) {\n Log.e(\"TextColorButton\", \"Impossible to set Text Color Button to 0, default value black is set! Please Check it\");\n mTextColorBtn2 = android.R.color.black;\n }\n else{\n mTextColorBtn2 = color[1];\n }\n }\n return this;\n }\n\n /**\n * Set Icon on Icon Button\n * @param icon int\n */\n public Builder iconButton(@DrawableRes int... icon)\n {\n if(icon.length > 3)\n {\n Log.e(\"TextColorButton\", \"Impossible to set Icon Button value more than 3! Please Check it\");\n throw new IllegalArgumentException(\"Impossible to set Icon Button value more than 3! Please Check it\");\n }\n if(icon.length > 0)\n {\n if(icon[0] == 0) {\n Log.e(\"Icon\", \"Impossible to set Icon to 0! Please Check it\");\n }else{\n mIconBtn1 = icon[0];\n isIconBtn1 = true;\n }\n }\n if(icon.length > 1)\n {\n if(icon[1] == 0) {\n Log.e(\"Icon\", \"Impossible to set Icon to 0! Please Check it\");\n }else{\n mIconBtn2 = icon[1];\n isIconBtn2 = true;\n }\n }\n\n if(icon.length > 2)\n {\n if(icon[2] == 0) {\n Log.e(\"Icon\", \"Impossible to set Icon to 0! Please Check it\");\n }else{\n mIconBtn3 = icon[2];\n isIconBtn3 = true;\n }\n }\n return this;\n }\n\n /**\n * Set Text on Text Button\n * @param text String\n */\n public Builder textButton(@NotNull String... text)\n {\n if(text.length > 2)\n {\n Log.e(\"TextColorButton\", \"Impossible to set Text Button value more than 2! Please Check it\");\n throw new IllegalArgumentException(\"Impossible to set Text Button value more than 2! Please Check it\");\n }\n if(text.length > 0)\n {\n if(text[0] == null) {\n Log.e(\"TextButton\", \"Impossible to set Text to null! Please Check it\");\n }\n else\n {\n mTextBtn1 = text[0];\n isTextBtn1 = true;\n }\n }\n if(text.length > 1)\n {\n if(text[1] == null) {\n Log.e(\"TextButton\", \"Impossible to set Text to null! Please Check it\");\n }\n else {\n mTextBtn2 = text[1];\n isTextBtn2 = true;\n }\n }\n return this;\n }\n\n /**\n * Constructor build()\n */\n public OptionViewAdditional build() {\n return new OptionViewAdditional(this);\n }\n }\n\n /**\n * Return true (boolean) if isIconBtn1 is set\n * @return true (boolean) if isIconBtn1 is set\n */\n public boolean isIconBtn1() {\n return isIconBtn1;\n }\n\n /**\n * Return true (boolean) if isIconBtn2 is set\n * @return true (boolean) if isIconBtn2 is set\n */\n public boolean isIconBtn2() {\n return isIconBtn2;\n }\n\n /**\n * Return true (boolean) if isIconBtn3 is set\n * @return true (boolean) if isIconBtn3 is set\n */\n public boolean isIconBtn3() {\n return isIconBtn3;\n }\n\n /**\n * Return true (boolean) if isTextBtn1 is set\n * @return true (boolean) if isTextBtn1 is set\n */\n public boolean isTextBtn1() {\n return isTextBtn1;\n }\n\n /**\n * Return true (boolean) if isTextBtn1 is set\n * @return true (boolean) if isTextBtn1 is set\n */\n public boolean isTextBtn2() {\n return isTextBtn2;\n }\n\n /**\n * Return int of Icon Button 1\n * @return int of Icon Button 1\n */\n public int getIconBtn1() {\n return mIconBtn1;\n }\n\n /**\n * Return int of Icon Button 2\n * @return int of Icon Button 2\n */\n public int getIconBtn2() {\n return mIconBtn2;\n }\n\n /**\n * Return int of Icon Button 3\n * @return int of Icon Button 3\n */\n public int getIconBtn3() {\n return mIconBtn3;\n }\n\n /**\n * Return String of Text Button 1\n * @return String of Text Button 1\n */\n public String getTextBtn1() {\n return mTextBtn1;\n }\n\n /**\n * Return String of Text Button 2\n * @return String of Text Button 2\n */\n public String getTextBtn2() {\n return mTextBtn2;\n }\n\n /**\n * Return int color of Text Button 1\n * @return int color of Text Button 1\n */\n public int getTextColorBtn1() {\n return mTextColorBtn1;\n }\n\n /**\n * Return int color of Text Button 2\n * @return int color of Text Button 2\n */\n public int getTextColorBtn2() {\n return mTextColorBtn2;\n }\n\n /**\n * Return float size of Text Button 1\n * @return float size of Text Button 1\n */\n public float getTextSizeBtn1() {\n return mTextSizeBtn1;\n }\n\n /**\n * Return float size of Text Button 2\n * @return float size of Text Button 2\n */\n public float getTextSizeBtn2() {\n return mTextSizeBtn2;\n }\n\n /**\n * Return onClickListener of Icon Button 1\n * @return onClickListener of Icon Button 1\n */\n @NotNull\n public View.OnClickListener getOnClickListenerIconBtn1() {\n return mOnClickListenerIconBtn1;\n }\n\n /**\n * Return onClickListener of Icon Button 2\n * @return onClickListener of Icon Button 2\n */\n @NotNull\n public View.OnClickListener getOnClickListenerIconBtn2() {\n return mOnClickListenerIconBtn2;\n }\n\n /**\n * Return onClickListener of Text Button 1\n * @return onClickListener of Text Button 1\n */\n @NotNull\n public View.OnClickListener getOnClickListenerTextBtn1() {\n return mOnClickListenerTextBtn1;\n }\n\n /**\n * Return onClickListener of Text Button 2\n * @return onClickListener of Text Button 2\n */\n @NotNull\n public View.OnClickListener getOnClickListenerTextBtn2() {\n return mOnClickListenerTextBtn2;\n }\n\n /**\n * Return onClickListener of Icon Button 1\n * @return onClickListener of Icon Button 1\n */\n @NotNull\n public View.OnClickListener getOnClickListenerIconBtn3() {\n return mOnClickListenerIconBtn3;\n }\n\n /**\n * Get Floating Action Button color\n * @return int color\n */\n public int getFabBackgroundColor() {\n return mFabBackgroundColor;\n }\n\n /**\n * Get Floating Action Button icon\n * @return int icon\n */\n public int getFabIcon() {\n return mFabIcon;\n }\n\n /**\n * Get OnClickListener for Floating Action Button\n * @return OnClickListener fab\n */\n @NotNull\n public View.OnClickListener getOnClickListenerFab() {\n return mOnClickListenerFab;\n }\n\n\n}",
"public class SwipeableCard extends LinearLayout implements View.OnClickListener, AnimationCard, OnMapReadyCallback{\n\n private int previousFingerPositionY;\n private int previousFingerPositionX;\n private boolean isLocked = false;\n private int pressedy;\n private int viewMariginY;\n\n private CardView card;\n private ImageView image;\n private TextView text;\n private TextView subTitle;\n private Toolbar toolbar;\n private int height;\n private FloatingActionButton fab;\n private FrameLayout frame;\n private OptionView mOptionView = null;\n private CreditCardView creditCardView;\n private Button newCreditCard;\n\n /**\n * Private Variable\n */\n private float cardRadiusAttr;\n private long duration;\n private String titleAttr;\n private String subTitleAttr;\n private int colorTitleAttr;\n private int colorToolbarAttr;\n private int imageAttr;\n private String textAttr;\n private boolean isSwipeToDismiss;\n private boolean isAutoAnimation;\n //private View rootView;\n\n /**\n * Maps Variable\n */\n private GoogleMap mGoogleMap;\n private LatLng mMapLocation;\n private MapView mapView;\n private TextView streetNameView;\n private RelativeLayout relativeMaps;\n private RelativeLayout relativeNormal;\n private RelativeLayout relativeCreditCard;\n private RelativeLayout relativeCreditCardCreation;\n private float mapsZoom;\n\n /**\n * Customizable Icon and Text\n */\n private ImageView iconBtn1;\n private ImageView iconBtn2;\n private ImageView iconBtn3;\n private TextView textBtn1;\n private TextView textBtn2;\n\n @SuppressWarnings(\"all\")\n public void init(@NotNull final Context context, @NotNull final OptionView option){\n if(option != null)\n {\n mOptionView = option;\n /*\n Check if Listener was set, clear and re-set it.\n */\n this.setOnTouchListener(null);\n /*\n Clear title and re-set it.\n */\n titleAttr = null;\n titleAttr = option.getTitle();\n /*\n Get Screen Size.\n */\n height = getScreenSize(context);\n\n /*\n Set up xml object.\n */\n card = (CardView) findViewById(R.id.card);\n image = (ImageView) findViewById(R.id.image);\n text = (TextView) findViewById(R.id.text);\n subTitle = (TextView) findViewById(R.id.subTitle);\n frame = (FrameLayout) findViewById(R.id.frame);\n mapView = (MapView) findViewById(R.id.mapLite);\n streetNameView = (TextView) findViewById(R.id.streetName);\n relativeNormal = (RelativeLayout) findViewById(R.id.relativeNormal);\n relativeMaps = (RelativeLayout) findViewById(R.id.relativeMaps);\n relativeCreditCard = (RelativeLayout) findViewById(R.id.relativeCreditCard);\n relativeCreditCardCreation = (RelativeLayout) findViewById(R.id.relativeCreditCardCreation);\n newCreditCard = (Button) findViewById(R.id.creditCardButton);\n /**\n * Set-up customizable Icon and Text\n */\n iconBtn1 = (ImageView) findViewById(R.id.iconBtn1);\n iconBtn2 = (ImageView) findViewById(R.id.iconBtn2);\n iconBtn3 = (ImageView) findViewById(R.id.iconBtn3);\n textBtn1 = (TextView) findViewById(R.id.textBtn1);\n textBtn2 = (TextView) findViewById(R.id.textBtn2);\n fab = (FloatingActionButton) findViewById(R.id.fab);\n creditCardView = (CreditCardView) findViewById(R.id.creditCard);\n\n frame.setOnTouchListener(null);\n card.setRadius(cardRadiusAttr);\n if(!option.isAutoAnimation()) {\n fab.setVisibility(GONE);\n }\n card.setLayoutParams(new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));\n\n\n /**\n * Check if Maps Card is set (reset object before)\n */\n streetNameView.setVisibility(GONE);\n mapView.setVisibility(GONE);\n relativeCreditCard.setVisibility(GONE);\n relativeCreditCardCreation.setVisibility(GONE);\n relativeNormal.setVisibility(GONE);\n relativeMaps.setVisibility(GONE);\n if(option.isTypeCardMaps() == true) {\n /**\n * Multiple marker mode\n */\n if((option.getLatLngArray() != null && option.getLatLngArray().length > 0) ||\n (option.getLatLngList() != null && option.getLatLngList().size() > 0)\n && option.isMultipleMarker() && !option.isSingleMarker())\n {\n relativeNormal.setVisibility(GONE);\n relativeMaps.setVisibility(VISIBLE);\n mapView.setVisibility(VISIBLE);\n text.setVisibility(GONE);\n image.setVisibility(GONE);\n mapView.onCreate(null);\n mapView.getMapAsync(this);\n setMapLocation();\n }else {\n /**\n * Single marker mode\n */\n mapsZoom = option.getMapsZoom();\n relativeNormal.setVisibility(GONE);\n relativeMaps.setVisibility(VISIBLE);\n mapView.setVisibility(VISIBLE);\n text.setVisibility(GONE);\n image.setVisibility(GONE);\n mapView.onCreate(null);\n mapView.getMapAsync(this);\n setMapLocation(option.getLatitude(), option.getLongitude());\n if(option.isStreetName() == true)\n {\n streetNameView.setText(getStreetNameFromLatLong(option.getLatitude(), option.getLongitude(), context));\n streetNameView.setVisibility(VISIBLE);\n }\n }\n }else if(option.isTypeCardCredit() == true) {\n if(option.isCreateCreditCard()) {\n /**\n * Create Card mode\n */\n newCreditCard.setVisibility(VISIBLE);\n relativeCreditCardCreation.setVisibility(VISIBLE);\n relativeCreditCard.setVisibility(GONE);\n newCreditCard.setOnClickListener(new OnClickListener() {\n @Override\n public void onClick(View v) {\n ActivityCardCreation.setCreditCardView(creditCardView, option, newCreditCard, relativeCreditCardCreation, relativeCreditCard);\n Intent intent = new Intent(option.getActivity(), ActivityCardCreation.class);\n option.getActivity().startActivityForResult(intent, 1);\n }\n });\n }else {\n /**\n * Setted Credit Card\n */\n creditCardView.setCardExpiry(option.getDateYear());\n creditCardView.setCardNumber(option.getRawCardNumber());\n creditCardView.setCardHolderName(option.getCardHolderName());\n if(option.getCvv() != null)\n {\n creditCardView.setCVV(option.getCvv());\n }else {\n creditCardView.setCVV(option.getIntCvv());\n }\n creditCardView.showFront();\n creditCardView.setOnClickListener(new OnClickListener() {\n boolean back = false;\n\n @Override\n public void onClick(View v) {\n if (!back) {\n creditCardView.showBack();\n back = true;\n } else {\n creditCardView.showFront();\n back = false;\n }\n }\n });\n relativeCreditCardCreation.setVisibility(GONE);\n relativeCreditCard.setVisibility(VISIBLE);\n }\n }else {\n relativeCreditCard.setVisibility(GONE);\n relativeCreditCardCreation.setVisibility(GONE);\n relativeNormal.setVisibility(VISIBLE);\n relativeMaps.setVisibility(GONE);\n }\n\n /**\n * Check if Additional Option is set (reset object before)\n */\n fab.setVisibility(GONE);\n iconBtn1.setVisibility(GONE);\n iconBtn2.setVisibility(GONE);\n iconBtn3.setVisibility(GONE);\n textBtn1.setVisibility(GONE);\n textBtn2.setVisibility(GONE);\n if(option.getOptionViewAdditional() != null) {\n if (option.getOptionViewAdditional().getFabIcon() > 0) {\n fab.setVisibility(View.VISIBLE);\n if (option.getOptionViewAdditional().getFabIcon() > 0) {\n fab.setImageResource(option.getOptionViewAdditional().getFabIcon());\n }\n if (option.getOptionViewAdditional().getFabBackgroundColor() > 0) {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {\n fab.setBackgroundTintList(ColorStateList.valueOf(ContextCompat.getColor(context, option.getOptionViewAdditional().getFabBackgroundColor())));\n } else {\n fab.setBackgroundTintList(ColorStateList.valueOf(getResources().getColor(option.getOptionViewAdditional().getFabBackgroundColor())));\n }\n }\n fab.setOnClickListener(option.getOptionViewAdditional().getOnClickListenerFab());\n }\n /**\n * Check if Additional Icon Button 1\n */\n if (option.getOptionViewAdditional().isIconBtn1()) {\n iconBtn1.setVisibility(View.VISIBLE);\n iconBtn1.setImageResource(option.getOptionViewAdditional().getIconBtn1());\n iconBtn1.setOnClickListener(option.getOptionViewAdditional().getOnClickListenerIconBtn1());\n\n }\n /**\n * Check if Additional Icon Button 2\n */\n if (option.getOptionViewAdditional().isIconBtn2()) {\n iconBtn2.setVisibility(View.VISIBLE);\n iconBtn2.setImageResource(option.getOptionViewAdditional().getIconBtn2());\n iconBtn2.setOnClickListener(option.getOptionViewAdditional().getOnClickListenerIconBtn2());\n }\n /**\n * Check if Additional Icon Button 3\n */\n if (option.getOptionViewAdditional().isIconBtn3()) {\n iconBtn3.setVisibility(View.VISIBLE);\n iconBtn3.setImageResource(option.getOptionViewAdditional().getIconBtn3());\n iconBtn3.setOnClickListener(option.getOptionViewAdditional().getOnClickListenerIconBtn3());\n }\n /**\n * Check if Additional Text Button 1\n */\n if (option.getOptionViewAdditional().isTextBtn1()) {\n textBtn1.setVisibility(View.VISIBLE);\n textBtn1.setText(option.getOptionViewAdditional().getTextBtn1());\n textBtn1.setTextSize(option.getOptionViewAdditional().getTextSizeBtn1());\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {\n textBtn1.setTextColor(ContextCompat.getColor(context, option.getOptionViewAdditional().getTextColorBtn1()));\n } else {\n textBtn1.setTextColor(getResources().getColor(option.getOptionViewAdditional().getTextColorBtn1()));\n }\n /**\n * Set OnClickListener Additional Text Button 1\n */\n textBtn1.setOnClickListener(option.getOptionViewAdditional().getOnClickListenerTextBtn1());\n }\n /**\n * Check if Additional Text Button 2\n */\n if (option.getOptionViewAdditional().isTextBtn2()) {\n textBtn2.setVisibility(View.VISIBLE);\n textBtn2.setText(option.getOptionViewAdditional().getTextBtn2());\n textBtn2.setTextSize(option.getOptionViewAdditional().getTextSizeBtn2());\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {\n textBtn2.setTextColor(ContextCompat.getColor(context, option.getOptionViewAdditional().getTextColorBtn2()));\n } else {\n textBtn2.setTextColor(getResources().getColor(option.getOptionViewAdditional().getTextColorBtn2()));\n }\n /**\n * Set OnClickListener Additional Text Button 2\n */\n textBtn2.setOnClickListener(option.getOptionViewAdditional().getOnClickListenerTextBtn2());\n }\n }\n\n /*\n Check if Text is set.\n */\n if (option.isText()) {\n image.setVisibility(View.GONE);\n text.setVisibility(View.VISIBLE);\n text.setText(option.getText());\n }\n if (textAttr != null) {\n image.setVisibility(View.GONE);\n text.setVisibility(View.VISIBLE);\n text.setText(textAttr);\n }\n /*\n Check if subTitle is set.\n */\n if (option.isSubTitle()) {\n subTitle.setVisibility(View.VISIBLE);\n subTitle.setText(option.getSubTitle());\n }\n if (subTitleAttr != null) {\n subTitle.setVisibility(View.VISIBLE);\n subTitle.setText(subTitleAttr);\n }\n /*\n Check if Image is set.\n */\n if (option.isImage()) {\n text.setVisibility(View.GONE);\n image.setVisibility(View.VISIBLE);\n image.setImageResource(option.getImage());\n }\n if (imageAttr != -1) {\n text.setVisibility(View.GONE);\n image.setVisibility(View.VISIBLE);\n image.setImageResource(imageAttr);\n }\n\n /*\n Configure the toolbar\n */\n initToolbar(context, option);\n\n if(option.isAutoAnimation() || isAutoAnimation) {\n /*\n Set listener for swipeable card.\n */\n this.setClickable(true);\n this.setOnClickListener(this);\n\n /*\n Set listener for root view.\n */\n frame.setOnClickListener(new OnClickListener() {\n @Override\n public void onClick(View v) {\n animationCardDown(card, toolbar, duration);\n }\n });\n /*\n Check if Swipe to Dismiss is set.\n */\n if (option.isSwipeToDismiss() || isSwipeToDismiss) {\n frame.setOnTouchListener(new SwipeDismissTouchListenerLeftRight(\n frame,\n null,\n new SwipeDismissTouchListenerLeftRight.DismissCallbacks() {\n @Override\n public boolean canDismiss(Object token) {\n return true;\n }\n\n @Override\n public void onDismiss(View view, Object token) {\n setVisibility(View.GONE);\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)\n Snackbar.make(SwipeableCard.this, \"Deleted!\", Snackbar.LENGTH_LONG)\n .setAction(\"Undo\", new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n setVisibility(View.VISIBLE);\n }\n })\n .show();\n }\n }));\n }\n }else{\n this.setClickable(false);\n this.setOnClickListener(null);\n frame.setOnClickListener(null);\n }\n /*\n Start animation\n */\n animationCardStart(card, toolbar);\n }else{\n Log.e(\"Initialization\", \"Option View not initialize!\");\n }\n }\n\n\n /**\n * Public constructor of Swipeable Card.\n * @param context Set application context\n * @param attrs Set attributeSet\n */\n public SwipeableCard(Context context, AttributeSet attrs) {\n super(context, attrs);\n /*\n Inflater custom layout to view.\n */\n LayoutInflater inflater = (LayoutInflater) context\n .getSystemService(Context.LAYOUT_INFLATER_SERVICE);\n inflater.inflate(R.layout.swipeable_card, this, true);\n /*\n Get attribute from XML\n */\n TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.SwipeableCard, 0, 0);\n try {\n cardRadiusAttr = ta.getDimension(R.styleable.SwipeableCard_sc_cardRadius, 4);\n duration = (long) ta.getFloat(R.styleable.SwipeableCard_sc_animDuration, 500);\n titleAttr = ta.getString(R.styleable.SwipeableCard_sc_title);\n colorTitleAttr = ta.getInteger(R.styleable.SwipeableCard_sc_titleColor, 0);\n imageAttr = ta.getResourceId(R.styleable.SwipeableCard_sc_image, -1);\n subTitleAttr = ta.getString(R.styleable.SwipeableCard_sc_subTitle);\n colorToolbarAttr = ta.getInteger(R.styleable.SwipeableCard_sc_toolbarColor, 0);\n textAttr = ta.getString(R.styleable.SwipeableCard_sc_text);\n isSwipeToDismiss = ta.getBoolean(R.styleable.SwipeableCard_sc_swipeToDismiss, false);\n isAutoAnimation = ta.getBoolean(R.styleable.SwipeableCard_sc_autoAnimation, true);\n } finally {\n ta.recycle();\n }\n init(context, OptionView.getOptionView());\n }\n\n /**\n * Get size of screen.\n * @param context Context\n * @return height of screen\n */\n private int getScreenSize(Context context)\n {\n WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);\n Display display = wm.getDefaultDisplay();\n Point size = new Point();\n display.getSize(size);\n return size.y;\n }\n\n /**\n * Initialize Toolbar.\n * @param context Context\n */\n @SuppressWarnings(\"deprecation\")\n private void initToolbar(Context context, OptionView option)\n {\n toolbar = (Toolbar) findViewById(R.id.toolbar);\n toolbar.setTitle(titleAttr);\n\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {\n if(colorTitleAttr == 0)\n {\n toolbar.setTitleTextColor(ContextCompat.getColor(context, option.getColorTitle()));\n }\n else {\n toolbar.setTitleTextColor(colorTitleAttr);\n }\n if(colorToolbarAttr == 0)\n {\n toolbar.setBackgroundColor((ContextCompat.getColor(context, option.getColorToolbar())));\n }else {\n\n toolbar.setBackgroundColor(colorToolbarAttr);\n }\n\n } else {\n if(colorTitleAttr == 0)\n {\n toolbar.setTitleTextColor(getResources().getColor(option.getColorTitle()));\n }\n else {\n toolbar.setTitleTextColor(colorTitleAttr);\n }\n if(colorToolbarAttr == 0) {\n toolbar.setBackgroundColor(getResources().getColor(option.getColorToolbar()));\n }else{\n toolbar.setBackgroundColor(colorToolbarAttr);\n }\n }\n if (option.isMenuItem()) {\n //Reset menù item (avoids duplicate)\n toolbar.getMenu().clear();\n //Set new menù item\n toolbar.inflateMenu(option.getMenuItem());\n toolbar.setOnMenuItemClickListener(option.getToolbarListener());\n }\n if(option.isAutoAnimation()) {\n toolbar.setOnClickListener(this);\n }else{\n toolbar.setOnClickListener(null);\n }\n }\n\n @Override\n protected void onFinishInflate() {\n super.onFinishInflate();\n }\n\n /**\n * Animation Card at start layout, please do not modify this.\n * @param card card view instance\n * @param toolbar toolbar instance\n */\n @Override\n public void animationCardStart(@NotNull final CardView card, @NotNull final Toolbar toolbar){\n new CountDownTimer(300, 1) {\n public void onTick(long millisUntilFinished) {\n card.setTranslationY(height - ((int)(toolbar.getHeight() * 1.7)));\n fab.setTranslationY((height - ((int) (toolbar.getHeight() * 1.7))) + card.getHeight() - (fab.getHeight() - fab.getHeight() / 4));\n }\n\n public void onFinish() {\n card.setTranslationY(height - ((int)(toolbar.getHeight() * 1.7)));\n fab.setTranslationY((height - ((int) (toolbar.getHeight() * 1.7))) + card.getHeight() - (fab.getHeight() - fab.getHeight() / 4));\n }\n }.start();\n }\n\n /**\n * Animation Card for down animation, please do not modify this.\n * @param card card view instance\n * @param toolbar toolbar instance\n */\n @Override\n public void animationCardDown(@NotNull final CardView card, @NotNull final Toolbar toolbar, final long duration){\n new CountDownTimer(1, 1) {\n public void onTick(long millisUntilFinished) {\n }\n\n public void onFinish() {\n card.animate()\n .translationY(height - ((int)(toolbar.getHeight() * 1.7)))\n .setDuration(duration).start();\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {\n fab.animate()\n .translationY((height - ((int) (toolbar.getHeight() * 1.7))) + card.getHeight() - (fab.getHeight() - fab.getHeight()/4))\n .setDuration(duration).start();\n }else{\n fab.animate()\n .translationY((height - ((int) (toolbar.getHeight() * 1.7))) + card.getHeight() - (fab.getHeight() - fab.getHeight()/3))\n .setDuration(duration).start();\n }\n }\n }.start();\n }\n\n /**\n * Animation Card for up animation, please do not modify this.\n * @param card card view instance\n * @param toolbar toolbar instance\n */\n @Override\n public void animationCardUp(@NotNull final CardView card, @NotNull final Toolbar toolbar, final long duration){\n new CountDownTimer(1, 1) {\n public void onTick(long millisUntilFinished) {\n }\n\n public void onFinish() {\n card.animate()\n .translationY(height - (card.getHeight() + toolbar.getHeight()))\n .setDuration(duration).start();\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {\n fab.animate()\n .translationY((height - (card.getHeight() + toolbar.getHeight())) + card.getHeight() - (fab.getHeight() - fab.getHeight() / 4))\n .setDuration(duration).start();\n }else {\n fab.animate()\n .translationY((height - (card.getHeight() + toolbar.getHeight())) + card.getHeight() - (fab.getHeight() - fab.getHeight() / 3))\n .setDuration(duration).start();\n }\n }\n }.start();\n }\n\n /**\n * onClick method for animate swipeable card.\n * @param v View\n */\n @Override\n public void onClick(View v) {\n animationCardUp(card, toolbar, duration);\n }\n\n /**\n * Update Google Maps marker, with option (icon and text) for marker\n */\n protected void updateMapContents() {\n mGoogleMap.clear();\n if(mOptionView.isMultipleMarker() && !mOptionView.isSingleMarker()) {\n LatLngBounds.Builder builder = new LatLngBounds.Builder();\n if(mOptionView.getLatLngArray() != null && mOptionView.getLatLngArray().length > 0) {\n if (mOptionView.getMarkerTitleArray() != null && mOptionView.getMarkerTitleArray().length > 0\n && mOptionView.getLatLngArray().length == mOptionView.getMarkerTitleArray().length) {\n if(mOptionView.getMarkerIconArray() != null && mOptionView.getMarkerIconArray().length > 0\n && mOptionView.getLatLngArray().length == mOptionView.getMarkerIconArray().length)\n {\n for (int i = 0; i < mOptionView.getLatLngArray().length; i++) {\n BitmapDescriptor icon = BitmapDescriptorFactory.fromResource(mOptionView.getMarkerIconArray()[i]);\n mGoogleMap.addMarker(new MarkerOptions().position(mOptionView.getLatLngArray()[i]).title(mOptionView.getMarkerTitleArray()[i]).icon(icon));\n builder.include(mOptionView.getLatLngArray()[i]);\n }\n }else {\n for (int i = 0; i < mOptionView.getLatLngArray().length; i++) {\n mGoogleMap.addMarker(new MarkerOptions().position(mOptionView.getLatLngArray()[i]).title(mOptionView.getMarkerTitleArray()[i]));\n builder.include(mOptionView.getLatLngArray()[i]);\n }\n }\n } else {\n if(mOptionView.getMarkerIconArray() != null && mOptionView.getMarkerIconArray().length > 0\n && mOptionView.getLatLngArray().length == mOptionView.getMarkerIconArray().length)\n {\n for (int i = 0; i < mOptionView.getLatLngArray().length; i++) {\n BitmapDescriptor icon = BitmapDescriptorFactory.fromResource(mOptionView.getMarkerIconArray()[i]);\n mGoogleMap.addMarker(new MarkerOptions().position(mOptionView.getLatLngArray()[i]).title(mOptionView.getMarkerTitleArray()[i]).icon(icon));\n builder.include(mOptionView.getLatLngArray()[i]);\n }\n }else {\n for (int i = 0; i < mOptionView.getLatLngArray().length; i++) {\n mGoogleMap.addMarker(new MarkerOptions().position(mOptionView.getLatLngArray()[i]));\n builder.include(mOptionView.getLatLngArray()[i]);\n }\n }\n }\n }\n if(mOptionView.getLatLngList() != null && mOptionView.getLatLngList().size() > 0)\n {\n if(mOptionView.getMarkerTitleList() != null && mOptionView.getMarkerTitleList().size() > 0\n && mOptionView.getMarkerTitleList().size() == mOptionView.getLatLngList().size())\n {\n if(mOptionView.getMarkerIconList() != null && mOptionView.getMarkerIconList().size() > 0\n && mOptionView.getMarkerIconList().size() == mOptionView.getLatLngList().size())\n {\n for (int i = 0; i < mOptionView.getLatLngList().size(); i++) {\n BitmapDescriptor icon = BitmapDescriptorFactory.fromResource(mOptionView.getMarkerIconList().get(i));\n mGoogleMap.addMarker(new MarkerOptions().position(mOptionView.getLatLngList().get(i)).title(mOptionView.getMarkerTitleList().get(i)).icon(icon));\n builder.include(mOptionView.getLatLngList().get(i));\n }\n }else {\n for (int i = 0; i < mOptionView.getLatLngList().size(); i++) {\n mGoogleMap.addMarker(new MarkerOptions().position(mOptionView.getLatLngList().get(i)).title(mOptionView.getMarkerTitleList().get(i)));\n builder.include(mOptionView.getLatLngList().get(i));\n }\n }\n }else{\n if(mOptionView.getMarkerIconList() != null && mOptionView.getMarkerIconList().size() > 0\n && mOptionView.getMarkerIconList().size() == mOptionView.getLatLngList().size())\n {\n for (int i = 0; i < mOptionView.getLatLngList().size(); i++) {\n BitmapDescriptor icon = BitmapDescriptorFactory.fromResource(mOptionView.getMarkerIconList().get(i));\n mGoogleMap.addMarker(new MarkerOptions().position(mOptionView.getLatLngList().get(i)).icon(icon));\n builder.include(mOptionView.getLatLngList().get(i));\n }\n }else {\n for (int i = 0; i < mOptionView.getLatLngList().size(); i++) {\n mGoogleMap.addMarker(new MarkerOptions().position(mOptionView.getLatLngList().get(i)));\n builder.include(mOptionView.getLatLngList().get(i));\n }\n }\n }\n }\n LatLngBounds bounds = builder.build();\n CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngBounds(bounds, 0);\n mGoogleMap.moveCamera(cameraUpdate);\n }else{\n if(mOptionView.getMarkerTitle() != null) {\n if (mOptionView.getMarkerIcon() != 0) {\n BitmapDescriptor icon = BitmapDescriptorFactory.fromResource(mOptionView.getMarkerIcon());\n mGoogleMap.addMarker(new MarkerOptions().position(mMapLocation).title(mOptionView.getMarkerTitle()).icon(icon));\n } else {\n mGoogleMap.addMarker(new MarkerOptions().position(mMapLocation).title(mOptionView.getMarkerTitle()));\n }\n }else{\n if (mOptionView.getMarkerIcon() != 0) {\n BitmapDescriptor icon = BitmapDescriptorFactory.fromResource(mOptionView.getMarkerIcon());\n mGoogleMap.addMarker(new MarkerOptions().position(mMapLocation).icon(icon));\n } else {\n mGoogleMap.addMarker(new MarkerOptions().position(mMapLocation));\n }\n }\n CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(mMapLocation, mapsZoom);\n mGoogleMap.moveCamera(cameraUpdate);\n }\n }\n\n /**\n * Set map location, check if Google Maps is not null, than update contents (Single marker)\n * @param lat latitude double\n * @param lon longitude double\n */\n public void setMapLocation(double lat, double lon) {\n mMapLocation = new LatLng(lat, lon);\n if (mGoogleMap != null) {\n updateMapContents();\n }\n }\n\n /**\n * Set map location, check if Google Maps is not null, than update contents (Array and List)\n */\n public void setMapLocation()\n {\n if (mGoogleMap != null) {\n updateMapContents();\n }\n }\n\n\n @Override\n public void onMapReady(GoogleMap googleMap) {\n mGoogleMap = googleMap;\n MapsInitializer.initialize(getContext());\n googleMap.getUiSettings().setMapToolbarEnabled(true);\n if (mMapLocation != null && !mOptionView.isMultipleMarker() && mOptionView.isSingleMarker()) {\n updateMapContents();\n }\n if(mOptionView.getLatLngArray() != null && mOptionView.getLatLngArray().length > 0 && mOptionView.isMultipleMarker() && !mOptionView.isSingleMarker())\n {\n updateMapContents();\n }\n if(mOptionView.getLatLngList() != null && mOptionView.getLatLngList().size() > 0 && mOptionView.isMultipleMarker() && !mOptionView.isSingleMarker())\n {\n updateMapContents();\n }\n }\n\n /**\n * Get street name from latitude and longitude\n * @param lat latitude double\n * @param lon longitude double\n * @param context Context\n * @return String street name\n */\n public String getStreetNameFromLatLong(double lat, double lon, Context context)\n {\n String streetName = null;\n Geocoder geocoder = new Geocoder(context, Locale.getDefault());\n\n try {\n List<Address> addresses = geocoder.getFromLocation(lat, lon, 1);\n\n if (addresses != null) {\n Address returnedAddress = addresses.get(0);\n StringBuilder strReturnedAddress = new StringBuilder();\n for (int j = 0; j < returnedAddress.getMaxAddressLineIndex(); j++) {\n strReturnedAddress.append(returnedAddress.getAddressLine(j)).append(\"\");\n }\n streetName = strReturnedAddress.toString();\n }\n } catch (IOException e) {\n Log.e(\"SwipeableCard\", \"Error tryng to retrieve street name from lat long\");\n }\n return streetName;\n }\n\n\n @Override\n public boolean onInterceptTouchEvent(MotionEvent ev) {\n if(!mOptionView.isAutoAnimation()) {\n if (isLocked) {\n return false;\n } else {\n final int y = (int) ev.getRawY();\n final int x = (int) ev.getRawX();\n if (ev.getActionMasked() == MotionEvent.ACTION_DOWN) {\n previousFingerPositionX = x;\n previousFingerPositionY = y;\n } else if (ev.getActionMasked() == MotionEvent.ACTION_MOVE) {\n int diffY = y - previousFingerPositionY;\n int diffX = x - previousFingerPositionX;\n if (Math.abs(diffX) + 25 < Math.abs(diffY)) {\n return true;\n }\n }\n return false;\n }\n }else{\n return false;\n }\n }\n\n\n @Override\n public boolean onTouchEvent(MotionEvent event) {\n\n if (!mOptionView.isAutoAnimation()) {\n int currenty = (int) event.getRawY();\n FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) card.getLayoutParams();\n switch (event.getAction()) {\n\n case MotionEvent.ACTION_DOWN:\n pressedy = currenty;\n viewMariginY = layoutParams.topMargin;\n break;\n\n\n case MotionEvent.ACTION_MOVE:\n int diffy = currenty - pressedy;\n int marginy = viewMariginY + diffy;\n layoutParams.topMargin = marginy;\n if (marginy >= height - (card.getHeight() + toolbar.getHeight()) && marginy <= height - ((int) (toolbar.getHeight() * 1.7))) {\n ObjectAnimator positionAnimator = ObjectAnimator.ofFloat(card, \"y\", this.getY(), marginy);\n positionAnimator.setDuration(0);\n positionAnimator.start();\n }\n break;\n\n case MotionEvent.ACTION_UP:\n int diffy2 = currenty - pressedy;\n int marginy2 = viewMariginY + diffy2;\n layoutParams.topMargin = marginy2;\n if (marginy2 >= height - (card.getHeight() + toolbar.getHeight()) && marginy2 <= height - ((int) (toolbar.getHeight() * 1.7))) {\n ObjectAnimator positionAnimator = ObjectAnimator.ofFloat(card, \"y\", this.getY(), marginy2);\n positionAnimator.setDuration(0);\n positionAnimator.start();\n }\n break;\n default:\n break;\n }\n\n return true;\n }else\n {\n return false;\n }\n }\n\n}",
"@SuppressWarnings({\"deprecation\", \"ConstantConditions\"})\npublic class SwipeableCardAdapter extends RecyclerView.Adapter<SwipeableCardAdapter.CardViewHolder> implements AnimationCard{\n private GoogleMap mGoogleMap;\n private LatLng mMapLocation;\n private float mapsZoom;\n private Context context;\n private List<OptionView> optionsView;\n private int height;\n private int width;\n\n public static class CardViewHolder extends RecyclerView.ViewHolder {\n private CardView card;\n private ImageView image;\n private TextView text;\n private TextView subTitle;\n private Toolbar toolbar;\n private Button newCreditCard;\n private CreditCardView creditCardView;\n /**\n * Customizable Icon and Text\n */\n private ImageView iconBtn1;\n private ImageView iconBtn2;\n private ImageView iconBtn3;\n private TextView textBtn1;\n private TextView textBtn2;\n /**\n * Maps Variable\n */\n private MapView mapView;\n private TextView streetNameView;\n private RelativeLayout relativeMaps;\n private RelativeLayout relativeNormal;\n private RelativeLayout relativeCreditCard;\n private RelativeLayout relativeCreditCardCreation;\n\n\n CardViewHolder(View itemView) {\n super(itemView);\n /*\n Set up recycler view custom object.\n */\n card = (CardView)itemView.findViewById(R.id.card);\n image = (ImageView) itemView.findViewById(it.michelelacorte.swipeablecard.R.id.image);\n text = (TextView) itemView.findViewById(it.michelelacorte.swipeablecard.R.id.text);\n subTitle = (TextView) itemView.findViewById(it.michelelacorte.swipeablecard.R.id.subTitle);\n toolbar = (Toolbar) itemView.findViewById(it.michelelacorte.swipeablecard.R.id.toolbar);\n mapView = (MapView) itemView.findViewById(R.id.mapLite);\n streetNameView = (TextView) itemView.findViewById(R.id.streetName);\n relativeNormal = (RelativeLayout) itemView.findViewById(R.id.relativeNormal);\n relativeMaps = (RelativeLayout) itemView.findViewById(R.id.relativeMaps);\n relativeCreditCard = (RelativeLayout) itemView.findViewById(R.id.relativeCreditCard);\n relativeCreditCardCreation = (RelativeLayout) itemView.findViewById(R.id.relativeCreditCardCreation);\n newCreditCard = (Button) itemView.findViewById(R.id.creditCardButton);\n creditCardView = (CreditCardView) itemView.findViewById(R.id.creditCard);\n /**\n * Set-up customizable Icon and Text\n */\n iconBtn1 = (ImageView) itemView.findViewById(R.id.iconBtn1);\n iconBtn2 = (ImageView) itemView.findViewById(R.id.iconBtn2);\n iconBtn3 = (ImageView) itemView.findViewById(R.id.iconBtn3);\n textBtn1 = (TextView) itemView.findViewById(R.id.textBtn1);\n textBtn2 = (TextView) itemView.findViewById(R.id.textBtn2);\n }\n\n\n }\n\n public SwipeableCardAdapter(List<OptionView> optionsView, Context context){\n this.optionsView = optionsView;\n this.context = context;\n }\n\n protected void updateMapContents(OptionView mOptionView) {\n mGoogleMap.clear();\n if(mOptionView.isMultipleMarker() && !mOptionView.isSingleMarker()) {\n LatLngBounds.Builder builder = new LatLngBounds.Builder();\n if(mOptionView.getLatLngArray() != null && mOptionView.getLatLngArray().length > 0) {\n if (mOptionView.getMarkerTitleArray() != null && mOptionView.getMarkerTitleArray().length > 0\n && mOptionView.getLatLngArray().length == mOptionView.getMarkerTitleArray().length) {\n if(mOptionView.getMarkerIconArray() != null && mOptionView.getMarkerIconArray().length > 0\n && mOptionView.getLatLngArray().length == mOptionView.getMarkerIconArray().length)\n {\n for (int i = 0; i < mOptionView.getLatLngArray().length; i++) {\n BitmapDescriptor icon = BitmapDescriptorFactory.fromResource(mOptionView.getMarkerIconArray()[i]);\n mGoogleMap.addMarker(new MarkerOptions().position(mOptionView.getLatLngArray()[i]).title(mOptionView.getMarkerTitleArray()[i]).icon(icon));\n builder.include(mOptionView.getLatLngArray()[i]);\n }\n }else {\n for (int i = 0; i < mOptionView.getLatLngArray().length; i++) {\n mGoogleMap.addMarker(new MarkerOptions().position(mOptionView.getLatLngArray()[i]).title(mOptionView.getMarkerTitleArray()[i]));\n builder.include(mOptionView.getLatLngArray()[i]);\n }\n }\n } else {\n if(mOptionView.getMarkerIconArray() != null && mOptionView.getMarkerIconArray().length > 0\n && mOptionView.getLatLngArray().length == mOptionView.getMarkerIconArray().length)\n {\n for (int i = 0; i < mOptionView.getLatLngArray().length; i++) {\n BitmapDescriptor icon = BitmapDescriptorFactory.fromResource(mOptionView.getMarkerIconArray()[i]);\n mGoogleMap.addMarker(new MarkerOptions().position(mOptionView.getLatLngArray()[i]).title(mOptionView.getMarkerTitleArray()[i]).icon(icon));\n builder.include(mOptionView.getLatLngArray()[i]);\n }\n }else {\n for (int i = 0; i < mOptionView.getLatLngArray().length; i++) {\n mGoogleMap.addMarker(new MarkerOptions().position(mOptionView.getLatLngArray()[i]));\n builder.include(mOptionView.getLatLngArray()[i]);\n }\n }\n }\n }\n if(mOptionView.getLatLngList() != null && mOptionView.getLatLngList().size() > 0)\n {\n if(mOptionView.getMarkerTitleList() != null && mOptionView.getMarkerTitleList().size() > 0\n && mOptionView.getMarkerTitleList().size() == mOptionView.getLatLngList().size())\n {\n if(mOptionView.getMarkerIconList() != null && mOptionView.getMarkerIconList().size() > 0\n && mOptionView.getMarkerIconList().size() == mOptionView.getLatLngList().size())\n {\n for (int i = 0; i < mOptionView.getLatLngList().size(); i++) {\n BitmapDescriptor icon = BitmapDescriptorFactory.fromResource(mOptionView.getMarkerIconList().get(i));\n mGoogleMap.addMarker(new MarkerOptions().position(mOptionView.getLatLngList().get(i)).title(mOptionView.getMarkerTitleList().get(i)).icon(icon));\n builder.include(mOptionView.getLatLngList().get(i));\n }\n }else {\n for (int i = 0; i < mOptionView.getLatLngList().size(); i++) {\n mGoogleMap.addMarker(new MarkerOptions().position(mOptionView.getLatLngList().get(i)).title(mOptionView.getMarkerTitleList().get(i)));\n builder.include(mOptionView.getLatLngList().get(i));\n }\n }\n }else{\n if(mOptionView.getMarkerIconList() != null && mOptionView.getMarkerIconList().size() > 0\n && mOptionView.getMarkerIconList().size() == mOptionView.getLatLngList().size())\n {\n for (int i = 0; i < mOptionView.getLatLngList().size(); i++) {\n BitmapDescriptor icon = BitmapDescriptorFactory.fromResource(mOptionView.getMarkerIconList().get(i));\n mGoogleMap.addMarker(new MarkerOptions().position(mOptionView.getLatLngList().get(i)).icon(icon));\n builder.include(mOptionView.getLatLngList().get(i));\n }\n }else {\n for (int i = 0; i < mOptionView.getLatLngList().size(); i++) {\n mGoogleMap.addMarker(new MarkerOptions().position(mOptionView.getLatLngList().get(i)));\n builder.include(mOptionView.getLatLngList().get(i));\n }\n }\n }\n }\n LatLngBounds bounds = builder.build();\n CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngBounds(bounds, 0);\n mGoogleMap.moveCamera(cameraUpdate);\n }else{\n if(mOptionView.getMarkerTitle() != null) {\n if (mOptionView.getMarkerIcon() != 0) {\n BitmapDescriptor icon = BitmapDescriptorFactory.fromResource(mOptionView.getMarkerIcon());\n mGoogleMap.addMarker(new MarkerOptions().position(mMapLocation).title(mOptionView.getMarkerTitle()).icon(icon));\n } else {\n mGoogleMap.addMarker(new MarkerOptions().position(mMapLocation).title(mOptionView.getMarkerTitle()));\n }\n }else{\n if (mOptionView.getMarkerIcon() != 0) {\n BitmapDescriptor icon = BitmapDescriptorFactory.fromResource(mOptionView.getMarkerIcon());\n mGoogleMap.addMarker(new MarkerOptions().position(mMapLocation).icon(icon));\n } else {\n mGoogleMap.addMarker(new MarkerOptions().position(mMapLocation));\n }\n }\n CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(mMapLocation, mapsZoom);\n mGoogleMap.moveCamera(cameraUpdate);\n }\n }\n\n public void setMapLocation(double lat, double lon, OptionView mOptionView) {\n mMapLocation = new LatLng(lat, lon);\n if (mGoogleMap != null) {\n updateMapContents(mOptionView);\n }\n }\n\n public void setMapLocation(OptionView mOptionView)\n {\n if (mGoogleMap != null) {\n updateMapContents(mOptionView);\n }\n }\n\n\n public String getStreetNameFromLatLong(double lat, double lon, Context context)\n {\n String streetName = null;\n Geocoder geocoder = new Geocoder(context, Locale.getDefault());\n\n try {\n List<Address> addresses = geocoder.getFromLocation(lat, lon, 1);\n\n if (addresses != null) {\n Address returnedAddress = addresses.get(0);\n StringBuilder strReturnedAddress = new StringBuilder();\n for (int j = 0; j < returnedAddress.getMaxAddressLineIndex(); j++) {\n strReturnedAddress.append(returnedAddress.getAddressLine(j)).append(\"\");\n }\n streetName = strReturnedAddress.toString();\n }\n } catch (IOException e) {\n Log.e(\"SwipeableCardAdapter\", \"Error tryng to retrieve street name from lat long\");\n }\n return streetName;\n }\n /**\n * Animation Card at start layout, please do not modify this.\n * @param card card view instance\n * @param toolbar toolbar instance\n */\n @Override\n public void animationCardStart(@NotNull final CardView card, @NotNull final Toolbar toolbar){\n new CountDownTimer(1, 1) {\n public void onTick(long millisUntilFinished) {\n }\n\n public void onFinish() {\n card.animate()\n .translationY(height - ((int) (toolbar.getHeight() * 1.7)))\n .setDuration(1)\n .setListener(new AnimatorListenerAdapter() {\n @Override\n public void onAnimationEnd(Animator animation) {\n super.onAnimationEnd(animation);\n card.setVisibility(View.VISIBLE);\n }\n }).start();\n }\n }.start();\n\n }\n\n /**\n * Animation Card for down animation, please do not modify this.\n * @param card card view instance\n * @param toolbar toolbar instance\n */\n @Override\n public void animationCardDown(@NotNull final CardView card, @NotNull final Toolbar toolbar, final long duration){\n new CountDownTimer(1, 1) {\n public void onTick(long millisUntilFinished) {\n }\n\n public void onFinish() {\n card.animate()\n .translationY(height - ((int)(toolbar.getHeight() * 1.7)))\n .setDuration(duration).start();\n }\n }.start();\n }\n\n /**\n * Animation Card for up animation, please do not modify this.\n * @param card card view instance\n * @param toolbar toolbar instance\n */\n @Override\n public void animationCardUp(@NotNull final CardView card, final Toolbar toolbar, final long duration){\n new CountDownTimer(1, 1) {\n public void onTick(long millisUntilFinished) {\n }\n\n public void onFinish() {\n card.animate()\n .translationY(height - (card.getHeight() + toolbar.getHeight()))\n .setDuration(duration).start();\n }\n }.start();\n }\n\n\n /**\n * Get number of option view.\n * @return item count\n */\n @Override\n public int getItemCount() {\n return optionsView.size();\n }\n\n private Point getScreenSize(Context context)\n {\n WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);\n Display display = wm.getDefaultDisplay();\n Point size = new Point();\n display.getSize(size);\n return new Point(size.x, size.y);\n }\n\n @Override\n public CardViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {\n //Inflate layout on recycler view.\n View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.recycler_view_card, viewGroup, false);\n final CardViewHolder cvh = new CardViewHolder(v);\n\n //Get screen size.\n width = getScreenSize(context).x;\n height = getScreenSize(context).y;\n\n //Return view.\n return cvh;\n\n }\n\n @Override\n public void onBindViewHolder(final CardViewHolder cardViewHolder, int i) {\n /*\n Set option for all swipeable card on recycler view.\n */\n //Set Text\n final long duration = optionsView.get(i).getDuration();\n cardViewHolder.card.setLayoutParams(new LinearLayout.LayoutParams(width, ViewGroup.LayoutParams.WRAP_CONTENT));\n cardViewHolder.card.setRadius(optionsView.get(i).getCardRadius());\n\n /**\n * Check if Maps Card is set (reset object before)\n */\n cardViewHolder.streetNameView.setVisibility(View.GONE);\n cardViewHolder.mapView.setVisibility(View.GONE);\n cardViewHolder.relativeNormal.setVisibility(View.GONE);\n cardViewHolder.relativeMaps.setVisibility(View.GONE);\n if(optionsView.get(i).isTypeCardMaps()) {\n if((optionsView.get(i).getLatLngArray() != null && optionsView.get(i).getLatLngArray().length > 0) ||\n (optionsView.get(i).getLatLngList() != null && optionsView.get(i).getLatLngList().size() > 0)\n && optionsView.get(i).isMultipleMarker() && !optionsView.get(i).isSingleMarker())\n {\n cardViewHolder.relativeNormal.setVisibility(View.GONE);\n cardViewHolder.relativeMaps.setVisibility(View.VISIBLE);\n cardViewHolder.mapView.setVisibility(View.VISIBLE);\n cardViewHolder.text.setVisibility(View.GONE);\n cardViewHolder.image.setVisibility(View.GONE);\n cardViewHolder.mapView.onCreate(null);\n final int j = i;\n cardViewHolder.mapView.getMapAsync(new OnMapReadyCallback() {\n @Override\n public void onMapReady(GoogleMap googleMap) {\n mGoogleMap = googleMap;\n MapsInitializer.initialize(context);\n googleMap.getUiSettings().setMapToolbarEnabled(true);\n if (mMapLocation != null && !optionsView.get(j).isMultipleMarker() && optionsView.get(j).isSingleMarker()) {\n updateMapContents(optionsView.get(j));\n }\n if(optionsView.get(j).getLatLngArray() != null && optionsView.get(j).getLatLngArray().length > 0 && optionsView.get(j).isMultipleMarker() && !optionsView.get(j).isSingleMarker())\n {\n updateMapContents(optionsView.get(j));\n }\n if(optionsView.get(j).getLatLngList() != null && optionsView.get(j).getLatLngList().size() > 0 && optionsView.get(j).isMultipleMarker() && !optionsView.get(j).isSingleMarker())\n {\n updateMapContents(optionsView.get(j));\n }\n }\n });\n setMapLocation(optionsView.get(i));\n }else {\n mapsZoom = optionsView.get(i).getMapsZoom();\n cardViewHolder.relativeNormal.setVisibility(View.GONE);\n cardViewHolder.relativeMaps.setVisibility(View.VISIBLE);\n cardViewHolder.mapView.setVisibility(View.VISIBLE);\n cardViewHolder.text.setVisibility(View.GONE);\n cardViewHolder.image.setVisibility(View.GONE);\n cardViewHolder.mapView.onCreate(null);\n final int j = i;\n cardViewHolder.mapView.getMapAsync(new OnMapReadyCallback() {\n @Override\n public void onMapReady(GoogleMap googleMap) {\n mGoogleMap = googleMap;\n MapsInitializer.initialize(context);\n googleMap.getUiSettings().setMapToolbarEnabled(true);\n if (mMapLocation != null && !optionsView.get(j).isMultipleMarker() && optionsView.get(j).isSingleMarker()) {\n updateMapContents(optionsView.get(j));\n }\n if(optionsView.get(j).getLatLngArray() != null && optionsView.get(j).getLatLngArray().length > 0 && optionsView.get(j).isMultipleMarker() && !optionsView.get(j).isSingleMarker())\n {\n updateMapContents(optionsView.get(j));\n }\n if(optionsView.get(j).getLatLngList() != null && optionsView.get(j).getLatLngList().size() > 0 && optionsView.get(j).isMultipleMarker() && !optionsView.get(j).isSingleMarker())\n {\n updateMapContents(optionsView.get(j));\n }\n }\n });\n setMapLocation(optionsView.get(i).getLatitude(), optionsView.get(i).getLongitude(), optionsView.get(i));\n if(optionsView.get(i).isStreetName())\n {\n cardViewHolder.streetNameView.setText(getStreetNameFromLatLong(optionsView.get(i).getLatitude(), optionsView.get(i).getLongitude(), context));\n cardViewHolder.streetNameView.setVisibility(View.VISIBLE);\n }\n }\n } else if(optionsView.get(i).isTypeCardCredit()) {\n if(optionsView.get(i).isCreateCreditCard()) {\n cardViewHolder.newCreditCard.setVisibility(View.VISIBLE);\n cardViewHolder.relativeCreditCardCreation.setVisibility(View.VISIBLE);\n cardViewHolder.relativeCreditCard.setVisibility(View.GONE);\n final int j = i;\n cardViewHolder.newCreditCard.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n ActivityCardCreation.setCreditCardView(cardViewHolder.creditCardView, optionsView.get(j), cardViewHolder.newCreditCard, cardViewHolder.relativeCreditCardCreation, cardViewHolder.relativeCreditCard);\n Intent intent = new Intent(optionsView.get(j).getActivity(), ActivityCardCreation.class);\n optionsView.get(j).getActivity().startActivityForResult(intent, 1);\n }\n });\n }else {\n cardViewHolder.creditCardView.setCardExpiry(optionsView.get(i).getDateYear());\n cardViewHolder.creditCardView.setCardNumber(optionsView.get(i).getRawCardNumber());\n cardViewHolder.creditCardView.setCardHolderName(optionsView.get(i).getCardHolderName());\n if(optionsView.get(i).getCvv() != null)\n {\n cardViewHolder.creditCardView.setCVV(optionsView.get(i).getCvv());\n }else {\n cardViewHolder.creditCardView.setCVV(optionsView.get(i).getIntCvv());\n }\n cardViewHolder.creditCardView.showFront();\n cardViewHolder.creditCardView.setOnClickListener(new View.OnClickListener() {\n boolean back = false;\n\n @Override\n public void onClick(View v) {\n if (!back) {\n cardViewHolder.creditCardView.showBack();\n back = true;\n } else {\n cardViewHolder.creditCardView.showFront();\n back = false;\n }\n }\n });\n cardViewHolder.relativeCreditCardCreation.setVisibility(View.GONE);\n cardViewHolder.relativeCreditCard.setVisibility(View.VISIBLE);\n }\n }else {\n cardViewHolder.relativeCreditCard.setVisibility(View.GONE);\n cardViewHolder.relativeCreditCardCreation.setVisibility(View.GONE);\n cardViewHolder.relativeNormal.setVisibility(View.VISIBLE);\n cardViewHolder.relativeMaps.setVisibility(View.GONE);\n }\n if(optionsView.get(i).isText())\n {\n cardViewHolder.image.setVisibility(View.GONE);\n cardViewHolder.text.setVisibility(View.VISIBLE);\n cardViewHolder.text.setText(optionsView.get(i).getText());\n }\n //Set Sub Title\n if(optionsView.get(i).isSubTitle())\n {\n cardViewHolder.subTitle.setVisibility(View.VISIBLE);\n cardViewHolder.subTitle.setText(optionsView.get(i).getSubTitle());\n }\n //Set Image\n if(optionsView.get(i).isImage())\n {\n cardViewHolder.text.setVisibility(View.GONE);\n cardViewHolder.image.setVisibility(View.VISIBLE);\n cardViewHolder.image.setImageResource(optionsView.get(i).getImage());\n }\n\n //Set toolbar\n cardViewHolder.toolbar.setTitle(optionsView.get(i).getTitle());\n\n //Check if has menu item\n if (optionsView.get(i).isMenuItem()) {\n //Reset menù item (avoids duplicate)\n cardViewHolder.toolbar.getMenu().clear();\n //Set new menù item\n cardViewHolder.toolbar.setOnMenuItemClickListener(optionsView.get(i).getToolbarListener());\n cardViewHolder.toolbar.inflateMenu(optionsView.get(i).getMenuItem());\n }\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {\n cardViewHolder.toolbar.setTitleTextColor(ContextCompat.getColor(context, optionsView.get(i).getColorTitle()));\n cardViewHolder.toolbar.setBackgroundColor(ContextCompat.getColor(context, optionsView.get(i).getColorToolbar()));\n\n } else {\n cardViewHolder.toolbar.setTitleTextColor(context.getResources().getColor(optionsView.get(i).getColorTitle()));\n cardViewHolder.toolbar.setBackgroundColor(context.getResources().getColor(optionsView.get(i).getColorToolbar()));\n }\n\n /**\n * Reset OptionViewAdditional object\n */\n cardViewHolder.iconBtn1.setVisibility(View.GONE);\n cardViewHolder.iconBtn2.setVisibility(View.GONE);\n cardViewHolder.iconBtn3.setVisibility(View.GONE);\n cardViewHolder.textBtn1.setVisibility(View.GONE);\n cardViewHolder.textBtn2.setVisibility(View.GONE);\n if(optionsView.get(i).getOptionViewAdditional() != null) {\n /**\n * Check if Additional Icon Button 1\n */\n if (optionsView.get(i).getOptionViewAdditional().isIconBtn1()) {\n cardViewHolder.iconBtn1.setVisibility(View.VISIBLE);\n cardViewHolder.iconBtn1.setImageResource(optionsView.get(i).getOptionViewAdditional().getIconBtn1());\n if (optionsView.get(i).getOptionViewAdditional().getOnClickListenerIconBtn1() != null) {\n cardViewHolder.iconBtn1.setOnClickListener(optionsView.get(i).getOptionViewAdditional().getOnClickListenerIconBtn1());\n }\n }\n /**\n * Check if Additional Icon Button 2\n */\n if (optionsView.get(i).getOptionViewAdditional().isIconBtn2()) {\n cardViewHolder.iconBtn2.setVisibility(View.VISIBLE);\n cardViewHolder.iconBtn2.setImageResource(optionsView.get(i).getOptionViewAdditional().getIconBtn2());\n if (optionsView.get(i).getOptionViewAdditional().getOnClickListenerIconBtn2() != null) {\n cardViewHolder.iconBtn2.setOnClickListener(optionsView.get(i).getOptionViewAdditional().getOnClickListenerIconBtn2());\n }\n }\n /**\n * Check if Additional Icon Button 3\n */\n if (optionsView.get(i).getOptionViewAdditional().isIconBtn3()) {\n cardViewHolder.iconBtn3.setVisibility(View.VISIBLE);\n cardViewHolder.iconBtn3.setImageResource(optionsView.get(i).getOptionViewAdditional().getIconBtn3());\n if (optionsView.get(i).getOptionViewAdditional().getOnClickListenerIconBtn3() != null) {\n cardViewHolder.iconBtn3.setOnClickListener(optionsView.get(i).getOptionViewAdditional().getOnClickListenerIconBtn3());\n }\n }\n /**\n * Check if Additional Text Button 1\n */\n if (optionsView.get(i).getOptionViewAdditional().isTextBtn1()) {\n cardViewHolder.textBtn1.setVisibility(View.VISIBLE);\n cardViewHolder.textBtn1.setText(optionsView.get(i).getOptionViewAdditional().getTextBtn1());\n cardViewHolder.textBtn1.setTextSize(optionsView.get(i).getOptionViewAdditional().getTextSizeBtn1());\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {\n ContextCompat.getColor(context, optionsView.get(i).getOptionViewAdditional().getTextColorBtn1());\n } else {\n cardViewHolder.textBtn1.setTextColor(context.getResources().getColor(optionsView.get(i).getOptionViewAdditional().getTextColorBtn1()));\n }\n /**\n * Check if OnClickListener Additional Text Button 1\n */\n if (optionsView.get(i).getOptionViewAdditional().getOnClickListenerTextBtn1() != null) {\n cardViewHolder.textBtn1.setOnClickListener(optionsView.get(i).getOptionViewAdditional().getOnClickListenerTextBtn1());\n }\n }\n /**\n * Check if Additional Text Button 2\n */\n if (optionsView.get(i).getOptionViewAdditional().isTextBtn2()) {\n cardViewHolder.textBtn2.setVisibility(View.VISIBLE);\n cardViewHolder.textBtn2.setText(optionsView.get(i).getOptionViewAdditional().getTextBtn2());\n cardViewHolder.textBtn2.setTextSize(optionsView.get(i).getOptionViewAdditional().getTextSizeBtn2());\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {\n cardViewHolder.textBtn2.setTextColor(ContextCompat.getColor(context, optionsView.get(i).getOptionViewAdditional().getTextColorBtn2()));\n } else {\n cardViewHolder.textBtn2.setTextColor(context.getResources().getColor(optionsView.get(i).getOptionViewAdditional().getTextColorBtn2()));\n }\n /**\n * Check if OnClickListener Additional Text Button 2\n */\n if (OptionView.getOptionView().getOptionViewAdditional().getOnClickListenerTextBtn2() != null) {\n cardViewHolder.textBtn2.setOnClickListener(OptionView.getOptionView().getOptionViewAdditional().getOnClickListenerTextBtn2());\n }\n }\n }\n\n //Start animation at end of creation of swipeable card\n animationCardStart(cardViewHolder.card, cardViewHolder.toolbar);\n\n //Set Listener for View and Card\n cardViewHolder.itemView.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n animationCardDown(cardViewHolder.card, cardViewHolder.toolbar, duration);\n }\n });\n\n cardViewHolder.toolbar.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n animationCardUp(cardViewHolder.card, cardViewHolder.toolbar, duration);\n }\n });\n }\n\n\n\n @Override\n public void onAttachedToRecyclerView(RecyclerView recyclerView) {\n super.onAttachedToRecyclerView(recyclerView);\n }\n}"
] | import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.method.LinkMovementMethod;
import android.view.MenuItem;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.maps.model.LatLng;
import java.util.ArrayList;
import java.util.List;
import it.michelelacorte.swipeablecard.CustomCardAnimation;
import it.michelelacorte.swipeablecard.OptionView;
import it.michelelacorte.swipeablecard.OptionViewAdditional;
import it.michelelacorte.swipeablecard.SwipeableCard;
import it.michelelacorte.swipeablecard.SwipeableCardAdapter; | .setOnClickListenerIconButton(clickIconButton1, clickIconButton2)
.build())
.build();
final OptionView dismissableSwipe = new OptionView.Builder()
.normalCard()
.image(R.drawable.image)
.title("Dismissable Card")
.menuItem(R.menu.menu_main)
.setSwipeToDismiss(true)
.toolbarListener(toolbarListener)
.setAdditionalItem(new OptionViewAdditional.Builder()
.textButton("SHARE", "LEARN MORE")
.textColorButton(R.color.colorPrimary)
.textSize(15f)
.setOnClickListenerTextButton(clickTextButton, clickTextButton)
.build())
.build();
final OptionView mapSwipeSingleMarker = new OptionView.Builder().mapsCard()
.title("Maps Card")
.setLocation(44.4937615, 11.3430542, "MyMarker")
.setZoom(10f)
.withStreetName(true)
.menuItem(R.menu.menu_main)
.toolbarListener(toolbarListener)
.build();
final OptionView mapSwipeMultipleMarker = new OptionView.Builder().mapsCard()
.title("Maps Card")
.setLocation(new LatLng(44.48, 11.33), new LatLng(43.45, 11.32), new LatLng(45.70, 10.11))
.menuItem(R.menu.menu_main)
.toolbarListener(toolbarListener)
.build();
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
cardOther = (CardView) findViewById(R.id.cardOther);
swipeableCard = (SwipeableCard) findViewById(R.id.swipeCard);
rv = (RecyclerView) findViewById(R.id.rv);
singleMarker = (RadioButton) findViewById(R.id.singleMarker);
multipleMarker = (RadioButton) findViewById(R.id.multipleMarker);
settedCard = (RadioButton) findViewById(R.id.settedCard);
creationCard = (RadioButton) findViewById(R.id.creationCard);
radioGroup = (RelativeLayout) findViewById(R.id.radioGroup);
radioGroupCreditCard = (RelativeLayout) findViewById(R.id.radioGroupCreditCard);
NavigationView navigationView = (NavigationView) findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.SingleSwipe:
/**
* Example of Single Swipeable Card.
*/
radioGroupCreditCard.setVisibility(View.GONE);
radioGroup.setVisibility(View.GONE);
rv.setVisibility(View.GONE);
cardOther.setVisibility(View.GONE);
swipeableCard.init(getApplicationContext(), singleSwipe);
swipeableCard.setVisibility(View.VISIBLE);
drawerLayout.closeDrawers();
break;
case R.id.CreditCard:
radioGroup.setVisibility(View.GONE);
radioGroupCreditCard.setVisibility(View.VISIBLE);
rv.setVisibility(View.GONE);
cardOther.setVisibility(View.GONE);
creationCard.setChecked(false);
settedCard.setChecked(true);
swipeableCard.init(getApplicationContext(), creditCardSetted);
swipeableCard.setVisibility(View.VISIBLE);
settedCard.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
swipeableCard.setVisibility(View.GONE);
if (settedCard.isChecked()) {
creationCard.setChecked(false);
swipeableCard.init(getApplicationContext(), creditCardSetted);
swipeableCard.setVisibility(View.VISIBLE);
}
}
});
creationCard.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
swipeableCard.setVisibility(View.GONE);
if (creationCard.isChecked()) {
settedCard.setChecked(false);
swipeableCard.init(getApplicationContext(), creditCardCreation);
swipeableCard.setVisibility(View.VISIBLE);
}
}
});
drawerLayout.closeDrawers();
break;
case R.id.SingleSwipeNotAutoAnimation:
/**
* Example of Single Swipeable Card with Swipe Gesture.
*/
radioGroupCreditCard.setVisibility(View.GONE);
radioGroup.setVisibility(View.GONE);
rv.setVisibility(View.GONE);
cardOther.setVisibility(View.GONE);
swipeableCard.init(getApplicationContext(), singleSwipeNotAutoAnimation);
swipeableCard.setVisibility(View.VISIBLE);
drawerLayout.closeDrawers();
break;
case R.id.OtherSwipe:
/**
* Example of Other Card Layout.
*/
radioGroupCreditCard.setVisibility(View.GONE);
radioGroup.setVisibility(View.GONE);
rv.setVisibility(View.GONE);
swipeableCard.setVisibility(View.GONE);
cardOther.setVisibility(View.VISIBLE); | final CustomCardAnimation cardAnim = new CustomCardAnimation(getApplicationContext(), cardOther, 200); | 0 |
adiyoss/StructED | src/com/structed/models/algorithms/ProbitLoss.java | [
"public class Consts {\n\n // GENERALS\n\tpublic static final String SPACE = \" \";\n public static final String TAB = \"\\t\";\n public static final String COMMA_NOTE = \",\";\n\tpublic static final String CLASSIFICATION_SPLITTER = \"-\";\n\tpublic static final String COLON_SPLITTER = \":\";\n public static final String PARAMS_SPLITTER = \";\";\n\tpublic static final String NEW_LINE = \"line.separator\";\n public static final int ERROR_NUMBER = -1;\n\n // DUMMY\n public static final int MIN_GAP_START_DUMMY = 3;\n public static final int MIN_GAP_END_DUMMY = 3;\n\n // VOWEL DURATION\n public static final int MIN_VOWEL = 9; //min training set: 45 frames\n\tpublic static final int MAX_VOWEL = 92; //max training set: 459 frames\n public static final int MIN_GAP_START = 10;\n public static final int MIN_GAP_END = 10;\n\n public static final double MEAN_VOWEL_LENGTH = 41.787; //pre calculated from the training set\n public static final double STD_VOWEL_LENGTH = 12.918; //pre calculated from the training set\n public static final double MAX_VOWEL_LENGTH = 38; //pre calculated from the training set\n\n // MODELS NUMBER OF PARAMETERS\n public static final int PA_PARAMS_SIZE = 1; //The number params 4 PA\n public static final int SVM_PARAMS_SIZE = 2; //The number params 4 SVM\n public static final int DL_PARAMS_SIZE = 2; //The number params 4 Direct Loss\n public static final int CRF_PARAMS_SIZE = 2; //The number params 4 CRF\n public static final int RL_PARAMS_SIZE = 2; //The number params 4 Ramp Loss\n public static final int PL_PARAMS_SIZE = 6; //The number params 4 Probit Loss\n public static final int SP_PARAMS_SIZE = 0; //The number params 0 Perceptron\n public static final int ORBIT_PARAMS_SIZE = 2; //The number params 4 orbit\n public static final int MULTICLASS_REGECT_SIZE = 4; //The number params 4 multiclass regect\n\n // KERNEL DEFAULT PARAMETERS\n public static double SIGMA = 1;\n\n //OCR\n public static final String END_NOTE = \"$\";\n}",
"public class ClassifierData {\n\n public ITaskLoss taskLoss;\n public IUpdateRule updateRule;\n public IInference inference;\n public IKernel kernel;\n public IFeatureFunctions phi;\n public List<Double> arguments;\n public int iteration = 0;\n public String verbose = \"\";\n}",
"public class ErrorConstants {\n\n\tpublic static final String GENERAL_ERROR = \"Error: \";\n\tpublic static final String RAW_DATA_EMPTY_ERROR = \"Raw data is empty\";\n\tpublic static final String VECTOR_CONVERT_ERROR = \"Error converting vector: \";\n\tpublic static final String PARSE_CLASSIFICATION_ERROR = \"Error with the classification of example: \";\n\tpublic static final String PHI_VECTOR_DATA = \"Phi vector data empty\";\n\t\n\tpublic static final String MULTIPLE_VECTORS_SIZE_ERROR = \"The vectors doesn't have the same size\";\n\tpublic static final String MULTIPLE_VECTORS_EMPTY_ERROR = \"The vectors are empty\";\n\t\n\tpublic static final String UPDATE_ARGUMENTS_ERROR = \"Size of arguments is not valid\";\n\tpublic static final String UPDATE_DIVIDE_ZERO_ERROR = \"Phi difference multiple return 0\";\n\t\n\tpublic static final String PHI_DATA_ERROR = \"Phi data is null\";\n\tpublic static final String EPOCH_ERROR = \"Epoch is a negative number\";\n\t\n\tpublic static final String SIZE_OF_TRAIN_ERROR = \"Train size is 0\";\n\tpublic static final String GAP_START_SIZE_ERROR = \"Gap start can not be 0\";\n\tpublic static final String GAP_END_SIZE_ERROR = \"Gap end can not be 0\";\n\tpublic static final String ZERO_DIVIDING = \"Can not divide by zero\";\n\t\n\tpublic static final String CONFIG_ERROR = \"Can not convert config file\";\n\tpublic static final String CONFIG_ARGUMENTS_ERROR = \"Invalid number of arguments\";\n public static final String CONFIG_ARGUMENTS_TYPE_ERROR = \"Invalid type of arguments\";\n\t\n\tpublic static final String WRONG_TEST_VALUES = \"Invalid test values\";\n\tpublic static final String WRONG_TRAIN_VALUES = \"Invalid train values\";\n\n public static final String WEIGHTS_VALUES = \"Error converting weights file.\";\n public static final String SORT_ERROR = \"Error, sorting the scores map.\";\n}",
"public abstract class Example {\n\n public String path;\n private String label;\n private int fold;\n public int sizeOfVector;\n\n\t//C'tor\n\tpublic Example() {\n label = \"\";\n sizeOfVector = 0;\n\t}\n\n\t//===========GETTERS AND SETTERS=========//\n\tpublic Vector getFeatures(){return null;}\n\tpublic void setFeatures(Vector features){}\n\n public ArrayList<Vector> getFeatures2D(){return null;}\n public void setFeatures2D(ArrayList<Vector> features){}\n public ArrayList<Integer> getLabels2D(){return null;}\n public void setLabels2D(ArrayList<Integer> rankLabels){}\n\n public String getLabel() {\n return label;\n }\n public void setLabel(String label) {\n this.label = label;\n }\n\n public int getFold() { return fold; }\n public void setFold(int fold) { this.fold = fold; }\n}",
"public class Vector extends HashMap<Integer, Double> implements Serializable{\n\n private static final long serialVersionUID = 1L;\n private int maxIndex;\n public Vector(){this.maxIndex = -1;}\n public Vector(Vector v){\n super(v);\n }\n\n @Override\n public Double put(Integer key, Double value){\n super.put(key, value);\n if(maxIndex < key) maxIndex = key;\n return value;\n }\n\n // getter\n public int getMaxIndex() {\n return maxIndex;\n }\n public void resetMaxIndex(){\n this.maxIndex = -1;\n }\n}",
"public class Logger {\n\n private static final String directory = \"log\";\n private static final String log_file = \"files.log\";\n\n /**\n * Write the message into the standard output\n * @param message - the message to be written\n */\n public static void info(String message){\n System.out.print(System.getProperty(Consts.NEW_LINE) + message);\n }\n\n /**\n * Write the message into the standard output without new line at the end\n * @param message - the message to be written\n */\n public static void info_no_new_line(String message){\n System.out.print(message);\n }\n\n /**\n * Write the message into the standard output with the data and time attached\n * @param message - the message to be written\n */\n public static void infoTime(String message){\n DateFormat dateFormat = new SimpleDateFormat(\"yyyy/MM/dd HH:mm:ss\");\n //get current date time with Date()\n Date date = new Date();\n if(message.isEmpty() || message.equals(\"\"))\n message = \"None,\";\n System.out.print(System.getProperty(Consts.NEW_LINE) + message + \" \" + dateFormat.format(date));\n }\n\n /**\n * Writes only the data and time to the standard output\n */\n public static void time(){\n DateFormat dateFormat = new SimpleDateFormat(\"yyyy/MM/dd HH:mm:ss\");\n //get current date time with Date()\n Date date = new Date();\n System.out.print(System.getProperty(Consts.NEW_LINE) + dateFormat.format(date));\n }\n\n /**\n * Write the message into the standard output with the data and time attached\n * @param msg - the message to be written\n * @param example - a running id\n */\n public static void timeExampleStandard(String msg, int example){\n DateFormat dateFormat = new SimpleDateFormat(\"yyyy/MM/dd HH:mm:ss\");\n //get current date time with Date()\n Date date = new Date();\n System.out.print(System.getProperty(Consts.NEW_LINE) + msg+example+\", \"+dateFormat.format(date));\n }\n\n /**\n * Write the message into the standard output as a progress bar\n * @param msg - the message to be written\n */\n public static void progressMessage(String msg){\n System.out.print(\"\\r\" + msg + \" \");\n }\n\n /**\n * Write the message into the standard error\n * @param message - the message to be written\n */\n public static void error(String message){\n System.err.println(\"Error: \"+message);\n }\n\n\n\n /**\n * Write the message into the files.log in the lod directory(if doesn't exists the program creates the dir)\n * @param message - tha message to ve written\n * @throws IOException\n */\n public static void log2File(String message) throws IOException\n {\n // create the log directory if does noe exists\n File dir = new File(directory);\n if(!dir.exists())\n dir.mkdir();\n\n // Create file stream\n File file = new File(directory+\"/\"+log_file);\n FileWriter fstream = new FileWriter(file,true);\n BufferedWriter out = new BufferedWriter(fstream);\n //writes the message\n out.write(message);\n out.write(System.getProperty(Consts.NEW_LINE));\n //close all the file descriptors\n out.close();\n fstream.close();\n }\n\n /**\n * clean the log directory\n */\n public static void clean(){\n File dir = new File(directory);\n if(dir.exists() && dir.isDirectory()) {\n String[]entries = dir.list();\n for(String s: entries){\n File currentFile = new File(dir.getPath(),s);\n currentFile.delete();\n }\n dir.delete();\n }\n\n dir.mkdir();\n }\n}",
"public class MathHelpers {\n\n /**\n * multiple two double vectors\n * @param v1 first vector\n * @param v2 second vector\n * @return the result\n */\n\tpublic static double multipleVectors(Vector v1, Vector v2)\n\t{\n\t\tdouble result = 0;\n Double num;\n\n\t\t//validation\n\t\tif(v1.size() == 0 || v2.size() == 0) {\n Logger.error(ErrorConstants.MULTIPLE_VECTORS_EMPTY_ERROR);\n\t\t\treturn 0;\n\t\t}\n\n if(v1.size() <= v2.size()) {\n //multiple the vectors\n for (Integer key : v1.keySet()) {\n num = v2.get(key);\n if (num != null)\n result += (v1.get(key) * v2.get(key));\n }\n } else {\n //multiple the vectors\n for (Integer key : v2.keySet()) {\n num = v1.get(key);\n if (num != null)\n result += (v1.get(key) * v2.get(key));\n }\n }\n\n\t\treturn result;\n\t}\n\n /**\n * add scalar to a double vector\n * @param v1 vector\n * @param scalar scalar\n * @return the result\n */\n\tpublic static Vector addScalar2Vectors(Vector v1, double scalar)\n\t{\n Vector result = new Vector();\n\n\t\tif(v1.size() == 0) {\n\t\t\tLogger.error(ErrorConstants.MULTIPLE_VECTORS_EMPTY_ERROR);\n\t\t\treturn null;\n\t\t}\n\n\t\t//multiple the vectors\n\t\tfor(Integer key : v1.keySet())\n\t\t\tresult.put(key, v1.get(key) + scalar);\n\n\t\treturn result;\n\t}\n\n /**\n * add scalar to a double vector\n * @param v1 vector\n * @param scalar scalar\n * @return the result\n */\n\tpublic static Vector mulScalarWithVectors(Vector v1, double scalar)\n\t{\n Vector result = new Vector();\n\n\t\tif(v1.size() == 0) {\n\t\t\tLogger.error(ErrorConstants.MULTIPLE_VECTORS_EMPTY_ERROR);\n\t\t\treturn null;\n\t\t}\n\n\t\t//multiple the vectors\n for(Integer key : v1.keySet())\n result.put(key, v1.get(key) * scalar);\n\n\t\treturn result;\n\t}\n\n /**\n * add scalar to a double vector\n * @param v1 first vector\n * @param v2 second vector\n * @return the result\n */\n\tpublic static Vector subtract2Vectors(Vector v1, Vector v2)\n\t{\n Vector result = new Vector ();\n Double num;\n\n\t\t//validation\n\t\tif(v1.size() == 0 || v2.size() == 0) {\n\t\t\tLogger.error(ErrorConstants.MULTIPLE_VECTORS_EMPTY_ERROR);\n\t\t\treturn null;\n\t\t}\n\n\t\t//subtract the vectors\n\t\tfor(Integer key : v1.keySet()){\n num = v2.get(key);\n if(num != null)\n\t\t\t result.put(key, v1.get(key)-v2.get(key));\n else\n result.put(key, v1.get(key));\n }\n\n for(Integer key : v2.keySet()){\n num = v1.get(key);\n if(num == null)\n result.put(key, (-1)*v2.get(key));\n }\n\n\t\treturn result;\n\t}\n\n /**\n * add scalar to a double vector\n * @param v1 first vector\n * @param v2 second vector\n * @return the result\n */\n\tpublic static Vector add2Vectors(Vector v1, Vector v2)\n\t{\n Vector result = new Vector();\n Double num;\n\t\t//validation\n if(v1.size() == 0 || v2.size() == 0) {\n Logger.error(ErrorConstants.MULTIPLE_VECTORS_EMPTY_ERROR);\n return null;\n }\n\n\t\t//add the vectors\n for(Integer key : v1.keySet()){\n num = v2.get(key);\n if(num != null)\n result.put(key, v1.get(key)+v2.get(key));\n else\n result.put(key, v1.get(key));\n }\n\n for(Integer key : v2.keySet()){\n num = v1.get(key);\n if(num == null)\n result.put(key, v2.get(key));\n }\n\n\t\treturn result;\n\t}\n\n /**\n * Preform sigmoid functions\n * @param x value\n * @return the sigmoid result\n */\n public static double sigmoid(double x) {\n return (1/( 1 + Math.pow(Math.E,(-1*x))));\n }\n}"
] | import com.structed.models.ClassifierData;
import com.structed.constants.ErrorConstants;
import com.structed.data.entities.Example;
import com.structed.data.entities.Vector;
import com.structed.data.Logger;
import com.structed.utils.MathHelpers;
import java.util.ArrayList;
import java.util.Random;
import com.structed.constants.Consts; | /*
* The MIT License (MIT)
*
* StructED - Machine Learning Package for Structured Prediction
*
* Copyright (c) 2015 Yossi Adi, E-Mail: [email protected]
*
* 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 com.structed.models.algorithms;
/**
* Probit Loss Algorithm
* http://cs.haifa.ac.il/~tamir/papers/KeshetMcHa10.pdf
*/
public class ProbitLoss implements IUpdateRule {
//data members
double lambda;
double eta;
double numOfIteration; //indicates the number of iterations
double noiseAllVector; //indicates whether to noise all the weights vector or just one random element from it
double mean; //indicates the mean to the noise to be generated
double stDev; //indicates the standard deviation to the noise to be generated
@Override
public void init(ArrayList<Double> args) {
if(args.size() != Consts.PL_PARAMS_SIZE){
Logger.error(ErrorConstants.UPDATE_ARGUMENTS_ERROR);
return;
}
//initialize the parameters
this.eta = args.get(0);
this.lambda = args.get(1);
this.numOfIteration = args.get(2);
this.noiseAllVector = args.get(3);
this.mean = args.get(4);
this.stDev = args.get(5);
}
/**
* Implementation of the update rule
* @param currentWeights - the current weights
* @param example - a single example
* @param classifierData - all the additional data that needed such as: loss function, inference, etc.
* @return the new set of weights
*/
@Override
//eta would be at the first cell
//lambda would be at the second cell
//the number of iteration that we'll go and generate epsilon | public Vector update(Vector currentWeights, Example example, ClassifierData classifierData) { | 3 |
shibing624/crf-seg | src/main/java/org/xm/xmnlp/seg/CRFSegment.java | [
"public class Xmnlp {\n /**\n * 日志组件\n */\n private static Logger logger = LogManager.getLogger();\n\n public static final class Config {\n /**\n * 默认关闭调试\n */\n public static boolean DEBUG = false;\n /**\n * 字符类型对应表\n */\n public static String CharTypePath = \"data/dictionary/other/CharType.dat.yes\";\n\n /**\n * 字符正规化表(全角转半角,繁体转简体)\n */\n public static String CharTablePath = \"data/dictionary/other/CharTable.bin.yes\";\n\n /**\n * 词频统计输出路径\n */\n public static String StatisticsResultPath = \"data/result/WordFrequencyStatistics-Result.txt\";\n /**\n * 最大熵-依存关系模型\n */\n public static String MaxEntModelPath = \"data/model/dependency/MaxEntModel.txt\";\n /**\n * 神经网络依存模型路径\n */\n public static String NNParserModelPath = \"data/model/dependency/NNParserModel.txt\";\n /**\n * CRF分词模型\n */\n public static String CRFSegmentModelPath = \"data/model/seg/CRFSegmentModel.txt\";\n /**\n * HMM分词模型\n */\n public static String HMMSegmentModelPath = \"data/model/seg/HMMSegmentModel.bin\";\n /**\n * CRF依存模型\n */\n public static String CRFDependencyModelPath = \"data/model/dependency/CRFDependencyModelMini.txt\";\n /**\n * 分词结果是否展示词性\n */\n public static boolean ShowTermNature = true;\n /**\n * 是否执行字符正规化(繁体->简体,全角->半角,大写->小写),切换配置后必须删CustomDictionary.txt.bin缓存\n */\n public static boolean Normalization = false;\n\n static {\n Properties p = new Properties();\n try {\n ClassLoader loader = Thread.currentThread().getContextClassLoader();\n if (loader == null) {\n loader = Xmnlp.Config.class.getClassLoader();\n }\n p.load(new InputStreamReader(Static.PROPERTIES_PATH == null ?\n loader.getResourceAsStream(\"xmnlp.properties\")\n : new FileInputStream(Static.PROPERTIES_PATH), \"UTF-8\"));\n String root = p.getProperty(\"root\", \"\").replaceAll(\"\\\\\\\\\", \"/\");\n if (!root.endsWith(\"/\")) root += \"/\";\n String prePath = root;\n MaxEntModelPath = root + p.getProperty(\"MaxEntModelPath\", MaxEntModelPath);\n NNParserModelPath = root + p.getProperty(\"NNParserModelPath\", NNParserModelPath);\n CRFSegmentModelPath = root + p.getProperty(\"CRFSegmentModelPath\", CRFSegmentModelPath);\n CRFDependencyModelPath = root + p.getProperty(\"CRFDependencyModelPath\", CRFDependencyModelPath);\n HMMSegmentModelPath = root + p.getProperty(\"HMMSegmentModelPath\", HMMSegmentModelPath);\n ShowTermNature = \"true\".equals(p.getProperty(\"ShowTermNature\", \"true\"));\n Normalization = \"true\".equals(p.getProperty(\"Normalization\", \"false\"));\n } catch (Exception e) {\n StringBuilder sb = new StringBuilder(\"make sure the xmnlp.properties is exist.\");\n String classPath = (String) System.getProperties().get(\"java.class.PATHS\");\n if (classPath != null) {\n for (String path : classPath.split(File.pathSeparator)) {\n if (new File(path).isDirectory()) {\n sb.append(path).append('\\n');\n }\n }\n }\n sb.append(\"并且编辑root=PARENT/PATHS/to/your/data\\n\");\n sb.append(\"现在Xmnlp将尝试从\").append(System.getProperties().get(\"user.dir\")).append(\"读取data……\");\n logger.warn(\"没有找到xmnlp.properties,可能会导致找不到data\\n\" + sb);\n }\n }\n\n }\n\n private Xmnlp() {\n }\n\n\n /**\n * CRF分词\n *\n * @param text 文本\n * @return 切分后的单词\n */\n public static List<Term> crfSegment(String text) {\n return new CRFSegment().seg(text);\n }\n\n}",
"public class CharTable {\n /**\n * 正规化使用的对应表\n */\n public static char[] CONVERT;\n\n static {\n long start = System.currentTimeMillis();\n try {\n ObjectInputStream in = new ObjectInputStream(new FileInputStream(Xmnlp.Config.CharTablePath));\n CONVERT = (char[]) in.readObject();\n in.close();\n } catch (Exception e) {\n System.err.println(\"字符正规化表加载失败,原因如下:\");\n e.printStackTrace();\n System.exit(-1);\n }\n\n //System.out.println(\"字符正规化表加载成功:\" + (System.currentTimeMillis() - start) + \" ms\");\n }\n\n /**\n * 将一个字符正规化\n *\n * @param c 字符\n * @return 正规化后的字符\n */\n public static char convert(char c) {\n return CONVERT[c];\n }\n\n public static char[] convert(char[] charArray) {\n char[] result = new char[charArray.length];\n for (int i = 0; i < charArray.length; i++) {\n result[i] = CONVERT[charArray[i]];\n }\n\n return result;\n }\n\n public static String convert(String charArray) {\n assert charArray != null;\n char[] result = new char[charArray.length()];\n for (int i = 0; i < charArray.length(); i++) {\n result[i] = CONVERT[charArray.charAt(i)];\n }\n\n return new String(result);\n }\n\n /**\n * 正规化一些字符(原地正规化)\n *\n * @param charArray 字符\n */\n public static void normalization(char[] charArray) {\n assert charArray != null;\n for (int i = 0; i < charArray.length; i++) {\n charArray[i] = CONVERT[charArray[i]];\n }\n }\n}",
"public final class CRFSegmentModel extends CRFModel {\n /**\n * 日志组件\n */\n public static Logger logger = LogManager.getLogger();\n public static CRFModel crfModel;\n\n static {\n logger.info(\"CRF分词模型正在加载 \" + Xmnlp.Config.CRFSegmentModelPath);\n long start = System.currentTimeMillis();\n crfModel = CRFModel.loadTxt(Xmnlp.Config.CRFSegmentModelPath, new CRFSegmentModel(new BinTrie<FeatureFunction>()));\n if (crfModel == null) {\n String error = \"CRF分词模型加载 \" + Xmnlp.Config.CRFSegmentModelPath + \" 失败,耗时 \" + (System.currentTimeMillis() - start) + \" ms\";\n logger.error(error);\n throw new IllegalArgumentException(error);\n } else\n logger.info(\"CRF分词模型加载 \" + Xmnlp.Config.CRFSegmentModelPath + \" 成功,耗时 \" + (System.currentTimeMillis() - start) + \" ms\");\n }\n\n private final static int idM = crfModel.getTagId(\"M\");\n private final static int idE = crfModel.getTagId(\"E\");\n private final static int idS = crfModel.getTagId(\"S\");\n\n /**\n * 单例包装静态模型,不允许构造实例\n */\n private CRFSegmentModel() {\n }\n\n /**\n * 以指定的trie树结构储存内部特征函数\n *\n * @param featureFunctionTrie\n */\n private CRFSegmentModel(ITrie<FeatureFunction> featureFunctionTrie) {\n super(featureFunctionTrie);\n }\n\n @Override\n public void tag(Table table) {\n int size = table.size();\n if (size == 1) {\n table.setLast(0, \"S\");\n return;\n }\n double[][] net = new double[size][4];\n for (int i = 0; i < size; ++i) {\n LinkedList<double[]> scoreList = computeScoreList(table, i);\n for (int tag = 0; tag < 4; ++tag) {\n net[i][tag] = computeScore(scoreList, tag);\n }\n }\n net[0][idM] = -1000.0; // 第一个字不可能是M或E\n net[0][idE] = -1000.0;\n int[][] from = new int[size][4];\n for (int i = 1; i < size; ++i) {\n for (int now = 0; now < 4; ++now) {\n double maxScore = -1e10;\n for (int pre = 0; pre < 4; ++pre) {\n double score = net[i - 1][pre] + matrix[pre][now] + net[i][now];\n if (score > maxScore) {\n maxScore = score;\n from[i][now] = pre;\n }\n }\n net[i][now] = maxScore;\n }\n }\n // 反向回溯最佳路径\n int maxTag = net[size - 1][idS] > net[size - 1][idE] ? idS : idE;\n table.setLast(size - 1, id2tag[maxTag]);\n maxTag = from[size - 1][maxTag];\n for (int i = size - 2; i > 0; --i) {\n table.setLast(i, id2tag[maxTag]);\n maxTag = from[i][maxTag];\n }\n table.setLast(0, id2tag[maxTag]);\n }\n}",
"public class Table {\n /**\n * 真实值,请不要直接读取\n */\n public String[][] v;\n static final String HEAD = \"_B\";\n\n @Override\n public String toString() {\n if (v == null) return \"null\";\n final StringBuilder sb = new StringBuilder(v.length * v[0].length * 2);\n for (String[] line : v) {\n for (String element : line) {\n sb.append(element).append('\\t');\n }\n sb.append('\\n');\n }\n return sb.toString();\n }\n\n /**\n * 获取表中某一个元素\n *\n * @param x\n * @param y\n * @return\n */\n public String get(int x, int y) {\n if (x < 0) return HEAD + x;\n if (x >= v.length) return HEAD + \"+\" + (x - v.length + 1);\n\n return v[x][y];\n }\n\n public void setLast(int x, String t) {\n v[x][v[x].length - 1] = t;\n }\n\n public int size() {\n return v.length;\n }\n}",
"public enum Nature {\n /**\n * 区别语素\n */\n bg,\n\n /**\n * 数语素\n */\n mg,\n\n /**\n * 名词性惯用语\n */\n nl,\n\n /**\n * 字母专名\n */\n nx,\n\n /**\n * 量词语素\n */\n qg,\n\n /**\n * 助词\n */\n ud,\n\n /**\n * 助词\n */\n uj,\n\n /**\n * 着\n */\n uz,\n\n /**\n * 过\n */\n ug,\n\n /**\n * 连词\n */\n ul,\n\n /**\n * 连词\n */\n uv,\n\n /**\n * 语气语素\n */\n yg,\n\n /**\n * 状态词\n */\n zg,\n\n // 以上标签来自ICT,以下标签来自北大\n\n /**\n * 名词\n */\n n,\n\n /**\n * 人名\n */\n nr,\n\n /**\n * 日语人名\n */\n nrj,\n\n /**\n * 音译人名\n */\n nrf,\n\n /**\n * 复姓\n */\n nr1,\n\n /**\n * 蒙古姓名\n */\n nr2,\n\n /**\n * 地名\n */\n ns,\n\n /**\n * 音译地名\n */\n nsf,\n\n /**\n * 机构团体名\n */\n nt,\n\n /**\n * 公司名\n */\n ntc,\n\n /**\n * 工厂\n */\n ntcf,\n\n /**\n * 银行\n */\n ntcb,\n\n /**\n * 酒店宾馆\n */\n ntch,\n\n /**\n * 政府机构\n */\n nto,\n\n /**\n * 大学\n */\n ntu,\n\n /**\n * 中小学\n */\n nts,\n\n /**\n * 医院\n */\n nth,\n\n /**\n * 医药疾病等健康相关名词\n */\n nh,\n\n /**\n * 药品\n */\n nhm,\n\n /**\n * 疾病\n */\n nhd,\n\n /**\n * 工作相关名词\n */\n nn,\n\n /**\n * 职务职称\n */\n nnt,\n\n /**\n * 职业\n */\n nnd,\n\n /**\n * 名词性语素\n */\n ng,\n\n /**\n * 食品,比如“薯片”\n */\n nf,\n\n /**\n * 机构相关(不是独立机构名)\n */\n ni,\n\n /**\n * 教育相关机构\n */\n nit,\n\n /**\n * 下属机构\n */\n nic,\n\n /**\n * 机构后缀\n */\n nis,\n\n /**\n * 物品名\n */\n nm,\n\n /**\n * 化学品名\n */\n nmc,\n\n /**\n * 生物名\n */\n nb,\n\n /**\n * 动物名\n */\n nba,\n\n /**\n * 动物纲目\n */\n nbc,\n\n /**\n * 植物名\n */\n nbp,\n\n /**\n * 其他专名\n */\n nz,\n\n /**\n * 学术词汇\n */\n g,\n\n /**\n * 数学相关词汇\n */\n gm,\n\n /**\n * 物理相关词汇\n */\n gp,\n\n /**\n * 化学相关词汇\n */\n gc,\n\n /**\n * 生物相关词汇\n */\n gb,\n\n /**\n * 生物类别\n */\n gbc,\n\n /**\n * 地理地质相关词汇\n */\n gg,\n\n /**\n * 计算机相关词汇\n */\n gi,\n\n /**\n * 简称略语\n */\n j,\n\n /**\n * 成语\n */\n i,\n\n /**\n * 习用语\n */\n l,\n\n /**\n * 时间词\n */\n t,\n\n /**\n * 时间词性语素\n */\n tg,\n\n /**\n * 处所词\n */\n s,\n\n /**\n * 方位词\n */\n f,\n\n /**\n * 动词\n */\n v,\n\n /**\n * 副动词\n */\n vd,\n\n /**\n * 名动词\n */\n vn,\n\n /**\n * 动词“是”\n */\n vshi,\n\n /**\n * 动词“有”\n */\n vyou,\n\n /**\n * 趋向动词\n */\n vf,\n\n /**\n * 形式动词\n */\n vx,\n\n /**\n * 不及物动词(内动词)\n */\n vi,\n\n /**\n * 动词性惯用语\n */\n vl,\n\n /**\n * 动词性语素\n */\n vg,\n\n /**\n * 形容词\n */\n a,\n\n /**\n * 副形词\n */\n ad,\n\n /**\n * 名形词\n */\n an,\n\n /**\n * 形容词性语素\n */\n ag,\n\n /**\n * 形容词性惯用语\n */\n al,\n\n /**\n * 区别词\n */\n b,\n\n /**\n * 区别词性惯用语\n */\n bl,\n\n /**\n * 状态词\n */\n z,\n\n /**\n * 代词\n */\n r,\n\n /**\n * 人称代词\n */\n rr,\n\n /**\n * 指示代词\n */\n rz,\n\n /**\n * 时间指示代词\n */\n rzt,\n\n /**\n * 处所指示代词\n */\n rzs,\n\n /**\n * 谓词性指示代词\n */\n rzv,\n\n /**\n * 疑问代词\n */\n ry,\n\n /**\n * 时间疑问代词\n */\n ryt,\n\n /**\n * 处所疑问代词\n */\n rys,\n\n /**\n * 谓词性疑问代词\n */\n ryv,\n\n /**\n * 代词性语素\n */\n rg,\n\n /**\n * 古汉语代词性语素\n */\n Rg,\n\n /**\n * 数词\n */\n m,\n\n /**\n * 数量词\n */\n mq,\n\n /**\n * 甲乙丙丁之类的数词\n */\n Mg,\n\n /**\n * 量词\n */\n q,\n\n /**\n * 动量词\n */\n qv,\n\n /**\n * 时量词\n */\n qt,\n\n /**\n * 副词\n */\n d,\n\n /**\n * 辄,俱,复之类的副词\n */\n dg,\n\n /**\n * 连语\n */\n dl,\n\n /**\n * 介词\n */\n p,\n\n /**\n * 介词“把”\n */\n pba,\n\n /**\n * 介词“被”\n */\n pbei,\n\n /**\n * 连词\n */\n c,\n\n /**\n * 并列连词\n */\n cc,\n\n /**\n * 助词\n */\n u,\n\n /**\n * 着\n */\n uzhe,\n\n /**\n * 了 喽\n */\n ule,\n\n /**\n * 过\n */\n uguo,\n\n /**\n * 的 底\n */\n ude1,\n\n /**\n * 地\n */\n ude2,\n\n /**\n * 得\n */\n ude3,\n\n /**\n * 所\n */\n usuo,\n\n /**\n * 等 等等 云云\n */\n udeng,\n\n /**\n * 一样 一般 似的 般\n */\n uyy,\n\n /**\n * 的话\n */\n udh,\n\n /**\n * 来讲 来说 而言 说来\n */\n uls,\n\n /**\n * 之\n */\n uzhi,\n\n /**\n * 连 (“连小学生都会”)\n */\n ulian,\n\n /**\n * 叹词\n */\n e,\n\n /**\n * 语气词(delete yg)\n */\n y,\n\n /**\n * 拟声词\n */\n o,\n\n /**\n * 前缀\n */\n h,\n\n /**\n * 后缀\n */\n k,\n\n /**\n * 字符串\n */\n x,\n\n /**\n * 非语素字\n */\n xx,\n\n /**\n * 网址URL\n */\n xu,\n\n /**\n * 标点符号\n */\n w,\n\n /**\n * 左括号,全角:( 〔 [ { 《 【 〖 〈 半角:( [ { <\n */\n wkz,\n\n /**\n * 右括号,全角:) 〕 ] } 》 】 〗 〉 半角: ) ] { >\n */\n wky,\n\n /**\n * 左引号,全角:“ ‘ 『\n */\n wyz,\n\n /**\n * 右引号,全角:” ’ 』\n */\n wyy,\n\n /**\n * 句号,全角:。\n */\n wj,\n\n /**\n * 问号,全角:? 半角:?\n */\n ww,\n\n /**\n * 叹号,全角:! 半角:!\n */\n wt,\n\n /**\n * 逗号,全角:, 半角:,\n */\n wd,\n\n /**\n * 分号,全角:; 半角: ;\n */\n wf,\n\n /**\n * 顿号,全角:、\n */\n wn,\n\n /**\n * 冒号,全角:: 半角: :\n */\n wm,\n\n /**\n * 省略号,全角:…… …\n */\n ws,\n\n /**\n * 破折号,全角:—— -- ——- 半角:--- ----\n */\n wp,\n\n /**\n * 百分号千分号,全角:% ‰ 半角:%\n */\n wb,\n\n /**\n * 单位符号,全角:¥ $ £ ° ℃ 半角:$\n */\n wh,\n\n /**\n * 仅用于终##终,不会出现在分词结果中\n */\n end,\n\n /**\n * 仅用于始##始,不会出现在分词结果中\n */\n begin,;\n\n /**\n * 词性是否以该前缀开头<br>\n * 词性根据开头的几个字母可以判断大的类别\n *\n * @param prefix 前缀\n * @return 是否以该前缀开头\n */\n public boolean startsWith(String prefix) {\n return toString().startsWith(prefix);\n }\n\n /**\n * 词性是否以该前缀开头<br>\n * 词性根据开头的几个字母可以判断大的类别\n *\n * @param prefix 前缀\n * @return 是否以该前缀开头\n */\n public boolean startsWith(char prefix) {\n return toString().charAt(0) == prefix;\n }\n\n /**\n * 词性的首字母<br>\n * 词性根据开头的几个字母可以判断大的类别\n *\n * @return\n */\n public char firstChar() {\n return toString().charAt(0);\n }\n\n /**\n * 安全地将字符串类型的词性转为Enum类型,如果未定义该词性,则返回null\n *\n * @param name 字符串词性\n * @return Enum词性\n */\n public static Nature fromString(String name) {\n try {\n return Nature.valueOf(name);\n } catch (Exception e) {\n return null;\n }\n }\n\n// /**\n// * 创建自定义词性,如果已有该对应词性,则直接返回已有的词性\n// *\n// * @param name 字符串词性\n// * @return Enum词性\n// */\n// public static Nature create(String name) {\n// try {\n// return Nature.valueOf(name);\n// } catch (Exception e) {\n// return CustomNatureUtility.addNature(name);\n// }\n// }\n}",
"public class Term {\n /**\n * 词语\n */\n public String word;\n\n /**\n * 词性\n */\n public Nature nature;\n\n /**\n * 在文本中的起始位置(需开启分词器的offset选项)\n */\n public int offset;\n\n /**\n * 长度\n */\n public int length() {\n return word.length();\n }\n\n /**\n * 词性\n */\n public Nature getNature() {\n return nature;\n }\n\n public void setNature(Nature nature) {\n this.nature = nature;\n }\n\n /**\n * 构造一个单词\n *\n * @param word 词语\n * @param nature 词性\n */\n public Term(String word, Nature nature) {\n this.word = word;\n this.setNature(nature);\n }\n\n @Override\n public String toString() {\n if (Xmnlp.Config.ShowTermNature)\n return word + \"/\" + getNature();\n return word;\n }\n\n public String toString(String split) {\n if (Xmnlp.Config.ShowTermNature)\n return word + split + getNature();\n return word;\n }\n\n}",
"public class Vertex {\n /**\n * 节点对应的词或等效词(如未##数)\n */\n public String word;\n /**\n * 节点对应的真实词,绝对不含##\n */\n public String realWord;\n /**\n * 等效词ID,也是Attribute的下标\n */\n public int wordID;\n /**\n * 在一维顶点数组中的下标,可以视作这个顶点的id\n */\n public int index;\n /**\n * 到该节点的最短路径的前驱节点\n */\n public Vertex from;\n /**\n * 最短路径对应的权重\n */\n public double weight;\n\n /**\n * 获取真实词\n *\n * @return\n */\n public String getRealWord() {\n return realWord;\n }\n\n\n public Vertex setWord(String word) {\n this.word = word;\n return this;\n }\n\n public Vertex setRealWord(String realWord) {\n this.realWord = realWord;\n return this;\n }\n\n @Override\n public String toString() {\n return realWord;\n }\n}",
"public class CharacterHelper {\n\n public static boolean isSpaceLetter(char input) {\n return input == 8 || input == 9\n || input == 10 || input == 13\n || input == 32 || input == 160;\n }\n\n public static boolean isEnglishLetter(char input) {\n return (input >= 'a' && input <= 'z')\n || (input >= 'A' && input <= 'Z');\n }\n\n public static boolean isArabicNumber(char input) {\n return input >= '0' && input <= '9';\n }\n\n public static boolean isCJKCharacter(char input) {\n Character.UnicodeBlock ub = Character.UnicodeBlock.of(input);\n if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS\n || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS\n || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A\n //全角数字字符和日韩字符\n || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS\n //韩文字符集\n || ub == Character.UnicodeBlock.HANGUL_SYLLABLES\n || ub == Character.UnicodeBlock.HANGUL_JAMO\n || ub == Character.UnicodeBlock.HANGUL_COMPATIBILITY_JAMO\n //日文字符集\n || ub == Character.UnicodeBlock.HIRAGANA //平假名\n || ub == Character.UnicodeBlock.KATAKANA //片假名\n || ub == Character.UnicodeBlock.KATAKANA_PHONETIC_EXTENSIONS\n ) {\n return true;\n } else {\n return false;\n }\n //其他的CJK标点符号,可以不做处理\n //|| ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION\n //|| ub == Character.UnicodeBlock.GENERAL_PUNCTUATION\n }\n\n\n /**\n * 进行字符规格化(全角转半角,大写转小写处理)\n *\n * @param input\n * @return char\n */\n public static char regularize(char input) {\n if (input == 12288) {\n input = (char) 32;\n\n } else if (input > 65280 && input < 65375) {\n input = (char) (input - 65248);\n\n } else if (input >= 'A' && input <= 'Z') {\n input += 32;\n }\n\n return input;\n }\n\n}"
] | import org.xm.xmnlp.Xmnlp;
import org.xm.xmnlp.dictionary.other.CharTable;
import org.xm.xmnlp.model.crf.CRFSegmentModel;
import org.xm.xmnlp.model.crf.Table;
import org.xm.xmnlp.seg.domain.Nature;
import org.xm.xmnlp.seg.domain.Term;
import org.xm.xmnlp.seg.domain.Vertex;
import org.xm.xmnlp.util.CharacterHelper;
import java.util.*; | package org.xm.xmnlp.seg;
/**
* 基于CRF的分词器
*
* @author XuMing
*/
public class CRFSegment extends Segment {
@Override
protected List<Term> segSentence(char[] sentence) {
if (sentence.length == 0) return Collections.emptyList();
char[] sentenceConverted = CharTable.convert(sentence); | Table table = new Table(); | 3 |
cjstehno/ersatz | ersatz/src/test/java/io/github/cjstehno/ersatz/impl/RequestMatcherTest.java | [
"public enum HttpMethod {\r\n\r\n /**\r\n * Wildcard matching any HTTP method.\r\n */\r\n ANY(\"*\"),\r\n\r\n /**\r\n * HTTP GET method matcher.\r\n */\r\n GET(\"GET\"),\r\n\r\n /**\r\n * HTTP HEAD method matcher.\r\n */\r\n HEAD(\"HEAD\"),\r\n\r\n /**\r\n * HTTP POST method matcher.\r\n */\r\n POST(\"POST\"),\r\n\r\n /**\r\n * HTTP PUT method matcher.\r\n */\r\n PUT(\"PUT\"),\r\n\r\n /**\r\n * HTTP DELETE method matcher.\r\n */\r\n DELETE(\"DELETE\"),\r\n\r\n /**\r\n * HTTP PATCH method matcher.\r\n */\r\n PATCH(\"PATCH\"),\r\n\r\n /**\r\n * HTTP OPTIONS method matcher.\r\n */\r\n OPTIONS(\"OPTIONS\"),\r\n\r\n /**\r\n * HTTP TRACE method matcher.\r\n */\r\n TRACE(\"TRACE\");\r\n\r\n private final String value;\r\n\r\n HttpMethod(final String value) {\r\n this.value = value;\r\n }\r\n\r\n /**\r\n * Retrieve the text value for the method.\r\n *\r\n * @return the method label.\r\n */\r\n public String getValue() {\r\n return value;\r\n }\r\n\r\n @Override public String toString() {\r\n return value;\r\n }\r\n}",
"public class DecoderChain extends FunctionChain<RequestDecoders> {\r\n\r\n /**\r\n * Creates a chain of decoders with the given initial item.\r\n *\r\n * @param firstItem the first decoders in the chain\r\n */\r\n public DecoderChain(final RequestDecoders firstItem) {\r\n super(firstItem);\r\n }\r\n\r\n /**\r\n * Resolves the decoder for the specified request content-type.\r\n *\r\n * @param contentType the request content-type\r\n * @return the decoder function\r\n */\r\n public BiFunction<byte[], DecodingContext, Object> resolve(final String contentType) {\r\n return resolveWith(d -> d.findDecoder(contentType));\r\n }\r\n\r\n /**\r\n * Resolves the decoder for the specified request content-type.\r\n *\r\n * @param contentType the request content-type\r\n * @return the decoder function\r\n */\r\n public BiFunction<byte[], DecodingContext, Object> resolve(final ContentType contentType) {\r\n return resolve(contentType.getValue());\r\n }\r\n}\r",
"public interface Decoders {\r\n\r\n /**\r\n * Decoder that simply passes the content bytes through as an array of bytes.\r\n */\r\n BiFunction<byte[], DecodingContext, Object> passthrough = (content, ctx) -> content;\r\n\r\n /**\r\n * Decoder that converts request content bytes into a UTF-8 string.\r\n */\r\n BiFunction<byte[], DecodingContext, Object> utf8String = string(UTF_8);\r\n\r\n /**\r\n * Decoder that converts request content bytes into a UTF-8 string.\r\n *\r\n * @return the decoded bytes as a string\r\n */\r\n static BiFunction<byte[], DecodingContext, Object> string() {\r\n return string(UTF_8);\r\n }\r\n\r\n /**\r\n * Decoder that converts request content bytes into a string of the specified charset.\r\n *\r\n * @param charset the name of the charset\r\n * @return the decoded bytes as a string\r\n */\r\n static BiFunction<byte[], DecodingContext, Object> string(final String charset) {\r\n return string(Charset.forName(charset));\r\n }\r\n\r\n /**\r\n * Decoder that converts request content bytes into a string of the specified charset.\r\n *\r\n * @param charset the charset to be used\r\n * @return the decoded bytes as a string\r\n */\r\n static BiFunction<byte[], DecodingContext, Object> string(final Charset charset) {\r\n return (content, ctx) -> content != null ? new String(content, charset) : \"\";\r\n }\r\n\r\n /**\r\n * Decoder that converts request content bytes in a url-encoded format into a map of name/value pairs.\r\n */\r\n BiFunction<byte[], DecodingContext, Object> urlEncoded = (content, ctx) -> {\r\n val map = new HashMap<String, String>();\r\n\r\n if (content != null) {\r\n for (val nvp : new String(content, UTF_8).split(\"&\")) {\r\n val parts = nvp.split(\"=\");\r\n try {\r\n if (parts.length == 2) {\r\n map.put(decode(parts[0], UTF_8.name()), decode(parts[1], UTF_8.name()));\r\n }\r\n } catch (Exception e) {\r\n throw new IllegalArgumentException(e.getMessage());\r\n }\r\n }\r\n }\r\n\r\n return map;\r\n };\r\n\r\n /**\r\n * Decoder that converts request content bytes into a <code>MultipartRequestContent</code> object populated with the multipart request content.\r\n */\r\n BiFunction<byte[], DecodingContext, Object> multipart = (content, ctx) -> {\r\n List<FileItem> parts;\r\n try {\r\n val tempDir = Files.createTempDirectory(\"ersatz-multipart-\").toFile();\r\n parts = new FileUpload(new DiskFileItemFactory(10_000, tempDir)).parseRequest(new UploadContext() {\r\n @Override\r\n public long contentLength() {\r\n return ctx.getContentLength();\r\n }\r\n\r\n @Override\r\n public String getCharacterEncoding() {\r\n return ctx.getCharacterEncoding();\r\n }\r\n\r\n @Override\r\n public String getContentType() {\r\n return ctx.getContentType();\r\n }\r\n\r\n @Override\r\n public int getContentLength() {\r\n return (int) ctx.getContentLength();\r\n }\r\n\r\n @Override\r\n public InputStream getInputStream() throws IOException {\r\n return new ByteArrayInputStream(content);\r\n }\r\n });\r\n } catch (final Exception e) {\r\n throw new IllegalArgumentException(e.getMessage());\r\n }\r\n\r\n val multipartRequest = new MultipartRequestContent();\r\n\r\n parts.forEach(part -> {\r\n val partCtx = new DecodingContext(part.getSize(), part.getContentType(), null, ctx.getDecoderChain());\r\n\r\n if (part.isFormField()) {\r\n multipartRequest.part(part.getFieldName(), TEXT_PLAIN, ctx.getDecoderChain().resolve(TEXT_PLAIN).apply(part.get(), partCtx));\r\n } else {\r\n multipartRequest.part(\r\n part.getFieldName(),\r\n part.getName(),\r\n part.getContentType(),\r\n ctx.getDecoderChain().resolve(part.getContentType()).apply(part.get(), partCtx)\r\n );\r\n }\r\n });\r\n\r\n return multipartRequest;\r\n };\r\n}\r",
"public class RequestDecoders {\r\n\r\n private final List<DecoderMapping> decoders = new LinkedList<>();\r\n\r\n /**\r\n * Creates a new request decoder container based on the configuration consumer.\r\n *\r\n * @param consumer the decoder configuration consumer\r\n * @return the configured decoders\r\n */\r\n public static RequestDecoders decoders(final Consumer<RequestDecoders> consumer) {\r\n final var decoders = new RequestDecoders();\r\n consumer.accept(decoders);\r\n return decoders;\r\n }\r\n\r\n /**\r\n * Registers the decoder function with the collection\r\n *\r\n * @param contentType the content type\r\n * @param decoder the decoder function\r\n */\r\n public void register(final ContentType contentType, final BiFunction<byte[], DecodingContext, Object> decoder) {\r\n register(contentType.getValue(), decoder);\r\n }\r\n\r\n /**\r\n * Registers the decoder function with the collection\r\n *\r\n * @param contentType the content type\r\n * @param decoder the decoder function\r\n */\r\n public void register(final String contentType, final BiFunction<byte[], DecodingContext, Object> decoder) {\r\n decoders.stream()\r\n .filter(m -> m.mimeType.toString().equals(contentType))\r\n .findFirst()\r\n .ifPresent(decoders::remove);\r\n\r\n decoders.add(new DecoderMapping(createMimeType(contentType), decoder));\r\n }\r\n\r\n /**\r\n * Finds a decoder for the specified content type.\r\n *\r\n * @param contentType the content type\r\n * @return the decoder function\r\n */\r\n public BiFunction<byte[], DecodingContext, Object> findDecoder(final ContentType contentType) {\r\n return findDecoder(contentType.getValue());\r\n }\r\n\r\n /**\r\n * Finds a decoder for the specified content type.\r\n *\r\n * @param contentType the content type\r\n * @return the decoder function\r\n */\r\n public BiFunction<byte[], DecodingContext, Object> findDecoder(final String contentType) {\r\n final MimeType mimeType = createMimeType(contentType);\r\n\r\n final List<DecoderMapping> found = decoders.stream()\r\n .filter(c -> c.mimeType.match(mimeType))\r\n .collect(Collectors.toList());\r\n\r\n if (found.isEmpty()) {\r\n return null;\r\n\r\n } else if (found.size() > 1) {\r\n return found.stream()\r\n .filter(f -> f.mimeType.toString().equals(contentType))\r\n .findFirst()\r\n .map(m -> m.decoder)\r\n .orElse(null);\r\n\r\n } else {\r\n return found.get(0).decoder;\r\n }\r\n }\r\n\r\n private static class DecoderMapping {\r\n\r\n final MimeType mimeType;\r\n final BiFunction<byte[], DecodingContext, Object> decoder;\r\n\r\n DecoderMapping(MimeType mimeType, BiFunction<byte[], DecodingContext, Object> decoder) {\r\n this.mimeType = mimeType;\r\n this.decoder = decoder;\r\n }\r\n }\r\n}",
"public class CookieMatcher extends BaseMatcher<Cookie> {\r\n\r\n private final Map<CookieField, Matcher> matchers = new EnumMap<>(CookieField.class);\r\n\r\n /**\r\n * Configures the cookie matcher with a consumer which is passed a <code>CookieMatcher</code> instance to configure.\r\n *\r\n * @param consumer the configuration consumer\r\n * @return the configured matcher\r\n */\r\n public static CookieMatcher cookieMatcher(final Consumer<CookieMatcher> consumer) {\r\n CookieMatcher cookieMatcher = new CookieMatcher();\r\n consumer.accept(cookieMatcher);\r\n return cookieMatcher;\r\n }\r\n\r\n /**\r\n * Applies a matcher for the specified cookie value. This is equivalent to calling <code>value(Matchers.equalTo('some value'))</code>.\r\n *\r\n * @param val the value string\r\n * @return a reference to the matcher being configured\r\n */\r\n public CookieMatcher value(final String val) {\r\n return value(equalTo(val));\r\n }\r\n\r\n /**\r\n * Applies the specified matcher to the cookie value.\r\n *\r\n * @param matcher the matcher to be used\r\n * @return a reference to the matcher being configured\r\n */\r\n public CookieMatcher value(final Matcher<String> matcher) {\r\n matchers.put(CookieField.VALUE, matcher);\r\n return this;\r\n }\r\n\r\n /**\r\n * Applies a matcher for the specified cookie comment value. This is equivalent to calling <code>comment(Matchers.equalTo('some value'))</code>.\r\n *\r\n * @param str the comment string\r\n * @return a reference to the matcher being configured\r\n */\r\n public CookieMatcher comment(final String str) {\r\n return comment(equalTo(str));\r\n }\r\n\r\n /**\r\n * Applies the specified matcher to the cookie comment.\r\n *\r\n * @param matcher the matcher to be used\r\n * @return a reference to the matcher being configured\r\n */\r\n public CookieMatcher comment(final Matcher<String> matcher) {\r\n matchers.put(CookieField.COMMENT, matcher);\r\n return this;\r\n }\r\n\r\n /**\r\n * Applies a matcher for the specified cookie domain value. This is equivalent to calling <code>domain(Matchers.equalTo('some value'))</code>.\r\n *\r\n * @param str the domain string\r\n * @return a reference to the matcher being configured\r\n */\r\n public CookieMatcher domain(final String str) {\r\n return domain(equalTo(str));\r\n }\r\n\r\n /**\r\n * Applies the specified matcher to the cookie domain.\r\n *\r\n * @param matcher the matcher to be used\r\n * @return a reference to the matcher being configured\r\n */\r\n public CookieMatcher domain(final Matcher<String> matcher) {\r\n matchers.put(CookieField.DOMAIN, matcher);\r\n return this;\r\n }\r\n\r\n /**\r\n * Applies a matcher for the specified cookie path value. This is equivalent to calling <code>path(Matchers.equalTo('some value'))</code>.\r\n *\r\n * @param str the path string\r\n * @return a reference to the matcher being configured\r\n */\r\n public CookieMatcher path(final String str) {\r\n return path(equalTo(str));\r\n }\r\n\r\n /**\r\n * Applies the specified matcher to the cookie path.\r\n *\r\n * @param matcher the matcher to be used\r\n * @return a reference to the matcher being configured\r\n */\r\n public CookieMatcher path(final Matcher<String> matcher) {\r\n matchers.put(CookieField.PATH, matcher);\r\n return this;\r\n }\r\n\r\n /**\r\n * Applies a matcher for the specified cookie version value. This is equivalent to calling <code>version(Matchers.equalTo(1))</code>.\r\n *\r\n * @param vers the version string\r\n * @return a reference to the matcher being configured\r\n */\r\n public CookieMatcher version(final int vers) {\r\n return version(equalTo(vers));\r\n }\r\n\r\n /**\r\n * Applies the specified matcher to the cookie version.\r\n *\r\n * @param matcher the matcher to be used\r\n * @return a reference to the matcher being configured\r\n */\r\n public CookieMatcher version(final Matcher<Integer> matcher) {\r\n matchers.put(CookieField.VERSION, matcher);\r\n return this;\r\n }\r\n\r\n /**\r\n * Applies a matcher for the specified cookie http-only value.\r\n *\r\n * @param httpOnly the httpOnly state\r\n * @return a reference to the matcher being configured\r\n */\r\n public CookieMatcher httpOnly(final boolean httpOnly) {\r\n matchers.put(CookieField.HTTP_ONLY, equalTo(httpOnly));\r\n return this;\r\n }\r\n\r\n /**\r\n * Applies a matcher for the specified cookie max-age value. This is equivalent to calling <code>maxAge(Matchers.equalTo(age))</code>.\r\n *\r\n * @param age the max-age value\r\n * @return a reference to the matcher being configured\r\n */\r\n public CookieMatcher maxAge(final int age) {\r\n return maxAge(equalTo(age));\r\n }\r\n\r\n /**\r\n * Applies the specified matcher to the cookie max-age value.\r\n *\r\n * @param matcher the matcher to be used\r\n * @return a reference to the matcher being configured\r\n */\r\n public CookieMatcher maxAge(final Matcher<Integer> matcher) {\r\n matchers.put(CookieField.MAX_AGE, matcher);\r\n return this;\r\n }\r\n\r\n /**\r\n * Applies a matcher for the specified cookie secure value.\r\n *\r\n * @param secure the secure state\r\n * @return a reference to the matcher being configured\r\n */\r\n public CookieMatcher secure(final boolean secure) {\r\n matchers.put(CookieField.SECURE, equalTo(secure));\r\n return this;\r\n }\r\n\r\n @Override\r\n public boolean matches(final Object item) {\r\n if (!(item instanceof Cookie)) {\r\n return false;\r\n }\r\n\r\n val cookie = (Cookie) item;\r\n\r\n return matchers.entrySet().stream().allMatch(entry -> {\r\n val matcher = entry.getValue();\r\n\r\n return switch (entry.getKey()) {\r\n case VALUE -> matcher.matches(cookie.getValue());\r\n case COMMENT -> matcher.matches(cookie.getComment());\r\n case DOMAIN -> matcher.matches(cookie.getDomain());\r\n case PATH -> matcher.matches(cookie.getPath());\r\n case MAX_AGE -> matcher.matches(cookie.getMaxAge());\r\n case HTTP_ONLY -> matcher.matches(cookie.isHttpOnly());\r\n case SECURE -> matcher.matches(cookie.isSecure());\r\n case VERSION -> matcher.matches(cookie.getVersion());\r\n };\r\n });\r\n }\r\n\r\n @Override\r\n public void describeTo(final Description description) {\r\n description.appendText(\"Cookie matching \");\r\n\r\n matchers.forEach((field, matcher) -> {\r\n description.appendText(field + \"(\");\r\n matcher.describeTo(description);\r\n description.appendText(\") \");\r\n });\r\n }\r\n\r\n private enum CookieField {\r\n VALUE, COMMENT, DOMAIN, PATH, MAX_AGE, HTTP_ONLY, SECURE, VERSION;\r\n }\r\n}\r",
"public class MockClientRequest implements ClientRequest {\r\n\r\n private HttpMethod method;\r\n private String protocol;\r\n private String path;\r\n private final Map<String, Deque<String>> queryParams = new LinkedHashMap<>();\r\n private final Map<String, Deque<String>> headers = new LinkedHashMap<>();\r\n private final Map<String, Deque<String>> bodyParameters = new LinkedHashMap<>();\r\n private Map<String, Cookie> cookies = new LinkedHashMap<>();\r\n private byte[] body;\r\n private int contentLength;\r\n private String characterEncoding;\r\n\r\n public MockClientRequest() {\r\n // nothing\r\n }\r\n\r\n public MockClientRequest(final HttpMethod method) {\r\n this.method = method;\r\n }\r\n\r\n public MockClientRequest(final HttpMethod method, final String path){\r\n this(method);\r\n setPath(path);\r\n }\r\n\r\n public MockClientRequest(final byte[] content){\r\n setBody(content);\r\n }\r\n\r\n public void setCookies(Map<String, Cookie> cookies) {\r\n this.cookies = cookies;\r\n }\r\n\r\n public void setHeaders(Map<String, Deque<String>> headers) {\r\n this.headers.clear();\r\n this.headers.putAll(headers);\r\n }\r\n\r\n @Override public HttpMethod getMethod() {\r\n return method;\r\n }\r\n\r\n @Override public String getProtocol() {\r\n return protocol;\r\n }\r\n\r\n @Override public String getPath() {\r\n return path;\r\n }\r\n\r\n @Override public Map<String, Deque<String>> getQueryParams() {\r\n return queryParams;\r\n }\r\n\r\n @Override public Map<String, Deque<String>> getHeaders() {\r\n return headers;\r\n }\r\n\r\n @Override public Map<String, Cookie> getCookies() {\r\n return cookies;\r\n }\r\n\r\n @Override public byte[] getBody() {\r\n return body;\r\n }\r\n\r\n @Override public Map<String, Deque<String>> getBodyParameters() {\r\n return bodyParameters;\r\n }\r\n\r\n public void setBodyParameters(final Map<String, Deque<String>> params) {\r\n bodyParameters.clear();\r\n bodyParameters.putAll(params);\r\n }\r\n\r\n @Override public long getContentLength() {\r\n return contentLength;\r\n }\r\n\r\n @Override public String getCharacterEncoding() {\r\n return characterEncoding;\r\n }\r\n\r\n @Override public String getContentType() {\r\n return headers.containsKey(CONTENT_TYPE_HEADER) ? headers.get(CONTENT_TYPE_HEADER).getFirst() : null;\r\n }\r\n\r\n public MockClientRequest header(final String name, final String value) {\r\n headers.computeIfAbsent(name, s -> new ArrayDeque<>()).add(value);\r\n return this;\r\n }\r\n\r\n public MockClientRequest query(final String name, final String... values) {\r\n final var params = queryParams.computeIfAbsent(name, s -> new ArrayDeque<>());\r\n\r\n if (values != null) {\r\n for (String value : values) {\r\n if (value != null) {\r\n params.add(value);\r\n }\r\n }\r\n }\r\n\r\n return this;\r\n }\r\n\r\n public void setContentType(String contentType) {\r\n header(CONTENT_TYPE_HEADER, contentType);\r\n }\r\n\r\n public void setMethod(HttpMethod method) {\r\n this.method = method;\r\n }\r\n\r\n public void setProtocol(String protocol) {\r\n this.protocol = protocol;\r\n }\r\n\r\n public void setPath(String path) {\r\n this.path = path;\r\n }\r\n\r\n public void setBody(byte[] body) {\r\n this.body = body;\r\n }\r\n\r\n public void setContentLength(int contentLength) {\r\n this.contentLength = contentLength;\r\n }\r\n\r\n public void setCharacterEncoding(String characterEncoding) {\r\n this.characterEncoding = characterEncoding;\r\n }\r\n\r\n public MockClientRequest cookie(String name, String value) {\r\n return cookie(name, value, null, null, null, 0, false, false, 0);\r\n }\r\n\r\n public MockClientRequest cookie(final String name, String value, String comment, String domain, String path, Integer maxAge, Boolean httpOnly, Boolean secure, Integer version) {\r\n cookies.put(name, new Cookie(value, comment, domain, path, version, httpOnly, maxAge, secure));\r\n return this;\r\n }\r\n}\r",
"public static final ContentType TEXT_PLAIN = new ContentType(\"text/plain\");\r",
"static Matcher<Iterable<? super String>> stringIterableMatcher(final Collection<Matcher<? super String>> matchers) {\r\n return new StringIterableMatcher(matchers);\r\n}\r"
] | import io.github.cjstehno.ersatz.cfg.HttpMethod;
import io.github.cjstehno.ersatz.encdec.DecoderChain;
import io.github.cjstehno.ersatz.encdec.Decoders;
import io.github.cjstehno.ersatz.encdec.RequestDecoders;
import io.github.cjstehno.ersatz.match.CookieMatcher;
import io.github.cjstehno.ersatz.server.MockClientRequest;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.MethodSource;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Stream;
import static io.github.cjstehno.ersatz.cfg.ContentType.TEXT_PLAIN;
import static io.github.cjstehno.ersatz.cfg.HttpMethod.GET;
import static io.github.cjstehno.ersatz.cfg.HttpMethod.HEAD;
import static io.github.cjstehno.ersatz.match.ErsatzMatchers.stringIterableMatcher;
import static org.hamcrest.Matchers.*;
import static org.hamcrest.core.IsIterableContaining.hasItem;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.params.provider.Arguments.arguments;
| /**
* Copyright (C) 2022 Christopher J. Stehno
*
* 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 io.github.cjstehno.ersatz.impl;
class RequestMatcherTest {
@ParameterizedTest @DisplayName("method") @MethodSource("methodProvider")
void method(final HttpMethod method, final boolean result) {
assertEquals(result, RequestMatcher.method(equalTo(HEAD)).matches(new MockClientRequest(method)));
}
private static Stream<Arguments> methodProvider() {
return Stream.of(
arguments(HEAD, true),
arguments(GET, false)
);
}
@ParameterizedTest @DisplayName("path")
@CsvSource({
"/something,true",
"/some,false"
})
void path(final String path, final boolean result) {
assertEquals(result, RequestMatcher.path(equalTo("/something")).matches(new MockClientRequest(GET, path)));
}
@ParameterizedTest @DisplayName("content-type") @MethodSource("contentTypeProvider")
void contentType(final MockClientRequest request, final boolean result) {
assertEquals(result, RequestMatcher.contentType(startsWith("application/")).matches(request));
}
private static Stream<Arguments> contentTypeProvider() {
final var factory = new Function<String, MockClientRequest>() {
@Override public MockClientRequest apply(String ctype) {
final var mcr = new MockClientRequest();
mcr.setContentType(ctype);
return mcr;
}
};
return Stream.of(
arguments(factory.apply("application/json"), true),
arguments(factory.apply("application/"), true),
arguments(new MockClientRequest(), false)
);
}
@ParameterizedTest @DisplayName("header") @MethodSource("headerProvider")
void header(final MockClientRequest request, final boolean result) {
assertEquals(result, RequestMatcher.header("foo", hasItem("bar")).matches(request));
}
private static Stream<Arguments> headerProvider() {
return Stream.of(
arguments(new MockClientRequest().header("foo", "bar"), true),
arguments(new MockClientRequest().header("one", "two"), false),
arguments(new MockClientRequest().header("Foo", "bar"), true),
arguments(new MockClientRequest().header("Foo", "Bar"), false),
arguments(new MockClientRequest(), false)
);
}
@ParameterizedTest @DisplayName("query") @MethodSource("queryProvider")
void query(final MockClientRequest request, final boolean result) {
assertEquals(
result,
RequestMatcher.query(
"name",
stringIterableMatcher(List.of(equalTo("alpha"), equalTo("blah")))
).matches(request)
);
}
private static Stream<Arguments> queryProvider() {
return Stream.of(
arguments(new MockClientRequest().query("name", "alpha", "blah"), true),
arguments(new MockClientRequest().query("name", "alpha"), false),
arguments(new MockClientRequest(), false)
);
}
@ParameterizedTest @DisplayName("param") @MethodSource("paramProvider")
void params(final MockClientRequest request, final boolean result) {
assertEquals(
result,
RequestMatcher.param(
"email",
stringIterableMatcher(List.of(containsString("@goomail.com")))
).matches(request)
);
}
private static Stream<Arguments> paramProvider() {
final var factory = new Function<Map<String, Deque<String>>, MockClientRequest>() {
@Override public MockClientRequest apply(Map<String, Deque<String>> map) {
final var mcr = new MockClientRequest();
mcr.setBodyParameters(map);
return mcr;
}
};
return Stream.of(
arguments(new MockClientRequest(), false),
arguments(factory.apply(Map.of(
"email", new ArrayDeque<>(List.of("[email protected]")),
"spam", new ArrayDeque<>(List.of("n"))
)), true),
arguments(factory.apply(Map.of(
"spam", new ArrayDeque<>(List.of("n"))
)), false)
);
}
@ParameterizedTest @DisplayName("cookie") @MethodSource("cookieProvider")
void cookie(final MockClientRequest request, final boolean result) {
assertEquals(result, RequestMatcher.cookie("id", new CookieMatcher().value(equalTo("asdf89s7g"))).matches(request));
}
private static Stream<Arguments> cookieProvider() {
return Stream.of(
arguments(new MockClientRequest().cookie("id", "asdf89s7g"), true),
arguments(new MockClientRequest().cookie("id", "assdfsdf"), false),
arguments(new MockClientRequest(), false)
);
}
@ParameterizedTest @DisplayName("body") @MethodSource("bodyProvider")
void body(final MockClientRequest request, final boolean result) {
| RequestDecoders decoders = RequestDecoders.decoders(d -> {
| 3 |
maruohon/worldutils | src/main/java/fi/dy/masa/worldutils/command/SubCommandBlockReplacePairs.java | [
"@Mod(modid = Reference.MOD_ID, name = Reference.MOD_NAME, version = Reference.MOD_VERSION, certificateFingerprint = Reference.FINGERPRINT,\n guiFactory = \"fi.dy.masa.worldutils.config.WorldUtilsGuiFactory\",\n updateJSON = \"https://raw.githubusercontent.com/maruohon/worldutils/master/update.json\",\n acceptableRemoteVersions = \"*\",\n acceptedMinecraftVersions = \"1.12\",\n dependencies = \"required-after:forge@[14.21.0.2373,);\")\npublic class WorldUtils\n{\n @Instance(Reference.MOD_ID)\n public static WorldUtils instance;\n\n @SidedProxy(clientSide = Reference.PROXY_CLASS_CLIENT, serverSide = Reference.PROXY_CLASS_SERVER)\n public static CommonProxy proxy;\n\n public static final Logger logger = LogManager.getLogger(Reference.MOD_ID);\n public static String configDirPath;\n\n private static boolean modLoadedNeid;\n\n @EventHandler\n public void preInit(FMLPreInitializationEvent event)\n {\n Configs.loadConfigsFromFile(event.getSuggestedConfigurationFile());\n configDirPath = new File(event.getModConfigurationDirectory(), Reference.MOD_ID).getAbsolutePath();\n\n PacketHandler.init(); // Initialize network stuff\n\n proxy.registerKeyBindings();\n proxy.registerEventHandlers();\n modLoadedNeid = Loader.isModLoaded(\"neid\");\n }\n\n @EventHandler\n public void serverStarting(FMLServerStartingEvent event)\n {\n event.registerServerCommand(new CommandWorldUtils());\n }\n\n @Mod.EventHandler\n public void onFingerPrintViolation(FMLFingerprintViolationEvent event)\n {\n // Not running in a dev environment\n if (event.isDirectory() == false)\n {\n logger.warn(\"*********************************************************************************************\");\n logger.warn(\"***** WARNING *****\");\n logger.warn(\"***** *****\");\n logger.warn(\"***** The signature of the mod file '{}' does not match the expected fingerprint! *****\", event.getSource().getName());\n logger.warn(\"***** This might mean that the mod file has been tampered with! *****\");\n logger.warn(\"***** If you did not download the mod {} directly from Curse/CurseForge, *****\", Reference.MOD_NAME);\n logger.warn(\"***** or using one of the well known launchers, and you did not *****\");\n logger.warn(\"***** modify the mod file at all yourself, then it's possible, *****\");\n logger.warn(\"***** that it may contain malware or other unwanted things! *****\");\n logger.warn(\"*********************************************************************************************\");\n }\n }\n\n public static boolean isModLoadedNEID()\n {\n return modLoadedNeid;\n }\n}",
"public class BlockTools\n{\n public enum LoadedType\n {\n ALL,\n UNLOADED,\n LOADED;\n }\n\n public static void replaceBlocks(int dimension, String replacement, List<String> blockNames, List<IBlockState> blockStates,\n boolean keepListedBlocks, LoadedType loaded, ICommandSender sender) throws CommandException\n {\n BlockReplacerSet replacer = new BlockReplacerSet(replacement, keepListedBlocks, loaded);\n replacer.addBlocksFromBlockStates(blockStates);\n replacer.addBlocksFromStrings(blockNames);\n\n if (keepListedBlocks)\n {\n replacer.addBlocksFromBlockStates(Lists.newArrayList(Blocks.AIR.getDefaultState()));\n }\n\n TaskScheduler.getInstance().scheduleTask(new TaskWorldProcessor(dimension, replacer, sender, 50), 1);\n }\n\n public static void replaceBlocksInPairs(int dimension, List<Pair<String, String>> blockPairs,\n LoadedType loaded, ICommandSender sender) throws CommandException\n {\n BlockReplacerPairs replacer = new BlockReplacerPairs(loaded);\n replacer.addBlockPairs(blockPairs);\n TaskScheduler.getInstance().scheduleTask(new TaskWorldProcessor(dimension, replacer, sender, 50), 1);\n }\n\n public static boolean setBlock(int dimension, BlockPos blockPos, BlockData blockData) throws CommandException\n {\n Region region = getRegion(dimension, blockPos);\n\n if (region.getRegionFile() == null)\n {\n CommandWorldUtils.throwCommand(\"worldutils.commands.error.setblock.region_not_found\");\n }\n\n final int chunkX = blockPos.getX() >> 4;\n final int chunkZ = blockPos.getZ() >> 4;\n NBTTagCompound chunkNBT = getChunkNBT(region, chunkX, chunkZ);\n\n if (chunkNBT != null && chunkNBT.hasKey(\"Level\", Constants.NBT.TAG_COMPOUND))\n {\n if (setBlock(chunkNBT, blockPos, blockData))\n {\n saveChunkNBT(region, chunkX, chunkZ, chunkNBT);\n\n return true;\n }\n }\n else\n {\n CommandWorldUtils.throwCommand(\"worldutils.commands.error.setblock.chunk_not_found\");\n }\n\n return false;\n }\n\n public static boolean inspectBlock(int dimension, BlockPos blockPos, boolean dumpToFile, ICommandSender sender) throws CommandException\n {\n Region region = getRegion(dimension, blockPos);\n\n if (region.getRegionFile() == null)\n {\n CommandWorldUtils.throwCommand(\"worldutils.commands.error.setblock.region_not_found\");\n }\n\n final int chunkX = blockPos.getX() >> 4;\n final int chunkZ = blockPos.getZ() >> 4;\n NBTTagCompound chunkNBT = getChunkNBT(region, chunkX, chunkZ);\n\n if (chunkNBT != null && chunkNBT.hasKey(\"Level\", Constants.NBT.TAG_COMPOUND))\n {\n int modified = getChunkModificationTimestamp(region.getAbsolutePath(), chunkX, chunkZ);\n\n if (inspectBlock(chunkNBT, blockPos, dumpToFile, sender, modified))\n {\n return true;\n }\n }\n else\n {\n CommandWorldUtils.throwCommand(\"worldutils.commands.error.setblock.chunk_not_found\");\n }\n\n return false;\n }\n\n private static int getChunkModificationTimestamp(String regionFilePath, int chunkX, int chunkZ)\n {\n try\n {\n RandomAccessFile raf = new RandomAccessFile(regionFilePath, \"r\");\n raf.seek((long)(4096 + ((chunkX & 0x1F) + (chunkZ & 0x1F) * 32) * 4));\n int timestamp = raf.readInt();\n raf.close();\n\n return timestamp;\n }\n catch (Exception e)\n {\n WorldUtils.logger.warn(\"BlockTools#getChunkModificationTimestamp(): Failed to read chunk\" +\n \" modification timestamp from region file '{}'\", regionFilePath);\n }\n\n return 0;\n }\n\n @Nullable\n private static Region getRegion(int dimension, BlockPos blockPos) throws CommandException\n {\n File worldDir = FileUtils.getWorldSaveLocation(dimension);\n\n if (worldDir == null)\n {\n CommandWorldUtils.throwCommand(\"worldutils.commands.error.invaliddimension\", Integer.valueOf(dimension));\n }\n\n return Region.fromRegionCoords(worldDir, blockPos.getX() >> 9, blockPos.getZ() >> 9, false);\n }\n\n @Nullable\n private static NBTTagCompound getChunkNBT(Region region, int chunkX, int chunkZ)\n {\n NBTTagCompound chunkNBT;\n DataInputStream dataIn = region.getRegionFile().getChunkDataInputStream(chunkX & 0x1F, chunkZ & 0x1F);\n\n if (dataIn == null)\n {\n WorldUtils.logger.warn(\"BlockTools#getChunkNBT(): Failed to get chunk data input stream for chunk ({}, {}) from file '{}'\",\n chunkX, chunkZ, region.getAbsolutePath());\n return null;\n }\n\n try\n {\n chunkNBT = CompressedStreamTools.read(dataIn);\n dataIn.close();\n\n return chunkNBT;\n }\n catch (IOException e)\n {\n WorldUtils.logger.warn(\"BlockTools#getChunkNBT(): Failed to read chunk NBT data for chunk ({}, {}) from file '{}'\",\n chunkX, chunkZ, region.getAbsolutePath(), e);\n }\n\n return null;\n }\n\n private static void saveChunkNBT(Region region, int chunkX, int chunkZ, NBTTagCompound chunkNBT)\n {\n if (chunkNBT != null && chunkNBT.hasKey(\"Level\", Constants.NBT.TAG_COMPOUND))\n {\n try\n {\n DataOutputStream dataOut = region.getRegionFile().getChunkDataOutputStream(chunkX & 0x1F, chunkZ & 0x1F);\n\n if (dataOut == null)\n {\n WorldUtils.logger.warn(\"BlockTools#saveChunkNBT(): Failed to get chunk data output stream for chunk [{}, {}] in region file '{}'\",\n chunkX, chunkZ, region.getAbsolutePath());\n return;\n }\n\n CompressedStreamTools.write(chunkNBT, dataOut);\n dataOut.close();\n }\n catch (Exception e)\n {\n WorldUtils.logger.warn(\"BlockTools#saveChunkNBT(): Failed to write chunk data for chunk [{}, {}] in region file '{}' ({})\",\n chunkX, chunkZ, region.getAbsolutePath(), e.getMessage());\n }\n }\n }\n\n private static boolean setBlock(NBTTagCompound chunkNBT, BlockPos pos, BlockData blockData) throws CommandException\n {\n if (chunkNBT != null && chunkNBT.hasKey(\"Level\", Constants.NBT.TAG_COMPOUND))\n {\n NBTTagCompound level = chunkNBT.getCompoundTag(\"Level\");\n NBTTagList sectionsList = level.getTagList(\"Sections\", Constants.NBT.TAG_COMPOUND);\n final int yPos = pos.getY() >> 4;\n\n if (sectionsList.tagCount() > yPos)\n {\n final int stateId = blockData.getBlockStateId();\n NBTTagCompound sectionTag = sectionsList.getCompoundTagAt(yPos);\n byte[] blockArray = sectionTag.getByteArray(\"Blocks\");\n NibbleArray metaNibble = new NibbleArray(sectionTag.getByteArray(\"Data\"));\n NibbleArray addNibble = null;\n final byte blockId = (byte) (stateId & 0xFF);\n final byte add = (byte) ((stateId >>> 8) & 0xF);\n final byte meta = (byte) ((stateId >>> 12) & 0xF);\n final int x = pos.getX() & 0xF;\n final int y = pos.getY() & 0xF;\n final int z = pos.getZ() & 0xF;\n\n blockArray[y << 8 | z << 4 | x] = blockId;\n metaNibble.set(x, y, z, meta);\n\n if (sectionTag.hasKey(\"Add\", Constants.NBT.TAG_BYTE_ARRAY))\n {\n addNibble = new NibbleArray(sectionTag.getByteArray(\"Add\"));\n addNibble.set(x, y, z, add);\n }\n // No existing Add array, but one is needed because of the new block\n else if (add != 0)\n {\n addNibble = new NibbleArray();\n addNibble.set(x, y, z, add);\n sectionTag.setByteArray(\"Add\", addNibble.getData());\n }\n\n removeTileEntityAndTileTick(level, pos);\n\n return true;\n }\n else\n {\n Integer sec = Integer.valueOf(sectionsList.tagCount());\n Integer maxY = sec * 16 - 1;\n CommandWorldUtils.throwCommand(\"worldutils.commands.error.chunk_section_doesnt_exist\", sec, maxY);\n }\n }\n\n return false;\n }\n\n private static boolean inspectBlock(NBTTagCompound chunkNBT, BlockPos pos, boolean dumpToFile,\n ICommandSender sender, int modified) throws CommandException\n {\n if (chunkNBT != null && chunkNBT.hasKey(\"Level\", Constants.NBT.TAG_COMPOUND))\n {\n NBTTagCompound level = chunkNBT.getCompoundTag(\"Level\");\n NBTTagList sectionsList = level.getTagList(\"Sections\", Constants.NBT.TAG_COMPOUND);\n final int yPos = pos.getY() >> 4;\n\n if (sectionsList.tagCount() > yPos)\n {\n NBTTagCompound sectionTag = sectionsList.getCompoundTagAt(yPos);\n byte[] blockArray = sectionTag.getByteArray(\"Blocks\");\n NibbleArray metaNibble = new NibbleArray(sectionTag.getByteArray(\"Data\"));\n\n final int x = pos.getX() & 0xF;\n final int y = pos.getY() & 0xF;\n final int z = pos.getZ() & 0xF;\n\n final int meta = metaNibble.get(x, y, z);\n int blockId = ((int) blockArray[y << 8 | z << 4 | x]) & 0xFF;\n\n if (sectionTag.hasKey(\"Add\", Constants.NBT.TAG_BYTE_ARRAY))\n {\n NibbleArray addNibble = new NibbleArray(sectionTag.getByteArray(\"Add\"));\n blockId |= addNibble.get(x, y, z) << 8;\n }\n\n NBTTagCompound tileNBT = getTileNBT(level, pos);\n BlockInfo.outputBlockInfo(blockId, meta, tileNBT, dumpToFile, sender, modified);\n\n return true;\n }\n else\n {\n Integer sec = Integer.valueOf(sectionsList.tagCount());\n Integer maxY = sec * 16 - 1;\n CommandWorldUtils.throwCommand(\"worldutils.commands.error.chunk_section_doesnt_exist\", sec, maxY);\n }\n }\n\n return false;\n }\n\n @Nullable\n private static NBTTagCompound getTileNBT(NBTTagCompound level, BlockPos pos)\n {\n NBTTagList list = level.getTagList(\"TileEntities\", Constants.NBT.TAG_COMPOUND);\n\n if (list != null)\n {\n final int size = list.tagCount();\n final int x = pos.getX();\n final int y = pos.getY();\n final int z = pos.getZ();\n\n for (int i = 0; i < size; i++)\n {\n NBTTagCompound tag = list.getCompoundTagAt(i);\n\n if (tag.getInteger(\"x\") == x && tag.getInteger(\"y\") == y && tag.getInteger(\"z\") == z)\n {\n return list.getCompoundTagAt(i);\n }\n }\n }\n\n return null;\n }\n\n private static void removeTileEntityAndTileTick(NBTTagCompound level, BlockPos pos)\n {\n NBTTagList list = level.getTagList(\"TileEntities\", Constants.NBT.TAG_COMPOUND);\n\n if (list != null)\n {\n removeTileEntry(list, pos);\n }\n\n list = level.getTagList(\"TileTicks\", Constants.NBT.TAG_COMPOUND);\n\n if (list != null)\n {\n removeTileEntry(list, pos);\n }\n }\n\n private static void removeTileEntry(NBTTagList list, BlockPos pos)\n {\n final int size = list.tagCount();\n final int x = pos.getX();\n final int y = pos.getY();\n final int z = pos.getZ();\n\n for (int i = 0; i < size; i++)\n {\n NBTTagCompound tag = list.getCompoundTagAt(i);\n\n if (tag.getInteger(\"x\") == x && tag.getInteger(\"y\") == y && tag.getInteger(\"z\") == z)\n {\n list.removeTag(i);\n break;\n }\n }\n }\n}",
"public enum LoadedType\n{\n ALL,\n UNLOADED,\n LOADED;\n}",
"public class TaskScheduler\n{\n private static TaskScheduler instance;\n private List<ITask> tasks = new ArrayList<ITask>();\n private List<Timer> timers = new ArrayList<Timer>();\n private List<Pair<ITask, Integer>> tasksToAdd = new ArrayList<Pair<ITask, Integer>>();\n\n private TaskScheduler()\n {\n }\n\n public static TaskScheduler getInstance()\n {\n if (instance == null)\n {\n instance = new TaskScheduler();\n }\n\n return instance;\n }\n\n public void scheduleTask(ITask task, int interval)\n {\n this.tasksToAdd.add(Pair.of(task, interval));\n }\n\n public void runTasks()\n {\n Iterator<ITask> taskIter = this.tasks.iterator();\n Iterator<Timer> timerIter = this.timers.iterator();\n\n while (taskIter.hasNext())\n {\n boolean finished = false;\n ITask task = taskIter.next();\n Timer timer = timerIter.next();\n\n if (timer.tick())\n {\n if (task.canExecute())\n {\n finished = task.execute();\n }\n else\n {\n finished = true;\n }\n }\n\n if (finished)\n {\n task.stop();\n taskIter.remove();\n timerIter.remove();\n }\n }\n\n this.addNewTasks();\n }\n\n private void addNewTasks()\n {\n for (Pair<ITask, Integer> pair : this.tasksToAdd)\n {\n ITask task = pair.getLeft();\n task.init();\n\n this.tasks.add(task);\n this.timers.add(new Timer(pair.getRight()));\n }\n\n this.tasksToAdd.clear();\n }\n\n public boolean hasTasks()\n {\n return this.tasks.isEmpty() == false || this.tasksToAdd.isEmpty() == false;\n }\n\n public boolean hasTask(Class <? extends ITask> clazz)\n {\n for (ITask task : this.tasks)\n {\n if (clazz.equals(task.getClass()))\n {\n return true;\n }\n }\n\n return false;\n }\n\n public boolean removeTask(Class <? extends ITask> clazz)\n {\n boolean removed = false;\n Iterator<ITask> taskIter = this.tasks.iterator();\n Iterator<Timer> timerIter = this.timers.iterator();\n\n while (taskIter.hasNext())\n {\n ITask task = taskIter.next();\n timerIter.next();\n\n if (clazz.equals(task.getClass()))\n {\n task.stop();\n taskIter.remove();\n timerIter.remove();\n removed = true;\n }\n }\n\n return removed;\n }\n\n public void clearTasks()\n {\n }\n\n private static class Timer\n {\n public int interval;\n public int counter;\n\n public Timer(int interval)\n {\n this.interval = interval;\n this.counter = interval;\n }\n\n public boolean tick()\n {\n if (--this.counter <= 0)\n {\n this.reset();\n return true;\n }\n\n return false;\n }\n\n public void reset()\n {\n this.counter = this.interval;\n }\n }\n}",
"public class TaskWorldProcessor extends TaskRegionDirectoryProcessor\n{\n private final int dimension;\n\n public TaskWorldProcessor(int dimension, IWorldDataHandler handler, ICommandSender sender, int maxTickTime) throws CommandException\n {\n super(FileUtils.getRegionDirectory(dimension), handler, sender, maxTickTime);\n\n this.dimension = dimension;\n }\n\n @Override\n protected void setWorldHandlerChunkProvider()\n {\n WorldServer world = DimensionManager.getWorld(this.dimension);\n\n if (world != null)\n {\n this.getWorldHandler().setChunkProvider(world.getChunkProvider());\n }\n else\n {\n this.getWorldHandler().setChunkProvider(null);\n }\n }\n}",
"public class BlockData\n{\n private DataType type;\n private int id;\n private int meta;\n private int blockStateId;\n private int[] blockStateIds = new int[0];\n private String name = \"\";\n private List<Pair<String, String>> props = new ArrayList<Pair<String, String>>();\n\n public BlockData(int id)\n {\n this.type = DataType.ID;\n this.id = id;\n this.setNumericValues();\n }\n\n public BlockData(int id, int meta)\n {\n this.type = DataType.ID_META;\n this.id = id;\n this.meta = meta;\n this.setNumericValues();\n }\n\n public BlockData(String name)\n {\n this.type = DataType.NAME;\n this.name = name;\n this.setNumericValues();\n }\n\n public BlockData(String name, int meta)\n {\n this.type = DataType.NAME_META;\n this.name = name;\n this.meta = meta;\n this.setNumericValues();\n }\n\n public BlockData(String name, List<Pair<String, String>> props)\n {\n this.type = DataType.NAME_PROPS;\n this.name = name;\n this.props.addAll(props);\n this.setNumericValues();\n }\n\n public DataType getType()\n {\n return this.type;\n }\n\n public String getName()\n {\n return this.name;\n }\n\n public int getId()\n {\n return this.id;\n }\n\n public int getMeta()\n {\n return this.meta;\n }\n\n public int getBlockStateId()\n {\n return this.blockStateId;\n }\n\n public int[] getBlockStateIds()\n {\n return this.blockStateIds;\n }\n\n public boolean ignoreMeta()\n {\n return this.type == DataType.ID || this.type == DataType.NAME;\n }\n\n public boolean isValid()\n {\n final boolean neid = WorldUtils.isModLoadedNEID();\n final int maxId = (neid ? (1 << 16) : (1 << 12)) - 1;\n\n switch (this.type)\n {\n case ID:\n return this.id >= 0 && this.id <= maxId;\n\n case ID_META:\n return this.id >= 0 && this.id <= maxId && this.meta >= 0 && this.meta < 16;\n\n case NAME:\n return Block.REGISTRY.containsKey(new ResourceLocation(this.name));\n\n case NAME_META:\n return Block.REGISTRY.containsKey(new ResourceLocation(this.name)) && this.meta >= 0 && this.meta < 16;\n\n case NAME_PROPS:\n if (Block.REGISTRY.containsKey(new ResourceLocation(this.name)) == false)\n {\n return false;\n }\n\n Block block = Block.REGISTRY.getObject(new ResourceLocation(this.name));\n\n for (Pair<String, String> pair : this.props)\n {\n IProperty<?> prop = block.getBlockState().getProperty(pair.getLeft());\n\n if (prop == null || prop.parseValue(pair.getRight()).isPresent() == false)\n {\n return false;\n }\n }\n\n return true;\n }\n\n return false;\n }\n\n private void setNumericValues()\n {\n if (this.isValid())\n {\n switch (this.type)\n {\n case NAME:\n this.id = Block.getIdFromBlock(Block.REGISTRY.getObject(new ResourceLocation(this.name)));\n break;\n\n case NAME_META:\n this.id = Block.getIdFromBlock(Block.REGISTRY.getObject(new ResourceLocation(this.name)));\n break;\n\n case NAME_PROPS:\n Block block = Block.REGISTRY.getObject(new ResourceLocation(this.name));\n IBlockState state = block.getDefaultState();\n\n for (Pair<String, String> pair : this.props)\n {\n IProperty<?> prop = block.getBlockState().getProperty(pair.getLeft());\n\n if (prop != null)\n {\n state = setPropertyValueFromString(state, prop, pair.getRight());\n }\n }\n\n final boolean neid = WorldUtils.isModLoadedNEID();\n final int metaShift = neid ? 16 : 12;\n final int mask = neid ? 0xFFFF : 0xFFF;\n int stateId = Block.getStateId(state);\n this.id = stateId & mask;\n this.meta = (stateId >> metaShift) & 0xF;\n\n break;\n\n default:\n }\n\n this.setBlockstateIds();\n }\n }\n\n private void setBlockstateIds()\n {\n if (this.isValid())\n {\n final boolean neid = WorldUtils.isModLoadedNEID();\n final int metaShift = neid ? 16 : 12;\n\n this.blockStateId = (this.meta << metaShift) | this.id;\n\n if (this.ignoreMeta())\n {\n int[] ids = new int[16];\n\n for (int i = 0; i < 16; i++)\n {\n ids[i] = (i << metaShift) | this.id;\n }\n\n this.blockStateIds = ids;\n }\n else\n {\n this.blockStateIds = new int[] { this.blockStateId };\n }\n }\n }\n\n @Override\n public String toString()\n {\n if (this.type == DataType.ID)\n {\n return \"BlockData:{ type=\" + this.type + \", id=\" + this.id + \" }\";\n }\n else if (this.type == DataType.ID_META)\n {\n return \"BlockData:{ type=\" + this.type + \", id=\" + this.id + \", meta=\" + this.meta + \" }\";\n }\n else if (this.type == DataType.NAME)\n {\n return \"BlockData:{ type=\" + this.type + \", name=\" + this.name + \", id=\" + this.id + \" }\";\n }\n else if (this.type == DataType.NAME_META)\n {\n return \"BlockData:{ type=\" + this.type + \", name=\" + this.name + \", meta=\" + this.meta + \", id=\" + this.id + \" }\";\n }\n else if (this.type == DataType.NAME_PROPS)\n {\n StringBuilder propStr = new StringBuilder(128);\n for (Pair<String, String> pair : this.props) { propStr.append(pair.getLeft()).append(\"=\").append(pair.getRight()).append(\",\"); }\n if (propStr.length() > 0) { propStr.deleteCharAt(propStr.length() - 1); }\n return \"BlockData:{ type=\" + this.type + \", name=\" + this.name +\n \", props=[\" + propStr.toString() + \"], id=\" + this.id + \", meta=\" + this.meta + \" }\";\n }\n else\n {\n return \"BlockData:{type=INVALID}\";\n }\n }\n\n public static BlockData parseBlockTypeFromString(String str)\n {\n try\n {\n Pattern patternId = Pattern.compile(\"(?<id>[0-9]+)\");\n Pattern patternIdMeta = Pattern.compile(\"(?<id>[0-9]+)[@:]{1}(?<meta>[0-9]+)\");\n Pattern patternName = Pattern.compile(\"(?<name>([a-z0-9_]+:)?[a-z0-9\\\\._ ]+)\");\n Pattern patternNameMeta = Pattern.compile(\"(?<name>([a-z0-9_]+:)?[a-z0-9\\\\._ ]+)[@:]{1}(?<meta>[0-9]+)\");\n Pattern patternNameProps = Pattern.compile(\"(?<name>([a-z0-9_]+:)?[a-z0-9\\\\._ ]+)\\\\[(?<props>[a-z0-9_]+=[a-z0-9_]+(,[a-z0-9_]+=[a-z0-9_]+)*)\\\\]\");\n\n Matcher matcherId = patternId.matcher(str);\n if (matcherId.matches())\n {\n //System.out.printf(\"Type.ID - id: %d\\n\", Integer.parseInt(matcherId.group(\"id\")));\n return new BlockData(Integer.parseInt(matcherId.group(\"id\")));\n }\n\n Matcher matcherIdMeta = patternIdMeta.matcher(str);\n if (matcherIdMeta.matches())\n {\n // id@meta\n //System.out.printf(\"Type.ID_META - id: %d, meta: %d\\n\",\n // Integer.parseInt(matcherIdMeta.group(\"id\")), Integer.parseInt(matcherIdMeta.group(\"meta\")));\n return new BlockData(Integer.parseInt(matcherIdMeta.group(\"id\")), Integer.parseInt(matcherIdMeta.group(\"meta\")));\n }\n\n Matcher matcherName = patternName.matcher(str);\n if (matcherName.matches())\n {\n //System.out.printf(\"Type.NAME - name: %s\\n\", matcherName.group(\"name\"));\n return new BlockData(matcherName.group(\"name\"));\n }\n\n Matcher matcherNameMeta = patternNameMeta.matcher(str);\n if (matcherNameMeta.matches())\n {\n // name@meta\n //System.out.printf(\"Type.NAME_META - name: %s, meta: %d\\n\",\n // matcherNameMeta.group(\"name\"), Integer.parseInt(matcherNameMeta.group(\"meta\")));\n return new BlockData(matcherNameMeta.group(\"name\"), Integer.parseInt(matcherNameMeta.group(\"meta\")));\n }\n\n Matcher matcherNameProps = patternNameProps.matcher(str);\n if (matcherNameProps.matches())\n {\n // name[props]\n String name = matcherNameProps.group(\"name\");\n String propStr = matcherNameProps.group(\"props\");\n String[] propParts = propStr.split(\",\");\n Pattern patternProp = Pattern.compile(\"(?<prop>[a-zA-Z0-9\\\\._-]+)=(?<value>[a-zA-Z0-9\\\\._-]+)\");\n List<Pair<String, String>> props = new ArrayList<Pair<String, String>>();\n\n for (int i = 0; i < propParts.length; i++)\n {\n Matcher matcherProp = patternProp.matcher(propParts[i]);\n\n if (matcherProp.matches())\n {\n props.add(Pair.of(matcherProp.group(\"prop\"), matcherProp.group(\"value\")));\n }\n else\n {\n WorldUtils.logger.warn(\"Invalid block property '{}'\", propParts[i]);\n }\n }\n\n Collections.sort(props); // the properties need to be in alphabetical order\n\n //System.out.printf(\"Type.NAME_PROPS - name: %s, props: %s (propStr: %s)\\n\", name, String.join(\",\", props), propStr);\n return new BlockData(name, props);\n }\n }\n catch (PatternSyntaxException e)\n {\n WorldUtils.logger.warn(\"Invalid regex pattern in parseBlockTypeFromString()\", e);\n }\n catch (Exception e)\n {\n WorldUtils.logger.warn(\"Failed to parse block type in parseBlockTypeFromString()\", e);\n }\n\n return null;\n }\n\n public static <T extends Comparable<T>> IBlockState setPropertyValueFromString(IBlockState state, IProperty<T> prop, String valueStr)\n {\n return state.withProperty(prop, prop.parseValue(valueStr).get());\n }\n\n public enum DataType\n {\n ID,\n ID_META,\n NAME,\n NAME_META,\n NAME_PROPS;\n }\n\n @Override\n public int hashCode()\n {\n final int prime = 31;\n int result = 1;\n result = prime * result + id;\n result = prime * result + meta;\n result = prime * result + ((type == null) ? 0 : type.hashCode());\n return result;\n }\n\n @Override\n public boolean equals(Object obj)\n {\n if (this == obj)\n return true;\n if (obj == null)\n return false;\n if (getClass() != obj.getClass())\n return false;\n BlockData other = (BlockData) obj;\n if (id != other.id)\n return false;\n if (meta != other.meta)\n return false;\n if (type != other.type)\n return false;\n return true;\n }\n}",
"public class BlockUtils\n{\n public static List<String> getAllBlockNames()\n {\n List<String> names = new ArrayList<String>();\n\n for (ResourceLocation rl : Block.REGISTRY.getKeys())\n {\n names.add(rl.toString());\n }\n\n return names;\n }\n\n public static List<IBlockState> getAllBlockStatesInMod(String modId)\n {\n List<IBlockState> list = new ArrayList<IBlockState>();\n\n for (ResourceLocation rl : Block.REGISTRY.getKeys())\n {\n if (rl.getNamespace().equals(modId))\n {\n Block block = Block.REGISTRY.getObject(rl);\n list.addAll(block.getBlockState().getValidStates());\n }\n }\n\n return list;\n }\n\n public static List<String> getAllBlockNamesInMod(String modId)\n {\n List<String> list = new ArrayList<String>();\n\n for (ResourceLocation rl : Block.REGISTRY.getKeys())\n {\n if (rl.getNamespace().equals(modId))\n {\n list.add(rl.toString());\n }\n }\n\n return list;\n }\n}"
] | import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.annotation.Nullable;
import org.apache.commons.lang3.tuple.Pair;
import net.minecraft.command.CommandBase;
import net.minecraft.command.CommandException;
import net.minecraft.command.ICommandSender;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.TextComponentString;
import fi.dy.masa.worldutils.WorldUtils;
import fi.dy.masa.worldutils.data.BlockTools;
import fi.dy.masa.worldutils.data.BlockTools.LoadedType;
import fi.dy.masa.worldutils.event.tasks.TaskScheduler;
import fi.dy.masa.worldutils.event.tasks.TaskWorldProcessor;
import fi.dy.masa.worldutils.util.BlockData;
import fi.dy.masa.worldutils.util.BlockUtils; | package fi.dy.masa.worldutils.command;
public class SubCommandBlockReplacePairs extends SubCommand
{
private static List<Pair<String, String>> blockPairs = new ArrayList<Pair<String, String>>();
private String preparedFrom = EMPTY_STRING;
private String preparedTo = EMPTY_STRING;
public SubCommandBlockReplacePairs(CommandWorldUtils baseCommand)
{
super(baseCommand);
this.subSubCommands.add("add");
this.subSubCommands.add("add-prepared");
this.subSubCommands.add("clear");
this.subSubCommands.add("execute-all-chunks");
this.subSubCommands.add("execute-loaded-chunks");
this.subSubCommands.add("execute-unloaded-chunks");
this.subSubCommands.add("list");
this.subSubCommands.add("prepare-from");
this.subSubCommands.add("prepare-to");
this.subSubCommands.add("remove");
this.subSubCommands.add("remove-with-spaces");
this.subSubCommands.add("stoptask");
}
@Override
public String getName()
{
return "blockreplacepairs";
}
@Override
public void printHelpGeneric(ICommandSender sender)
{
this.sendMessage(sender, "worldutils.commands.help.generic.runhelpforallcommands", this.getUsageStringCommon() + " help");
}
@Override
public void printFullHelp(ICommandSender sender, String[] args)
{
sender.sendMessage(new TextComponentString(this.getUsageStringCommon() + " add <block1 | id1>[@meta1] <block2 | id2>[@meta2] Ex: minecraft:ice minecraft:wool@5"));
sender.sendMessage(new TextComponentString(this.getUsageStringCommon() + " add <block1[prop1=val1,prop2=val2]> <block2[prop1=val1,prop2=val2]> Ex: minecraft:stone[variant=granite]"));
sender.sendMessage(new TextComponentString(this.getUsageStringCommon() + " add-prepared (adds the prepared space-containing names)"));
sender.sendMessage(new TextComponentString(this.getUsageStringCommon() + " clear"));
sender.sendMessage(new TextComponentString(this.getUsageStringCommon() + " execute-all-chunks [dimension id]"));
sender.sendMessage(new TextComponentString(this.getUsageStringCommon() + " execute-loaded-chunks [dimension id]"));
sender.sendMessage(new TextComponentString(this.getUsageStringCommon() + " execute-unloaded-chunks [dimension id]"));
sender.sendMessage(new TextComponentString(this.getUsageStringCommon() + " list"));
sender.sendMessage(new TextComponentString(this.getUsageStringCommon() + " prepare-from <block specifier containing spaces>"));
sender.sendMessage(new TextComponentString(this.getUsageStringCommon() + " prepare-to <block specifier containing spaces>"));
sender.sendMessage(new TextComponentString(this.getUsageStringCommon() + " remove <block-from> [block-from] ..."));
sender.sendMessage(new TextComponentString(this.getUsageStringCommon() + " remove-with-spaces <block-from>"));
sender.sendMessage(new TextComponentString(this.getUsageStringCommon() + " stoptask"));
}
@Override
protected List<String> getTabCompletionsSub(MinecraftServer server, ICommandSender sender, String[] args, @Nullable BlockPos targetPos)
{
if (args.length < 1)
{
return Collections.emptyList();
}
String cmd = args[0];
args = CommandWorldUtils.dropFirstStrings(args, 1);
if (cmd.equals("add") || cmd.equals("prepare-from") || cmd.equals("prepare-to"))
{ | return CommandBase.getListOfStringsMatchingLastWord(args, BlockUtils.getAllBlockNames()); | 6 |
zetbaitsu/CodePolitan | app/src/main/java/id/zelory/codepolitan/ui/adapter/NewsAdapter.java | [
"public abstract class BenihHeaderAdapter<Data, ViewHolder extends BenihItemViewHolder<Data>,\n Header extends BenihHeaderViewHolder> extends\n BenihRecyclerAdapter<Data, BenihItemViewHolder>\n{\n protected static final int TYPE_HEADER = 0;\n protected static final int TYPE_ITEM = 1;\n protected boolean hasHeader = true;\n protected Header header;\n protected Bundle bundle;\n\n public BenihHeaderAdapter(Context context, Bundle bundle)\n {\n super(context);\n this.bundle = bundle;\n if (hasHeader)\n {\n data.add(null);\n }\n }\n\n @Override\n protected int getItemView(int viewType)\n {\n if (viewType == TYPE_HEADER)\n {\n return getHeaderResourceLayout();\n } else\n {\n return getItemResourceLayout(viewType);\n }\n }\n\n protected abstract int getHeaderResourceLayout();\n\n protected abstract int getItemResourceLayout(int viewType);\n\n @Override\n public BenihItemViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType)\n {\n if (hasHeader && viewType == TYPE_HEADER)\n {\n header = onCreateHeaderViewHolder(viewGroup, viewType);\n return header;\n }\n\n return onCreateItemViewHolder(viewGroup, viewType);\n }\n\n protected abstract Header onCreateHeaderViewHolder(ViewGroup viewGroup, int viewType);\n\n public abstract ViewHolder onCreateItemViewHolder(ViewGroup viewGroup, int viewType);\n\n @Override\n public void onBindViewHolder(BenihItemViewHolder holder, int position)\n {\n if (hasHeader && position == 0)\n {\n header.show();\n return;\n }\n holder.setHasHeader(hasHeader);\n super.onBindViewHolder(holder, position);\n }\n\n\n @Override\n public int getItemViewType(int position)\n {\n if (position == 0 && hasHeader)\n {\n return TYPE_HEADER;\n } else\n {\n return TYPE_ITEM;\n }\n }\n\n public void showHeader()\n {\n if (!hasHeader)\n {\n hasHeader = true;\n data.add(0, null);\n }\n }\n\n public void hideHeader()\n {\n if (hasHeader)\n {\n hasHeader = false;\n data.remove(0);\n }\n }\n\n public boolean isHasHeader()\n {\n return hasHeader;\n }\n\n @Override\n public void clear()\n {\n super.clear();\n if (hasHeader)\n {\n data.add(null);\n }\n }\n\n @Override\n public List<Data> getData()\n {\n return hasHeader ? new ArrayList<>(data.subList(1, data.size())) : super.getData();\n }\n\n public Header getHeader()\n {\n return header;\n }\n\n @Override\n public void add(Data item, int position)\n {\n if (hasHeader)\n {\n data.add(position + 1, item);\n notifyItemInserted(position + 1);\n } else\n {\n super.add(item, position);\n }\n }\n\n @Override\n public void remove(int position)\n {\n if (hasHeader)\n {\n data.remove(position + 1);\n notifyItemRemoved(position + 1);\n } else\n {\n super.remove(position);\n }\n }\n}",
"public abstract class BenihItemViewHolder<Data> extends RecyclerView.ViewHolder implements\n View.OnClickListener,\n View.OnLongClickListener\n{\n private OnItemClickListener itemClickListener;\n private OnLongItemClickListener longItemClickListener;\n private boolean hasHeader = false;\n\n public BenihItemViewHolder(View itemView, OnItemClickListener itemClickListener, OnLongItemClickListener longItemClickListener)\n {\n super(itemView);\n ButterKnife.bind(this, itemView);\n Timber.tag(getClass().getSimpleName());\n this.itemClickListener = itemClickListener;\n this.longItemClickListener = longItemClickListener;\n itemView.setOnClickListener(this);\n itemView.setOnLongClickListener(this);\n }\n\n public abstract void bind(Data data);\n\n public boolean isHasHeader()\n {\n return hasHeader;\n }\n\n public void setHasHeader(boolean hasHeader)\n {\n this.hasHeader = hasHeader;\n }\n\n @Override\n public void onClick(View v)\n {\n if (itemClickListener != null)\n {\n itemClickListener.onItemClick(v, hasHeader ? getAdapterPosition() - 1 : getAdapterPosition());\n }\n }\n\n @Override\n public boolean onLongClick(View v)\n {\n if (longItemClickListener != null)\n {\n longItemClickListener.onLongItemClick(v, hasHeader ? getAdapterPosition() - 1 : getAdapterPosition());\n return true;\n }\n\n return false;\n }\n}",
"public class Article implements Parcelable\n{\n public final static String TYPE_NEWS = \"news\";\n public final static String TYPE_KOMIK = \"nyankomik\";\n public final static String TYPE_MEME = \"meme\";\n public final static String TYPE_QUOTE = \"quotes\";\n\n private int id;\n private String slug;\n private String title;\n private String excerpt;\n private String content;\n private String date;\n private String dateClear;\n private String link;\n private String thumbnailSmall;\n private String thumbnailMedium;\n private boolean bookmarked;\n private boolean readLater;\n private boolean big;\n private String postType;\n private List<Category> category;\n private List<Tag> tags;\n\n public Article()\n {\n postType = TYPE_NEWS;\n }\n\n protected Article(Parcel in)\n {\n id = in.readInt();\n slug = in.readString();\n title = in.readString();\n excerpt = in.readString();\n content = in.readString();\n date = in.readString();\n dateClear = in.readString();\n link = in.readString();\n thumbnailSmall = in.readString();\n thumbnailMedium = in.readString();\n bookmarked = in.readByte() != 0;\n readLater = in.readByte() != 0;\n big = in.readByte() != 0;\n postType = in.readString();\n category = in.createTypedArrayList(Category.CREATOR);\n tags = in.createTypedArrayList(Tag.CREATOR);\n }\n\n public static final Creator<Article> CREATOR = new Creator<Article>()\n {\n @Override\n public Article createFromParcel(Parcel in)\n {\n return new Article(in);\n }\n\n @Override\n public Article[] newArray(int size)\n {\n return new Article[size];\n }\n };\n\n public int getId()\n {\n return id;\n }\n\n public void setId(int id)\n {\n this.id = id;\n }\n\n public String getSlug()\n {\n return slug;\n }\n\n public void setSlug(String slug)\n {\n this.slug = slug;\n }\n\n public String getTitle()\n {\n return title;\n }\n\n public void setTitle(String title)\n {\n this.title = title;\n }\n\n public String getExcerpt()\n {\n return excerpt;\n }\n\n public void setExcerpt(String excerpt)\n {\n this.excerpt = excerpt;\n }\n\n public String getContent()\n {\n return content;\n }\n\n public void setContent(String content)\n {\n this.content = content;\n }\n\n public String getDate()\n {\n return date;\n }\n\n public void setDate(String date)\n {\n this.date = date;\n }\n\n public String getDateClear()\n {\n return dateClear;\n }\n\n public void setDateClear(String dateClear)\n {\n this.dateClear = dateClear;\n }\n\n public String getLink()\n {\n return link;\n }\n\n public void setLink(String link)\n {\n this.link = link;\n }\n\n public String getThumbnailSmall()\n {\n return thumbnailSmall;\n }\n\n public void setThumbnailSmall(String thumbnailSmall)\n {\n this.thumbnailSmall = thumbnailSmall;\n }\n\n public String getThumbnailMedium()\n {\n return thumbnailMedium;\n }\n\n public void setThumbnailMedium(String thumbnailMedium)\n {\n this.thumbnailMedium = thumbnailMedium;\n }\n\n public boolean isBookmarked()\n {\n return bookmarked;\n }\n\n public void setBookmarked(boolean bookmarked)\n {\n this.bookmarked = bookmarked;\n }\n\n public boolean isReadLater()\n {\n return readLater;\n }\n\n public void setReadLater(boolean readLater)\n {\n this.readLater = readLater;\n }\n\n public boolean isBig()\n {\n return big;\n }\n\n public void setBig(boolean big)\n {\n this.big = big;\n }\n\n public String getPostType()\n {\n return postType;\n }\n\n public void setPostType(String postType)\n {\n this.postType = postType;\n }\n\n public List<Category> getCategory()\n {\n return category;\n }\n\n public void setCategory(List<Category> category)\n {\n this.category = category;\n }\n\n public List<Tag> getTags()\n {\n return tags;\n }\n\n public void setTags(List<Tag> tags)\n {\n this.tags = tags;\n }\n\n @Override\n public int describeContents()\n {\n return hashCode();\n }\n\n @Override\n public void writeToParcel(Parcel dest, int flags)\n {\n dest.writeInt(id);\n dest.writeString(slug);\n dest.writeString(title);\n dest.writeString(excerpt);\n dest.writeString(content);\n dest.writeString(date);\n dest.writeString(dateClear);\n dest.writeString(link);\n dest.writeString(thumbnailSmall);\n dest.writeString(thumbnailMedium);\n dest.writeByte((byte) (bookmarked ? 1 : 0));\n dest.writeByte((byte) (readLater ? 1 : 0));\n dest.writeByte((byte) (big ? 1 : 0));\n dest.writeString(postType);\n dest.writeTypedList(category);\n dest.writeTypedList(tags);\n }\n}",
"public class NewsHeaderViewHolder extends BenihHeaderViewHolder implements\n RandomContentController.Presenter, BookmarkController.Presenter,\n ReadLaterController.Presenter\n{\n @Bind(R.id.title) TextView title;\n @Bind(R.id.date) TextView date;\n @Bind(R.id.thumbnail) CodePolitanImageView thumbnail;\n @Bind(R.id.iv_bookmark) ImageView ivBookmark;\n @Bind(R.id.iv_read_later) ImageView ivReadLater;\n @Bind(R.id.tv_more) TextView tvMore;\n @Bind(R.id.iv_error) ImageView ivError;\n @Bind(R.id.card_view) CardView cardView;\n private BookmarkController bookmarkController;\n private ReadLaterController readLaterController;\n private RandomContentController randomContentController;\n private List<Article> articles;\n private Animation animation;\n\n public NewsHeaderViewHolder(View itemView, Bundle bundle)\n {\n super(itemView, bundle);\n animation = AnimationUtils.loadAnimation(CodePolitanApplication.pluck().getApplicationContext(),\n R.anim.push_right_in);\n bookmarkController = new BookmarkController(this);\n readLaterController = new ReadLaterController(this);\n randomContentController = new RandomContentController(this);\n if (bundle != null)\n {\n randomContentController.loadState(bundle);\n }\n }\n\n public void bind(Article article)\n {\n title.setText(article.getTitle());\n date.setText(article.getDateClear());\n thumbnail.setBackgroundColor(BenihUtils.getRandomColor());\n thumbnail.setImageUrl(article.isBig() ? article.getThumbnailMedium() : article.getThumbnailSmall(), ivError);\n ivBookmark.setImageResource(article.isBookmarked() ? R.mipmap.ic_bookmark_on : R.mipmap.ic_bookmark);\n ivBookmark.setOnClickListener(v -> bookmarkController.bookmark(article));\n ivBookmark.setOnLongClickListener(this::onBookmarkLongClick);\n ivReadLater.setImageResource(article.isReadLater() ? R.mipmap.ic_read_later_on : R.mipmap.ic_read_later);\n ivReadLater.setOnClickListener(v -> readLaterController.readLater(article));\n ivReadLater.setOnLongClickListener(this::onReadLaterLongClick);\n tvMore.setOnClickListener(v -> BenihBus.pluck().send(new MoreNewsHeaderEvent()));\n bookmarkController.setArticle(article);\n readLaterController.setArticle(article);\n }\n\n private boolean onReadLaterLongClick(View view)\n {\n Snackbar.make(view, CodePolitanApplication.pluck().getString(R.string.read_later_desc), Snackbar.LENGTH_SHORT).show();\n return true;\n }\n\n private boolean onBookmarkLongClick(View view)\n {\n Snackbar.make(view, CodePolitanApplication.pluck().getString(R.string.bookmark_desc), Snackbar.LENGTH_SHORT).show();\n return true;\n }\n\n @Override\n public void showRandomArticles(List<Article> articles)\n {\n this.articles = articles;\n bind(articles.get(0));\n cardView.setOnClickListener(v -> BenihBus.pluck().send(new NewsHeaderEvent(this.articles)));\n }\n\n @Override\n public void showRandomCategory(Category category)\n {\n randomContentController.loadRandomArticles(category);\n }\n\n @Override\n public void showRandomTag(Tag tag)\n {\n randomContentController.loadRandomArticles(tag);\n }\n\n @Override\n public void showListBookmarkedArticles(List<Article> listArticle)\n {\n\n }\n\n @Override\n public void onBookmark(Article article)\n {\n ivBookmark.startAnimation(animation);\n ivBookmark.setImageResource(R.mipmap.ic_bookmark_on);\n }\n\n @Override\n public void onUnBookmark(Article article)\n {\n ivBookmark.startAnimation(animation);\n ivBookmark.setImageResource(R.mipmap.ic_bookmark);\n }\n\n @Override\n public void showFilteredArticles(List<Article> articles)\n {\n\n }\n\n @Override\n public void showListReadLaterArticles(List<Article> listArticle)\n {\n\n }\n\n @Override\n public void onReadLater(Article article)\n {\n ivReadLater.startAnimation(animation);\n ivReadLater.setImageResource(R.mipmap.ic_read_later_on);\n }\n\n @Override\n public void onUnReadLater(Article article)\n {\n ivReadLater.startAnimation(animation);\n ivReadLater.setImageResource(R.mipmap.ic_read_later);\n }\n\n @Override\n public void showLoading()\n {\n\n }\n\n @Override\n public void dismissLoading()\n {\n\n }\n\n @Override\n public void showError(Throwable throwable)\n {\n switch (throwable.getMessage())\n {\n case ErrorEvent.LOAD_STATE_RANDOM_ARTICLES:\n randomContentController.loadRandomArticles();\n break;\n case ErrorEvent.LOAD_RANDOM_ARTICLES:\n Snackbar.make(ivBookmark, R.string.error_message, Snackbar.LENGTH_LONG)\n .setAction(R.string.retry, v -> randomContentController.loadRandomArticles())\n .show();\n break;\n }\n }\n\n @Override\n public void show()\n {\n if (articles != null && !articles.isEmpty())\n {\n bind(articles.get(0));\n } else\n {\n randomContentController.loadRandomArticles();\n }\n }\n\n @Override\n public void saveState(Bundle bundle)\n {\n super.saveState(bundle);\n randomContentController.saveState(bundle);\n }\n}",
"public class NewsItemViewHolder extends AbstractArticleViewHolder\n{\n @Bind(R.id.title) TextView title;\n @Bind(R.id.date) TextView date;\n\n public NewsItemViewHolder(View itemView, OnItemClickListener itemClickListener, OnLongItemClickListener longItemClickListener)\n {\n super(itemView, itemClickListener, longItemClickListener);\n }\n\n @Override\n public void bind(Article article)\n {\n super.bind(article);\n title.setText(article.getTitle());\n date.setText(article.getDateClear());\n }\n\n @Override\n protected void setThumbnail(Article article)\n {\n thumbnail.setImageUrl(article.isBig() ? article.getThumbnailMedium() : article.getThumbnailSmall(), ivError);\n }\n}",
"public class SearchFooterViewHolder extends BenihItemViewHolder\n{\n public SearchFooterViewHolder(View itemView, OnItemClickListener itemClickListener, OnLongItemClickListener longItemClickListener)\n {\n super(itemView, itemClickListener, longItemClickListener);\n }\n\n @Override\n public void bind(Object o)\n {\n\n }\n\n @Override\n public void onClick(View v)\n {\n BenihBus.pluck().send(new SearchFooterEvent());\n }\n\n @Override\n public boolean onLongClick(View v)\n {\n return false;\n }\n}"
] | import android.content.Context;
import android.os.Bundle;
import android.view.ViewGroup;
import id.zelory.benih.adapter.BenihHeaderAdapter;
import id.zelory.benih.adapter.viewholder.BenihItemViewHolder;
import id.zelory.codepolitan.R;
import id.zelory.codepolitan.data.model.Article;
import id.zelory.codepolitan.ui.adapter.viewholder.NewsHeaderViewHolder;
import id.zelory.codepolitan.ui.adapter.viewholder.NewsItemViewHolder;
import id.zelory.codepolitan.ui.adapter.viewholder.SearchFooterViewHolder; | /*
* Copyright (c) 2015 Zelory.
*
* 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 id.zelory.codepolitan.ui.adapter;
/**
* Created on : July 28, 2015
* Author : zetbaitsu
* Name : Zetra
* Email : [email protected]
* GitHub : https://github.com/zetbaitsu
* LinkedIn : https://id.linkedin.com/in/zetbaitsu
*/
public class NewsAdapter extends
BenihHeaderAdapter<Article, BenihItemViewHolder<Article>, NewsHeaderViewHolder>
{
private final static int TYPE_BIG = 2;
private final static int TYPE_MINI = 3;
private final static int TYPE_FOOTER = 4;
public NewsAdapter(Context context, Bundle bundle)
{
super(context, bundle);
}
@Override
protected int getHeaderResourceLayout()
{
return R.layout.list_header_news;
}
@Override
protected int getItemResourceLayout(int viewType)
{
switch (viewType)
{
case TYPE_BIG:
return R.layout.list_item_news_big;
case TYPE_FOOTER:
return R.layout.list_footer_search;
default:
return R.layout.list_item_news_mini;
}
}
@Override
protected NewsHeaderViewHolder onCreateHeaderViewHolder(ViewGroup viewGroup, int viewType)
{
return new NewsHeaderViewHolder(getView(viewGroup, viewType), bundle);
}
@Override
public BenihItemViewHolder<Article> onCreateItemViewHolder(ViewGroup viewGroup, int viewType)
{
switch (viewType)
{
case TYPE_FOOTER: | return new SearchFooterViewHolder(getView(viewGroup, viewType), itemClickListener, longItemClickListener); | 5 |
alphadev-net/drive-mount | app/src/main/java/net/alphadev/usbstorage/DocumentProviderImpl.java | [
"public enum FileAttribute {\n FILESIZE,\n LAST_MODIFIED\n}",
"public interface FileSystemProvider {\n /**\n * Returs true if, and only if, the item represented by the given Path is a directory.\n *\n * @param path Path to check\n * @return true if is directory\n */\n boolean isDirectory(Path path);\n\n /**\n * Returns list of Paths (sub entries) for a given Path or an empty list otherwise.\n *\n * @param path path Path to look for sub entries\n * @return List of Paths\n */\n Iterable<Path> getEntries(Path path);\n\n /**\n * Returns the requested File Attribute or null if not applicable.\n *\n * @param path Path to get the Attribute for\n * @param attr Type of Attribute accortidng to FileAttribute\n * @return Attribute value or null\n */\n Object getAttribute(Path path, FileAttribute attr);\n\n FileHandle openDocument(Path path);\n}",
"public final class Path {\n private final List<String> paths;\n\n public Path(String path) {\n this(Arrays.asList(path.split(\"/\")));\n }\n\n private Path(List<String> list) {\n this.paths = list;\n }\n\n public static Path createWithAppended(Path path, String... appendToPath) {\n final List<String> paths = new ArrayList<>(path.paths);\n for (String appendix : appendToPath) {\n if (appendix.indexOf('/') != -1) {\n paths.addAll(Arrays.asList(appendix.split(\"/\")));\n } else {\n paths.add(appendix);\n }\n }\n return new Path(paths);\n }\n\n /**\n * Returns parent.\n *\n * @return parent path or null\n */\n public Path getParent() {\n if (paths.size() < 3) {\n return null;\n }\n\n List<String> parentPaths = paths.subList(0, paths.size() - 1);\n return new Path(parentPaths);\n }\n\n public String getName() {\n if (paths.size() < 2) {\n return null;\n }\n\n return paths.get(paths.size() - 1);\n }\n\n public String getDeviceId() {\n if (paths.get(0).isEmpty()) {\n return null;\n }\n\n return paths.get(0);\n }\n\n public final Iterable<String> getIterator() {\n return paths.subList(1, paths.size());\n }\n\n public String toAbsolute() {\n StringBuilder sb = new StringBuilder();\n boolean firstTime = true;\n\n for (String token : paths) {\n if (firstTime) {\n firstTime = false;\n } else {\n sb.append('/');\n }\n sb.append(token);\n }\n\n return sb.toString();\n }\n\n public boolean isRoot() {\n return paths.size() == 1;\n }\n}",
"@SuppressWarnings(\"unused\")\npublic interface StorageDevice extends Identifiable, Closeable {\n /**\n * Returns the size, in bytes, of the file store.\n *\n * @return the size of the file store, in bytes\n */\n long getTotalSpace();\n\n /**\n * Returns the number of unallocated bytes in the file store.\n * <p/>\n * The returned number of unallocated bytes is a hint, but not a guarantee, that it is possible\n * to use most or any of these bytes. The number of unallocated bytes is most likely to be\n * accurate immediately after the space attributes are obtained. It is likely to be made\n * inaccurate by any external I/O operations including those made on the system outside of this\n * virtual machine.\n *\n * @return the number of unallocated bytes\n */\n long getUnallocatedSpace();\n\n /**\n * Returns the number of bytes available to this Java virtual machine on the file store.\n * <p/>\n * The returned number of available bytes is a hint, but not a guarantee, that it is possible to\n * use most or any of these bytes. The number of usable bytes is most likely to be accurate\n * immediately after the space attributes are obtained. It is likely to be made inaccurate by\n * any external I/O operations including those made on the system outside of this Java virtual\n * machine.\n *\n * @return the number of bytes available\n */\n long getUsableSpace();\n\n /**\n * Tells whether this file store is read-only.\n * <p/>\n * A file store is read-only if it does not support write operations or other changes to files.\n * Any attempt to create a file, open an existing file for writing etc. causes an IOException to\n * be thrown.\n *\n * @return true if, and only if, this file store is read-only\n */\n boolean isReadOnly();\n\n /**\n * Returns the type of this file store.\n * <p/>\n * The format of the string returned by this method is highly implementation specific.\n * It may indicate, for example, the format used or if the file store is local or remote.\n *\n * @return a string representing the type of this file store\n */\n String getType();\n\n /**\n * Returns the name of this file store.\n * <p/>\n * The format of the name is highly implementation specific.\n * It will typically be the name of the storage pool or volume.\n * The string returned by this method may differ from the string returned by the toString\n * method.\n *\n * @return the name of this file store\n */\n String getName();\n\n FileSystemProvider getProvider();\n}",
"public class ParcelFileDescriptorUtil {\n public static ParcelFileDescriptor pipeFrom(InputStream inputStream)\n throws IOException {\n final ParcelFileDescriptor[] pipe = ParcelFileDescriptor.createPipe();\n final OutputStream output = new ParcelFileDescriptor.AutoCloseOutputStream(pipe[1]);\n\n new TransferThread(inputStream, output).start();\n\n return pipe[0];\n }\n\n @SuppressWarnings(\"unused\")\n public static ParcelFileDescriptor pipeTo(OutputStream outputStream)\n throws IOException {\n final ParcelFileDescriptor[] pipe = ParcelFileDescriptor.createPipe();\n final InputStream input = new ParcelFileDescriptor.AutoCloseInputStream(pipe[0]);\n\n new TransferThread(input, outputStream).start();\n\n return pipe[1];\n }\n\n static class TransferThread extends Thread {\n final InputStream mIn;\n final OutputStream mOut;\n\n TransferThread(InputStream in, OutputStream out) {\n super(\"ParcelFileDescriptor Transfer Thread\");\n mIn = in;\n mOut = out;\n setDaemon(true);\n }\n\n @Override\n public void run() {\n try {\n IOUtils.copy(mIn, mOut);\n mOut.flush();\n } catch (IOException e) {\n Log.e(\"TransferThread\", \"writing failed\");\n e.printStackTrace();\n } finally {\n IOUtils.closeQuietly(mIn);\n IOUtils.closeQuietly(mOut);\n }\n }\n }\n}"
] | import android.database.Cursor;
import android.database.MatrixCursor;
import android.os.CancellationSignal;
import android.os.ParcelFileDescriptor;
import android.provider.DocumentsContract.Document;
import android.provider.DocumentsContract.Root;
import android.provider.DocumentsProvider;
import android.util.Log;
import net.alphadev.usbstorage.api.filesystem.FileAttribute;
import net.alphadev.usbstorage.api.filesystem.FileSystemProvider;
import net.alphadev.usbstorage.api.filesystem.Path;
import net.alphadev.usbstorage.api.filesystem.StorageDevice;
import net.alphadev.usbstorage.util.ParcelFileDescriptorUtil;
import org.apache.tika.Tika;
import org.apache.tika.config.TikaConfig;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat; | /**
* Copyright © 2014-2015 Jan Seeger
*
* 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 net.alphadev.usbstorage;
public class DocumentProviderImpl extends DocumentsProvider {
private static final String[] DEFAULT_ROOT_PROJECTION = new String[]{
Root.COLUMN_ROOT_ID, Root.COLUMN_FLAGS, Root.COLUMN_ICON, Root.COLUMN_TITLE,
Root.COLUMN_DOCUMENT_ID, Root.COLUMN_AVAILABLE_BYTES, Root.COLUMN_SUMMARY
};
private static final String[] DEFAULT_DOCUMENT_PROJECTION = new String[]{
Document.COLUMN_DOCUMENT_ID, Document.COLUMN_MIME_TYPE, Document.COLUMN_DISPLAY_NAME,
Document.COLUMN_LAST_MODIFIED, Document.COLUMN_FLAGS, Document.COLUMN_SIZE,
};
private StorageManager mStorageManager;
private static String[] resolveRootProjection(String[] projection) {
return projection != null ? projection : DEFAULT_ROOT_PROJECTION;
}
private static String[] resolveDocumentProjection(String[] projection) {
return projection != null ? projection : DEFAULT_DOCUMENT_PROJECTION;
}
/**
* http://stackoverflow.com/questions/3263892/format-file-size-as-mb-gb-etc
*/
private static String readableFileSize(long size) {
if (size <= 0) {
return "0B";
}
final String[] units = new String[]{"B", "kB", "MB", "GB", "TB"};
final int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
final float roundedSize = (float) (size / Math.pow(1024, digitGroups));
return new DecimalFormat("#,##0.#").format(roundedSize) + " " + units[digitGroups];
}
@Override
public boolean onCreate() {
mStorageManager = new StorageManager(getContext());
new DeviceManager(getContext(), mStorageManager);
return true;
}
@Override
public Cursor queryRoots(final String[] requestedProjection) throws FileNotFoundException {
final String[] projection = resolveRootProjection(requestedProjection);
final MatrixCursor roots = new MatrixCursor(projection);
for (StorageDevice device : mStorageManager.getMounts()) {
createDevice(roots.newRow(), device, projection);
}
return roots;
}
private void createDevice(MatrixCursor.RowBuilder row, StorageDevice device,
String[] projection) {
for (String column : projection) {
switch (column) {
case Root.COLUMN_ROOT_ID:
row.add(Root.COLUMN_ROOT_ID, device.getId());
break;
case Root.COLUMN_DOCUMENT_ID:
row.add(Root.COLUMN_DOCUMENT_ID, device.getId());
break;
case Root.COLUMN_TITLE:
row.add(Root.COLUMN_TITLE, device.getName());
break;
case Root.COLUMN_ICON:
row.add(Root.COLUMN_ICON, R.drawable.drive_icon);
break;
case Root.COLUMN_SUMMARY:
final String sizeUnit = readableFileSize(device.getUnallocatedSpace());
final String summary = getContext().getString(R.string.free_space, sizeUnit);
row.add(Root.COLUMN_SUMMARY, summary);
break;
case Root.COLUMN_AVAILABLE_BYTES:
row.add(Root.COLUMN_AVAILABLE_BYTES, device.getUnallocatedSpace());
break;
case Root.COLUMN_FLAGS:
int flags = 0;
if (!device.isReadOnly()) {
flags |= Root.FLAG_SUPPORTS_CREATE;
}
row.add(Root.COLUMN_FLAGS, flags);
break;
default:
Log.w("Drive Mount", "Couldn't satisfy " + column + " column.");
}
}
}
@Override
public Cursor queryDocument(String documentId,
final String[] requestedProjection) throws FileNotFoundException {
final String[] projection = resolveDocumentProjection(requestedProjection);
final MatrixCursor result = new MatrixCursor(projection);
addEntry(result, new Path(documentId), projection);
return result;
}
@Override
public Cursor queryChildDocuments(String parentDocumentId, final String[] requestedProjection,
String sortOrder) throws FileNotFoundException {
final String[] projection = resolveDocumentProjection(requestedProjection);
final MatrixCursor result = new MatrixCursor(projection);
final Path parent = new Path(parentDocumentId);
final FileSystemProvider provider = getProvider(parent);
for (Path child : provider.getEntries(parent)) {
addEntry(result, child, projection);
}
return result;
}
@Override
public ParcelFileDescriptor openDocument(final String documentId, final String mode,
CancellationSignal signal) throws FileNotFoundException {
try {
final Path path = new Path(documentId);
final InputStream inputStream = getProvider(path)
.openDocument(path).readDocument();
| return ParcelFileDescriptorUtil.pipeFrom(inputStream); | 4 |
hoijui/JavaOSC | modules/core/src/main/java/com/illposed/osc/argument/handler/StringArgumentHandler.java | [
"public interface BytesReceiver {\n\n\t/**\n\t * Relative <i>put</i> method <i>(optional operation)</i>.\n\t *\n\t * <p> Writes the given byte into this buffer at the current\n\t * position, and then increments the position. </p>\n\t *\n\t * @param data\n\t * The byte to be written\n\t *\n\t * @return This buffer\n\t *\n\t * @throws java.nio.BufferOverflowException\n\t * If this buffer's current position is not smaller than its limit\n\t *\n\t * @throws java.nio.ReadOnlyBufferException\n\t * If this buffer is read-only\n\t */\n\tBytesReceiver put(byte data);\n\n\t/**\n\t * Relative bulk <i>put</i> method <i>(optional operation)</i>.\n\t *\n\t * <p> This method transfers the entire content of the given source\n\t * byte array into this buffer. An invocation of this method of the\n\t * form <tt>dst.put(a)</tt> behaves in exactly the same way as the\n\t * invocation\n\t *\n\t * <pre>\n\t * dst.put(a, 0, a.length) </pre>\n\t *\n\t * @param src\n\t * The source array\n\t *\n\t * @return This buffer\n\t *\n\t * @throws java.nio.BufferOverflowException\n\t * If there is insufficient space in this buffer\n\t *\n\t * @throws java.nio.ReadOnlyBufferException\n\t * If this buffer is read-only\n\t */\n\tBytesReceiver put(byte[] src);\n\n\t/**\n\t * Relative bulk <i>put</i> method <i>(optional operation)</i>.\n\t *\n\t * <p> This method transfers the bytes remaining in the given source\n\t * buffer into this buffer. If there are more bytes remaining in the\n\t * source buffer than in this buffer, that is, if\n\t * <tt>src.remaining()</tt> <tt>></tt> <tt>remaining()</tt>,\n\t * then no bytes are transferred and a {@link\n\t * java.nio.BufferOverflowException} is thrown.\n\t *\n\t * <p> Otherwise, this method copies\n\t * <i>n</i> = <tt>src.remaining()</tt> bytes from the given\n\t * buffer into this buffer, starting at each buffer's current position.\n\t * The positions of both buffers are then incremented by <i>n</i>.\n\t *\n\t * <p> In other words, an invocation of this method of the form\n\t * <tt>dst.put(src)</tt> has exactly the same effect as the loop\n\t *\n\t * <pre>\n\t * while (src.hasRemaining())\n\t * dst.put(src.get()); </pre>\n\t *\n\t * except that it first checks that there is sufficient space in this\n\t * buffer and it is potentially much more efficient.\n\t *\n\t * @param src\n\t * The source buffer from which bytes are to be read;\n\t * must not be this buffer\n\t *\n\t * @return This buffer\n\t *\n\t * @throws java.nio.BufferOverflowException\n\t * If there is insufficient space in this buffer\n\t * for the remaining bytes in the source buffer\n\t *\n\t * @throws IllegalArgumentException\n\t * If the source buffer is this buffer\n\t *\n\t * @throws java.nio.ReadOnlyBufferException\n\t * If this buffer is read-only\n\t */\n\tBytesReceiver put(ByteBuffer src);\n\n\t/**\n\t * Clears this buffer. The position is set to zero, the limit is set to\n\t * the capacity, and the mark is discarded.\n\t *\n\t * <p> Invoke this method before using a sequence of channel-read or\n\t * <i>put</i> operations to fill this buffer. For example:\n\t *\n\t * <blockquote><pre>\n\t * buf.clear(); // Prepare buffer for reading\n\t * in.read(buf); // Read data</pre></blockquote>\n\t *\n\t * <p> This method does not actually erase the data in the buffer, but it\n\t * is named as if it did because it will most often be used in situations\n\t * in which that might as well be the case. </p>\n\t *\n\t * @return This buffer\n\t */\n\tBytesReceiver clear();\n\n\t/**\n\t * Returns this buffers position.\n\t *\n\t * @return The position of this buffer\n\t */\n\tint position();\n\n\t/**\n\t * A piece of data, stored in the buffer at the current location,\n\t * which can later be replaced with an other piece of data of the same length.\n\t */\n\tinterface PlaceHolder {\n\t\tvoid replace(byte[] src) throws OSCSerializeException;\n\t}\n\n\t/**\n\t * But a piece of data, which we later might want to replace\n\t * with an other one of equal length.\n\t * @param src the preliminary piece of data\n\t * @return an object holding an internal reference on the put piece of data,\n\t * which allows to later replace it in the internal buffer\n\t */\n\tPlaceHolder putPlaceHolder(byte[] src);\n\n\t/**\n\t * Returns a raw byte array containing all data this instance received\n\t * since tha last {@link #clear()}.\n\t * NOTE This is a costly method (performance wise -> memory usage),\n\t * and should therefore only be used in unit tests.\n\t *\n\t * @return the current internal buffers content in a byte array\n\t */\n\tbyte[] toByteArray();\n}",
"public class OSCParseException extends Exception {\n\tprivate final ByteBuffer data;\n\n\tpublic ByteBuffer getData() {\n\t\treturn data;\n\t}\n\n\tpublic OSCParseException(final String message, final ByteBuffer data) {\n\t\tsuper(message);\n\t\tthis.data = data;\n\t}\n\n\tpublic OSCParseException(final Throwable cause, final ByteBuffer data) {\n\t\tsuper(cause);\n\t\tthis.data = data;\n\t}\n\n\tpublic OSCParseException(\n\t\tfinal String message,\n\t\tfinal Throwable cause,\n\t\tfinal ByteBuffer data)\n\t{\n\t\tsuper(message, cause);\n\t\tthis.data = data;\n\t}\n}",
"public class OSCParser {\n\n\t// Public API\n\t/**\n\t * Number of bytes the raw OSC data stream is aligned to.\n\t */\n\t@SuppressWarnings(\"WeakerAccess\")\n\tpublic static final int ALIGNMENT_BYTES = 4;\n\t// Public API\n\t@SuppressWarnings(\"WeakerAccess\")\n\tpublic static final String BUNDLE_START = \"#bundle\";\n\tprivate static final byte[] BUNDLE_START_BYTES\n\t\t\t= BUNDLE_START.getBytes(StandardCharsets.UTF_8);\n\tprivate static final String NO_ARGUMENT_TYPES = \"\";\n\t// Public API\n\t@SuppressWarnings(\"WeakerAccess\")\n\tpublic static final byte TYPES_VALUES_SEPARATOR = (byte) ',';\n\t// Public API\n\t@SuppressWarnings(\"WeakerAccess\")\n\tpublic static final char TYPE_ARRAY_BEGIN = (byte) '[';\n\t// Public API\n\t@SuppressWarnings(\"WeakerAccess\")\n\tpublic static final char TYPE_ARRAY_END = (byte) ']';\n\n\tprivate final Logger log = LoggerFactory.getLogger(OSCParser.class);\n\n\tprivate final Map<Character, ArgumentHandler> identifierToType;\n\tprivate final Map<String, Object> properties;\n\tprivate final byte[] bundleStartChecker;\n\n\tprivate static class UnknownArgumentTypeParseException extends OSCParseException {\n\t\tUnknownArgumentTypeParseException(\n\t\t\tfinal char argumentType,\n\t\t\tfinal ByteBuffer data)\n\t\t{\n\t\t\tsuper(\"No \" + ArgumentHandler.class.getSimpleName() + \" registered for type '\"\n\t\t\t\t\t+ argumentType + '\\'', data);\n\t\t}\n\t}\n\n\t// Public API\n\t/**\n\t * Creates a new parser with all the required ingredients.\n\t * @param identifierToType all of these, and only these arguments will be\n\t * parsable by this object, that are supported by these handlers\n\t * @param properties see {@link ArgumentHandler#setProperties(Map)}\n\t */\n\t@SuppressWarnings(\"WeakerAccess\")\n\tpublic OSCParser(\n\t\t\tfinal Map<Character, ArgumentHandler> identifierToType,\n\t\t\tfinal Map<String, Object> properties)\n\t{\n\t\t// We create (shallow) copies of these collections,\n\t\t// so if \"the creator\" modifies them after creating us,\n\t\t// we do not get different behaviour during our lifetime,\n\t\t// which might be very confusing to users of this class.\n\t\t// As the copies are not deep though,\n\t\t// It does not protect us from change in behaviour\n\t\t// do to change of the objects themselves,\n\t\t// which are contained in these collections.\n\t\t// TODO instead of these shallow copies, maybe create deep ones?\n\t\tthis.identifierToType = Collections.unmodifiableMap(\n\t\t\t\tnew HashMap<>(identifierToType));\n\t\tthis.properties = Collections.unmodifiableMap(\n\t\t\t\tnew HashMap<>(properties));\n\t\tthis.bundleStartChecker = new byte[BUNDLE_START.length()];\n\t}\n\n\t/**\n\t * If not yet aligned, move the position to the next index dividable by\n\t * {@link #ALIGNMENT_BYTES}.\n\t * @param input to be aligned\n\t * @see OSCSerializer#align\n\t */\n\tpublic static void align(final ByteBuffer input) {\n\t\tfinal int mod = input.position() % ALIGNMENT_BYTES;\n\t\tfinal int padding = (ALIGNMENT_BYTES - mod) % ALIGNMENT_BYTES;\n\t\t((Buffer)input).position(input.position() + padding);\n\t}\n\n\t// Public API\n\t@SuppressWarnings(\"unused\")\n\tpublic Map<Character, ArgumentHandler> getIdentifierToTypeMapping() {\n\t\treturn identifierToType;\n\t}\n\n\t/**\n\t * Returns the set of properties this parser was created with.\n\t * @return the set of properties to adhere to\n\t * @see ArgumentHandler#setProperties(Map)\n\t */\n\tpublic Map<String, Object> getProperties() {\n\t\treturn properties;\n\t}\n\n\t/**\n\t * Converts a byte-buffer into an {@link OSCPacket}\n\t * (either an {@link OSCMessage} or {@link OSCBundle}).\n\t * @param rawInput the storage containing the raw OSC packet\n\t * @return the successfully parsed OSC packet\n\t * @throws OSCParseException if the input has an invalid format\n\t */\n\tpublic OSCPacket convert(final ByteBuffer rawInput) throws OSCParseException {\n\n\t\tfinal ByteBuffer readOnlyInput = rawInput.asReadOnlyBuffer();\n\t\tfinal OSCPacket packet;\n\t\tif (isBundle(readOnlyInput)) {\n\t\t\tpacket = convertBundle(readOnlyInput);\n\t\t} else {\n\t\t\tOSCPacket tmpPacket = null;\n\t\t\ttry {\n\t\t\t\ttmpPacket = convertMessage(readOnlyInput);\n\t\t\t} catch (final UnknownArgumentTypeParseException ex) {\n\t\t\t\t// NOTE Some OSC applications communicate among instances of themselves\n\t\t\t\t// with additional, nonstandard argument types beyond those specified\n\t\t\t\t// in the OSC specification. OSC applications are not required to recognize\n\t\t\t\t// these types; an OSC application should discard any message whose\n\t\t\t\t// OSC Type Tag string contains any unrecognized OSC Type Tags.\n\t\t\t\tlog.warn(\"Package ignored because: {}\", ex.getMessage());\n\t\t\t}\n\t\t\tpacket = tmpPacket;\n\t\t}\n\n\t\treturn packet;\n\t}\n\n\t/**\n\t * Checks whether my byte array is a bundle.\n\t * From the OSC 1.0 specifications:\n\t * <quote>\n\t * The contents of an OSC packet must be either an OSC Message\n\t * or an OSC Bundle. The first byte of the packet's contents unambiguously\n\t * distinguishes between these two alternatives.\n\t * </quote>\n\t * Meaning, if the first byte is '#', the packet is a bundle,\n\t * otherwise it is a message.\n\t * Yet, the OSC standard body later itself broke with this standard/concept,\n\t * when they released a document suggesting to use messages\n\t * with an address of \"#reply\" for a stateful meta protocol\n\t * in the following document:\n\t *\n\t * @see <a href=\"http://opensoundcontrol.org/files/osc-query-system.pdf\">\n\t * A Query System for Open Sound Control (Draft Proposal)</a>\n\t *\n\t * @return true if it the byte array is a bundle, false o.w.\n\t */\n\tprivate boolean isBundle(final ByteBuffer rawInput) {\n\n\t\tboolean bundle;\n\t\tfinal int positionStart = rawInput.position();\n\t\ttry {\n\t\t\trawInput.get(bundleStartChecker);\n\t\t\tbundle = Arrays.equals(bundleStartChecker, BUNDLE_START_BYTES);\n\t\t} catch (final BufferUnderflowException bue) {\n\t\t\t// the package is too short to even contain the bundle start indicator\n\t\t\tbundle = false;\n\t\t}\n\t\t((Buffer)rawInput).position(positionStart);\n\t\treturn bundle;\n\t}\n\n\t/**\n\t * Converts the byte array to a bundle.\n\t * Assumes that the byte array is a bundle.\n\t * @return a bundle containing the data specified in the byte stream\n\t */\n\tprivate OSCBundle convertBundle(final ByteBuffer rawInput) throws OSCParseException {\n\t\t// skip the \"#bundle \" stuff\n\t\t((Buffer)rawInput).position(BUNDLE_START.length() + 1);\n\t\tfinal OSCTimeTag64 timestamp = TimeTag64ArgumentHandler.INSTANCE.parse(rawInput);\n\t\tfinal OSCBundle bundle = new OSCBundle(timestamp);\n\t\twhile (rawInput.hasRemaining()) {\n\t\t\t// recursively read through the stream and convert packets you find\n\t\t\tfinal int packetLength = IntegerArgumentHandler.INSTANCE.parse(rawInput);\n\t\t\tif (packetLength == 0) {\n\t\t\t\tthrow new IllegalArgumentException(\"Packet length may not be 0\");\n\t\t\t} else if ((packetLength % ALIGNMENT_BYTES) != 0) {\n\t\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\t\"Packet length has to be a multiple of \" + ALIGNMENT_BYTES\n\t\t\t\t\t\t\t\t+ \", is:\" + packetLength);\n\t\t\t}\n\t\t\tfinal ByteBuffer packetBytes = rawInput.slice();\n\t\t\t((Buffer)packetBytes).limit(packetLength);\n\t\t\t((Buffer)rawInput).position(rawInput.position() + packetLength);\n\t\t\tfinal OSCPacket packet = convert(packetBytes);\n\t\t\tbundle.addPacket(packet);\n\t\t}\n\t\treturn bundle;\n\t}\n\n\t/**\n\t * Converts the byte array to a simple message.\n\t * Assumes that the byte array is a message.\n\t * @return a message containing the data specified in the byte stream\n\t */\n\tprivate OSCMessage convertMessage(final ByteBuffer rawInput) throws OSCParseException {\n\n\t\tfinal String address = readString(rawInput);\n\t\tfinal CharSequence typeIdentifiers = readTypes(rawInput);\n\t\t// typeIdentifiers.length() gives us an upper bound for the number of arguments\n\t\t// and a good approximation in general.\n\t\t// It is equal to the number of arguments if there are no arrays.\n\t\tfinal List<Object> arguments = new ArrayList<>(typeIdentifiers.length());\n\t\tfor (int ti = 0; ti < typeIdentifiers.length(); ++ti) {\n\t\t\tif (TYPE_ARRAY_BEGIN == typeIdentifiers.charAt(ti)) {\n\t\t\t\t// we're looking at an array -- read it in\n\t\t\t\targuments.add(readArray(rawInput, typeIdentifiers, ++ti));\n\t\t\t\t// then increment i to the end of the array\n\t\t\t\twhile (typeIdentifiers.charAt(ti) != TYPE_ARRAY_END) {\n\t\t\t\t\tti++;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\targuments.add(readArgument(rawInput, typeIdentifiers.charAt(ti)));\n\t\t\t}\n\t\t}\n\n\t\ttry {\n\t\t\treturn new OSCMessage(address, arguments, new OSCMessageInfo(typeIdentifiers));\n\t\t} catch (final IllegalArgumentException ex) {\n\t\t\tthrow new OSCParseException(ex, rawInput);\n\t\t}\n\t}\n\n\t/**\n\t * Reads a string from the byte stream.\n\t * @return the next string in the byte stream\n\t */\n\tprivate String readString(final ByteBuffer rawInput) throws OSCParseException {\n\t\treturn (String) identifierToType.get('s').parse(rawInput);\n\t}\n\n\t/**\n\t * Reads the types of the arguments from the byte stream.\n\t * @return a char array with the types of the arguments,\n\t * or <code>null</code>, in case of no arguments\n\t */\n\tprivate CharSequence readTypes(final ByteBuffer rawInput) throws OSCParseException {\n\n\t\tfinal String typeTags;\n\t\t// The next byte should be a TYPES_VALUES_SEPARATOR, but some legacy code may omit it\n\t\t// in case of no arguments, according to \"OSC Messages\" in:\n\t\t// http://opensoundcontrol.org/spec-1_0\n\t\tif (rawInput.hasRemaining()) {\n\t\t\tif (rawInput.get(rawInput.position()) == TYPES_VALUES_SEPARATOR) {\n\t\t\t\t// position++ to skip the TYPES_VALUES_SEPARATOR\n\t\t\t\trawInput.get();\n\t\t\t\ttypeTags = readString(rawInput);\n\t\t\t} else {\n\t\t\t\t// data format is invalid\n\t\t\t\tthrow new OSCParseException(\n\t\t\t\t\t\t\"No '\" + TYPES_VALUES_SEPARATOR + \"' present after the address, \"\n\t\t\t\t\t\t\t\t+ \"but there is still more data left in the message\",\n\t\t\t\t\t\trawInput);\n\t\t\t}\n\t\t} else {\n\t\t\t// NOTE Strictly speaking, it is invalid for a message to omit the \"OSC Type Tag String\",\n\t\t\t// even if that message has no arguments.\n\t\t\t// See these two excerpts from the OSC 1.0 specification:\n\t\t\t// 1. \"An OSC message consists of an OSC Address Pattern followed by\n\t\t\t// an OSC Type Tag String followed by zero or more OSC Arguments.\"\n\t\t\t// 2. \"An OSC Type Tag String is an OSC-string beginning with the character ','\"\n\t\t\t// But to be compatible with older OSC implementations,\n\t\t\t// and because it should cause no troubles,\n\t\t\t// we accept this as a valid message anyway.\n\t\t\ttypeTags = NO_ARGUMENT_TYPES;\n\t\t}\n\n\t\treturn typeTags;\n\t}\n\n\t/**\n\t * Reads an object of the type specified by the type char.\n\t * @param typeIdentifier type of the argument to read\n\t * @return a Java representation of the argument\n\t */\n\tprivate Object readArgument(final ByteBuffer rawInput, final char typeIdentifier)\n\t\t\tthrows OSCParseException\n\t{\n\t\tfinal Object argumentValue;\n\n\t\tfinal ArgumentHandler type = identifierToType.get(typeIdentifier);\n\t\tif (type == null) {\n\t\t\tthrow new UnknownArgumentTypeParseException(typeIdentifier, rawInput);\n\t\t} else {\n\t\t\targumentValue = type.parse(rawInput);\n\t\t}\n\n\t\treturn argumentValue;\n\t}\n\n\t/**\n\t * Reads an array of arguments from the byte stream.\n\t * @param typeIdentifiers type identifiers of the whole message\n\t * @param pos at which position to start reading\n\t * @return the array that was read\n\t */\n\tprivate List<Object> readArray(\n\t\t\tfinal ByteBuffer rawInput, final CharSequence typeIdentifiers, final int pos)\n\t\t\tthrows OSCParseException\n\t{\n\t\tint arrayLen = 0;\n\t\twhile (typeIdentifiers.charAt(pos + arrayLen) != TYPE_ARRAY_END) {\n\t\t\tarrayLen++;\n\t\t}\n\t\tfinal List<Object> array = new ArrayList<>(arrayLen);\n\t\tfor (int ai = 0; ai < arrayLen; ai++) {\n\t\t\tarray.add(readArgument(rawInput, typeIdentifiers.charAt(pos + ai)));\n\t\t}\n\t\treturn array;\n\t}\n}",
"public class OSCSerializer {\n\n\t/**\n\t * If a supplied arguments class implements more then one supported argument types,\n\t * there is no solid way to figure out as which one we should interpret and serialize it,\n\t * so we will fail fast.\n\t */\n\tprivate static final int MAX_IMPLEMENTED_ARGUMENT_TYPES = 1;\n\n\t/**\n\t * Intermediate/Mock/Placeholder value indicating the size of a packet.\n\t * It will be used internally, as long as we do not yet know\n\t * the size of the packet in bytes.\n\t * The actual value is arbitrary.\n\t */\n\tprivate static final Integer PACKET_SIZE_PLACEHOLDER = -1;\n\n\tprivate final Logger log = LoggerFactory.getLogger(OSCSerializer.class);\n\n\tprivate final BytesReceiver output;\n\t/**\n\t * Cache for Java classes of which we know, that we have no argument handler\n\t * that supports serializing them.\n\t */\n\tprivate final Set<Class> unsupportedTypes;\n\t/**\n\t * Cache for Java classes that are sub-classes of a supported argument handlers Java class,\n\t * mapped to that base class.\n\t * This does not include base classes\n\t * (Java classes directly supported by one of our argument handlers).\n\t */\n\tprivate final Map<Class, Class> subToSuperTypes;\n\t/**\n\t * For each base-class, indicates whether it is a marker-only type.\n\t * @see ArgumentHandler#isMarkerOnly()\n\t */\n\tprivate final Map<Class, Boolean> classToMarker;\n\t/**\n\t * Maps supported Java class to argument-handlers for all our non-marker-only base-classes.\n\t * @see ArgumentHandler#isMarkerOnly()\n\t */\n\tprivate final Map<Class, ArgumentHandler> classToType;\n\t/**\n\t * Maps values to argument-handlers for all our marker-only base-classes.\n\t * @see ArgumentHandler#isMarkerOnly()\n\t */\n\tprivate final Map<Object, ArgumentHandler> markerValueToType;\n\tprivate final Map<String, Object> properties;\n\n\t/**\n\t * Creates a new serializer with all the required ingredients.\n\t * @param types all of these, and only these arguments will be serializable\n\t * by this object, that are supported by these handlers\n\t * @param properties see {@link ArgumentHandler#setProperties(Map)}\n\t * @param output the output buffer, where raw OSC data is written to\n\t */\n\tpublic OSCSerializer(\n\t\t\tfinal List<ArgumentHandler> types,\n\t\t\tfinal Map<String, Object> properties,\n\t\t\tfinal BytesReceiver output)\n\t{\n\t\tfinal Map<Class, Boolean> classToMarkerTmp = new HashMap<>(types.size());\n\t\tfinal Map<Class, ArgumentHandler> classToTypeTmp = new HashMap<>();\n\t\tfinal Map<Object, ArgumentHandler> markerValueToTypeTmp = new HashMap<>();\n\t\tfor (final ArgumentHandler type : types) {\n\t\t\tfinal Class typeJava = type.getJavaClass();\n\t\t\tfinal Boolean registeredIsMarker = classToMarkerTmp.get(typeJava);\n\t\t\tif ((registeredIsMarker != null) && (registeredIsMarker != type.isMarkerOnly())) {\n\t\t\t\tthrow new IllegalStateException(ArgumentHandler.class.getSimpleName()\n\t\t\t\t\t\t+ \" implementations disagree on the marker nature of their class: \"\n\t\t\t\t\t\t+ typeJava);\n\t\t\t}\n\t\t\tclassToMarkerTmp.put(typeJava, type.isMarkerOnly());\n\n\t\t\tif (type.isMarkerOnly()) {\n\t\t\t\ttry {\n\t\t\t\t\tfinal Object markerValue = type.parse(null);\n\t\t\t\t\tfinal ArgumentHandler previousType = markerValueToTypeTmp.get(markerValue);\n\t\t\t\t\tif (previousType != null) {\n\t\t\t\t\t\tthrow new IllegalStateException(\"Marker value \\\"\" + markerValue\n\t\t\t\t\t\t\t\t+ \"\\\" is already used for type \"\n\t\t\t\t\t\t\t\t+ previousType.getClass().getCanonicalName());\n\t\t\t\t\t}\n\t\t\t\t\tmarkerValueToTypeTmp.put(markerValue, type);\n\t\t\t\t} catch (final OSCParseException ex) {\n\t\t\t\t\tthrow new IllegalStateException(\"Developer error; this should never happen\",\n\t\t\t\t\t\t\tex);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tfinal ArgumentHandler previousType = classToTypeTmp.get(typeJava);\n\t\t\t\tif (previousType != null) {\n\t\t\t\t\tthrow new IllegalStateException(\"Java argument type \"\n\t\t\t\t\t\t\t+ typeJava.getCanonicalName() + \" is already used for type \"\n\t\t\t\t\t\t\t+ previousType.getClass().getCanonicalName());\n\t\t\t\t}\n\t\t\t\tclassToTypeTmp.put(typeJava, type);\n\t\t\t}\n\t\t}\n\n\t\tthis.output = output;\n\t\t// usually, we should not need a stack size of 16, which is the default initial size\n\t\tthis.unsupportedTypes = new HashSet<>(4);\n\t\tthis.subToSuperTypes = new HashMap<>(4);\n\t\t// We create (shallow) copies of these collections,\n\t\t// so if \"the creator\" modifies them after creating us,\n\t\t// we do not get different behaviour during our lifetime,\n\t\t// which might be very confusing to users of this class.\n\t\t// As the copies are not deep though,\n\t\t// It does not protect us from change in behaviour\n\t\t// do to change of the objects themselves,\n\t\t// which are contained in these collections.\n\t\t// TODO instead of these shallow copies, maybe create deep ones?\n\t\tthis.classToMarker = Collections.unmodifiableMap(\n\t\t\t\tnew HashMap<>(classToMarkerTmp));\n\t\tthis.classToType = Collections.unmodifiableMap(\n\t\t\t\tnew HashMap<>(classToTypeTmp));\n\t\tthis.markerValueToType = Collections.unmodifiableMap(\n\t\t\t\tnew HashMap<>(markerValueToTypeTmp));\n\t\tthis.properties = Collections.unmodifiableMap(\n\t\t\t\tnew HashMap<>(properties));\n\t}\n\n\t// Public API\n\t@SuppressWarnings({\"WeakerAccess\", \"unused\"})\n\tpublic Map<Class, ArgumentHandler> getClassToTypeMapping() {\n\t\treturn classToType;\n\t}\n\n\t/**\n\t * Returns the set of properties this parser was created with.\n\t * @return the set of properties to adhere to\n\t * @see ArgumentHandler#setProperties(Map)\n\t */\n\tpublic Map<String, Object> getProperties() {\n\t\treturn properties;\n\t}\n\n\t// Public API\n\t@SuppressWarnings(\"WeakerAccess\")\n\tpublic static byte[] toByteArray(final ByteBuffer buffer) {\n\n\t\tfinal byte[] bytes = new byte[buffer.remaining()];\n\t\tbuffer.get(bytes);\n\t\treturn bytes;\n\t}\n\n\t// Public API\n\t/**\n\t * Terminates the previously written piece of data with a single {@code (byte) '0'}.\n\t * We always need to terminate with a zero, especially when the stream is already aligned.\n\t * @param output to receive the data-piece termination\n\t */\n\t@SuppressWarnings(\"WeakerAccess\")\n\tpublic static void terminate(final BytesReceiver output) {\n\t\toutput.put((byte) 0);\n\t}\n\n\t/**\n\t * Align a buffer by padding it with {@code (byte) '0'}s so it has a size\n\t * divisible by {@link OSCParser#ALIGNMENT_BYTES}.\n\t * @param output to be aligned\n\t * @see OSCParser#align\n\t */\n\tpublic static void align(final BytesReceiver output) {\n\t\tfinal int alignmentOverlap = output.position() % OSCParser.ALIGNMENT_BYTES;\n\t\tfinal int padLen = (OSCParser.ALIGNMENT_BYTES - alignmentOverlap) % OSCParser.ALIGNMENT_BYTES;\n\t\tfor (int pci = 0; pci < padLen; pci++) {\n\t\t\toutput.put((byte) 0);\n\t\t}\n\t}\n\n\t/**\n\t * Terminates the previously written piece of data with a single {@code (byte) '0'},\n\t * and then aligns the stream by padding it with {@code (byte) '0'}s so it has a size\n\t * divisible by {@link OSCParser#ALIGNMENT_BYTES}.\n\t * We always need to terminate with a zero, especially when the stream is already aligned.\n\t * @param output to receive the data-piece termination and alignment\n\t */\n\tpublic static void terminateAndAlign(final BytesReceiver output) {\n\t\tterminate(output);\n\t\talign(output);\n\t}\n\n\tprivate void write(final OSCBundle bundle) throws OSCSerializeException {\n\t\twrite(OSCParser.BUNDLE_START);\n\t\twrite(bundle.getTimestamp());\n\t\tfor (final OSCPacket pkg : bundle.getPackets()) {\n\t\t\twriteSizeAndData(pkg);\n\t\t}\n\t}\n\n\t/**\n\t * Serializes a messages address.\n\t * @param message the address of this message will be serialized\n\t * @throws OSCSerializeException if the message failed to serialize\n\t */\n\tprivate void writeAddress(final OSCMessage message) throws OSCSerializeException {\n\t\twrite(message.getAddress());\n\t}\n\n\t/**\n\t * Serializes the arguments of a message.\n\t * @param message the arguments of this message will be serialized\n\t * @throws OSCSerializeException if the message arguments failed to serialize\n\t */\n\tprivate void writeArguments(final OSCMessage message) throws OSCSerializeException {\n\n\t\toutput.put(OSCParser.TYPES_VALUES_SEPARATOR);\n\t\twriteTypeTags(message.getArguments());\n\t\tfor (final Object argument : message.getArguments()) {\n\t\t\twrite(argument);\n\t\t}\n\t}\n\n\tprivate void write(final OSCMessage message) throws OSCSerializeException {\n\t\twriteAddress(message);\n\t\twriteArguments(message);\n\t}\n\n\t/**\n\t * Converts the packet into its OSC compliant byte array representation,\n\t * then writes the number of bytes to the stream, followed by the actual data bytes.\n\t * @param packet to be converted and written to the stream\n\t * @throws OSCSerializeException if the packet failed to serialize\n\t */\n\tprivate void writeSizeAndData(final OSCPacket packet) throws OSCSerializeException {\n\n\t\tfinal ByteBuffer serializedPacketBuffer = ByteBuffer.allocate(4);\n\t\tfinal BufferBytesReceiver serializedPacketSize = new BufferBytesReceiver(serializedPacketBuffer);\n\t\tfinal ArgumentHandler<Integer> type = findType(PACKET_SIZE_PLACEHOLDER);\n\n\t\tfinal int sizePosition = output.position();\n\t\t// write place-holder size (will be overwritten later)\n\t\ttype.serialize(serializedPacketSize, PACKET_SIZE_PLACEHOLDER);\n\t\tfinal BytesReceiver.PlaceHolder packetSizePlaceholder = output.putPlaceHolder(serializedPacketBuffer.array());\n\t\twritePacket(packet);\n\t\tfinal int afterPacketPosition = output.position();\n\t\tfinal int packetSize = afterPacketPosition - sizePosition - OSCParser.ALIGNMENT_BYTES;\n\n\t\tserializedPacketSize.clear();\n\t\ttype.serialize(serializedPacketSize, packetSize);\n\t\tpacketSizePlaceholder.replace(serializedPacketBuffer.array());\n\t}\n\n\tprivate void writePacket(final OSCPacket packet) throws OSCSerializeException {\n\n\t\tif (packet instanceof OSCBundle) {\n\t\t\twrite((OSCBundle) packet);\n\t\t} else if (packet instanceof OSCMessage) {\n\t\t\twrite((OSCMessage) packet);\n\t\t} else {\n\t\t\tthrow new UnsupportedOperationException(\"We do not support writing packets of type: \"\n\t\t\t\t\t+ packet.getClass());\n\t\t}\n\t}\n\n\tpublic void write(final OSCPacket packet) throws OSCSerializeException {\n\n\t\t// reset position, limit and mark\n\t\toutput.clear();\n\t\ttry {\n\t\t\twritePacket(packet);\n\t\t} catch (final BufferOverflowException ex) {\n\t\t\tthrow new OSCSerializeException(\"Packet is too large for the buffer in use\", ex);\n\t\t}\n\t}\n\n\t/**\n\t * Write only the type tags for a given list of arguments.\n\t * This is primarily used by the packet dispatcher.\n\t * @param arguments to write the type tags from\n\t * @throws OSCSerializeException if the arguments failed to serialize\n\t */\n\tpublic void writeOnlyTypeTags(final List<?> arguments) throws OSCSerializeException {\n\n\t\t// reset position, limit and mark\n\t\toutput.clear();\n\t\ttry {\n\t\t\twriteTypeTagsRaw(arguments);\n\t\t} catch (final BufferOverflowException ex) {\n\t\t\tthrow new OSCSerializeException(\"Type tags are too large for the buffer in use\", ex);\n\t\t}\n\t}\n\n\tprivate Set<ArgumentHandler> findSuperTypes(final Class argumentClass) {\n\n\t\tfinal Set<ArgumentHandler> matchingSuperTypes = new HashSet<>();\n\n\t\t// check all base-classes, for whether our argument-class is a sub-class\n\t\t// of any of them\n\t\tfor (final Map.Entry<Class, ArgumentHandler> baseClassAndType\n\t\t\t\t: classToType.entrySet())\n\t\t{\n\t\t\tfinal Class<?> baseClass = baseClassAndType.getKey();\n\t\t\tif ((baseClass != Object.class)\n\t\t\t\t\t&& baseClass.isAssignableFrom(argumentClass))\n\t\t\t{\n\t\t\t\tmatchingSuperTypes.add(baseClassAndType.getValue());\n\t\t\t}\n\t\t}\n\n\t\treturn matchingSuperTypes;\n\t}\n\n\tprivate Class findSuperType(final Class argumentClass) throws OSCSerializeException {\n\n\t\t// check if we already found the base-class for this argument-class before\n\t\tClass superType = subToSuperTypes.get(argumentClass);\n\t\t// ... if we did not, ...\n\t\tif ((superType == null)\n\t\t\t\t// check if we already know this argument-class to not be supported\n\t\t\t\t&& !unsupportedTypes.contains(argumentClass))\n\t\t{\n\t\t\tfinal Set<ArgumentHandler> matchingSuperTypes = findSuperTypes(argumentClass);\n\t\t\tif (matchingSuperTypes.isEmpty()) {\n\t\t\t\tunsupportedTypes.add(argumentClass);\n\t\t\t} else {\n\t\t\t\tif (matchingSuperTypes.size() > MAX_IMPLEMENTED_ARGUMENT_TYPES) {\n\t\t\t\t\tlog.warn(\"Java class {} is a sub-class of multiple supported argument types:\",\n\t\t\t\t\t\t\targumentClass.getCanonicalName());\n\t\t\t\t\tfor (final ArgumentHandler matchingSuperType : matchingSuperTypes) {\n\t\t\t\t\t\tlog.warn(\"\\t{} (supported by {})\",\n\t\t\t\t\t\t\t\tmatchingSuperType.getJavaClass().getCanonicalName(),\n\t\t\t\t\t\t\t\tmatchingSuperType.getClass().getCanonicalName());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfinal ArgumentHandler matchingSuperType = matchingSuperTypes.iterator().next();\n\t\t\t\tlog.info(\"Java class {} will be mapped to {} (supported by {})\",\n\t\t\t\t\t\targumentClass.getCanonicalName(),\n\t\t\t\t\t\tmatchingSuperType.getJavaClass().getCanonicalName(),\n\t\t\t\t\t\tmatchingSuperType.getClass().getCanonicalName());\n\t\t\t\tfinal Class matchingSuperClass = matchingSuperType.getJavaClass();\n\t\t\t\tsubToSuperTypes.put(argumentClass, matchingSuperClass);\n\t\t\t\tsuperType = matchingSuperClass;\n\t\t\t}\n\t\t}\n\n\t\tif (superType == null) {\n\t\t\tthrow new OSCSerializeException(\"No type handler registered for serializing class \"\n\t\t\t\t\t+ argumentClass.getCanonicalName());\n\t\t}\n\n\t\treturn superType;\n\t}\n\n\tprivate ArgumentHandler findType(final Object argumentValue, final Class argumentClass)\n\t\t\tthrows OSCSerializeException\n\t{\n\t\tfinal ArgumentHandler type;\n\n\t\tfinal Boolean markerType = classToMarker.get(argumentClass);\n\t\tif (markerType == null) {\n\t\t\ttype = findType(argumentValue, findSuperType(argumentClass));\n\t\t} else if (markerType) {\n\t\t\ttype = markerValueToType.get(argumentValue);\n\t\t} else {\n\t\t\ttype = classToType.get(argumentClass);\n\t\t}\n\n\t\treturn type;\n\t}\n\n\tprivate ArgumentHandler findType(final Object argumentValue) throws OSCSerializeException {\n\t\treturn findType(argumentValue, extractTypeClass(argumentValue));\n\t}\n\n\t/**\n\t * Write an object into the byte stream.\n\t * @param anObject (usually) one of Float, Double, String, Character, Integer, Long,\n\t * or a Collection of these.\n\t * See {@link #getClassToTypeMapping()} for a complete list of which classes may be used here.\n\t * @throws OSCSerializeException if the argument object failed to serialize\n\t */\n\tprivate void write(final Object anObject) throws OSCSerializeException {\n\n\t\tif (anObject instanceof Collection) {\n\t\t\t// We can safely suppress the warning, as we already made sure the cast will not fail.\n\t\t\t@SuppressWarnings(\"unchecked\") final Collection<?> theArray = (Collection<?>) anObject;\n\t\t\tfor (final Object entry : theArray) {\n\t\t\t\twrite(entry);\n\t\t\t}\n\t\t} else {\n\t\t\t@SuppressWarnings(\"unchecked\") final ArgumentHandler<Object> type = findType(anObject);\n\t\t\ttype.serialize(output, anObject);\n\t\t}\n\t}\n\n\tprivate static Class extractTypeClass(final Object value) {\n\t\treturn (value == null) ? Object.class : value.getClass();\n\t}\n\n\t/**\n\t * Write the OSC specification type tag for the type a certain Java type\n\t * converts to.\n\t * @param value of this argument, we need to write the type identifier\n\t * @throws OSCSerializeException if the value failed to serialize\n\t */\n\tprivate void writeType(final Object value) throws OSCSerializeException {\n\n\t\tfinal ArgumentHandler type = findType(value);\n\t\toutput.put((byte) type.getDefaultIdentifier());\n\t}\n\n\t/**\n\t * Write the type tags for a given list of arguments.\n\t * @param arguments array of base Objects\n\t * @throws OSCSerializeException if the arguments failed to serialize\n\t */\n\tprivate void writeTypeTagsRaw(final List<?> arguments) throws OSCSerializeException {\n\n\t\tfor (final Object argument : arguments) {\n\t\t\tif (argument instanceof List) {\n\t\t\t\t@SuppressWarnings(\"unchecked\") final List<?> argumentsArray = (List<?>) argument;\n\t\t\t\t// This is used for nested arguments.\n\t\t\t\t// open the array\n\t\t\t\toutput.put((byte) OSCParser.TYPE_ARRAY_BEGIN);\n\t\t\t\t// fill the [] with the nested argument types\n\t\t\t\twriteTypeTagsRaw(argumentsArray);\n\t\t\t\t// close the array\n\t\t\t\toutput.put((byte) OSCParser.TYPE_ARRAY_END);\n\t\t\t} else {\n\t\t\t\t// write a single, simple arguments type\n\t\t\t\twriteType(argument);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Write the type tags for a given list of arguments, and cleanup the stream.\n\t * @param arguments the arguments to an OSCMessage\n\t * @throws OSCSerializeException if the arguments failed to serialize\n\t */\n\tprivate void writeTypeTags(final List<?> arguments) throws OSCSerializeException {\n\n\t\twriteTypeTagsRaw(arguments);\n\t\tterminateAndAlign(output);\n\t}\n}",
"public interface ArgumentHandler<T> extends Cloneable {\n\n\t/**\n\t * Returns the default identifier character of this type of OSC Argument,\n\t * which is the character used in the types string of an OSC Message.\n\t * @return default type identifier, as specified in the OSC specification,\n\t * if this type is part of it\n\t */\n\tchar getDefaultIdentifier();\n\n\t/**\n\t * Returns the Java class this OSC type converts to/from.\n\t * Objects of this class are serialized to this OSC Argument type,\n\t * and this type is parsed into Java Objects of this class.\n\t * @return the Java class this OSC type converts to/from.\n\t */\n\tClass<T> getJavaClass();\n\n\t/**\n\t * Used to configure special properties that might further specify\n\t * parsing and/or serializing objects of this type.\n\t * Most default OSC Argument are \"static\" in this regard,\n\t * as they have a single, not configurable way of operating.\n\t * But the <code>String</code> type for example, allows to specify the character-set.\n\t * This method is usually called once for all types before the parsing/serialization starts.\n\t * Note that this set of properties is parser/serializer global,\n\t * meaning that there is a single set per parser/serializer\n\t * and all the associated handlers,\n\t * which means one has to make sure to not use a single property key\n\t * in multiple places (i.e. two different handlers)\n\t * with different meaning or syntax.\n\t * @param properties a set of properties that usually gets passed over to all types,\n\t * for example: <code>properties.put(StringArgumentHandler.PROP_NAME_CHARSET, Charset.defaultCharset());</code>\n\t */\n\tvoid setProperties(Map<String, Object> properties);\n\n\t/**\n\t * Indicates whether this type is only a marker type,\n\t * meaning all of its information is incorporated in the type identifier,\n\t * and that it comes with no additional data.\n\t * This means that the {@link #parse} and {@link #serialize} methods never throw exceptions,\n\t * and that {@link #parse} always returns the same value, even <code>parse(null)</code>,\n\t * and that {@link #serialize} is basically a no-op.\n\t * @return <code>true</code> if this is only a marker type,\n\t * <code>false</code> if it comes with additional data\n\t */\n\tboolean isMarkerOnly();\n\n\tArgumentHandler<T> clone() throws CloneNotSupportedException;\n\n\t/**\n\t * Converts from the OSC byte representation to a Java object.\n\t * @param input contains the OSC byte representation of one instance of this type.\n\t * The data for this types object starts at the current position.\n\t * Where the end is, depends on the specific type.\n\t * After the invocation of this method, the current position should point at\n\t * the last byte of this types object + 1.\n\t * @return the parsed Java object\n\t * @throws OSCParseException if anything went wrong while parsing,\n\t * for example invalid or incomplete data in the input\n\t */\n\tT parse(ByteBuffer input) throws OSCParseException;\n\n\t/**\n\t * Converts from a Java objects to the OSC byte representation.\n\t * @param output where the OSC byte representation of value has to be written to\n\t * @param value the Java value to be serialized into its OSC byte representation\n\t * @throws OSCSerializeException if anything went wrong while serializing,\n\t * for example an invalid value was given\n\t */\n\tvoid serialize(BytesReceiver output, T value) throws OSCSerializeException;\n}"
] | import com.illposed.osc.BytesReceiver;
import com.illposed.osc.OSCParseException;
import com.illposed.osc.OSCParser;
import com.illposed.osc.OSCSerializer;
import com.illposed.osc.argument.ArgumentHandler;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.util.Map; | // SPDX-FileCopyrightText: 2015-2017 C. Ramakrishnan / Illposed Software
// SPDX-FileCopyrightText: 2021 Robin Vobruba <[email protected]>
//
// SPDX-License-Identifier: BSD-3-Clause
package com.illposed.osc.argument.handler;
/**
* Parses and serializes an OSC string type.
*/
public class StringArgumentHandler implements ArgumentHandler<String>, Cloneable {
// Public API
@SuppressWarnings("WeakerAccess")
public static final char DEFAULT_IDENTIFIER = 's';
public static final String PROP_NAME_CHARSET = "charset";
private Charset charset;
// Public API
@SuppressWarnings("WeakerAccess")
public StringArgumentHandler(final Charset charset) {
this.charset = charset;
}
// Public API
@SuppressWarnings("WeakerAccess")
public StringArgumentHandler() {
this(Charset.defaultCharset());
}
// Public API
/**
* Returns the character-set used to encode and decode string arguments.
* @return the currently used character-encoding-set
*/
@SuppressWarnings("unused")
public Charset getCharset() {
return charset;
}
// Public API
/**
* Sets the character-set used to encode and decode string arguments.
* @param charset the new character-encoding-set
*/
@SuppressWarnings("WeakerAccess")
public void setCharset(final Charset charset) {
this.charset = charset;
}
@Override
public char getDefaultIdentifier() {
return DEFAULT_IDENTIFIER;
}
@Override
public Class<String> getJavaClass() {
return String.class;
}
@Override
public void setProperties(final Map<String, Object> properties) {
final Charset newCharset = (Charset) properties.get(PROP_NAME_CHARSET);
if (newCharset != null) {
setCharset(newCharset);
}
}
@Override
public boolean isMarkerOnly() {
return false;
}
@Override
@SuppressWarnings("unchecked")
public StringArgumentHandler clone() throws CloneNotSupportedException {
return (StringArgumentHandler) super.clone();
}
/**
* Get the length of the string currently in the byte stream.
*/
private int lengthOfCurrentString(final ByteBuffer rawInput) {
int len = 0;
while (rawInput.get(rawInput.position() + len) != 0) {
len++;
}
return len;
}
@Override
public String parse(final ByteBuffer input) throws OSCParseException {
final int strLen = lengthOfCurrentString(input);
final ByteBuffer strBuffer = input.slice();
((Buffer)strBuffer).limit(strLen);
final String res;
try {
res = charset.newDecoder().decode(strBuffer).toString();
} catch (final CharacterCodingException ex) {
throw new OSCParseException(
"Failed decoding a string argument", ex, input
);
}
((Buffer)input).position(input.position() + strLen);
// because strings are always padded with at least one zero,
// as their length is not given in advance, as is the case with blobs,
// we skip over the terminating zero byte (position++)
input.get();
OSCParser.align(input);
return res;
}
@Override
public void serialize(final BytesReceiver output, final String value) {
final byte[] stringBytes = value.getBytes(charset);
output.put(stringBytes); | OSCSerializer.terminateAndAlign(output); | 3 |
raffaeleguidi/DirectMemory | DirectMemory-Cache/src/main/java/org/directmemory/cache/Cache.java | [
"public class Every extends In {\r\n\r\n\tpublic Every(double measure) {\r\n\t\tsuper(measure);\r\n\t}\r\n\r\n}\r",
"public class Ram extends Sizing {\r\n\r\n}\r",
"public class MemoryManager {\r\n\tprivate static Logger logger = LoggerFactory.getLogger(MemoryManager.class);\r\n\tpublic static List<OffHeapMemoryBuffer> buffers = new Vector<OffHeapMemoryBuffer>();\r\n\tpublic static OffHeapMemoryBuffer activeBuffer = null;\r\n\t\r\n\tprivate MemoryManager() {\r\n\t\t//static class\r\n\t}\r\n\t\r\n\tpublic static void init(int numberOfBuffers, int size) {\r\n\t\tfor (int i = 0; i < numberOfBuffers; i++) {\r\n\t\t\tbuffers.add(OffHeapMemoryBuffer.createNew(size, i));\r\n\t\t}\r\n\t\tactiveBuffer = buffers.get(0);\r\n\t\tlogger.info(Format.it(\"MemoryManager initialized - %d buffers, %s each\", numberOfBuffers, Ram.inMb(size)));\r\n\t}\r\n\t\r\n\tpublic static Pointer store(byte[] payload, int expiresIn) {\r\n\t\tPointer p = activeBuffer.store(payload, expiresIn);\r\n\t\tif (p == null) {\r\n\t\t\tif (activeBuffer.bufferNumber+1 == buffers.size()) {\r\n\t\t\t\treturn null;\r\n\t\t\t} else {\r\n\t\t\t\t// try next buffer\r\n\t\t\t\tactiveBuffer = buffers.get(activeBuffer.bufferNumber+1);\r\n\t\t\t\tp = activeBuffer.store(payload, expiresIn);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn p;\r\n\t}\r\n\t\r\n\tpublic static Pointer store(byte[] payload) {\r\n\t\treturn store(payload, 0);\r\n\t}\r\n\t\r\n\tpublic static Pointer update(Pointer pointer, byte[] payload) {\r\n\t\tPointer p = activeBuffer.update(pointer, payload);\r\n\t\tif (p == null) {\r\n\t\t\tif (activeBuffer.bufferNumber == buffers.size()) {\r\n\t\t\t\treturn null;\r\n\t\t\t} else {\r\n\t\t\t\t// try next buffer\r\n\t\t\t\tactiveBuffer = buffers.get(activeBuffer.bufferNumber+1);\r\n\t\t\t\tp = activeBuffer.store(payload);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn p;\r\n\t}\r\n\t\r\n\tpublic static byte[] retrieve(Pointer pointer) {\r\n\t\treturn buffers.get(pointer.bufferNumber).retrieve(pointer);\r\n\t}\r\n\t\r\n\tpublic static void free(Pointer pointer) {\r\n\t\tbuffers.get(pointer.bufferNumber).free(pointer);\r\n\t}\r\n\t\r\n\tpublic static void clear() {\r\n\t\tfor (OffHeapMemoryBuffer buffer : buffers) {\r\n\t\t\tbuffer.clear();\r\n\t\t}\r\n\t\tactiveBuffer = buffers.get(0);\r\n\t}\r\n\t\r\n\tpublic static long capacity() {\r\n\t\tlong totalCapacity = 0;\r\n\t\tfor (OffHeapMemoryBuffer buffer : buffers) {\r\n\t\t\ttotalCapacity += buffer.capacity();\r\n\t\t}\r\n\t\treturn totalCapacity;\r\n\t}\r\n\r\n\tpublic static long collectExpired() {\r\n\t\tlong disposed = 0;\r\n\t\tfor (OffHeapMemoryBuffer buffer : buffers) {\r\n\t\t\tdisposed += buffer.collectExpired();\r\n\t\t}\r\n\t\treturn disposed;\r\n\t}\r\n\r\n\tpublic static void collectLFU() {\r\n\t\tfor (OffHeapMemoryBuffer buf : MemoryManager.buffers) {\r\n\t\t\tbuf.collectLFU(-1);\r\n\t\t}\r\n\t}\r\n\r\n}\r",
"public class OffHeapMemoryBuffer {\r\n\tprivate static Logger logger = LoggerFactory.getLogger(OffHeapMemoryBuffer.class);\r\n\tprotected ByteBuffer buffer;\r\n\tpublic List<Pointer> pointers = new ArrayList<Pointer>();\r\n//\tpublic List<Pointer> pointers = new CopyOnWriteArrayList<Pointer>();\r\n\tAtomicInteger used = new AtomicInteger();\r\n\tpublic int bufferNumber;\r\n\t\r\n\t\r\n\tpublic int used() {\r\n\t\treturn used.get();\r\n\t}\r\n\t\r\n\tpublic int capacity(){\r\n\t\treturn buffer.capacity();\r\n\t}\r\n\t\r\n\tpublic static OffHeapMemoryBuffer createNew(int capacity, int bufferNumber) {\r\n\t\tlogger.info(Format.it(\"Creating OffHeapMemoryBuffer %d with a capacity of %s\", bufferNumber, Ram.inMb(capacity)));\r\n\t\treturn new OffHeapMemoryBuffer(ByteBuffer.allocateDirect(capacity), bufferNumber); \r\n\t}\r\n\t\r\n\tpublic static OffHeapMemoryBuffer createNew(int capacity) {\r\n\t\treturn new OffHeapMemoryBuffer(ByteBuffer.allocateDirect(capacity), -1); \r\n\t}\r\n\t\r\n\tprivate OffHeapMemoryBuffer(ByteBuffer buffer, int bufferNumber) {\r\n\t\tthis.buffer = buffer;\r\n\t\tthis.bufferNumber = bufferNumber;\r\n\t\tcreateAndAddFirstPointer();\r\n\t}\r\n\r\n\tprivate Pointer createAndAddFirstPointer() {\r\n\t\tPointer first = new Pointer();\r\n\t\tfirst.bufferNumber = bufferNumber;\r\n\t\tfirst.start = 0;\r\n\t\tfirst.free = true;\r\n\t\tfirst.end = buffer.capacity()-1;\r\n\t\tpointers.add(first);\r\n\t\treturn first;\r\n\t}\r\n\t\r\n\tpublic Pointer slice(Pointer existing, int capacity) {\r\n\t\tPointer fresh = new Pointer();\r\n\t\tfresh.bufferNumber = existing.bufferNumber;\r\n\t\tfresh.start = existing.start;\r\n\t\tfresh.end = fresh.start+capacity;\r\n\t\tfresh.free = true;\r\n\t\texisting.start+=capacity+1;\r\n\t\treturn fresh;\r\n\t}\r\n\r\n\t\r\n\tpublic Pointer firstMatch(int capacity) {\r\n\t\tfor (Pointer ptr : pointers) {\r\n\t\t\tif (ptr.free && ptr.end >= capacity) {\r\n\t\t\t\treturn ptr;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn null;\r\n\t}\r\n\t\r\n\tpublic Pointer store(byte[] payload) {\r\n\t\treturn store(payload, -1);\r\n\t}\r\n\t\r\n\tpublic byte[] retrieve(Pointer pointer) {\r\n//\t\tif (!pointer.expired()) {\r\n\t\t\tpointer.lastHit = System.currentTimeMillis();\r\n\t\t\tpointer.hits++;\r\n\t\t\t\r\n\t\t\tByteBuffer buf = null;\r\n\t\t\tsynchronized (buffer) {\r\n\t\t\t\tbuf = buffer.duplicate();\r\n\t\t\t}\r\n\t\t\tbuf.position(pointer.start);\r\n\t\t\t// not needed for reads\r\n\t\t\t// buf.limit(pointer.end+pointer.start);\r\n\t\t\tfinal byte[] swp = new byte[pointer.end-pointer.start];\r\n\t\t\tbuf.get(swp);\r\n\t\t\treturn swp;\r\n//\t\t} else {\r\n//\t\t\tfree(pointer);\r\n//\t\t\treturn null;\r\n//\t\t}\r\n\t}\r\n\t\r\n\t\r\n\tpublic long free(Pointer pointer2free) {\r\n\t\tpointer2free.free = true;\r\n\t\tpointer2free.created = 0;\r\n\t\tpointer2free.lastHit = 0;\r\n\t\tpointer2free.hits = 0;\r\n\t\tpointer2free.expiresIn = 0;\r\n\t\tpointer2free.clazz = null;\r\n\t\tused.addAndGet(-( pointer2free.end-pointer2free.start));\r\n\t\tpointers.add(pointer2free);\r\n\t\treturn pointer2free.end-pointer2free.start;\r\n\t}\r\n\t\r\n\tpublic void clear() {\r\n\t\tpointers.clear();\r\n\t\tcreateAndAddFirstPointer();\r\n\t\tbuffer.clear();\r\n\t\tused.set(0);\r\n\t}\r\n\r\n\tpublic Pointer store(byte[] payload, Date expires) {\r\n\t\treturn store(payload, 0, expires.getTime());\r\n\t}\r\n\t\r\n\tpublic Pointer store(byte[] payload, long expiresIn) {\r\n\t\treturn store(payload, expiresIn, 0);\r\n\t}\r\n\t\r\n\tprivate synchronized Pointer store(byte[] payload, long expiresIn, long expires) {\r\n\t\tPointer goodOne = firstMatch(payload.length);\r\n\t\t\r\n\t\tif (goodOne == null ) {\r\n\t\t\tthrow new NullPointerException(\"did not find a suitable buffer\");\r\n\t\t}\r\n\t\t\r\n\t\tPointer fresh = slice(goodOne, payload.length);\r\n\r\n\r\n\t\tfresh.created = System.currentTimeMillis();\r\n\t\tif (expiresIn > 0) {\r\n\t\t\tfresh.expiresIn = expiresIn;\r\n\t\t\tfresh.expires = 0;\r\n\t\t} else if (expires > 0) {\r\n\t\t\tfresh.expiresIn = 0;\r\n\t\t\tfresh.expires = expires;\r\n\t\t}\r\n\t\t\r\n\t\tfresh.free = false;\r\n\t\tused.addAndGet(payload.length);\r\n\t\tByteBuffer buf = buffer.slice();\r\n\t\tbuf.position(fresh.start);\r\n\t\ttry {\r\n\t\t\tbuf.put(payload);\r\n\t\t} catch (BufferOverflowException e) {\r\n\t\t\t// RpG not convincing - let's fix it later\r\n\t\t\tgoodOne.start = fresh.start;\r\n\t\t\tgoodOne.end = buffer.limit();\r\n\t\t\treturn null;\r\n\t\t}\r\n\t\tpointers.add(fresh);\r\n\t\treturn fresh;\r\n\t}\r\n\t\r\n\tprivate QueryResults select(String whereClause) throws QueryParseException, QueryExecutionException {\r\n\t\tQuery q = new Query ();\r\n\t\tq.parse (\"SELECT * FROM \" + Pointer.class.getCanonicalName() + \" WHERE \" + whereClause);\r\n\t\tQueryResults qr = q.execute (pointers);\r\n\t\treturn qr;\r\n\t}\r\n\t\r\n\tprivate QueryResults selectOrderBy(String whereClause, String orderBy, String limit) throws QueryParseException, QueryExecutionException {\r\n\t\tQuery q = new Query ();\r\n\t\tq.parse (\"SELECT * FROM \" + Pointer.class.getCanonicalName() + \" WHERE \" + whereClause + \" order by \" + orderBy + \" \" + limit);\r\n\t\tQueryResults qr = q.execute (pointers);\r\n\t\treturn qr;\r\n\t}\r\n\t\r\n\tpublic long collectLFU(int limit) {\r\n\t\tif (limit<=0) limit = pointers.size()/10;\r\n\t\tQueryResults qr;\r\n\t\ttry {\r\n\t\t\tqr = selectOrderBy(\"free=false\", \"frequency\", \"limit 1, \" + limit);\r\n\t\t\t@SuppressWarnings(\"unchecked\")\r\n\t\t\tList<Pointer> result = qr.getResults();\r\n\t\t\treturn free(result);\r\n\t\t} catch (QueryParseException e) {\r\n\t\t\t// TODO Auto-generated catch block\r\n\t\t\te.printStackTrace();\r\n\t\t} catch (QueryExecutionException e) {\r\n\t\t\t// TODO Auto-generated catch block\r\n\t\t\te.printStackTrace();\r\n\t\t}\r\n\t\treturn 0;\r\n\t} \r\n\t\r\n\t\r\n\t\r\n\t@SuppressWarnings(\"unchecked\")\r\n\tprivate List<Pointer> filter(final String whereClause) {\r\n\t\ttry {\r\n\t\t\treturn select(whereClause).getResults();\r\n\t\t} catch (QueryParseException e) {\r\n\t\t\te.printStackTrace();\r\n\t\t} catch (QueryExecutionException e) {\r\n\t\t\te.printStackTrace();\r\n\t\t}\r\n\t\treturn (List<Pointer>) new ArrayList<Pointer>();\r\n\t}\r\n\t\r\n\tprivate long free(List<Pointer> pointers) {\r\n\t\tlong howMuch = 0;\r\n\t\tfor (Pointer expired : pointers) {\r\n\t\t\thowMuch += free(expired);\r\n\t\t}\r\n\t\treturn howMuch;\r\n\t}\r\n\t\r\n\tpublic void disposeExpiredRelative() {\r\n\t\tfree(filter(\"free=false and expiresIn > 0 and (expiresIn+created) <= \" + System.currentTimeMillis()));\r\n\t}\r\n\t\r\n\tpublic void disposeExpiredAbsolute() {\r\n\t\tfree(filter(\"free=false and expires > 0 and (expires) <= \" + System.currentTimeMillis()));\r\n\t}\r\n\t\r\n\tpublic long collectExpired() {\r\n\t\tint limit = 50;\r\n\t\tlong disposed = free(filter(\"free=false and expiresIn > 0 and (expiresIn+created) <= \" + System.currentTimeMillis() + \" limit 1, \" + limit));\r\n\t\tdisposed += free(filter(\"free=false and expires > 0 and (expires) <= \" + System.currentTimeMillis() + \" limit 1, 100\" + limit));\r\n\t\treturn disposed;\r\n\t}\r\n\t\r\n\tpublic static long crc32(byte[] payload) {\r\n\t\tfinal Checksum checksum = new CRC32();\r\n\t\tchecksum.update(payload,0,payload.length);\r\n\t\treturn checksum.getValue();\r\n\t}\r\n\r\n\tpublic Pointer update(Pointer pointer, byte[] payload) {\r\n\t\tfree(pointer);\r\n\t\treturn store(payload);\r\n\t}\r\n\t\r\n}\r",
"public class Pointer {\r\n\tpublic int start;\r\n\tpublic int end;\r\n\tpublic long created;\r\n\tpublic long expires;\r\n\tpublic long expiresIn;\r\n\tpublic long hits;\r\n\tpublic boolean free;\r\n\tpublic long lastHit;\r\n\tpublic int bufferNumber;\r\n\tpublic Class<? extends Object> clazz;\r\n\t\r\n\tpublic byte[] content() {\r\n\t\treturn null;\r\n\t}\r\n\tpublic boolean expired() {\r\n\t\tif (expires > 0 || expiresIn > 0) { \r\n\t\t\treturn (expiresIn + created < System.currentTimeMillis());\r\n\t\t} else {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic float getFrequency() {\r\n\t\treturn (float)(System.currentTimeMillis()-created)/hits;\r\n\t}\r\n}\r",
"public class Format {\r\n\t\r\n\tpublic static String it(String string, Object ... args) {\r\n\t\tjava.util.Formatter formatter = new java.util.Formatter();\r\n\t\treturn formatter.format(string, args).toString();\r\n\t}\r\n\t\r\n\tpublic static String logo() {\r\n return\r\n\" ____ _ __ __ ___\\r\\n\" + \r\n\" / __ \\\\(_)________ _____/ /_/ |/ /___ ____ ___ ____ _______ __\\r\\n\" + \r\n\" / / / / // ___/ _ \\\\/ ___/ __/ /|_/ // _ \\\\/ __ `__ \\\\/ __ \\\\/ ___/ / / /\\r\\n\" +\r\n\" / /_/ / // / / __/ /__/ /_/ / / // __/ / / / / / /_/ / / / /_/ / \\r\\n\" +\r\n\" /_____/_//_/ \\\\___/\\\\___/\\\\__/_/ /_/ \\\\___/_/ /_/ /_/\\\\____/_/ \\\\__, /\\r\\n\" +\r\n\" /____/ \";\r\n\t \r\n// return\r\n//\t\t \" ___ _ _ _\\r\\n\" + \r\n//\t\t \" ( / \\\\ o _/_( / ) )\\r\\n\" + \r\n//\t\t \" / /, _ _ _, / / / / _ _ _ _ __ _ __ ,\\r\\n\" + \r\n//\t\t \"(/\\\\_/ (_/ (_(/_(__(__ / / (_(/_/ / / /_(_)/ (_/ (_/_\\r\\n\" + \r\n//\t\t \" /\\r\\n\" + \r\n//\t\t \" '\"; \r\n\t}\r\n\r\n}\r",
"public class ProtoStuffSerializerV1 implements Serializer {\r\n\t\r\n\tstatic int serBufferSize = Ram.Kb(3);\r\n//\tstatic int serBufferSize = 300;\r\n\t\r\n\t/* (non-Javadoc)\r\n\t * @see org.directmemory.utils.Serializer#serialize(java.lang.Object, java.lang.Class)\r\n\t */\r\n\t@SuppressWarnings(\"unchecked\")\r\n\tpublic byte[] serialize(Object obj, @SuppressWarnings(\"rawtypes\") Class clazz) throws IOException {\r\n\t\t@SuppressWarnings(\"rawtypes\")\r\n\t\tSchema schema = RuntimeSchema.getSchema(clazz);\r\n\t\tfinal LinkedBuffer buffer = LinkedBuffer.allocate(serBufferSize);\r\n\t\tbyte[] protostuff = null;\r\n\r\n\t\ttry {\r\n\t\t\tprotostuff = ProtostuffIOUtil.toByteArray(obj, schema, buffer);\r\n\t\t} finally {\r\n\t\t\tbuffer.clear();\r\n\t\t}\t\t\r\n\t\treturn protostuff;\r\n\t}\r\n\r\n\t/* (non-Javadoc)\r\n\t * @see org.directmemory.utils.Serializer#deserialize(byte[], java.lang.Class)\r\n\t */\r\n\t@SuppressWarnings(\"unchecked\")\r\n\tpublic Object deserialize(byte[] source, @SuppressWarnings(\"rawtypes\") Class clazz) throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException {\r\n\t\tfinal Object object = clazz.newInstance();\r\n\t\t@SuppressWarnings(\"rawtypes\")\r\n\t\tfinal Schema schema = RuntimeSchema.getSchema(clazz);\r\n\t\tProtostuffIOUtil.mergeFrom(source, object, schema);\r\n\t\treturn object;\r\n\t}\t\r\n}\r",
"public interface Serializer {\r\n\r\n\tpublic abstract byte[] serialize(Object obj, @SuppressWarnings({\"rawtypes\",\"unchecked\"}) Class clazz) throws IOException;\r\n\r\n\tpublic abstract Object deserialize(byte[] source, @SuppressWarnings({\"rawtypes\",\"unchecked\"}) Class clazz) throws IOException,\r\n\t\t\tClassNotFoundException, InstantiationException, IllegalAccessException, EOFException;\r\n\r\n}"
] | import java.io.EOFException;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentMap;
import org.directmemory.measures.Every;
import org.directmemory.measures.Ram;
import org.directmemory.memory.MemoryManager;
import org.directmemory.memory.OffHeapMemoryBuffer;
import org.directmemory.memory.Pointer;
import org.directmemory.misc.Format;
import org.directmemory.serialization.ProtoStuffSerializerV1;
import org.directmemory.serialization.Serializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.MapMaker;
|
public static Pointer put(String key, Object object, int expiresIn) {
try {
byte[] payload = serializer.serialize(object, object.getClass());
Pointer ptr = putByteArray(key, payload);
ptr.clazz = object.getClass();
return ptr;
} catch (IOException e) {
logger.error(e.getMessage());
return null;
}
}
public static Pointer updateByteArray(String key, byte[] payload) {
Pointer p = map.get(key);
p = MemoryManager.update(p, payload);
return p;
}
public static Pointer update(String key, Object object) {
Pointer p = map.get(key);
try {
p = MemoryManager.update(p, serializer.serialize(object, object.getClass()));
p.clazz = object.getClass();
return p;
} catch (IOException e) {
logger.error(e.getMessage());
return null;
}
}
public static byte[] retrieveByteArray(String key) {
Pointer ptr = getPointer(key);
if (ptr == null) return null;
if (ptr.expired() || ptr.free) {
map.remove(key);
if (!ptr.free) {
MemoryManager.free(ptr);
}
return null;
} else {
return MemoryManager.retrieve(ptr);
}
}
public static Object retrieve(String key) {
Pointer ptr = getPointer(key);
if (ptr == null) return null;
if (ptr.expired() || ptr.free) {
map.remove(key);
if (!ptr.free) {
MemoryManager.free(ptr);
}
return null;
} else {
try {
return serializer.deserialize(MemoryManager.retrieve(ptr),ptr.clazz);
} catch (EOFException e) {
logger.error(e.getMessage());
} catch (IOException e) {
logger.error(e.getMessage());
} catch (ClassNotFoundException e) {
logger.error(e.getMessage());
} catch (InstantiationException e) {
logger.error(e.getMessage());
} catch (IllegalAccessException e) {
logger.error(e.getMessage());
}
}
return null;
}
public static Pointer getPointer(String key) {
return map.get(key);
}
public static void free(String key) {
Pointer p = map.remove(key);
if (p != null) {
MemoryManager.free(p);
}
}
public static void free(Pointer pointer) {
MemoryManager.free(pointer);
}
public static void collectExpired() {
MemoryManager.collectExpired();
// still have to look for orphan (storing references to freed pointers) map entries
}
public static void collectLFU() {
MemoryManager.collectLFU();
// can possibly clear one whole buffer if it's too fragmented - investigate
}
public static void collectAll() {
Thread thread = new Thread(){
public void run(){
logger.info("begin disposal");
collectExpired();
collectLFU();
logger.info("disposal complete");
}
};
thread.start();
}
public static void clear() {
map.clear();
MemoryManager.clear();
logger.info("Cache cleared");
}
public static long entries() {
return map.size();
}
| private static void dump(OffHeapMemoryBuffer mem) {
| 3 |
caseydavenport/biermacht | src/com/biermacht/brews/xml/RecipeXmlWriter.java | [
"public class Fermentable extends Ingredient implements Parcelable {\n\n // Beer XML 1.0 Required Fields ===================================\n // ================================================================\n // Name - Inherited\n // Version - Inherited\n private String type; // Grain, Extract, Adjunct\n private double yield; // Dry yeild / raw yield\n private double color; // Color in Lovibond (SRM)\n\n // Beer XML 1.0 Optional Fields ===================================\n // ================================================================\n private boolean addAfterBoil; // True if added after boil\n private double maxInBatch; // Max reccomended in this batch\n\n // Custom Fields ==================================================\n // ================================================================\n private String description; // Description of fermentable\n\n // Static values =================================================\n // ===============================================================\n public static final String TYPE_GRAIN = \"Grain\";\n public static final String TYPE_EXTRACT = \"Extract\";\n public static final String TYPE_ADJUNCT = \"Adjunct\";\n public static final String TYPE_SUGAR = \"Sugar\";\n\n public Fermentable(String name) {\n super(name);\n this.type = TYPE_GRAIN;\n this.amount = 0;\n this.yield = 1;\n this.color = 0;\n this.addAfterBoil = false;\n this.setMaxInBatch(0);\n this.description = \"No description provided.\";\n }\n\n public Fermentable(Parcel p) {\n super(p);\n type = p.readString();\n yield = p.readDouble();\n color = p.readDouble();\n addAfterBoil = p.readInt() > 0;\n maxInBatch = p.readDouble();\n description = p.readString();\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel p, int flags) {\n super.writeToParcel(p, flags);\n p.writeString(type); // Grain, Extract, Adjunct\n p.writeDouble(yield); // Dry yeild / raw yield\n p.writeDouble(color); // Color in Lovibond (SRM)\n p.writeInt(addAfterBoil ? 1 : 0); // True if added after boil\n p.writeDouble(maxInBatch); // Max reccomended in this batch\n p.writeString(description); // Description of fermentable\n }\n\n public static final Parcelable.Creator<Fermentable> CREATOR =\n new Parcelable.Creator<Fermentable>() {\n @Override\n public Fermentable createFromParcel(Parcel p) {\n return new Fermentable(p);\n }\n\n @Override\n public Fermentable[] newArray(int size) {\n return null;\n }\n };\n\n @Override\n public String getType() {\n return Ingredient.FERMENTABLE;\n }\n\n public double getLovibondColor() {\n color = (float) Math.round(color * 10) / 10;\n return color;\n }\n\n public void setLovibondColor(double color) {\n color = (float) Math.round(color * 10) / 10;\n this.color = color;\n }\n\n public double getGravity() {\n return yieldToGravity(yield);\n }\n\n public void setGravity(double gravity) {\n this.yield = gravityToYield(gravity);\n }\n\n public float getPpg() {\n return (float) (this.yield * 46) / 100;\n }\n\n public String getFermentableType() {\n return type;\n }\n\n public void setFermentableType(String type) {\n if (! Constants.FERMENTABLE_TYPES.contains(type)) {\n Log.e(\"Fermentable\", \"Setting invalid fermentable type: \" + type);\n }\n this.type = type;\n }\n\n @Override\n public double getDisplayAmount() {\n if (getDisplayUnits().equals(Units.POUNDS)) {\n return Units.kilosToPounds(this.amount);\n }\n else {\n return this.amount;\n }\n }\n\n @Override\n public double getBeerXmlStandardAmount() {\n return this.amount;\n }\n\n @Override\n public void setDisplayAmount(double amt) {\n if (getDisplayUnits().equals(Units.POUNDS)) {\n this.amount = Units.poundsToKilos(amt);\n }\n else {\n this.amount = amt;\n }\n }\n\n @Override\n public void setBeerXmlStandardAmount(double amt) {\n this.amount = amt;\n }\n\n @Override\n public int hashCode() {\n int hc = this.getName().hashCode();\n hc += this.getLovibondColor();\n hc |= (int) this.getGravity() * 1234;\n hc += (int) this.getBeerXmlStandardAmount();\n hc |= this.getType().hashCode();\n return hc;\n }\n\n @Override\n public String getDisplayUnits() {\n return Units.getFermentableUnits();\n }\n\n @Override\n public void setDisplayUnits(String s) {\n }\n\n @Override\n public String getBeerXmlStandardUnits() {\n return Units.KILOGRAMS;\n }\n\n /**\n * Evaluates equality of this Fermentable and the given Object.\n *\n * @param o\n * @return true if this Fermentable equals Object o, false otherwise.\n */\n @Override\n public boolean equals(Object o) {\n if (o instanceof Fermentable) {\n // Compare to other.\n return this.compareTo((Fermentable) o) == 0;\n }\n\n // Not a fermentable, and so is not equal.\n return false;\n }\n\n @Override\n public int getTime() {\n return time;\n }\n\n @Override\n public void setTime(int time) {\n this.time = time;\n }\n\n /**\n * @return the yield\n */\n public double getYield() {\n return yield;\n }\n\n /**\n * @param yield\n * the yield to set\n */\n public void setYield(double yield) {\n this.yield = yield;\n }\n\n /**\n * @return the addAfterBoil\n */\n public boolean isAddAfterBoil() {\n return addAfterBoil;\n }\n\n /**\n * @param addAfterBoil\n * the addAfterBoil to set\n */\n public void setAddAfterBoil(boolean addAfterBoil) {\n this.addAfterBoil = addAfterBoil;\n }\n\n @Override\n public void setShortDescription(String description) {\n this.description = description;\n }\n\n @Override\n public String getShortDescription() {\n return this.description;\n }\n\n /**\n * @return the maxInBatch\n */\n public double getMaxInBatch() {\n return maxInBatch;\n }\n\n @Override\n public String getUse() {\n if (this.getFermentableType().equals(TYPE_EXTRACT) ||\n this.getFermentableType().equals(TYPE_SUGAR)) {\n // Sugars and Extracts should be boiled.\n return Ingredient.USE_BOIL;\n }\n else {\n // Everything else should be mashed. Grains, Adjuncts.\n return Ingredient.USE_MASH;\n }\n }\n\n /**\n * @param maxInBatch\n * the maxInBatch to set\n */\n public void setMaxInBatch(double maxInBatch) {\n this.maxInBatch = maxInBatch;\n }\n\n /**\n * Turns given gravity into a yield\n *\n * @param gravity\n * @return\n */\n public double gravityToYield(double gravity) {\n double yield = 0;\n\n yield = gravity - 1;\n yield = yield * 1000;\n yield = yield * 100 / 46;\n\n return yield;\n }\n\n /**\n *\n * @return The gravity points contributed by this fermentable.\n */\n public double gravityPoints() {\n return this.getPpg() * Units.kilosToPounds(this.amount);\n }\n\n /**\n * turns given yield into a gravity\n *\n * @param yield\n * @return\n */\n public double yieldToGravity(double yield) {\n return 1 + (((yield * 46) / 100) / 1000);\n }\n\n /**\n * Compares the given Ingredient to this Fermentable and returns and indicator of (in)equality.\n *\n * @param other\n * The Ingredient with which to compare this Fermentable\n * @return 0 if argument is equal to this, < 0 if argument is greater than this, > 0 if argument\n * is less than this\n */\n @Override\n public int compareTo(Ingredient other) {\n // If not the same type of Ingredient, sort based on Ingredient type.\n int typeCompare = this.getType().compareTo(other.getType());\n if (typeCompare != 0) {\n return typeCompare;\n }\n Fermentable f = (Fermentable) other;\n\n // If they are both Fermentables, sort based on amount.\n int amountCompare = Double.compare(f.getBeerXmlStandardAmount(), this.getBeerXmlStandardAmount());\n if (amountCompare != 0) {\n return amountCompare;\n }\n\n // Sort based on name.\n int nameCompare = this.getName().compareTo(f.getName());\n if (nameCompare != 0) {\n return nameCompare;\n }\n\n // Sort based on color.\n int colorCompare = Double.compare(this.getLovibondColor(), f.getLovibondColor());\n if (colorCompare != 0) {\n return colorCompare;\n }\n\n // Sort based on gravity.\n int gravCompare = Double.compare(this.getGravity(), f.getGravity());\n if (gravCompare != 0) {\n return gravCompare;\n }\n\n // If all the above are equal, they are the same.\n return 0;\n }\n}",
"public class Hop extends Ingredient {\n\n // Beer XML 1.0 Required Fields ===================================\n // ================================================================\n\n // Name - Inherited\n // Version - Inherited\n private double alpha; // Alpha in %\n private String use; // Boil, Dry Hop, etc\n\n // Beer XML 1.0 Optional Fields ===================================\n // ================================================================\n private String type; // Bittering, Armoa, Both\n private String form; // Pellet, plug, whole\n private String origin; // Place of origin\n private ArrayList<String> substitutes; // Substitute options\n\n // Custom Fields ==================================================\n // ================================================================\n private String description; // Short description of flavor / use\n\n // Static values =================================================\n // ===============================================================\n public static final String FORM_PELLET = \"Pellet\";\n public static final String FORM_WHOLE = \"Whole\";\n public static final String FORM_PLUG = \"Plug\";\n\n // Hop types\n public static final String TYPE_BITTERING = \"Bittering\";\n public static final String TYPE_AROMA = \"Aromatic\";\n public static final String TYPE_BOTH = \"Bittering / Aromatic\";\n\n public Hop(String name) {\n super(name);\n this.amount = 0;\n this.alpha = 0;\n this.use = USE_BOIL;\n this.type = TYPE_BOTH;\n this.form = FORM_PELLET;\n this.origin = \"\";\n this.substitutes = new ArrayList<String>(); // TODO Get this from somewhere\n this.description = \"No description\";\n }\n\n public Hop(Parcel p) {\n super(p);\n this.substitutes = new ArrayList<String>();\n alpha = p.readDouble();\n use = p.readString();\n\n type = p.readString();\n form = p.readString();\n origin = p.readString();\n p.readStringList(this.substitutes);\n description = p.readString();\n }\n\n @Override\n public void writeToParcel(Parcel p, int flags) {\n super.writeToParcel(p, flags);\n\n // Required\n p.writeDouble(alpha);\n p.writeString(use);\n\n // Optional\n p.writeString(type);\n p.writeString(form);\n p.writeString(origin);\n p.writeStringList(substitutes);\n p.writeString(description);\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n public static final Parcelable.Creator<Hop> CREATOR =\n new Parcelable.Creator<Hop>() {\n @Override\n public Hop createFromParcel(Parcel p) {\n return new Hop(p);\n }\n\n @Override\n public Hop[] newArray(int size) {\n return null;\n }\n };\n\n @Override\n public String getType() {\n return Ingredient.HOP;\n }\n\n public String getDescription() {\n return description;\n }\n\n public void setDescription(String description) {\n this.description = description;\n }\n\n public double getAlphaAcidContent() {\n return alpha;\n }\n\n public void setAlphaAcidContent(double alpha) {\n this.alpha = alpha;\n }\n\n @Override\n public String getShortDescription() {\n return this.description;\n }\n\n @Override\n public double getDisplayAmount() {\n if (getDisplayUnits().equals(Units.OUNCES)) {\n return Units.kilosToOunces(this.amount);\n }\n else {\n return Units.kilosToGrams(this.amount);\n }\n }\n\n public int getDisplayTime() {\n if (this.getUse().equals(Hop.USE_DRY_HOP)) {\n return (int) Units.minutesToDays(this.time);\n }\n else {\n return this.time;\n }\n }\n\n public void setDisplayTime(int time) {\n if (this.getUse().equals(Hop.USE_DRY_HOP)) {\n this.time = (int) Units.daysToMinutes(time);\n }\n else {\n this.time = time;\n }\n }\n\n @Override\n public double getBeerXmlStandardAmount() {\n return this.amount;\n }\n\n @Override\n public void setDisplayAmount(double amt) {\n if (getDisplayUnits().equals(Units.OUNCES)) {\n this.amount = Units.ouncesToKilos(amt);\n }\n else {\n this.amount = Units.gramsToKilos(amt);\n }\n }\n\n @Override\n public void setBeerXmlStandardAmount(double amt) {\n this.amount = amt;\n }\n\n public String getForm() {\n return form;\n }\n\n public void setForm(String form) {\n this.form = form;\n }\n\n @Override\n public String getDisplayUnits() {\n return Units.getHopUnits();\n }\n\n public void setDisplayUnits(String s) {\n }\n\n @Override\n public String getBeerXmlStandardUnits() {\n return Units.KILOGRAMS;\n }\n\n @Override\n public int hashCode() {\n int hc = this.getName().hashCode();\n hc = hc ^ (int) (getAlphaAcidContent() * 1234);\n hc += this.getTime();\n hc += this.getUse().hashCode();\n hc += this.getType().hashCode();\n return hc;\n }\n\n @Override\n public boolean equals(Object o) {\n if (o instanceof Hop) {\n return this.compareTo((Hop) o) == 0;\n }\n return false;\n }\n\n /**\n * @return the use\n */\n public String getUse() {\n return use;\n }\n\n /**\n * @param use\n * the use to set\n */\n public void setUse(String use) {\n this.use = use;\n }\n\n /**\n * @return the time\n */\n public int getBeerXmlStandardTime() {\n return time;\n }\n\n @Override\n public int getTime() {\n return this.getDisplayTime();\n }\n\n @Override\n public void setTime(int time) {\n setDisplayTime(time);\n }\n\n /**\n * @return the origin\n */\n public String getOrigin() {\n return origin;\n }\n\n /**\n * @param origin\n * the origin to set\n */\n public void setOrigin(String origin) {\n this.origin = origin;\n }\n\n /**\n * @return the substitutes\n */\n public ArrayList<String> getSubstitutes() {\n return substitutes;\n }\n\n /**\n * @param substitutes\n * the substitutes to set\n */\n public void setSubstitutes(ArrayList<String> substitutes) {\n this.substitutes = substitutes;\n }\n\n /**\n * @return the hopType\n */\n public String getHopType() {\n return type;\n }\n\n /**\n * @param type\n * the hopType to set\n */\n public void setHopType(String type) {\n this.type = type;\n }\n\n /**\n * @param time\n * the time to set\n */\n public void setBeerXmlStandardTime(int time) {\n this.time = time;\n }\n\n @Override\n public void setShortDescription(String description) {\n this.description = description;\n }\n\n @Override\n public int compareTo(Ingredient other) {\n // If not the same type, sort based on type.\n int typeCompare = this.getType().compareTo(other.getType());\n if (typeCompare != 0) {\n return typeCompare;\n }\n Hop h = (Hop) other;\n\n // If they are not the same use, sort based on use.\n if (! this.getUse().equals(other.getUse())) {\n return this.getUse().compareTo(other.getUse());\n }\n\n // Sort based on time.\n int timeCompare = Double.compare(h.getTime(), this.getTime());\n if (timeCompare != 0) {\n return timeCompare;\n }\n\n // Sort based on name.\n int nameCompare = this.getName().compareTo(h.getName());\n if (nameCompare != 0) {\n return nameCompare;\n }\n\n // Sort based on alpha acid.\n int alphaCompare = Double.compare(this.getAlphaAcidContent(), h.getAlphaAcidContent());\n if (alphaCompare != 0) {\n return alphaCompare;\n }\n\n // If all else is the same, they are equal.\n return 0;\n }\n}",
"public class Misc extends Ingredient {\n\n // Beer XML 1.0 Required Fields (To be inherited) =================\n // ================================================================\n private String miscType;\n private String use;\n private boolean amountIsWeight;\n private String useFor;\n private String notes;\n\n // Custom Fields ==================================================\n // ================================================================\n private String displayUnits;\n\n // Static values =================================================\n // ===============================================================\n public static String TYPE_SPICE = \"Spice\";\n public static String TYPE_FINING = \"Fining\";\n public static String TYPE_WATER_AGENT = \"Water Agent\";\n public static String TYPE_HERB = \"Herb\";\n public static String TYPE_FLAVOR = \"Flavor\";\n public static String TYPE_OTHER = \"Other\";\n\n public Misc(String name) {\n super(name);\n setDisplayUnits(\"\");\n setAmountIsWeight(false);\n setBeerXmlStandardAmount(0);\n setShortDescription(\"\");\n this.amount = 0;\n setUse(\"\");\n setVersion(1);\n setTime(0);\n setMiscType(TYPE_OTHER);\n }\n\n public Misc(Parcel p) {\n super(p);\n\n // Required\n this.miscType = p.readString();\n this.use = p.readString();\n this.amount = p.readDouble();\n this.amountIsWeight = p.readInt() > 0 ? true : false;\n this.useFor = p.readString();\n this.notes = p.readString();\n\n // Optional\n this.displayUnits = p.readString();\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel p, int flags) {\n super.writeToParcel(p, flags);\n\n // Required\n p.writeString(this.miscType);\n p.writeString(this.use);\n p.writeDouble(this.amount);\n p.writeInt(amountIsWeight ? 1 : 0);\n p.writeString(this.useFor);\n p.writeString(this.notes);\n\n // Optional\n p.writeString(this.displayUnits);\n }\n\n public static final Parcelable.Creator<Misc> CREATOR =\n new Parcelable.Creator<Misc>() {\n @Override\n public Misc createFromParcel(Parcel p) {\n return new Misc(p);\n }\n\n @Override\n public Misc[] newArray(int size) {\n return null;\n }\n };\n\n @Override\n public String toString() {\n return this.getName();\n }\n\n public void setMiscType(String type) {\n this.miscType = type;\n }\n\n public String getMiscType() {\n if (! miscType.isEmpty() || this.miscType == null) {\n return this.miscType;\n }\n else {\n return Misc.TYPE_OTHER;\n }\n }\n\n public String getArrayAdapterDescription() {\n String s = this.getUse() + \", \";\n if (getTime() > 0) {\n s += this.getTime() + \" \" + this.getTimeUnits() + \", \";\n }\n s += getUseFor();\n return s;\n }\n\n public void setUse(String u) {\n this.use = u;\n }\n\n public String getUse() {\n return this.use;\n }\n\n public void setAmountIsWeight(boolean b) {\n this.amountIsWeight = b;\n }\n\n public boolean amountIsWeight() {\n return this.amountIsWeight;\n }\n\n public void setUseFor(String s) {\n this.useFor = s;\n }\n\n public String getUseFor() {\n return this.useFor;\n }\n\n @Override\n public String getType() {\n return Ingredient.MISC;\n }\n\n @Override\n public String getShortDescription() {\n return notes;\n }\n\n @Override\n public double getDisplayAmount() {\n\n String unit = this.getDisplayUnits();\n\n if (unit.equalsIgnoreCase(Units.GALLONS)) {\n return Units.litersToGallons(this.amount);\n }\n else if (unit.equalsIgnoreCase(Units.GRAMS)) {\n return Units.kilosToGrams(this.amount);\n }\n else if (unit.equalsIgnoreCase(Units.MILLIGRAMS)) {\n return Units.kilosToMilligrams(this.amount);\n }\n else if (unit.equalsIgnoreCase(Units.KILOGRAMS)) {\n return this.amount;\n }\n else if (unit.equalsIgnoreCase(Units.LITERS)) {\n return this.amount;\n }\n else if (unit.equalsIgnoreCase(Units.MILLILITERS)) {\n return Units.litersToMillis(this.amount);\n }\n else if (unit.equalsIgnoreCase(Units.TEASPOONS)) {\n return Units.litersToTeaspoons(this.amount);\n }\n else if (unit.equalsIgnoreCase(Units.TABLESPOONS)) {\n return Units.litersToTablespoons(this.amount);\n }\n else if (unit.equalsIgnoreCase(Units.OUNCES)) {\n if (this.amountIsWeight()) {\n return Units.kilosToOunces(this.amount);\n }\n else {\n return Units.litersToOunces(this.amount);\n }\n }\n else if (unit.equalsIgnoreCase(Units.POUNDS)) {\n return Units.kilosToPounds(this.amount);\n }\n else if (unit.equalsIgnoreCase(Units.QUARTS)) {\n return Units.litersToQuarts(this.amount);\n }\n else if (unit.equalsIgnoreCase(Units.PINTS)) {\n return Units.litersToPints(this.amount);\n }\n else if (unit.equalsIgnoreCase(Units.CUP) || unit.equalsIgnoreCase(Units.CUPS)) {\n return Units.litersToCups(this.amount);\n }\n else if (unit.equalsIgnoreCase(Units.ITEMS)) {\n return this.amount;\n }\n else if (unit.equalsIgnoreCase(Units.PACKAGES)) {\n return this.amount;\n }\n else {\n Log.e(\"Misc\", \"Failed to get display amount - bad units? \" + unit);\n return 0; // Should show that we couldn't compute\n }\n }\n\n @Override\n public double getBeerXmlStandardAmount() {\n return this.amount;\n }\n\n @Override\n public void setDisplayAmount(double amt) {\n // Not implemented - must use other method.\n // Get punished! (Can't throw exceptions here, but to make debugging\n // easier lets cause a problem!)\n int x = (Integer) null;\n x = x / 2;\n }\n\n public void setDisplayAmount(double amt, String unit) {\n Log.d(getName() + \"::setDisplayAmount\", \"Setting amt to: \" + amt + \" \" + unit);\n if (unit.equalsIgnoreCase(Units.GALLONS)) {\n this.amount = Units.gallonsToLiters(amt);\n }\n else if (unit.equalsIgnoreCase(Units.GRAMS)) {\n this.amount = Units.gramsToKilos(amt);\n }\n else if (unit.equalsIgnoreCase(Units.MILLIGRAMS)) {\n this.amount = Units.milligramsToKilos(amt);\n }\n else if (unit.equalsIgnoreCase(Units.KILOGRAMS)) {\n this.amount = amt;\n }\n else if (unit.equalsIgnoreCase(Units.LITERS)) {\n this.amount = amt;\n this.amountIsWeight = false;\n }\n else if (unit.equalsIgnoreCase(Units.MILLILITERS)) {\n this.amount = Units.millisToLiters(amt);\n this.amountIsWeight = false;\n }\n else if (unit.equalsIgnoreCase(Units.TEASPOONS)) {\n this.amount = Units.teaspoonsToLiters(amt);\n }\n else if (unit.equalsIgnoreCase(Units.TABLESPOONS)) {\n this.amount = Units.tablespoonsToLiters(amt);\n }\n else if (unit.equalsIgnoreCase(Units.PINTS)) {\n this.amount = Units.pintsToLiters(amt);\n }\n else if (unit.equalsIgnoreCase(Units.OUNCES)) {\n if (this.amountIsWeight()) {\n this.amount = Units.ouncesToKilos(amt);\n }\n else {\n this.amount = Units.ouncesToLiters(amt);\n }\n }\n else if (unit.equalsIgnoreCase(Units.POUNDS)) {\n this.amount = Units.poundsToKilos(amt);\n }\n else if (unit.equalsIgnoreCase(Units.CUP) || unit.equalsIgnoreCase(Units.CUPS)) {\n this.amount = Units.cupsToLiters(amt);\n }\n else if (unit.equalsIgnoreCase(Units.ITEMS)) {\n this.amount = amt;\n }\n else if (unit.equalsIgnoreCase(Units.PACKAGES)) {\n this.amount = amt;\n }\n else {\n this.amount = - 1.0; // Should show that we couldn't compute\n }\n }\n\n @Override\n public void setBeerXmlStandardAmount(double amt) {\n this.amount = amt;\n }\n\n // This method is used when we want the value of the stored displayUnits\n // Not for use to determine the display units.\n public String getUnits() {\n return this.displayUnits;\n }\n\n @Override\n public String getDisplayUnits() {\n // If not, call the appropriate method based on which unit system the user has chosen\n if (Units.getUnitSystem().equals(Units.IMPERIAL)) {\n return getDisplayUnitsImperial();\n }\n else {\n return getDisplayUnitsMetric();\n }\n }\n\n // Called when preferred units are metric\n private String getDisplayUnitsMetric() {\n // First check if we have units specified\n if (! this.displayUnits.equals(\"\")) {\n return Units.getMetricEquivalent(this.displayUnits, this.amountIsWeight);\n }\n\n if (this.amountIsWeight()) {\n if (this.amount > 1) {\n return Units.KILOGRAMS;\n }\n else {\n return Units.GRAMS;\n }\n }\n else if (this.amount > .5) {\n return Units.LITERS;\n }\n else {\n return Units.MILLILITERS;\n }\n }\n\n // Called when preferred units are imperial\n private String getDisplayUnitsImperial() {\n // First check if we have units specified\n if (! this.displayUnits.equals(\"\")) {\n return this.displayUnits;\n }\n\n if (this.amountIsWeight()) {\n if (this.amount > .113)// .25lbs\n {\n return Units.POUNDS;\n }\n else {\n return Units.OUNCES;\n }\n }\n else if (this.amount > .946) // .25gal\n {\n return Units.GALLONS;\n }\n else {\n return Units.OUNCES;\n }\n }\n\n @Override\n public String getBeerXmlStandardUnits() {\n if (this.amountIsWeight()) {\n return Units.KILOGRAMS;\n }\n else {\n return Units.LITERS;\n }\n }\n\n @Override\n public int hashCode() {\n int hc = this.getName().hashCode();\n hc = hc ^ this.use.hashCode();\n hc = hc ^ this.miscType.hashCode();\n hc = hc + this.displayUnits.hashCode();\n hc = hc + this.getTime();\n return hc;\n }\n\n @Override\n public boolean equals(Object o) {\n if (o instanceof Misc) {\n return this.compareTo((Misc) o) == 0;\n }\n return false;\n }\n\n @Override\n public int compareTo(Ingredient other) {\n // If not the same type of Ingredient, sort based on Ingredient type.\n int typeCompare = this.getType().compareTo(other.getType());\n if (typeCompare != 0) {\n return typeCompare;\n }\n Misc m = (Misc) other;\n\n // If they are both Misc, sort based on use.\n int useCompare = this.getUse().compareTo(m.getUse());\n if (useCompare != 0) {\n return useCompare;\n }\n\n // Sort based on time.\n int timeCompare = Double.compare(m.getTime(), this.getTime());\n if (timeCompare != 0) {\n return timeCompare;\n }\n\n // Sort based on name.\n int nameCompare = this.getName().compareTo(m.getName());\n if (nameCompare != 0) {\n return nameCompare;\n }\n\n // Sort based on type.\n int miscTypeCompare = this.getMiscType().compareTo(m.getMiscType());\n if (miscTypeCompare != 0) {\n return miscTypeCompare;\n }\n\n // Sort based on units.\n int unitCompare = this.getDisplayUnits().compareTo(m.getDisplayUnits());\n if (unitCompare != 0) {\n return unitCompare;\n }\n\n // Equal.\n return 0;\n }\n\n @Override\n public int getTime() {\n return time;\n }\n\n @Override\n public void setTime(int i) {\n this.time = i;\n }\n\n public String getTimeUnits() {\n if (use.equals(Misc.USE_PRIMARY) || use.equals(Misc.USE_SECONDARY)) {\n return Units.DAYS;\n }\n else if (use.equals(Misc.USE_BOIL) || use.equals(Misc.USE_MASH)) {\n return Units.MINUTES;\n }\n else {\n return Units.MINUTES;\n }\n }\n\n @Override\n public void setShortDescription(String description) {\n if (description.isEmpty()) {\n description = \"No description provided\";\n }\n this.notes = description;\n }\n\n @Override\n public void setDisplayUnits(String units) {\n this.displayUnits = units;\n }\n}",
"public class Water extends Ingredient {\n public Water(String name) {\n super(name);\n }\n\n public Water(Parcel p) {\n // TODO Implement this?\n this(\"New Water\");\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel p, int flags) {\n\n }\n\n public static final Parcelable.Creator<Water> CREATOR =\n new Parcelable.Creator<Water>() {\n @Override\n public Water createFromParcel(Parcel p) {\n return new Water(p);\n }\n\n @Override\n public Water[] newArray(int size) {\n return new Water[]{};\n }\n };\n\n @Override\n public String getType() {\n return Ingredient.WATER;\n }\n\n @Override\n public String getShortDescription() {\n // TODO Auto-generated method stub\n return null;\n }\n\n public double getDisplayAmount() {\n // TODO: Implement this method\n return 0;\n }\n\n public double getBeerXmlStandardAmount() {\n // TODO: Implement this method\n return 0;\n }\n\n public void setDisplayAmount(double amt) {\n // TODO: Implement this method\n }\n\n public void setBeerXmlStandardAmount(double amt) {\n // TODO: Implement this method\n }\n\n @Override\n public String getDisplayUnits() {\n // TODO Auto-generated method stub\n return null;\n }\n\n @Override\n public void setDisplayUnits(String units) {\n // TODO Auto-generated method stub\n\n }\n\n public String getBeerXmlStandardUnits() {\n // TODO: Implement this method\n return Units.LITERS;\n }\n\n @Override\n public int hashCode() {\n // TODO Auto-generated method stub\n return 0;\n }\n\n @Override\n public boolean equals(Object o) {\n // TODO Auto-generated method stub\n return false;\n }\n\n @Override\n public int compareTo(Ingredient other) {\n // If not the same type of Ingredient, sort based on Ingredient type.\n int typeCompare = this.getType().compareTo(other.getType());\n if (typeCompare != 0) {\n return typeCompare;\n }\n\n // Equal.\n return 0;\n }\n\n @Override\n public int getTime() {\n // TODO Auto-generated method stub\n return 0;\n }\n\n @Override\n public void setTime(int i) {\n this.time = i;\n }\n\n @Override\n public void setShortDescription(String description) {\n // TODO Auto-generated method stub\n\n }\n}",
"public class Yeast extends Ingredient {\n\n // Beer XML 1.0 Required Fields ===================================\n // ================================================================\n // Name - Inherited\n // Version - Inherited\n // Amount - Inherited\n private String type; // Ale, Lager, etc\n private String form; // Liquid, Dry, etc\n\n // Beer XML 1.0 Optional Fields ===================================\n // ================================================================\n private double minTemp;\n private double maxTemp;\n private double attenuation; // Percentage: x / 100\n private String notes;\n private String bestFor;\n private String productid;\n private String lab;\n\n // Custom Fields ==================================================\n // ================================================================\n\n // Static values =================================================\n // ===============================================================\n public static final String TYPE_ALE = \"Ale\";\n public static final String TYPE_LAGER = \"Lager\";\n public static final String TYPE_WHEAT = \"Wheat\";\n public static final String TYPE_WINE = \"Wine\";\n public static final String TYPE_CHAMPAGNE = \"Champagne\";\n\n public static final String FORM_LIQUID = \"Liquid\";\n public static final String FORM_DRY = \"Dry\";\n public static final String FORM_SLANT = \"Slant\";\n public static final String FORM_CULTURE = \"Culture\";\n\n public Yeast(String name) {\n super(name);\n this.type = TYPE_ALE;\n this.form = FORM_LIQUID;\n this.amount = 0;\n this.minTemp = 0;\n this.maxTemp = 0;\n this.attenuation = 75;\n this.notes = \"\";\n this.bestFor = \"\";\n this.productid = \"Unknown ID\";\n this.lab = \"Unknown lab\";\n }\n\n public Yeast(Parcel p) {\n super(p);\n type = p.readString();\n form = p.readString();\n minTemp = p.readDouble();\n maxTemp = p.readDouble();\n attenuation = p.readDouble();\n notes = p.readString();\n bestFor = p.readString();\n productid = p.readString();\n lab = p.readString();\n }\n\n @Override\n public void writeToParcel(Parcel p, int flags) {\n super.writeToParcel(p, flags);\n p.writeString(type); // Ale, Lager, etc\n p.writeString(form); // Liquid, Dry, etc\n p.writeDouble(minTemp);\n p.writeDouble(maxTemp);\n p.writeDouble(attenuation); // Percentage: x / 100\n p.writeString(notes);\n p.writeString(bestFor);\n p.writeString(productid);\n p.writeString(lab);\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n public static final Parcelable.Creator<Yeast> CREATOR =\n new Parcelable.Creator<Yeast>() {\n @Override\n public Yeast createFromParcel(Parcel p) {\n return new Yeast(p);\n }\n\n @Override\n public Yeast[] newArray(int size) {\n return null;\n }\n };\n\n @Override\n public String toString() {\n return this.getName();\n }\n\n @Override\n public String getType() {\n return Ingredient.YEAST;\n }\n\n @Override\n public String getShortDescription() {\n String s = this.getLaboratory();\n s += \" \" + this.getProductId();\n\n if (s.length() > 3) {\n s += \": \";\n }\n s += this.notes;\n return s;\n }\n\n public String getArrayAdapterDescription() {\n String s = getLaboratory() + \", \" + getProductId();\n\n if (s.length() < 3) {\n s = String.format(\"%2.2f\", this.getAttenuation()) + \"% attenuation\";\n }\n\n return s;\n }\n\n public String getBeerXmlStandardUnits() {\n return Units.LITERS;\n }\n\n public double getDisplayAmount() {\n // TODO: We just assume a single yeast pkg\n return 1;\n }\n\n public double getBeerXmlStandardAmount() {\n return this.amount;\n }\n\n public void setDisplayAmount(double amt) {\n this.amount = amt;\n }\n\n public void setBeerXmlStandardAmount(double amt) {\n this.amount = amt;\n }\n\n @Override\n public String getDisplayUnits() {\n return Units.PACKAGES;\n }\n\n @Override\n public int hashCode() {\n int hc = this.getName().hashCode();\n hc = hc ^ (int) (this.getAttenuation() * 1234);\n return hc;\n }\n\n @Override\n public boolean equals(Object o) {\n if (o instanceof Yeast) {\n return this.compareTo((Yeast) o) == 0;\n }\n return false;\n }\n\n @Override\n public int compareTo(Ingredient other) {\n // If not the same type of Ingredient, sort based on Ingredient type.\n int typeCompare = this.getType().compareTo(other.getType());\n if (typeCompare != 0) {\n return typeCompare;\n }\n Yeast y = (Yeast) other;\n\n // If they are both Yeast, sort based on attenuation.\n int attnCompare = Double.compare(this.getAttenuation(), y.getAttenuation());\n if (attnCompare != 0) {\n return attnCompare;\n }\n\n // Sort based on name.\n int nameCompare = this.getName().compareTo(y.getName());\n if (nameCompare != 0) {\n return nameCompare;\n }\n\n // Equal.\n return 0;\n }\n\n @Override\n public int getTime() {\n return this.time;\n }\n\n @Override\n public void setTime(int time) {\n this.time = time;\n }\n\n @Override\n public void setShortDescription(String description) {\n this.notes = description;\n }\n\n @Override\n public void setDisplayUnits(String units) {\n\n }\n\n /**\n * @return the type\n */\n public String getYeastType() {\n return type;\n }\n\n /**\n * @param type\n * the type to set\n */\n public void setType(String type) {\n this.type = type;\n }\n\n /**\n * @return the form\n */\n public String getForm() {\n return form;\n }\n\n /**\n * @param form\n * the form to set\n */\n public void setForm(String form) {\n this.form = form;\n }\n\n /**\n * @return the minTemp\n */\n public double getMinTemp() {\n return minTemp;\n }\n\n /**\n * @param minTemp\n * the minTemp to set\n */\n public void setMinTemp(double minTemp) {\n this.minTemp = minTemp;\n }\n\n /**\n * @return the maxTemp\n */\n public double getMaxTemp() {\n return maxTemp;\n }\n\n /**\n * @param maxTemp\n * the maxTemp to set\n */\n public void setMaxTemp(double maxTemp) {\n this.maxTemp = maxTemp;\n }\n\n public int getBeerXmlStandardFermentationTemp() {\n return (int) ((maxTemp + minTemp) / 2);\n }\n\n public int getDisplayFermentationTemp() {\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n return (int) Units.celsiusToFahrenheit(((maxTemp + minTemp) / 2));\n }\n else {\n return (int) ((maxTemp + minTemp) / 2);\n }\n }\n\n /**\n * @return the attenuation\n */\n public double getAttenuation() {\n return attenuation;\n }\n\n /**\n * @param attenuation\n * the attenuation to set\n */\n public void setAttenuation(double attenuation) {\n this.attenuation = attenuation;\n }\n\n /**\n * @return the notes\n */\n public String getNotes() {\n return notes;\n }\n\n /**\n * @param notes\n * the notes to set\n */\n public void setNotes(String notes) {\n this.notes = notes;\n }\n\n /**\n * f\n *\n * @return the bestFor\n */\n public String getBestFor() {\n return bestFor;\n }\n\n /**\n * @param bestFor\n * the bestFor to set\n */\n public void setBestFor(String bestFor) {\n this.bestFor = bestFor;\n }\n\n public void setProductId(String s) {\n this.productid = s;\n }\n\n public void setLaboratory(String s) {\n this.lab = s;\n }\n\n public String getLaboratory() {\n return this.lab;\n }\n\n public String getProductId() {\n return this.productid;\n }\n}",
"public class BeerStyle implements Parcelable {\n\n // Categories based on beerXMl standard\n private String name;\n private String category;\n private Integer version;\n private String categoryNumber;\n private String styleLetter;\n private String styleGuide;\n private String type;\n private String notes;\n private String profile;\n private String ingredients;\n private String examples;\n\n // Reccomended values\n private double MinOg;\n private double MaxOg;\n private double MinFg;\n private double MaxFg;\n private double MinIbu;\n private double MaxIbu;\n private double minColor;\n private double maxColor;\n private double minAbv;\n private double maxAbv;\n\n // More\n private long ownerId;\n\n // Defines\n public static String TYPE_ALE = \"Ale\";\n public static String TYPE_LAGER = \"Lager\";\n public static String TYPE_MEAD = \"Mead\";\n public static String TYPE_WHEAT = \"Wheat\";\n public static String TYPE_MIXED = \"Mixed\";\n public static String TYPE_CIDER = \"Cider\";\n\n public BeerStyle(String name) {\n setName(name);\n setType(\"\");\n setCategory(\"\");\n setStyleLetter(\"\");\n setNotes(\"\");\n setExamples(\"\");\n setIngredients(\"\");\n setProfile(\"\");\n setStyleGuide(\"\");\n setCategoryNumber(\"\");\n setVersion(1);\n setOwnerId(- 1);\n\n this.MinOg = 1;\n this.MaxOg = 2;\n this.MinFg = 1;\n this.MaxFg = 2;\n this.MinIbu = 0;\n this.MaxIbu = 200;\n this.minColor = 0;\n this.maxColor = 100;\n this.minAbv = 0;\n this.maxAbv = 100;\n }\n\n public BeerStyle(Parcel p) {\n // Categories based on beerXMl standard\n name = p.readString();\n category = p.readString();\n version = p.readInt();\n categoryNumber = p.readString();\n styleLetter = p.readString();\n styleGuide = p.readString();\n type = p.readString();\n notes = p.readString();\n profile = p.readString();\n ingredients = p.readString();\n examples = p.readString();\n MinOg = p.readDouble();\n MaxOg = p.readDouble();\n MinFg = p.readDouble();\n MaxFg = p.readDouble();\n MinIbu = p.readDouble();\n MaxIbu = p.readDouble();\n minColor = p.readDouble();\n maxColor = p.readDouble();\n minAbv = p.readDouble();\n maxAbv = p.readDouble();\n ownerId = p.readLong();\n }\n\n @Override\n public void writeToParcel(Parcel p, int flags) {\n // Categories based on beerXMl standard\n p.writeString(name);\n p.writeString(category);\n p.writeInt(version);\n p.writeString(categoryNumber);\n p.writeString(styleLetter);\n p.writeString(styleGuide);\n p.writeString(type);\n p.writeString(notes);\n p.writeString(profile);\n p.writeString(ingredients);\n p.writeString(examples);\n p.writeDouble(MinOg);\n p.writeDouble(MaxOg);\n p.writeDouble(MinFg);\n p.writeDouble(MaxFg);\n p.writeDouble(MinIbu);\n p.writeDouble(MaxIbu);\n p.writeDouble(minColor);\n p.writeDouble(maxColor);\n p.writeDouble(minAbv);\n p.writeDouble(maxAbv);\n p.writeLong(ownerId);\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n public static final Parcelable.Creator<BeerStyle> CREATOR =\n new Parcelable.Creator<BeerStyle>() {\n @Override\n public BeerStyle createFromParcel(Parcel p) {\n return new BeerStyle(p);\n }\n\n @Override\n public BeerStyle[] newArray(int size) {\n return new BeerStyle[]{};\n }\n };\n\n @Override\n public boolean equals(Object o) {\n // Fist make sure its a BeerStyle\n if (! (o instanceof BeerStyle)) {\n return false;\n }\n\n // Based only off the name\n if (this.toString().equals(o.toString())) {\n return true;\n }\n else {\n return false;\n }\n\n }\n\n public String toString() {\n return name;\n }\n\n public void setOwnerId(long i) {\n this.ownerId = i;\n }\n\n public long getOwnerId() {\n return this.ownerId;\n }\n\n public void setMinCarb(double d) {\n // TODO\n }\n\n public void setMaxCarb(double d) {\n // TODO\n }\n\n public void setName(String s) {\n this.name = s;\n }\n\n public String getName() {\n return this.name;\n }\n\n public void setType(String s) {\n this.type = s;\n }\n\n public void setCategory(String s) {\n this.category = s;\n }\n\n public void setStyleLetter(String s) {\n this.styleLetter = s;\n }\n\n public void setNotes(String s) {\n this.notes = s;\n }\n\n public void setExamples(String s) {\n this.examples = s;\n }\n\n public void setProfile(String s) {\n this.profile = s;\n }\n\n public void setCategoryNumber(String s) {\n this.categoryNumber = s;\n }\n\n public void setStyleGuide(String s) {\n this.styleGuide = s;\n }\n\n public void setIngredients(String s) {\n this.ingredients = s;\n }\n\n public void setVersion(int i) {\n this.version = i;\n }\n\n // Methods for getting individual mins and maxes\n public double getMinOg() {\n return MinOg;\n }\n\n public void setMinOg(double minGrav) {\n this.MinOg = minGrav;\n }\n\n public double getMaxOg() {\n return MaxOg;\n }\n\n public void setMaxOg(double maxGrav) {\n this.MaxOg = maxGrav;\n }\n\n public double getMinIbu() {\n return MinIbu;\n }\n\n public void setMinIbu(double MinIbu) {\n this.MinIbu = MinIbu;\n }\n\n public double getMaxIbu() {\n return MaxIbu;\n }\n\n public void setMaxIbu(double MaxIbu) {\n this.MaxIbu = MaxIbu;\n }\n\n public double getMinColor() {\n return minColor;\n }\n\n public void setMinColor(double minColor) {\n this.minColor = minColor;\n }\n\n public double getMaxColor() {\n return maxColor;\n }\n\n public void setMaxColor(double maxColor) {\n this.maxColor = maxColor;\n }\n\n public double getAverageColor() {\n return (this.minColor + this.maxColor) / 2;\n }\n\n public double getMinAbv() {\n return minAbv;\n }\n\n public void setMinAbv(double minAbv) {\n this.minAbv = minAbv;\n }\n\n public double getMaxAbv() {\n return maxAbv;\n }\n\n public void setMaxAbv(double maxAbv) {\n this.maxAbv = maxAbv;\n }\n\n public double getMaxFg() {\n return MaxFg;\n }\n\n public void setMaxFg(double MaxFg) {\n this.MaxFg = MaxFg;\n }\n\n public double getMinFg() {\n return MinFg;\n }\n\n public void setMinFg(double MinFg) {\n this.MinFg = MinFg;\n }\n\n public String getCategory() {\n return this.category;\n }\n\n public String getCatNum() {\n return this.categoryNumber;\n }\n\n public String getStyleLetter() {\n return this.styleLetter;\n }\n\n public String getStyleGuide() {\n return this.styleGuide;\n }\n\n public String getType() {\n return this.type;\n }\n\n public double getMinCarb() {\n return 0; // TODO\n }\n\n public double getMaxCarb() {\n return 0; // TODO\n }\n\n public String getNotes() {\n // Return the string without any newlines or tabs.\n return this.notes.trim()\n .replace(\"\\n\", \"\")\n .replace(\"\\r\", \"\")\n .replace(\"\\t\", \" \")\n .replaceAll(\" +\", \" \");\n }\n\n public String getProfile() {\n return this.profile.trim()\n .replace(\"\\n\", \"\")\n .replace(\"\\r\", \"\")\n .replace(\"\\t\", \" \")\n .replaceAll(\" +\", \" \");\n }\n\n public String getIngredients() {\n return this.ingredients.trim()\n .replace(\"\\n\", \"\")\n .replace(\"\\r\", \"\")\n .replace(\"\\t\", \" \")\n .replaceAll(\" +\", \" \");\n }\n\n public String getExamples() {\n return this.examples.trim()\n .replace(\"\\n\", \"\")\n .replace(\"\\r\", \"\")\n .replace(\"\\t\", \" \")\n .replaceAll(\" +\", \" \");\n }\n}",
"public class MashProfile implements Parcelable {\n // Beer XML 1.0 Required Fields ===================================\n // ================================================================\n private String name; // profile name\n private Integer version; // XML Version -- 1\n private double grainTemp; // Grain temp in C\n private ArrayList<MashStep> mashSteps; // List of steps\n\n // Beer XML 1.0 Optional Fields ===================================\n // ================================================================\n private double tunTemp; // TUN Temperature in C\n private double spargeTemp; // Sparge Temp in C\n private double pH; // pH of water\n private double tunWeight; // Weight of TUN in kG\n private double tunSpecificHeat; // Specific heat of TUN\n private String notes; // Notes\n private Boolean equipAdj; // Adjust for heating of equip?\n\n // Custom Fields ==================================================\n // ================================================================\n private long id; // id for use in database\n private long ownerId; // id for parent recipe\n private String mashType; // one of infusion, decoction, temperature\n private String spargeType; // one of batch, fly\n private Recipe recipe; // Recipe which owns this mash.\n\n // Static values =================================================\n // ===============================================================\n public static String MASH_TYPE_INFUSION = \"Infusion\";\n public static String MASH_TYPE_DECOCTION = \"Decoction\";\n public static String MASH_TYPE_TEMPERATURE = \"Temperature\";\n public static String MASH_TYPE_BIAB = \"BIAB\";\n public static String SPARGE_TYPE_BATCH = \"Batch\";\n public static String SPARGE_TYPE_FLY = \"Fly\";\n public static String SPARGE_TYPE_BIAB = \"BIAB\";\n\n // Basic Constructor\n public MashProfile(Recipe r) {\n this.setName(\"New Mash Profile\");\n this.setVersion(1);\n this.setBeerXmlStandardGrainTemp(20);\n this.mashSteps = new ArrayList<MashStep>();\n this.setBeerXmlStandardTunTemp(20);\n this.setBeerXmlStandardSpargeTemp(75.5555);\n this.setpH(7);\n this.setBeerXmlStandardTunWeight(0);\n this.setBeerXmlStandardTunSpecHeat(0);\n this.setEquipmentAdjust(false);\n this.setNotes(\"\");\n this.id = - 1;\n this.ownerId = - 1;\n this.mashType = MASH_TYPE_INFUSION;\n this.spargeType = SPARGE_TYPE_BATCH;\n this.recipe = r;\n }\n\n public MashProfile() {\n this(new Recipe());\n }\n\n public MashProfile(Parcel p) {\n name = p.readString();\n version = p.readInt();\n grainTemp = p.readDouble();\n\n mashSteps = new ArrayList<MashStep>();\n p.readTypedList(mashSteps, MashStep.CREATOR);\n\n // Beer XML 1.0 Optional Fields ===================================\n // ================================================================\n tunTemp = p.readDouble();\n spargeTemp = p.readDouble();\n pH = p.readDouble();\n tunWeight = p.readDouble();\n tunSpecificHeat = p.readDouble();\n notes = p.readString();\n equipAdj = (p.readInt() > 0 ? true : false);\n\n // Custom Fields ==================================================\n // ================================================================\n id = p.readLong();\n ownerId = p.readLong();\n mashType = p.readString();\n spargeType = p.readString();\n // Don't read recipe because it recurses.\n }\n\n @Override\n public void writeToParcel(Parcel p, int flags) {\n p.writeString(name); // profile name\n p.writeInt(version); // XML Version -- 1\n p.writeDouble(grainTemp); // Grain temp in C\n p.writeTypedList(mashSteps); // List of steps\n\n // Beer XML 1.0 Optional Fields ===================================\n // ================================================================\n p.writeDouble(tunTemp); // TUN Temperature in C\n p.writeDouble(spargeTemp); // Sparge Temp in C\n p.writeDouble(pH); // pH of water\n p.writeDouble(tunWeight); // Weight of TUN in kG\n p.writeDouble(tunSpecificHeat); // Specific heat of TUN\n p.writeString(notes); // Notes\n p.writeInt(equipAdj ? 1 : 0); // Adjust for heating of equip?\n\n // Custom Fields ==================================================\n // ================================================================\n p.writeLong(id); // id for use in database\n p.writeLong(ownerId); // id for parent recipe\n p.writeString(mashType);\n p.writeString(spargeType);\n // Don't write recipe because it recurses.\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n public static final Parcelable.Creator<MashProfile> CREATOR =\n new Parcelable.Creator<MashProfile>() {\n @Override\n public MashProfile createFromParcel(Parcel p) {\n return new MashProfile(p);\n }\n\n @Override\n public MashProfile[] newArray(int size) {\n return new MashProfile[size];\n }\n };\n\n @Override\n public String toString() {\n return this.name;\n }\n\n @Override\n public boolean equals(Object o) {\n if (! (o instanceof MashProfile)) {\n return false;\n }\n\n MashProfile other = (MashProfile) o;\n if (this.hashCode() != other.hashCode()) {\n return false;\n }\n return true;\n }\n\n @Override\n public int hashCode() {\n int hc = this.name.hashCode();\n for (MashStep m : this.mashSteps) {\n hc ^= m.hashCode();\n }\n return hc;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getName() {\n return this.name;\n }\n\n public void setVersion(Integer v) {\n this.version = v;\n }\n\n public Integer getVersion() {\n return this.version;\n }\n\n public void setBeerXmlStandardGrainTemp(double temp) {\n this.grainTemp = temp;\n }\n\n public void setDisplayGrainTemp(double temp) {\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n this.grainTemp = Units.fahrenheitToCelsius(temp);\n }\n else {\n this.grainTemp = temp;\n }\n }\n\n public double getBeerXmlStandardGrainTemp() {\n return this.grainTemp;\n }\n\n public double getDisplayGrainTemp() {\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n return Units.celsiusToFahrenheit(this.grainTemp);\n }\n else {\n return this.grainTemp;\n }\n }\n\n public String getMashType() {\n return this.mashType;\n }\n\n public String getSpargeType() {\n return this.spargeType;\n }\n\n public void setMashType(String s) {\n this.mashType = s;\n }\n\n public void setSpargeType(String s) {\n Log.d(\"MashProfile\", \"Sparge type set: \" + s);\n this.spargeType = s;\n }\n\n public void setBeerXmlStandardTunTemp(double temp) {\n this.tunTemp = temp;\n }\n\n public void setDisplayTunTemp(double temp) {\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n this.tunTemp = Units.fahrenheitToCelsius(temp);\n }\n else {\n this.tunTemp = temp;\n }\n }\n\n public double getBeerXmlStandardTunTemp() {\n return this.tunTemp;\n }\n\n public double getDisplayTunTemp() {\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n return Units.celsiusToFahrenheit(this.tunTemp);\n }\n else {\n return this.tunTemp;\n }\n }\n\n public void setBeerXmlStandardSpargeTemp(double temp) {\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n this.spargeTemp = temp;\n }\n }\n\n public void setDisplaySpargeTemp(double temp) {\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n this.spargeTemp = Units.fahrenheitToCelsius(temp);\n }\n else {\n this.spargeTemp = temp;\n }\n }\n\n public double getDisplaySpargeTemp() {\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n return Units.celsiusToFahrenheit(this.spargeTemp);\n }\n else {\n return this.spargeTemp;\n }\n }\n\n public double getBeerXmlStandardSpargeTemp() {\n return this.spargeTemp;\n }\n\n public void setpH(double pH) {\n this.pH = pH;\n }\n\n public double getpH() {\n return this.pH;\n }\n\n public void setBeerXmlStandardTunWeight(double weight) {\n this.tunWeight = weight;\n }\n\n public void setDisplayTunWeight(double weight) {\n if (Units.getWeightUnits().equals(Units.POUNDS)) {\n this.tunWeight = Units.poundsToKilos(weight);\n }\n else {\n this.tunWeight = weight;\n }\n }\n\n public double getBeerXmlStandardTunWeight() {\n return this.tunWeight;\n }\n\n public double getDisplayTunWeight() {\n if (Units.getWeightUnits().equals(Units.POUNDS)) {\n return Units.kilosToPounds(this.tunWeight);\n }\n else {\n return this.tunWeight;\n }\n }\n\n public void setBeerXmlStandardTunSpecHeat(double heat) {\n this.tunSpecificHeat = heat;\n }\n\n public double getBeerXmlStandardTunSpecHeat() {\n // Cal / (g * C)\n return this.tunSpecificHeat;\n }\n\n public void setEquipmentAdjust(boolean adj) {\n this.equipAdj = adj;\n }\n\n public Boolean getEquipmentAdjust() {\n return this.equipAdj;\n }\n\n public void setId(long id) {\n this.id = id;\n }\n\n public long getId() {\n return this.id;\n }\n\n public void setOwnerId(long id) {\n this.ownerId = id;\n }\n\n public long getOwnerId() {\n return this.ownerId;\n }\n\n public void setNotes(String s) {\n this.notes = s;\n }\n\n public String getNotes() {\n return this.notes;\n }\n\n public int getNumberOfSteps() {\n return this.mashSteps.size();\n }\n\n public void setRecipe(Recipe r) {\n this.recipe = r;\n for (MashStep m : this.mashSteps) {\n m.setRecipe(this.recipe);\n }\n }\n\n public ArrayList<MashStep> getMashStepList() {\n return this.mashSteps;\n }\n\n public void clearMashSteps() {\n this.mashSteps = new ArrayList<MashStep>();\n }\n\n /**\n * Sets mash step list to given list. Assumes list is in the desired order and overrides orders\n * if reorder set to true\n *\n * @param list\n */\n public void setMashStepList(ArrayList<MashStep> list) {\n this.mashSteps = list;\n for (MashStep s : this.mashSteps) {\n s.setRecipe(this.recipe);\n }\n Collections.sort(this.mashSteps, new FromDatabaseMashStepComparator());\n }\n\n /**\n * Removes the given step, returns true if success\n *\n * @param step\n * @return\n */\n public boolean removeMashStep(MashStep step) {\n return this.mashSteps.remove(step);\n }\n\n public MashStep removeMashStep(int order) {\n return this.mashSteps.remove(order);\n }\n\n public void addMashStep(MashStep step) {\n step.setRecipe(this.recipe);\n this.mashSteps.add(step);\n }\n\n public void addMashStep(int order, MashStep step) {\n step.setRecipe(this.recipe);\n this.mashSteps.add(order, step);\n }\n\n public void save(Context c, long database) {\n Log.d(\"MashProfile\", \"Saving \" + name + \" to database \" + database);\n if (this.id < 0) {\n // We haven't yet saved this. Add it to the database.\n new DatabaseAPI(c).addMashProfile(database, this, this.getOwnerId());\n }\n else {\n // Already exists. Update it.\n new DatabaseAPI(c).updateMashProfile(this, this.getOwnerId(), database);\n }\n }\n\n public void delete(Context c, long database) {\n new DatabaseAPI(c).deleteMashProfileFromDatabase(this, database);\n }\n}",
"public class MashStep implements Parcelable {\n // ================================================================\n // Beer XML 1.0 Required Fields ===================================\n // ================================================================\n private String name; // profile name\n private int version; // XML Version -- 1\n private String type; // infusion, temp, decoc\n private double infuseAmount; // Amount\n private double stepTemp; // Temp for this step in C\n private double stepTime; // Time for this step\n\n // ================================================================\n // Beer XML 1.0 Optional Fields ===================================\n // ================================================================\n private double rampTime; // Time to ramp temp\n private double endTemp; // Final temp for long steps\n private String description; // Description of step\n private double waterToGrainRatio; // Water to grain ratio (L/kg)\n private double decoctAmount; // Amount of mash to decoct. (L)\n\n // ================================================================\n // Custom Fields ==================================================\n // ================================================================\n private long ownerId; // id for parent mash profile\n private long id; // id for use in database\n public int order; // Order in step list\n private double infuseTemp; // Temperature of infuse water\n private boolean calcInfuseTemp; // Auto calculate the infusion temperature if true.\n private boolean calcInfuseAmt; // Auto calculate the infusion amount if true.\n private boolean calcDecoctAmt; // Auto calculate the amount to decoct if true.\n private Recipe recipe; // Reference to the recipe that owns this mash.\n\n // ================================================================\n // Static values ==================================================\n // ================================================================\n public static String INFUSION = \"Infusion\";\n public static String TEMPERATURE = \"Temperature\";\n public static String DECOCTION = \"Decoction\";\n\n // Basic Constructor\n public MashStep(Recipe r) {\n this.setName(\"Mash Step (\" + (r.getMashProfile().getMashStepList().size() + 1) + \")\");\n this.setVersion(1);\n this.setType(MashStep.INFUSION);\n this.setDisplayInfuseAmount(0);\n this.setBeerXmlStandardStepTemp(65.555556);\n this.setStepTime(60);\n this.setRampTime(0);\n this.setBeerXmlStandardEndTemp(0.0);\n this.setDescription(\"\");\n this.setBeerXmlStandardWaterToGrainRatio(2.60793889);\n this.infuseTemp = 0.0;\n this.id = - 1;\n this.ownerId = - 1;\n this.order = 1;\n this.decoctAmount = 0;\n this.calcInfuseAmt = true;\n this.calcInfuseTemp = true;\n this.calcDecoctAmt = true;\n this.recipe = r;\n }\n\n // Only use this when we don't have a mash profile to\n // use!\n public MashStep() {\n this(new Recipe());\n }\n\n public MashStep(Parcel p) {\n // Beer XML 1.0 Required Fields ===================================\n // ================================================================\n name = p.readString();\n version = p.readInt();\n type = p.readString();\n infuseAmount = p.readDouble();\n stepTemp = p.readDouble();\n stepTime = p.readDouble();\n\n // Beer XML 1.0 Optional Fields ===================================\n // ================================================================\n rampTime = p.readDouble();\n endTemp = p.readDouble();\n description = p.readString();\n waterToGrainRatio = p.readDouble();\n decoctAmount = p.readDouble();\n\n // Custom Fields ==================================================\n // ================================================================\n ownerId = p.readLong();\n id = p.readLong();\n order = p.readInt();\n infuseTemp = p.readDouble();\n calcInfuseTemp = p.readInt() == 0 ? false : true;\n calcInfuseAmt = p.readInt() == 0 ? false : true;\n calcDecoctAmt = p.readInt() == 0 ? false : true;\n }\n\n @Override\n public void writeToParcel(Parcel p, int flags) {\n // Beer XML 1.0 Required Fields ===================================\n // ================================================================\n p.writeString(name); // profile name\n p.writeInt(version); // XML Version -- 1\n p.writeString(type); // infusion, temp, decoc\n p.writeDouble(infuseAmount); // Amount\n p.writeDouble(stepTemp); // Temp for this step in C\n p.writeDouble(stepTime); // Time for this step\n\n // Beer XML 1.0 Optional Fields ===================================\n // ================================================================\n p.writeDouble(rampTime); // Time to ramp temp\n p.writeDouble(endTemp); // Final temp for long steps\n p.writeString(description); // Description of step\n p.writeDouble(waterToGrainRatio); // Water to grain ratio (L/kg)\n p.writeDouble(decoctAmount); // Amount of water to decoct.\n\n // Custom Fields ==================================================\n // ================================================================\n p.writeLong(ownerId); // id for parent mash profile\n p.writeLong(id); // id for use in database\n p.writeInt(order); // Order in step list\n p.writeDouble(infuseTemp);\n p.writeInt(calcInfuseTemp ? 1 : 0);\n p.writeInt(calcInfuseAmt ? 1 : 0);\n p.writeInt(calcDecoctAmt ? 1 : 0);\n }\n\n public static final Parcelable.Creator<MashStep> CREATOR =\n new Parcelable.Creator<MashStep>() {\n @Override\n public MashStep createFromParcel(Parcel p) {\n return new MashStep(p);\n }\n\n @Override\n public MashStep[] newArray(int size) {\n return new MashStep[size];\n }\n };\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public boolean equals(Object o) {\n // Non-MashStep objects cannot equal a MashStep.\n if (! (o instanceof MashStep)) {\n return false;\n }\n\n // Comparing to a MashStep - cast the given Object.\n MashStep other = (MashStep) o;\n\n // Both are MashStep objects - compare important fields.\n if (! this.getName().equals(other.getName())) {\n Log.d(\"MashStep\", \"MashStep.equals(): \" + this.getName() + \" != \" + other.getName());\n return false;\n }\n else if (this.getStepTime() != other.getStepTime()) {\n Log.d(\"MashStep\", \"MashStep.equals(): \" + this.getStepTime() + \" != \" + other.getStepTime());\n return false;\n }\n else if (this.getBeerXmlStandardStepTemp() != other.getBeerXmlStandardStepTemp()) {\n Log.d(\"MashStep\", \"MashStep.equals(): \" + this.getBeerXmlStandardStepTemp() + \" != \" + other.getBeerXmlStandardStepTemp());\n return false;\n }\n else if (! this.getType().equals(other.getType())) {\n Log.d(\"MashStep\", \"MashStep.equals(): \" + this.getType() + \" != \" + other.getType());\n return false;\n }\n\n // All index fields match - these objects are equal.\n return true;\n }\n\n @Override\n public String toString() {\n return this.name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getName() {\n return this.name;\n }\n\n public void setVersion(int version) {\n this.version = version;\n }\n\n public int getVersion() {\n return this.version;\n }\n\n public void setType(String type) {\n this.type = type;\n }\n\n public String getType() {\n return this.type;\n }\n\n public double getDisplayDecoctAmount() {\n // If we are autocalculating.\n if (this.calcDecoctAmt) {\n return this.calculateDecoctAmount();\n }\n\n // We're not auto-calculating.\n if (Units.getVolumeUnits().equals(Units.GALLONS)) {\n return Units.litersToGallons(this.decoctAmount);\n }\n else {\n return this.decoctAmount;\n }\n }\n\n public void setDisplayDecoctAmount(double amt) {\n Log.d(\"MashStep\", \"Setting display decoction amount: \" + amt);\n if (Units.getVolumeUnits().equals(Units.GALLONS)) {\n this.decoctAmount = Units.gallonsToLiters(amt);\n }\n else {\n this.decoctAmount = amt;\n }\n }\n\n public void setBeerXmlDecoctAmount(double amt) {\n this.decoctAmount = amt;\n }\n\n public double getBeerXmlDecoctAmount() {\n return this.decoctAmount;\n }\n\n public void setDisplayInfuseAmount(double amt) {\n if (Units.getVolumeUnits().equals(Units.GALLONS)) {\n this.infuseAmount = Units.gallonsToLiters(amt);\n }\n else {\n this.infuseAmount = amt;\n }\n }\n\n public double getDisplayAmount() {\n if (this.getType().equals(DECOCTION)) {\n Log.d(\"MashStep\", \"Returning display decoction amount: \" + this.getDisplayDecoctAmount());\n return this.getDisplayDecoctAmount();\n }\n else if (this.getType().equals(INFUSION)) {\n Log.d(\"MashStep\", \"Returning display infusion amount: \" + this.getDisplayInfuseAmount());\n return this.getDisplayInfuseAmount();\n }\n else if (this.getType().equals(TEMPERATURE)) {\n Log.d(\"MashStep\", \"Temperature mash, returning 0 for display amount\");\n return 0;\n }\n Log.d(\"MashStep\", \"Invalid type: \" + this.getType() + \". Returning -1 for display amount\");\n return - 1;\n }\n\n public double getDisplayInfuseAmount() {\n // No infuse amount for decoction steps. Ever.\n if (this.getType().equals(MashStep.DECOCTION)) {\n return 0;\n }\n\n // If we are autocalculating.\n if (this.calcInfuseAmt) {\n return this.calculateInfuseAmount();\n }\n\n // If we're not auto-calculating.\n if (Units.getVolumeUnits().equals(Units.GALLONS)) {\n return Units.litersToGallons(this.infuseAmount);\n }\n else {\n return this.infuseAmount;\n }\n }\n\n /* Calculates the infusion amount based on\n /* water to grain ratio, water temp, water to add,\n /* and the step temperature.\n /* Also sets this.infuseAmount to the correct value. */\n public double calculateInfuseAmount() {\n // We perform different calculations if this is the initial infusion.\n double amt = - 1;\n if (this.firstInList() &&\n ! this.recipe.getMashProfile().getMashType().equals(MashProfile.MASH_TYPE_BIAB)) {\n // Initial infusion for a non-biab mash. Water is constant * amount of grain.\n amt = this.getBeerXmlStandardWaterToGrainRatio() * this.getBeerXmlStandardMashWeight();\n }\n else if (this.firstInList() &&\n this.recipe.getMashProfile().getMashType().equals(MashProfile.MASH_TYPE_BIAB)) {\n // Initial infusion for a BIAB mash.\n // Water is boil volume + grain absorption.\n amt = this.recipe.getBeerXmlStandardBoilSize();\n\n // Estimate ~1 liter per kg absobtion.\n // TODO: Get this from equipment profile.\n amt += this.getBeerXmlStandardMashWeight();\n }\n else {\n // The actual temperature of the water being infused.\n double actualInfuseTemp = calcInfuseTemp ? calculateBXSInfuseTemp() : getBeerXmlStandardInfuseTemp();\n\n // Not initial infusion. Calculate water to add to reach appropriate temp.\n try {\n amt = (this.getBeerXmlStandardStepTemp() - getPreviousStep().getBeerXmlStandardStepTemp());\n } catch (Exception e) {\n e.printStackTrace();\n }\n amt = amt * (.41 * this.getBeerXmlStandardMashWeight() + this.getBXSTotalWaterInMash());\n amt = amt / (actualInfuseTemp - this.getBeerXmlStandardStepTemp());\n }\n\n // Set BXL amount so that database is consistent.\n this.infuseAmount = amt;\n\n // Use appropriate units.\n if (Units.getVolumeUnits().equals(Units.LITERS)) {\n return amt;\n }\n else {\n return Units.litersToGallons(amt);\n }\n }\n\n /* Calculates the decoction amount */\n public double calculateDecoctAmount() {\n Log.d(\"MashStep\", \"Auto-calculating decoct amount\");\n /**\n * F = (TS – TI) / (TB – TI – X)\n *\n * Where f is the fraction, TS is the target step temperature, TI is the initial (current) temperature,\n * TB is the temperature of the boiling mash and X is an equipment dependent parameter (typically 18F or 10C).\n */\n double target = this.getBeerXmlStandardStepTemp();\n double initial = 0;\n try {\n initial = this.getPreviousStep().getBeerXmlStandardStepTemp();\n } catch (Exception e) {\n // Attempted to calculate decoct amount for first step in MashProfile. This isn't\n // allowed (the first step must be an infusion step). Handle this\n // somewhat gracefully, as this can occur temporarily during recipe formulation.\n e.printStackTrace();\n return 0;\n }\n double boiling = 99; // Boiling temperature of mash (C).\n double X = 10; // TODO: Equipment factor - accounts for heat absorbtion of mash tun.\n double grainDensity = .43; // .43kg / 1L\n double waterVolume = getBXSTotalWaterInMash(); // L\n double grainMass = (waterVolume / waterToGrainRatio); // kg\n double grainVolume = grainMass / grainDensity; // L\n double totalVolume = waterVolume + grainVolume; // L\n\n // This calculates the ratio of \"mash to boil\" / \"mash to leave in tun\".\n double fraction = (target - initial) / (boiling - initial - X);\n\n // Convert this ratio to \"Mash to boil\" / \"Total Mash\"\n fraction = (fraction) / (1 + fraction);\n\n // Return the fraction of mash, adjusted for the selected units.\n if (Units.getUnitSystem().equals(Units.METRIC)) {\n return fraction * totalVolume; // Return Liters of mash.\n }\n else {\n return fraction * Units.litersToGallons(totalVolume); // Return Gallons of mash.\n }\n }\n\n /**\n * Calculates the infusion temperature for both initial infusion, and water adds.\n * http://www.howtobrew.com/section3/chapter16-3.html\n */\n public double calculateInfuseTemp() {\n // We perform different calculations if this is the initial infusion.\n double temp = 0;\n if (this.firstInList()) {\n // Initial infusion.\n // TODO: For now, we don't have equipment so we combine tun / grain temp for calculation.\n double tunTemp = .7 * this.recipe.getMashProfile().getBeerXmlStandardGrainTemp() +\n .3 * this.recipe.getMashProfile().getBeerXmlStandardTunTemp();\n temp = (.41) / (this.getBeerXmlStandardWaterToGrainRatio());\n temp = temp * (this.getBeerXmlStandardStepTemp() - tunTemp) + this.getBeerXmlStandardStepTemp();\n }\n else {\n // Not initial infusion. Assume boiling water to make\n // calculation easier. If the next step has a LOWER temperature,\n // use room temperature water (72F).\n try {\n if (getPreviousStep().getBeerXmlStandardStepTemp() < this.getBeerXmlStandardStepTemp()) {\n temp = 100;\n }\n else {\n temp = 22.2222;\n }\n } catch (Exception e) {\n temp = - 1;\n }\n }\n\n // Set the infuse temperature.\n this.infuseTemp = temp;\n\n // Use appropriate units.\n if (Units.getTemperatureUnits().equals(Units.CELSIUS)) {\n return temp;\n }\n else {\n return Units.celsiusToFahrenheit(temp);\n }\n }\n\n private double calculateBXSInfuseTemp() {\n if (Units.getTemperatureUnits().equals(Units.CELSIUS)) {\n return this.calculateInfuseTemp();\n }\n else {\n return Units.fahrenheitToCelsius(this.calculateInfuseTemp());\n }\n }\n\n public boolean firstInList() {\n return this.getOrder() == 0;\n }\n\n public void setBeerXmlStandardInfuseAmount(double amt) {\n this.infuseAmount = amt;\n }\n\n public double getBeerXmlStandardInfuseAmount() {\n if (this.calcInfuseAmt) {\n calculateInfuseAmount();\n }\n return this.infuseAmount;\n }\n\n public double getDisplayInfuseTemp() {\n if (this.calcInfuseTemp) {\n return Math.round(this.calculateInfuseTemp());\n }\n\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n return Math.round(Units.celsiusToFahrenheit(this.infuseTemp));\n }\n else {\n return Math.round(this.infuseTemp);\n }\n }\n\n public void setDisplayInfuseTemp(double d) {\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n this.infuseTemp = Units.fahrenheitToCelsius(d);\n }\n else {\n this.infuseTemp = d;\n }\n }\n\n public double getBeerXmlStandardInfuseTemp() {\n return this.infuseTemp;\n }\n\n public void setBeerXmlStandardInfuseTemp(double d) {\n this.infuseTemp = d;\n }\n\n public void setAutoCalcInfuseTemp(boolean b) {\n this.calcInfuseTemp = b;\n }\n\n public void setAutoCalcInfuseAmt(boolean b) {\n this.calcInfuseAmt = b;\n }\n\n public void setAutoCalcDecoctAmt(boolean b) {\n this.calcDecoctAmt = b;\n }\n\n public boolean getAutoCalcDecoctAmt() {\n return this.calcDecoctAmt;\n }\n\n public boolean getAutoCalcInfuseTemp() {\n return this.calcInfuseTemp;\n }\n\n public boolean getAutoCalcInfuseAmt() {\n return this.calcInfuseAmt;\n }\n\n public void setDisplayStepTemp(double temp) {\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n this.stepTemp = Units.fahrenheitToCelsius(temp);\n }\n else {\n this.stepTemp = temp;\n }\n }\n\n public double getDisplayStepTemp() {\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n return Units.celsiusToFahrenheit(this.stepTemp);\n }\n else {\n return this.stepTemp;\n }\n }\n\n public void setBeerXmlStandardStepTemp(double temp) {\n this.stepTemp = temp;\n }\n\n public double getBeerXmlStandardStepTemp() {\n return this.stepTemp;\n }\n\n public double getBeerXmlStandardWaterToGrainRatio() {\n // If this is the first in the list, use the configured value.\n // Otherwise, we need to calculate it based on the water added.\n if (this.firstInList() && ! this.recipe.getMashProfile().getMashType().equals(MashProfile.MASH_TYPE_BIAB)) {\n return this.waterToGrainRatio;\n }\n return (this.getBeerXmlStandardInfuseAmount() + this.getBXSTotalWaterInMash()) / this.getBeerXmlStandardMashWeight();\n }\n\n public double getDisplayWaterToGrainRatio() {\n if (Units.getUnitSystem().equals(Units.IMPERIAL)) {\n return Units.LPKGtoQPLB(getBeerXmlStandardWaterToGrainRatio());\n }\n else {\n return getBeerXmlStandardWaterToGrainRatio();\n }\n }\n\n public void setBeerXmlStandardWaterToGrainRatio(double d) {\n // Don't update if less than 0. Impossible value.\n if (d <= 0) {\n return;\n }\n this.waterToGrainRatio = d;\n }\n\n public void setDisplayWaterToGrainRatio(double d) {\n if (d <= 0) {\n return;\n }\n if (Units.getUnitSystem().equals(Units.IMPERIAL)) {\n this.waterToGrainRatio = Units.QPLBtoLPKG(d);\n }\n else {\n this.waterToGrainRatio = d;\n }\n }\n\n public void setOrder(int i) {\n // Order is privately used for ordering mash steps\n // when they are received from the database. Once they\n // are out of the db, we use the order in the list as the order.\n // When saved, the orders will be updated in the database.\n this.order = i;\n }\n\n public int getOrder() {\n return this.recipe.getMashProfile().getMashStepList().indexOf(this);\n }\n\n public void setDescription(String s) {\n this.description = s;\n }\n\n public String getDescription() {\n return this.description;\n }\n\n public void setStepTime(double time) {\n this.stepTime = time;\n }\n\n public double getStepTime() {\n return this.stepTime;\n }\n\n public void setRampTime(double time) {\n this.rampTime = time;\n }\n\n public double getRampTime() {\n return this.rampTime;\n }\n\n public void setBeerXmlStandardEndTemp(double temp) {\n this.endTemp = temp;\n }\n\n public double getBeerXmlStandardEndTemp() {\n return this.endTemp;\n }\n\n public void setId(long id) {\n this.id = id;\n }\n\n public long getId() {\n return this.id;\n }\n\n public void setOwnerId(long id) {\n this.ownerId = id;\n }\n\n public long getOwnerId() {\n return this.ownerId;\n }\n\n public void setRecipe(Recipe r) {\n this.recipe = r;\n }\n\n public Recipe getRecipe() {\n return this.recipe;\n }\n\n public double getBeerXmlStandardMashWeight() {\n // If there are no ingredients for this recipe yet, we need to use something!\n // Fake it, assume 12 pounds of grain by default.\n double weight = BrewCalculator.TotalBeerXmlMashWeight(this.recipe);\n return weight == 0 ? Units.poundsToKilos(12) : weight;\n }\n\n public MashStep getPreviousStep() throws Exception {\n if (this.firstInList()) {\n throw new Exception(); // TODO: This should throw a specific exception.\n }\n\n int idx = this.recipe.getMashProfile().getMashStepList().indexOf(this);\n return this.recipe.getMashProfile().getMashStepList().get(idx - 1);\n }\n\n public double getBXSTotalWaterInMash() {\n double amt = 0;\n\n for (MashStep step : this.recipe.getMashProfile().getMashStepList()) {\n if (step.equals(this)) {\n break;\n }\n amt += step.getBeerXmlStandardInfuseAmount();\n }\n Log.d(\"MashStep\", \"Step \" + this.getName() + \" has \" + Units.litersToGallons(amt) + \" gal in mash.\");\n return amt;\n }\n}",
"public class Recipe implements Parcelable {\n // ===============================================================\n // Static values =================================================\n // ===============================================================\n public static final String EXTRACT = \"Extract\";\n public static final String ALL_GRAIN = \"All Grain\";\n public static final String PARTIAL_MASH = \"Partial Mash\";\n public static final int STAGE_PRIMARY = 1;\n public static final int STAGE_SECONDARY = 2;\n public static final int STAGE_TERTIARY = 3;\n public static final Parcelable.Creator<Recipe> CREATOR =\n new Parcelable.Creator<Recipe>() {\n @Override\n public Recipe createFromParcel(Parcel p) {\n return new Recipe(p);\n }\n\n @Override\n public Recipe[] newArray(int size) {\n return new Recipe[]{};\n }\n };\n\n // ================================================================\n // Beer XML 1.0 Required Fields ===================================\n // ================================================================\n private String name; // Recipe name\n private int version; // XML Version -- 1\n private String type; // Extract, Grain, Mash\n private BeerStyle style; // Stout, Pilsner, etc.\n private String brewer; // Brewer's name\n private double batchSize; // Target size (L)\n private double boilSize; // Pre-boil vol (L)\n private int boilTime; // In Minutes\n private double efficiency; // 100 for extract\n private ArrayList<Hop> hops; // Hops used\n private ArrayList<Fermentable> fermentables; // Fermentables used\n private ArrayList<Yeast> yeasts; // Yeasts used\n private ArrayList<Misc> miscs; // Misc ingredients used\n private ArrayList<Water> waters; // Waters used\n private MashProfile mashProfile; // Mash profile for non-extracts\n\n // ================================================================\n // Beer XML 1.0 Optional Fields ===================================\n // ================================================================\n private double OG; // Original Gravity\n private double FG; // Final Gravity\n private int fermentationStages; // # of Fermentation stages\n private int primaryAge; // Time in primary in days\n private double primaryTemp; // Temp in primary in C\n private int secondaryAge; // Time in Secondary in days\n private double secondaryTemp; // Temp in secondary in C\n private int tertiaryAge; // Time in tertiary in days\n private double tertiaryTemp; // Temp in tertiary in C\n private String tasteNotes; // Taste notes\n private int tasteRating; // Taste score out of 50\n private int bottleAge; // Bottle age in days\n private double bottleTemp; // Bottle temp in C\n private boolean isForceCarbonated;// True if force carb is used\n private double carbonation; // Volumes of carbonation\n private String brewDate; // Date brewed\n private String primingSugarName; // Name of sugar for priming\n private double primingSugarEquiv; // Equivalent amount of priming sugar to be used\n private double kegPrimingFactor; // factor - use less sugar when kegging vs bottles\n private double carbonationTemp; // Carbonation temperature in C\n private int calories; // Calories (KiloCals)\n private String lastModified; // Date last modified in database.\n\n // ================================================================\n // Custom Fields ==================================================\n // ================================================================\n private long id; // id for use in database\n private String notes; // User input notes\n private int batchTime; // Total length in weeks\n private double ABV; // Alcohol by volume\n private double bitterness; // Bitterness in IBU\n private double color; // Color - SRM\n private InstructionGenerator instructionGenerator;\n private double measuredOG; // Brew day stat: measured OG\n private double measuredFG; // Brew stat: measured FG\n private double measuredVol; // Measured final volume (L) of batch.\n private double steepTemp; // Temperature to steep grains.\n\n // ================================================================\n // Fields for auto-calculation ====================================\n // ================================================================\n private boolean calculateBoilVolume; // Calculate the boil volume automatically\n private boolean calculateStrikeVolume; // Calculate strike vol automatically\n private boolean calculateStrikeTemp; // Calculate strike temp automatically\n\n // Public constructors\n public Recipe(String s) {\n // ================================================================\n // Beer XML 1.0 Required Fields ===================================\n // ================================================================\n this.name = s;\n this.setVersion(1);\n this.setType(ALL_GRAIN);\n this.style = Constants.BEERSTYLE_OTHER;\n this.setBrewer(\"Unknown Brewer\");\n this.setDisplayBatchSize(5);\n this.setDisplayBoilSize(2.5);\n this.setBoilTime(60);\n this.setEfficiency(70);\n this.hops = new ArrayList<Hop>();\n this.fermentables = new ArrayList<Fermentable>();\n this.yeasts = new ArrayList<Yeast>();\n this.miscs = new ArrayList<Misc>();\n this.waters = new ArrayList<Water>();\n this.mashProfile = new MashProfile(this);\n\n // Beer XML 1.0 Optional Fields ===================================\n // ================================================================\n this.OG = 1;\n this.setFG(1);\n this.setFermentationStages(1);\n this.primaryAge = 14;\n this.secondaryAge = 0;\n this.tertiaryAge = 0;\n this.primaryTemp = 21;\n this.secondaryTemp = 21;\n this.tertiaryTemp = 21;\n this.bottleAge = 14;\n this.brewDate = \"\";\n\n // Custom Fields ==================================================\n // ================================================================\n this.id = - 1;\n this.notes = \"\";\n this.tasteNotes = \"\";\n this.batchTime = 60;\n this.ABV = 0;\n this.bitterness = 0;\n this.color = 0;\n this.instructionGenerator = new InstructionGenerator(this);\n this.measuredOG = 0;\n this.measuredFG = 0;\n this.measuredVol = 0;\n this.steepTemp = Units.fahrenheitToCelsius(155);\n this.lastModified = new SimpleDateFormat(Constants.LAST_MODIFIED_DATE_FMT).format(new Date());\n\n // Fields for auto-calculation ====================================\n // ================================================================\n calculateBoilVolume = true;\n calculateStrikeVolume = false;\n calculateStrikeTemp = false;\n\n update();\n }\n\n // Constructor with no arguments!\n public Recipe() {\n this(\"New Recipe\");\n }\n\n public Recipe(Parcel p) {\n hops = new ArrayList<Hop>();\n fermentables = new ArrayList<Fermentable>();\n yeasts = new ArrayList<Yeast>();\n miscs = new ArrayList<Misc>();\n waters = new ArrayList<Water>();\n\n name = p.readString(); // Recipe name\n version = p.readInt(); // XML Version -- 1\n type = p.readString(); // Extract, Grain, Mash\n style = p.readParcelable(BeerStyle.class.getClassLoader()); // Stout, Pilsner, etc.\n brewer = p.readString(); // Brewer's name\n batchSize = p.readDouble();\n boilSize = p.readDouble();\n boilTime = p.readInt(); // In Minutes\n efficiency = p.readDouble(); // 100 for extract\n p.readTypedList(hops, Hop.CREATOR); // Hops used\n p.readTypedList(fermentables, Fermentable.CREATOR); // Fermentables used\n p.readTypedList(yeasts, Yeast.CREATOR); // Yeasts used\n p.readTypedList(miscs, Misc.CREATOR); // Misc ingredients used\n p.readTypedList(waters, Water.CREATOR); // Waters used\n mashProfile = p.readParcelable(MashProfile.class.getClassLoader()); // Mash profile for non-extracts\n mashProfile.setRecipe(this);\n\n // Beer XML 1.0 Optional Fields ===================================\n // ================================================================\n OG = p.readDouble(); // Original Gravity\n FG = p.readDouble(); // Final Gravity\n fermentationStages = p.readInt(); // # of Fermentation stages\n primaryAge = p.readInt(); // Time in primary in days\n primaryTemp = p.readDouble(); // Temp in primary in C\n secondaryAge = p.readInt(); // Time in Secondary in days\n secondaryTemp = p.readDouble(); // Temp in secondary in C\n tertiaryAge = p.readInt(); // Time in tertiary in days\n tertiaryTemp = p.readDouble(); // Temp in tertiary in C\n tasteNotes = p.readString(); // Taste notes\n tasteRating = p.readInt(); // Taste score out of 50\n bottleAge = p.readInt(); // Bottle age in days\n bottleTemp = p.readDouble(); // Bottle temp in C\n isForceCarbonated = p.readInt() > 0; // True if force carb is used\n carbonation = p.readDouble(); // Volumes of carbonation\n brewDate = p.readString(); // Date brewed\n primingSugarName = p.readString(); // Name of sugar for priming\n primingSugarEquiv = p.readDouble(); // Equivalent amount of priming sugar to be used\n kegPrimingFactor = p.readDouble(); // factor - use less sugar when kegging vs bottles\n carbonationTemp = p.readDouble(); // Carbonation temperature in C\n calories = p.readInt();\n lastModified = p.readString();\n\n // Custom Fields ==================================================\n // ================================================================\n id = p.readLong(); // id for use in database\n notes = p.readString(); // User input notes\n batchTime = p.readInt(); // Total length in weeks\n ABV = p.readDouble(); // Alcohol by volume\n bitterness = p.readDouble(); // Bitterness in IBU\n color = p.readDouble(); // Color - SRM\n // Instruction generator not included in parcel\n measuredOG = p.readDouble(); // Brew day stat: measured OG\n measuredFG = p.readDouble(); // Brew stat: measured FG\n measuredVol = p.readDouble(); // Brew stat: measured volume\n steepTemp = p.readDouble(); // Temperature to steep grains for extract recipes.\n\n // Fields for auto-calculation ====================================\n // ================================================================\n calculateBoilVolume = p.readInt() > 0;\n calculateStrikeVolume = p.readInt() > 0;\n calculateStrikeTemp = p.readInt() > 0;\n\n // Create instruction generator\n instructionGenerator = new InstructionGenerator(this);\n update();\n }\n\n @Override\n public void writeToParcel(Parcel p, int flags) {\n p.writeString(name); // Recipe name\n p.writeInt(version); // XML Version -- 1\n p.writeString(type); // Extract, Grain, Mash\n p.writeParcelable(style, flags); // Stout, Pilsner, etc.\n p.writeString(brewer); // Brewer's name\n p.writeDouble(batchSize); // Target size (L)\n p.writeDouble(boilSize); // Pre-boil vol (L)\n p.writeInt(boilTime); // In Minutes\n p.writeDouble(efficiency); // 100 for extract\n p.writeTypedList(hops); // Hops used\n p.writeTypedList(fermentables); // Fermentables used\n p.writeTypedList(yeasts); // Yeasts used\n p.writeTypedList(miscs); // Misc ingredients used\n p.writeTypedList(waters); // Waters used\n p.writeParcelable(mashProfile, flags); // Mash profile for non-extracts\n\n // Beer XML 1.0 Optional Fields ===================================\n // ================================================================\n p.writeDouble(OG); // Original Gravity\n p.writeDouble(FG); // Final Gravity\n p.writeInt(fermentationStages); // # of Fermentation stages\n p.writeInt(primaryAge); // Time in primary in days\n p.writeDouble(primaryTemp); // Temp in primary in C\n p.writeInt(secondaryAge); // Time in Secondary in days\n p.writeDouble(secondaryTemp); // Temp in secondary in C\n p.writeInt(tertiaryAge); // Time in tertiary in days\n p.writeDouble(tertiaryTemp); // Temp in tertiary in C\n p.writeString(tasteNotes); // Taste notes\n p.writeInt(tasteRating); // Taste score out of 50\n p.writeInt(bottleAge); // Bottle age in days\n p.writeDouble(bottleTemp); // Bottle temp in C\n p.writeInt(isForceCarbonated ? 1 : 0); // True if force carb is used\n p.writeDouble(carbonation); // Volumes of carbonation\n p.writeString(brewDate); // Date brewed\n p.writeString(primingSugarName); // Name of sugar for priming\n p.writeDouble(primingSugarEquiv); // Equivalent amount of priming sugar to be used\n p.writeDouble(kegPrimingFactor); // factor - use less sugar when kegging vs bottles\n p.writeDouble(carbonationTemp); // Carbonation temperature in C\n p.writeInt(calories); // Calories (KiloCals)\n p.writeString(lastModified);\n\n // Custom Fields ==================================================\n // ================================================================\n p.writeLong(id); // id for use in database\n p.writeString(notes); // User input notes\n p.writeInt(batchTime); // Total length in weeks\n p.writeDouble(ABV); // Alcohol by volume\n p.writeDouble(bitterness); // Bitterness in IBU\n p.writeDouble(color); // Color - SRM\n // Instruction generator not included in parcel\n p.writeDouble(measuredOG); // Brew day stat: measured OG\n p.writeDouble(measuredFG); // Brew stat: measured FG\n p.writeDouble(measuredVol); // Brew stat: measured volume\n p.writeDouble(steepTemp); // Steep temperature for extract recipes.\n\n // Fields for auto-calculation ====================================\n // ================================================================\n p.writeInt(calculateBoilVolume ? 1 : 0);\n p.writeInt(calculateStrikeVolume ? 1 : 0);\n p.writeInt(calculateStrikeTemp ? 1 : 0);\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n /**\n * Recipe objects are identified by the recipe name and the recipe's ID, as used when stored in\n * the database. If a recipe has not been stored in the database, it will not necessarily have a\n * unique ID.\n */\n @Override\n public boolean equals(Object o) {\n // If the given object is not a Recipe, it cannot be equal.\n if (! (o instanceof Recipe)) {\n return false;\n }\n\n // The given object is a recipe - cast it.\n Recipe other = (Recipe) o;\n\n // Check index fields.\n if (! other.getRecipeName().equals(this.getRecipeName())) {\n // If the given recipe does not have the same name, it is not equal.\n return false;\n }\n else if (other.getId() != this.getId()) {\n // If the given recipe does not have the same ID, it is not equal.\n return false;\n }\n\n // Otherwise, the two recipes are equal.\n return true;\n }\n\n @Override\n public String toString() {\n return this.getRecipeName();\n }\n\n // Public methods\n public void update() {\n setColor(BrewCalculator.Color(this));\n setOG(BrewCalculator.OriginalGravity(this));\n setBitterness(BrewCalculator.Bitterness(this));\n setFG(BrewCalculator.FinalGravity(this));\n setABV(BrewCalculator.AlcoholByVolume(this));\n this.instructionGenerator.generate();\n }\n\n public String getRecipeName() {\n return this.name;\n }\n\n public void setRecipeName(String name) {\n this.name = name;\n }\n\n public void addIngredient(Ingredient i) {\n Log.d(getRecipeName() + \"::addIngredient\", \"Adding ingredient: \" + i.getName());\n if (i.getType().equals(Ingredient.HOP)) {\n addHop(i);\n }\n else if (i.getType().equals(Ingredient.FERMENTABLE)) {\n addFermentable(i);\n }\n else if (i.getType().equals(Ingredient.MISC)) {\n addMisc(i);\n }\n else if (i.getType().equals(Ingredient.YEAST)) {\n addYeast(i);\n }\n else if (i.getType().equals(Ingredient.WATER)) {\n addWater(i);\n }\n\n update();\n }\n\n public void removeIngredientWithId(long id) {\n for (Ingredient i : getIngredientList()) {\n if (i.getId() == id) {\n Log.d(\"Recipe\", \"Removing ingredient \" + i.getName());\n removeIngredient(i);\n }\n }\n }\n\n public void removeIngredient(Ingredient i) {\n if (i.getType().equals(Ingredient.HOP)) {\n hops.remove(i);\n }\n else if (i.getType().equals(Ingredient.FERMENTABLE)) {\n fermentables.remove(i);\n }\n else if (i.getType().equals(Ingredient.MISC)) {\n miscs.remove(i);\n }\n else if (i.getType().equals(Ingredient.YEAST)) {\n yeasts.remove(i);\n }\n else if (i.getType().equals(Ingredient.WATER)) {\n waters.remove(i);\n }\n\n if (getIngredientList().contains(i)) {\n Log.d(\"Recipe\", \"Failed to remove ingredient\");\n }\n else {\n Log.d(\"Recipe\", \"Successfully removed ingredient\");\n }\n\n update();\n }\n\n public MashProfile getMashProfile() {\n return this.mashProfile;\n }\n\n public void setMashProfile(MashProfile profile) {\n this.mashProfile = profile;\n this.mashProfile.setRecipe(this);\n update();\n }\n\n public String getNotes() {\n return notes;\n }\n\n public void setNotes(String notes) {\n this.notes = notes;\n }\n\n public BeerStyle getStyle() {\n return style;\n }\n\n public void setStyle(BeerStyle beerStyle) {\n this.style = beerStyle;\n }\n\n public ArrayList<Ingredient> getIngredientList() {\n ArrayList<Ingredient> list = new ArrayList<Ingredient>();\n list.addAll(hops);\n list.addAll(fermentables);\n list.addAll(yeasts);\n list.addAll(miscs);\n list.addAll(waters);\n\n Collections.sort(list, new RecipeIngredientsComparator());\n return list;\n }\n\n public void setIngredientsList(ArrayList<Ingredient> ingredientsList) {\n\n for (Ingredient i : ingredientsList) {\n if (i.getType().equals(Ingredient.HOP)) {\n addHop(i);\n }\n else if (i.getType().equals(Ingredient.FERMENTABLE)) {\n addFermentable(i);\n }\n else if (i.getType().equals(Ingredient.MISC)) {\n addMisc(i);\n }\n else if (i.getType().equals(Ingredient.YEAST)) {\n addYeast(i);\n }\n else if (i.getType().equals(Ingredient.WATER)) {\n addWater(i);\n }\n }\n\n update();\n }\n\n private void addWater(Ingredient i) {\n Water w = (Water) i;\n waters.add(w);\n }\n\n private void addYeast(Ingredient i) {\n Yeast y = (Yeast) i;\n yeasts.add(y);\n }\n\n private void addMisc(Ingredient i) {\n Misc m = (Misc) i;\n miscs.add(m);\n }\n\n private void addFermentable(Ingredient i) {\n Log.d(getRecipeName() + \"::addFermentable\", \"Adding fermentable: \" + i.getName());\n Fermentable f = (Fermentable) i;\n this.fermentables.add(f);\n }\n\n private void addHop(Ingredient i) {\n Hop h = (Hop) i;\n this.hops.add(h);\n }\n\n public ArrayList<Instruction> getInstructionList() {\n return this.instructionGenerator.getInstructions();\n }\n\n public double getOG() {\n return OG;\n }\n\n public void setOG(double gravity) {\n gravity = (double) Math.round(gravity * 1000) / 1000;\n this.OG = gravity;\n }\n\n public double getBitterness() {\n bitterness = (double) Math.round(bitterness * 10) / 10;\n return bitterness;\n }\n\n public void setBitterness(double bitterness) {\n bitterness = (double) Math.round(bitterness * 10) / 10;\n this.bitterness = bitterness;\n }\n\n public double getColor() {\n color = (double) Math.round(color * 10) / 10;\n return color;\n }\n\n public void setColor(double color) {\n color = (double) Math.round(color * 10) / 10;\n this.color = color;\n }\n\n public double getABV() {\n ABV = (double) Math.round(ABV * 10) / 10;\n return ABV;\n }\n\n public void setABV(double aBV) {\n ABV = (double) Math.round(ABV * 10) / 10;\n ABV = aBV;\n }\n\n public int getBatchTime() {\n return batchTime;\n }\n\n public void setBatchTime(int batchTime) {\n this.batchTime = batchTime;\n }\n\n public long getId() {\n return id;\n }\n\n public void setId(long id) {\n this.id = id;\n }\n\n public String getVolumeUnits() {\n return Units.getVolumeUnits();\n }\n\n public double getDisplayBatchSize() {\n if (Units.getVolumeUnits().equals(Units.GALLONS)) {\n return Units.litersToGallons(this.batchSize);\n }\n else {\n return this.batchSize;\n }\n }\n\n public void setDisplayBatchSize(double size) {\n if (Units.getVolumeUnits().equals(Units.GALLONS)) {\n this.batchSize = Units.gallonsToLiters(size);\n }\n else {\n this.batchSize = size;\n }\n }\n\n public double getDisplayMeasuredBatchSize() {\n if (Units.getVolumeUnits().equals(Units.GALLONS)) {\n return Units.litersToGallons(this.measuredVol);\n }\n else {\n return this.measuredVol;\n }\n }\n\n public void setDisplayMeasuredBatchSize(double size) {\n if (Units.getVolumeUnits().equals(Units.GALLONS)) {\n this.measuredVol = Units.gallonsToLiters(size);\n }\n else {\n this.measuredVol = size;\n }\n }\n\n public double getBeerXmlStandardBatchSize() {\n return this.batchSize;\n }\n\n public void setBeerXmlStandardBatchSize(double v) {\n this.batchSize = v;\n }\n\n public double getBeerXmlMeasuredBatchSize() {\n return this.measuredVol;\n }\n\n public void setBeerXmlMeasuredBatchSize(double d) {\n this.measuredVol = d;\n }\n\n public int getBoilTime() {\n return boilTime;\n }\n\n public void setBoilTime(int boilTime) {\n this.boilTime = boilTime;\n }\n\n public double getEfficiency() {\n if (this.getType().equals(EXTRACT)) {\n return 100;\n }\n return efficiency;\n }\n\n public void setEfficiency(double efficiency) {\n this.efficiency = efficiency;\n }\n\n public String getBrewer() {\n return brewer;\n }\n\n public void setBrewer(String brewer) {\n this.brewer = brewer;\n }\n\n public double getDisplayBoilSize() {\n if (Units.getVolumeUnits().equals(Units.GALLONS)) {\n if (this.calculateBoilVolume) {\n return Units.litersToGallons(calculateBoilVolume());\n }\n else {\n return Units.litersToGallons(this.boilSize);\n }\n }\n else {\n if (this.calculateBoilVolume) {\n return calculateBoilVolume();\n }\n else {\n return this.boilSize;\n }\n }\n }\n\n public void setDisplayBoilSize(double size) {\n if (Units.getVolumeUnits().equals(Units.GALLONS)) {\n this.boilSize = Units.gallonsToLiters(size);\n }\n else {\n this.boilSize = size;\n }\n }\n\n private double calculateBoilVolume() {\n // TODO: Get parameters from equipment profile.\n double TRUB_LOSS = Units.gallonsToLiters(.3); // Liters lost\n double SHRINKAGE = .04; // Percent lost\n double EVAP_LOSS = Units.gallonsToLiters(1.5); // Evaporation loss (L/hr)\n\n if (this.type.equals(Recipe.ALL_GRAIN)) {\n return batchSize * (1 + SHRINKAGE) + TRUB_LOSS + (EVAP_LOSS * Units.minutesToHours(boilTime));\n }\n else {\n return (batchSize / 3) * (1 + SHRINKAGE) + TRUB_LOSS + (EVAP_LOSS * Units.minutesToHours\n (boilTime));\n }\n }\n\n public double getBeerXmlStandardBoilSize() {\n return boilSize;\n }\n\n public void setBeerXmlStandardBoilSize(double boilSize) {\n this.boilSize = boilSize;\n }\n\n public String getType() {\n return type;\n }\n\n public void setType(String type) {\n this.type = type;\n }\n\n public double getFG() {\n this.FG = (double) Math.round(FG * 1000) / 1000;\n return this.FG;\n }\n\n public void setFG(double fG) {\n fG = (double) Math.round(fG * 1000) / 1000;\n this.FG = fG;\n }\n\n public int getFermentationStages() {\n return fermentationStages;\n }\n\n public void setFermentationStages(int fermentationStages) {\n this.fermentationStages = fermentationStages;\n }\n\n public int getTotalFermentationDays() {\n return this.primaryAge + this.secondaryAge + this.tertiaryAge;\n }\n\n public int getVersion() {\n return version;\n }\n\n public void setVersion(int version) {\n this.version = version;\n }\n\n public ArrayList<Misc> getMiscList() {\n return miscs;\n }\n\n public ArrayList<Fermentable> getFermentablesList() {\n return fermentables;\n }\n\n public ArrayList<Hop> getHopsList() {\n return hops;\n }\n\n public ArrayList<Yeast> getYeastsList() {\n return yeasts;\n }\n\n public ArrayList<Water> getWatersList() {\n return waters;\n }\n\n /**\n * Generates a list of hops in this recipe with the given use.\n *\n * @param use\n * One of Ingredient.USE_*\n * @return An ArrayList of Ingredients.\n */\n public ArrayList<Ingredient> getHops(String use) {\n ArrayList<Ingredient> list = new ArrayList<Ingredient>();\n for (Hop h : this.getHopsList()) {\n if (h.getUse().equals(use)) {\n list.add(h);\n }\n }\n return list;\n }\n\n public double getMeasuredOG() {\n return this.measuredOG;\n }\n\n public void setMeasuredOG(double d) {\n this.measuredOG = d;\n }\n\n public double getMeasuredFG() {\n return this.measuredFG;\n }\n\n public void setMeasuredFG(double d) {\n this.measuredFG = d;\n }\n\n public int getDisplayCoolToFermentationTemp() {\n // Metric - imperial conversion is performed in Yeast\n for (Yeast y : this.getYeastsList()) {\n return y.getDisplayFermentationTemp();\n }\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n return 65;\n }\n else {\n return (int) Units.fahrenheitToCelsius(65);\n }\n }\n\n public double getDisplaySteepTemp() {\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n return Units.celsiusToFahrenheit(steepTemp);\n }\n else {\n return steepTemp;\n }\n }\n\n public void setDisplaySteepTemp(double t) {\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n this.steepTemp = Units.fahrenheitToCelsius(t);\n }\n else {\n this.steepTemp = t;\n }\n }\n\n public void setNumberFermentationStages(int stages) {\n this.fermentationStages = stages;\n }\n\n public void setFermentationAge(int stage, int age) {\n switch (stage) {\n case STAGE_PRIMARY:\n this.primaryAge = age;\n case STAGE_SECONDARY:\n this.secondaryAge = age;\n case STAGE_TERTIARY:\n this.tertiaryAge = age;\n }\n }\n\n public int getFermentationAge(int stage) {\n switch (stage) {\n case STAGE_PRIMARY:\n return this.primaryAge;\n case STAGE_SECONDARY:\n return this.secondaryAge;\n case STAGE_TERTIARY:\n return this.tertiaryAge;\n default:\n return 7;\n }\n }\n\n public void setBeerXmlStandardFermentationTemp(int stage, double temp) {\n switch (stage) {\n case STAGE_PRIMARY:\n this.primaryTemp = temp;\n case STAGE_SECONDARY:\n this.secondaryTemp = temp;\n case STAGE_TERTIARY:\n this.tertiaryTemp = temp;\n }\n }\n\n public double getBeerXmlStandardFermentationTemp(int stage) {\n switch (stage) {\n case STAGE_PRIMARY:\n return this.primaryTemp;\n case STAGE_SECONDARY:\n return this.secondaryTemp;\n case STAGE_TERTIARY:\n return this.tertiaryTemp;\n default:\n return 21;\n }\n }\n\n public void setDisplayFermentationTemp(int stage, double temp) {\n switch (stage) {\n case STAGE_PRIMARY:\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n this.primaryTemp = Units.fahrenheitToCelsius(temp);\n }\n else {\n this.primaryTemp = temp;\n }\n break;\n\n case STAGE_SECONDARY:\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n this.secondaryTemp = Units.fahrenheitToCelsius(temp);\n }\n else {\n this.secondaryTemp = temp;\n }\n break;\n\n case STAGE_TERTIARY:\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n this.tertiaryTemp = Units.fahrenheitToCelsius(temp);\n }\n else {\n this.secondaryTemp = temp;\n }\n break;\n }\n }\n\n public double getDisplayFermentationTemp(int stage) {\n switch (stage) {\n case STAGE_PRIMARY:\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n return Units.celsiusToFahrenheit(this.primaryTemp);\n }\n else {\n return this.primaryTemp;\n }\n\n case STAGE_SECONDARY:\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n return Units.celsiusToFahrenheit(this.secondaryTemp);\n }\n else {\n return this.secondaryTemp;\n }\n\n case STAGE_TERTIARY:\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n return Units.celsiusToFahrenheit(this.tertiaryTemp);\n }\n else {\n return this.tertiaryTemp;\n }\n\n default:\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n return Units.celsiusToFahrenheit(21);\n }\n else {\n return 21;\n }\n }\n }\n\n public String getTasteNotes() {\n if (this.tasteNotes == null) {\n this.tasteNotes = \"\";\n }\n return this.tasteNotes;\n }\n\n public void setTasteNotes(String s) {\n this.tasteNotes = s;\n }\n\n public int getTasteRating() {\n return this.tasteRating;\n }\n\n public void setTasteRating(int i) {\n this.tasteRating = i;\n }\n\n public int getBottleAge() {\n return this.bottleAge;\n }\n\n public void setBottleAge(int i) {\n this.bottleAge = i;\n }\n\n public double getBeerXmlStandardBottleTemp() {\n return this.bottleTemp;\n }\n\n public void setBeerXmlStandardBottleTemp(double d) {\n this.bottleTemp = d;\n }\n\n public double getDisplayBottleTemp() {\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n return Units.celsiusToFahrenheit(this.bottleTemp);\n }\n else {\n return this.bottleTemp;\n }\n }\n\n public void setDisplayBottleTemp(double d) {\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n this.bottleTemp = Units.fahrenheitToCelsius(d);\n }\n else {\n this.bottleTemp = d;\n }\n }\n\n public boolean isForceCarbonated() {\n return this.isForceCarbonated;\n }\n\n public void setIsForceCarbonated(boolean b) {\n this.isForceCarbonated = b;\n }\n\n public double getCarbonation() {\n return this.carbonation;\n }\n\n public void setCarbonation(double d) {\n this.carbonation = d;\n }\n\n public void setLastModified(String s) {\n this.lastModified = s;\n }\n\n public Date getLastModified() {\n try {\n Date d = new SimpleDateFormat(Constants.LAST_MODIFIED_DATE_FMT).parse(this.lastModified);\n Log.d(\"Recipe\", this.toString() + \" was last modified \" + d.toString());\n return d;\n } catch (ParseException e) {\n Log.w(\"Recipe\", \"Failed to parse lastModified: \" + this.lastModified);\n return new Date();\n } catch (NullPointerException e) {\n // No modified date was ever set - likely a recipe from before this\n // feature existed.\n Log.w(\"Recipe\", \"No last modified for recipe: \" + this.toString());\n return new Date();\n }\n }\n\n public String getBrewDate() {\n if (this.brewDate == null) {\n this.brewDate = \"\";\n }\n return this.brewDate;\n }\n\n public void setBrewDate(String s) {\n this.brewDate = s;\n }\n\n /* There is no standardized date format in beerXML. Thus, we need\n * to try and parse as many formats as possible. This method takes the given raw\n * date string and returns the best effort Date object. If not we're unable to parse\n * the date, then this method returns today's date.\n */\n public Date getBrewDateDate() {\n // First, try the common date formats to speed things up. We'll resort to a full search\n // of known formats if these fail.\n String d = this.getBrewDate();\n\n // This format is common for BeerSmith recipes.\n try {\n return new SimpleDateFormat(\"MM/dd/yyyy\").parse(d);\n } catch (ParseException e) {\n // Do nothing.\n }\n\n // This format is used by Biermacht.\n try {\n return new SimpleDateFormat(\"dd MMM yyyy\").parse(d);\n } catch (ParseException e) {\n // Do nothing.\n }\n\n // This takes a long time, so only do it as a last resort.\n // Look through a bunch of known formats to figure out what it is.\n String fmt = DateUtil.determineDateFormat(d);\n if (fmt == null) {\n Log.w(\"Recipe\", \"Failed to parse date: \" + d);\n return new Date();\n }\n try {\n return new SimpleDateFormat(fmt).parse(d);\n } catch (ParseException e) {\n Log.e(\"Recipe\", \"Failed to parse date: \" + d);\n e.printStackTrace();\n return new Date();\n }\n }\n\n public String getPrimingSugarName() {\n return this.primingSugarName;\n }\n\n public void setPrimingSugarName(String s) {\n this.primingSugarName = s;\n }\n\n public double getPrimingSugarEquiv() {\n // TODO\n return 0.0;\n }\n\n public void setPrimingSugarEquiv(double d) {\n this.primingSugarEquiv = d;\n }\n\n public double getBeerXmlStandardCarbonationTemp() {\n return this.carbonationTemp;\n }\n\n public void setBeerXmlStandardCarbonationTemp(double d) {\n this.carbonationTemp = d;\n }\n\n public double getDisplayCarbonationTemp() {\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n return Units.celsiusToFahrenheit(this.carbonationTemp);\n }\n else {\n return this.carbonationTemp;\n }\n }\n\n public void setDisplayCarbonationTemp(double d) {\n if (Units.getTemperatureUnits().equals(Units.FAHRENHEIT)) {\n this.carbonationTemp = Units.fahrenheitToCelsius(d);\n }\n else {\n this.carbonationTemp = d;\n }\n }\n\n public double getKegPrimingFactor() {\n return this.kegPrimingFactor;\n }\n\n public void setKegPrimingFactor(double d) {\n this.kegPrimingFactor = d;\n }\n\n public int getCalories() {\n return this.calories;\n }\n\n public void setCalories(int i) {\n this.calories = i;\n }\n\n public boolean getCalculateBoilVolume() {\n return this.calculateBoilVolume;\n }\n\n public void setCalculateBoilVolume(boolean b) {\n this.calculateBoilVolume = b;\n }\n\n public boolean getCalculateStrikeVolume() {\n return this.calculateStrikeVolume;\n }\n\n public void setCalculateStrikeVolume(boolean b) {\n this.calculateStrikeVolume = b;\n }\n\n public boolean getCalculateStrikeTemp() {\n return this.calculateStrikeTemp;\n }\n\n public void setCalculateStrikeTemp(boolean b) {\n this.calculateStrikeTemp = b;\n }\n\n public double getMeasuredABV() {\n if (this.getMeasuredFG() > 0 && this.getMeasuredOG() > this.getMeasuredFG()) {\n return (this.getMeasuredOG() - this.getMeasuredFG()) * 131;\n }\n else {\n return 0;\n }\n }\n\n public double getMeasuredEfficiency() {\n double potGravP, measGravP;\n double eff = 100;\n double measBatchSize = this.getBeerXmlMeasuredBatchSize();\n\n // If the user hasn't input a measured batch size, assume the recipe went as planned\n // and that the target final batch size was hit.\n if (measBatchSize == 0) {\n Log.d(\"Recipe\", \"No measured batch size, try using recipe batch size\");\n measBatchSize = this.getBeerXmlStandardBatchSize();\n }\n\n if (! this.getType().equals(Recipe.EXTRACT)) {\n eff = getEfficiency();\n }\n\n // Computation only valid if measured gravity is greater than 1, and batch size is non-zero.\n // Theoretically, measured gravity could be less than 1, but we don't support that yet.\n if ((this.getMeasuredOG() > 1) && (batchSize > 0)) {\n // Calculate potential milli-gravity points. Adjust the value returned by the\n // brew calculator, because it takes the expected efficiency into account (which\n // we don't want here).\n potGravP = (BrewCalculator.OriginalGravity(this) - 1) / (eff / 100);\n\n // Adjust potential gravity points to account for measured batch size.\n potGravP = potGravP * (getBeerXmlStandardBatchSize() / measBatchSize);\n\n // Calculate the measured milli-gravity points.\n measGravP = this.getMeasuredOG() - 1;\n\n // Return the efficiency.\n return 100 * measGravP / potGravP;\n }\n else {\n return 0;\n }\n }\n\n public void save(Context c) {\n Log.d(getRecipeName() + \"::save\", \"Saving with id: \" + this.getId());\n new DatabaseAPI(c).updateRecipe(this);\n }\n}"
] | import android.content.Context;
import android.os.Environment;
import android.util.Log;
import com.biermacht.brews.ingredient.Fermentable;
import com.biermacht.brews.ingredient.Hop;
import com.biermacht.brews.ingredient.Misc;
import com.biermacht.brews.ingredient.Water;
import com.biermacht.brews.ingredient.Yeast;
import com.biermacht.brews.recipe.BeerStyle;
import com.biermacht.brews.recipe.MashProfile;
import com.biermacht.brews.recipe.MashStep;
import com.biermacht.brews.recipe.Recipe;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult; | Element colorElement = d.createElement("COLOR");
Element addAfterBoilElement = d.createElement("ADD_AFTER_BOIL");
// Assign values
nameElement.setTextContent(f.getName());
versionElement.setTextContent(f.getVersion() + "");
typeElement.setTextContent(f.getFermentableType());
amountElement.setTextContent(f.getBeerXmlStandardAmount() + "");
yieldElement.setTextContent(f.getYield() + "");
colorElement.setTextContent(f.getLovibondColor() + "");
addAfterBoilElement.setTextContent(f.isAddAfterBoil() + "");
// Attach to element.
fermentableElement.appendChild(nameElement);
fermentableElement.appendChild(versionElement);
fermentableElement.appendChild(typeElement);
fermentableElement.appendChild(amountElement);
fermentableElement.appendChild(yieldElement);
fermentableElement.appendChild(colorElement);
fermentableElement.appendChild(addAfterBoilElement);
// Attach to list of elements.
fermentablesElement.appendChild(fermentableElement);
}
return fermentablesElement;
}
public Element getMiscsChild(Document d, ArrayList<Misc> l) {
// Create the element.
Element miscsElement = d.createElement("MISCS");
for (Misc m : l) {
miscsElement.appendChild(this.getMiscChild(d, m));
}
return miscsElement;
}
public Element getMiscChild(Document d, Misc m) {
// Create the element.
Element rootElement = d.createElement("MISC");
// Create a mapping of name -> value
Map<String, String> map = new HashMap<String, String>();
map.put("NAME", m.getName());
map.put("VERSION", m.getVersion() + "");
map.put("TYPE", m.getType());
map.put("USE", m.getUse());
map.put("AMOUNT", String.format("%2.8f", m.getBeerXmlStandardAmount()));
map.put("DISPLAY_AMOUNT", m.getDisplayAmount() + " " + m.getDisplayUnits());
map.put("DISPLAY_TIME", m.getTime() + " " + m.getTimeUnits());
map.put("AMOUNT_IS_WEIGHT", m.amountIsWeight() ? "true" : "false");
map.put("NOTES", m.getShortDescription());
map.put("USE_FOR", m.getUseFor());
for (Map.Entry<String, String> e : map.entrySet()) {
String fieldName = e.getKey();
String fieldValue = e.getValue();
Element element = d.createElement(fieldName);
element.setTextContent(fieldValue);
rootElement.appendChild(element);
}
return rootElement;
}
public Element getYeastsChild(Document d, ArrayList<Yeast> l) {
// Create the element.
Element yeastsElement = d.createElement("YEASTS");
for (Yeast y : l) {
Element yeastElement = d.createElement("YEAST");
// Create fields of element
Element nameElement = d.createElement("NAME");
Element versionElement = d.createElement("VERSION");
Element typeElement = d.createElement("TYPE");
Element formElement = d.createElement("FORM");
Element amountElement = d.createElement("AMOUNT");
Element laboratoryElement = d.createElement("LABORATORY");
Element productIdElement = d.createElement("PRODUCT_ID");
Element minTempElement = d.createElement("MIN_TEMPERATURE");
Element maxTempElement = d.createElement("MAX_TEMPERATURE");
Element attenuationElement = d.createElement("ATTENUATION");
// Assign values
nameElement.setTextContent(y.getName());
versionElement.setTextContent(y.getVersion() + "");
typeElement.setTextContent(y.getType());
formElement.setTextContent(y.getForm());
amountElement.setTextContent(y.getBeerXmlStandardAmount() + "");
laboratoryElement.setTextContent(y.getLaboratory());
productIdElement.setTextContent(y.getProductId());
minTempElement.setTextContent(y.getBeerXmlStandardFermentationTemp() + "");
maxTempElement.setTextContent(y.getBeerXmlStandardFermentationTemp() + "");
attenuationElement.setTextContent(y.getAttenuation() + "");
// Attach to element.
yeastElement.appendChild(nameElement);
yeastElement.appendChild(versionElement);
yeastElement.appendChild(typeElement);
yeastElement.appendChild(amountElement);
yeastElement.appendChild(laboratoryElement);
yeastElement.appendChild(productIdElement);
yeastElement.appendChild(minTempElement);
yeastElement.appendChild(maxTempElement);
yeastElement.appendChild(attenuationElement);
// Attach to list of elements.
yeastsElement.appendChild(yeastElement);
}
return yeastsElement;
}
public Element getWatersChild(Document d, ArrayList<Water> l) {
return d.createElement("WATERS");
}
| public Element getMashChild(Document d, MashProfile m) { | 6 |
nongdenchet/android-mvvm-with-tests | app/src/androidTest/java/apidez/com/android_mvvm_sample/view/fragment/PlacesFragmentIntegrationTest.java | [
"public class ComponentBuilder {\n private AppComponent appComponent;\n\n public ComponentBuilder(AppComponent appComponent) {\n this.appComponent = appComponent;\n }\n\n public PlacesComponent placesComponent() {\n return appComponent.plus(new PlacesModule());\n }\n\n public PurchaseComponent purchaseComponent() {\n return appComponent.plus(new PurchaseModule());\n }\n}",
"@Singleton\n@Component(modules = {AppModule.class})\npublic interface AppComponent {\n PlacesComponent plus(PlacesModule placesModule);\n PurchaseComponent plus(PurchaseModule purchaseModule);\n}",
"@ViewScope\n@Subcomponent(modules = {PlacesModule.class})\npublic interface PlacesComponent {\n void inject(PlacesFragment placesFragment);\n}",
"@Module\npublic class PlacesModule {\n @Provides\n @ViewScope\n public IPlacesApi providePlacesApi() {\n return RetrofitUtils.create(IPlacesApi.class, \"https://maps.googleapis.com/maps/api/place/\");\n }\n\n @Provides\n @ViewScope\n public IPlacesViewModel providePlacesViewModel(IPlacesApi placesApi) {\n return new PlacesViewModel(placesApi);\n }\n}",
"public interface IPlacesApi {\n @GET(\"nearbysearch/json?location=10.7864422,106.677516&radius=500&types=food&key=AIzaSyBk3A8Q3pqVWYYmZhODbE-D2lf2ZHEoKuo\")\n Observable<GoogleSearchResult> placesResult();\n}",
"public class ApplicationUtils {\n public static TestApplication application() {\n Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();\n return (TestApplication) instrumentation.getTargetContext().getApplicationContext();\n }\n}",
"public class TestDataUtils {\n\n /**\n * Google search nearby test data\n */\n public static GoogleSearchResult nearByData() {\n List<Place> places = new ArrayList<>();\n places.add(new Place.Builder().name(\"A\").types(Arrays.asList(\"food\", \"cafe\")).build());\n places.add(new Place.Builder().name(\"B\").types(Arrays.asList(\"food\", \"movie_theater\")).build());\n places.add(new Place.Builder().name(\"C\").types(Arrays.asList(\"store\")).build());\n places.add(new Place.Builder().name(\"D\").types(Arrays.asList(\"store\")).build());\n places.add(new Place.Builder().name(\"E\").types(Arrays.asList(\"cafe\")).build());\n places.add(new Place.Builder().name(\"F\").types(Arrays.asList(\"food\", \"store\", \"cafe\", \"movie_theater\")).build());\n places.add(new Place.Builder().name(\"G\").types(Arrays.asList(\"restaurant\", \"store\")).build());\n places.add(new Place.Builder().name(\"H\").types(Arrays.asList(\"restaurant\", \"cafe\")).build());\n places.add(new Place.Builder().name(\"I\").types(Arrays.asList(\"restaurant\")).build());\n places.add(new Place.Builder().name(\"K\").types(Arrays.asList(\"movie_theater\", \"cafe\", \"food\")).build());\n GoogleSearchResult googleSearchResult = new GoogleSearchResult();\n googleSearchResult.status = \"OK\";\n googleSearchResult.results = places;\n return googleSearchResult;\n }\n}",
"public class EmptyActivity extends BaseActivity {\n}",
"public static Matcher<View> hasItemCount(int count) {\n return new TypeSafeMatcher<View>() {\n @Override\n public void describeTo(Description description) {\n description.appendText(\"has items\");\n }\n\n @TargetApi(Build.VERSION_CODES.JELLY_BEAN)\n @Override\n public boolean matchesSafely(View view) {\n try {\n return ((RecyclerView) view).getAdapter().getItemCount() == count;\n } catch (Exception exception) {\n return false;\n }\n }\n };\n}"
] | import android.content.Intent;
import android.support.test.rule.ActivityTestRule;
import android.test.suitebuilder.annotation.MediumTest;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.mockito.Mockito;
import apidez.com.android_mvvm_sample.ComponentBuilder;
import apidez.com.android_mvvm_sample.R;
import apidez.com.android_mvvm_sample.dependency.component.AppComponent;
import apidez.com.android_mvvm_sample.dependency.component.PlacesComponent;
import apidez.com.android_mvvm_sample.dependency.module.PlacesModule;
import apidez.com.android_mvvm_sample.model.api.IPlacesApi;
import apidez.com.android_mvvm_sample.utils.ApplicationUtils;
import apidez.com.android_mvvm_sample.utils.TestDataUtils;
import apidez.com.android_mvvm_sample.view.activity.EmptyActivity;
import rx.Observable;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
import static apidez.com.android_mvvm_sample.utils.MatcherEx.hasItemCount;
import static org.mockito.Mockito.when; | package apidez.com.android_mvvm_sample.view.fragment;
/**
* Created by nongdenchet on 10/22/15.
*/
@MediumTest
@RunWith(JUnit4.class)
public class PlacesFragmentIntegrationTest {
@Rule
public ActivityTestRule<EmptyActivity> activityTestRule =
new ActivityTestRule<>(EmptyActivity.class, true, false);
@Before
public void setUp() throws Exception {
PlacesModule mockModule = new PlacesModule() {
@Override
public IPlacesApi providePlacesApi() {
IPlacesApi placesApi = Mockito.mock(IPlacesApi.class);
when(placesApi.placesResult()) | .thenReturn(Observable.just(TestDataUtils.nearByData())); | 6 |
Lambda-3/DiscourseSimplification | src/main/java/org/lambda3/text/simplification/discourse/runner/discourse_tree/extraction/rules/LeadNPExtractor.java | [
"public enum Relation {\n\n UNKNOWN,\n\n // Coordinations\n UNKNOWN_COORDINATION, // the default for coordination\n CONTRAST,\n CAUSE_C,\n RESULT_C,\n LIST,\n DISJUNCTION,\n TEMPORAL_AFTER_C,\n TEMPORAL_BEFORE_C,\n\n // Subordinations\n UNKNOWN_SUBORDINATION, // the default for subordination\n ATTRIBUTION,\n BACKGROUND,\n CAUSE,\n RESULT,\n CONDITION,\n ELABORATION,\n PURPOSE,\n TEMPORAL_AFTER,\n TEMPORAL_BEFORE,\n\n // for sentence simplification\n NOUN_BASED,\n SPATIAL,\n TEMPORAL,\n TEMPORAL_TIME, // indicating a particular instance on a time scale (e.g. “Next Sunday 2 pm”).\n TEMPORAL_DURATION, // the amount of time between the two end-points of a time interval (e.g. “2 weeks\").\n TEMPORAL_DATE, // particular date (e.g. “On 7 April 2013”).\n TEMPORAL_SET, IDENTIFYING_DEFINITION, DESCRIBING_DEFINITION; // periodic temporal sets representing times that occur with some frequency (“Every Tuesday”).\n\n static {\n UNKNOWN_COORDINATION.coordination = true;\n CONTRAST.coordination = true;\n CAUSE_C.coordination = true;\n RESULT_C.coordination = true;\n LIST.coordination = true;\n DISJUNCTION.coordination = true;\n TEMPORAL_AFTER_C.coordination = true;\n TEMPORAL_BEFORE_C.coordination = true;\n\n CAUSE.coordinateVersion = CAUSE_C;\n RESULT.coordinateVersion = RESULT_C;\n TEMPORAL_AFTER.coordinateVersion = TEMPORAL_AFTER_C;\n TEMPORAL_BEFORE.coordinateVersion = TEMPORAL_BEFORE_C;\n\n CAUSE_C.subordinateVersion = CAUSE;\n RESULT_C.subordinateVersion = RESULT;\n TEMPORAL_AFTER_C.subordinateVersion = TEMPORAL_AFTER;\n TEMPORAL_BEFORE_C.subordinateVersion = TEMPORAL_BEFORE;\n\n CAUSE_C.inverse = RESULT_C;\n RESULT_C.inverse = CAUSE_C;\n TEMPORAL_AFTER_C.inverse = TEMPORAL_BEFORE_C;\n TEMPORAL_BEFORE_C.inverse = TEMPORAL_AFTER_C;\n CAUSE.inverse = RESULT;\n RESULT.inverse = CAUSE;\n TEMPORAL_AFTER.inverse = TEMPORAL_BEFORE;\n TEMPORAL_BEFORE.inverse = TEMPORAL_AFTER;\n }\n\n private boolean coordination;\n private Relation regular; // class of context span (in subordination) or right span (coordination)\n private Relation inverse; // class of core span (in subordination) or left span (coordination)\n private Relation coordinateVersion; // optional\n private Relation subordinateVersion; // optional\n\n Relation() {\n this.coordination = false;\n this.regular = this;\n this.inverse = this; // only used in coordinations\n this.coordinateVersion = null;\n this.subordinateVersion = null;\n }\n\n public boolean isCoordination() {\n return coordination;\n }\n\n public Relation getRegulatRelation() {\n return regular;\n }\n\n public Relation getInverseRelation() {\n return inverse;\n }\n\n public Optional<Relation> getCoordinateVersion() {\n return Optional.ofNullable(coordinateVersion);\n }\n\n public Optional<Relation> getSubordinateVersion() {\n return Optional.ofNullable(subordinateVersion);\n }\n}",
"public class Extraction {\n private String extractionRule;\n private boolean referring;\n private String cuePhrase; // optional\n private Relation relation;\n private boolean contextRight; // only for subordinate relations\n private List<Leaf> constituents;\n\n public Extraction(String extractionRule, boolean referring, List<Word> cuePhraseWords, Relation relation, boolean contextRight, List<Leaf> constituents) {\n if ((referring) && (constituents.size() != 1)) {\n throw new AssertionError(\"Referring relations should have one constituent\");\n }\n\n if ((!referring) && (!relation.isCoordination()) && (constituents.size() != 2)) {\n throw new AssertionError(\"(Non-referring) subordinate relations rules should have two constituents\");\n }\n\n this.extractionRule = extractionRule;\n this.referring = referring;\n this.cuePhrase = (cuePhraseWords == null)? null : WordsUtils.wordsToString(cuePhraseWords);\n this.relation = relation;\n this.contextRight = contextRight;\n this.constituents = constituents;\n }\n\n public Optional<DiscourseTree> generate(Leaf currChild) {\n\n if (relation.isCoordination()) {\n if (referring) {\n\n // find previous node to use as a reference\n Optional<DiscourseTree> prevNode = currChild.getPreviousNode();\n if ((prevNode.isPresent()) && (prevNode.get().usableAsReference())) {\n\n // use prev node as a reference\n prevNode.get().useAsReference();\n\n Coordination res = new Coordination(\n extractionRule,\n relation,\n cuePhrase,\n Collections.emptyList()\n );\n res.addCoordination(prevNode.get()); // set prev node as a reference\n res.addCoordination(constituents.get(0));\n\n return Optional.of(res);\n }\n } else {\n return Optional.of(new Coordination(\n extractionRule,\n relation,\n cuePhrase,\n constituents.stream().collect(Collectors.toList())\n ));\n }\n } else {\n if (referring) {\n\n // find previous node to use as a reference\n Optional<DiscourseTree> prevNode = currChild.getPreviousNode();\n if ((prevNode.isPresent()) && (prevNode.get().usableAsReference())) {\n\n // use prev node as a reference\n prevNode.get().useAsReference();\n\n Subordination res = new Subordination(\n extractionRule,\n relation,\n cuePhrase,\n new Leaf(), // tmp\n constituents.get(0),\n contextRight\n );\n res.replaceLeftConstituent(prevNode.get()); // set prev node as a reference\n\n return Optional.of(res);\n }\n } else {\n return Optional.of(new Subordination(\n extractionRule,\n relation,\n cuePhrase,\n constituents.get(0),\n constituents.get(1),\n contextRight\n ));\n }\n }\n\n return Optional.empty();\n }\n}",
"public abstract class ExtractionRule {\n protected static final Logger LOGGER = LoggerFactory.getLogger(ExtractionRule.class);\n\n protected enum Tense {\n PRESENT,\n PAST\n }\n\n protected enum Number {\n SINGULAR,\n PLURAL\n }\n\n protected CuePhraseClassifier classifer;\n\n public ExtractionRule() {\n }\n\n public void setConfig(Config config) {\n this.classifer = new CuePhraseClassifier(config);\n }\n\n public abstract Optional<Extraction> extract(Leaf leaf) throws ParseTreeException;\n\n protected static List<Tree> getSiblings(Tree parseTree, List<String> tags) {\n return parseTree.getChildrenAsList().stream().filter(c -> tags.contains(c.value())).collect(Collectors.toList());\n }\n\n protected static Number getNumber(Tree np) {\n Number res = Number.SINGULAR;\n\n // find plural forms\n TregexPattern p = TregexPattern.compile(\"NNS|NNPS\");\n TregexMatcher matcher = p.matcher(np);\n if (matcher.find()) {\n res = Number.PLURAL;\n }\n\n // find and\n p = TregexPattern.compile(\"CC <<: and\");\n matcher = p.matcher(np);\n if (matcher.find()) {\n res = Number.PLURAL;\n }\n\n return res;\n }\n\n protected static Tense getTense(Tree vp) {\n Tense res = Tense.PRESENT;\n\n // find past tense\n TregexPattern p = TregexPattern.compile(\"VBD|VBN\");\n TregexMatcher matcher = p.matcher(vp);\n\n if (matcher.find()) {\n res = Tense.PAST;\n }\n\n return res;\n }\n\n protected static Optional<Word> getHeadVerb(Tree vp) {\n TregexPattern pattern = TregexPattern.compile(vp.value() + \" [ <+(VP) (VP=lowestvp !< VP < /V../=v) | ==(VP=lowestvp !< VP < /V../=v) ]\");\n TregexMatcher matcher = pattern.matcher(vp);\n while (matcher.findAt(vp)) {\n return Optional.of(ParseTreeExtractionUtils.getContainingWords(matcher.getNode(\"v\")).get(0));\n }\n return Optional.empty();\n }\n\n private static List<Word> appendWordsFromTree(List<Word> words, Tree tree) {\n List<Word> res = new ArrayList<Word>();\n res.addAll(words);\n\n TregexPattern p = TregexPattern.compile(tree.value() + \" <<, NNP|NNPS\");\n TregexMatcher matcher = p.matcher(tree);\n\n boolean isFirst = true;\n for (Word word : tree.yieldWords()) {\n if ((isFirst) && (!matcher.findAt(tree))) {\n res.add(WordsUtils.lowercaseWord(word));\n } else {\n res.add(word);\n }\n isFirst = false;\n }\n\n return res;\n }\n\n // pp is optional\n protected static List<Word> rephraseIntraSententialAttribution(List<Word> words) {\n try {\n List<Word> res = new ArrayList<>();\n\n Tree parseTree = ParseTreeParser.parse(WordsUtils.wordsToProperSentenceString(words));\n\n TregexPattern p = TregexPattern.compile(\"ROOT << (S !> S < (NP=np ?$,, PP=pp $.. VP=vp))\");\n TregexMatcher matcher = p.matcher(parseTree);\n if (matcher.findAt(parseTree)) {\n Tree pp = matcher.getNode(\"pp\"); // optional\n Tree np = matcher.getNode(\"np\");\n Tree vp = matcher.getNode(\"vp\");\n\n Tense tense = getTense(vp);\n if (tense.equals(Tense.PRESENT)) {\n res.add(new Word(\"This\"));\n res.add(new Word(\"is\"));\n res.add(new Word(\"what\"));\n } else {\n res.add(new Word(\"This\"));\n res.add(new Word(\"was\"));\n res.add(new Word(\"what\"));\n }\n res = appendWordsFromTree(res, np);\n res = appendWordsFromTree(res, vp);\n if (pp != null) {\n res = appendWordsFromTree(res, pp);\n }\n }\n\n return res;\n } catch (ParseTreeException e) {\n return words;\n }\n }\n\n protected static List<Word> rephraseEnablement(Tree s, Tree vp) {\n List<Word> res = new ArrayList<>();\n\n Tense tense = getTense(vp);\n if (tense.equals(Tense.PRESENT)) {\n res.add(new Word(\"This\"));\n res.add(new Word(\"is\"));\n } else {\n res.add(new Word(\"This\"));\n res.add(new Word(\"was\"));\n }\n res = appendWordsFromTree(res, s);\n\n return res;\n }\n\n \n protected static String rephraseApposition(Tree vp, String np) {\n String res = \"\";\n\n Tense tense = getTense(vp);\n //Number number = getNumber(np);\n if (tense.equals(Tense.PRESENT)) {\n \tif (np.equals(\"NN\") || np.equals(\"NNP\")) {\n \t\tres = \" is \";\n \t} else {\n \t\tres = \" are \";\n \t}\n } else {\n \tif (np.equals(\"NN\") || np.equals(\"NNP\")) {\n \t\tres = \" was \";\n \t} else {\n \t\tres = \" were \";\n \t}\n }\n \n return res;\n }\n \n protected static List<Word> rephraseAppositionNonRes(Tree vp, Tree np, Tree np2) {\n List<Word> res = new ArrayList<>();\n\n Tense tense = getTense(vp);\n Number number = getNumber(np);\n if (tense.equals(Tense.PRESENT)) {\n \tif (number.equals(Number.SINGULAR)) {\n \t\t res.add(new Word(\"is\"));\n \t} else {\n \t\t res.add(new Word(\"are\"));\n \t}\n } else {\n \tif (number.equals(Number.SINGULAR)) {\n \t\t res.add(new Word(\"was\"));\n \t} else {\n \t\t res.add(new Word(\"were\"));\n \t}\n }\n res = appendWordsFromTree(res, np2);\n \n return res;\n }\n\n\n protected static List<Word> getRephrasedParticipalS(Tree np, Tree vp, Tree s, Tree vbgn) {\n Number number = getNumber(np);\n Tense tense = getTense(vp);\n\n TregexPattern p = TregexPattern.compile(vbgn.value() + \" <<: (having . (been . VBN=vbn))\");\n TregexPattern p2 = TregexPattern.compile(vbgn.value() + \" <<: (having . VBN=vbn)\");\n TregexPattern p3 = TregexPattern.compile(vbgn.value() + \" <<: (being . VBN=vbn)\");\n\n TregexMatcher matcher = p.matcher(s);\n if (matcher.findAt(s)) {\n List<Word> res = new ArrayList<>();\n\n res.add(new Word((number.equals(Number.SINGULAR))? \"has\" : \"have\"));\n res.add(new Word(\"been\"));\n List<Word> next = ParseTreeExtractionUtils.getFollowingWords(s, matcher.getNode(\"vbn\"), true);\n if (next.size() > 0) {\n next.set(0, WordsUtils.lowercaseWord(next.get(0)));\n }\n res.addAll(next);\n\n return res;\n }\n\n matcher = p2.matcher(s);\n if (matcher.findAt(s)) {\n List<Word> res = new ArrayList<>();\n\n res.add(new Word((number.equals(Number.SINGULAR))? \"has\" : \"have\"));\n List<Word> next = ParseTreeExtractionUtils.getFollowingWords(s, matcher.getNode(\"vbn\"), true);\n if (next.size() > 0) {\n next.set(0, WordsUtils.lowercaseWord(next.get(0)));\n }\n res.addAll(next);\n\n return res;\n }\n\n matcher = p3.matcher(s);\n if (matcher.findAt(s)) {\n List<Word> res = new ArrayList<>();\n if (tense.equals(Tense.PRESENT)) {\n res.add(new Word((number.equals(Number.SINGULAR)) ? \"is\" : \"are\"));\n } else {\n res.add(new Word((number.equals(Number.SINGULAR)) ? \"was\" : \"were\"));\n }\n List<Word> next = ParseTreeExtractionUtils.getFollowingWords(s, matcher.getNode(\"vbn\"), true);\n if (next.size() > 0) {\n next.set(0, WordsUtils.lowercaseWord(next.get(0)));\n }\n res.addAll(next);\n\n return res;\n }\n\n // default\n List<Word> res = new ArrayList<>();\n if (tense.equals(Tense.PRESENT)) {\n res.add(new Word((number.equals(Number.SINGULAR)) ? \"is\" : \"are\"));\n } else {\n res.add(new Word((number.equals(Number.SINGULAR)) ? \"was\" : \"were\"));\n }\n List<Word> next = ParseTreeExtractionUtils.getFollowingWords(s, vbgn, true);\n if (next.size() > 0) {\n next.set(0, WordsUtils.lowercaseWord(next.get(0)));\n }\n res.addAll(next);\n\n return res;\n }\n\n}",
"public class Leaf extends DiscourseTree {\n private Tree parseTree;\n private boolean allowSplit; // true, if extraction-rules will be applied on the text\n private boolean toSimpleContext;\n\n public Leaf() {\n super(\"UNKNOWN\");\n }\n\n public Leaf(String extractionRule, Tree parseTree) {\n super(extractionRule);\n this.parseTree = parseTree;\n this.allowSplit = true;\n this.toSimpleContext = false;\n }\n\n // not efficient -> prefer to use constructor with tree\n public Leaf(String extractionRule, String text) throws ParseTreeException {\n this(extractionRule, ParseTreeParser.parse(text));\n }\n\n public void dontAllowSplit() {\n this.allowSplit = false;\n }\n\n public Tree getParseTree() {\n return parseTree;\n }\n\n public void setParseTree(Tree parseTree) {\n this.parseTree = parseTree;\n }\n\n public String getText() {\n return WordsUtils.wordsToString(ParseTreeExtractionUtils.getContainingWords(parseTree));\n }\n\n public void setToSimpleContext(boolean toSimpleContext) {\n this.toSimpleContext = toSimpleContext;\n }\n\n public boolean isAllowSplit() {\n return allowSplit;\n }\n\n public boolean isToSimpleContext() {\n return toSimpleContext;\n }\n\n // VISUALIZATION ///////////////////////////////////////////////////////////////////////////////////////////////////\n\n @Override\n public List<String> getPTPCaption() {\n return Collections.singletonList(\"'\" + getText() + \"'\");\n }\n\n @Override\n public List<PrettyTreePrinter.Edge> getPTPEdges() {\n return new ArrayList<>();\n }\n}",
"public class ParseTreeException extends Exception {\n\n public ParseTreeException(String text) {\n super(\"Failed to parse text: \\\"\" + text + \"\\\"\");\n }\n}",
"public class ParseTreeExtractionUtils {\n\n public interface INodeChecker {\n boolean check(Tree anchorTree, Tree node);\n }\n\n\n public static List<Integer> getLeafNumbers(Tree anchorTree, Tree node) {\n List<Integer> res = new ArrayList<>();\n for (Tree leaf : node.getLeaves()) {\n res.add(leaf.nodeNumber(anchorTree));\n }\n return res;\n }\n\n private static IndexRange getLeafIndexRange(Tree anchorTree, Tree node) {\n int fromIdx = -1;\n int toIdx = -1;\n\n List<Integer> leafNumbers = getLeafNumbers(anchorTree, anchorTree);\n List<Integer> nodeLeafNumbers = getLeafNumbers(anchorTree, node);\n int fromNumber = nodeLeafNumbers.get(0);\n int toNumber = nodeLeafNumbers.get(nodeLeafNumbers.size() - 1);\n\n int idx = 0;\n for (int leafNumber : leafNumbers) {\n if (leafNumber == fromNumber) {\n fromIdx = idx;\n }\n if (leafNumber == toNumber) {\n toIdx = idx;\n }\n ++idx;\n }\n\n if ((fromIdx >= 0) && (toIdx >= 0)) {\n return new IndexRange(fromIdx, toIdx);\n } else {\n throw new IllegalArgumentException(\"node should be a subtree of anchorTree.\");\n }\n }\n\n // returns True, if the model of node would not check/divide a NER group, else False\n public static boolean isNERSafeExtraction(Tree anchorTree, NERString anchorNERString, Tree node) {\n IndexRange leafIdxRange = getLeafIndexRange(anchorTree, node);\n List<IndexRange> nerIdxRanges = NERExtractionUtils.getNERIndexRanges(anchorNERString);\n\n for (IndexRange nerIdxRange : nerIdxRanges) {\n if (((nerIdxRange.getFromIdx() < leafIdxRange.getFromIdx()) && (leafIdxRange.getFromIdx() <= nerIdxRange.getToIdx()))\n || ((nerIdxRange.getFromIdx() <= leafIdxRange.getToIdx()) && (leafIdxRange.getToIdx() < nerIdxRange.getToIdx()))) {\n return false;\n }\n }\n\n return true;\n }\n\n\n\n\n public static List<Word> leavesToWords(List<Tree> leaves) {\n return leaves.stream().map(l -> l.yieldWords().get(0)).collect(Collectors.toList());\n }\n\n public static List<List<Tree>> splitLeaves(Tree anchorTree, List<Tree> leaves, INodeChecker leafChecker, boolean removeEmpty) {\n List<List<Tree>> res = new ArrayList<>();\n List<Tree> currElement = new ArrayList<>();\n for (Tree leaf : leaves) {\n if (leafChecker.check(anchorTree, leaf)) {\n if ((currElement.size() > 0) || (!removeEmpty))\n res.add(currElement);\n currElement = new ArrayList<>();\n } else {\n currElement.add(leaf);\n }\n }\n if ((currElement.size() > 0) || (!removeEmpty))\n res.add(currElement);\n\n return res;\n }\n\n public static List<Tree> findLeaves(Tree anchorTree, List<Tree> leaves, INodeChecker leafChecker, boolean reversed) {\n List<Tree> res = leaves.stream().filter(l -> leafChecker.check(anchorTree, l)).collect(Collectors.toList());\n if (reversed) {\n Collections.reverse(res);\n }\n return res;\n }\n\n public static Tree getFirstLeaf(Tree tree) {\n if (tree.isLeaf()) {\n return tree;\n } else {\n return getFirstLeaf(tree.firstChild());\n }\n }\n\n public static Tree getLastLeaf(Tree tree) {\n if (tree.isLeaf()) {\n return tree;\n } else {\n return getLastLeaf(tree.lastChild());\n }\n }\n\n public static List<Tree> getLeavesInBetween(Tree anchorTree, Tree leftNode, Tree rightNode, boolean includeLeft, boolean includeRight) {\n List<Tree> res = new ArrayList<>();\n\n if (leftNode == null) {\n leftNode = getFirstLeaf(anchorTree);\n }\n if (rightNode == null) {\n rightNode = getLastLeaf(anchorTree);\n }\n\n int startLeafNumber = (includeLeft) ? getFirstLeaf(leftNode).nodeNumber(anchorTree) : getLastLeaf(leftNode).nodeNumber(anchorTree) + 1;\n int endLeafNumber = (includeRight) ? getLastLeaf(rightNode).nodeNumber(anchorTree) : getFirstLeaf(rightNode).nodeNumber(anchorTree) - 1;\n if ((startLeafNumber < 0) || (endLeafNumber < 0)) {\n return res;\n }\n\n for (int i = startLeafNumber; i <= endLeafNumber; ++i) {\n Tree node = anchorTree.getNodeNumber(i);\n if (node.isLeaf()) {\n res.addAll(node);\n }\n }\n\n return res;\n }\n\n public static List<Tree> getPrecedingLeaves(Tree anchorTree, Tree node, boolean include) {\n return getLeavesInBetween(anchorTree, getFirstLeaf(anchorTree), node, true, include);\n }\n\n public static List<Tree> getFollowingLeaves(Tree anchorTree, Tree node, boolean include) {\n return getLeavesInBetween(anchorTree, node, getLastLeaf(anchorTree), include, true);\n }\n\n public static List<Tree> getContainingLeaves(Tree node) {\n return getLeavesInBetween(node, getFirstLeaf(node), getLastLeaf(node), true, true);\n }\n\n public static List<Word> getWordsInBetween(Tree anchorTree, Tree leftNode, Tree rightNode, boolean includeLeft, boolean includeRight) {\n return leavesToWords(getLeavesInBetween(anchorTree, leftNode, rightNode, includeLeft, includeRight));\n }\n\n public static List<Word> getPrecedingWords(Tree anchorTree, Tree node, boolean include) {\n return leavesToWords(getPrecedingLeaves(anchorTree, node, include));\n }\n\n public static List<Word> getFollowingWords(Tree anchorTree, Tree node, boolean include) {\n return leavesToWords(getFollowingLeaves(anchorTree, node, include));\n }\n\n public static List<Word> getContainingWords(Tree node) {\n return leavesToWords(getContainingLeaves(node));\n }\n\n public static Optional<Tree> findSpanningTree(Tree anchorTree, Tree firstLeaf, Tree lastLeaf) {\n return findSpanningTreeRec(anchorTree, anchorTree, firstLeaf, lastLeaf);\n }\n\n private static Optional<Tree> findSpanningTreeRec(Tree anchorTree, Tree currTree, Tree firstLeaf, Tree lastLeaf) {\n int firstNumber = firstLeaf.nodeNumber(anchorTree);\n int lastNumber = lastLeaf.nodeNumber(anchorTree);\n int currFirstNumber = getFirstLeaf(currTree).nodeNumber(anchorTree);\n int currLastNumber = getLastLeaf(currTree).nodeNumber(anchorTree);\n if (((currFirstNumber <= firstNumber) && (firstNumber <= currLastNumber)) && ((currFirstNumber <= lastNumber) && (lastNumber <= currLastNumber))) {\n if ((currFirstNumber == firstNumber) && (lastNumber == currLastNumber)) {\n return Optional.of(currTree);\n } else {\n // recursion\n for (Tree child : currTree.getChildrenAsList()) {\n Optional<Tree> cr = findSpanningTreeRec(anchorTree, child, firstLeaf, lastLeaf);\n if (cr.isPresent()) {\n return Optional.of(cr.get());\n }\n }\n }\n }\n\n return Optional.empty();\n }\n}",
"public class WordsUtils {\n\n public static Word lemmatize(Word word) {\n Sentence sentence = new Sentence(word.value());\n return new Word(sentence.lemma(0));\n }\n\n public static List<Word> splitIntoWords(String sentence) {\n PTBTokenizer<CoreLabel> ptbt = new PTBTokenizer<>(new StringReader(sentence), new CoreLabelTokenFactory(), \"\");\n List<Word> words = new ArrayList<>();\n\n while (ptbt.hasNext()) {\n CoreLabel label = ptbt.next();\n words.add(new Word(label));\n }\n\n return words;\n }\n\n public static String wordsToString(List<Word> words) {\n return SentenceUtils.listToString(words);\n }\n\n public static String wordsToProperSentenceString(List<Word> words) {\n return wordsToString(wordsToProperSentence(words));\n }\n\n private static Word capitalizeWord(Word word) {\n String s = word.value();\n if (s.length() > 0) {\n s = s.substring(0, 1).toUpperCase() + s.substring(1);\n }\n\n return new Word(s);\n }\n\n public static Word lowercaseWord(Word word) {\n return new Word(word.value().toLowerCase());\n }\n\n private static List<Word> wordsToProperSentence(List<Word> words) {\n List<Word> res = new ArrayList<>();\n res.addAll(words);\n\n // trim '.' and ',' at beginning and the end and remove multiple, consecutive occurrences\n for (String c : Arrays.asList(\".\", \",\")) {\n Word prev = null;\n Iterator<Word> it = res.iterator();\n while (it.hasNext()) {\n Word word = it.next();\n if (word.value().equals(c)) {\n if (prev == null || prev.value().equals(word.value())) {\n it.remove();\n }\n }\n prev = word;\n }\n if ((!res.isEmpty()) && (res.get(res.size() - 1).value().equals(c))) {\n res.remove(res.size() - 1);\n }\n }\n\n // add a '.' at the end\n res.add(new Word(\".\"));\n\n // capitalize first word\n if (!res.isEmpty()) {\n res.set(0, capitalizeWord(res.get(0)));\n }\n\n return res;\n }\n}"
] | import org.lambda3.text.simplification.discourse.utils.parseTree.ParseTreeExtractionUtils;
import org.lambda3.text.simplification.discourse.utils.words.WordsUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import edu.stanford.nlp.ling.Word;
import edu.stanford.nlp.trees.tregex.TregexMatcher;
import edu.stanford.nlp.trees.tregex.TregexPattern;
import org.lambda3.text.simplification.discourse.runner.discourse_tree.Relation;
import org.lambda3.text.simplification.discourse.runner.discourse_tree.extraction.Extraction;
import org.lambda3.text.simplification.discourse.runner.discourse_tree.extraction.ExtractionRule;
import org.lambda3.text.simplification.discourse.runner.discourse_tree.model.Leaf;
import org.lambda3.text.simplification.discourse.utils.parseTree.ParseTreeException; | /*
* ==========================License-Start=============================
* DiscourseSimplification : SubordinationPostExtractor
*
* Copyright © 2017 Lambda³
*
* GNU General Public License 3
* 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/.
* ==========================License-End==============================
*/
package org.lambda3.text.simplification.discourse.runner.discourse_tree.extraction.rules;
/**
*
*/
public class LeadNPExtractor extends ExtractionRule {
@Override | public Optional<Extraction> extract(Leaf leaf) throws ParseTreeException { | 4 |
millecker/senti-storm | src/at/illecker/sentistorm/SentiStormTopology.java | [
"public class FeatureGenerationBolt extends BaseBasicBolt {\n public static final String ID = \"feature-generation-bolt\";\n public static final String CONF_LOGGING = ID + \".logging\";\n private static final long serialVersionUID = 5340637976415982170L;\n private static final Logger LOG = LoggerFactory\n .getLogger(FeatureGenerationBolt.class);\n private boolean m_logging = false;\n private Dataset m_dataset;\n private FeatureVectorGenerator m_fvg = null;\n\n @Override\n public void declareOutputFields(OutputFieldsDeclarer declarer) {\n // key of output tuples\n declarer.declare(new Fields(\"text\", \"featureVector\"));\n }\n\n @Override\n public void prepare(Map config, TopologyContext context) {\n this.m_dataset = Configuration.getDataSetSemEval2013();\n\n // Optional set logging\n if (config.get(CONF_LOGGING) != null) {\n m_logging = (Boolean) config.get(CONF_LOGGING);\n } else {\n m_logging = false;\n }\n\n // TODO serialize CombinedFeatureVectorGenerator\n List<FeaturedTweet> featuredTrainTweets = SerializationUtils\n .deserialize(m_dataset.getTrainDataSerializationFile());\n if (featuredTrainTweets != null) {\n TweetTfIdf tweetTfIdf = TweetTfIdf.createFromTaggedTokens(\n FeaturedTweet.getTaggedTokensFromTweets(featuredTrainTweets),\n TfType.LOG, TfIdfNormalization.COS, true);\n\n LOG.info(\"Load CombinedFeatureVectorGenerator...\");\n m_fvg = new CombinedFeatureVectorGenerator(true, tweetTfIdf);\n\n } else {\n LOG.error(\"TaggedTweets could not be found! File is missing: \"\n + m_dataset.getTrainDataSerializationFile());\n }\n }\n\n @Override\n public void execute(Tuple tuple, BasicOutputCollector collector) {\n String text = tuple.getStringByField(\"text\");\n List<TaggedToken> taggedTokens = (List<TaggedToken>) tuple\n .getValueByField(\"taggedTokens\");\n\n // Generate Feature Vector\n Map<Integer, Double> featureVector = m_fvg\n .generateFeatureVector(taggedTokens);\n\n if (m_logging) {\n LOG.info(\"Tweet: \" + text + \" FeatureVector: \" + featureVector);\n }\n\n // Emit new tuples\n collector.emit(new Values(text, featureVector));\n }\n\n}",
"public class POSTaggerBolt extends BaseBasicBolt {\n public static final String ID = \"pos-tagger-bolt\";\n public static final String CONF_LOGGING = ID + \".logging\";\n public static final String CONF_MODEL = ID + \".model\";\n private static final long serialVersionUID = -7890576107718544088L;\n private static final Logger LOG = LoggerFactory\n .getLogger(POSTaggerBolt.class);\n private boolean m_logging = false;\n\n private Model m_model;\n private FeatureExtractor m_featureExtractor;\n\n @Override\n public void declareOutputFields(OutputFieldsDeclarer declarer) {\n // key of output tuples\n declarer.declare(new Fields(\"text\", \"taggedTokens\"));\n }\n\n @Override\n public void prepare(Map config, TopologyContext context) {\n // Optional set logging\n if (config.get(CONF_LOGGING) != null) {\n m_logging = (Boolean) config.get(CONF_LOGGING);\n } else {\n m_logging = false;\n }\n\n // Load POS Tagger\n String taggingModel = Configuration.get(\"sentistorm.bolt.postagger.model\");\n LOG.info(\"Load POS Tagger model: \" + taggingModel + \"_model.ser\");\n m_model = SerializationUtils.deserialize(taggingModel + \"_model.ser\");\n LOG.info(\"Load POS Tagger featureExtractor : \" + taggingModel\n + \"_featureExtractor.ser\");\n m_featureExtractor = SerializationUtils.deserialize(taggingModel\n + \"_featureExtractor.ser\");\n }\n\n @Override\n public void execute(Tuple tuple, BasicOutputCollector collector) {\n String text = tuple.getStringByField(\"text\");\n List<String> preprocessedTokens = (List<String>) tuple\n .getValueByField(\"preprocessedTokens\");\n\n // POS Tagging\n List<TaggedToken> taggedTokens = tag(preprocessedTokens);\n\n if (m_logging) {\n LOG.info(\"Tweet: \" + taggedTokens);\n }\n\n // Emit new tuples\n collector.emit(new Values(text, taggedTokens));\n }\n\n private List<TaggedToken> tag(List<String> tokens) {\n Sentence sentence = new Sentence();\n sentence.tokens = tokens;\n ModelSentence ms = new ModelSentence(sentence.T());\n m_featureExtractor.computeFeatures(sentence, ms);\n m_model.greedyDecode(ms, false);\n\n List<TaggedToken> taggedTokens = new ArrayList<TaggedToken>();\n for (int t = 0; t < sentence.T(); t++) {\n TaggedToken tt = new TaggedToken(tokens.get(t),\n m_model.labelVocab.name(ms.labels[t]));\n taggedTokens.add(tt);\n }\n return taggedTokens;\n }\n\n}",
"public class PreprocessorBolt extends BaseBasicBolt {\n public static final String ID = \"preprocessor-bolt\";\n public static final String CONF_LOGGING = ID + \".logging\";\n private static final long serialVersionUID = -8518185528053643981L;\n private static final Logger LOG = LoggerFactory\n .getLogger(PreprocessorBolt.class);\n private boolean m_logging = false;\n private Preprocessor m_preprocessor;\n\n @Override\n public void declareOutputFields(OutputFieldsDeclarer declarer) {\n // key of output tuples\n declarer.declare(new Fields(\"text\", \"preprocessedTokens\"));\n }\n\n @Override\n public void prepare(Map config, TopologyContext context) {\n // Optional set logging\n if (config.get(CONF_LOGGING) != null) {\n m_logging = (Boolean) config.get(CONF_LOGGING);\n } else {\n m_logging = false;\n }\n // Load Preprocessor\n m_preprocessor = Preprocessor.getInstance();\n }\n\n @Override\n public void execute(Tuple tuple, BasicOutputCollector collector) {\n String text = tuple.getStringByField(\"text\");\n List<String> tokens = (List<String>) tuple.getValueByField(\"tokens\");\n\n // Preprocess\n List<String> preprocessedTokens = m_preprocessor.preprocess(tokens);\n\n if (m_logging) {\n LOG.info(\"Tweet: \" + preprocessedTokens);\n }\n\n // Emit new tuples\n collector.emit(new Values(text, preprocessedTokens));\n }\n\n}",
"public class SVMBolt extends BaseBasicBolt {\n public static final String ID = \"support-vector-maschine-bolt\";\n public static final String CONF_LOGGING = ID + \".logging\";\n private static final long serialVersionUID = -6790858930924043126L;\n private static final Logger LOG = LoggerFactory.getLogger(SVMBolt.class);\n private boolean m_logging = false;\n private Dataset m_dataset;\n private svm_model m_model;\n\n @Override\n public void declareOutputFields(OutputFieldsDeclarer declarer) {\n // no output tuples\n }\n\n @Override\n public void prepare(Map config, TopologyContext context) {\n // Optional set logging\n if (config.get(CONF_LOGGING) != null) {\n m_logging = (Boolean) config.get(CONF_LOGGING);\n } else {\n m_logging = false;\n }\n\n LOG.info(\"Loading SVM model...\");\n m_dataset = Configuration.getDataSetSemEval2013();\n m_model = SerializationUtils.deserialize(m_dataset.getDatasetPath()\n + File.separator + SVM.SVM_MODEL_FILE_SER);\n\n if (m_model == null) {\n LOG.error(\"Could not load SVM model! File: \" + m_dataset.getDatasetPath()\n + File.separator + SVM.SVM_MODEL_FILE_SER);\n throw new RuntimeException();\n }\n }\n\n @Override\n public void execute(Tuple tuple, BasicOutputCollector collector) {\n String text = tuple.getStringByField(\"text\");\n Map<Integer, Double> featureVector = (Map<Integer, Double>) tuple\n .getValueByField(\"featureVector\");\n\n // Create feature nodes\n svm_node[] testNodes = new svm_node[featureVector.size()];\n int i = 0;\n for (Map.Entry<Integer, Double> feature : featureVector.entrySet()) {\n svm_node node = new svm_node();\n node.index = feature.getKey();\n node.value = feature.getValue();\n testNodes[i] = node;\n i++;\n }\n\n double predictedClass = svm.svm_predict(m_model, testNodes);\n\n if (m_logging) {\n LOG.info(\"Tweet: \" + text + \" predictedSentiment: \"\n + SentimentClass.fromScore(m_dataset, (int) predictedClass));\n }\n }\n\n}",
"public class TokenizerBolt extends BaseBasicBolt {\n public static final String ID = \"tokenizer-bolt\";\n public static final String CONF_LOGGING = ID + \".logging\";\n private static final long serialVersionUID = -2447717633925641497L;\n private static final Logger LOG = LoggerFactory\n .getLogger(TokenizerBolt.class);\n private boolean m_logging = false;\n\n @Override\n public void declareOutputFields(OutputFieldsDeclarer declarer) {\n // key of output tuples\n declarer.declare(new Fields(\"text\", \"tokens\"));\n }\n\n @Override\n public void prepare(Map config, TopologyContext context) {\n // Optional set logging\n if (config.get(CONF_LOGGING) != null) {\n m_logging = (Boolean) config.get(CONF_LOGGING);\n } else {\n m_logging = false;\n }\n }\n\n @Override\n public void execute(Tuple tuple, BasicOutputCollector collector) {\n String text = tuple.getStringByField(\"text\");\n\n List<String> tokens = Tokenizer.tokenize(text);\n\n if (m_logging) {\n LOG.info(\"Tweet: \\\"\" + text + \"\\\" Tokenized: \" + tokens);\n }\n\n // Emit new tuples\n collector.emit(new Values(text, tokens));\n }\n\n}",
"public class Configuration {\n private static final Logger LOG = LoggerFactory\n .getLogger(Configuration.class);\n\n public static final boolean RUNNING_WITHIN_JAR = Configuration.class\n .getResource(\"Configuration.class\").toString().startsWith(\"jar:\");\n\n public static final String WORKING_DIR_PATH = (RUNNING_WITHIN_JAR) ? \"\"\n : System.getProperty(\"user.dir\") + File.separator;\n\n public static final String TEMP_DIR_PATH = System\n .getProperty(\"java.io.tmpdir\");\n\n public static final String GLOBAL_RESOURCES_DATASETS_SEMEVAL = \"global.resources.datasets.semeval\";\n public static final String GLOBAL_RESOURCES_DICT = \"global.resources.dict\";\n public static final String GLOBAL_RESOURCES_DICT_SENTIMENT = \"global.resources.dict.sentiment\";\n public static final String GLOBAL_RESOURCES_DICT_SLANG = \"global.resources.dict.slang\";\n public static final String GLOBAL_RESOURCES_DICT_WORDNET_PATH = \"global.resources.dict.wordnet.path\";\n\n public static final Map CONFIG = readConfig();\n\n @SuppressWarnings(\"rawtypes\")\n public static Map readConfig() {\n Map conf = readConfigFile(WORKING_DIR_PATH + \"conf/defaults.yaml\", true);\n // read custom config\n LOG.info(\"Try to load user-specific config...\");\n Map customConfig = readConfigFile(WORKING_DIR_PATH\n + \"conf/configuration.yaml\", false);\n if (customConfig != null) {\n conf.putAll(customConfig);\n } else if (RUNNING_WITHIN_JAR) {\n customConfig = readConfigFile(\"../conf/configuration.yaml\", false);\n if (customConfig != null) {\n conf.putAll(customConfig);\n }\n }\n return conf;\n }\n\n @SuppressWarnings(\"rawtypes\")\n public static Map readConfigFile(String file, boolean mustExist) {\n Yaml yaml = new Yaml(new SafeConstructor());\n Map ret = null;\n InputStream input = IOUtils.getInputStream(file);\n if (input != null) {\n ret = (Map) yaml.load(new InputStreamReader(input));\n LOG.info(\"Loaded \" + file);\n try {\n input.close();\n } catch (IOException e) {\n LOG.error(\"IOException: \" + e.getMessage());\n }\n } else if (mustExist) {\n LOG.error(\"Config file \" + file + \" was not found!\");\n }\n if ((ret == null) && (mustExist)) {\n throw new RuntimeException(\"Config file \" + file + \" was not found!\");\n }\n return ret;\n }\n\n public static <K, V> V get(K key) {\n return get(key, null);\n }\n\n public static <K, V> V get(K key, V defaultValue) {\n return get((Map<K, V>) CONFIG, key, defaultValue);\n }\n\n public static <K, V> V get(Map<K, V> map, K key, V defaultValue) {\n V value = map.get(key);\n if (value == null) {\n value = defaultValue;\n }\n return value;\n }\n\n public static Dataset getDataSetSemEval2013() {\n return Dataset.readFromYaml((Map) ((Map) CONFIG\n .get(GLOBAL_RESOURCES_DATASETS_SEMEVAL)).get(\"2013\"));\n }\n\n public static List<String> getFirstNames() {\n return (List<String>) ((Map) CONFIG.get(GLOBAL_RESOURCES_DICT))\n .get(\"FirstNames\");\n }\n\n public static List<String> getStopWords() {\n return (List<String>) ((Map) CONFIG.get(GLOBAL_RESOURCES_DICT))\n .get(\"StopWords\");\n }\n\n public static List<Map> getSentimentWordlists() {\n return (List<Map>) CONFIG.get(GLOBAL_RESOURCES_DICT_SENTIMENT);\n }\n\n public static List<Map> getSlangWordlists() {\n return (List<Map>) CONFIG.get(GLOBAL_RESOURCES_DICT_SLANG);\n }\n\n public static String getWordNetDict() {\n return (String) CONFIG.get(GLOBAL_RESOURCES_DICT_WORDNET_PATH);\n }\n\n}",
"public class TaggedTokenSerializer extends Serializer<TaggedToken> {\n\n @Override\n public TaggedToken read(Kryo kryo, Input input, Class<TaggedToken> type) {\n return new TaggedToken(input.readString(), input.readString());\n }\n\n @Override\n public void write(Kryo kryo, Output output, TaggedToken taggedToken) {\n output.writeString(taggedToken.token);\n output.writeString(taggedToken.tag);\n }\n\n}",
"public class DatasetSpout extends BaseRichSpout {\n public static final String ID = \"dataset-spout\";\n public static final String CONF_STARTUP_SLEEP_MS = ID + \".startup.sleep.ms\";\n public static final String CONF_TUPLE_SLEEP_MS = ID + \".tuple.sleep.ms\";\n public static final String CONF_TUPLE_SLEEP_NS = ID + \".spout.tuple.sleep.ns\";\n private static final long serialVersionUID = 3028853846518561027L;\n private Dataset m_dataset;\n private SpoutOutputCollector m_collector;\n private List<Tweet> m_tweets;\n private long m_messageId = 0;\n private int m_index = 0;\n private long m_tupleSleepMs = 0;\n private long m_tupleSleepNs = 0;\n\n public void declareOutputFields(OutputFieldsDeclarer declarer) {\n // key of output tuples\n declarer.declare(new Fields(\"id\", \"score\", \"text\"));\n }\n\n public void open(Map config, TopologyContext context,\n SpoutOutputCollector collector) {\n this.m_collector = collector;\n this.m_dataset = Configuration.getDataSetSemEval2013();\n this.m_tweets = m_dataset.getTestTweets();\n\n // Optional sleep between tuples emitting\n if (config.get(CONF_TUPLE_SLEEP_MS) != null) {\n m_tupleSleepMs = (Long) config.get(CONF_TUPLE_SLEEP_MS);\n } else {\n m_tupleSleepMs = 0;\n }\n if (config.get(CONF_TUPLE_SLEEP_NS) != null) {\n m_tupleSleepNs = (Long) config.get(CONF_TUPLE_SLEEP_NS);\n } else {\n m_tupleSleepNs = 0;\n }\n\n // Optional startup sleep to finish bolt preparation\n // before spout starts emitting\n if (config.get(CONF_STARTUP_SLEEP_MS) != null) {\n long startupSleepMillis = (Long) config.get(CONF_STARTUP_SLEEP_MS);\n TimeUtils.sleepMillis(startupSleepMillis);\n }\n }\n\n public void nextTuple() {\n Tweet tweet = m_tweets.get(m_index);\n\n // infinite loop\n m_index++;\n if (m_index >= m_tweets.size()) {\n m_index = 0;\n }\n m_messageId++; // accept possible overflow\n\n // Emit tweet\n m_collector.emit(\n new Values(tweet.getId(), tweet.getScore(), tweet.getText()),\n m_messageId);\n\n // Optional sleep\n if (m_tupleSleepMs != 0) {\n TimeUtils.sleepMillis(m_tupleSleepMs);\n }\n if (m_tupleSleepNs != 0) {\n TimeUtils.sleepNanos(m_tupleSleepNs);\n }\n }\n}",
"public class TwitterStreamSpout extends BaseRichSpout {\n public static final String ID = \"twitter-stream-spout\";\n public static final String CONF_STARTUP_SLEEP_MS = ID + \".startup.sleep.ms\";\n private static final long serialVersionUID = -4657730220755697034L;\n private SpoutOutputCollector m_collector;\n private LinkedBlockingQueue<Status> m_tweetsQueue = null;\n private TwitterStream m_twitterStream;\n private String m_consumerKey;\n private String m_consumerSecret;\n private String m_accessToken;\n private String m_accessTokenSecret;\n private String[] m_keyWords;\n private String m_filterLanguage;\n\n public TwitterStreamSpout(String consumerKey, String consumerSecret,\n String accessToken, String accessTokenSecret, String[] keyWords,\n String filterLanguage) {\n this.m_consumerKey = consumerKey;\n this.m_consumerSecret = consumerSecret;\n this.m_accessToken = accessToken;\n this.m_accessTokenSecret = accessTokenSecret;\n this.m_keyWords = keyWords;\n this.m_filterLanguage = filterLanguage; // \"en\"\n }\n\n @Override\n public void declareOutputFields(OutputFieldsDeclarer declarer) {\n // key of output tuples\n declarer.declare(new Fields(\"id\", \"text\", \"score\"));\n }\n\n @Override\n public void open(Map config, TopologyContext context,\n SpoutOutputCollector collector) {\n m_collector = collector;\n m_tweetsQueue = new LinkedBlockingQueue<Status>(1000);\n\n // Optional startup sleep to finish bolt preparation\n // before spout starts emitting\n if (config.get(CONF_STARTUP_SLEEP_MS) != null) {\n long startupSleepMillis = (Long) config.get(CONF_STARTUP_SLEEP_MS);\n TimeUtils.sleepMillis(startupSleepMillis);\n }\n\n TwitterStream twitterStream = new TwitterStreamFactory(\n new ConfigurationBuilder().setJSONStoreEnabled(true).build())\n .getInstance();\n\n // Set Listener\n twitterStream.addListener(new StatusListener() {\n @Override\n public void onStatus(Status status) {\n m_tweetsQueue.offer(status); // add tweet into queue\n }\n\n @Override\n public void onException(Exception arg0) {\n }\n\n @Override\n public void onDeletionNotice(StatusDeletionNotice arg0) {\n }\n\n @Override\n public void onScrubGeo(long arg0, long arg1) {\n }\n\n @Override\n public void onStallWarning(StallWarning arg0) {\n }\n\n @Override\n public void onTrackLimitationNotice(int arg0) {\n }\n });\n\n // Set credentials\n twitterStream.setOAuthConsumer(m_consumerKey, m_consumerSecret);\n AccessToken token = new AccessToken(m_accessToken, m_accessTokenSecret);\n twitterStream.setOAuthAccessToken(token);\n\n // Filter twitter stream\n FilterQuery tweetFilterQuery = new FilterQuery();\n if (m_keyWords != null) {\n tweetFilterQuery.track(m_keyWords);\n }\n\n // Filter location\n // https://dev.twitter.com/docs/streaming-apis/parameters#locations\n tweetFilterQuery.locations(new double[][] { new double[] { -180, -90, },\n new double[] { 180, 90 } }); // any geotagged tweet\n\n // Filter language\n tweetFilterQuery.language(new String[] { m_filterLanguage });\n\n twitterStream.filter(tweetFilterQuery);\n }\n\n @Override\n public void nextTuple() {\n Status tweet = m_tweetsQueue.poll();\n if (tweet == null) {\n TimeUtils.sleepMillis(50); // sleep 50 ms\n } else {\n // Emit tweet\n m_collector.emit(new Values(tweet.getId(), tweet.getText(), null));\n }\n }\n\n @Override\n public void close() {\n m_twitterStream.shutdown();\n }\n\n @Override\n public Map<String, Object> getComponentConfiguration() {\n Config ret = new Config();\n ret.setMaxTaskParallelism(1);\n return ret;\n }\n\n @Override\n public void ack(Object id) {\n }\n\n @Override\n public void fail(Object id) {\n }\n}"
] | import backtype.storm.topology.IRichSpout;
import backtype.storm.topology.TopologyBuilder;
import cmu.arktweetnlp.Tagger.TaggedToken;
import com.esotericsoftware.kryo.serializers.DefaultSerializers.TreeMapSerializer;
import java.util.Arrays;
import java.util.TreeMap;
import at.illecker.sentistorm.bolt.FeatureGenerationBolt;
import at.illecker.sentistorm.bolt.POSTaggerBolt;
import at.illecker.sentistorm.bolt.PreprocessorBolt;
import at.illecker.sentistorm.bolt.SVMBolt;
import at.illecker.sentistorm.bolt.TokenizerBolt;
import at.illecker.sentistorm.commons.Configuration;
import at.illecker.sentistorm.commons.util.io.kyro.TaggedTokenSerializer;
import at.illecker.sentistorm.spout.DatasetSpout;
import at.illecker.sentistorm.spout.TwitterStreamSpout;
import backtype.storm.Config;
import backtype.storm.StormSubmitter; | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 at.illecker.sentistorm;
public class SentiStormTopology {
public static final String TOPOLOGY_NAME = "senti-storm-topology";
public static void main(String[] args) throws Exception {
String consumerKey = "";
String consumerSecret = "";
String accessToken = "";
String accessTokenSecret = "";
String[] keyWords = null;
if (args.length > 0) {
if (args.length >= 4) {
consumerKey = args[0];
System.out.println("TwitterSpout using ConsumerKey: " + consumerKey);
consumerSecret = args[1];
accessToken = args[2];
accessTokenSecret = args[3];
if (args.length == 5) {
keyWords = args[4].split(" ");
System.out.println("TwitterSpout using KeyWords: "
+ Arrays.toString(keyWords));
}
} else {
System.out.println("Wrong argument size!");
System.out.println(" Argument1=consumerKey");
System.out.println(" Argument2=consumerSecret");
System.out.println(" Argument3=accessToken");
System.out.println(" Argument4=accessTokenSecret");
System.out.println(" [Argument5=keyWords]");
}
}
Config conf = new Config();
// Create Spout
IRichSpout spout;
String spoutID = "";
if (consumerKey.isEmpty()) {
if (Configuration.get("sentistorm.spout.startup.sleep.ms") != null) { | conf.put(DatasetSpout.CONF_STARTUP_SLEEP_MS, | 7 |
akeranen/the-one | src/ui/DTNSimUI.java | [
"public abstract class Report {\n\t/** Name space of the settings that are common to all reports ({@value}). */\n\tpublic static final String REPORT_NS = \"Report\";\n\t/** The interval (simulated seconds) of creating new settings files\n\t * -setting id ({@value}) */\n\tpublic static final String INTERVAL_SETTING = \"interval\";\n\t/** The output file path of the report -setting id ({@value})*/\n\tpublic static final String OUTPUT_SETTING = \"output\";\n\t/** Precision of formatted double values - setting id ({@value}).\n\t * Defines the amount of decimals shown in formatted double values.\n\t * Default value is {@value #DEF_PRECISION}. */\n\tpublic static final String PRECISION_SETTING = \"precision\";\n\t/** Default precision of formatted double values */\n\tpublic static final int DEF_PRECISION = 4;\n\t/** The default output directory of reports (can be overridden per report\n\t * with {@link Report#OUTPUT_SETTING}) -setting id ({@value})*/\n\tpublic static final String REPORTDIR_SETTING = \"Report.reportDir\";\n\t/** Warm up period -setting id ({@value}). Defines how many seconds from\n\t * the beginning of the simulation should not be included in the reports.\n\t * Implementation of the feature is report specific, so check out the\n\t * respective report classes for details. Default is 0. Must be a positive\n\t * integer or 0. */\n\tpublic static final String WARMUP_S = \"warmup\";\n\t/** Suffix of report files without explicit output */\n\tpublic static final String OUT_SUFFIX = \".txt\";\n\t/** Suffix for reports that are created on n second intervals */\n\tpublic static final String INTERVALLED_FORMAT =\"%04d\" + OUT_SUFFIX;\n\t/** The print writer used to write output. See {@link #write(String)} */\n\tprotected PrintWriter out;\n\t/** String value for values that could not be calculated */\n\tpublic static final String NAN = \"NaN\";\n\tprivate String prefix = \"\";\n\tprivate int precision;\n\tprotected int warmupTime;\n\tprotected Set<String> warmupIDs;\n\n\tprivate int lastOutputSuffix;\n\tprivate double outputInterval;\n\tprivate double lastReportTime;\n\tprivate String outFileName;\n\tprivate String scenarioName;\n\n\t/**\n\t * Constructor.\n\t * Looks for a className.output setting in the Settings and\n\t * if such is found, uses that as the output file name. Otherwise\n\t * scenarioname_classname.txt is used as the file name.\n\t */\n\tpublic Report(){\n\t\tthis.lastOutputSuffix = 0;\n\t\tthis.outputInterval = -1;\n\t\tthis.warmupIDs = null;\n\n\t\tSettings settings = new Settings();\n\t\tscenarioName = settings.valueFillString(settings.getSetting(\n\t\t\t\tSimScenario.SCENARIO_NS + \".\" +\tSimScenario.NAME_S));\n\n\t\tsettings = getSettings();\n\n\t\tif (settings.contains(INTERVAL_SETTING)) {\n\t\t\toutputInterval = settings.getDouble(INTERVAL_SETTING);\n\t\t}\n\n\t\tif (settings.contains(WARMUP_S)) {\n\t\t\tthis.warmupTime = settings.getInt(WARMUP_S);\n\t\t}\n\t\telse {\n\t\t\tthis.warmupTime = 0;\n\t\t}\n\n\n\t\tif (settings.contains(PRECISION_SETTING)) {\n\t\t\tprecision = settings.getInt(PRECISION_SETTING);\n\t\t\tif (precision < 0) {\n\t\t\t\tprecision = 0;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tprecision = DEF_PRECISION;\n\t\t}\n\n\t\tif (settings.contains(OUTPUT_SETTING)) {\n\t\t\toutFileName = settings.getSetting(OUTPUT_SETTING);\n\t\t\t// fill value place holders in the name\n\t\t\toutFileName = settings.valueFillString(outFileName);\n\t\t}\n\t\telse {\n\t\t\t// no output name define -> construct one from report class' name\n\t\t\tsettings.setNameSpace(null);\n\t\t\tString outDir = settings.getSetting(REPORTDIR_SETTING);\n\t\t\tif (!outDir.endsWith(\"/\")) {\n\t\t\t\toutDir += \"/\";\t// make sure dir ends with directory delimiter\n\t\t\t}\n\t\t\toutFileName = outDir + scenarioName +\n\t\t\t\t\"_\" + this.getClass().getSimpleName();\n\t\t\tif (outputInterval == -1) {\n\t\t\t\toutFileName += OUT_SUFFIX; // no intervalled reports\n\t\t\t}\n\n\t\t}\n\n\t\tcheckDirExistence(outFileName);\n\t}\n\n\t/**\n\t * Checks that a directory for a file exists or creates the directory\n\t * if it didn't exist.\n\t * @param outFileName Name of the file\n\t */\n\tprivate void checkDirExistence(String outFileName) {\n\t\tFile outFile = new File(outFileName);\n\t\tFile outDir = outFile.getParentFile();\n\n\t\tif (outDir != null && !outDir.exists()) {\n\t\t\tif (!createDirs(outDir)) {\n\t\t\t\tthrow new SimError(\"Couldn't create report directory '\" +\n\t\t\t\t\t\toutDir.getAbsolutePath()+\"'\");\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Recursively creates a directory structure\n\t * @param directory The directory to create\n\t * @return True if the creation succeeded, false if not\n\t */\n\tprivate boolean createDirs(File directory) {\n\t\tif (directory==null) {\n\t\t\treturn true;\n\t\t}\n\t\tif (directory.exists()) {\n\t\t\treturn true;\n\t\t} else {\n\t\t\tif (!createDirs(directory.getParentFile())) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (!directory.mkdir()) {\n\t\t\t\treturn false;\n\t\t\t} else {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Initializes the report output. Method is called in the beginning of\n\t * every new report file. Subclasses must call this method first in their\n\t * own implementations of init().\n\t */\n\tprotected void init() {\n\t\tthis.lastReportTime = getSimTime();\n\n\t\tif (outputInterval > 0) {\n\t\t\tcreateSuffixedOutput(outFileName);\n\t\t}\n\t\telse {\n\t\t\tcreateOutput(outFileName);\n\t\t}\n\t}\n\n\t/**\n\t * Creates a new output file\n\t * @param outFileName Name (&path) of the file to create\n\t */\n\tprivate void createOutput(String outFileName) {\n\t\ttry {\n\t\t\tthis.out = new PrintWriter(new FileWriter(outFileName));\n\t\t} catch (IOException e) {\n\t\t\tthrow new SimError(\"Couldn't open file '\" + outFileName +\n\t\t\t\t\t\"' for report output\\n\" + e.getMessage(), e);\n\t\t}\n\t}\n\n\t/**\n\t * Creates a number-suffixed output file with increasing number suffix\n\t * @param outFileName Prefix of the output file's name\n\t */\n\tprivate void createSuffixedOutput(String outFileName) {\n\t\tString suffix = String.format(INTERVALLED_FORMAT,\n\t\t\t\tthis.lastOutputSuffix);\n\t\tcreateOutput(outFileName+suffix);\n\t\tthis.lastOutputSuffix++;\n\t}\n\n\t/**\n\t * This method should be called before every new (complete) event the\n\t * report logs. If the report has no meaningful use for multiple reports,\n\t * the call can be omitted (then only single output file will be generated)\n\t */\n\tprotected void newEvent() {\n\t\tif (this.outputInterval <= 0) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (getSimTime() > this.lastReportTime + this.outputInterval) {\n\t\t\tdone(); // finalize the old file\n\t\t\tinit(); // init the new file\n\t\t}\n\t}\n\n\t/**\n\t * Writes a line to report using defined prefix and {@link #out} writer.\n\t * @param txt Line to write\n\t * @see #setPrefix(String)\n\t */\n\tprotected void write(String txt) {\n\t\tif (out == null) {\n\t\t\tinit();\n\t\t}\n\t\tout.println(prefix + txt);\n\t}\n\n\t/**\n\t * Formats a double value according to current precision setting (see\n\t * {@link #PRECISION_SETTING}) and returns it in a string.\n\t * @param value The value to format\n\t * @return Formatted value in a string\n\t */\n\tprotected String format(double value) {\n\t\treturn String.format(\"%.\" + precision + \"f\", value);\n\t}\n\n\t/**\n\t * Sets a prefix that will be inserted before every line in the report\n\t * @param txt Text to use as the prefix\n\t */\n\tprotected void setPrefix(String txt) {\n\t\tthis.prefix = txt;\n\t}\n\n\t/**\n\t * Returns the name of the scenario as read from the settings\n\t * @return the name of the scenario as read from the settings\n\t */\n\tprotected String getScenarioName() {\n\t\treturn this.scenarioName;\n\t}\n\n\t/**\n\t * Returns the current simulation time from the SimClock\n\t * @return the current simulation time from the SimClock\n\t */\n\tprotected double getSimTime() {\n\t\treturn SimClock.getTime();\n\t}\n\n\t/**\n\t * Returns true if the warm up period is still ongoing (simTime < warmup)\n\t * @return true if the warm up period is still ongoing, false if not\n\t */\n\tprotected boolean isWarmup() {\n\t\treturn this.warmupTime > SimClock.getTime();\n\t}\n\n\t/**\n\t * Adds a new ID to the warm up ID set\n\t * @param id The ID\n\t */\n\tprotected void addWarmupID(String id) {\n\t\tif (this.warmupIDs == null) { // lazy creation of the Set\n\t\t\tthis.warmupIDs = new HashSet<String>();\n\t\t}\n\n\t\tthis.warmupIDs.add(id);\n\t}\n\n\t/**\n\t * Removes a warm up ID from the warm up ID set\n\t * @param id The ID to remove\n\t */\n\tprotected void removeWarmupID(String id) {\n\t\tthis.warmupIDs.remove(id);\n\t}\n\n\t/**\n\t * Returns true if the given ID is in the warm up ID set\n\t * @param id The ID\n\t * @return true if the given ID is in the warm up ID set\n\t */\n\tprotected boolean isWarmupID(String id) {\n\t\tif (this.warmupIDs == null || this.warmupIDs.size() == 0) {\n\t\t\treturn false;\n\t\t}\n\n\t\treturn this.warmupIDs.contains(id);\n\t}\n\n\t/**\n\t * Returns a Settings object initialized for the report class' name space\n\t * that uses {@value REPORT_NS} as the secondary name space.\n\t * @return a Settings object initialized for the report class' name space\n\t */\n\tprotected Settings getSettings() {\n\t\tSettings s = new Settings(this.getClass().getSimpleName());\n\t\ts.setSecondaryNamespace(REPORT_NS);\n\t\treturn s;\n\t}\n\n\t/**\n\t * Called when the simulation is done, user requested\n\t * premature termination or intervalled report generating decided\n\t * that it's time for the next report.\n\t */\n\tpublic void done() {\n\t\tif (out != null) {\n\t\t\tout.close();\n\t\t}\n\t}\n\n\t/**\n\t * Returns the average of double values stored in a List or \"NaN\" for\n\t * empty lists.\n\t * @param values The list of double values\n\t * @return average of double values stored in the List in a formatted String\n\t */\n\tpublic String getAverage(List<Double> values) {\n\t\tdouble sum = 0;\n\t\tif (values.size() == 0) {\n\t\t\treturn NAN;\n\t\t}\n\n\t\tfor (double dValue : values) {\n\t\t\tsum += dValue;\n\t\t}\n\n\t\treturn format(sum / values.size());\n\t}\n\n\t/**\n\t * Returns the average of integer values stored in a List\n\t * @param values The list of values\n\t * @return average of integer values stored in the List or \"NaN\" for\n\t * empty lists.\n\t */\n\tpublic String getIntAverage(List<Integer> values) {\n\t\tList<Double> dValues = new ArrayList<Double>(values.size());\n\t\tfor (int i : values) {\n\t\t\tdValues.add((double)i);\n\t\t}\n\t\treturn getAverage(dValues);\n\t}\n\n\t/**\n\t * Returns the median of double values stored in a List\n\t * @param values The list of double values\n\t * @return median of double values stored in the List or \"NaN\" for\n\t * empty lists.\n\t */\n\tpublic String getMedian(List<Double> values) {\n\t\tif (values.size() == 0) {\n\t\t\treturn NAN;\n\t\t}\n\n\t\tCollections.sort(values);\n\t\treturn format(values.get(values.size()/2));\n\t}\n\n\t/**\n\t * Returns the median of integer values stored in a List\n\t * @param values The list of values\n\t * @return median of integer values stored in the List or 0 for\n\t * empty lists.\n\t */\n\tpublic int getIntMedian(List<Integer> values) {\n\t\tif (values.size() == 0) {\n\t\t\treturn 0;\n\t\t}\n\n\t\tCollections.sort(values);\n\t\treturn values.get(values.size()/2);\n\t}\n\n\t/**\n\t * Returns the variance of the values in the List.\n\t *\n\t * @param values\tThe list of values\n\t * @return The variance of the values in the list or \"NaN\" if the list is\n\t * empty.\n\t */\n\tpublic String getVariance(List<Double> values) {\n\t\tif (values.size()==0) return \"NaN\";\n\t\tdouble E_X;\n\t\tdouble sum=0, sum2=0;\n\t\tfor (double dValue : values) {\n\t\t\tsum += dValue;\n\t\t\tsum2 += dValue*dValue;\n\t\t}\n\t\tE_X = sum / values.size();\n\t\treturn format(sum2/values.size() - (E_X*E_X));\n\t}\n\n}",
"public class Settings {\n\t/** properties object where the setting files are read into */\n\tprotected static Properties props;\n\t/** file name of the default settings file ({@value}) */\n\tpublic static final String DEF_SETTINGS_FILE =\"default_settings.txt\";\n\n\t/**\n\t * Setting to define the file name where all read settings are written\n\t * ({@value}. If set to an empty string, standard output is used.\n\t * By default setting are not written anywhere.\n\t */\n\tpublic static final String SETTING_OUTPUT_S = \"Settings.output\";\n\n\t/** delimiter for requested values in strings ({@value})\n\t * @see #valueFillString(String) */\n\tpublic static final String FILL_DELIMITER = \"%%\";\n\n\t/** Stream where all read settings are written to */\n\tprivate static PrintStream out = null;\n\tprivate static Set<String> writtenSettings = new HashSet<String>();\n\n\t/** run index for run-specific settings */\n\tprivate static int runIndex = 0;\n\tprivate String namespace = null; // namespace to look the settings from\n\tprivate String secondaryNamespace = null;\n\tprivate Stack<String> oldNamespaces;\n\tprivate Stack<String> secondaryNamespaces;\n\n\t/**\n\t * Creates a setting object with a namespace. Namespace is the prefix\n\t * of the all subsequent setting requests.\n\t * @param namespace Namespace to use\n\t */\n\tpublic Settings(String namespace) {\n\t\tthis.oldNamespaces = new Stack<String>();\n\t\tthis.secondaryNamespaces = new Stack<String>();\n\t\tsetNameSpace(namespace);\n\t}\n\n\t/**\n\t * Create a setting object without namespace. All setting requests must\n\t * be prefixed with a valid namespace (e.g. \"Report.nrofReports\").\n\t */\n\tpublic Settings() {\n\t\tthis(null);\n\t}\n\n\t/**\n\t * Sets the run index for the settings (only has effect on settings with\n\t * run array). A run array can be defined with syntax<BR>\n\t * <CODE>[settingFor1stRun ; settingFor2ndRun ; SettingFor3rdRun]</CODE>\n\t * <BR>I.e. settings are put in brackets and delimited with semicolon.\n\t * First run's setting is returned when index is 0, second when index is\n\t * 1 etc. If run index is bigger than run array's length, indexing wraps\n\t * around in run array (i.e. return value is the value at index\n\t * <CODE>runIndex % arrayLength</CODE>).\n\t * To disable whole run-index-thing, set index to value smaller than\n\t * zero (e.g. -1). When disabled, run-arrays are returned as normal values,\n\t * including the brackets.\n\t * @param index The run index to use for subsequent settings calls, or\n\t * -1 to disable run indexing\n\t */\n\tpublic static void setRunIndex(int index) {\n\t\trunIndex = index;\n\t\twrittenSettings.clear();\n\t}\n\n\t/**\n\t * Checks that the given integer array contains a valid range. I.e.,\n\t * the length of the array must be two and\n\t * <code>first_value <= second_value</code>.\n\t * @param range The range array\n\t * @param sname Name of the setting (for error messages)\n\t * @throws SettingsError If the given array didn't qualify as a range\n\t */\n\tpublic void assertValidRange(int range[], String sname)\n\t\tthrows SettingsError {\n\t\tif (range.length != 2) {\n\t\t\tthrow new SettingsError(\"Range setting \" +\n\t\t\t\t\tgetFullPropertyName(sname) +\n\t\t\t\t\t\" should contain only two comma separated integer values\");\n\t\t}\n\t\tif (range[0] > range[1]) {\n\t\t\tthrow new SettingsError(\"Range setting's \" +\n\t\t\t\t\tgetFullPropertyName(sname) +\n\t\t\t\t\t\" first value should be smaller or equal to second value\");\n\t\t}\n\t}\n\n\t/**\n\t * Makes sure that the given settings value is positive\n\t * @param value Value to check\n\t * @param settingName Name of the setting (for error's message)\n\t * @throws SettingsError if the value was not positive\n\t */\n\tpublic void ensurePositiveValue(double value, String settingName) {\n\t\tif (value < 0) {\n\t\t\tthrow new SettingsError(\"Negative value (\" + value +\n\t\t\t\t\t\") not accepted for setting \" + settingName);\n\t\t}\n\t}\n\n\t/**\n\t * Sets the namespace to something else than the current namespace.\n\t * This change can be reverted using {@link #restoreNameSpace()}\n\t * @param namespace The new namespace\n\t */\n\tpublic void setNameSpace(String namespace) {\n\t\tthis.oldNamespaces.push(this.namespace);\n\t\tthis.namespace = namespace;\n\t}\n\n\t/**\n\t * Appends the given namespace to the the current namespace, <strong>\n\t * for both the primary and secondary namespace </strong>.\n\t * This change can be reverted using {@link #restoreNameSpace()} and\n\t * {@link #restoreSecondaryNamespace()}.\n\t * @param namespace The new namespace to append\n\t */\n\tpublic void setSubNameSpace(String namespace) {\n\t\tthis.oldNamespaces.push(this.namespace);\n\t\tthis.namespace = this.namespace + \".\" + namespace;\n\t\tthis.secondaryNamespaces.push(this.secondaryNamespace);\n\t\tthis.secondaryNamespace = this.secondaryNamespace + \".\" + namespace;\n\t}\n\n\t/**\n\t * Returns full (namespace prefixed) property name for a setting.\n\t * @param setting The name of the setting\n\t * @return The setting name prefixed with fully qualified name of the\n\t * namespace where the requested setting would be retrieved from or null\n\t * if that setting is not found from any of the current namespace(s)\n\t */\n\tpublic String getFullPropertyName(String setting) {\n\t\tif (!contains(setting)) {\n\t\t\treturn null;\n\t\t}\n\n\t\tif (props.getProperty(getFullPropertyName(setting, false)) != null) {\n\t\t\treturn getFullPropertyName(setting, false);\n\t\t}\n\n\t\t// not found from primary, but Settings contains -> must be from 2ndary\n\t\telse return getFullPropertyName(setting, true);\n\t}\n\n\t/**\n\t * Returns the namespace of the settings object\n\t * @return the namespace of the settings object\n\t */\n\tpublic String getNameSpace() {\n\t\treturn this.namespace;\n\t}\n\n\t/**\n\t * Returns the secondary namespace of the settings object\n\t * @return the secondary namespace of the settings object\n\t */\n\tpublic String getSecondaryNameSpace() {\n\t\treturn this.secondaryNamespace;\n\t}\n\n\t/**\n\t * Sets a secondary namespace where a setting is searched from if it\n\t * isn't found from the primary namespace. Secondary namespace can\n\t * be used e.g. as a \"default\" space where the settings are looked from\n\t * if no specific setting is set.\n\t * This change can be reverted using {@link #restoreSecondaryNamespace()}\n\t * @param namespace The new secondary namespace or null if secondary\n\t * namespace is not used (default behavior)\n\t */\n\tpublic void setSecondaryNamespace(String namespace) {\n\t\tthis.secondaryNamespaces.push(this.secondaryNamespace);\n\t\tthis.secondaryNamespace = namespace;\n\t}\n\n\t/**\n\t * Restores the namespace that was in use before a call to setNameSpace\n\t * @see #setNameSpace(String)\n\t */\n\tpublic void restoreNameSpace() {\n\t\tthis.namespace = this.oldNamespaces.pop();\n\t}\n\n\t/**\n\t * Restores the secondary namespace that was in use before a call to\n\t * setSecondaryNameSpace\n\t * @see #setSecondaryNamespace(String)\n\t */\n\tpublic void restoreSecondaryNamespace() {\n\t\tthis.secondaryNamespace = this.secondaryNamespaces.pop();\n\t}\n\n\t/**\n\t * Reverts the change made with {@link #setSubNameSpace(String)}, i.e.,\n\t * restores both the primary and secondary namespace.\n\t */\n\tpublic void restoreSubNameSpace() {\n\t\trestoreNameSpace();\n\t\trestoreSecondaryNamespace();\n\t}\n\n\t/**\n\t * Initializes the settings all Settings objects will use. This should be\n\t * called before any setting requests. Subsequent calls replace all\n\t * old settings and then Settings contains only the new settings.\n\t * The file {@link #DEF_SETTINGS_FILE}, if exists, is always read.\n\t * @param propFile Path to the property file where additional settings\n\t * are read from or null if no additional settings files are needed.\n\t * @throws SettingsError If loading the settings file(s) didn't succeed\n\t */\n\tpublic static void init(String propFile) throws SettingsError {\n\t\tString outFile;\n\t\ttry {\n\t\t\tif (new File(DEF_SETTINGS_FILE).exists()) {\n\t\t\t\tProperties defProperties = new Properties();\n\t\t\t\tdefProperties.load(new FileInputStream(DEF_SETTINGS_FILE));\n\t\t\t\tprops = new Properties(defProperties);\n\t\t\t}\n\t\t\telse {\n\t\t\t\tprops = new Properties();\n\t\t\t}\n\t\t\tif (propFile != null) {\n\t\t\t\tprops.load(new FileInputStream(propFile));\n\t\t\t}\n\t\t} catch (IOException e) {\n\t\t\tthrow new SettingsError(e);\n\t\t}\n\n\t\toutFile = props.getProperty(SETTING_OUTPUT_S);\n\t\tif (outFile != null) {\n\t\t\tif (outFile.trim().length() == 0) {\n\t\t\t\tout = System.out;\n\t\t\t} else {\n\t\t\t\ttry {\n\t\t\t\t\tout = new PrintStream(new File(outFile));\n\t\t\t\t} catch (FileNotFoundException e) {\n\t\t\t\t\tthrow new SettingsError(\"Can't open Settings output file:\" +\n\t\t\t\t\t\t\te);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Initializes the settings all Settings objects will use. This should be\n\t * called before any setting requests. Subsequent calls replace all\n\t * old settings and then Settings contains only the new settings.\n\t *\n\t * @param settingsStream\n\t * \t\tInputStream where the properties are read.\n\t * @throws SettingsError\n\t * \t\tIf loading the settings didn't succeed\n\t */\n\tpublic static void initFromStream(final InputStream settingsStream)\n\tthrows SettingsError {\n\t\tprops = new Properties();\n\t\ttry {\n\t\t\tprops.load(settingsStream);\n\t\t} catch (IOException e) {\n\t\t\tthrow new SettingsError(e);\n\t\t}\n\n\t\tString outFile = props.getProperty(SETTING_OUTPUT_S);\n\t\tif (outFile != null) {\n\t\t\tif (outFile.trim().length() == 0) {\n\t\t\t\tout = System.out;\n\t\t\t} else {\n\t\t\t\ttry {\n\t\t\t\t\tout = new PrintStream(new File(outFile));\n\t\t\t\t} catch (FileNotFoundException e) {\n\t\t\t\t\tthrow new SettingsError(\"Can't open Settings output file:\" +\n\t\t\t\t\t\t\te);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Reads another settings file and adds the key-value pairs to the current\n\t * settings overriding any values that already existed with the same keys.\n\t * @param propFile Path to the property file\n\t * @throws SettingsError If loading the settings file didn't succeed\n\t * @see #init(String)\n\t */\n\tpublic static void addSettings(String propFile) throws SettingsError {\n\t\ttry {\n\t\t\tprops.load(new FileInputStream(propFile));\n\t\t} catch (IOException e) {\n\t\t\tthrow new SettingsError(e);\n\t\t}\n\t}\n\n\t/**\n\t * Writes the given setting string to the settings output (if any)\n\t * @param setting The string to write\n\t */\n\tprivate static void outputSetting(String setting) {\n\t\tif (out != null && !writtenSettings.contains(setting)) {\n\t\t\tif (writtenSettings.size() == 0) {\n\t\t\t\tout.println(\"# Settings for run \" + (runIndex + 1));\n\t\t\t}\n\t\t\tout.println(setting);\n\t\t\twrittenSettings.add(setting);\n\t\t}\n\t}\n\n\t/**\n\t * Returns true if a setting with defined name (in the current namespace\n\t * or secondary namespace if such is set) exists and has some value\n\t * (not just white space)\n\t * @param name Name of the setting to check\n\t * @return True if the setting exists, false if not\n\t */\n\tpublic boolean contains(String name) {\n\t\ttry {\n\t\t\tString value = getSetting(name);\n\t\t\tif (value == null) {\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\telse return value.trim().length() > 0;\n\t\t}\n\t\tcatch (SettingsError e) {\n\t\t\treturn false; // didn't find the setting\n\t\t}\n\t}\n\n\t/**\n\t * Returns full (namespace prefixed) property name for setting.\n\t * @param name Name of the settings\n\t * @param secondary If true, the secondary namespace is used.\n\t * @return full (prefixed with current namespace) property name for setting\n\t */\n\tprivate String getFullPropertyName(String name, boolean secondary) {\n\t\tString usedNamespace = (secondary ? secondaryNamespace : namespace);\n\n\t\tif (usedNamespace != null) {\n\t\t\treturn usedNamespace + \".\" + name;\n\t\t}\n\t\telse {\n\t\t\treturn name;\n\t\t}\n\t}\n\n\t/**\n\t * Returns a String-valued setting. Setting is first looked from the\n\t * namespace that is set (if any) and then from the secondary namespace\n\t * (if any). All other getters use this method as their first step too\n\t * (so all getters may throw SettingsError and look from both namespaces).\n\t * @param name Name of the setting to get\n\t * @return The contents of the setting in a String\n\t * @throws SettingsError if the setting is not found from either one of\n\t * the namespaces\n\t */\n\tpublic String getSetting(String name) {\n\t\tString fullPropName;\n\t\tif (props == null) {\n\t\t\tinit(null);\n\t\t}\n\t\tfullPropName = getFullPropertyName(name, false);\n\t\tString value = props.getProperty(fullPropName);\n\n\t\tif (value != null) { // found value, check if run setting can be parsed\n\t\t\tvalue = parseRunSetting(value.trim());\n\t\t}\n\n\t\tif ((value == null || value.length() == 0) &&\n\t\t\t\tthis.secondaryNamespace != null) {\n\t\t\t// try secondary namespace if the value wasn't found from primary\n\t\t\tfullPropName = getFullPropertyName(name, true);\n\t\t\tvalue = props.getProperty(fullPropName);\n\n\t\t\tif (value != null) {\n\t\t\t\tvalue = parseRunSetting(value.trim());\n\t\t\t}\n\t\t}\n\n\t\tif (value == null || value.length() == 0) {\n\t\t\tthrow new SettingsError(\"Can't find setting \" +\n\t\t\t\t\tgetPropertyNamesString(name));\n\t\t}\n\n\t\toutputSetting(fullPropName + \" = \" + value);\n\t\treturn value;\n\t}\n\n\t/**\n\t * Returns the given setting if it exists, or defaultValue if the setting\n\t * does not exist\n\t * @param name The name of the setting\n\t * @param defaultValue The value to return if the given setting didn't exist\n\t * @return The setting value or the default value if the setting didn't\n\t * exist\n\t */\n\tpublic String getSetting(String name, String defaultValue) {\n\t\tif (!contains(name)) {\n\t\t\treturn defaultValue;\n\t\t} else {\n\t\t\treturn getSetting(name);\n\t\t}\n\t}\n\n\t/**\n\t * Parses run-specific settings from a String value\n\t * @param value The String to parse\n\t * @return The runIndex % arrayLength'th value of the run array\n\t */\n\tprivate static String parseRunSetting(String value) {\n\t\tfinal String RUN_ARRAY_START = \"[\";\n\t\tfinal String RUN_ARRAY_END = \"]\";\n\t\tfinal String RUN_ARRAY_DELIM = \";\";\n\t\tfinal int MIN_LENGTH = 3; // minimum run is one value. e.g. \"[v]\"\n\n\t\tif (!value.startsWith(RUN_ARRAY_START) ||\n\t\t\t!value.endsWith(RUN_ARRAY_END) ||\n\t\t\trunIndex < 0 ||\n\t\t\tvalue.length() < MIN_LENGTH) {\n\t\t\treturn value; // standard format setting -> return\n\t\t}\n\n\t\tvalue = value.substring(1,value.length()-1); // remove brackets\n\t\tString[] valueArr = value.split(RUN_ARRAY_DELIM);\n\t\tint arrIndex = runIndex % valueArr.length;\n\t\tvalue = valueArr[arrIndex].trim();\n\n\t\treturn value;\n\t}\n\n\t/**\n\t * Returns the setting name appended to namespace name(s) on a String\n\t * (for error messages)\n\t * @param name Name of the setting\n\t * @return the setting name appended to namespace name(s) on a String\n\t */\n\tprivate String getPropertyNamesString(String name) {\n\t\tif (this.secondaryNamespace != null) {\n\t\t\treturn \"'\"+ this.secondaryNamespace + \".\" + name + \"' nor '\" +\n\t\t\t\tthis.namespace + \".\" + name + \"'\";\n\t\t}\n\t\telse if (this.namespace != null){\n\t\t\treturn \"'\" + this.namespace + \".\" + name + \"'\";\n\t\t}\n\t\telse {\n\t\t\treturn \"'\" + name + \"'\";\n\t\t}\n\t}\n\n\t/**\n\t * Returns a double-valued setting\n\t * @param name Name of the setting to get\n\t * @return Value of the setting as a double\n\t */\n\tpublic double getDouble(String name) {\n\t\treturn parseDouble(getSetting(name), name);\n\t}\n\n\t/**\n\t * Returns a double-valued setting, or the default value if the given\n\t * setting does not exist\n\t * @param name Name of the setting to get\n\t * @param defaultValue The value to return if the setting doesn't exist\n\t * @return Value of the setting as a double (or the default value)\n\t */\n\tpublic double getDouble(String name, double defaultValue) {\n\t\treturn parseDouble(getSetting(name, \"\"+defaultValue), name);\n\t}\n\n\t/**\n\t * Parses a double value from a String valued setting. Supports\n\t * kilo (k), mega (M) and giga (G) suffixes.\n\t * @param value String value to parse\n\t * @param setting The setting where this value was from (for error msgs)\n\t * @return The value as a double\n\t * @throws SettingsError if the value wasn't a numeric value\n\t * (or the suffix wasn't recognized)\n\t */\n\tprivate double parseDouble(String value, String setting) {\n\t\tdouble number;\n\t\tint multiplier = getMultiplier(value);\n\n\t\tif (multiplier > 1) { // take the suffix away before parsing\n\t\t\tvalue = value.replaceAll(\"[^\\\\d.]\",\"\");\n\t\t\t//replaceAll removes everything which is not a digit or point\n\t\t}\n\n\t\ttry {\n\t\t\tnumber = Double.parseDouble(value) * multiplier;\n\t\t} catch (NumberFormatException e) {\n\t\t\tthrow new SettingsError(\"Invalid numeric setting '\" + value +\n\t\t\t\t\t\"' for '\" + setting +\"'\\n\" + e.getMessage());\n\t\t}\n\t\treturn number;\n\t}\n\t\n\t/**\n\t * Parses a long value from a String valued setting. Supports\n\t * kilo (k), mega (M) and giga (G) suffixes.\n\t * @param value String value to parse\n\t * @param setting The setting where this value was from (for error msgs)\n\t * @return The value as a long\n\t * @throws SettingsError if the value wasn't a numeric value\n\t * (or the suffix wasn't recognized)\n\t */\n\tprivate long parseLong(String value, String setting) {\n\t\tlong number;\n\t\tint multiplier = getMultiplier(value);\n\n\t\tif (multiplier > 1) { // take the suffix away before parsing\n\t\t\tvalue = value.replaceAll(\"[^\\\\d.]\",\"\");\n\t\t}\n\n\t\ttry {\n\t\t\tnumber = Long.parseLong(value) * multiplier;\n\t\t} catch (NumberFormatException e) {\n\t\t\tthrow new SettingsError(\"Invalid numeric setting '\" + value +\n\t\t\t\t\t\"' for '\" + setting +\"'\\n\" + e.getMessage());\n\t\t}\n\t\treturn number;\n\t}\n\t\n\t/**\n\t * Parses the multiplier suffix from numeric setting\n\t * @param value The setting value\n\t * @return The muliplier as a number\n\t */\n\tprivate int getMultiplier(String value) {\n\t\tvalue = value.trim();\n\t\t\n\t\tif (value.endsWith(\"k\")) {\n\t\t\treturn 1000;\n\t\t}\n\t\telse if (value.endsWith(\"M\")) {\n\t\t\treturn 1000000;\n\t\t}\n\t\telse if (value.endsWith(\"G\")) {\n\t\t\treturn 1000000000;\n\t\t}\n\t\telse if (value.endsWith(\"kiB\")) {\n\t\t\t//2^10\n\t\t\treturn 1024;\n\t\t}\n\t\telse if (value.endsWith(\"MiB\")) {\n\t\t\t//2^20\n\t\t\treturn 1048576;\n\t\t}\n\t\telse if (value.endsWith(\"GiB\")) {\n\t\t\t//2^30\n\t\t\treturn 1073741824;\n\t\t} else {\n\t\t\t// no multiplier\n\t\t\treturn 1;\n\t\t}\n\t}\n\n\t/**\n\t * Returns a CSV setting. Value part of the setting must be a list of\n\t * comma separated values. Whitespace between values is trimmed away.\n\t * @param name Name of the setting\n\t * @return Array of values that were comma-separated\n\t * @throws SettingsError if something went wrong with reading\n\t */\n\tpublic String[] getCsvSetting(String name) {\n\t\tArrayList<String> values = new ArrayList<String>();\n\t\tString csv = getSetting(name);\n\t\tScanner s = new Scanner(csv);\n\t\ts.useDelimiter(\",\");\n\n\t\twhile (s.hasNext()) {\n\t\t\tvalues.add(s.next().trim());\n\t\t}\n\n\t\ts.close();\n\t\treturn values.toArray(new String[0]);\n\t}\n\n\t/**\n\t * Returns a CSV setting containing expected amount of values.\n\t * Value part of the setting must be a list of\n\t * comma separated values. Whitespace between values is trimmed away.\n\t * @param name Name of the setting\n\t * @param expectedCount how many values are expected\n\t * @return Array of values that were comma-separated\n\t * @throws SettingsError if something went wrong with reading or didn't\n\t * read the expected amount of values.\n\t */\n\tpublic String[] getCsvSetting(String name, int expectedCount) {\n\t\tString[] values = getCsvSetting(name);\n\n\t\tif (values.length != expectedCount) {\n\t\t\tthrow new SettingsError(\"Read unexpected amount (\" + values.length +\n\t\t\t\t\t\") of comma separated values for setting '\"\n\t\t\t\t\t+ name + \"' (expected \" + expectedCount + \")\");\n\t\t}\n\n\t\treturn values;\n\t}\n\n\t/**\n\t * Returns an array of CSV setting double values containing expected\n\t * amount of values.\n\t * @param name Name of the setting\n\t * @param expectedCount how many values are expected\n\t * @return Array of values that were comma-separated\n\t * @see #getCsvSetting(String, int)\n\t */\n\tpublic double[] getCsvDoubles(String name, int expectedCount) {\n\t\treturn parseDoubles(getCsvSetting(name, expectedCount),name);\n\t}\n\n\t/**\n\t * Returns an array of CSV setting double values.\n\t * @param name Name of the setting\n\t * @return Array of values that were comma-separated\n\t * @see #getCsvSetting(String)\n\t */\n\tpublic double[] getCsvDoubles(String name) {\n\t\treturn parseDoubles(getCsvSetting(name), name);\n\t}\n\n\t/**\n\t * Parses a double array out of a String array\n\t * @param strings The array of strings containing double values\n\t * @param name Name of the setting\n\t * @return Array of double values parsed from the string values\n\t */\n\tprivate double[] parseDoubles(String[] strings, String name) {\n\t\tdouble[] values = new double[strings.length];\n\t\tfor (int i=0; i<values.length; i++) {\n\t\t\tvalues[i] = parseDouble(strings[i], name);\n\t\t}\n\t\treturn values;\n\t}\n\n\t/**\n\t * Returns an array of CSV setting integer values\n\t * @param name Name of the setting\n\t * @param expectedCount how many values are expected\n\t * @return Array of values that were comma-separated\n\t * @see #getCsvSetting(String, int)\n\t */\n\tpublic int[] getCsvInts(String name, int expectedCount) {\n\t\treturn convertToInts(getCsvDoubles(name, expectedCount), name);\n\t}\n\n\t/**\n\t * Returns an array of CSV setting integer values\n\t * @param name Name of the setting\n\t * @return Array of values that were comma-separated\n\t * @see #getCsvSetting(String, int)\n\t */\n\tpublic int[] getCsvInts(String name) {\n\t\treturn convertToInts(getCsvDoubles(name), name);\n\t}\n\n\t/**\n\t * Returns comma-separated ranges (e.g., \"3-5, 17-20, 15\")\n\t * @param name Name of the setting\n\t * @return Array of ranges that were comma-separated in the setting\n\t * @throws SettingsError if something went wrong with reading\n\t */\n\tpublic Range[] getCsvRanges(String name) {\n\t\tString[] strRanges = getCsvSetting(name);\n\t\tRange[] ranges = new Range[strRanges.length];\n\n\t\ttry {\n\t\t\tfor (int i=0; i < strRanges.length; i++) {\n\t\t\t\tranges[i] = new Range(strRanges[i]);\n\t\t\t}\n\t\t} catch (NumberFormatException nfe) {\n\t\t\tthrow new SettingsError(\"Invalid numeric range value in \" +\n\t\t\t\t\tname, nfe);\n\t\t}\n\n\t\treturn ranges;\n\t}\n\n\t/**\n\t * Returns an integer-valued setting\n\t * @param name Name of the setting to get\n\t * @return Value of the setting as an integer\n\t */\n\tpublic int getInt(String name) {\n\t\treturn convertToInt(getDouble(name), name);\n\t}\n\t\n\t/**\n\t * Returns a long-valued setting\n\t * @param name Name of the setting to get\n\t * @return Value of the setting as an integer\n\t */\n\tpublic long getLong(String name) {\n\t\treturn parseLong(getSetting(name), name);\n\t}\n\n\t/**\n\t * Returns an integer-valued setting, or the default value if the\n\t * setting does not exist\n\t * @param name Name of the setting to get\n\t * @param defaultValue The value to return if the setting didn't exist\n\t * @return Value of the setting as an integer\n\t */\n\tpublic int getInt(String name, int defaultValue) {\n\t\treturn convertToInt(getDouble(name, defaultValue), name);\n\t}\n\n\t/**\n\t * Converts a double value that is supposedly equal to an integer value\n\t * to an integer value.\n\t * @param doubleValue The double value to convert\n\t * @param name Name of the setting where this value is from (for\n\t * SettingsError)\n\t * @return The integer value\n\t * @throws SettingsError if the double value was not equal to any integer\n\t * value\n\t */\n\tprivate int convertToInt(double doubleValue, String name) {\n\t\tint number = (int)doubleValue;\n\n\t\tif (number != doubleValue) {\n\t\t\tthrow new SettingsError(\"Expected integer value for setting '\" +\n\t\t\t\t\tname + \"' \" + \" got '\" + doubleValue + \"'\");\n\t\t}\n\t\treturn number;\n\t}\n\n\t/**\n\t * Converts an array of double values to int values using\n\t * {@link #convertToInt(double, String)}.\n\t * @param doubleValues The double valued array\n\t * @param name Name of the setting where this value is from (for\n\t * SettingsError)\n\t * @return Array of integer values\n\t * @see #convertToInt(double, String)\n\t */\n\tprivate int[] convertToInts(double [] doubleValues, String name) {\n\t\tint[] values = new int[doubleValues.length];\n\t\tfor (int i=0; i<values.length; i++) {\n\t\t\tvalues[i] = convertToInt(doubleValues[i], name);\n\t\t}\n\t\treturn values;\n\t}\n\n\t/**\n\t * Returns a boolean-valued setting\n\t * @param name Name of the setting to get\n\t * @return True if the settings value was either \"true\" (case ignored)\n\t * or \"1\", false is the settings value was either \"false\" (case ignored)\n\t * or \"0\".\n\t * @throws SettingsError if the value wasn't any recognized value\n\t * @see #getSetting(String)\n\t */\n\tpublic boolean getBoolean(String name) {\n\t\tString stringValue = getSetting(name);\n\t\tboolean value;\n\n\t\tif (stringValue.equalsIgnoreCase(\"true\") ||\n\t\t\t\tstringValue.equals(\"1\")) {\n\t\t\tvalue = true;\n\t\t}\n\t\telse if (stringValue.equalsIgnoreCase(\"false\") ||\n\t\t\t\tstringValue.equals(\"0\")) {\n\t\t\tvalue = false;\n\t\t}\n\t\telse {\n\t\t\tthrow new SettingsError(\"Not a boolean value: '\"+stringValue+\n\t\t\t\t\t\"' for setting \" + name);\n\t\t}\n\n\t\treturn value;\n\t}\n\n\t/**\n\t * Returns the given boolean setting if it exists, or defaultValue if the\n\t * setting does not exist\n\t * @param name The name of the setting\n\t * @param defaultValue The value to return if the given setting didn't exist\n\t * @return The setting value or the default value if the setting didn't\n\t * exist\n\t */\n\tpublic boolean getBoolean(String name, boolean defaultValue) {\n\t\tif (!contains(name)) {\n\t\t\treturn defaultValue;\n\t\t} else {\n\t\t\treturn getBoolean(name);\n\t\t}\n\t}\n\n\t/**\n\t * Returns an ArithmeticCondition setting. See {@link ArithmeticCondition}\n\t * @param name Name of the setting to get\n\t * @return ArithmeticCondition from the setting\n\t * @throws SettingsError if the value wasn't a valid arithmetic expression\n\t */\n\tpublic ArithmeticCondition getCondition(String name) {\n\t\treturn new ArithmeticCondition(getSetting(name));\n\t}\n\n\t/**\n\t * Creates (and dynamically loads the class of) an object that\n\t * initializes itself using the settings in this Settings object\n\t * (given as the only parameter to the constructor).\n\t * @param className Name of the class of the object\n\t * @return Initialized object\n\t * @throws SettingsError if object couldn't be created\n\t */\n\tpublic Object createIntializedObject(String className) {\n\t\tClass<?>[] argsClass = {Settings.class};\n\t\tObject[] args = {this};\n\n\t\treturn loadObject(className, argsClass, args);\n\t}\n\n\t/**\n\t * Creates (and dynamically loads the class of) an object using the\n\t * constructor without any parameters.\n\t * @param className Name of the class of the object\n\t * @return Initialized object\n\t * @throws SettingsError if object couldn't be created\n\t */\n\tpublic Object createObject(String className) {\n\t\treturn loadObject(className, null, null);\n\t}\n\n\t/**\n\t * Dynamically loads and creates an object.\n\t * @param className Name of the class of the object\n\t * @param argsClass Class(es) of the argument(s) or null if no-argument\n\t * constructor should be called\n\t * @param args Argument(s)\n\t * @return The new object\n\t * @throws SettingsError if object couldn't be created\n\t */\n\tprivate Object loadObject(String className, Class<?>[] argsClass,\n\t\t\tObject[] args) {\n\t\tObject o = null;\n\t\tClass<?> objClass = getClass(className);\n\t\tConstructor<?> constructor;\n\n\t\ttry {\n\t\t\tif (argsClass != null) { // use a specific constructor\n\t\t\t\tconstructor = objClass.getConstructor((Class[])argsClass);\n\t\t\t\to = constructor.newInstance(args);\n\t\t\t}\n\t\t\telse { // call empty constructor\n\t\t\t\to = objClass.newInstance();\n\t\t\t}\n\t\t} catch (SecurityException e) {\n\t\t\te.printStackTrace();\n\t\t\tthrow new SettingsError(\"Fatal exception \" + e, e);\n\t\t} catch (IllegalArgumentException e) {\n\t\t\te.printStackTrace();\n\t\t\tthrow new SettingsError(\"Fatal exception \" + e, e);\n\t\t} catch (NoSuchMethodException e) {\n\t\t\tthrow new SettingsError(\"Class '\" + className +\n\t\t\t\t\t\"' doesn't have a suitable constructor\", e);\n\t\t} catch (InstantiationException e) {\n\t\t\tthrow new SettingsError(\"Can't create an instance of '\" +\n\t\t\t\t\tclassName + \"'\", e);\n\t\t} catch (IllegalAccessException e) {\n\t\t\te.printStackTrace();\n\t\t\tthrow new SettingsError(\"Fatal exception \" + e, e);\n\t\t} catch (InvocationTargetException e) {\n\t\t\t// this exception occurs if initialization of the object fails\n\t\t\tif (e.getCause() instanceof SettingsError) {\n\t\t\t\tthrow (SettingsError)e.getCause();\n\t\t\t}\n\t\t\telse {\n\t\t\t\te.printStackTrace();\n\t\t\t\tthrow new SimError(\"Couldn't create settings-accepting object\"+\n\t\t\t\t\t\" for '\" + className + \"'\\n\" + \"cause: \" + e.getCause(), e);\n\t\t\t}\n\t\t}\n\n\t\treturn o;\n\t}\n\n\t/**\n\t * Returns a Class object for the name of class of throws SettingsError\n\t * if such class wasn't found.\n\t * @param name Full name of the class (including package name)\n\t * @return A Class object of that class\n\t * @throws SettingsError if such class wasn't found or couldn't be loaded\n\t */\n\tprivate Class<?> getClass(String name) {\n\t\tString className = name;\n\t\tClass<?> c;\n\n\t\ttry {\n\t\t\tc = Class.forName(className);\n\t\t} catch (ClassNotFoundException e) {\n\t\t\tthrow new SettingsError(\"Couldn't find class '\" + className + \"'\"+\n\t\t\t\t\t\"\\n\" + e.getMessage(),e);\n\t\t}\n\n\t\treturn c;\n\t}\n\n\t/**\n\t * Fills a String formatted in a special way with values from Settings.\n\t * String can contain (fully qualified) setting names surrounded by\n\t * delimiters (see {@link #FILL_DELIMITER}). Values for those settings\n\t * are retrieved and filled in the place of place holders.\n\t * @param input The input string that may contain value requests\n\t * @return A string filled with requested values (or the original string\n\t * if no requests were found)\n\t * @throws SettingsError if such settings were not found\n\t */\n\tpublic String valueFillString(String input) {\n\t\tif (!input.contains(FILL_DELIMITER)) {\n\t\t\treturn input;\t// nothing to fill\n\t\t}\n\n\t\tSettings s = new Settings(); // don't use any namespace\n\t\tString result = \"\";\n\t\tScanner scan = new Scanner(input);\n\t\tscan.useDelimiter(FILL_DELIMITER);\n\n\t\tif (input.startsWith(FILL_DELIMITER)) {\n\t\t\tresult += s.getSetting(scan.next());\n\t\t}\n\n\t\twhile(scan.hasNext()) {\n\t\t\tresult += scan.next();\n\t\t\tif (!scan.hasNext()) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tresult += s.getSetting(scan.next());\n\t\t}\n\t\t\n\t\tscan.close();\n\t\treturn result;\n\t}\n\n\t/**\n\t * Returns a String representation of the stored settings\n\t * @return a String representation of the stored settings\n\t */\n\tpublic String toString() {\n\t\treturn props.toString();\n\t}\n\n}",
"public class SettingsError extends SimError {\n\n\tpublic SettingsError(String cause) {\n\t\tsuper(cause);\n\t}\n\n\tpublic SettingsError(String cause, Exception e) {\n\t\tsuper(cause,e);\n\t}\n\n\tpublic SettingsError(Exception e) {\n\t\tsuper(e);\n\t}\n\n}",
"public class SimError extends AssertionError {\n\tprivate Exception e;\n\n\tpublic SimError(String cause) {\n\t\tsuper(cause);\n\t\te = null;\n\t}\n\n\tpublic SimError(String cause, Exception e) {\n\t\tsuper(cause);\n\t\tthis.e = e;\n\t}\n\n\tpublic SimError(Exception e) {\n\t\tthis(e.getMessage(),e);\n\t}\n\n\tpublic Exception getException() {\n\t\treturn e;\n\t}\n\n}",
"public class SimScenario implements Serializable {\n\n\t/** a way to get a hold of this... */\n\tprivate static SimScenario myinstance=null;\n\n\t/** namespace of scenario settings ({@value})*/\n\tpublic static final String SCENARIO_NS = \"Scenario\";\n\t/** number of host groups -setting id ({@value})*/\n\tpublic static final String NROF_GROUPS_S = \"nrofHostGroups\";\n\t/** number of interface types -setting id ({@value})*/\n\tpublic static final String NROF_INTTYPES_S = \"nrofInterfaceTypes\";\n\t/** scenario name -setting id ({@value})*/\n\tpublic static final String NAME_S = \"name\";\n\t/** end time -setting id ({@value})*/\n\tpublic static final String END_TIME_S = \"endTime\";\n\t/** update interval -setting id ({@value})*/\n\tpublic static final String UP_INT_S = \"updateInterval\";\n\t/** simulate connections -setting id ({@value})*/\n\tpublic static final String SIM_CON_S = \"simulateConnections\";\n\n\t/** namespace for interface type settings ({@value}) */\n\tpublic static final String INTTYPE_NS = \"Interface\";\n\t/** interface type -setting id ({@value}) */\n\tpublic static final String INTTYPE_S = \"type\";\n\t/** interface name -setting id ({@value}) */\n\tpublic static final String INTNAME_S = \"name\";\n\n\t/** namespace for application type settings ({@value}) */\n\tpublic static final String APPTYPE_NS = \"Application\";\n\t/** application type -setting id ({@value}) */\n\tpublic static final String APPTYPE_S = \"type\";\n\t/** setting name for the number of applications */\n\tpublic static final String APPCOUNT_S = \"nrofApplications\";\n\n\t/** namespace for host group settings ({@value})*/\n\tpublic static final String GROUP_NS = \"Group\";\n\t/** group id -setting id ({@value})*/\n\tpublic static final String GROUP_ID_S = \"groupID\";\n\t/** number of hosts in the group -setting id ({@value})*/\n\tpublic static final String NROF_HOSTS_S = \"nrofHosts\";\n\t/** movement model class -setting id ({@value})*/\n\tpublic static final String MOVEMENT_MODEL_S = \"movementModel\";\n\t/** router class -setting id ({@value})*/\n\tpublic static final String ROUTER_S = \"router\";\n\t/** number of interfaces in the group -setting id ({@value})*/\n\tpublic static final String NROF_INTERF_S = \"nrofInterfaces\";\n\t/** interface name in the group -setting id ({@value})*/\n\tpublic static final String INTERFACENAME_S = \"interface\";\n\t/** application name in the group -setting id ({@value})*/\n\tpublic static final String GAPPNAME_S = \"application\";\n\n\t/** package where to look for movement models */\n\tprivate static final String MM_PACKAGE = \"movement.\";\n\t/** package where to look for router classes */\n\tprivate static final String ROUTING_PACKAGE = \"routing.\";\n\n\t/** package where to look for interface classes */\n\tprivate static final String INTTYPE_PACKAGE = \"interfaces.\";\n\n\t/** package where to look for application classes */\n\tprivate static final String APP_PACKAGE = \"applications.\";\n\n\t/** The world instance */\n\tprivate World world;\n\t/** List of hosts in this simulation */\n\tprotected List<DTNHost> hosts;\n\t/** Name of the simulation */\n\tprivate String name;\n\t/** number of host groups */\n\tint nrofGroups;\n\t/** Width of the world */\n\tprivate int worldSizeX;\n\t/** Height of the world */\n\tprivate int worldSizeY;\n\t/** Largest host's radio range */\n\tprivate double maxHostRange;\n\t/** Simulation end time */\n\tprivate double endTime;\n\t/** Update interval of sim time */\n\tprivate double updateInterval;\n\t/** External events queue */\n\tprivate EventQueueHandler eqHandler;\n\t/** Should connections between hosts be simulated */\n\tprivate boolean simulateConnections;\n\t/** Map used for host movement (if any) */\n\tprivate SimMap simMap;\n\n\t/** Global connection event listeners */\n\tprivate List<ConnectionListener> connectionListeners;\n\t/** Global message event listeners */\n\tprivate List<MessageListener> messageListeners;\n\t/** Global movement event listeners */\n\tprivate List<MovementListener> movementListeners;\n\t/** Global update event listeners */\n\tprivate List<UpdateListener> updateListeners;\n\t/** Global application event listeners */\n\tprivate List<ApplicationListener> appListeners;\n\n\tstatic {\n\t\tDTNSim.registerForReset(SimScenario.class.getCanonicalName());\n\t\treset();\n\t}\n\n\tpublic static void reset() {\n\t\tmyinstance = null;\n\t}\n\n\t/**\n\t * Creates a scenario based on Settings object.\n\t */\n\tprotected SimScenario() {\n\t\tSettings s = new Settings(SCENARIO_NS);\n\t\tnrofGroups = s.getInt(NROF_GROUPS_S);\n\n\t\tthis.name = s.valueFillString(s.getSetting(NAME_S));\n\t\tthis.endTime = s.getDouble(END_TIME_S);\n\t\tthis.updateInterval = s.getDouble(UP_INT_S);\n\t\tthis.simulateConnections = s.getBoolean(SIM_CON_S);\n\n\t\ts.ensurePositiveValue(nrofGroups, NROF_GROUPS_S);\n\t\ts.ensurePositiveValue(endTime, END_TIME_S);\n\t\ts.ensurePositiveValue(updateInterval, UP_INT_S);\n\n\t\tthis.simMap = null;\n\t\tthis.maxHostRange = 1;\n\n\t\tthis.connectionListeners = new ArrayList<ConnectionListener>();\n\t\tthis.messageListeners = new ArrayList<MessageListener>();\n\t\tthis.movementListeners = new ArrayList<MovementListener>();\n\t\tthis.updateListeners = new ArrayList<UpdateListener>();\n\t\tthis.appListeners = new ArrayList<ApplicationListener>();\n\t\tthis.eqHandler = new EventQueueHandler();\n\n\t\t/* TODO: check size from movement models */\n\t\ts.setNameSpace(MovementModel.MOVEMENT_MODEL_NS);\n\t\tint [] worldSize = s.getCsvInts(MovementModel.WORLD_SIZE, 2);\n\t\tthis.worldSizeX = worldSize[0];\n\t\tthis.worldSizeY = worldSize[1];\n\n\t\tcreateHosts();\n\n\t\tthis.world = new World(hosts, worldSizeX, worldSizeY, updateInterval,\n\t\t\t\tupdateListeners, simulateConnections,\n\t\t\t\teqHandler.getEventQueues());\n\t}\n\n\t/**\n\t * Returns the SimScenario instance and creates one if it doesn't exist yet\n\t */\n\tpublic static SimScenario getInstance() {\n\t\tif (myinstance == null) {\n\t\t\tmyinstance = new SimScenario();\n\t\t}\n\t\treturn myinstance;\n\t}\n\n\n\n\t/**\n\t * Returns the name of the simulation run\n\t * @return the name of the simulation run\n\t */\n\tpublic String getName() {\n\t\treturn this.name;\n\t}\n\n\t/**\n\t * Returns true if connections should be simulated\n\t * @return true if connections should be simulated (false if not)\n\t */\n\tpublic boolean simulateConnections() {\n\t\treturn this.simulateConnections;\n\t}\n\n\t/**\n\t * Returns the width of the world\n\t * @return the width of the world\n\t */\n\tpublic int getWorldSizeX() {\n\t\treturn this.worldSizeX;\n\t}\n\n\t/**\n\t * Returns the height of the world\n\t * @return the height of the world\n\t */\n\tpublic int getWorldSizeY() {\n\t\treturn worldSizeY;\n\t}\n\n\t/**\n\t * Returns simulation's end time\n\t * @return simulation's end time\n\t */\n\tpublic double getEndTime() {\n\t\treturn endTime;\n\t}\n\n\t/**\n\t * Returns update interval (simulated seconds) of the simulation\n\t * @return update interval (simulated seconds) of the simulation\n\t */\n\tpublic double getUpdateInterval() {\n\t\treturn updateInterval;\n\t}\n\n\t/**\n\t * Returns how long range the hosts' radios have\n\t * @return Range in meters\n\t */\n\tpublic double getMaxHostRange() {\n\t\treturn maxHostRange;\n\t}\n\n\t/**\n\t * Returns the (external) event queue(s) of this scenario or null if there\n\t * aren't any\n\t * @return External event queues in a list or null\n\t */\n\tpublic List<EventQueue> getExternalEvents() {\n\t\treturn this.eqHandler.getEventQueues();\n\t}\n\n\t/**\n\t * Returns the SimMap this scenario uses, or null if scenario doesn't\n\t * use any map\n\t * @return SimMap or null if no map is used\n\t */\n\tpublic SimMap getMap() {\n\t\treturn this.simMap;\n\t}\n\n\t/**\n\t * Adds a new connection listener for all nodes\n\t * @param cl The listener\n\t */\n\tpublic void addConnectionListener(ConnectionListener cl){\n\t\tthis.connectionListeners.add(cl);\n\t}\n\n\t/**\n\t * Adds a new message listener for all nodes\n\t * @param ml The listener\n\t */\n\tpublic void addMessageListener(MessageListener ml){\n\t\tthis.messageListeners.add(ml);\n\t}\n\n\t/**\n\t * Adds a new movement listener for all nodes\n\t * @param ml The listener\n\t */\n\tpublic void addMovementListener(MovementListener ml){\n\t\tthis.movementListeners.add(ml);\n\n\t\t// Invoke the initialLocation() for all nodes that already exist in\n\t\t// the Scenario. This ensures initialLocation() gets called for every\n\t\t// node.\n\t\tfor (final DTNHost host : this.hosts) {\n\t\t\tml.initialLocation(host, host.getLocation());\n\t\t}\n\t}\n\n\t/**\n\t * Adds a new update listener for the world\n\t * @param ul The listener\n\t */\n\tpublic void addUpdateListener(UpdateListener ul) {\n\t\tthis.updateListeners.add(ul);\n\t}\n\n\t/**\n\t * Returns the list of registered update listeners\n\t * @return the list of registered update listeners\n\t */\n\tpublic List<UpdateListener> getUpdateListeners() {\n\t\treturn this.updateListeners;\n\t}\n\n\t/**\n\t * Adds a new application event listener for all nodes.\n\t * @param al The listener\n\t */\n\tpublic void addApplicationListener(ApplicationListener al) {\n\t\tthis.appListeners.add(al);\n\t}\n\n\t/**\n\t * Returns the list of registered application event listeners\n\t * @return the list of registered application event listeners\n\t */\n\tpublic List<ApplicationListener> getApplicationListeners() {\n\t\treturn this.appListeners;\n\t}\n\n\t/**\n\t * Creates hosts for the scenario\n\t */\n\tprotected void createHosts() {\n\t\tthis.hosts = new ArrayList<DTNHost>();\n\n\t\tfor (int i=1; i<=nrofGroups; i++) {\n\t\t\tList<NetworkInterface> interfaces =\n\t\t\t\tnew ArrayList<NetworkInterface>();\n\t\t\tSettings s = new Settings(GROUP_NS+i);\n\t\t\ts.setSecondaryNamespace(GROUP_NS);\n\t\t\tString gid = s.getSetting(GROUP_ID_S);\n\t\t\tint nrofHosts = s.getInt(NROF_HOSTS_S);\n\t\t\tint nrofInterfaces = s.getInt(NROF_INTERF_S);\n\t\t\tint appCount;\n\n\t\t\t// creates prototypes of MessageRouter and MovementModel\n\t\t\tMovementModel mmProto =\n\t\t\t\t(MovementModel)s.createIntializedObject(MM_PACKAGE +\n\t\t\t\t\t\ts.getSetting(MOVEMENT_MODEL_S));\n\t\t\tMessageRouter mRouterProto =\n\t\t\t\t(MessageRouter)s.createIntializedObject(ROUTING_PACKAGE +\n\t\t\t\t\t\ts.getSetting(ROUTER_S));\n\n\t\t\t/* checks that these values are positive (throws Error if not) */\n\t\t\ts.ensurePositiveValue(nrofHosts, NROF_HOSTS_S);\n\t\t\ts.ensurePositiveValue(nrofInterfaces, NROF_INTERF_S);\n\n\t\t\t// setup interfaces\n\t\t\tfor (int j=1;j<=nrofInterfaces;j++) {\n\t\t\t\tString intName = s.getSetting(INTERFACENAME_S + j);\n\t\t\t\tSettings intSettings = new Settings(intName);\n\t\t\t\tNetworkInterface iface =\n\t\t\t\t\t(NetworkInterface)intSettings.createIntializedObject(\n\t\t\t\t\t\t\tINTTYPE_PACKAGE +intSettings.getSetting(INTTYPE_S));\n\t\t\t\tiface.setClisteners(connectionListeners);\n\t\t\t\tiface.setGroupSettings(s);\n\t\t\t\tinterfaces.add(iface);\n\t\t\t}\n\n\t\t\t// setup applications\n\t\t\tif (s.contains(APPCOUNT_S)) {\n\t\t\t\tappCount = s.getInt(APPCOUNT_S);\n\t\t\t} else {\n\t\t\t\tappCount = 0;\n\t\t\t}\n\t\t\tfor (int j=1; j<=appCount; j++) {\n\t\t\t\tString appname = null;\n\t\t\t\tApplication protoApp = null;\n\t\t\t\ttry {\n\t\t\t\t\t// Get name of the application for this group\n\t\t\t\t\tappname = s.getSetting(GAPPNAME_S+j);\n\t\t\t\t\t// Get settings for the given application\n\t\t\t\t\tSettings t = new Settings(appname);\n\t\t\t\t\t// Load an instance of the application\n\t\t\t\t\tprotoApp = (Application)t.createIntializedObject(\n\t\t\t\t\t\t\tAPP_PACKAGE + t.getSetting(APPTYPE_S));\n\t\t\t\t\t// Set application listeners\n\t\t\t\t\tprotoApp.setAppListeners(this.appListeners);\n\t\t\t\t\t// Set the proto application in proto router\n\t\t\t\t\t//mRouterProto.setApplication(protoApp);\n\t\t\t\t\tmRouterProto.addApplication(protoApp);\n\t\t\t\t} catch (SettingsError se) {\n\t\t\t\t\t// Failed to create an application for this group\n\t\t\t\t\tSystem.err.println(\"Failed to setup an application: \" + se);\n\t\t\t\t\tSystem.err.println(\"Caught at \" + se.getStackTrace()[0]);\n\t\t\t\t\tSystem.exit(-1);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (mmProto instanceof MapBasedMovement) {\n\t\t\t\tthis.simMap = ((MapBasedMovement)mmProto).getMap();\n\t\t\t}\n\n\t\t\t// creates hosts of ith group\n\t\t\tfor (int j=0; j<nrofHosts; j++) {\n\t\t\t\tModuleCommunicationBus comBus = new ModuleCommunicationBus();\n\n\t\t\t\t// prototypes are given to new DTNHost which replicates\n\t\t\t\t// new instances of movement model and message router\n\t\t\t\tDTNHost host = new DTNHost(this.messageListeners,\n\t\t\t\t\t\tthis.movementListeners,\tgid, interfaces, comBus,\n\t\t\t\t\t\tmmProto, mRouterProto);\n\t\t\t\thosts.add(host);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Returns the list of nodes for this scenario.\n\t * @return the list of nodes for this scenario.\n\t */\n\tpublic List<DTNHost> getHosts() {\n\t\treturn this.hosts;\n\t}\n\n\t/**\n\t * Returns the World object of this scenario\n\t * @return the World object\n\t */\n\tpublic World getWorld() {\n\t\treturn this.world;\n\t}\n\n}",
"public interface UpdateListener {\n\n\t/**\n\t * Method is called on every update cycle.\n\t * @param hosts A list of all hosts in the world\n\t */\n\tpublic void updated(List<DTNHost> hosts);\n\n}",
"public class World {\n\t/** name space of optimization settings ({@value})*/\n\tpublic static final String OPTIMIZATION_SETTINGS_NS = \"Optimization\";\n\n\t/**\n\t * Should the order of node updates be different (random) within every\n\t * update step -setting id ({@value}). Boolean (true/false) variable.\n\t * Default is @link {@link #DEF_RANDOMIZE_UPDATES}.\n\t */\n\tpublic static final String RANDOMIZE_UPDATES_S = \"randomizeUpdateOrder\";\n\t/** should the update order of nodes be randomized -setting's default value\n\t * ({@value}) */\n\tpublic static final boolean DEF_RANDOMIZE_UPDATES = true;\n\n\t\n\t/**\n\t * Real-time simulation enabled -setting id ({@value}). \n\t * If set to true and simulation time moves faster than real time,\n\t * the simulation will pause after each update round to wait until real\n\t * time catches up. Default = false.\n\t */\n\tpublic static final String REALTIME_SIM_S = \"realtime\";\n\t/** should the update order of nodes be randomized -setting's default value\n\t * ({@value}) */\n\t\n\t/**\n\t * Should the connectivity simulation be stopped after one round\n\t * -setting id ({@value}). Boolean (true/false) variable. Default = false.\n\t */\n\tpublic static final String SIMULATE_CON_ONCE_S = \"simulateConnectionsOnce\";\n\n\tprivate int sizeX;\n\tprivate int sizeY;\n\tprivate List<EventQueue> eventQueues;\n\tprivate double updateInterval;\n\tprivate SimClock simClock;\n\tprivate double nextQueueEventTime;\n\tprivate EventQueue nextEventQueue;\n\t/** list of nodes; nodes are indexed by their network address */\n\tprivate List<DTNHost> hosts;\n\tprivate boolean simulateConnections;\n\t/** nodes in the order they should be updated (if the order should be\n\t * randomized; null value means that the order should not be randomized) */\n\tprivate ArrayList<DTNHost> updateOrder;\n\t/** is cancellation of simulation requested from UI */\n\tprivate boolean isCancelled;\n\tprivate List<UpdateListener> updateListeners;\n\t/** Queue of scheduled update requests */\n\tprivate ScheduledUpdatesQueue scheduledUpdates;\n\tprivate boolean simulateConOnce;\n\t\n\tprivate boolean realtimeSimulation;\n\tprivate long simStartRealtime;\n\n\t/**\n\t * Constructor.\n\t */\n\tpublic World(List<DTNHost> hosts, int sizeX, int sizeY,\n\t\t\tdouble updateInterval, List<UpdateListener> updateListeners,\n\t\t\tboolean simulateConnections, List<EventQueue> eventQueues) {\n\t\tthis.hosts = hosts;\n\t\tthis.sizeX = sizeX;\n\t\tthis.sizeY = sizeY;\n\t\tthis.updateInterval = updateInterval;\n\t\tthis.updateListeners = updateListeners;\n\t\tthis.simulateConnections = simulateConnections;\n\t\tthis.eventQueues = eventQueues;\n\n\t\tthis.simClock = SimClock.getInstance();\n\t\tthis.scheduledUpdates = new ScheduledUpdatesQueue();\n\t\tthis.isCancelled = false;\n\n\t\tthis.simStartRealtime = -1;\n\t\t\n\t\tsetNextEventQueue();\n\t\tinitSettings();\n\t}\n\n\t/**\n\t * Initializes settings fields that can be configured using Settings class\n\t */\n\tprivate void initSettings() {\n\t\tSettings s = new Settings(OPTIMIZATION_SETTINGS_NS);\n\t\tboolean randomizeUpdates = s.getBoolean(RANDOMIZE_UPDATES_S, \n\t\t\t\tDEF_RANDOMIZE_UPDATES);\n\n\t\tthis.simulateConOnce = s.getBoolean(SIMULATE_CON_ONCE_S, false);\n\t\t\n\t\tthis.realtimeSimulation = s.getBoolean(REALTIME_SIM_S ,false);\n\n\t\tif(randomizeUpdates) {\n\t\t\t// creates the update order array that can be shuffled\n\t\t\tthis.updateOrder = new ArrayList<DTNHost>(this.hosts);\n\t\t}\n\t\telse { // null pointer means \"don't randomize\"\n\t\t\tthis.updateOrder = null;\n\t\t}\n\t}\n\n\t/**\n\t * Moves hosts in the world for the time given time initialize host\n\t * positions properly. SimClock must be set to <CODE>-time</CODE> before\n\t * calling this method.\n\t * @param time The total time (seconds) to move\n\t */\n\tpublic void warmupMovementModel(double time) {\n\t\tif (time <= 0) {\n\t\t\treturn;\n\t\t}\n\n\t\twhile(SimClock.getTime() < -updateInterval) {\n\t\t\tmoveHosts(updateInterval);\n\t\t\tsimClock.advance(updateInterval);\n\t\t}\n\n\t\tdouble finalStep = -SimClock.getTime();\n\n\t\tmoveHosts(finalStep);\n\t\tsimClock.setTime(0);\n\t}\n\n\t/**\n\t * Goes through all event Queues and sets the\n\t * event queue that has the next event.\n\t */\n\tpublic void setNextEventQueue() {\n\t\tEventQueue nextQueue = scheduledUpdates;\n\t\tdouble earliest = nextQueue.nextEventsTime();\n\n\t\t/* find the queue that has the next event */\n\t\tfor (EventQueue eq : eventQueues) {\n\t\t\tif (eq.nextEventsTime() < earliest){\n\t\t\t\tnextQueue = eq;\n\t\t\t\tearliest = eq.nextEventsTime();\n\t\t\t}\n\t\t}\n\n\t\tthis.nextEventQueue = nextQueue;\n\t\tthis.nextQueueEventTime = earliest;\n\t}\n\n\t/**\n\t * Update (move, connect, disconnect etc.) all hosts in the world.\n\t * Runs all external events that are due between the time when\n\t * this method is called and after one update interval.\n\t */\n\tpublic void update () {\n\t\tdouble runUntil = SimClock.getTime() + this.updateInterval;\n\t\t\n\t\tif (realtimeSimulation) {\n\t\t\tif (this.simStartRealtime < 0) {\n\t\t\t\t/* first update round */\n\t\t\t\tthis.simStartRealtime = System.currentTimeMillis();\n\t\t\t}\n\n\t\t\tlong sleepTime = (long) (SimClock.getTime() * 1000 \n\t\t\t\t\t- (System.currentTimeMillis() - this.simStartRealtime));\n\t\t\tif (sleepTime > 0) {\n\t\t\t\ttry {\n\t\t\t\t\tThread.sleep(sleepTime);\n\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t\tthrow new SimError(\"Sleep interrupted:\" + e);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tsetNextEventQueue();\n\n\t\t/* process all events that are due until next interval update */\n\t\twhile (this.nextQueueEventTime <= runUntil) {\n\t\t\tsimClock.setTime(this.nextQueueEventTime);\n\t\t\tExternalEvent ee = this.nextEventQueue.nextEvent();\n\t\t\tee.processEvent(this);\n\t\t\tupdateHosts(); // update all hosts after every event\n\t\t\tsetNextEventQueue();\n\t\t}\n\n\t\tmoveHosts(this.updateInterval);\n\t\tsimClock.setTime(runUntil);\n\n\t\tupdateHosts();\n\n\t\t/* inform all update listeners */\n\t\tfor (UpdateListener ul : this.updateListeners) {\n\t\t\tul.updated(this.hosts);\n\t\t}\n\t\t\n\t}\n\n\t/**\n\t * Updates all hosts (calls update for every one of them). If update\n\t * order randomizing is on (updateOrder array is defined), the calls\n\t * are made in random order.\n\t */\n\tprivate void updateHosts() {\n\t\tif (this.updateOrder == null) { // randomizing is off\n\t\t\tfor (int i=0, n = hosts.size();i < n; i++) {\n\t\t\t\tif (this.isCancelled) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\thosts.get(i).update(simulateConnections);\n\t\t\t}\n\t\t}\n\t\telse { // update order randomizing is on\n\t\t\tassert this.updateOrder.size() == this.hosts.size() :\n\t\t\t\t\"Nrof hosts has changed unexpectedly\";\n\t\t\tRandom rng = new Random(SimClock.getIntTime());\n\t\t\tCollections.shuffle(this.updateOrder, rng);\n\t\t\tfor (int i=0, n = hosts.size();i < n; i++) {\n\t\t\t\tif (this.isCancelled) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tthis.updateOrder.get(i).update(simulateConnections);\n\t\t\t}\n\t\t}\n\n\t\tif (simulateConOnce && simulateConnections) {\n\t\t\tsimulateConnections = false;\n\t\t}\n\t}\n\n\t/**\n\t * Moves all hosts in the world for a given amount of time\n\t * @param timeIncrement The time how long all nodes should move\n\t */\n\tprivate void moveHosts(double timeIncrement) {\n\t\tfor (int i=0,n = hosts.size(); i<n; i++) {\n\t\t\tDTNHost host = hosts.get(i);\n\t\t\thost.move(timeIncrement);\n\t\t}\n\t}\n\n\t/**\n\t * Asynchronously cancels the currently running simulation\n\t */\n\tpublic void cancelSim() {\n\t\tthis.isCancelled = true;\n\t}\n\n\t/**\n\t * Returns the hosts in a list\n\t * @return the hosts in a list\n\t */\n\tpublic List<DTNHost> getHosts() {\n\t\treturn this.hosts;\n\t}\n\n\t/**\n\t * Returns the x-size (width) of the world\n\t * @return the x-size (width) of the world\n\t */\n\tpublic int getSizeX() {\n\t\treturn this.sizeX;\n\t}\n\n\t/**\n\t * Returns the y-size (height) of the world\n\t * @return the y-size (height) of the world\n\t */\n\tpublic int getSizeY() {\n\t\treturn this.sizeY;\n\t}\n\n\t/**\n\t * Returns a node from the world by its address\n\t * @param address The address of the node\n\t * @return The requested node or null if it wasn't found\n\t */\n\tpublic DTNHost getNodeByAddress(int address) {\n\t\tif (address < 0 || address >= hosts.size()) {\n\t\t\tthrow new SimError(\"No host for address \" + address + \". Address \" +\n\t\t\t\t\t\"range of 0-\" + (hosts.size()-1) + \" is valid\");\n\t\t}\n\n\t\tDTNHost node = this.hosts.get(address);\n\t\tassert node.getAddress() == address : \"Node indexing failed. \" +\n\t\t\t\"Node \" + node + \" in index \" + address;\n\n\t\treturn node;\n\t}\n\n\t/**\n\t * Schedules an update request to all nodes to happen at the specified\n\t * simulation time.\n\t * @param simTime The time of the update\n\t */\n\tpublic void scheduleUpdate(double simTime) {\n\t\tscheduledUpdates.addUpdate(simTime);\n\t}\n}"
] | import java.util.Vector;
import report.Report;
import core.ApplicationListener;
import core.ConnectionListener;
import core.MessageListener;
import core.MovementListener;
import core.Settings;
import core.SettingsError;
import core.SimClock;
import core.SimError;
import core.SimScenario;
import core.UpdateListener;
import core.World; | /*
* Copyright 2010 Aalto University, ComNet
* Released under GPLv3. See LICENSE.txt for details.
*/
package ui;
/**
* Abstract superclass for user interfaces; contains also some simulation
* settings.
*/
public abstract class DTNSimUI {
/**
* Number of reports -setting id ({@value}). Defines how many reports
* are loaded.
*/
public static final String NROF_REPORT_S = "Report.nrofReports";
/**
* Report class name -setting id prefix ({@value}). Defines name(s) of
* the report classes to load. Must be suffixed with numbers starting from
* one.
*/
public static final String REPORT_S = "Report.report";
/**
* Movement model warmup time -setting id ({@value}). Defines how many
* seconds of movement simulation is run without connectivity etc. checks
* before starting the real simulation.
*/
public static final String MM_WARMUP_S =
movement.MovementModel.MOVEMENT_MODEL_NS + ".warmup";
/** report class' package name */
private static final String REPORT_PAC = "report.";
/** The World where all actors of the simulator are */
protected World world;
/** Reports that are loaded for this simulation */ | protected Vector<Report> reports; | 0 |
bhatti/PlexRBAC | src/main/java/com/plexobject/rbac/service/impl/JAXBContextResolver.java | [
"@Entity\n@XmlRootElement\npublic class Domain extends PersistentObject implements Validatable,\n Identifiable<String> {\n public static final String DEFAULT_DOMAIN_NAME = Configuration\n .getInstance().getProperty(\"default.domain\", \"default\");\n\n @PrimaryKey\n private String id;\n private String description;\n // @SecondaryKey(relate = Relationship.MANY_TO_MANY, relatedEntity =\n // Subject.class, onRelatedEntityDelete = DeleteAction.NULLIFY)\n Set<String> ownerSubjectNames = new HashSet<String>();\n\n // for JPA\n Domain() {\n }\n\n public void setDescription(String description) {\n this.description = description;\n }\n\n public String getDescription() {\n return description;\n }\n\n public Domain(final String id, final String description) {\n setId(id);\n setDescription(description);\n }\n\n void setId(final String id) {\n if (GenericValidator.isBlankOrNull(id)) {\n throw new IllegalArgumentException(\"id is not specified\");\n }\n this.id = id;\n }\n\n @XmlElement\n public String getId() {\n return id;\n }\n\n public Set<String> getOwnerSubjectNames() {\n return new HashSet<String>(ownerSubjectNames);\n }\n\n public void setOwnerSubjectNames(final Set<String> ownerSubjectNames) {\n firePropertyChange(\"ownerSubjectNames\", this.ownerSubjectNames,\n ownerSubjectNames);\n\n this.ownerSubjectNames.clear();\n this.ownerSubjectNames.addAll(ownerSubjectNames);\n }\n\n public void addOwner(final String subjectName) {\n if (GenericValidator.isBlankOrNull(subjectName)) {\n throw new IllegalArgumentException(\"subjectName is not specified\");\n }\n Set<String> old = getOwnerSubjectNames();\n this.ownerSubjectNames.add(subjectName);\n firePropertyChange(\"ownerSubjectNames\", old, this.ownerSubjectNames);\n\n }\n\n public void addOwner(final Subject subject) {\n if (subject == null) {\n throw new IllegalArgumentException(\"subject is not specified\");\n }\n addOwner(subject.getId());\n }\n\n public void removeOwner(final Subject subject) {\n if (subject == null) {\n throw new IllegalArgumentException(\"subject is not specified\");\n }\n removeOwner(subject.getId());\n }\n\n public void removeOwner(final String subjectName) {\n if (GenericValidator.isBlankOrNull(subjectName)) {\n throw new IllegalArgumentException(\"subjectName is not specified\");\n }\n Set<String> old = getOwnerSubjectNames();\n this.ownerSubjectNames.remove(subjectName);\n firePropertyChange(\"ownerSubjectNames\", old, this.ownerSubjectNames);\n }\n\n /**\n * @see java.lang.Object#equals(Object)\n */\n @Override\n public boolean equals(Object object) {\n if (!(object instanceof Domain)) {\n return false;\n }\n Domain rhs = (Domain) object;\n return new EqualsBuilder().append(this.id, rhs.id).isEquals();\n }\n\n /**\n * @see java.lang.Object#hashCode()\n */\n @Override\n public int hashCode() {\n return new HashCodeBuilder(786529047, 1924536713).append(this.id)\n .toHashCode();\n }\n\n /**\n * @see java.lang.Object#toString()\n */\n @Override\n public String toString() {\n return new ToStringBuilder(this).append(\"name\", this.id).append(\n \"owners\", this.ownerSubjectNames).toString();\n }\n\n @Override\n public void validate() throws ValidationException {\n final Map<String, String> errorsByField = new HashMap<String, String>();\n if (GenericValidator.isBlankOrNull(id)) {\n errorsByField.put(\"name\", \"domain id is not specified\");\n }\n if (errorsByField.size() > 0) {\n throw new ValidationException(errorsByField);\n }\n }\n\n}",
"@Entity\n@XmlRootElement\npublic class Permission extends PersistentObject implements Validatable,\n Identifiable<Integer> {\n\n @PrimaryKey(sequence = \"permission_seq\")\n private Integer id;\n\n @SecondaryKey(relate = Relationship.MANY_TO_ONE)\n private String operation; // can be string or regular expression\n @SecondaryKey(relate = Relationship.MANY_TO_ONE)\n private String target;\n private String expression;\n\n @SecondaryKey(relate = Relationship.MANY_TO_MANY, relatedEntity = Role.class, onRelatedEntityDelete = DeleteAction.NULLIFY)\n Set<String> roleIds = new HashSet<String>();\n\n // for JPA\n Permission() {\n }\n\n public Permission(final String operation, final String target,\n final String expression) {\n setOperation(operation);\n setTarget(target);\n setExpression(expression);\n }\n\n void setId(Integer id) {\n this.id = id;\n }\n\n @XmlElement\n public Integer getId() {\n return id;\n }\n\n /**\n * The operation is action like read/write/update/delete or regular\n * expression\n * \n * @return\n */\n public String getOperation() {\n return operation;\n }\n\n /**\n * This method matches operation by equality or regular expression\n * \n * @param action\n * @return\n */\n public boolean implies(final String op, final String tgt) {\n if (GenericValidator.isBlankOrNull(op)) {\n return false;\n }\n if (GenericValidator.isBlankOrNull(tgt)) {\n return false;\n }\n\n return (operation.equalsIgnoreCase(op) || op.toLowerCase().matches(\n operation))\n && (target.equalsIgnoreCase(tgt) || tgt.toLowerCase().matches(\n target));\n }\n\n /**\n * The target is object that is being acted upon such as file, row in the\n * database\n * \n * @return\n */\n public String getTarget() {\n return target;\n }\n\n public void setOperation(String operation) {\n if (GenericValidator.isBlankOrNull(operation)) {\n throw new IllegalArgumentException(\"operation not specified\");\n }\n if (operation.equals(\"*\")) {\n operation = \".*\";\n }\n firePropertyChange(\"operation\", this.operation, operation);\n\n this.operation = operation.toLowerCase();\n }\n\n public void setTarget(String target) {\n if (GenericValidator.isBlankOrNull(target)) {\n throw new IllegalArgumentException(\"target not specified\");\n }\n firePropertyChange(\"target\", this.target, target);\n\n this.target = target;\n }\n\n /**\n * \n * @return\n */\n public String getExpression() {\n return expression;\n }\n\n public void setExpression(final String expression) {\n firePropertyChange(\"expression\", this.expression, expression);\n\n this.expression = expression;\n }\n\n @XmlTransient\n public Set<String> getRoleIds() {\n return new HashSet<String>(roleIds);\n }\n\n public void setRoleIds(Set<String> roleIds) {\n firePropertyChange(\"roleIds\", this.roleIds, roleIds);\n\n this.roleIds.clear();\n this.roleIds.addAll(roleIds);\n }\n\n public void addRole(Role role) {\n Set<String> old = getRoleIds();\n this.roleIds.add(role.getId());\n firePropertyChange(\"roleIds\", old, this.roleIds);\n }\n\n public void removeRole(Role role) {\n Set<String> old = getRoleIds();\n this.roleIds.remove(role.getId());\n firePropertyChange(\"roleIds\", old, this.roleIds);\n }\n\n /**\n * @see java.lang.Object#equals(Object)\n */\n @Override\n public boolean equals(Object object) {\n if (!(object instanceof Permission)) {\n return false;\n }\n Permission rhs = (Permission) object;\n return new EqualsBuilder().append(this.operation, rhs.operation)\n .append(this.target, rhs.target).append(this.expression,\n rhs.expression).isEquals();\n }\n\n /**\n * @see java.lang.Object#hashCode()\n */\n @Override\n public int hashCode() {\n return new HashCodeBuilder(786529047, 1924536713)\n .append(this.operation).append(this.target).toHashCode();\n }\n\n /**\n * @see java.lang.Object#toString()\n */\n @Override\n public String toString() {\n return new ToStringBuilder(this).append(\"id\", this.id).append(\n \"operation\", this.operation).append(\"target\", target).append(\n \"expression\", this.expression).append(\"roleIds\", this.roleIds)\n .toString();\n }\n\n @Override\n public void validate() throws ValidationException {\n final Map<String, String> errorsByField = new HashMap<String, String>();\n if (GenericValidator.isBlankOrNull(operation)) {\n errorsByField.put(\"operation\", \"operation is not specified\");\n }\n if (GenericValidator.isBlankOrNull(target)) {\n errorsByField.put(\"target\", \"target is not specified\");\n }\n if (errorsByField.size() > 0) {\n throw new ValidationException(errorsByField);\n }\n }\n}",
"@Entity\n@XmlRootElement\npublic class Role extends PersistentObject implements Validatable,\n Identifiable<String> {\n public static final Role ANONYMOUS = new Role(\"anonymous\");\n public static final Role SUPER_ADMIN = new Role(\"super_admin\");\n\n @PrimaryKey\n private String id;\n\n @SecondaryKey(relate = Relationship.MANY_TO_MANY, relatedEntity = Role.class)\n Set<String> parentIds = new HashSet<String>();\n\n @SecondaryKey(relate = Relationship.MANY_TO_MANY, relatedEntity = Subject.class, onRelatedEntityDelete = DeleteAction.NULLIFY)\n Set<String> subjectIds = new HashSet<String>();\n\n Role() {\n }\n\n public Role(String id) {\n this(id, (Role) null);\n }\n\n public Role(String id, Role parent) {\n setId(id);\n if (parent != null) {\n addParentId(parent.getId());\n } else if (ANONYMOUS != null) {\n addParentId(ANONYMOUS.getId());\n }\n }\n\n public Role(String id, Set<String> parentIds) {\n setId(id);\n if (parentIds != null && parentIds.size() > 0) {\n setParentIds(parentIds);\n } else {\n addParentId(ANONYMOUS.getId());\n }\n }\n\n @XmlElement\n public String getId() {\n return id;\n }\n\n void setId(String id) {\n this.id = id;\n }\n\n @XmlTransient\n public Set<String> getSubjectIds() {\n return new HashSet<String>(subjectIds);\n }\n\n public void setSubjectIds(Set<String> subjectIds) {\n firePropertyChange(\"subjectIds\", this.subjectIds, subjectIds);\n\n this.subjectIds.clear();\n this.subjectIds.addAll(subjectIds);\n }\n\n public void addSubject(String subjectName) {\n Set<String> old = getSubjectIds();\n this.subjectIds.add(subjectName);\n firePropertyChange(\"subjectIds\", old, this.subjectIds);\n\n }\n\n public void removeSubject(String subjectName) {\n Set<String> old = getSubjectIds();\n this.subjectIds.remove(subjectName);\n firePropertyChange(\"subjectIds\", old, this.subjectIds);\n }\n\n public void addSubject(Subject subject) {\n addSubject(subject.getId());\n }\n\n public void removeSubject(Subject subject) {\n removeSubject(subject.getId());\n }\n\n @XmlElement\n public Set<String> getParentIds() {\n return new HashSet<String>(parentIds);\n }\n\n public boolean hasParentIds() {\n return parentIds != null && parentIds.size() > 0;\n }\n\n public void setParentIds(Set<String> parentIds) {\n firePropertyChange(\"parentIds\", this.parentIds, parentIds);\n\n this.parentIds.clear();\n this.parentIds.addAll(parentIds);\n }\n\n public void addParentId(String parentId) {\n Set<String> old = getParentIds();\n this.parentIds.add(parentId);\n firePropertyChange(\"parentIds\", old, this.parentIds);\n\n }\n\n public void removeParentId(String parentId) {\n Set<String> old = getParentIds();\n this.parentIds.remove(parentId);\n firePropertyChange(\"parentIds\", old, this.parentIds);\n }\n\n public void addParentId(Role parent) {\n addParentId(parent.getId());\n }\n\n public void removeParentId(Role parent) {\n removeParentId(parent.getId());\n }\n\n /**\n * @see java.lang.Object#equals(Object)\n */\n @Override\n public boolean equals(Object object) {\n if (!(object instanceof Role)) {\n return false;\n }\n Role rhs = (Role) object;\n return new EqualsBuilder().append(this.id, rhs.id).isEquals();\n }\n\n /**\n * @see java.lang.Object#hashCode()\n */\n @Override\n public int hashCode() {\n return new HashCodeBuilder(786529047, 1924536713).append(this.id)\n .toHashCode();\n }\n\n /**\n * @see java.lang.Object#toString()\n */\n @Override\n public String toString() {\n return new ToStringBuilder(this).append(\"rolename\", this.id).append(\n \"subjectIds\", this.subjectIds).append(\"parentIds\",\n this.parentIds).toString();\n }\n\n @Override\n public void validate() throws ValidationException {\n final Map<String, String> errorsByField = new HashMap<String, String>();\n if (GenericValidator.isBlankOrNull(id)) {\n errorsByField.put(\"id\", \"rolename is not specified\");\n }\n if ((parentIds == null || parentIds.size() == 0)\n && !ANONYMOUS.getId().equals(id)) {\n addParentId(ANONYMOUS.getId());\n }\n if (errorsByField.size() > 0) {\n throw new ValidationException(errorsByField);\n }\n }\n\n}",
"@Entity\n@XmlRootElement\npublic class Subject extends PersistentObject implements Validatable,\n Identifiable<String> {\n public static final Subject SUPER_ADMIN = new Subject(Configuration\n .getInstance()\n .getProperty(\"super_admin_subjectName\", \"super_admin\"),\n PasswordUtils.getHash(Configuration.getInstance().getProperty(\n \"super_admin_credentials\", \"changeme\")));\n @PrimaryKey\n private String id;\n private String credentials;\n\n // for JPA\n Subject() {\n }\n\n @XmlElement\n public String getId() {\n return id;\n }\n\n public void setId(String id) {\n if (GenericValidator.isBlankOrNull(id)) {\n throw new IllegalArgumentException(\"subjectName not specified\");\n }\n\n this.id = id;\n }\n\n public Subject(final String id, final String credentials) {\n setId(id);\n setCredentials(credentials);\n }\n\n public void setCredentials(String credentials) {\n this.credentials = credentials;\n }\n\n public String getCredentials() {\n return credentials;\n }\n\n /**\n * @see java.lang.Object#equals(Object)\n */\n @Override\n public boolean equals(Object object) {\n if (!(object instanceof Subject)) {\n return false;\n }\n Subject rhs = (Subject) object;\n return new EqualsBuilder().append(this.id, rhs.id).isEquals();\n }\n\n /**\n * @see java.lang.Object#hashCode()\n */\n @Override\n public int hashCode() {\n return new HashCodeBuilder(786529047, 1924536713).append(this.id)\n .toHashCode();\n }\n\n /**\n * @see java.lang.Object#toString()\n */\n @Override\n public String toString() {\n return new ToStringBuilder(this).append(\"subjectName\", this.id)\n .toString();\n }\n\n @Override\n public void validate() throws ValidationException {\n final Map<String, String> errorsByField = new HashMap<String, String>();\n if (GenericValidator.isBlankOrNull(id)) {\n errorsByField.put(\"id\", \"subjectName is not specified\");\n }\n\n if (errorsByField.size() > 0) {\n throw new ValidationException(errorsByField);\n }\n }\n\n}",
"@XmlRootElement\npublic class PagedList<T, ID> implements List<T> {\n private static final long serialVersionUID = 1L;\n private final List<T> list;\n private final ID firstKey;\n private final ID lastKey;\n private final int limit;\n private final boolean more;\n\n PagedList() {\n this.list = null;\n this.firstKey = null;\n this.lastKey = null;\n this.limit = 0;\n this.more = false;\n }\n\n public PagedList(final List<T> list) {\n this(list, null, null, list.size(), false);\n }\n\n public PagedList(final List<T> list, final ID start, final ID end,\n final int limit, final boolean hasMore) {\n this.list = list;\n this.firstKey = start;\n this.lastKey = end;\n this.limit = limit;\n this.more = hasMore;\n }\n\n /**\n * @return the start of the key\n */\n @XmlElement\n public ID getFirstKey() {\n return firstKey;\n }\n\n @XmlElement\n public Object[] getItems() {\n return toArray();\n }\n\n /**\n * @return the limit\n */\n @XmlElement\n public int getLimit() {\n return limit;\n }\n\n /**\n * @return the last key that will be passed to the next request\n */\n @XmlElement\n public ID getLastKey() {\n return lastKey;\n }\n\n /**\n * @return the hasMore\n */\n public boolean hasMore() {\n return more;\n }\n\n public static <T, ID> PagedList<T, ID> emptyList() {\n return new PagedList<T, ID>(Collections.<T> emptyList(), null, null, 0,\n false);\n }\n\n public static <T, ID> PagedList<T, ID> asList(T... args) {\n return new PagedList<T, ID>(Arrays.<T> asList(args));\n }\n\n @Override\n public boolean add(T e) {\n throw new UnsupportedOperationException();\n }\n\n @Override\n public void add(int index, T element) {\n throw new UnsupportedOperationException();\n\n }\n\n @Override\n public boolean addAll(Collection<? extends T> c) {\n throw new UnsupportedOperationException();\n }\n\n @Override\n public boolean addAll(int index, Collection<? extends T> c) {\n throw new UnsupportedOperationException();\n }\n\n @Override\n public void clear() {\n throw new UnsupportedOperationException();\n\n }\n\n @Override\n public boolean contains(Object o) {\n return list.contains(o);\n }\n\n @Override\n public boolean containsAll(Collection<?> c) {\n return list.containsAll(c);\n }\n\n @Override\n public T get(int index) {\n return list.get(index);\n }\n\n @Override\n public int indexOf(Object o) {\n return list.indexOf(o);\n }\n\n @Override\n public boolean isEmpty() {\n return list.isEmpty();\n }\n\n @Override\n public Iterator<T> iterator() {\n return list.iterator();\n }\n\n @Override\n public int lastIndexOf(Object o) {\n return list.lastIndexOf(o);\n }\n\n @Override\n public ListIterator<T> listIterator() {\n return list.listIterator();\n }\n\n @Override\n public ListIterator<T> listIterator(int index) {\n return list.listIterator(index);\n }\n\n @Override\n public boolean remove(Object o) {\n return list.remove(o);\n }\n\n @Override\n public T remove(int index) {\n return list.remove(index);\n }\n\n @Override\n public boolean removeAll(Collection<?> c) {\n throw new UnsupportedOperationException();\n }\n\n @Override\n public boolean retainAll(Collection<?> c) {\n throw new UnsupportedOperationException();\n }\n\n @Override\n public T set(int index, T element) {\n throw new UnsupportedOperationException();\n }\n\n @Override\n public int size() {\n return list.size();\n }\n\n @Override\n public List<T> subList(int fromIndex, int toIndex) {\n return list.subList(fromIndex, toIndex);\n }\n\n @SuppressWarnings(\"hiding\")\n @Override\n public <T> T[] toArray(T[] a) {\n return list.toArray(a);\n }\n\n @Override\n public String toString() {\n return list.toString();\n }\n\n @Override\n public Object[] toArray() {\n return list.toArray();\n }\n}"
] | import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;
import javax.xml.bind.JAXBContext;
import org.apache.log4j.Logger;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import com.plexobject.rbac.domain.Domain;
import com.plexobject.rbac.domain.Permission;
import com.plexobject.rbac.domain.Role;
import com.plexobject.rbac.domain.Subject;
import com.plexobject.rbac.repository.PagedList;
import com.sun.jersey.api.json.JSONConfiguration;
import com.sun.jersey.api.json.JSONJAXBContext;
import com.sun.jersey.api.json.JSONConfiguration.MappedBuilder; | package com.plexobject.rbac.service.impl;
@Path("/jsonFormats")
@Component("jaxbContextResolver")
@Scope("singleton")
@Provider
@Produces(MediaType.APPLICATION_JSON)
public class JAXBContextResolver implements ContextResolver<JAXBContext> {
private static final Logger LOGGER = Logger
.getLogger(JAXBContextResolver.class);
private static final Class<?>[] TYPES = new java.lang.Class[] { | PagedList.class, Domain.class, Permission.class, Role.class, | 4 |
tteguayco/JITRAX | src/es/ull/etsii/jitrax/analysis/dsl/DatabaseEvalVisitor.java | [
"public class Database {\n\n\tprivate String name;\n\tprivate ArrayList<Table> tables;\n\tprivate DbmsDriver dbmsDriver;\n\t\n\t/**\n\t * @param name name for the database.\n\t */\n\tpublic Database(String aName) {\n\t\tname = aName;\n\t\ttables = new ArrayList<Table>();\n\t}\n\t\n\tpublic Database(String aName, ArrayList<Table> tableList) {\n\t\tname = aName;\n\t\ttables = tableList;\n\t}\n\t\n\tpublic void addTable(Table newTable) throws DuplicateTableException {\n\t\tif (containsTable(newTable.getName())) {\n\t\t\tthrow new DuplicateTableException();\n\t\t}\n\t\t\n\t\tgetTables().add(newTable);\n\t}\n\t\n\tpublic void removeTable(Table tableToRemove) {\n\t\tfor (int i = 0; i < tables.size(); i++) {\n\t\t\tif (tables.get(i).getName().equalsIgnoreCase(tableToRemove.getName())) {\n\t\t\t\ttables.remove(i);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic String[] getTablesNames() {\n\t\tString[] tablesNames = new String[getTables().size()];\n\t\t\n\t\tfor (int i = 0; i < getTables().size(); i++) {\n\t\t\ttablesNames[i] = getTables().get(i).getName();\n\t\t}\n\t\t\n\t\treturn tablesNames;\n\t}\n\t\n\t/**\n\t * Ask if the database contains the specified table \n\t * (case sensitive way).\n\t * \n\t * @param tableName\n\t * @return\n\t */\n\tpublic boolean containsTable(String tableName) {\n\t\tfor (int i = 0; i < getTables().size(); i++) {\n\t\t\tif (getTables().get(i).getName().equalsIgnoreCase(tableName)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn false;\n\t}\n\t\n\t/**\n\t * Returns the attribute which matches the name.\n\t * @param attrName\n\t * @return\n\t */\n\tpublic Attribute getAttributeByName(String attrName) {\n\t\tfor (int i = 0; i < getTables().size(); i++) {\n\t\t\tfor (int j = 0; j < getTables().get(i).getAttributes().size(); j++) {\n\t\t\t\tAttribute auxAttr = getTables().get(i).getAttributes().get(j);\n\t\t\t\tif (attrName.equalsIgnoreCase(auxAttr.getName())) {\n\t\t\t\t\treturn auxAttr;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn null;\n\t}\n\t\n\tpublic String toString() {\n\t\treturn getName();\n\t}\n\t\n\tpublic String toDSL() {\n\t\tString toString = \"\";\n\t\t\n\t\ttoString += \"DATABASE \" + getName() + \";\\n\";\n\t\t\n\t\tfor (int i = 0; i < getTables().size(); i++) {\n\t\t\ttoString += \"\\nTABLE \" + getTables().get(i).getName() + \" (\";\n\t\t\t\n\t\t\t// Attributes with domains\n\t\t\tfor (int j = 0; j < getTables().get(i).getAttributes().size(); j++) {\n\t\t\t\ttoString += getTables().get(i).getAttributes().get(j).getName() + \": \" +\n\t\t\t\t\t\tgetTables().get(i).getAttributes().get(j).getDataType();\n\t\t\t\t\n\t\t\t\t// Add semicolon\n\t\t\t\tif (j < getTables().get(i).getAttributes().size() - 1) {\n\t\t\t\t\ttoString += \",\\n\";\n\t\t\t\t} \n\t\t\t\t\n\t\t\t\telse {\n\t\t\t\t\ttoString += \")\\n\";\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\ttoString += \"=>\\n\";\n\t\t\t\n\t\t\t// Rows\n\t\t\tfor (int j = 0; j < getTables().get(i).getRows().size(); j++) {\n\t\t\t\ttoString += \"(\";\n\t\t\t\tfor (int k = 0; k < getTables().get(i).getRows().get(j).size(); k++) {\n\t\t\t\t\tString datum = getTables().get(i).getRows().get(j).getData().get(k).getStringValue();\n\t\t\t\t\ttoString += datum;\n\t\t\t\t\t\n\t\t\t\t\tif (k < getTables().get(i).getRows().get(j).size() - 1) {\n\t\t\t\t\t\ttoString += \",\";\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\telse {\n\t\t\t\t\t\ttoString += \");\\n\";\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn toString;\n\t}\n\t\n\t/**\n\t * Returns the table whose name matches the specified.\n\t * \n\t * @param tableName\n\t * @return\n\t */\n\tpublic Table getTableByName(String tableName) {\n\t\tfor (int i = 0; i < getTables().size(); i++) {\n\t\t\tif (tableName.equalsIgnoreCase(getTables().get(i).getName())) {\n\t\t\t\treturn getTables().get(i);\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn null;\n\t}\n\t\n\t/**\n\t * Returns the number of tables the DB has.\n\t * @return\n\t */\n\tpublic int getNumOfTables() {\n\t\treturn getTables().size();\n\t}\n\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\n\tpublic ArrayList<Table> getTables() {\n\t\treturn tables;\n\t}\n\n\tpublic void setTables(ArrayList<Table> tables) {\n\t\tthis.tables = tables;\n\t}\n\n\tpublic DbmsDriver getDbmsDriver() {\n\t\treturn dbmsDriver;\n\t}\n\n\tpublic void setDbmsDriver(DbmsDriver dbmsDriver) {\n\t\tthis.dbmsDriver = dbmsDriver;\n\t}\n}",
"public class Datum {\n\tprivate String stringValue;\n\t\n\tpublic Datum(String aValue) {\n\t\tstringValue = aValue;\n\t}\n\t\n\tpublic boolean equals(Datum anOther) {\n\t\tif (anOther.getStringValue().equals(this.getStringValue())) {\n\t\t\treturn true;\n\t\t}\n\t\t\n\t\treturn false;\n\t}\n\t\n\tpublic String toString() {\n\t\tString toString = \"\";\n\t\ttoString += getStringValue();\n\t\t\n\t\treturn toString;\n\t}\n\t\n\tpublic String getStringValue() {\n\t\treturn stringValue;\n\t}\n\n\tpublic void setStringValue(String stringValue) {\n\t\tthis.stringValue = stringValue;\n\t}\n}",
"public class Attribute {\n\n\tprivate String name;\n\tprivate DataType dataType;\n\t\n\tpublic Attribute(String aName, DataType aDataType) {\n\t\tname = aName;\n\t\tdataType = aDataType;\n\t}\n\t\n\tpublic boolean equals(Object object) {\n\t\tif (object != null && object instanceof Attribute) {\n\t\t\tAttribute anotherAttr = (Attribute) object;\n\t\t\t\n\t\t\t// Comparing names and domains (data types)\n\t\t\tif (this.getName().equalsIgnoreCase(anotherAttr.getName())) {\n\t\t\t\tif (this.getDataType() == anotherAttr.getDataType()) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn false;\n\t}\n\t\n\tpublic int hashCode() {\n\t\treturn getName().hashCode() * getDataType().hashCode();\n\t}\n\t\n\tpublic String toString() {\n\t\tString toString = \"\";\t\n\t\ttoString += getName() + \" (\" + getDataType() + \")\";\n\t\n\t\treturn toString;\n\t}\n\t\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\n\tpublic DataType getDataType() {\n\t\treturn dataType;\n\t}\n\n\tpublic void setDataType(DataType dataType) {\n\t\tthis.dataType = dataType;\n\t}\n}",
"public class Row {\n\t\n\tprivate ArrayList<Attribute> tableAttributes;\n\tprivate ArrayList<Datum> data;\n\t\n\tpublic Row(ArrayList<Attribute> attributes, ArrayList<Datum> rowData) {\n\t\ttableAttributes = attributes;\n\t\tdata = rowData;\n\t}\n\n\t/**\n\t * The size of a row is its number of attributes or column.\n\t * @return\n\t */\n\tpublic int size() {\n\t\treturn getData().size();\n\t}\n\t\n\tpublic boolean equals(Row anOther) {\n\t\tif (anOther.size() != this.size()) {\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\t// Comparing Data\n\t\tfor (int i = 0; i < anOther.size(); i++) {\n\t\t\tif (!anOther.getDatum(i).equals(this.getDatum(i))) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn true;\n\t}\n\t\n\tpublic Datum getDatum(int index) {\n\t\treturn getData().get(index);\n\t}\n\t\n\tpublic String toString() {\n\t\tString toString = \"\";\n\t\t\n\t\tfor (int i = 0; i < getData().size(); i++) {\n\t\t\ttoString += getData().get(i).getStringValue() + \",\";\n\t\t}\n\t\t\n\t\treturn toString;\n\t}\n\t\n\tpublic ArrayList<Attribute> getTableAttributes() {\n\t\treturn tableAttributes;\n\t}\n\n\tpublic void setTableAttributes(ArrayList<Attribute> tableAttributes) {\n\t\tthis.tableAttributes = tableAttributes;\n\t}\n\n\tpublic ArrayList<Datum> getData() {\n\t\treturn data;\n\t}\n\n\tpublic void setData(ArrayList<Datum> data) {\n\t\tthis.data = data;\n\t}\n}",
"public class Table {\n\tprivate String name;\n\tprivate ArrayList<Attribute> attributes;\n\tprivate LinkedHashMap<String, Integer> attributesNames;\n\tprivate ArrayList<Row> rows;\n\t\n\tpublic Table(String aName, ArrayList<Attribute> attrList) {\n\t\tname = aName;\n\t\tattributes = attrList;\n\t\tattributesNames = new LinkedHashMap<String, Integer>();\n\t\trows = new ArrayList<Row>();\n\t}\n\n\t/**\n\t * Returns true if an attribute already exists.\n\t * @param anAttribute\n\t * @return\n\t */\n\tprivate boolean attributeExists(String attributeName) {\n\t\tif (getAttributesNames().containsKey(attributeName)) {\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\tpublic boolean attributeExists(String attrName, DataType attrDataType) {\n\t\tfor (int i = 0; i < getAttributes().size(); i++) {\n\t\t\tif (getAttributes().get(i).getName().equalsIgnoreCase(attrName) \n\t\t\t\t\t&& getAttributes().get(i).getDataType() == attrDataType) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn false;\n\t}\n\t\n\tpublic Attribute getAttributeByName(String attrName) {\n\t\tfor (int i = 0; i < getAttributes().size(); i++) {\n\t\t\tif (getAttributes().get(i).getName().equalsIgnoreCase(attrName)) {\n\t\t\t\treturn getAttributes().get(i);\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn null;\n\t}\n\t\n\tpublic Row getRowAt(int rowIndex) {\n\t\treturn rows.get(rowIndex);\n\t}\n\t\n\t/**\n\t * Returns the names of the columns of this table.\n\t */\n\tpublic String[] getColumnsNames() {\n\t\tString[] columnNames = new String[getAttributes().size()];\n\t\t\n\t\tfor (int i = 0; i < getAttributes().size(); i++) {\n\t\t\tcolumnNames[i] = getAttributes().get(i).getName();\n\t\t}\n\t\t\n\t\treturn columnNames;\n\t}\n\t\n\tpublic String[][] getRowsData() {\n\t\tString[][] rowsData = new String[getRows().size()][getAttributes().size()];\n\t\t\n\t\tfor (int i = 0; i < getRows().size(); i++) {\n\t\t\tfor (int j = 0; j < getRows().get(i).size(); j++) {\n\t\t\t\trowsData[i][j] = getRows().get(i).getData().get(j).getStringValue();\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn rowsData;\n\t}\n\t\n\t/**\n\t * The size of a table will be its number of attributes.\n\t * @return\n\t */\n\tpublic int getNumOfColumns() {\n\t\treturn getAttributes().size();\n\t}\n\t\n\tpublic int getNumOfRows() {\n\t\treturn getRows().size();\n\t}\n\t\n\t/**\n\t * Adds a new row or tuple to this table.\n\t * @return\n\t */\n\tpublic void addRow(ArrayList<Datum> newRowData) {\n\t\tRow newRow = new Row(getAttributes(), newRowData);\n\t\tgetRows().add(newRow);\n\t}\n\t\n\tpublic void addRow(Row newRow) {\n\t\tgetRows().add(newRow);\n\t}\n\t\n\tpublic void addRowIfNotExist(Row newRow) {\n\t\tfor (int i = 0; i < getRows().size(); i++) {\n\t\t\tif (getRows().get(i).equals(newRow)) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\t\n\t\taddRow(newRow);\n\t}\n\t\n\tpublic void removeRowByIndex(int rowIndex) {\n\t\tgetRows().remove(rowIndex);\n\t}\n\t\n\t/**\n\t * Adds a new attribute to the table. Returns false if couldn't do it\n\t * because the attribute already exists.\n\t * @param attributeName\n\t * @param attributeDatatype\n\t * @return\n\t */\n\tpublic boolean addAttribute(String attributeName, DataType attributeDatatype) {\n\t\tif (!attributeExists(attributeName)) {\n\t\t\tAttribute newAttribute = new Attribute(attributeName, attributeDatatype);\n\t\t\tgetAttributes().add(newAttribute);\n\t\t\treturn true;\n\t\t\t\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\t\n\tpublic String toString() {\n\t\tString toString = \"\";\n\t\t\n\t\ttoString += \"TABLE \" + getName() + \"\\n\";\n\t\ttoString += \"ATTRIBUTES\\n\";\n\t\tfor (int i = 0; i < getAttributes().size(); i++) {\n\t\t\ttoString += getAttributes().get(i).toString() + \"\\n\";\n\t\t}\n\t\t\n\t\ttoString += \"DATA\\n\";\n\t\tfor (int i = 0; i < getRows().size(); i++) {\n\t\t\ttoString += getRows().get(i).toString() + \"\\n\";\n\t\t}\n\t\t\n\t\treturn toString;\n\t}\n\t\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\n\tpublic ArrayList<Attribute> getAttributes() {\n\t\treturn attributes;\n\t}\n\n\tpublic void setAttributes(ArrayList<Attribute> attributes) {\n\t\tthis.attributes = attributes;\n\t}\n\n\tpublic HashMap<String, Integer> getAttributesNames() {\n\t\treturn attributesNames;\n\t}\n\n\tpublic void setAttributesNames(LinkedHashMap<String, Integer> attributesNames) {\n\t\tthis.attributesNames = attributesNames;\n\t}\n\n\tpublic ArrayList<Row> getRows() {\n\t\treturn rows;\n\t}\n\n\tpublic void setRows(ArrayList<Row> rows) {\n\t\tthis.rows = rows;\n\t}\n}",
"public enum DataType {\n\tCHAR, STRING, INT, FLOAT, DATE;\n\t\n\tpublic String toString() {\n\t\tswitch(this) {\n\t\t\tcase CHAR: return \"Char\";\n\t\t\tcase STRING: return \"String\";\n\t\t\tcase INT: return \"Integer\";\n\t\t\tcase FLOAT: return \"Float\";\n\t\t\tcase DATE: return \"Date\";\n\t\t\tdefault: return \"\";\n\t\t}\n\t}\n}",
"public class DuplicateTableException extends Exception {\n\tprivate static final String DEFAULT_MESSAGE = \"DuplicatePrimaryKeyException was thrown\";\n\t\n\tpublic DuplicateTableException() {\n\t\tsuper(DEFAULT_MESSAGE);\n\t}\n\t\n\tpublic DuplicateTableException(String message) {\n\t\tsuper(message);\n\t}\n}"
] | import es.ull.etsii.jitrax.adt.Database;
import es.ull.etsii.jitrax.adt.Datum;
import es.ull.etsii.jitrax.adt.Attribute;
import es.ull.etsii.jitrax.adt.Row;
import es.ull.etsii.jitrax.adt.Table;
import es.ull.etsii.jitrax.adt.DataType;
import es.ull.etsii.jitrax.exceptions.DuplicateTableException;
import java.util.ArrayList; | package es.ull.etsii.jitrax.analysis.dsl;
/**
* This class allows to semantically analyze an expression which describes
* a database specification (using a DSL). It has to be syntactically correct.
*/
public class DatabaseEvalVisitor extends DatabaseBaseVisitor<Object> {
private Database database; | private ArrayList<Attribute> auxAttributeList; | 2 |
sherlok/sherlok | src/test/java/org/sherlok/mappings/BundleDefTest.java | [
"public static <T> T read(File f, Class<T> clazz) throws SherlokException {\n try {\n return MAPPER.readValue(new FileInputStream(f), clazz);\n\n } catch (FileNotFoundException io) {\n throw new SherlokException()\n .setMessage(\n clazz.getSimpleName().replaceAll(\"Def$\", \"\")\n + \" does not exist.\")\n .setObject(f.getName()).setDetails(io.toString());\n\n } catch (UnrecognizedPropertyException upe) {\n throw new SherlokException()\n .setMessage(\n \"Unrecognized field \\\"\" + upe.getPropertyName()\n + \"\\\"\")\n .setObject(\n clazz.getSimpleName().replaceAll(\"Def$\", \"\") + \" \"\n + f.getName())\n .setDetails(upe.getMessageSuffix());\n\n } catch (JsonMappingException jme) {\n\n StringBuilder sb = new StringBuilder();\n sb.append(\"cannot read \");\n jme.getPathReference(sb);\n sb.append(\" in '\" + f.getName() + \"': \");\n sb.append(\" \" + jme.getOriginalMessage());\n\n throw new SherlokException().setMessage(sb.toString().replaceAll(\n \"org\\\\.sherlok\\\\.mappings\\\\.\\\\w+Def\\\\[\", \"[\"));\n\n } catch (JsonParseException jpe) {\n\n throw new SherlokException()\n .setMessage(\n \"Could not parse JSON object of type \"\n + clazz.getSimpleName())\n .setObject(f.getName().replaceAll(\"Def$\", \"\"))\n .setDetails(jpe.getMessage());\n\n } catch (Exception e) {\n throw new SherlokException().setMessage(e.getMessage())\n .setObject(f.getName().replaceAll(\"Def$\", \"\"))\n .setDetails(e.getStackTrace());\n }\n}",
"public static <E> HashSet<E> set() {\n return new HashSet<E>();\n}",
"public class FileBased {\n\n /* package */static final String CONFIG_DIR_PATH = \"config/\";\n public static final String RUNTIME_DIR_PATH = \"runtime/\";\n\n public static final String BUNDLES_PATH = CONFIG_DIR_PATH\n + SherlokServer.BUNDLES + \"/\";\n public static final String PIPELINES_PATH = CONFIG_DIR_PATH\n + SherlokServer.PIPELINES + \"/\";\n public static final String RUTA_RESOURCES_PATH = CONFIG_DIR_PATH\n + SherlokServer.RUTA_RESOURCES + \"/\";\n public static final String PIPELINE_CACHE_PATH = RUNTIME_DIR_PATH\n + \"pipelines/\";\n public static final String ENGINE_CACHE_PATH = RUNTIME_DIR_PATH\n + \"engines/\";\n\n /** 100Mb, in bytes */\n static final long MAX_UPLOAD_SIZE = 100 * 1000000l;\n\n /** JSON serializer for mapped objects. */\n private static final ObjectMapper MAPPER = new ObjectMapper(\n new JsonFactory());\n static {\n MAPPER.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true);\n MAPPER.enable(SerializationFeature.INDENT_OUTPUT);\n // important for EngineDef.properties\n MAPPER.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);\n }\n\n /** path convention: BUNDLE_PATH{name}_{version}.json */\n private static String getBundlePath(String name, String version) {\n return BUNDLES_PATH + name + \"_\" + version + \".json\";\n }\n\n /** path convention: PIPELINES_PATH{domain}/{name}_{version}.json */\n private static String getPipelinePath(String domain, String name,\n String version) {\n return PIPELINES_PATH + domain + \"/\" + name + \"_\" + version + \".json\";\n }\n\n /**\n * PUTs (writes) this bundle to disk.\n * \n * @param bundleStr\n * a {@link BundleDef} as a String\n * @return the {@link BundleDef}, for convenience\n */\n public static BundleDef putBundle(String bundleStr) throws SherlokException {\n try {\n BundleDef b = MAPPER.readValue(bundleStr, BundleDef.class);\n writeBundle(b);\n return b;\n } catch (Exception e) {\n throw new SherlokException(e.getMessage());// FIXME validate better\n }\n }\n\n /**\n * PUTs (writes) this pipeline to disk. First, validates it.\n * \n * @param pipelineStr\n * a {@link PipelineDef} as a String\n * @param engineIds\n * the engine ids of the controller, used to\n * {@link PipelineDef#validateEngines(Set)}.\n * @return the {@link PipelineDef}, for convenience\n */\n public static PipelineDef putPipeline(String pipelineStr,\n Set<String> engineIds) throws SherlokException {\n try {\n PipelineDef p = parsePipeline(pipelineStr);\n p.validateEngines(engineIds);\n writePipeline(p);\n return p;\n } catch (Exception e) {\n throw new SherlokException(e.getMessage());// FIXME validate better\n }\n }\n\n /**\n * PUTs (writes) this resource to disk.\n * \n * @param path\n * the path where to write this resource to\n * @param part\n * holds the resource file itself\n */\n public static void putResource(String path, Part part)\n throws SherlokException {\n\n validateArgument(!path.contains(\"..\"), \"path cannot contain '..'\");\n validateArgument(part.getSize() < MAX_UPLOAD_SIZE,\n \"file too large, max allowed \" + MAX_UPLOAD_SIZE + \" bytes\");\n validateArgument(part.getSize() > 0, \"file is empty\");\n\n File outFile = new File(RUTA_RESOURCES_PATH, path);\n outFile.getParentFile().mkdirs();\n try {\n FileUtils.copyInputStreamToFile(part.getInputStream(), outFile);\n } catch (IOException e) {\n new SherlokException(\"could not upload file to\", path);\n }\n }\n\n /** Used e.g. to test a pipeline without writing it out */\n public static PipelineDef parsePipeline(String pipelineStr)\n throws JsonParseException, JsonMappingException, IOException {\n return MAPPER.readValue(pipelineStr, PipelineDef.class);\n }\n\n /**\n * Writes a {@link Def} to a file<br/>\n * Note: this should be private, but is used in tests...\n * \n * @param f\n * the file to write to\n * @param def\n * the object to write\n */\n public static void write(File f, Def def) throws SherlokException {\n try {\n MAPPER.writeValue(f, def);\n } catch (Exception e) {\n throw new SherlokException(\"could not write \"\n + def.getClass().getSimpleName(), def.toString())\n .setDetails(e.getStackTrace());\n }\n }\n\n /** Writes this object as String, using Jackson's {@link ObjectMapper} */\n public static String writeAsString(Object obj)\n throws JsonProcessingException {\n return MAPPER.writeValueAsString(obj);\n }\n\n private static void writeBundle(BundleDef b) throws SherlokException {\n b.validate(b.toString());\n File bFile = new File(getBundlePath(b.getName(), b.getVersion()));\n bFile.getParentFile().mkdirs();\n write(bFile, b);\n }\n\n private static void writePipeline(PipelineDef p) throws SherlokException {\n p.validate(p.toString());\n File defFile = new File(getPipelinePath(p.getDomain(), p.getName(),\n p.getVersion()));\n defFile.getParentFile().mkdirs();\n write(defFile, p);\n }\n\n /**\n * Read a JSON-serialized object from file and parse it back to an object.\n * Performs extensive error-catching to provide useful information in case\n * of error.\n * \n * @param f\n * the file to read\n * @param clazz\n * the class to cast this object into\n * @return the parsed object\n * @throws SherlokException\n * if the object cannot be found or parsed\n */\n public static <T> T read(File f, Class<T> clazz) throws SherlokException {\n try {\n return MAPPER.readValue(new FileInputStream(f), clazz);\n\n } catch (FileNotFoundException io) {\n throw new SherlokException()\n .setMessage(\n clazz.getSimpleName().replaceAll(\"Def$\", \"\")\n + \" does not exist.\")\n .setObject(f.getName()).setDetails(io.toString());\n\n } catch (UnrecognizedPropertyException upe) {\n throw new SherlokException()\n .setMessage(\n \"Unrecognized field \\\"\" + upe.getPropertyName()\n + \"\\\"\")\n .setObject(\n clazz.getSimpleName().replaceAll(\"Def$\", \"\") + \" \"\n + f.getName())\n .setDetails(upe.getMessageSuffix());\n\n } catch (JsonMappingException jme) {\n\n StringBuilder sb = new StringBuilder();\n sb.append(\"cannot read \");\n jme.getPathReference(sb);\n sb.append(\" in '\" + f.getName() + \"': \");\n sb.append(\" \" + jme.getOriginalMessage());\n\n throw new SherlokException().setMessage(sb.toString().replaceAll(\n \"org\\\\.sherlok\\\\.mappings\\\\.\\\\w+Def\\\\[\", \"[\"));\n\n } catch (JsonParseException jpe) {\n\n throw new SherlokException()\n .setMessage(\n \"Could not parse JSON object of type \"\n + clazz.getSimpleName())\n .setObject(f.getName().replaceAll(\"Def$\", \"\"))\n .setDetails(jpe.getMessage());\n\n } catch (Exception e) {\n throw new SherlokException().setMessage(e.getMessage())\n .setObject(f.getName().replaceAll(\"Def$\", \"\"))\n .setDetails(e.getStackTrace());\n }\n }\n\n /** @return all {@link BundleDef}s */\n public static Collection<BundleDef> allBundleDefs() throws SherlokException {\n List<BundleDef> ret = list();\n File bPath = new File(BUNDLES_PATH);\n validateArgument(bPath.exists(), \"bundles directory does not exist\",\n BUNDLES_PATH, \"make sure path exists (currently resolves to '\"\n + bPath.getAbsolutePath() + \"')\");\n for (File bf : newArrayList(iterateFiles(bPath,\n new String[] { \"json\" }, true))) {\n ret.add(read(bf, BundleDef.class));\n }\n return ret;\n }\n\n /** @return all {@link PipelineDef}s */\n public static Collection<PipelineDef> allPipelineDefs()\n throws SherlokException {\n List<PipelineDef> ret = list();\n File pPath = new File(PIPELINES_PATH);\n validateArgument(\n pPath.exists(),\n \"pipelines directory does not exist\",\n PIPELINES_PATH,\n \"make sure directory exists (currently resolves to '\"\n + pPath.getAbsolutePath() + \"')\");\n for (File bf : newArrayList(iterateFiles(pPath,\n new String[] { \"json\" }, true))) {\n ret.add(FileBased.read(bf, PipelineDef.class));\n }\n return ret;\n }\n\n /** @return a list of the paths of all resources */\n public static Collection<String> allResources() throws SherlokException {\n try {\n List<String> resources = list();\n File dir = new File(RUTA_RESOURCES_PATH);\n validateArgument(dir.exists(), \"resources directory '\"\n + RUTA_RESOURCES_PATH + \"' does not exist (resolves to '\"\n + dir.getAbsolutePath() + \"')\");\n Iterator<File> fit = FileUtils.iterateFiles(dir, null, true);\n while (fit.hasNext()) {\n File f = fit.next();\n if (!f.getName().startsWith(\".\")) { // filtering hidden files\n String relativePath = Paths.get(dir.getAbsolutePath())\n .relativize(Paths.get(f.getAbsolutePath()))\n .toString();\n if (!relativePath.startsWith(\".\")) {\n resources.add(relativePath);\n }\n }\n }\n return resources;\n } catch (Throwable e) { // you never know...\n throw new SherlokException(\"could not list resources\").setDetails(e\n .getStackTrace());\n }\n }\n\n public static boolean deleteBundle(String bundleId) throws SherlokException {\n validateId(bundleId, \"BundleId not valid: \");\n File defFile = new File(getBundlePath(getName(bundleId),\n getVersion(bundleId)));\n if (!defFile.exists())\n throw new SherlokException(\n \"Cannot delete bundle, since it does not exist\", bundleId);\n return defFile.delete();\n }\n\n public static boolean deletePipeline(String pipelineId, String domain)\n throws SherlokException {\n validateId(pipelineId, \"PipelineId not valid: \");\n File defFile = new File(getPipelinePath(domain, getName(pipelineId),\n getVersion(pipelineId)));\n if (!defFile.exists())\n throw new SherlokException(\n \"Cannot delete pipeline, since it does not exist\",\n pipelineId);\n return defFile.delete();\n }\n\n public static void deleteResource(String path) throws SherlokException {\n validatePath(path);\n File file = new File(RUTA_RESOURCES_PATH, path);\n validateArgument(file.exists(), \"could not find file '\" + path + \"'\");\n validateArgument(file.delete(), \"could not delete file '\" + path + \"'\");\n }\n\n /** @return this resource's {@link File} */\n static InputStream getResource(String path) throws SherlokException {\n validatePath(path);\n File file = new File(RUTA_RESOURCES_PATH, path);\n validateArgument(file.exists(), \"could not find file '\" + path + \"'\");\n try {\n return new FileInputStream(file);\n } catch (FileNotFoundException e) {\n throw new SherlokException(\"file not found\", path);\n }\n }\n\n /**\n * Compute the relative path from a give absolute path and the resource\n * directory.\n */\n public static String getRelativePathToResources(File absolutePath) {\n checkArgument(absolutePath.isAbsolute());\n\n Path absolute = absolutePath.toPath();\n Path base = new File(RUTA_RESOURCES_PATH).getAbsoluteFile().toPath();\n return base.relativize(absolute).toString();\n }\n\n /*-\n // Util to read and rewrite all {@link Def}s \n public static void main(String[] args) throws SherlokException {\n Controller controller = new Controller().load();\n for (BundleDef b : controller.listBundles())\n writeBundle(b);\n for (PipelineDef p : controller.listPipelines())\n writePipeline(p);\n }*/\n}",
"@JsonInclude(JsonInclude.Include.NON_DEFAULT)\npublic static class BundleDependency {\n\n /** Dependencies can only have these formats. */\n public enum DependencyType {\n /** Default value, corresponds to a released maven artifact. */\n mvn, //\n /** any accessible git repository that contains a Maven project. */\n git, // TODO xLATER git protocol not implemented\n /** corresponds to a local or remote jar. */\n jar // TODO xLATER jar protocol not implemented\n }\n\n private DependencyType type = DependencyType.mvn;\n /** Format: {group id}:{artifact id}:{version} */\n private String value;\n\n public BundleDependency() {\n }\n\n public BundleDependency(DependencyType type, String value) {\n this.type = type;\n this.value = value;\n }\n\n public DependencyType getType() {\n return type;\n }\n\n public void setType(DependencyType type) {\n this.type = type;\n }\n\n public String getValue() {\n return value;\n }\n\n public void setValue(String value) {\n this.value = value;\n }\n\n @JsonIgnore\n public String getGroupId() {\n return value.split(SEPARATOR)[0];\n }\n\n @JsonIgnore\n public String getArtifactId() {\n return value.split(SEPARATOR)[1];\n }\n\n @JsonIgnore\n public String getVersion() {\n return value.split(SEPARATOR)[2];\n }\n\n @JsonIgnore\n public int hashCode() {\n return value.hashCode();\n }\n\n @JsonIgnore\n public boolean equals(Object obj) {\n if (obj instanceof BundleDependency) {\n BundleDependency o = (BundleDependency) obj;\n if (o.value.equals(value) && o.type == type) {\n return true;\n }\n }\n return false;\n }\n\n @JsonIgnore\n public String toString() {\n return value + \" (\" + type + \")\";\n };\n\n /** @see {@link DefaultModelValidator} */\n private static final Pattern VALIDATE_ID = compile(\"[A-Za-z0-9_\\\\-.]+\");\n\n @JsonIgnore\n public void validate() throws SherlokException {\n\n validateArgument(isLetterOrDigit(value.charAt(0)),\n \"Dependency value should start with a letter or a digit, but was '\"\n + value + \"'\", \"\", \"\");\n validateArgument(value.split(SEPARATOR).length == 3,\n \"Dependency value should contain exactly 3 columns (':'), but was '\"\n + value + \"'\", \"\", \"\");\n validateArgument(VALIDATE_ID.matcher(getGroupId()).matches(),\n \"Dependency '\" + value + \"'has an invalid group id '\"\n + getGroupId() + \"', allowed characters are \"\n + VALIDATE_ID.toString(), \"\", \"\");\n validateArgument(VALIDATE_ID.matcher(getArtifactId()).matches(),\n \"Dependency '\" + value + \"'has an invalid artifact id '\"\n + getArtifactId() + \"', allowed characters are \"\n + VALIDATE_ID.toString(), \"\", \"\");\n validateArgument(VALIDATE_ID.matcher(getVersion()).matches(),\n \"Dependency '\" + value + \"' has an invalid version id '\"\n + getVersion() + \"', allowed characters are \"\n + VALIDATE_ID.toString(), \"\", \"\");\n }\n}",
"@JsonPropertyOrder({ \"name\", \"class\", \"description\", \"parameters\" })\n@JsonInclude(JsonInclude.Include.NON_DEFAULT)\npublic static class EngineDef {\n\n /**\n * an optional unique name for this bundle. Letters, numbers and\n * underscore only\n */\n private String name,\n\n /** (optional) */\n description;\n\n /** the Java UIMA class name of this engine. */\n @JsonProperty(\"class\")\n private String classz;\n\n /** UIMA parameters. To overwrite default parameters */\n // TODO serialize without [ ], by creating custom\n // serializer, see Def.LineSerializer\n private Map<String, List<String>> parameters = map();\n\n /** TRANSITIVE (JsonIgnore), dynamically set by the bundle. */\n @JsonIgnore\n private BundleDef bundle;\n\n // get/set\n\n /** @return the engine name. Falls back on {@link #classz's simple name}. */\n public String getName() {\n if (name != null) {\n return name;\n } else if (classz != null) {\n if (classz.contains(\".\")) {\n return classz.substring(classz.lastIndexOf(\".\") + 1,\n classz.length());\n } else { // no dot in class name --> just return it\n return classz;\n }\n }\n return null;\n }\n\n public EngineDef setName(String name) {\n this.name = name;\n return this;\n }\n\n public String getDescription() {\n return description;\n }\n\n public EngineDef setDescription(String description) {\n this.description = description;\n return this;\n }\n\n public String getClassz() {\n return classz;\n }\n\n public EngineDef setClassz(String classz) {\n this.classz = classz;\n return this;\n }\n\n public Map<String, List<String>> getParameters() {\n return parameters;\n }\n\n public EngineDef setParameters(Map<String, List<String>> parameters) {\n this.parameters = parameters;\n return this;\n }\n\n public EngineDef addParameter(String key, List<String> value) {\n this.parameters.put(key, value);\n return this;\n }\n\n public List<String> getParameter(String key) {\n return this.parameters.get(key);\n }\n\n public boolean validate() throws SherlokException {\n checkOnlyAlphanumDotUnderscore(name,\n \"EngineDef '\" + this.toString() + \"'' id\");\n return true;\n }\n\n public BundleDef getBundle() {\n return bundle;\n }\n\n /** Is set at load time by {@link Controller#_load()}. */\n public EngineDef setBundle(final BundleDef bundle) {\n this.bundle = bundle;\n return this;\n }\n\n /** Needs bundle to be set (see {@link #setBundle()}). */\n @JsonIgnore\n public String getId() {\n return createId(name, bundle.getVersion());\n }\n\n /** @return the id without non-alphanumeric, separated by separator */\n public String getIdForDescriptor(final String separator) {\n return getName().replaceAll(\"[^A-Za-z0-9]\", \"_\") + separator\n + bundle.getVersion().replaceAll(\"[^A-Za-z0-9]\", \"_\");\n }\n\n @Override\n public String toString() {\n return name;\n }\n}"
] | import static java.lang.System.currentTimeMillis;
import static org.junit.Assert.assertEquals;
import static org.sherlok.FileBased.read;
import static org.sherlok.mappings.BundleDef.BundleDependency.DependencyType.jar;
import static org.sherlok.mappings.BundleDef.BundleDependency.DependencyType.mvn;
import static org.sherlok.utils.Create.set;
import java.io.File;
import java.util.Set;
import org.junit.Test;
import org.sherlok.FileBased;
import org.sherlok.mappings.BundleDef.BundleDependency;
import org.sherlok.mappings.BundleDef.EngineDef; | /**
* Copyright (C) 2014-2015 Renaud Richardet
*
* 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 org.sherlok.mappings;
public class BundleDefTest {
public static BundleDef getDkproOpennlpEn() {
BundleDef b = (BundleDef) new BundleDef()
.addDependency(
new BundleDependency(
mvn,
"de.tudarmstadt.ukp.dkpro.core:de.tudarmstadt.ukp.dkpro.core.stanfordnlp-gpl:1.6.2"))
.addDependency(
new BundleDependency(
mvn,
"de.tudarmstadt.ukp.dkpro.core:de.tudarmstadt.ukp.dkpro.core.opennlp-model-ner-en-organization:20100907.0"))
.addRepository(
"dkpro",
"http://zoidberg.ukp.informatik.tu-darmstadt.de/artifactory/public-model-releases-local/");
b.setName("dkpro_opennlp_en");
b.setVersion("1.6.2");
b.setDescription("all opennlp engines and models for English");
return b;
}
@Test
public void testWriteRead() throws Exception {
File bf = new File("target/bundleTest_" + currentTimeMillis() + ".json");
BundleDef b = getDkproOpennlpEn();
FileBased.write(bf, b);
BundleDef b2 = read(bf, BundleDef.class);
b2.validate("");
assertEquals(b.getName(), b2.getName());
assertEquals(b.getVersion(), b2.getVersion());
assertEquals(b.getDependencies().size(), b2.getDependencies().size());
}
// TODO test BundleDef.validate()
@Test
public void testValidateBundle() throws Exception {
new BundleDef().setName("a").setVersion("b").validate();
}
@Test(expected = SherlokException.class)
// $ in domain
public void testValidateBundle1() throws Exception {
new BundleDef().setName("a").setVersion("b").setDomain("a$b")
.validate();
}
@Test
public void testValidateBundle2() throws Exception {
new BundleDef().setName("a").setVersion("b").setDomain("a/b")
.validate();
}
@Test
public void testBundleDependencyEquality() throws Exception {
Set<BundleDependency> bdl = set();
bdl.add(new BundleDependency(mvn, "abc"));
bdl.add(new BundleDependency(jar, "abc"));
assertEquals("distinct DependencyTypes", 2, bdl.size());
bdl.add(new BundleDependency(jar, "abc"));
assertEquals("same DependencyTypes, should not increase the set", 2,
bdl.size());
}
@Test
public void testEngineNameFallback() throws Exception { | assertEquals("MyName", new EngineDef().setClassz("a.b.c.Dclass") | 4 |
opacapp/opacclient | opacclient/libopac/src/main/java/de/geeksfactory/opacclient/apis/WebOpacNet.java | [
"public class Account {\n private long id;\n private String library;\n\n private String label;\n private String name;\n private String password;\n private long cached;\n private boolean password_known_valid = false;\n private boolean supportPolicyHintSeen = false;\n\n @Override\n public String toString() {\n return \"Account [id=\" + id + \", library=\" + library + \", label=\"\n + label + \", name=\" + name + \", cached=\" + cached + \", \" +\n \"passwordValid=\" + password_known_valid + \"]\";\n }\n\n /**\n * Get ID this account is stored with in <code>AccountDataStore</code>\n *\n * @return Account ID\n */\n public long getId() {\n return id;\n }\n\n /**\n * Set ID this account is stored with in <code>AccountDataStore</code>\n *\n * @param id Account ID\n */\n public void setId(long id) {\n this.id = id;\n }\n\n /**\n * Get library identifier this Account belongs to.\n *\n * @return Library identifier (see {@link Library#getIdent()})\n */\n public String getLibrary() {\n return library;\n }\n\n /**\n * Set library identifier this Account belongs to.\n *\n * @param library Library identifier (see {@link Library#getIdent()})\n */\n public void setLibrary(String library) {\n this.library = library;\n }\n\n /**\n * Get user-configured Account label.\n *\n * @return Label\n */\n public String getLabel() {\n return label;\n }\n\n /**\n * Set user-configured Account label.\n *\n * @param label Label\n */\n public void setLabel(String label) {\n this.label = label;\n }\n\n /**\n * Get user name / identification\n *\n * @return User name or ID\n */\n public String getName() {\n return name;\n }\n\n /**\n * Set user name / identification\n *\n * @param name User name or ID\n */\n public void setName(String name) {\n this.name = name;\n }\n\n /**\n * Set user password\n *\n * @return Password\n */\n public String getPassword() {\n return password;\n }\n\n /**\n * Get user password\n *\n * @param password Password\n */\n public void setPassword(String password) {\n this.password = password;\n }\n\n /**\n * Get date of last data update\n *\n * @return Timestamp in milliseconds\n */\n public long getCached() {\n return cached;\n }\n\n /**\n * Set date of last data update\n *\n * @param cached Timestamp in milliseconds (use\n * <code>System.currentTimeMillis</code>)\n */\n public void setCached(long cached) {\n this.cached = cached;\n }\n\n public boolean isPasswordKnownValid() {\n return password_known_valid;\n }\n\n public void setPasswordKnownValid(boolean password_known_valid) {\n this.password_known_valid = password_known_valid;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n\n Account account = (Account) o;\n\n return id == account.id;\n }\n\n @Override\n public int hashCode() {\n return (int) (id ^ (id >>> 32));\n }\n\n public boolean isSupportPolicyHintSeen() {\n return supportPolicyHintSeen;\n }\n\n public void setSupportPolicyHintSeen(boolean supportPolicyHintSeen) {\n this.supportPolicyHintSeen = supportPolicyHintSeen;\n }\n}",
"public class Copy {\n private String barcode;\n private String location;\n private String department;\n private String branch;\n private String issue;\n private String status;\n private SearchResult.Status statusCode;\n private LocalDate returnDate;\n private String reservations;\n private String shelfmark;\n private String resInfo;\n private String url;\n\n /**\n * @return The barcode of a copy. Optional.\n */\n public String getBarcode() {\n return barcode;\n }\n\n /**\n * @param barcode The barcode of a copy. Optional.\n */\n public void setBarcode(String barcode) {\n this.barcode = barcode;\n }\n\n /**\n * @return The location (like \"third floor\") of a copy. Optional.\n */\n public String getLocation() {\n return location;\n }\n\n /**\n * @param location The location (like \"third floor\") of a copy. Optional.\n */\n public void setLocation(String location) {\n this.location = location;\n }\n\n /**\n * @return The department (like \"music library\") of a copy. Optional.\n */\n public String getDepartment() {\n return department;\n }\n\n /**\n * @param department The department (like \"music library\") of a copy. Optional.\n */\n public void setDepartment(String department) {\n this.department = department;\n }\n\n /**\n * @return The branch a copy is in. Should be set, if your library has more than one branch.\n */\n public String getBranch() {\n return branch;\n }\n\n /**\n * @param branch The branch a copy is in. Should be set, if your library has more than one\n * branch.\n */\n public void setBranch(String branch) {\n this.branch = branch;\n }\n\n /**\n * @return The issue, e.g. when the item represents a year of magazines, this is the magazine number.\n */\n public String getIssue() {\n return issue;\n }\n\n /**\n * @param issue The issue, e.g. when the item represents a year of magazines, this is the magazine number.\n */\n public void setIssue(String issue) {\n this.issue = issue;\n }\n\n /**\n * @return Current status of a copy (\"lent\", \"free\", ...). Should be set.\n */\n public String getStatus() {\n return status;\n }\n\n /**\n * @param status Current status of a copy (\"lent\", \"free\", ...). Should be set.\n */\n public void setStatus(String status) {\n this.status = status;\n }\n\n /**\n * @return Current status code of a copy or <code>null</code> if not set.\n */\n public SearchResult.Status getStatusCode() {\n return statusCode;\n }\n\n /**\n * @param statusCode Current status code of a copy.\n */\n public void setStatusCode(SearchResult.Status statusCode) {\n this.statusCode = statusCode;\n }\n\n /**\n * @return Expected date of return if a copy is lent out. Optional.\n */\n public LocalDate getReturnDate() {\n return returnDate;\n }\n\n /**\n * @param returndate Expected date of return if a copy is lent out. Optional.\n */\n public void setReturnDate(LocalDate returndate) {\n this.returnDate = returndate;\n }\n\n /**\n * @return Number of pending reservations if a copy is currently lent out. Optional.\n */\n public String getReservations() {\n return reservations;\n }\n\n /**\n * @param reservations Number of pending reservations if a copy is currently lent out.\n * Optional.\n */\n public void setReservations(String reservations) {\n this.reservations = reservations;\n }\n\n /**\n * @return Identification in the libraries' shelf system. Optional.\n */\n public String getShelfmark() {\n return shelfmark;\n }\n\n /**\n * @param shelfmark Identification in the libraries' shelf system. Optional.\n */\n public void setShelfmark(String shelfmark) {\n this.shelfmark = shelfmark;\n }\n\n /**\n * @return Reservation information for copy-based reservations. Intended for use in your {@link\n * de.geeksfactory.opacclient.apis.OpacApi#reservation(DetailedItem, Account, int, String)}\n * implementation.\n */\n public String getResInfo() {\n return resInfo;\n }\n\n /**\n * @param resInfo Reservation information for copy-based reservations. Intended for use in your\n * {@link de.geeksfactory.opacclient.apis.OpacApi#reservation (DetailedItem,\n * Account, int, String)} implementation.\n */\n public void setResInfo(String resInfo) {\n this.resInfo = resInfo;\n }\n\n /**\n * @return URL to an online copy\n */\n public String getUrl() {\n return url;\n }\n\n /**\n * @param url URL to an online copy\n */\n public void setUrl(String url) {\n this.url = url;\n }\n\n /**\n * Set property using the following keys: barcode, location, department, branch, status,\n * returndate, reservations, signature, resinfo, url\n *\n * If you supply an invalid key, an {@link IllegalArgumentException} will be thrown.\n *\n * This method is used to simplify refactoring of old APIs from the Map<String, String> data\n * structure to this class. If you are creating a new API, you probably don't need to use it.\n *\n * @param key one of the keys mentioned above\n * @param value the value to set. Dates must be in ISO-8601 format (yyyy-MM-dd).\n */\n public void set(String key, String value) {\n switch (key) {\n case \"barcode\":\n setBarcode(value);\n break;\n case \"location\":\n setLocation(value);\n break;\n case \"department\":\n setDepartment(value);\n break;\n case \"branch\":\n setBranch(value);\n break;\n case \"status\":\n setStatus(value);\n break;\n case \"returndate\":\n setReturnDate(new LocalDate(value));\n break;\n case \"reservations\":\n setReservations(value);\n break;\n case \"signature\":\n setShelfmark(value);\n break;\n case \"resinfo\":\n setResInfo(value);\n break;\n case \"url\":\n setUrl(value);\n break;\n default:\n throw new IllegalArgumentException(\"key unknown\");\n }\n }\n\n /**\n * Set property using the following keys: barcode, location, department, branch, status,\n * returndate, reservations, signature, resinfo, url\n *\n * For \"returndate\", the given {@link DateTimeFormatter} will be used to parse the date.\n *\n * If you supply an invalid key, an {@link IllegalArgumentException} will be thrown.\n *\n * This method is used to simplify refactoring of old APIs from the Map<String, String> data\n * structure to this class. If you are creating a new API, you probably don't need to use it.\n *\n * @param key one of the keys mentioned above\n * @param value the value to set. Dates must be in a format parseable by the given {@link\n * DateTimeFormatter}, otherwise an {@link IllegalArgumentException} will be\n * thrown.\n * @param fmt the {@link DateTimeFormatter} to use for parsing dates\n */\n public void set(String key, String value, DateTimeFormatter fmt) {\n if (key.equals(\"returndate\")) {\n if (!value.isEmpty()) {\n setReturnDate(fmt.parseLocalDate(value));\n }\n } else {\n set(key, value);\n }\n }\n\n /**\n * Get property using the following keys: barcode, location, department, branch, status,\n * returndate, reservations, signature, resinfo, url\n *\n * Dates will be returned in ISO-8601 format (yyyy-MM-dd). If you supply an invalid key, an\n * {@link IllegalArgumentException} will be thrown.\n *\n * This method is used to simplify refactoring of old APIs from the Map<String, String> data\n * structure to this class. If you are creating a new API, you probably don't need to use it.\n *\n * @param key one of the keys mentioned above\n */\n public String get(String key) {\n switch (key) {\n case \"barcode\":\n return getBarcode();\n case \"location\":\n return getLocation();\n case \"department\":\n return getDepartment();\n case \"branch\":\n return getBranch();\n case \"status\":\n return getStatus();\n case \"returndate\":\n return getReturnDate() != null ? ISODateTimeFormat.date().print(getReturnDate()) : null;\n case \"reservations\":\n return getReservations();\n case \"signature\":\n return getShelfmark();\n case \"resinfo\":\n return getResInfo();\n case \"url\":\n return getUrl();\n default:\n throw new IllegalArgumentException(\"key unknown\");\n }\n }\n\n /**\n * @return boolean value indicating if this copy contains any data or not.\n */\n public boolean notEmpty() {\n return getBarcode() != null\n || getLocation() != null\n || getDepartment() != null\n || getBranch() != null\n || getStatus() != null\n || getStatusCode() != null\n || getReturnDate() != null\n || getReservations() != null\n || getShelfmark() != null\n || getResInfo() != null\n || getIssue() != null\n || getUrl() != null;\n }\n\n @Override\n public String toString() {\n return \"Copy{\" +\n \"barcode='\" + barcode + '\\'' +\n \", location='\" + location + '\\'' +\n \", department='\" + department + '\\'' +\n \", branch='\" + branch + '\\'' +\n \", status='\" + status + '\\'' +\n \", statusCode='\" + statusCode + '\\'' +\n \", returnDate=\" + returnDate +\n \", reservations='\" + reservations + '\\'' +\n \", shelfmark='\" + shelfmark + '\\'' +\n \", issue='\" + issue + '\\'' +\n \", resInfo='\" + resInfo + '\\'' +\n \", url='\" + url + '\\'' +\n '}';\n }\n}",
"public class DetailedItem implements CoverHolder {\n private List<Detail> details = new ArrayList<>();\n private List<Copy> copies = new ArrayList<>();\n private List<Volume> volumes = new ArrayList<>();\n private CompletableFuture<Void> coverFuture = null;\n private String cover;\n private String title;\n private SearchResult.MediaType mediaType;\n private byte[] coverBitmap;\n private boolean reservable;\n private String reservation_info;\n private boolean bookable;\n private String booking_info;\n private String id;\n private Map<String, String> volumesearch;\n private String collectionid;\n\n /**\n * Get unique media identifier\n *\n * @return media ID\n */\n public String getId() {\n return id;\n }\n\n /**\n * Set unique media identifier\n *\n * @param id media ID\n */\n public void setId(String id) {\n this.id = id;\n }\n\n /**\n * Get media title\n */\n public String getTitle() {\n return title;\n }\n\n /**\n * Set media title\n */\n public void setTitle(String title) {\n this.title = title;\n }\n\n /**\n * Get cover image bitmap\n */\n @Override\n public byte[] getCoverBitmap() {\n return coverBitmap;\n }\n\n /**\n * Set cover image bitmap\n */\n @Override\n public void setCoverBitmap(byte[] coverBitmap) {\n this.coverBitmap = coverBitmap;\n }\n\n /**\n * Get cover image URL\n */\n @Override\n public String getCover() {\n return cover;\n }\n\n /**\n * Set cover image URL\n */\n @Override\n public void setCover(String cover) {\n this.cover = cover;\n }\n\n /**\n * Returns all data stored in this object, serialized as a human-readable\n * string.\n */\n @Override\n public String toString() {\n return \"DetailedItem [details=\" + details + \", copies=\" + copies\n + \", volumes=\" + volumes + \", cover=\" + cover + \", title=\"\n + title + \", coverBitmap=\" + coverBitmap + \", reservable=\"\n + reservable + \", reservation_info=\" + reservation_info\n + \", id=\" + id + \", volumesearch=\" + volumesearch + \", mediatype=\" + mediaType +\n \"]\";\n }\n\n /**\n * Get details (like author, summary, …).\n *\n * @return List of Details\n * @see Detail\n */\n public List<Detail> getDetails() {\n return details;\n }\n\n /**\n * List of copies of this item available\n *\n * @return List of copies\n * @see #addCopy(Copy)\n */\n public List<Copy> getCopies() {\n return copies;\n }\n\n /**\n * Set list of copies of this item available\n *\n * @param copies List of copies\n * @see #addCopy(Copy)\n */\n public void setCopies(List<Copy> copies) {\n this.copies = copies;\n }\n\n /**\n * List of child items (e.g. volumes of a series) available\n *\n * @return List of child items available\n * @see #addVolume(Volume)\n */\n public List<Volume> getVolumes() {\n return volumes;\n }\n\n /**\n * Set list of child items (e.g. volumes of a series) available\n *\n * @param volumes List of child items available\n * @see #addVolume(Volume)\n */\n public void setVolumes(List<Volume> volumes) {\n this.volumes = volumes;\n }\n\n /**\n * Add a detail\n *\n * @see Detail\n */\n public void addDetail(Detail detail) {\n details.add(detail);\n }\n\n /**\n * Add a copy.\n *\n * @param copy An object representing a copy\n * @see Copy\n */\n public void addCopy(Copy copy) {\n copies.add(copy);\n }\n\n /**\n * Add a child item.\n */\n public void addVolume(Volume child) {\n volumes.add(child);\n }\n\n /**\n * Can return a\n * {@link de.geeksfactory.opacclient.apis.OpacApi#search(List)} query\n * <code>List</code> for a volume search based on this item.\n *\n * @return Search query or <code>null</code> if not applicable\n * @see Detail\n */\n public Map<String, String> getVolumesearch() {\n return volumesearch;\n }\n\n /**\n * Sets a search query which is passed back to your\n * {@link de.geeksfactory.opacclient.apis.OpacApi#search(List)}\n * implementation for a volume search based on this item-\n *\n * @param volumesearch Search query\n */\n public void setVolumesearch(Map<String, String> volumesearch) {\n this.volumesearch = volumesearch;\n }\n\n /**\n * Returns whether it is possible to order this item through the app\n *\n * @return <code>true</code> if possible, <code>false</code> otherwise.\n */\n public boolean isReservable() {\n return reservable;\n }\n\n /**\n * Specifies whether it is possible to order this item through the app\n */\n public void setReservable(boolean reservable) {\n this.reservable = reservable;\n }\n\n /**\n * Get extra information stored to be returned to your\n * {@link de.geeksfactory.opacclient.apis.OpacApi#reservation(DetailedItem, Account, int, String)}\n * implementation.\n *\n * @return Some custom information.\n */\n public String getReservation_info() {\n return reservation_info;\n }\n\n /**\n * Set extra information stored to be returned to your\n * {@link de.geeksfactory.opacclient.apis.OpacApi#reservation(DetailedItem, Account, int, String)}\n * implementation.\n *\n * @param reservation_info Some custom information.\n */\n public void setReservation_info(String reservation_info) {\n this.reservation_info = reservation_info;\n }\n\n /**\n * @return the bookable\n */\n public boolean isBookable() {\n return bookable;\n }\n\n /**\n * @param bookable Some custom information.\n */\n public void setBookable(boolean bookable) {\n this.bookable = bookable;\n }\n\n /**\n * @return the booking_info\n */\n public String getBooking_info() {\n return booking_info;\n }\n\n /**\n * @param booking_info Some custom information.\n */\n public void setBooking_info(String booking_info) {\n this.booking_info = booking_info;\n }\n\n /**\n * Get the ID of the item which is a collection containing this item as a\n * child item\n *\n * @since 2.0.17\n */\n public String getCollectionId() {\n return collectionid;\n }\n\n /**\n * Sets the ID of the item which is a collection containing this item as a\n * child item\n *\n * @param collectionid the collectionid to set\n * @since 2.0.17\n */\n public void setCollectionId(String collectionid) {\n this.collectionid = collectionid;\n }\n\n /**\n * @return this item's media type\n */\n public SearchResult.MediaType getMediaType() {\n return mediaType;\n }\n\n /**\n * @param mediaType the media type to set\n */\n public void setMediaType(SearchResult.MediaType mediaType) {\n this.mediaType = mediaType;\n }\n\n public CompletableFuture<Void> getCoverFuture() {\n return coverFuture;\n }\n\n public void setCoverFuture(CompletableFuture<Void> coverFuture) {\n this.coverFuture = coverFuture;\n }\n}",
"public class SearchResult implements CoverHolder {\n private MediaType type;\n private int nr;\n private String id;\n private String innerhtml;\n private Status status;\n private byte[] coverBitmap;\n private String cover;\n private CompletableFuture<Void> coverFuture = null;\n private int page;\n private List<SearchQuery> childQuery;\n private String libraryIdent;\n\n /**\n * Create a new SearchResult object\n *\n * @param type media type (like \"BOOK\")\n * @param nr Position in result list\n * @param innerhtml HTML to display\n */\n public SearchResult(MediaType type, int nr, String innerhtml) {\n this.type = type;\n this.nr = nr;\n this.innerhtml = innerhtml;\n }\n\n /**\n * Create an empty object\n */\n public SearchResult() {\n this.type = MediaType.NONE;\n this.nr = 0;\n this.innerhtml = \"\";\n }\n\n /**\n * Get the unique identifier of this object\n *\n * @return ID or <code>null</code> if unknown\n */\n public String getId() {\n return id;\n }\n\n /**\n * Set the unique identifier of this object\n *\n * @param id unique identifier\n */\n public void setId(String id) {\n this.id = id;\n }\n\n /**\n * Get this item's media type.\n *\n * @return Media type or <code>null</code> if unknown\n */\n public MediaType getType() {\n return type;\n }\n\n /**\n * Set this item's media type.\n *\n * @param type Media type\n */\n public void setType(MediaType type) {\n this.type = type;\n }\n\n /**\n * Get this item's position in result list\n *\n * @return position\n */\n public int getNr() {\n return nr;\n }\n\n /**\n * Set this item's position in result list\n *\n * @param nr position\n */\n public void setNr(int nr) {\n this.nr = nr;\n }\n\n /**\n * Get HTML describing the item to the user in a result list.\n *\n * @return position\n */\n public String getInnerhtml() {\n return innerhtml;\n }\n\n /**\n * Set HTML describing the item to the user in a result list. Only \"simple\" HTML like\n * {@code <b>}, {@code <i>}, etc. can be used.\n *\n * @param innerhtml simple HTML code\n */\n public void setInnerhtml(String innerhtml) {\n this.innerhtml = innerhtml;\n }\n\n /**\n * Get item status (if known)\n *\n * @return Status or <code>null</code> if not set.\n * @since 2.0.7\n */\n public Status getStatus() {\n return status;\n }\n\n /**\n * Set item status (if known)\n *\n * @since 2.0.7\n */\n public void setStatus(Status status) {\n this.status = status;\n }\n\n /**\n * Get the page this result was found on\n */\n public int getPage() {\n return page;\n }\n\n /**\n * Set the page this result was found on\n */\n public void setPage(int page) {\n this.page = page;\n }\n\n /**\n * Get cover image bitmap\n */\n @Override\n public byte[] getCoverBitmap() {\n return coverBitmap;\n }\n\n /**\n * Set cover image bitmap\n */\n @Override\n public void setCoverBitmap(byte[] coverBitmap) {\n this.coverBitmap = coverBitmap;\n }\n\n /**\n * Get cover image URL\n */\n @Override\n public String getCover() {\n return cover;\n }\n\n /**\n * Set cover image URL\n */\n @Override\n public void setCover(String cover) {\n this.cover = cover;\n }\n\n /**\n * Get the child query (see setChildQuery for details)\n */\n public List<SearchQuery> getChildQuery() {\n return childQuery;\n }\n\n /**\n * Set the child query. If this is set, clicking the item in the UI will not\n * open a detail page, but start another search.\n */\n public void setChildQuery(\n List<SearchQuery> childQuery) {\n this.childQuery = childQuery;\n }\n\n /**\n * Sets the libraryIdent of the library this search result belongs to.\n */\n public void setLibraryIdent(String libraryIdent) {\n this.libraryIdent = libraryIdent;\n }\n\n /**\n * Gets the libraryIdent of the library this search result belongs to if set.\n * Returns null if libraryIdent is not set\n */\n public String getLibraryIdent() {\n return libraryIdent;\n }\n\n public CompletableFuture<Void> getCoverFuture() {\n return coverFuture;\n }\n\n public void setCoverFuture(CompletableFuture<Void> coverFuture) {\n this.coverFuture = coverFuture;\n }\n\n @Override\n public String toString() {\n return \"SearchResult [id= \" + id + \", type=\" + type + \", nr=\" + nr\n + \", innerhtml=\" + innerhtml + \"]\";\n }\n\n /**\n * Supported media types.\n *\n * @since 2.0.3\n */\n public enum MediaType {\n NONE, BOOK, CD, CD_SOFTWARE, CD_MUSIC, DVD, MOVIE, AUDIOBOOK, PACKAGE,\n GAME_CONSOLE, EBOOK, SCORE_MUSIC, PACKAGE_BOOKS, UNKNOWN, NEWSPAPER,\n BOARDGAME, SCHOOL_VERSION, MAP, BLURAY, AUDIO_CASSETTE, ART, MAGAZINE,\n GAME_CONSOLE_WII, GAME_CONSOLE_NINTENDO, GAME_CONSOLE_PLAYSTATION,\n GAME_CONSOLE_XBOX, LP_RECORD, MP3, URL, EVIDEO, EDOC, EAUDIO, DEVICE,\n MICROFORM, FIGURINE\n }\n\n /**\n * Media status, simplified like a traffic light, e.g. red for \"lent out, no reservation\n * possible\", yellow for \"reservation needed\" or green for \"available\".\n *\n * @since 2.0.7\n */\n public enum Status {\n UNKNOWN, RED, YELLOW, GREEN\n }\n\n}",
"public enum MediaType {\n NONE, BOOK, CD, CD_SOFTWARE, CD_MUSIC, DVD, MOVIE, AUDIOBOOK, PACKAGE,\n GAME_CONSOLE, EBOOK, SCORE_MUSIC, PACKAGE_BOOKS, UNKNOWN, NEWSPAPER,\n BOARDGAME, SCHOOL_VERSION, MAP, BLURAY, AUDIO_CASSETTE, ART, MAGAZINE,\n GAME_CONSOLE_WII, GAME_CONSOLE_NINTENDO, GAME_CONSOLE_PLAYSTATION,\n GAME_CONSOLE_XBOX, LP_RECORD, MP3, URL, EVIDEO, EDOC, EAUDIO, DEVICE,\n MICROFORM, FIGURINE\n}",
"@SuppressWarnings({\"CaughtExceptionImmediatelyRethrown\", \"UnusedAssignment\"})\npublic class Base64 {\n\n/* ******** P U B L I C F I E L D S ******** */\n\n\n /**\n * No options specified. Value is zero.\n */\n public final static int NO_OPTIONS = 0;\n\n /**\n * Specify encoding in first bit. Value is one.\n */\n public final static int ENCODE = 1;\n\n\n /**\n * Specify decoding in first bit. Value is zero.\n */\n public final static int DECODE = 0;\n\n\n /**\n * Specify that data should be gzip-compressed in second bit. Value is two.\n */\n public final static int GZIP = 2;\n\n /**\n * Specify that gzipped data should <em>not</em> be automatically gunzipped.\n */\n public final static int DONT_GUNZIP = 4;\n\n\n /**\n * Do break lines when encoding. Value is 8.\n */\n public final static int DO_BREAK_LINES = 8;\n\n /**\n * Encode using Base64-like encoding that is URL- and Filename-safe as described in Section 4 of\n * RFC3548: <a href=\"http://www.faqs.org/rfcs/rfc3548.html\">http://www.faqs.org/rfcs/rfc3548\n * .html</a>.\n * It is important to note that data encoded this way is <em>not</em> officially valid Base64,\n * or at the very least should not be called Base64 without also specifying that is was encoded\n * using the URL- and Filename-safe dialect.\n */\n public final static int URL_SAFE = 16;\n\n\n /**\n * Encode using the special \"ordered\" dialect of Base64 described here: <a\n * href=\"http://www.faqs.org/qa/rfcc-1940.html\">http://www.faqs.org/qa/rfcc-1940.html</a>.\n */\n public final static int ORDERED = 32;\n\n\n/* ******** P R I V A T E F I E L D S ******** */\n\n\n /**\n * Maximum line length (76) of Base64 output.\n */\n private final static int MAX_LINE_LENGTH = 76;\n\n\n /**\n * The equals sign (=) as a byte.\n */\n private final static byte EQUALS_SIGN = (byte) '=';\n\n\n /**\n * The new line character (\\n) as a byte.\n */\n private final static byte NEW_LINE = (byte) '\\n';\n\n\n /**\n * Preferred encoding.\n */\n private final static String PREFERRED_ENCODING = \"US-ASCII\";\n\n\n private final static byte WHITE_SPACE_ENC = -5; // Indicates white space in encoding\n private final static byte EQUALS_SIGN_ENC = -1; // Indicates equals sign in encoding\n\n\n/* ******** S T A N D A R D B A S E 6 4 A L P H A B E T ******** */\n\n /**\n * The 64 valid Base64 values.\n */\n /* Host platform me be something funny like EBCDIC, so we hardcode these values. */\n private final static byte[] _STANDARD_ALPHABET = {\n (byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', (byte) 'G',\n (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N',\n (byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U',\n (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z',\n (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f', (byte) 'g',\n (byte) 'h', (byte) 'i', (byte) 'j', (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n',\n (byte) 'o', (byte) 'p', (byte) 'q', (byte) 'r', (byte) 's', (byte) 't', (byte) 'u',\n (byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z',\n (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5',\n (byte) '6', (byte) '7', (byte) '8', (byte) '9', (byte) '+', (byte) '/'\n };\n\n\n /**\n * Translates a Base64 value to either its 6-bit reconstruction value or a negative number\n * indicating some other meaning.\n */\n private final static byte[] _STANDARD_DECODABET = {\n -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8\n -5, -5, // Whitespace: Tab and Linefeed\n -9, -9, // Decimal 11 - 12\n -5, // Whitespace: Carriage Return\n -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - 26\n -9, -9, -9, -9, -9, // Decimal 27 - 31\n -5, // Whitespace: Space\n -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 42\n 62, // Plus sign at decimal 43\n -9, -9, -9, // Decimal 44 - 46\n 63, // Slash at decimal 47\n 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // Numbers zero through nine\n -9, -9, -9, // Decimal 58 - 60\n -1, // Equals sign at decimal 61\n -9, -9, -9, // Decimal 62 - 64\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, // Letters 'A' through 'N'\n 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // Letters 'O' through 'Z'\n -9, -9, -9, -9, -9, -9, // Decimal 91 - 96\n 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // Letters 'a' through 'm'\n 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // Letters 'n' through 'z'\n -9, -9, -9, -9, -9 // Decimal 123 - 127\n , -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 128 - 139\n -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 140 - 152\n -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 153 - 165\n -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 166 - 178\n -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 179 - 191\n -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 192 - 204\n -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 205 - 217\n -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 218 - 230\n -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 231 - 243\n -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9 // Decimal 244 - 255\n };\n\n\n/* ******** U R L S A F E B A S E 6 4 A L P H A B E T ******** */\n\n /**\n * Used in the URL- and Filename-safe dialect described in Section 4 of RFC3548: <a\n * href=\"http://www.faqs.org/rfcs/rfc3548.html\">http://www.faqs.org/rfcs/rfc3548.html</a>.\n * Notice that the last two bytes become \"hyphen\" and \"underscore\" instead of \"plus\" and\n * \"slash.\"\n */\n private final static byte[] _URL_SAFE_ALPHABET = {\n (byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', (byte) 'G',\n (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N',\n (byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U',\n (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z',\n (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f', (byte) 'g',\n (byte) 'h', (byte) 'i', (byte) 'j', (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n',\n (byte) 'o', (byte) 'p', (byte) 'q', (byte) 'r', (byte) 's', (byte) 't', (byte) 'u',\n (byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z',\n (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5',\n (byte) '6', (byte) '7', (byte) '8', (byte) '9', (byte) '-', (byte) '_'\n };\n\n /**\n * Used in decoding URL- and Filename-safe dialects of Base64.\n */\n private final static byte[] _URL_SAFE_DECODABET = {\n -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8\n -5, -5, // Whitespace: Tab and Linefeed\n -9, -9, // Decimal 11 - 12\n -5, // Whitespace: Carriage Return\n -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - 26\n -9, -9, -9, -9, -9, // Decimal 27 - 31\n -5, // Whitespace: Space\n -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 42\n -9, // Plus sign at decimal 43\n -9, // Decimal 44\n 62, // Minus sign at decimal 45\n -9, // Decimal 46\n -9, // Slash at decimal 47\n 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // Numbers zero through nine\n -9, -9, -9, // Decimal 58 - 60\n -1, // Equals sign at decimal 61\n -9, -9, -9, // Decimal 62 - 64\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, // Letters 'A' through 'N'\n 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // Letters 'O' through 'Z'\n -9, -9, -9, -9, // Decimal 91 - 94\n 63, // Underscore at decimal 95\n -9, // Decimal 96\n 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // Letters 'a' through 'm'\n 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // Letters 'n' through 'z'\n -9, -9, -9, -9, -9 // Decimal 123 - 127\n , -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 128 - 139\n -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 140 - 152\n -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 153 - 165\n -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 166 - 178\n -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 179 - 191\n -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 192 - 204\n -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 205 - 217\n -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 218 - 230\n -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 231 - 243\n -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9 // Decimal 244 - 255\n };\n\n\n\n/* ******** O R D E R E D B A S E 6 4 A L P H A B E T ******** */\n\n /**\n * I don't get the point of this technique, but someone requested it, and it is described here:\n * <a href=\"http://www.faqs.org/qa/rfcc-1940.html\">http://www.faqs.org/qa/rfcc-1940.html</a>.\n */\n private final static byte[] _ORDERED_ALPHABET = {\n (byte) '-',\n (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4',\n (byte) '5', (byte) '6', (byte) '7', (byte) '8', (byte) '9',\n (byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', (byte) 'G',\n (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N',\n (byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U',\n (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z',\n (byte) '_',\n (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f', (byte) 'g',\n (byte) 'h', (byte) 'i', (byte) 'j', (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n',\n (byte) 'o', (byte) 'p', (byte) 'q', (byte) 'r', (byte) 's', (byte) 't', (byte) 'u',\n (byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z'\n };\n\n /**\n * Used in decoding the \"ordered\" dialect of Base64.\n */\n private final static byte[] _ORDERED_DECODABET = {\n -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8\n -5, -5, // Whitespace: Tab and Linefeed\n -9, -9, // Decimal 11 - 12\n -5, // Whitespace: Carriage Return\n -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - 26\n -9, -9, -9, -9, -9, // Decimal 27 - 31\n -5, // Whitespace: Space\n -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 42\n -9, // Plus sign at decimal 43\n -9, // Decimal 44\n 0, // Minus sign at decimal 45\n -9, // Decimal 46\n -9, // Slash at decimal 47\n 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, // Numbers zero through nine\n -9, -9, -9, // Decimal 58 - 60\n -1, // Equals sign at decimal 61\n -9, -9, -9, // Decimal 62 - 64\n 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, // Letters 'A' through 'M'\n 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, // Letters 'N' through 'Z'\n -9, -9, -9, -9, // Decimal 91 - 94\n 37, // Underscore at decimal 95\n -9, // Decimal 96\n 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, // Letters 'a' through 'm'\n 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, // Letters 'n' through 'z'\n -9, -9, -9, -9, -9 // Decimal 123 - 127\n , -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 128 - 139\n -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 140 - 152\n -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 153 - 165\n -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 166 - 178\n -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 179 - 191\n -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 192 - 204\n -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 205 - 217\n -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 218 - 230\n -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 231 - 243\n -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9 // Decimal 244 - 255\n };\n\n\n/* ******** D E T E R M I N E W H I C H A L H A B E T ******** */\n\n\n /**\n * Defeats instantiation.\n */\n private Base64() {\n }\n\n /**\n * Returns one of the _SOMETHING_ALPHABET byte arrays depending on the options specified. It's\n * possible, though silly, to specify ORDERED <b>and</b> URLSAFE in which case one of them will\n * be picked, though there is no guarantee as to which one will be picked.\n */\n private static byte[] getAlphabet(int options) {\n if ((options & URL_SAFE) == URL_SAFE) {\n return _URL_SAFE_ALPHABET;\n } else if ((options & ORDERED) == ORDERED) {\n return _ORDERED_ALPHABET;\n } else {\n return _STANDARD_ALPHABET;\n }\n } // end getAlphabet\n\n /**\n * Returns one of the _SOMETHING_DECODABET byte arrays depending on the options specified. It's\n * possible, though silly, to specify ORDERED and URL_SAFE in which case one of them will be\n * picked, though there is no guarantee as to which one will be picked.\n */\n private static byte[] getDecodabet(int options) {\n if ((options & URL_SAFE) == URL_SAFE) {\n return _URL_SAFE_DECODABET;\n } else if ((options & ORDERED) == ORDERED) {\n return _ORDERED_DECODABET;\n } else {\n return _STANDARD_DECODABET;\n }\n } // end getAlphabet\n\n\n\n\n/* ******** E N C O D I N G M E T H O D S ******** */\n\n /**\n * Encodes up to the first three bytes of array <var>threeBytes</var> and returns a four-byte\n * array in Base64 notation. The actual number of significant bytes in your array is given by\n * <var>numSigBytes</var>. The array <var>threeBytes</var> needs only be as big as\n * <var>numSigBytes</var>. Code can reuse a byte array by passing a four-byte array as\n * <var>b4</var>.\n *\n * @param b4 A reusable byte array to reduce array instantiation\n * @param threeBytes the array to convert\n * @param numSigBytes the number of significant bytes in your array\n * @return four byte array in Base64 notation.\n * @since 1.5.1\n */\n private static byte[] encode3to4(byte[] b4, byte[] threeBytes, int numSigBytes, int options) {\n encode3to4(threeBytes, 0, numSigBytes, b4, 0, options);\n return b4;\n } // end encode3to4\n\n\n /**\n * <p>Encodes up to three bytes of the array <var>source</var> and writes the resulting four\n * Base64 bytes to <var>destination</var>. The source and destination arrays can be manipulated\n * anywhere along their length by specifying <var>srcOffset</var> and <var>destOffset</var>.\n * This method does not check to make sure your arrays are large enough to accomodate\n * <var>srcOffset</var> + 3 for the <var>source</var> array or <var>destOffset</var> + 4 for the\n * <var>destination</var> array. The actual number of significant bytes in your array is given\n * by <var>numSigBytes</var>.</p> <p>This is the lowest level of the encoding methods with all\n * possible parameters.</p>\n *\n * @param source the array to convert\n * @param srcOffset the index where conversion begins\n * @param numSigBytes the number of significant bytes in your array\n * @param destination the array to hold the conversion\n * @param destOffset the index where output will be put\n * @return the <var>destination</var> array\n * @since 1.3\n */\n private static byte[] encode3to4(\n byte[] source, int srcOffset, int numSigBytes,\n byte[] destination, int destOffset, int options) {\n\n byte[] ALPHABET = getAlphabet(options);\n\n // 1 2 3\n // 01234567890123456789012345678901 Bit position\n // --------000000001111111122222222 Array position from threeBytes\n // --------| || || || | Six bit groups to index ALPHABET\n // >>18 >>12 >> 6 >> 0 Right shift necessary\n // 0x3f 0x3f 0x3f Additional AND\n\n // Create buffer with zero-padding if there are only one or two\n // significant bytes passed in the array.\n // We have to shift left 24 in order to flush out the 1's that appear\n // when Java treats a value as negative that is cast from a byte to an int.\n int inBuff = (numSigBytes > 0 ? ((source[srcOffset] << 24) >>> 8) : 0)\n | (numSigBytes > 1 ? ((source[srcOffset + 1] << 24) >>> 16) : 0)\n | (numSigBytes > 2 ? ((source[srcOffset + 2] << 24) >>> 24) : 0);\n\n switch (numSigBytes) {\n case 3:\n destination[destOffset] = ALPHABET[(inBuff >>> 18)];\n destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f];\n destination[destOffset + 2] = ALPHABET[(inBuff >>> 6) & 0x3f];\n destination[destOffset + 3] = ALPHABET[(inBuff) & 0x3f];\n return destination;\n\n case 2:\n destination[destOffset] = ALPHABET[(inBuff >>> 18)];\n destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f];\n destination[destOffset + 2] = ALPHABET[(inBuff >>> 6) & 0x3f];\n destination[destOffset + 3] = EQUALS_SIGN;\n return destination;\n\n case 1:\n destination[destOffset] = ALPHABET[(inBuff >>> 18)];\n destination[destOffset + 1] = ALPHABET[(inBuff >>> 12) & 0x3f];\n destination[destOffset + 2] = EQUALS_SIGN;\n destination[destOffset + 3] = EQUALS_SIGN;\n return destination;\n\n default:\n return destination;\n } // end switch\n } // end encode3to4\n\n\n /**\n * Performs Base64 encoding on the <code>raw</code> ByteBuffer, writing it to the\n * <code>encoded</code> ByteBuffer. This is an experimental feature. Currently it does not pass\n * along any options (such as {@link #DO_BREAK_LINES} or {@link #GZIP}.\n *\n * @param raw input buffer\n * @param encoded output buffer\n * @since 2.3\n */\n public static void encode(java.nio.ByteBuffer raw, java.nio.ByteBuffer encoded) {\n byte[] raw3 = new byte[3];\n byte[] enc4 = new byte[4];\n\n while (raw.hasRemaining()) {\n int rem = Math.min(3, raw.remaining());\n raw.get(raw3, 0, rem);\n Base64.encode3to4(enc4, raw3, rem, Base64.NO_OPTIONS);\n encoded.put(enc4);\n } // end input remaining\n }\n\n\n /**\n * Performs Base64 encoding on the <code>raw</code> ByteBuffer, writing it to the\n * <code>encoded</code> CharBuffer. This is an experimental feature. Currently it does not pass\n * along any options (such as {@link #DO_BREAK_LINES} or {@link #GZIP}.\n *\n * @param raw input buffer\n * @param encoded output buffer\n * @since 2.3\n */\n public static void encode(java.nio.ByteBuffer raw, java.nio.CharBuffer encoded) {\n byte[] raw3 = new byte[3];\n byte[] enc4 = new byte[4];\n\n while (raw.hasRemaining()) {\n int rem = Math.min(3, raw.remaining());\n raw.get(raw3, 0, rem);\n Base64.encode3to4(enc4, raw3, rem, Base64.NO_OPTIONS);\n for (int i = 0; i < 4; i++) {\n encoded.put((char) (enc4[i] & 0xFF));\n }\n } // end input remaining\n }\n\n\n /**\n * Serializes an object and returns the Base64-encoded version of that serialized object.\n * <p>As of v 2.3, if the object cannot be serialized or there is another error, the method will\n * throw an java.io.IOException. <b>This is new to v2.3!</b> In earlier versions, it just\n * returned a null value, but in retrospect that's a pretty poor way to handle it.</p>\n *\n * The object is not GZip-compressed before being encoded.\n *\n * @param serializableObject The object to encode\n * @return The Base64-encoded object\n * @throws java.io.IOException if there is an error\n * @throws NullPointerException if serializedObject is null\n * @since 1.4\n */\n public static String encodeObject(java.io.Serializable serializableObject)\n throws java.io.IOException {\n return encodeObject(serializableObject, NO_OPTIONS);\n } // end encodeObject\n\n\n /**\n * Serializes an object and returns the Base64-encoded version of that serialized object.\n * <p>As of v 2.3, if the object cannot be serialized or there is another error, the method will\n * throw an java.io.IOException. <b>This is new to v2.3!</b> In earlier versions, it just\n * returned a null value, but in retrospect that's a pretty poor way to handle it.</p>\n *\n * The object is not GZip-compressed before being encoded.\n *\n * Example options:<pre>\n * GZIP: gzip-compresses object before encoding it.\n * DO_BREAK_LINES: break lines at 76 characters\n * </pre>\n *\n * Example: <code>encodeObject( myObj, Base64.GZIP )</code> or\n *\n * Example: <code>encodeObject( myObj, Base64.GZIP | Base64.DO_BREAK_LINES )</code>\n *\n * @param serializableObject The object to encode\n * @param options Specified options\n * @return The Base64-encoded object\n * @throws java.io.IOException if there is an error\n * @see Base64#GZIP\n * @see Base64#DO_BREAK_LINES\n * @since 2.0\n */\n public static String encodeObject(java.io.Serializable serializableObject, int options)\n throws java.io.IOException {\n\n if (serializableObject == null) {\n throw new NullPointerException(\"Cannot serialize a null object.\");\n } // end if: null\n\n // Streams\n java.io.ByteArrayOutputStream baos = null;\n java.io.OutputStream b64os = null;\n java.util.zip.GZIPOutputStream gzos = null;\n java.io.ObjectOutputStream oos = null;\n\n\n try {\n // ObjectOutputStream -> (GZIP) -> Base64 -> ByteArrayOutputStream\n baos = new java.io.ByteArrayOutputStream();\n b64os = new Base64.OutputStream(baos, ENCODE | options);\n if ((options & GZIP) != 0) {\n // Gzip\n gzos = new java.util.zip.GZIPOutputStream(b64os);\n oos = new java.io.ObjectOutputStream(gzos);\n } else {\n // Not gzipped\n oos = new java.io.ObjectOutputStream(b64os);\n }\n oos.writeObject(serializableObject);\n } // end try\n catch (java.io.IOException e) {\n // Catch it and then throw it immediately so that\n // the finally{} block is called for cleanup.\n throw e;\n } // end catch\n finally {\n try {\n oos.close();\n } catch (Exception e) {\n }\n try {\n gzos.close();\n } catch (Exception e) {\n }\n try {\n b64os.close();\n } catch (Exception e) {\n }\n try {\n baos.close();\n } catch (Exception e) {\n }\n } // end finally\n\n // Return value according to relevant encoding.\n try {\n return new String(baos.toByteArray(), PREFERRED_ENCODING);\n } // end try\n catch (java.io.UnsupportedEncodingException uue) {\n // Fall back to some Java default\n return new String(baos.toByteArray());\n } // end catch\n\n } // end encode\n\n\n /**\n * Encodes a byte array into Base64 notation. Does not GZip-compress data.\n *\n * @param source The data to convert\n * @return The data in Base64-encoded form\n * @throws NullPointerException if source array is null\n * @since 1.4\n */\n public static String encodeBytes(byte[] source) {\n // Since we're not going to have the GZIP encoding turned on,\n // we're not going to have an java.io.IOException thrown, so\n // we should not force the user to have to catch it.\n String encoded = null;\n try {\n encoded = encodeBytes(source, 0, source.length, NO_OPTIONS);\n } catch (java.io.IOException ex) {\n assert false : ex.getMessage();\n } // end catch\n assert encoded != null;\n return encoded;\n } // end encodeBytes\n\n\n /**\n * Encodes a byte array into Base64 notation. <p>\n * Example options:<pre>\n * GZIP: gzip-compresses object before encoding it.\n * DO_BREAK_LINES: break lines at 76 characters\n * <i>Note: Technically, this makes your encoding non-compliant.</i>\n * </pre>\n * <p> Example: <code>encodeBytes( myData, Base64.GZIP )</code> or <p> Example:\n * <code>encodeBytes( myData, Base64.GZIP | Base64.DO_BREAK_LINES )</code> <p>As of v\n * 2.3, if there is an error with the GZIP stream, the method will throw an java.io.IOException.\n * <b>This is new to v2.3!</b> In earlier versions, it just returned a null value, but in\n * retrospect that's a pretty poor way to handle it.</p>\n *\n * @param source The data to convert\n * @param options Specified options\n * @return The Base64-encoded data as a String\n * @throws java.io.IOException if there is an error\n * @throws NullPointerException if source array is null\n * @see Base64#GZIP\n * @see Base64#DO_BREAK_LINES\n * @since 2.0\n */\n public static String encodeBytes(byte[] source, int options) throws java.io.IOException {\n return encodeBytes(source, 0, source.length, options);\n } // end encodeBytes\n\n\n /**\n * Encodes a byte array into Base64 notation. Does not GZip-compress data. <p>As of v 2.3,\n * if there is an error, the method will throw an java.io.IOException. <b>This is new to\n * v2.3!</b> In earlier versions, it just returned a null value, but in retrospect that's a\n * pretty poor way to handle it.</p>\n *\n * @param source The data to convert\n * @param off Offset in array where conversion should begin\n * @param len Length of data to convert\n * @return The Base64-encoded data as a String\n * @throws NullPointerException if source array is null\n * @throws IllegalArgumentException if source array, offset, or length are invalid\n * @since 1.4\n */\n public static String encodeBytes(byte[] source, int off, int len) {\n // Since we're not going to have the GZIP encoding turned on,\n // we're not going to have an java.io.IOException thrown, so\n // we should not force the user to have to catch it.\n String encoded = null;\n try {\n encoded = encodeBytes(source, off, len, NO_OPTIONS);\n } catch (java.io.IOException ex) {\n assert false : ex.getMessage();\n } // end catch\n assert encoded != null;\n return encoded;\n } // end encodeBytes\n\n\n /**\n * Encodes a byte array into Base64 notation. <p>\n * Example options:<pre>\n * GZIP: gzip-compresses object before encoding it.\n * DO_BREAK_LINES: break lines at 76 characters\n * <i>Note: Technically, this makes your encoding non-compliant.</i>\n * </pre>\n * <p> Example: <code>encodeBytes( myData, Base64.GZIP )</code> or <p> Example:\n * <code>encodeBytes( myData, Base64.GZIP | Base64.DO_BREAK_LINES )</code> <p>As of v\n * 2.3, if there is an error with the GZIP stream, the method will throw an java.io.IOException.\n * <b>This is new to v2.3!</b> In earlier versions, it just returned a null value, but in\n * retrospect that's a pretty poor way to handle it.</p>\n *\n * @param source The data to convert\n * @param off Offset in array where conversion should begin\n * @param len Length of data to convert\n * @param options Specified options\n * @return The Base64-encoded data as a String\n * @throws java.io.IOException if there is an error\n * @throws NullPointerException if source array is null\n * @throws IllegalArgumentException if source array, offset, or length are invalid\n * @see Base64#GZIP\n * @see Base64#DO_BREAK_LINES\n * @since 2.0\n */\n public static String encodeBytes(byte[] source, int off, int len, int options)\n throws java.io.IOException {\n byte[] encoded = encodeBytesToBytes(source, off, len, options);\n\n // Return value according to relevant encoding.\n try {\n return new String(encoded, PREFERRED_ENCODING);\n } // end try\n catch (java.io.UnsupportedEncodingException uue) {\n return new String(encoded);\n } // end catch\n\n } // end encodeBytes\n\n\n /**\n * Similar to {@link #encodeBytes(byte[])} but returns a byte array instead of instantiating a\n * String. This is more efficient if you're working with I/O streams and have large data sets to\n * encode.\n *\n * @param source The data to convert\n * @return The Base64-encoded data as a byte[] (of ASCII characters)\n * @throws NullPointerException if source array is null\n * @since 2.3.1\n */\n public static byte[] encodeBytesToBytes(byte[] source) {\n byte[] encoded = null;\n try {\n encoded = encodeBytesToBytes(source, 0, source.length, Base64.NO_OPTIONS);\n } catch (java.io.IOException ex) {\n assert false :\n \"IOExceptions only come from GZipping, which is turned off: \" + ex.getMessage();\n }\n return encoded;\n }\n\n\n /**\n * Similar to {@link #encodeBytes(byte[], int, int, int)} but returns a byte array instead of\n * instantiating a String. This is more efficient if you're working with I/O streams and have\n * large data sets to encode.\n *\n * @param source The data to convert\n * @param off Offset in array where conversion should begin\n * @param len Length of data to convert\n * @param options Specified options\n * @return The Base64-encoded data as a String\n * @throws java.io.IOException if there is an error\n * @throws NullPointerException if source array is null\n * @throws IllegalArgumentException if source array, offset, or length are invalid\n * @see Base64#GZIP\n * @see Base64#DO_BREAK_LINES\n * @since 2.3.1\n */\n public static byte[] encodeBytesToBytes(byte[] source, int off, int len, int options)\n throws java.io.IOException {\n\n if (source == null) {\n throw new NullPointerException(\"Cannot serialize a null array.\");\n } // end if: null\n\n if (off < 0) {\n throw new IllegalArgumentException(\"Cannot have negative offset: \" + off);\n } // end if: off < 0\n\n if (len < 0) {\n throw new IllegalArgumentException(\"Cannot have length offset: \" + len);\n } // end if: len < 0\n\n if (off + len > source.length) {\n throw new IllegalArgumentException(\n String.format(\n \"Cannot have offset of %d and length of %d with array of length %d\",\n off, len, source.length));\n } // end if: off < 0\n\n\n // Compress?\n if ((options & GZIP) != 0) {\n java.io.ByteArrayOutputStream baos = null;\n java.util.zip.GZIPOutputStream gzos = null;\n Base64.OutputStream b64os = null;\n\n try {\n // GZip -> Base64 -> ByteArray\n baos = new java.io.ByteArrayOutputStream();\n b64os = new Base64.OutputStream(baos, ENCODE | options);\n gzos = new java.util.zip.GZIPOutputStream(b64os);\n\n gzos.write(source, off, len);\n gzos.close();\n } // end try\n catch (java.io.IOException e) {\n // Catch it and then throw it immediately so that\n // the finally{} block is called for cleanup.\n throw e;\n } // end catch\n finally {\n try {\n gzos.close();\n } catch (Exception e) {\n }\n try {\n b64os.close();\n } catch (Exception e) {\n }\n try {\n baos.close();\n } catch (Exception e) {\n }\n } // end finally\n\n return baos.toByteArray();\n } // end if: compress\n\n // Else, don't compress. Better not to use streams at all then.\n else {\n boolean breakLines = (options & DO_BREAK_LINES) != 0;\n\n //int len43 = len * 4 / 3;\n //byte[] outBuff = new byte[ ( len43 ) // Main 4:3\n // + ( (len % 3) > 0 ? 4 : 0 ) // Account for padding\n // + (breakLines ? ( len43 / MAX_LINE_LENGTH ) : 0) ]; //\n // New lines\n // Try to determine more precisely how big the array needs to be.\n // If we get it right, we don't have to do an array copy, and\n // we save a bunch of memory.\n int encLen = (len / 3) * 4 + (len % 3 > 0 ? 4 : 0); // Bytes needed for actual encoding\n if (breakLines) {\n encLen += encLen / MAX_LINE_LENGTH; // Plus extra newline characters\n }\n byte[] outBuff = new byte[encLen];\n\n\n int d = 0;\n int e = 0;\n int len2 = len - 2;\n int lineLength = 0;\n for (; d < len2; d += 3, e += 4) {\n encode3to4(source, d + off, 3, outBuff, e, options);\n\n lineLength += 4;\n if (breakLines && lineLength >= MAX_LINE_LENGTH) {\n outBuff[e + 4] = NEW_LINE;\n e++;\n lineLength = 0;\n } // end if: end of line\n } // en dfor: each piece of array\n\n if (d < len) {\n encode3to4(source, d + off, len - d, outBuff, e, options);\n e += 4;\n } // end if: some padding needed\n\n\n // Only resize array if we didn't guess it right.\n if (e <= outBuff.length - 1) {\n // If breaking lines and the last byte falls right at\n // the line length (76 bytes per line), there will be\n // one extra byte, and the array will need to be resized.\n // Not too bad of an estimate on array size, I'd say.\n byte[] finalOut = new byte[e];\n System.arraycopy(outBuff, 0, finalOut, 0, e);\n //System.err.println(\"Having to resize array from \" + outBuff.length + \" to \" + e );\n return finalOut;\n } else {\n //System.err.println(\"No need to resize array.\");\n return outBuff;\n }\n\n } // end else: don't compress\n\n } // end encodeBytesToBytes\n\n\n\n\n\n/* ******** D E C O D I N G M E T H O D S ******** */\n\n\n /**\n * Decodes four bytes from array <var>source</var> and writes the resulting bytes (up to three\n * of them) to <var>destination</var>. The source and destination arrays can be manipulated\n * anywhere along their length by specifying <var>srcOffset</var> and <var>destOffset</var>.\n * This method does not check to make sure your arrays are large enough to accomodate\n * <var>srcOffset</var> + 4 for the <var>source</var> array or <var>destOffset</var> + 3 for the\n * <var>destination</var> array. This method returns the actual number of bytes that were\n * converted from the Base64 encoding. <p>This is the lowest level of the decoding methods with\n * all possible parameters.</p>\n *\n * @param source the array to convert\n * @param srcOffset the index where conversion begins\n * @param destination the array to hold the conversion\n * @param destOffset the index where output will be put\n * @param options alphabet type is pulled from this (standard, url-safe, ordered)\n * @return the number of decoded bytes converted\n * @throws NullPointerException if source or destination arrays are null\n * @throws IllegalArgumentException if srcOffset or destOffset are invalid or there is not\n * enough room in the array.\n * @since 1.3\n */\n private static int decode4to3(\n byte[] source, int srcOffset,\n byte[] destination, int destOffset, int options) {\n\n // Lots of error checking and exception throwing\n if (source == null) {\n throw new NullPointerException(\"Source array was null.\");\n } // end if\n if (destination == null) {\n throw new NullPointerException(\"Destination array was null.\");\n } // end if\n if (srcOffset < 0 || srcOffset + 3 >= source.length) {\n throw new IllegalArgumentException(String.format(\n \"Source array with length %d cannot have offset of %d and still process four \" +\n \"bytes.\",\n source.length, srcOffset));\n } // end if\n if (destOffset < 0 || destOffset + 2 >= destination.length) {\n throw new IllegalArgumentException(String.format(\n \"Destination array with length %d cannot have offset of %d and still store \" +\n \"three bytes.\",\n destination.length, destOffset));\n } // end if\n\n\n byte[] DECODABET = getDecodabet(options);\n\n // Example: Dk==\n if (source[srcOffset + 2] == EQUALS_SIGN) {\n // Two ways to do the same thing. Don't know which way I like best.\n //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )\n // | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 );\n int outBuff = ((DECODABET[source[srcOffset]] & 0xFF) << 18)\n | ((DECODABET[source[srcOffset + 1]] & 0xFF) << 12);\n\n destination[destOffset] = (byte) (outBuff >>> 16);\n return 1;\n }\n\n // Example: DkL=\n else if (source[srcOffset + 3] == EQUALS_SIGN) {\n // Two ways to do the same thing. Don't know which way I like best.\n //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )\n // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )\n // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 );\n int outBuff = ((DECODABET[source[srcOffset]] & 0xFF) << 18)\n | ((DECODABET[source[srcOffset + 1]] & 0xFF) << 12)\n | ((DECODABET[source[srcOffset + 2]] & 0xFF) << 6);\n\n destination[destOffset] = (byte) (outBuff >>> 16);\n destination[destOffset + 1] = (byte) (outBuff >>> 8);\n return 2;\n }\n\n // Example: DkLE\n else {\n // Two ways to do the same thing. Don't know which way I like best.\n //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )\n // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )\n // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 )\n // | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 );\n int outBuff = ((DECODABET[source[srcOffset]] & 0xFF) << 18)\n | ((DECODABET[source[srcOffset + 1]] & 0xFF) << 12)\n | ((DECODABET[source[srcOffset + 2]] & 0xFF) << 6)\n | ((DECODABET[source[srcOffset + 3]] & 0xFF));\n\n\n destination[destOffset] = (byte) (outBuff >> 16);\n destination[destOffset + 1] = (byte) (outBuff >> 8);\n destination[destOffset + 2] = (byte) (outBuff);\n\n return 3;\n }\n } // end decodeToBytes\n\n\n /**\n * Low-level access to decoding ASCII characters in the form of a byte array. <strong>Ignores\n * GUNZIP option, if it's set.</strong> This is not generally a recommended method, although it\n * is used internally as part of the decoding process. Special case: if len = 0, an empty array\n * is returned. Still, if you need more speed and reduced memory footprint (and aren't\n * gzipping), consider this method.\n *\n * @param source The Base64 encoded data\n * @return decoded data\n * @since 2.3.1\n */\n public static byte[] decode(byte[] source)\n throws java.io.IOException {\n byte[] decoded = null;\n// try {\n decoded = decode(source, 0, source.length, Base64.NO_OPTIONS);\n// } catch( java.io.IOException ex ) {\n// assert false : \"IOExceptions only come from GZipping,\n// which is turned off: \" + ex.getMessage();\n// }\n return decoded;\n }\n\n\n /**\n * Low-level access to decoding ASCII characters in the form of a byte array. <strong>Ignores\n * GUNZIP option, if it's set.</strong> This is not generally a recommended method, although it\n * is used internally as part of the decoding process. Special case: if len = 0, an empty array\n * is returned. Still, if you need more speed and reduced memory footprint (and aren't\n * gzipping), consider this method.\n *\n * @param source The Base64 encoded data\n * @param off The offset of where to begin decoding\n * @param len The length of characters to decode\n * @param options Can specify options such as alphabet type to use\n * @return decoded data\n * @throws java.io.IOException If bogus characters exist in source data\n * @since 1.3\n */\n public static byte[] decode(byte[] source, int off, int len, int options)\n throws java.io.IOException {\n\n // Lots of error checking and exception throwing\n if (source == null) {\n throw new NullPointerException(\"Cannot decode null source array.\");\n } // end if\n if (off < 0 || off + len > source.length) {\n throw new IllegalArgumentException(String.format(\n \"Source array with length %d cannot have offset of %d and process %d bytes.\",\n source.length, off, len));\n } // end if\n\n if (len == 0) {\n return new byte[0];\n } else if (len < 4) {\n throw new IllegalArgumentException(\n \"Base64-encoded string must have at least four characters, \" +\n \"but length specified was \" +\n len);\n } // end if\n\n byte[] DECODABET = getDecodabet(options);\n\n int len34 = len * 3 / 4; // Estimate on array size\n byte[] outBuff = new byte[len34]; // Upper limit on size of output\n int outBuffPosn = 0; // Keep track of where we're writing\n\n byte[] b4 = new byte[4]; // Four byte buffer from source, eliminating white space\n int b4Posn = 0; // Keep track of four byte input buffer\n int i = 0; // Source array counter\n byte sbiDecode = 0; // Special value from DECODABET\n\n for (i = off; i < off + len; i++) { // Loop through source\n\n sbiDecode = DECODABET[source[i] & 0xFF];\n\n // White space, Equals sign, or legit Base64 character\n // Note the values such as -5 and -9 in the\n // DECODABETs at the top of the file.\n if (sbiDecode >= WHITE_SPACE_ENC) {\n if (sbiDecode >= EQUALS_SIGN_ENC) {\n b4[b4Posn++] = source[i]; // Save non-whitespace\n if (b4Posn > 3) { // Time to decode?\n outBuffPosn += decode4to3(b4, 0, outBuff, outBuffPosn, options);\n b4Posn = 0;\n\n // If that was the equals sign, break out of 'for' loop\n if (source[i] == EQUALS_SIGN) {\n break;\n } // end if: equals sign\n } // end if: quartet built\n } // end if: equals sign or better\n } // end if: white space, equals sign or better\n else {\n // There's a bad input character in the Base64 stream.\n throw new java.io.IOException(String.format(\n \"Bad Base64 input character decimal %d in array position %d\",\n ((int) source[i]) & 0xFF, i));\n } // end else:\n } // each input character\n\n byte[] out = new byte[outBuffPosn];\n System.arraycopy(outBuff, 0, out, 0, outBuffPosn);\n return out;\n } // end decode\n\n\n /**\n * Decodes data from Base64 notation, automatically detecting gzip-compressed data and\n * decompressing it.\n *\n * @param s the string to decode\n * @return the decoded data\n * @throws java.io.IOException If there is a problem\n * @since 1.4\n */\n public static byte[] decode(String s) throws java.io.IOException {\n return decode(s, NO_OPTIONS);\n }\n\n\n /**\n * Decodes data from Base64 notation, automatically detecting gzip-compressed data and\n * decompressing it.\n *\n * @param s the string to decode\n * @param options encode options such as URL_SAFE\n * @return the decoded data\n * @throws java.io.IOException if there is an error\n * @throws NullPointerException if <code>s</code> is null\n * @since 1.4\n */\n public static byte[] decode(String s, int options) throws java.io.IOException {\n\n if (s == null) {\n throw new NullPointerException(\"Input string was null.\");\n } // end if\n\n byte[] bytes;\n try {\n bytes = s.getBytes(PREFERRED_ENCODING);\n } // end try\n catch (java.io.UnsupportedEncodingException uee) {\n bytes = s.getBytes();\n } // end catch\n //</change>\n\n // Decode\n bytes = decode(bytes, 0, bytes.length, options);\n\n // Check to see if it's gzip-compressed\n // GZIP Magic Two-Byte Number: 0x8b1f (35615)\n boolean dontGunzip = (options & DONT_GUNZIP) != 0;\n if ((bytes != null) && (bytes.length >= 4) && (!dontGunzip)) {\n\n int head = ((int) bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00);\n if (java.util.zip.GZIPInputStream.GZIP_MAGIC == head) {\n java.io.ByteArrayInputStream bais = null;\n java.util.zip.GZIPInputStream gzis = null;\n java.io.ByteArrayOutputStream baos = null;\n byte[] buffer = new byte[2048];\n int length = 0;\n\n try {\n baos = new java.io.ByteArrayOutputStream();\n bais = new java.io.ByteArrayInputStream(bytes);\n gzis = new java.util.zip.GZIPInputStream(bais);\n\n while ((length = gzis.read(buffer)) >= 0) {\n baos.write(buffer, 0, length);\n } // end while: reading input\n\n // No error? Get new bytes.\n bytes = baos.toByteArray();\n\n } // end try\n catch (java.io.IOException e) {\n e.printStackTrace();\n // Just return originally-decoded bytes\n } // end catch\n finally {\n try {\n baos.close();\n } catch (Exception e) {\n }\n try {\n gzis.close();\n } catch (Exception e) {\n }\n try {\n bais.close();\n } catch (Exception e) {\n }\n } // end finally\n\n } // end if: gzipped\n } // end if: bytes.length >= 2\n\n return bytes;\n } // end decode\n\n\n /**\n * Attempts to decode Base64 data and deserialize a Java Object within. Returns <code>null</code> if\n * there was an error.\n *\n * @param encodedObject The Base64 data to decode\n * @return The decoded and deserialized object\n * @throws NullPointerException if encodedObject is null\n * @throws java.io.IOException if there is a general error\n * @throws ClassNotFoundException if the decoded object is of a class that cannot be found by\n * the JVM\n * @since 1.5\n */\n public static Object decodeToObject(String encodedObject)\n throws java.io.IOException, java.lang.ClassNotFoundException {\n return decodeToObject(encodedObject, NO_OPTIONS, null);\n }\n\n\n /**\n * Attempts to decode Base64 data and deserialize a Java Object within. Returns <code>null</code> if\n * there was an error. If <code>loader</code> is not null, it will be the class loader used when\n * deserializing.\n *\n * @param encodedObject The Base64 data to decode\n * @param options Various parameters related to decoding\n * @param loader Optional class loader to use in deserializing classes.\n * @return The decoded and deserialized object\n * @throws NullPointerException if encodedObject is null\n * @throws java.io.IOException if there is a general error\n * @throws ClassNotFoundException if the decoded object is of a class that cannot be found by\n * the JVM\n * @since 2.3.4\n */\n public static Object decodeToObject(\n String encodedObject, int options, final ClassLoader loader)\n throws java.io.IOException, java.lang.ClassNotFoundException {\n\n // Decode and gunzip if necessary\n byte[] objBytes = decode(encodedObject, options);\n\n java.io.ByteArrayInputStream bais = null;\n java.io.ObjectInputStream ois = null;\n Object obj = null;\n\n try {\n bais = new java.io.ByteArrayInputStream(objBytes);\n\n // If no custom class loader is provided, use Java's builtin OIS.\n if (loader == null) {\n ois = new java.io.ObjectInputStream(bais);\n } // end if: no loader provided\n\n // Else make a customized object input stream that uses\n // the provided class loader.\n else {\n ois = new java.io.ObjectInputStream(bais) {\n @Override\n public Class<?> resolveClass(java.io.ObjectStreamClass streamClass)\n throws java.io.IOException, ClassNotFoundException {\n Class<?> c = Class.forName(streamClass.getName(), false, loader);\n if (c == null) {\n return super.resolveClass(streamClass);\n } else {\n return c; // Class loader knows of this class.\n } // end else: not null\n } // end resolveClass\n }; // end ois\n } // end else: no custom class loader\n\n obj = ois.readObject();\n } // end try\n catch (java.io.IOException | ClassNotFoundException e) {\n throw e; // Catch and throw in order to execute finally{}\n } // end catch\n // end catch\n finally {\n try {\n bais.close();\n } catch (Exception e) {\n }\n try {\n ois.close();\n } catch (Exception e) {\n }\n } // end finally\n\n return obj;\n } // end decodeObject\n\n\n /**\n * Convenience method for encoding data to a file. <p>As of v 2.3, if there is a error, the\n * method will throw an java.io.IOException. <b>This is new to v2.3!</b> In earlier versions, it\n * just returned false, but in retrospect that's a pretty poor way to handle it.</p>\n *\n * @param dataToEncode byte array of data to encode in base64 form\n * @param filename Filename for saving encoded data\n * @throws java.io.IOException if there is an error\n * @throws NullPointerException if dataToEncode is null\n * @since 2.1\n */\n public static void encodeToFile(byte[] dataToEncode, String filename)\n throws java.io.IOException {\n\n if (dataToEncode == null) {\n throw new NullPointerException(\"Data to encode was null.\");\n } // end iff\n\n Base64.OutputStream bos = null;\n try {\n bos = new Base64.OutputStream(\n new java.io.FileOutputStream(filename), Base64.ENCODE);\n bos.write(dataToEncode);\n } // end try\n catch (java.io.IOException e) {\n throw e; // Catch and throw to execute finally{} block\n } // end catch: java.io.IOException\n finally {\n try {\n bos.close();\n } catch (Exception e) {\n }\n } // end finally\n\n } // end encodeToFile\n\n\n /**\n * Convenience method for decoding data to a file. <p>As of v 2.3, if there is a error, the\n * method will throw an java.io.IOException. <b>This is new to v2.3!</b> In earlier versions, it\n * just returned false, but in retrospect that's a pretty poor way to handle it.</p>\n *\n * @param dataToDecode Base64-encoded data as a string\n * @param filename Filename for saving decoded data\n * @throws java.io.IOException if there is an error\n * @since 2.1\n */\n public static void decodeToFile(String dataToDecode, String filename)\n throws java.io.IOException {\n\n Base64.OutputStream bos = null;\n try {\n bos = new Base64.OutputStream(\n new java.io.FileOutputStream(filename), Base64.DECODE);\n bos.write(dataToDecode.getBytes(PREFERRED_ENCODING));\n } // end try\n catch (java.io.IOException e) {\n throw e; // Catch and throw to execute finally{} block\n } // end catch: java.io.IOException\n finally {\n try {\n bos.close();\n } catch (Exception e) {\n }\n } // end finally\n\n } // end decodeToFile\n\n\n /**\n * Convenience method for reading a base64-encoded file and decoding it. <p>As of v 2.3, if\n * there is a error, the method will throw an java.io.IOException. <b>This is new to v2.3!</b>\n * In earlier versions, it just returned false, but in retrospect that's a pretty poor way to\n * handle it.</p>\n *\n * @param filename Filename for reading encoded data\n * @return decoded byte array\n * @throws java.io.IOException if there is an error\n * @since 2.1\n */\n public static byte[] decodeFromFile(String filename)\n throws java.io.IOException {\n\n byte[] decodedData = null;\n Base64.InputStream bis = null;\n try {\n // Set up some useful variables\n java.io.File file = new java.io.File(filename);\n byte[] buffer = null;\n int length = 0;\n int numBytes = 0;\n\n // Check for size of file\n if (file.length() > Integer.MAX_VALUE) {\n throw new java.io.IOException(\n \"File is too big for this convenience method (\" + file.length() +\n \" bytes).\");\n } // end if: file too big for int index\n buffer = new byte[(int) file.length()];\n\n // Open a stream\n bis = new Base64.InputStream(\n new java.io.BufferedInputStream(\n new java.io.FileInputStream(file)), Base64.DECODE);\n\n // Read until done\n while ((numBytes = bis.read(buffer, length, 4096)) >= 0) {\n length += numBytes;\n } // end while\n\n // Save in a variable to return\n decodedData = new byte[length];\n System.arraycopy(buffer, 0, decodedData, 0, length);\n\n } // end try\n catch (java.io.IOException e) {\n throw e; // Catch and release to execute finally{}\n } // end catch: java.io.IOException\n finally {\n try {\n bis.close();\n } catch (Exception e) {\n }\n } // end finally\n\n return decodedData;\n } // end decodeFromFile\n\n\n /**\n * Convenience method for reading a binary file and base64-encoding it. <p>As of v 2.3, if\n * there is a error, the method will throw an java.io.IOException. <b>This is new to v2.3!</b>\n * In earlier versions, it just returned false, but in retrospect that's a pretty poor way to\n * handle it.</p>\n *\n * @param filename Filename for reading binary data\n * @return base64-encoded string\n * @throws java.io.IOException if there is an error\n * @since 2.1\n */\n public static String encodeFromFile(String filename)\n throws java.io.IOException {\n\n String encodedData = null;\n Base64.InputStream bis = null;\n try {\n // Set up some useful variables\n java.io.File file = new java.io.File(filename);\n byte[] buffer = new byte[Math.max((int) (file.length() * 1.4 + 1),\n 40)]; // Need max() for math on small files (v2.2.1); Need +1 for a few\n // corner cases (v2.3.5)\n int length = 0;\n int numBytes = 0;\n\n // Open a stream\n bis = new Base64.InputStream(\n new java.io.BufferedInputStream(\n new java.io.FileInputStream(file)), Base64.ENCODE);\n\n // Read until done\n while ((numBytes = bis.read(buffer, length, 4096)) >= 0) {\n length += numBytes;\n } // end while\n\n // Save in a variable to return\n encodedData = new String(buffer, 0, length, Base64.PREFERRED_ENCODING);\n\n } // end try\n catch (java.io.IOException e) {\n throw e; // Catch and release to execute finally{}\n } // end catch: java.io.IOException\n finally {\n try {\n bis.close();\n } catch (Exception e) {\n }\n } // end finally\n\n return encodedData;\n } // end encodeFromFile\n\n /**\n * Reads <code>infile</code> and encodes it to <code>outfile</code>.\n *\n * @param infile Input file\n * @param outfile Output file\n * @throws java.io.IOException if there is an error\n * @since 2.2\n */\n public static void encodeFileToFile(String infile, String outfile)\n throws java.io.IOException {\n\n String encoded = Base64.encodeFromFile(infile);\n java.io.OutputStream out = null;\n try {\n out = new java.io.BufferedOutputStream(\n new java.io.FileOutputStream(outfile));\n out.write(encoded.getBytes(\"US-ASCII\")); // Strict, 7-bit output.\n } // end try\n catch (java.io.IOException e) {\n throw e; // Catch and release to execute finally{}\n } // end catch\n finally {\n try {\n out.close();\n } catch (Exception ex) {\n }\n } // end finally\n } // end encodeFileToFile\n\n\n /**\n * Reads <code>infile</code> and decodes it to <code>outfile</code>.\n *\n * @param infile Input file\n * @param outfile Output file\n * @throws java.io.IOException if there is an error\n * @since 2.2\n */\n public static void decodeFileToFile(String infile, String outfile)\n throws java.io.IOException {\n\n byte[] decoded = Base64.decodeFromFile(infile);\n java.io.OutputStream out = null;\n try {\n out = new java.io.BufferedOutputStream(\n new java.io.FileOutputStream(outfile));\n out.write(decoded);\n } // end try\n catch (java.io.IOException e) {\n throw e; // Catch and release to execute finally{}\n } // end catch\n finally {\n try {\n out.close();\n } catch (Exception ex) {\n }\n } // end finally\n } // end decodeFileToFile\n\n\n /* ******** I N N E R C L A S S I N P U T S T R E A M ******** */\n\n\n /**\n * A {@link Base64.InputStream} will read data from another <code>java.io.InputStream</code>, given\n * in the constructor, and encode/decode to/from Base64 notation on the fly.\n *\n * @see Base64\n * @since 1.3\n */\n @SuppressWarnings(\"UnusedAssignment\")\n public static class InputStream extends java.io.FilterInputStream {\n\n private boolean encode; // Encoding or decoding\n private int position; // Current position in the buffer\n private byte[] buffer; // Small buffer holding converted data\n private int bufferLength; // Length of buffer (3 or 4)\n private int numSigBytes; // Number of meaningful bytes in the buffer\n private int lineLength;\n private boolean breakLines; // Break lines at less than 80 characters\n private int options; // Record options used to create the stream.\n private byte[] decodabet; // Local copies to avoid extra method calls\n\n\n /**\n * Constructs a {@link Base64.InputStream} in DECODE mode.\n *\n * @param in the <code>java.io.InputStream</code> from which to read data.\n * @since 1.3\n */\n public InputStream(java.io.InputStream in) {\n this(in, DECODE);\n } // end constructor\n\n\n /**\n * Constructs a {@link Base64.InputStream} in either ENCODE or DECODE mode.\n *\n * Valid options:<pre>\n * ENCODE or DECODE: Encode or Decode as data is read.\n * DO_BREAK_LINES: break lines at 76 characters\n * <i>(only meaningful when encoding)</i>\n * </pre>\n *\n * Example: <code>new Base64.InputStream( in, Base64.DECODE )</code>\n *\n * @param in the <code>java.io.InputStream</code> from which to read data.\n * @param options Specified options\n * @see Base64#ENCODE\n * @see Base64#DECODE\n * @see Base64#DO_BREAK_LINES\n * @since 2.0\n */\n public InputStream(java.io.InputStream in, int options) {\n\n super(in);\n this.options = options; // Record for later\n this.breakLines = (options & DO_BREAK_LINES) > 0;\n this.encode = (options & ENCODE) > 0;\n this.bufferLength = encode ? 4 : 3;\n this.buffer = new byte[bufferLength];\n this.position = -1;\n this.lineLength = 0;\n this.decodabet = getDecodabet(options);\n } // end constructor\n\n /**\n * Reads enough of the input stream to convert to/from Base64 and returns the next byte.\n *\n * @return next byte\n * @since 1.3\n */\n @Override\n public int read() throws java.io.IOException {\n\n // Do we need to get data?\n if (position < 0) {\n if (encode) {\n byte[] b3 = new byte[3];\n int numBinaryBytes = 0;\n for (int i = 0; i < 3; i++) {\n int b = in.read();\n\n // If end of stream, b is -1.\n if (b >= 0) {\n b3[i] = (byte) b;\n numBinaryBytes++;\n } else {\n break; // out of for loop\n } // end else: end of stream\n\n } // end for: each needed input byte\n\n if (numBinaryBytes > 0) {\n encode3to4(b3, 0, numBinaryBytes, buffer, 0, options);\n position = 0;\n numSigBytes = 4;\n } // end if: got data\n else {\n return -1; // Must be end of stream\n } // end else\n } // end if: encoding\n\n // Else decoding\n else {\n byte[] b4 = new byte[4];\n int i = 0;\n for (i = 0; i < 4; i++) {\n // Read four \"meaningful\" bytes:\n int b = 0;\n do {\n b = in.read();\n }\n while (b >= 0 && decodabet[b & 0x7f] <= WHITE_SPACE_ENC);\n\n if (b < 0) {\n break; // Reads a -1 if end of stream\n } // end if: end of stream\n\n b4[i] = (byte) b;\n } // end for: each needed input byte\n\n if (i == 4) {\n numSigBytes = decode4to3(b4, 0, buffer, 0, options);\n position = 0;\n } // end if: got four characters\n else if (i == 0) {\n return -1;\n } // end else if: also padded correctly\n else {\n // Must have broken out from above.\n throw new java.io.IOException(\"Improperly padded Base64 input.\");\n } // end\n\n } // end else: decode\n } // end else: get data\n\n // Got data?\n if (position >= 0) {\n // End of relevant data?\n if ( /*!encode &&*/ position >= numSigBytes) {\n return -1;\n } // end if: got data\n\n if (encode && breakLines && lineLength >= MAX_LINE_LENGTH) {\n lineLength = 0;\n return '\\n';\n } // end if\n else {\n lineLength++; // This isn't important when decoding\n // but throwing an extra \"if\" seems\n // just as wasteful.\n\n int b = buffer[position++];\n\n if (position >= bufferLength) {\n position = -1;\n } // end if: end\n\n return b & 0xFF; // This is how you \"cast\" a byte that's\n // intended to be unsigned.\n } // end else\n } // end if: position >= 0\n\n // Else error\n else {\n throw new java.io.IOException(\"Error in Base64 code reading stream.\");\n } // end else\n } // end read\n\n\n /**\n * Calls {@link #read()} repeatedly until the end of stream is reached or <var>len</var>\n * bytes are read. Returns number of bytes read into array or -1 if end of stream is\n * encountered.\n *\n * @param dest array to hold values\n * @param off offset for array\n * @param len max number of bytes to read into array\n * @return bytes read into array or -1 if end of stream is encountered.\n * @since 1.3\n */\n @Override\n public int read(byte[] dest, int off, int len)\n throws java.io.IOException {\n int i;\n int b;\n for (i = 0; i < len; i++) {\n b = read();\n\n if (b >= 0) {\n dest[off + i] = (byte) b;\n } else if (i == 0) {\n return -1;\n } else {\n break; // Out of 'for' loop\n } // Out of 'for' loop\n } // end for: each byte read\n return i;\n } // end read\n\n } // end inner class InputStream\n\n\n\n\n\n\n /* ******** I N N E R C L A S S O U T P U T S T R E A M ******** */\n\n\n /**\n * A {@link Base64.OutputStream} will write data to another <code>java.io.OutputStream</code>, given\n * in the constructor, and encode/decode to/from Base64 notation on the fly.\n *\n * @see Base64\n * @since 1.3\n */\n public static class OutputStream extends java.io.FilterOutputStream {\n\n private boolean encode;\n private int position;\n private byte[] buffer;\n private int bufferLength;\n private int lineLength;\n private boolean breakLines;\n private byte[] b4; // Scratch used in a few places\n private boolean suspendEncoding;\n private int options; // Record for later\n private byte[] decodabet; // Local copies to avoid extra method calls\n\n /**\n * Constructs a {@link Base64.OutputStream} in ENCODE mode.\n *\n * @param out the <code>java.io.OutputStream</code> to which data will be written.\n * @since 1.3\n */\n public OutputStream(java.io.OutputStream out) {\n this(out, ENCODE);\n } // end constructor\n\n\n /**\n * Constructs a {@link Base64.OutputStream} in either ENCODE or DECODE mode.\n *\n * Valid options:<pre>\n * ENCODE or DECODE: Encode or Decode as data is read.\n * DO_BREAK_LINES: don't break lines at 76 characters\n * <i>(only meaningful when encoding)</i>\n * </pre>\n *\n * Example: <code>new Base64.OutputStream( out, Base64.ENCODE )</code>\n *\n * @param out the <code>java.io.OutputStream</code> to which data will be written.\n * @param options Specified options.\n * @see Base64#ENCODE\n * @see Base64#DECODE\n * @see Base64#DO_BREAK_LINES\n * @since 1.3\n */\n public OutputStream(java.io.OutputStream out, int options) {\n super(out);\n this.breakLines = (options & DO_BREAK_LINES) != 0;\n this.encode = (options & ENCODE) != 0;\n this.bufferLength = encode ? 3 : 4;\n this.buffer = new byte[bufferLength];\n this.position = 0;\n this.lineLength = 0;\n this.suspendEncoding = false;\n this.b4 = new byte[4];\n this.options = options;\n this.decodabet = getDecodabet(options);\n } // end constructor\n\n\n /**\n * Writes the byte to the output stream after converting to/from Base64 notation. When\n * encoding, bytes are buffered three at a time before the output stream actually gets a\n * write() call. When decoding, bytes are buffered four at a time.\n *\n * @param theByte the byte to write\n * @since 1.3\n */\n @Override\n public void write(int theByte)\n throws java.io.IOException {\n // Encoding suspended?\n if (suspendEncoding) {\n this.out.write(theByte);\n return;\n } // end if: supsended\n\n // Encode?\n if (encode) {\n buffer[position++] = (byte) theByte;\n if (position >= bufferLength) { // Enough to encode.\n\n this.out.write(encode3to4(b4, buffer, bufferLength, options));\n\n lineLength += 4;\n if (breakLines && lineLength >= MAX_LINE_LENGTH) {\n this.out.write(NEW_LINE);\n lineLength = 0;\n } // end if: end of line\n\n position = 0;\n } // end if: enough to output\n } // end if: encoding\n\n // Else, Decoding\n else {\n // Meaningful Base64 character?\n if (decodabet[theByte & 0x7f] > WHITE_SPACE_ENC) {\n buffer[position++] = (byte) theByte;\n if (position >= bufferLength) { // Enough to output.\n\n int len = Base64.decode4to3(buffer, 0, b4, 0, options);\n out.write(b4, 0, len);\n position = 0;\n } // end if: enough to output\n } // end if: meaningful base64 character\n else if (decodabet[theByte & 0x7f] != WHITE_SPACE_ENC) {\n throw new java.io.IOException(\"Invalid character in Base64 data.\");\n } // end else: not white space either\n } // end else: decoding\n } // end write\n\n\n /**\n * Calls {@link #write(int)} repeatedly until <var>len</var> bytes are written.\n *\n * @param theBytes array from which to read bytes\n * @param off offset for array\n * @param len max number of bytes to read into array\n * @since 1.3\n */\n @Override\n public void write(byte[] theBytes, int off, int len)\n throws java.io.IOException {\n // Encoding suspended?\n if (suspendEncoding) {\n this.out.write(theBytes, off, len);\n return;\n } // end if: supsended\n\n for (int i = 0; i < len; i++) {\n write(theBytes[off + i]);\n } // end for: each byte written\n\n } // end write\n\n\n /**\n * Method added by PHIL. [Thanks, PHIL. -Rob] This pads the buffer without closing the\n * stream.\n *\n * @throws java.io.IOException if there's an error.\n */\n public void flushBase64() throws java.io.IOException {\n if (position > 0) {\n if (encode) {\n out.write(encode3to4(b4, buffer, position, options));\n position = 0;\n } // end if: encoding\n else {\n throw new java.io.IOException(\"Base64 input not properly padded.\");\n } // end else: decoding\n } // end if: buffer partially full\n\n } // end flush\n\n\n /**\n * Flushes and closes (I think, in the superclass) the stream.\n *\n * @since 1.3\n */\n @Override\n public void close() throws java.io.IOException {\n // 1. Ensure that pending characters are written\n flushBase64();\n\n // 2. Actually close the stream\n // Base class both flushes and closes.\n super.close();\n\n buffer = null;\n out = null;\n } // end close\n\n\n /**\n * Suspends encoding of the stream. May be helpful if you need to embed a piece of\n * base64-encoded data in a stream.\n *\n * @throws java.io.IOException if there's an error flushing\n * @since 1.5.1\n */\n public void suspendEncoding() throws java.io.IOException {\n flushBase64();\n this.suspendEncoding = true;\n } // end suspendEncoding\n\n\n /**\n * Resumes encoding of the stream. May be helpful if you need to embed a piece of\n * base64-encoded data in a stream.\n *\n * @since 1.5.1\n */\n public void resumeEncoding() {\n this.suspendEncoding = false;\n } // end resumeEncoding\n\n\n } // end inner class OutputStream\n\n\n} // end class Base64"
] | import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.RSAPublicKeySpec;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import de.geeksfactory.opacclient.i18n.StringProvider;
import de.geeksfactory.opacclient.networking.HttpClientFactory;
import de.geeksfactory.opacclient.objects.Account;
import de.geeksfactory.opacclient.objects.AccountData;
import de.geeksfactory.opacclient.objects.Copy;
import de.geeksfactory.opacclient.objects.Detail;
import de.geeksfactory.opacclient.objects.DetailedItem;
import de.geeksfactory.opacclient.objects.Filter;
import de.geeksfactory.opacclient.objects.Filter.Option;
import de.geeksfactory.opacclient.objects.LentItem;
import de.geeksfactory.opacclient.objects.Library;
import de.geeksfactory.opacclient.objects.ReservedItem;
import de.geeksfactory.opacclient.objects.SearchRequestResult;
import de.geeksfactory.opacclient.objects.SearchResult;
import de.geeksfactory.opacclient.objects.SearchResult.MediaType;
import de.geeksfactory.opacclient.searchfields.DropdownSearchField;
import de.geeksfactory.opacclient.searchfields.SearchField;
import de.geeksfactory.opacclient.searchfields.SearchQuery;
import de.geeksfactory.opacclient.searchfields.TextSearchField;
import de.geeksfactory.opacclient.utils.Base64;
import okhttp3.FormBody;
import okhttp3.RequestBody;
import okio.Buffer;
import okio.BufferedSink; | throws JSONException, IOException, OpacErrorException {
// aktion:
// 1 = make reservation
// 2 = cancel reservation
// 3 = check reservation
FormBody.Builder formData = new FormBody.Builder(Charset.forName(getDefaultEncoding()));
formData.add("aktion", aktion);
if (aktion.equals("2")) {
String medid = media.split("Z")[0].replace("dat", "");
String resid = media.split("Z")[1];
formData.add("medid", medid);
formData.add("resid", resid);
} else {
formData.add("medid", media);
formData.add("bemerkung", "");
formData.add("zws", "");
}
formData.add("biblNr", "0");
formData.add("sessionid", sessionId);
return httpPostAccount(opac_url + "/de/mobile/Res.ashx", formData.build(), acc);
}
@Override
public AccountData account(Account account) throws IOException,
JSONException, OpacErrorException {
if (sessionId == null) login(account);
FormBody.Builder formData = new FormBody.Builder(Charset.forName(getDefaultEncoding()));
formData.add("art", "7");
formData.add("rsa", "");
formData.add("sessionId", sessionId);
JSONObject response =
httpPostAccount(opac_url + "/de/mobile/Konto.ashx", formData.build(), account);
AccountData data = new AccountData(account.getId());
parseAccount(response, data);
return data;
}
static void parseAccount(JSONObject response, AccountData data) throws JSONException {
data.setValidUntil(ifNotEmpty(response.getString("gueltigbis")));
data.setPendingFees(ifNotEmpty(response.getString("gebuehren")));
DateTimeFormatter format = DateTimeFormat.forPattern("dd.MM.yyyy");
List<LentItem> lent = new ArrayList<>();
JSONArray ausleihen = response.getJSONArray("ausleihen");
for (int i = 0; i < ausleihen.length(); i++) {
LentItem item = new LentItem();
JSONObject json = ausleihen.getJSONObject(i);
item.setAuthor(json.getString("urheber"));
item.setTitle(json.getString("titelkurz").replace(item.getAuthor() + " : ", ""));
item.setCover(json.getString("imageurl"));
item.setMediaType(getMediaType(json.getString("iconurl")));
item.setStatus(ifNotEmpty(json.getString("hinweis")));
item.setProlongData(json.getString("exemplarid"));
JSONArray felder = json.getJSONArray("felder");
for (int j = 0; j < felder.length(); j++) {
String value = felder.getJSONObject(j).getString("display");
if (value.startsWith("Leihfrist: ")) {
String dateStr = value.replace("Leihfrist: ", "");
item.setDeadline(format.parseLocalDate(dateStr));
break;
}
}
lent.add(item);
}
data.setLent(lent);
List<ReservedItem> reservations = new ArrayList<>();
JSONArray reservationen = response.getJSONArray("reservationen");
for (int i = 0; i < reservationen.length(); i++) {
ReservedItem item = new ReservedItem();
JSONObject json = reservationen.getJSONObject(i);
item.setAuthor(json.getString("urheber"));
item.setTitle(json.getString("titelkurz").replace(item.getAuthor() + " : ", ""));
item.setCover(json.getString("imageurl"));
item.setMediaType(getMediaType(json.getString("iconurl")));
item.setStatus(ifNotEmpty(json.getString("hinweis")));
if (!json.getString("abholdat").equals("")) {
item.setExpirationDate(format.parseLocalDate(json.getString("abholdat")));
}
if (json.getString("status").equals("1")) {
item.setCancelData(json.getString("exemplarid"));
}
reservations.add(item);
}
data.setLent(lent);
data.setReservations(reservations);
}
private static String ifNotEmpty(String value) {
if (value == null || value.equals("")) {
return null;
} else {
return value;
}
}
private void login(Account account) throws IOException, JSONException, OpacErrorException {
String toEncrypt =
account.getName() + "|" + account.getPassword() + "|"; // + stammbibliothek + "|"
toEncrypt += randomString();
JSONObject response = new JSONObject(
httpGet(opac_url + "/de/mobile/GetRsaPublic.ashx", getDefaultEncoding()));
BigInteger key = new BigInteger(response.getString("key"), 16);
BigInteger modulus = new BigInteger(response.getString("modulus"), 16);
try {
final Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, KeyFactory.getInstance("RSA").generatePublic
(new RSAPublicKeySpec(key, modulus)));
byte[] result = cipher.doFinal(toEncrypt.getBytes()); | String str = Base64.encodeBytes(result); | 5 |
keeps/roda-in | src/main/java/org/roda/rodain/core/sip/creators/SipPreviewCreator.java | [
"public class ConfigurationManager {\n private static final Logger LOGGER = LoggerFactory.getLogger(ConfigurationManager.class.getName());\n\n private static final Path rodainPath = computeRodainPath();\n private static Path schemasPath, templatesPath, logPath, metadataPath, helpPath, externalConfigPath,\n externalAppConfigPath;\n private static PropertiesConfiguration style = load(\"styles\"), internalConfig = load(\"config\"), externalConfig,\n externalAppConfig;\n private static PropertiesConfiguration startExternalConfig, startExternalAppConfig;\n private static ResourceBundle resourceBundle, defaultResourceBundle, helpBundle, defaultHelpBundle;\n private static Locale locale;\n\n private static Set<Path> allSchemas;\n\n private ConfigurationManager() {\n }\n\n private static Path computeRodainPath() {\n String envString = System.getenv(Constants.RODAIN_HOME_ENV_VARIABLE);\n if (envString != null) {\n Path envPath = Paths.get(envString);\n if (Files.exists(envPath) && Files.isDirectory(envPath)) {\n Path confPath = envPath.resolve(Constants.RODAIN_CONFIG_FOLDER);\n try {\n FileUtils.deleteDirectory(confPath.toFile());\n } catch (IOException e) {\n LOGGER.debug(\"Unable to remove configuration directory '{}'\", confPath, e);\n }\n return confPath;\n }\n }\n String documentsString = FileSystemView.getFileSystemView().getDefaultDirectory().getPath();\n Path documentsPath = Paths.get(documentsString);\n return documentsPath.resolve(Constants.RODAIN_CONFIG_FOLDER);\n }\n\n /**\n * Creates the external properties files if they don't exist. Loads the\n * external properties files.\n */\n public static void initialize() {\n externalConfigPath = rodainPath.resolve(Constants.CONFIG_FILE);\n externalAppConfigPath = rodainPath.resolve(Constants.APP_CONFIG_FILE);\n\n try {\n createBaseFolderStructure();\n\n configureLogback();\n\n copyConfigFiles();\n\n copyMetadataTemplates();\n\n copyAndProcessSchemas();\n\n loadConfigs();\n\n processLanguageAndOtherResources();\n\n processIgnoreFilesInfo();\n\n copyHelpFiles();\n\n } catch (IOException e) {\n LOGGER.error(\"Error creating folders or copying config files\", e);\n } catch (MissingResourceException e) {\n LOGGER.error(\"Can't find the language resource for the current locale\", e);\n locale = Locale.forLanguageTag(\"en\");\n resourceBundle = ResourceBundle.getBundle(\"properties/lang\", locale, new FolderBasedUTF8Control());\n helpBundle = ResourceBundle.getBundle(\"properties/help\", locale, new FolderBasedUTF8Control());\n } catch (Throwable e) {\n LOGGER.error(\"Error loading the config file\", e);\n } finally {\n // force the default locale for the JVM\n Locale.setDefault(locale);\n }\n }\n\n private static void createBaseFolderStructure() throws IOException {\n // create folder in home if it doesn't exist\n if (!Files.exists(rodainPath)) {\n Files.createDirectory(rodainPath);\n }\n // create schemas folder\n schemasPath = rodainPath.resolve(Constants.FOLDER_SCHEMAS);\n if (!Files.exists(schemasPath)) {\n Files.createDirectory(schemasPath);\n }\n // create templates folder\n templatesPath = rodainPath.resolve(Constants.FOLDER_TEMPLATES);\n if (!Files.exists(templatesPath)) {\n Files.createDirectory(templatesPath);\n }\n // create LOGGER folder\n logPath = rodainPath.resolve(Constants.FOLDER_LOG);\n if (!Files.exists(logPath)) {\n Files.createDirectory(logPath);\n }\n // create metadata folder\n metadataPath = rodainPath.resolve(Constants.FOLDER_METADATA);\n if (!Files.exists(metadataPath)) {\n Files.createDirectory(metadataPath);\n }\n // create help folder\n helpPath = rodainPath.resolve(Constants.FOLDER_HELP);\n if (!Files.exists(helpPath)) {\n Files.createDirectory(helpPath);\n }\n }\n\n private static void configureLogback() {\n System.setProperty(\"rodain.log\", logPath.toString());\n try {\n LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();\n JoranConfigurator configurator = new JoranConfigurator();\n configurator.setContext(context);\n context.reset();\n // 20170314 hsilva: logback file was named differently from what logback\n // usually expects in order to avoid auto-loading by logback as we want to\n // place the log file under roda-in home\n configurator.doConfigure(ClassLoader.getSystemResource(\"lllogback.xml\"));\n } catch (JoranException e) {\n LOGGER.error(\"Error configuring logback\", e);\n }\n }\n\n private static void copyConfigFiles() throws IOException {\n if (!Files.exists(externalConfigPath)) {\n Files.copy(ClassLoader.getSystemResourceAsStream(\"properties/\" + Constants.CONFIG_FILE), externalConfigPath);\n }\n\n if (!Files.exists(externalAppConfigPath)) {\n Files.copy(ClassLoader.getSystemResourceAsStream(\"properties/\" + Constants.APP_CONFIG_FILE),\n externalAppConfigPath);\n }\n }\n\n private static void copyMetadataTemplates() throws IOException {\n String templatesRaw = getConfig(Constants.CONF_K_METADATA_TEMPLATES);\n String[] templates = templatesRaw.split(Constants.MISC_COMMA);\n for (String templ : templates) {\n String templateName = Constants.CONF_K_PREFIX_METADATA + templ.trim() + Constants.CONF_K_SUFFIX_TEMPLATE;\n String fileName = internalConfig.getString(templateName);\n // copy the sample to the templates folder too, if it doesn't exist\n // already\n if (!Files.exists(templatesPath.resolve(fileName))) {\n Files.copy(\n ClassLoader.getSystemResourceAsStream(Constants.FOLDER_TEMPLATES + Constants.MISC_FWD_SLASH + fileName),\n templatesPath.resolve(fileName), StandardCopyOption.REPLACE_EXISTING);\n }\n }\n }\n\n private static void copyAndProcessSchemas() throws IOException {\n String typesRaw = getConfig(Constants.CONF_K_METADATA_TYPES);\n String[] types = typesRaw.split(Constants.MISC_COMMA);\n for (String type : types) {\n String schemaName = Constants.CONF_K_PREFIX_METADATA + type.trim() + Constants.CONF_K_SUFFIX_SCHEMA;\n String schemaFileName = internalConfig.getString(schemaName);\n if (schemaFileName == null || schemaFileName.length() == 0) {\n continue;\n }\n if (!Files.exists(schemasPath.resolve(schemaFileName))) {\n Files.copy(\n ClassLoader.getSystemResourceAsStream(Constants.FOLDER_TEMPLATES + Constants.MISC_FWD_SLASH + schemaFileName),\n schemasPath.resolve(schemaFileName), StandardCopyOption.REPLACE_EXISTING);\n }\n }\n\n // ensure that the xlink.xsd and xml.xsd files are in the application home\n // folder\n Files.copy(ClassLoader.getSystemResourceAsStream(\"xlink.xsd\"), schemasPath.resolve(\"xlink.xsd\"),\n StandardCopyOption.REPLACE_EXISTING);\n Files.copy(ClassLoader.getSystemResourceAsStream(\"xml.xsd\"), schemasPath.resolve(\"xml.xsd\"),\n StandardCopyOption.REPLACE_EXISTING);\n\n // get all schema files in the roda-in home directory\n allSchemas = new HashSet<>();\n File folder = rodainPath.toFile();\n File[] listOfFiles = folder.listFiles();\n\n for (int i = 0; i < listOfFiles.length; i++) {\n if (listOfFiles[i].isFile()) {\n File file = listOfFiles[i];\n if (file.getName().endsWith(\".xsd\")) {\n allSchemas.add(Paths.get(file.getPath()));\n }\n }\n }\n }\n\n private static void loadConfigs() throws ConfigurationException, FileNotFoundException {\n externalConfig = new PropertiesConfiguration();\n externalConfig.load(new FileInputStream(externalConfigPath.toFile()), Constants.RODAIN_DEFAULT_CONFIG_ENCODING);\n externalAppConfig = new PropertiesConfiguration();\n externalAppConfig.load(new FileInputStream(externalAppConfigPath.toFile()),\n Constants.RODAIN_DEFAULT_CONFIG_ENCODING);\n\n // keep the starting configuration to use when saving\n startExternalConfig = new PropertiesConfiguration();\n startExternalConfig.load(new FileInputStream(externalConfigPath.toFile()),\n Constants.RODAIN_DEFAULT_CONFIG_ENCODING);\n startExternalAppConfig = new PropertiesConfiguration();\n startExternalAppConfig.load(new FileInputStream(externalAppConfigPath.toFile()),\n Constants.RODAIN_DEFAULT_CONFIG_ENCODING);\n }\n\n private static void processLanguageAndOtherResources() {\n String appLanguage = getAppConfig(\"app.language\");\n if (StringUtils.isBlank(appLanguage)) {\n appLanguage = getConfig(Constants.CONF_K_DEFAULT_LANGUAGE);\n }\n locale = parseLocale(appLanguage);\n resourceBundle = ResourceBundle.getBundle(\"properties/lang\", locale, new FolderBasedUTF8Control());\n helpBundle = ResourceBundle.getBundle(\"properties/help\", locale, new FolderBasedUTF8Control());\n defaultResourceBundle = ResourceBundle.getBundle(\"properties/lang\", Locale.ENGLISH, new FolderBasedUTF8Control());\n defaultHelpBundle = ResourceBundle.getBundle(\"properties/help\", Locale.ENGLISH, new FolderBasedUTF8Control());\n }\n\n public static Locale parseLocale(String localeString) {\n Locale locale = Locale.ENGLISH;\n if (StringUtils.isNotBlank(localeString)) {\n String[] localeArgs = localeString.split(\"_\");\n\n if (localeArgs.length == 1) {\n locale = new Locale(localeArgs[0]);\n } else if (localeArgs.length == 2) {\n locale = new Locale(localeArgs[0], localeArgs[1]);\n } else if (localeArgs.length == 3) {\n locale = new Locale(localeArgs[0], localeArgs[1], localeArgs[2]);\n }\n }\n\n return locale;\n }\n\n private static void processIgnoreFilesInfo() {\n String ignorePatterns = getAppConfig(Constants.CONF_K_IGNORED_FILES);\n if (ignorePatterns != null && !ignorePatterns.trim().equalsIgnoreCase(\"\")) {\n String[] patterns = ignorePatterns.split(Constants.MISC_COMMA);\n for (String pattern : patterns) {\n IgnoredFilter.addIgnoreRule(pattern.trim());\n }\n }\n }\n\n private static void copyHelpFiles() {\n // 20170524 hsilva: we need to copy help files knowing all the file names\n // because using windows exe (jar wrapped with launch4j), strategies like\n // reflections do not work well\n List<Object> helpFiles = internalConfig.getList(\"help.files\");\n for (Object object : helpFiles) {\n String helpFile = (String) object;\n Path helpFilePath = helpPath.resolve(helpFile);\n if (!Files.exists(helpFilePath)) {\n try {\n Files.copy(ClassLoader.getSystemResourceAsStream(Constants.FOLDER_HELP + Constants.MISC_FWD_SLASH + helpFile),\n helpFilePath, StandardCopyOption.REPLACE_EXISTING);\n } catch (IOException e) {\n LOGGER.error(\"Error while copying help file '{}' to '{}'\", helpFile, helpPath);\n }\n }\n }\n }\n\n /**\n * @return The path of the application folder.\n */\n public static Path getRodainPath() {\n return rodainPath;\n }\n\n /**\n * @return The locale of the application.\n */\n public static Locale getLocale() {\n return locale;\n }\n\n private static PropertiesConfiguration load(String fileName) {\n PropertiesConfiguration result = null;\n try {\n result = new PropertiesConfiguration(\"properties/\" + fileName + \".properties\");\n } catch (ConfigurationException e) {\n LOGGER.error(\"Error loading the config file\", e);\n }\n return result;\n }\n\n public static String getHelpFile() {\n Path helpFile = helpPath.resolve(\"help_\" + getLocale().toString() + \".html\");\n if (!Files.exists(helpFile)) {\n helpFile = helpPath.resolve(\"help_en.html\");\n if (!Files.exists(helpFile)) {\n helpFile = helpPath.resolve(\"help.html\");\n }\n }\n\n if (Controller.systemIsWindows()) {\n try {\n return helpFile.toUri().toURL().toString();\n } catch (MalformedURLException e) {\n return \"file://\" + helpFile.toString();\n }\n } else {\n return \"file://\" + helpFile.toString();\n }\n }\n\n /**\n * @param templateName\n * The name of the template\n * @return The content of the template file\n */\n public static String getTemplateContent(String templateName) {\n String completeKey = Constants.CONF_K_PREFIX_METADATA + templateName + Constants.CONF_K_SUFFIX_TEMPLATE;\n return getFile(completeKey);\n }\n\n /**\n * @param templateType\n * The name of the template\n * @return The content of the schema file associated to the template\n */\n public static InputStream getSchemaFile(String templateType) {\n String completeKey = Constants.CONF_K_PREFIX_METADATA + templateType + Constants.CONF_K_SUFFIX_SCHEMA;\n if (externalConfig.containsKey(completeKey)) {\n Path filePath = schemasPath.resolve(externalConfig.getString(completeKey));\n if (Files.exists(filePath)) {\n try {\n return Files.newInputStream(filePath);\n } catch (IOException e) {\n LOGGER.error(\"Unable to get schema file '{}'\", filePath, e);\n }\n }\n }\n return null;\n }\n\n /**\n * @param templateType\n * The name of the template\n * @return The path of the schema file associated to the template\n */\n public static Path getSchemaPath(String templateType) {\n String completeKey = Constants.CONF_K_PREFIX_METADATA + templateType + Constants.CONF_K_SUFFIX_SCHEMA;\n if (externalConfig.containsKey(completeKey)) {\n Path filePath = schemasPath.resolve(externalConfig.getString(completeKey));\n if (Files.exists(filePath)) {\n return filePath;\n }\n }\n String fileName = internalConfig.getString(completeKey);\n URL temp = ClassLoader.getSystemResource(Constants.FOLDER_TEMPLATES + Constants.MISC_FWD_SLASH + fileName);\n if (temp != null)\n return Paths.get(temp.getPath());\n else\n return null;\n }\n\n private static String getFile(String completeKey) {\n try {\n if (externalConfig.containsKey(completeKey)) {\n Path filePath = templatesPath.resolve(externalConfig.getString(completeKey));\n if (Files.exists(filePath)) {\n return ControllerUtils.readFile(filePath);\n }\n }\n String fileName = internalConfig.getString(completeKey);\n URL temp = ClassLoader.getSystemResource(Constants.FOLDER_TEMPLATES + Constants.MISC_FWD_SLASH + fileName);\n if (temp == null) {\n return \"\";\n }\n InputStream contentStream = temp.openStream();\n return ControllerUtils.convertStreamToString(contentStream);\n } catch (IOException e) {\n LOGGER.error(\"Error reading metadata file\", e);\n }\n return \"\";\n }\n\n /**\n * @param key\n * The name of the property (style)\n * @return The value of the property (style)\n */\n public static String getStyle(String key) {\n return style.getString(key);\n }\n\n /**\n * Method to return config related to metadata (it composes the key to look\n * for by prefixing the method argument with \"metadata.\")\n * \n * @param partialKey\n * the end part of the key to look for\n */\n public static String getMetadataConfig(String partialKey) {\n return getConfig(Constants.CONF_K_PREFIX_METADATA + partialKey);\n }\n\n /**\n * @param key\n * The name of the property (config)\n * @return The value of the property (config)\n */\n public static String getConfig(String key) {\n Object res;\n if (externalConfig != null && externalConfig.containsKey(key)) {\n res = externalConfig.getProperty(key);\n } else {\n res = internalConfig.getProperty(key);\n }\n if (res == null) {\n return null;\n }\n if (res instanceof String) {\n return (String) res;\n }\n // if it isn't a string then it must be a list Ex: a,b,c,d\n return String.join(Constants.MISC_COMMA, (List<String>) res);\n }\n\n /**\n * @param key\n * The name of the property (config)\n * @return The value of the property (config)\n */\n public static Boolean getConfigAsBoolean(String key, boolean defaultValue) {\n // valueOf defaults to false, using an 'or' to force the default\n return Boolean.valueOf(getConfig(key)) || defaultValue;\n }\n\n /**\n * @param key\n * The name of the property (config)\n * @return The value of the property (config)\n */\n public static Boolean getConfigAsBoolean(String key) {\n return getConfigAsBoolean(key, false);\n }\n\n /**\n * @param key\n * The name of the property (config)\n * @return The value of the property (config)\n */\n public static String[] getConfigAsStringArray(String key) {\n String[] res;\n if (externalConfig != null && externalConfig.containsKey(key)) {\n res = externalConfig.getStringArray(key);\n } else {\n res = internalConfig.getStringArray(key);\n }\n if (res == null) {\n return new String[] {};\n } else {\n return res;\n }\n }\n\n /**\n * @param key\n * The name of the property (config)\n * @return The value of the property (config)\n */\n public static String getConfigArray(String key) {\n Object res;\n if (externalConfig != null && externalConfig.containsKey(key)) {\n res = externalConfig.getProperty(key);\n } else {\n res = internalConfig.getProperty(key);\n }\n if (res == null) {\n return null;\n }\n if (res instanceof String) {\n return (String) res;\n }\n // if it isn't a string then it must be a list Ex: a,b,c,d\n return String.join(Constants.MISC_COMMA, (List<String>) res);\n }\n\n protected static String getLocalizedStringForLanguage(String key, String languageTag) {\n ResourceBundle localResourceBundle = ResourceBundle.getBundle(\"properties/lang\", Locale.forLanguageTag(languageTag),\n new FolderBasedUTF8Control());\n String result = null;\n\n try {\n result = localResourceBundle.getString(key);\n } catch (MissingResourceException e) {\n LOGGER.trace(\"Missing translation for {} in language: {}\", key, localResourceBundle.getLocale().getDisplayName());\n result = getLocalizedString(key);\n }\n return result;\n }\n\n /**\n * Uses ResourceBundle to get the language specific string\n *\n * @param key\n * The name of the property\n *\n * @param values\n * Optional replacement values that will, in order, replace any {}\n * found in the localized string\n * \n * @return The value of the property using\n */\n protected static String getLocalizedString(String key, Object... values) {\n String result = null;\n try {\n result = resourceBundle.getString(key);\n } catch (MissingResourceException e) {\n LOGGER.trace(\"Missing translation for {} in language: {}\", key, locale.getDisplayName());\n try {\n result = defaultResourceBundle.getString(key);\n } catch (Exception e1) {\n LOGGER.trace(\"Missing translation for {} in language: {}\", key, Locale.ENGLISH);\n }\n }\n\n if (result != null) {\n for (Object value : values) {\n result = result.replace(\"{}\", String.valueOf(value));\n }\n }\n\n return result;\n }\n\n protected static String getLocalizedHelp(String key) {\n String result = null;\n try {\n result = helpBundle.getString(key);\n if (\"\".equals(result)) {\n throw new MissingResourceException(\"\", \"\", key);\n }\n } catch (MissingResourceException e) {\n LOGGER.trace(\"Missing translation for help {} in language: {}\", key, locale.getDisplayName());\n try {\n result = defaultHelpBundle.getString(key);\n } catch (Exception e1) {\n LOGGER.trace(\"Missing translation for help {} in language: {}\", key, Locale.ENGLISH);\n }\n }\n return result;\n }\n\n /**\n * Sets the value of a configuration.\n * \n * @param key\n * The key of the property.\n * @param value\n * The value of the property\n */\n public static void setConfig(String key, String value) {\n setConfig(key, value, false);\n }\n\n /**\n * Sets the value of a configuration.\n * \n * @param key\n * The key of the property.\n * @param value\n * The value of the property\n * @param saveToFile\n * true if after setting the key/value, is supposed to save that\n * information to file\n */\n public static void setConfig(String key, String value, boolean saveToFile) {\n externalConfig.setProperty(key, value);\n if (saveToFile) {\n saveConfig();\n }\n }\n\n public static void setAppConfig(String key, String value, boolean saveToFile) {\n externalAppConfig.setProperty(key, value);\n if (saveToFile) {\n saveAppConfig();\n }\n }\n\n public static void setAppConfig(String key, String value) {\n setAppConfig(key, value, false);\n }\n\n public static String getAppConfig(String key) {\n Object res = null;\n if (externalAppConfig != null && externalAppConfig.containsKey(key)) {\n res = externalAppConfig.getProperty(key);\n }\n if (res == null) {\n return null;\n }\n if (res instanceof String) {\n return (String) res;\n }\n // if it isn't a string then it must be a list Ex: a,b,c,d\n return String.join(Constants.MISC_COMMA, (List<String>) res);\n }\n\n /**\n * Saves the configuration to a file in the application home folder.\n */\n public static void saveConfig() {\n try {\n PropertiesConfiguration temp = new PropertiesConfiguration();\n temp.load(new FileReader(externalConfigPath.toFile()));\n if (externalConfig != null) {\n HashSet<String> keys = new HashSet<>();\n externalConfig.getKeys().forEachRemaining(keys::add);\n temp.getKeys().forEachRemaining(keys::add);\n keys.forEach(s -> {\n // Add new properties to the ext_config\n if (temp.containsKey(s) && !externalConfig.containsKey(s)) {\n externalConfig.addProperty(s, temp.getProperty(s));\n } else {\n // check if there's any property in the current file that is\n // different from the ones we loaded in the beginning of the\n // execution of the application.\n if (temp.containsKey(s) && startExternalConfig.containsKey(s)\n && !temp.getProperty(s).equals(startExternalConfig.getProperty(s))) {\n // Set the property to keep the changes made outside the\n // application\n externalConfig.setProperty(s, temp.getProperty(s));\n }\n }\n });\n }\n externalConfig.save(externalConfigPath.toFile());\n } catch (ConfigurationException | FileNotFoundException e) {\n LOGGER.error(\"Error loading the config file\", e);\n }\n }\n\n public static void saveAppConfig() {\n try {\n PropertiesConfiguration temp = new PropertiesConfiguration();\n temp.load(new FileReader(externalAppConfigPath.toFile()));\n if (externalAppConfig != null) {\n HashSet<String> keys = new HashSet<>();\n externalAppConfig.getKeys().forEachRemaining(keys::add);\n temp.getKeys().forEachRemaining(keys::add);\n keys.forEach(s -> {\n // Add new properties to the ext_config\n if (temp.containsKey(s) && !externalAppConfig.containsKey(s)) {\n externalAppConfig.addProperty(s, temp.getProperty(s));\n } else {\n // check if there's any property in the current file that is\n // different from the ones we loaded in the beginning of the\n // execution of the application.\n if (temp.containsKey(s) && startExternalAppConfig.containsKey(s)\n && !temp.getProperty(s).equals(startExternalAppConfig.getProperty(s))) {\n // Set the property to keep the changes made outside the\n // application\n externalAppConfig.setProperty(s, temp.getProperty(s));\n }\n }\n });\n }\n externalAppConfig.save(externalAppConfigPath.toFile());\n } catch (ConfigurationException | FileNotFoundException e) {\n LOGGER.error(\"Error saving the app config file\", e);\n }\n }\n\n public static URL getBuildProperties() {\n return ClassLoader.getSystemResource(\"build.properties\");\n }\n\n public static <T extends Serializable> T deserialize(String filename) {\n Path serialFile = rodainPath.resolve(Constants.RODAIN_SERIALIZE_FILE_PREFIX + filename);\n try (InputStream in = Files.newInputStream(serialFile, StandardOpenOption.READ)) {\n return (T) SerializationUtils.deserialize(in);\n } catch (IOException | ClassCastException e) {\n LOGGER.error(\"Error deserializing from file {}\", serialFile.toAbsolutePath().toString(), e);\n }\n return null;\n }\n\n public static <T extends Serializable> void serialize(T object, String filename) {\n Path serialFile = rodainPath.resolve(Constants.RODAIN_SERIALIZE_FILE_PREFIX + filename);\n try (OutputStream out = Files.newOutputStream(serialFile, StandardOpenOption.CREATE, StandardOpenOption.WRITE,\n StandardOpenOption.TRUNCATE_EXISTING)) {\n SerializationUtils.serialize(object, out);\n } catch (IOException e) {\n LOGGER.error(\"Error serializing to file {}\", serialFile.toAbsolutePath().toString(), e);\n }\n }\n}",
"public final class Constants {\n\n // misc\n public static final String RODAIN_HOME_ENV_VARIABLE = \"RODAIN_HOME\";\n public static final String RODAIN_ENV_VARIABLE = \"RODAIN_ENV\";\n public static final String RODAIN_ENV_TESTING = \"testing\";\n public static final String RODAIN_CONFIG_FOLDER = \"roda-in\";\n public static final String RODAIN_SERIALIZE_FILE_PREFIX = \"serial_\";\n public static final String RODAIN_SERIALIZE_FILE_METS_HEADER_SUFFIX = \"_metsheader.bin\";\n public static final String RODAIN_GITHUB_LATEST_VERSION_LINK = \"https://github.com/keeps/roda-in/releases\";\n public static final String RODAIN_GITHUB_LATEST_VERSION_API_LINK = \"https://api.github.com/repos/keeps/roda-in/releases/latest\";\n public static final String RODAIN_GUI_TITLE = \"RODA-In\";\n public static final String RODAIN_DEFAULT_ENCODING = \"UTF-8\";\n public static final String RODAIN_DEFAULT_CONFIG_ENCODING = RODAIN_DEFAULT_ENCODING;\n public static final String ENCODING_BASE64 = \"Base64\";\n public static final String MISC_TRUE = \"true\";\n public static final String MISC_FALSE = \"false\";\n public static final String MISC_GLOB = \"glob:\";\n public static final String MISC_DEFAULT_ID_PREFIX = \"uuid-\";\n public static final String MISC_XML_EXTENSION = \".xml\";\n public static final String MISC_DOT = \".\";\n public static final String MISC_COLON = \":\";\n public static final String MISC_COMMA = \",\";\n public static final String MISC_DOUBLE_QUOTE = \"\\\"\";\n public static final String MISC_DOUBLE_QUOTE_W_SPACE = \" \\\"\";\n public static final String MISC_OR_OP = \"||\";\n public static final String MISC_AND_OP = \"&&\";\n public static final String MISC_FWD_SLASH = \"/\";\n public static final String MISC_METADATA_SEP = \"!###!\";\n public static final String MISC_DEFAULT_HUNGARIAN_SIP_SERIAL = \"001\";\n\n // langs\n public static final String LANG_PT_BR = \"pt-br\";\n public static final String LANG_PT_PT = \"pt-pt\";\n public static final String LANG_PT = \"pt\";\n public static final String LANG_ES_CL = \"es-cl\";\n public static final String LANG_ES = \"es\";\n public static final String LANG_EN = \"en\";\n public static final String LANG_HU = \"hu\";\n public static final String LANG_HR = \"hr\";\n public static final String LANG_DEFAULT = LANG_EN;\n\n // sip related\n public static final String SIP_DEFAULT_PACKAGE_TYPE = \"UNKNOWN\";\n public static final String SIP_DEFAULT_CONTENT_TYPE = \"MIXED\";\n public static final String SIP_CONTENT_TYPE_OTHER = \"OTHER\";\n public static final String SIP_DEFAULT_REPRESENTATION_CONTENT_TYPE = SIP_DEFAULT_CONTENT_TYPE;\n public static final String SIP_REP_FIRST = \"rep1\";\n public static final String SIP_REP_PREFIX = \"rep\";\n public static final String SIP_DEFAULT_AGENT_NAME = \"RODA-in\";\n public static final String SIP_AGENT_ROLE_OTHER = \"OTHER\";\n public static final String SIP_AGENT_TYPE_INDIVIDUAL = \"INDIVIDUAL\";\n public static final String SIP_AGENT_OTHERROLE_SUBMITTER = \"SUBMITTER\";\n public static final String SIP_AGENT_NOTETYPE_IDENTIFICATIONCODE = \"IDENTIFICATIONCODE\";\n public static final String SIP_AGENT_VERSION_UNKNOWN = \"UNKNOWN\";\n public static final String SIP_AGENT_NAME_FORMAT = \"RODA-in %s\";\n public static final String SIP_NAME_STRATEGY_SERIAL_FORMAT_NUMBER = \"%03d\";\n\n // folders\n public static final String FOLDER_SCHEMAS = \"schemas\";\n public static final String FOLDER_TEMPLATES = \"templates\";\n public static final String FOLDER_LOG = \"log\";\n public static final String FOLDER_METADATA = \"metadata\";\n public static final String FOLDER_HELP = \"help\";\n\n // configs keys prefixes & sufixes\n public static final String CONF_K_PREFIX_METADATA = \"metadata.\";\n public static final String CONF_K_SUFFIX_SCHEMA = \".schema\";\n public static final String CONF_K_SUFFIX_TEMPLATE = \".template\";\n public static final String CONF_K_SUFFIX_TITLE = \".title\";\n public static final String CONF_K_SUFFIX_TYPE = \".type\";\n public static final String CONF_K_SUFFIX_VERSION = \".version\";\n public static final String CONF_K_SUFFIX_AGGREG_LEVEL = \".aggregationLevel\";\n public static final String CONF_K_SUFFIX_TOP_LEVEL = \".topLevel\";\n public static final String CONF_K_SUFFIX_ITEM_LEVEL = \".itemLevel\";\n public static final String CONF_K_SUFFIX_FILE_LEVEL = \".fileLevel\";\n public static final String CONF_K_SUFFIX_TAGS = \".tags\";\n public static final String CONF_K_SUFFIX_SYNCHRONIZED = \".synchronized\";\n public static final String CONF_K_SUFFIX_LEVELS_ICON = \"levels.icon.\";\n // configs keys\n public static final String CONF_K_ACTIVE_SIP_TYPES = \"activeSipTypes\";\n public static final String CONF_K_DEFAULT_LANGUAGE = \"defaultLanguage\";\n public static final String CONF_K_LAST_SIP_TYPE = \"lastSipType\";\n public static final String CONF_K_DEFAULT_SIP_TYPE = \"creationModalPreparation.defaultSipType\";\n public static final String CONF_K_IGNORED_FILES = \"app.ignoredFiles\";\n public static final String CONF_K_METADATA_TEMPLATES = \"metadata.templates\";\n public static final String CONF_K_METADATA_TYPES = \"metadata.types\";\n public static final String CONF_K_LEVELS_ICON_DEFAULT = \"levels.icon.internal.default\";\n public static final String CONF_K_LEVELS_ICON_ITEM = \"levels.icon.internal.itemLevel\";\n public static final String CONF_K_LEVELS_ICON_FILE = \"levels.icon.internal.fileLevel\";\n public static final String CONF_K_LEVELS_ICON_AGGREGATION = \"levels.icon.internal.aggregationLevel\";\n public static final String CONF_K_EXPORT_LAST_PREFIX = \"export.lastPrefix\";\n public static final String CONF_K_EXPORT_LAST_TRANSFERRING = \"export.lastTransferring\";\n public static final String CONF_K_EXPORT_LAST_SERIAL = \"export.lastSerial\";\n public static final String CONF_K_EXPORT_LAST_ITEM_EXPORT_SWITCH = \"export.lastItemExportSwitch\";\n public static final String CONF_K_EXPORT_LAST_REPORT_CREATION_SWITCH = \"export.lastReportCreationSwitch\";\n public static final String CONF_K_EXPORT_LAST_SIP_OUTPUT_FOLDER = \"export.lastSipOutputFolder\";\n public static final String CONF_K_ID_PREFIX = \"idPrefix\";\n public static final String CONF_K_SIP_CREATION_ALWAYS_JUMP_FOLDER = \"sipPreviewCreator.createSip.alwaysJumpFolder\";\n // METS Header fields\n public static final String CONF_K_METS_HEADER_FIELDS_PREFIX = \"metsheader.\";\n public static final String CONF_K_METS_HEADER_FIELDS_SUFFIX = \".fields\";\n public static final String CONF_K_METS_HEADER_FIELD_SEPARATOR = \".field.\";\n public static final String CONF_K_METS_HEADER_TYPES_SEPARATOR = \".type.\";\n public static final String CONF_K_METS_HEADER_TYPE_RECORD_STATUS = \"recordstatus\";\n public static final String CONF_K_METS_HEADER_TYPE_ALTRECORD_ID = \"altrecordid\";\n public static final String CONF_K_METS_HEADER_TYPE_AGENT = \"agent\";\n public static final String CONF_K_METS_HEADER_FIELD_TITLE = \".title\";\n public static final String CONF_K_METS_HEADER_FIELD_TYPE = \".type\";\n public static final String CONF_K_METS_HEADER_FIELD_AMOUNT_MAX = \".amount.max\";\n public static final String CONF_K_METS_HEADER_FIELD_AMOUNT_MIN = \".amount.min\";\n public static final String CONF_K_METS_HEADER_FIELD_LABEL = \".label\";\n public static final String CONF_K_METS_HEADER_FIELD_DESCRIPTION = \".description\";\n public static final String CONF_K_METS_HEADER_FIELD_COMBO_VALUES = \".combo\";\n public static final String CONF_K_METS_HEADER_FIELD_ATTRIBUTE_OTHERTYPE_VALUE = \".attr.othertype.value\";\n public static final String CONF_K_METS_HEADER_FIELD_ATTRIBUTE_OTHERTYPE_LABEL = \".attr.othertype.label\";\n public static final String CONF_K_METS_HEADER_FIELD_ATTRIBUTE_OTHERTYPE_DESCRIPTION = \".attr.othertype.description\";\n public static final String CONF_K_METS_HEADER_FIELD_ATTRIBUTE_ROLE_VALUE = \".attr.role.value\";\n public static final String CONF_K_METS_HEADER_FIELD_ATTRIBUTE_ROLE_LABEL = \".attr.role.label\";\n public static final String CONF_K_METS_HEADER_FIELD_ATTRIBUTE_ROLE_DESCRIPTION = \".attr.role.description\";\n public static final String CONF_K_METS_HEADER_FIELD_ATTRIBUTE_TYPE_VALUE = \".attr.type.value\";\n public static final String CONF_K_METS_HEADER_FIELD_ATTRIBUTE_TYPE_LABEL = \".attr.type.label\";\n public static final String CONF_K_METS_HEADER_FIELD_ATTRIBUTE_TYPE_DESCRIPTION = \".attr.type.description\";\n public static final String CONF_K_METS_HEADER_FIELD_ATTRIBUTE_NAME_LABEL = \".attr.name.label\";\n public static final String CONF_K_METS_HEADER_FIELD_ATTRIBUTE_NAME_DESCRIPTION = \".attr.name.description\";\n public static final String CONF_K_METS_HEADER_FIELD_ATTRIBUTE_NOTE_LABEL = \".attr.note.label\";\n public static final String CONF_K_METS_HEADER_FIELD_ATTRIBUTE_NOTE_DESCRIPTION = \".attr.note.description\";\n public static final String CONF_K_METS_HEADER_FIELD_ATTRIBUTE_NOTE_MANDATORY = \".attr.note.mandatory\";\n public static final String CONF_K_METS_HEADER_FIELD_MULTI_FIELD_COMBO_VALUES_NAME = \".multifieldcombo.attr.name\";\n public static final String CONF_K_METS_HEADER_FIELD_MULTI_FIELD_COMBO_VALUES_NOTE = \".multifieldcombo.attr.note\";\n public static final String CONF_V_METS_HEADER_FIELD_TYPE_AGENT = \"agent\";\n public static final String CONF_V_METS_HEADER_FIELD_TYPE_ALTRECORDID = \"altrecordid\";\n public static final String CONF_V_METS_HEADER_FIELD_TYPE_RECORDSTATUS = \"recordstatus\";\n public static final String CONF_V_METS_HEADER_FIELD_AMOUNT_MAX_INFINITE = \"N\";\n\n // app configs keys\n public static final String CONF_K_APP_LAST_CLASS_SCHEME = \"lastClassificationScheme\";\n public static final String CONF_K_APP_HELP_ENABLED = \"app.helpEnabled\";\n public static final String CONF_K_APP_LANGUAGE = \"app.language\";\n public static final String CONF_K_APP_MULTIPLE_EDIT_MAX = \"app.multipleEdit.max\";\n // configs files\n public static final String CONFIG_FILE = \"config.properties\";\n public static final String APP_CONFIG_FILE = \".app.properties\";\n // configs values\n public static final String CONF_V_TRUE = MISC_TRUE;\n public static final String CONF_V_FALSE = MISC_FALSE;\n\n // events\n public static final String EVENT_REMOVED_RULE = \"Removed rule\";\n public static final String EVENT_REMOVE_FROM_RULE = \"Remove from rule\";\n public static final String EVENT_REMOVED_SIP = \"Removed SIP\";\n public static final String EVENT_FINISHED = \"Finished\";\n\n // date related formats\n public static final String DATE_FORMAT_1 = \"yyyy.MM.dd HH.mm.ss.SSS\";\n public static final String DATE_FORMAT_2 = \"dd.MM.yyyy '@' HH:mm:ss z\";\n public static final String DATE_FORMAT_3 = \"yyyy-MM-dd'T'HH:mm:ss'Z'\";\n public static final String DATE_FORMAT_4 = \"yyyy-MM-dd\";\n public static final String DATE_FORMAT_5 = \"yyyyMMdd\";\n\n // resources\n public static final String RSC_SPLASH_SCREEN_IMAGE = \"roda-in-splash.png\";\n public static final String RSC_RODA_LOGO = \"RODA-in.png\";\n public static final String RSC_LOADING_GIF = \"loading.GIF\";\n public static final String RSC_ICON_FOLDER = \"icons/folder_yellow.png\";\n public static final String RSC_ICON_FOLDER_EXPORT = \"icons/folder_export_yellow.png\";\n public static final String RSC_ICON_FOLDER_OPEN = \"icons/folder-open_yellow.png\";\n public static final String RSC_ICON_FOLDER_OPEN_EXPORT = \"icons/folder-open_export_yellow.png\";\n public static final String RSC_ICON_FILE = \"icons/file_blue.png\";\n public static final String RSC_ICON_FILE_EXPORT = \"icons/file-export_blue.png\";\n public static final String RSC_ICON_FOLDER_COLAPSE = \"icons/folder_yellow.png\";\n public static final String RSC_ICON_FOLDER_EXPAND = \"icons/folder-open_yellow.png\";\n public static final String RSC_ICON_LIST_ADD = \"icons/list-add.png\";\n public static final String RSC_CSS_SHARED = \"css/shared.css\";\n public static final String RSC_CSS_MODAL = \"css/modal.css\";\n\n // CSS\n public static final String CSS_BOLDTEXT = \"boldText\";\n public static final String CSS_BORDER_PANE = \"border-pane\";\n public static final String CSS_CELL = \"cell\";\n public static final String CSS_CELLTEXT = \"cellText\";\n public static final String CSS_DARK_BUTTON = \"dark-button\";\n public static final String CSS_DESCRIPTION = \"description\";\n public static final String CSS_EDGE_TO_EDGE = \"edge-to-edge\";\n public static final String CSS_ERROR = \"error\";\n public static final String CSS_EXPORT_BUTTON = \"export-button\";\n public static final String CSS_FOOTER = \"footer\";\n public static final String CSS_FORMLABEL = \"formLabel\";\n public static final String CSS_FORMSEPARATOR = \"formSeparator\";\n public static final String CSS_FORM_TEXT_AREA = \"form-text-area\";\n public static final String CSS_HBOX = \"hbox\";\n public static final String CSS_HELPBUTTON = \"helpButton\";\n public static final String CSS_HELPTITLE = \"helpTitle\";\n public static final String CSS_INDEXED_CELL = \"indexed-cell\";\n public static final String CSS_INSPECTIONPART = \"inspectionPart\";\n public static final String CSS_MAIN_TREE = \"main-tree\";\n public static final String CSS_METS_HEADER_ITEM_ADD_MORE_LINK = \"mets-header-item-add-more-link\";\n public static final String CSS_METS_HEADER_GROUP_LAST = \"mets-header-group-last\";\n public static final String CSS_METS_HEADER_GROUP = \"mets-header-group\";\n public static final String CSS_METS_HEADER_ITEM_BUTTON_REMOVE = \"mets-item-button-remove\";\n public static final String CSS_METS_HEADER_ITEM_WITHOUT_SIBLINGS = \"mets-item-without-siblings\";\n public static final String CSS_METS_HEADER_ITEM_WITH_SIBLINGS = \"mets-item-with-siblings\";\n public static final String CSS_METS_HEADER_ITEM_WITH_MULTIPLE_FIELDS = \"mets-item-multiple-fields\";\n public static final String CSS_METS_HEADER_SECTION_TITLE = \"mets-header-section-title\";\n public static final String CSS_METS_HEADER_SECTION = \"mets-header-section\";\n public static final String CSS_MODAL = \"modal\";\n public static final String CSS_PREPARECREATIONSUBTITLE = \"prepareCreationSubtitle\";\n public static final String CSS_RULECELL = \"ruleCell\";\n public static final String CSS_SCHEMANODE = \"schemaNode\";\n public static final String CSS_SCHEMANODEEMPTY = \"schemaNodeEmpty\";\n public static final String CSS_SCHEMANODEHOVERED = \"schemaNodeHovered\";\n public static final String CSS_SIPCREATOR = \"sipcreator\";\n public static final String CSS_TITLE = \"title\";\n public static final String CSS_TITLE_BOX = \"title-box\";\n public static final String CSS_TOP = \"top\";\n public static final String CSS_TOP_SUBTITLE = \"top-subtitle\";\n public static final String CSS_TREE_CELL = \"tree-cell\";\n public static final String CSS_BACKGROUNDWHITE = \"backgroundWhite\";\n public static final String CSS_FX_BACKGROUND_COLOR_TRANSPARENT = \"-fx-background-color: transparent\";\n public static final String CSS_FX_FONT_SIZE_16PX = \"-fx-font-size: 16px\";\n public static final String CSS_FX_TEXT_FILL_BLACK = \"-fx-text-fill: black\";\n\n // I18n\n public static final String I18N_NEW_VERSION_CONTENT = \"Main.newVersion.content\";\n public static final String I18N_ASSOCIATION_SINGLE_SIP_DESCRIPTION = \"association.singleSip.description\";\n public static final String I18N_ASSOCIATION_SINGLE_SIP_TITLE = \"association.singleSip.title\";\n public static final String I18N_ASSOCIATION_SIP_PER_FILE_DESCRIPTION = \"association.sipPerFile.description\";\n public static final String I18N_ASSOCIATION_SIP_PER_FILE_TITLE = \"association.sipPerFile.title\";\n public static final String I18N_ASSOCIATION_SIP_SELECTION_DESCRIPTION = \"association.sipSelection.description\";\n public static final String I18N_ASSOCIATION_SIP_SELECTION_TITLE = \"association.sipSelection.title\";\n public static final String I18N_ASSOCIATION_SIP_WITH_STRUCTURE_DESCRIPTION = \"association.sipWithStructure.description\";\n public static final String I18N_ASSOCIATION_SIP_WITH_STRUCTURE_TITLE = \"association.sipWithStructure.title\";\n public static final String I18N_CREATIONMODALMETSHEADER_HEADER = \"CreationModalMETSHeader.METSHeader\";\n public static final String I18N_CREATIONMODALMETSHEADER_SECTION_STATUS = \"CreationModalMETSHeader.section.status\";\n public static final String I18N_CREATIONMODALMETSHEADER_SECTION_AGENTS = \"CreationModalMETSHeader.section.agents\";\n public static final String I18N_CREATIONMODALMETSHEADER_SECTION_ALTRECORDS = \"CreationModalMETSHeader.section.altrecords\";\n public static final String I18N_CREATIONMODALMETSHEADER_ERROR_MINIMUM = \"CreationModalMETSHeader.error.minimum\";\n public static final String I18N_CREATIONMODALMETSHEADER_ERROR_MAXIMUM = \"CreationModalMETSHeader.error.maximum\";\n public static final String I18N_CREATIONMODALMETSHEADER_ERROR_ONE_OF = \"CreationModalMETSHeader.error.oneOf\";\n public static final String I18N_CREATIONMODALMETSHEADER_ERROR_MANDATORY_CAN_NOT_BE_BLANK = \"CreationModalMETSHeader.error.mandatoryCanNotBeBlank\";\n public static final String I18N_CREATIONMODALMETSHEADER_ERROR_MANDATORY_WHEN = \"CreationModalMETSHeader.error.mandatoryWhen\";\n public static final String I18N_CREATIONMODALMETSHEADER_ERROR_MANDATORY = \"CreationModalMETSHeader.error.mandatory\";\n public static final String I18N_CREATIONMODALMETSHEADER_WARNING_MAXIMUM = \"CreationModalMETSHeader.warning.maximum\";\n public static final String I18N_CREATIONMODALMETSHEADER_HELPER_BLANK = \"CreationModalMETSHeader.helper.blank\";\n public static final String I18N_CREATIONMODALPREPARATION_CHOOSE = \"CreationModalPreparation.choose\";\n public static final String I18N_CREATIONMODALPREPARATION_CREATE_REPORT = \"CreationModalPreparation.createReport\";\n public static final String I18N_CREATIONMODALPREPARATION_CREATING_SIPS = \"CreationModalPreparation.creatingSips\";\n public static final String I18N_CREATIONMODALPREPARATION_EXPORT_ALL = \"CreationModalPreparation.exportAll\";\n public static final String I18N_CREATIONMODALPREPARATION_INCLUDE_HIERARCHY = \"CreationModalPreparation.includeHierarchy\";\n public static final String I18N_CREATIONMODALPREPARATION_OUTPUT_DIRECTORY = \"CreationModalPreparation.outputDirectory\";\n public static final String I18N_CREATIONMODALPREPARATION_PREFIX = \"CreationModalPreparation.prefix\";\n public static final String I18N_CREATIONMODALPREPARATION_AGENT_NAME = \"CreationModalPreparation.submitterAgentName\";\n public static final String I18N_CREATIONMODALPREPARATION_AGENT_ID = \"CreationModalPreparation.submitterAgentID\";\n public static final String I18N_CREATIONMODALPREPARATION_TRANSFERRING = \"CreationModalPreparation.transferring\";\n public static final String I18N_CREATIONMODALPREPARATION_SERIAL = \"CreationModalPreparation.serial\";\n public static final String I18N_CREATIONMODALPREPARATION_SIP_FORMAT = \"CreationModalPreparation.sipFormat\";\n public static final String I18N_CREATIONMODALPROCESSING_ACTION = \"CreationModalProcessing.action\";\n public static final String I18N_CREATIONMODALPROCESSING_ALERT_HEADER = \"CreationModalProcessing.alert.header\";\n public static final String I18N_CREATIONMODALPROCESSING_ALERT_STACK_TRACE = \"CreationModalProcessing.alert.stacktrace\";\n public static final String I18N_CREATIONMODALPROCESSING_ALERT_TITLE = \"CreationModalProcessing.alert.title\";\n public static final String I18N_CREATIONMODALPROCESSING_CAUSE = \"CreationModalProcessing.cause\";\n public static final String I18N_CREATIONMODALPROCESSING_CURRENT_SIP = \"CreationModalProcessing.currentSip\";\n public static final String I18N_CREATIONMODALPROCESSING_EARK_PROGRESS = \"CreationModalProcessing.eark.progress\";\n public static final String I18N_CREATIONMODALPROCESSING_ELAPSED = \"CreationModalProcessing.elapsed\";\n public static final String I18N_CREATIONMODALPROCESSING_ERROR_MESSAGES_STOPPED_CONTENT = \"CreationModalProcessing.errorMessagesStopped.content\";\n public static final String I18N_CREATIONMODALPROCESSING_ERROR_MESSAGES_STOPPED_HEADER = \"CreationModalProcessing.errorMessagesStopped.header\";\n public static final String I18N_CREATIONMODALPROCESSING_ERRORS = \"CreationModalProcessing.errors\";\n public static final String I18N_CREATIONMODALPROCESSING_FINISHED = \"CreationModalProcessing.finished\";\n public static final String I18N_CREATIONMODALPROCESSING_HOUR = \"CreationModalProcessing.hour\";\n public static final String I18N_CREATIONMODALPROCESSING_HOURS = \"CreationModalProcessing.hours\";\n public static final String I18N_CREATIONMODALPROCESSING_IMPOSSIBLE_ESTIMATE = \"CreationModalProcessing.impossibleEstimate\";\n public static final String I18N_CREATIONMODALPROCESSING_LESS_MINUTE = \"CreationModalProcessing.lessMinute\";\n public static final String I18N_CREATIONMODALPROCESSING_LESS_SECONDS = \"CreationModalProcessing.lessSeconds\";\n public static final String I18N_CREATIONMODALPROCESSING_MINUTE = \"CreationModalProcessing.minute\";\n public static final String I18N_CREATIONMODALPROCESSING_MINUTES = \"CreationModalProcessing.minutes\";\n public static final String I18N_CREATIONMODALPROCESSING_OPEN_FOLDER = \"CreationModalProcessing.openfolder\";\n public static final String I18N_CREATIONMODALPROCESSING_REMAINING = \"CreationModalProcessing.remaining\";\n public static final String I18N_CREATIONMODALPROCESSING_SUBTITLE = \"CreationModalProcessing.subtitle\";\n public static final String I18N_DIRECTORY_CHOOSER_TITLE = \"directorychooser.title\";\n public static final String I18N_EXPORT_BOX_TITLE = \"ExportBox.title\";\n public static final String I18N_FILE_CHOOSER_TITLE = \"filechooser.title\";\n public static final String I18N_FILE_EXPLORER_PANE_ALERT_ADD_FOLDER_CONTENT = \"FileExplorerPane.alertAddFolder.content\";\n public static final String I18N_FILE_EXPLORER_PANE_ALERT_ADD_FOLDER_HEADER = \"FileExplorerPane.alertAddFolder.header\";\n public static final String I18N_FILE_EXPLORER_PANE_ALERT_ADD_FOLDER_TITLE = \"FileExplorerPane.alertAddFolder.title\";\n public static final String I18N_FILE_EXPLORER_PANE_CHOOSE_DIR = \"FileExplorerPane.chooseDir\";\n public static final String I18N_FILE_EXPLORER_PANE_HELP_TITLE = \"FileExplorerPane.help.title\";\n public static final String I18N_FILE_EXPLORER_PANE_REMOVE_FOLDER = \"FileExplorerPane.removeFolder\";\n public static final String I18N_FILE_EXPLORER_PANE_TITLE = \"FileExplorerPane.title\";\n public static final String I18N_FOOTER_MEMORY = \"Footer.memory\";\n public static final String I18N_GENERIC_ERROR_CONTENT = \"genericError.content\";\n public static final String I18N_GENERIC_ERROR_TITLE = \"genericError.title\";\n public static final String I18N_INSPECTIONPANE_ADDMETADATA = \"InspectionPane.addMetadata\";\n public static final String I18N_INSPECTIONPANE_ADD_METADATA_ERROR_CONTENT = \"InspectionPane.addMetadataError.content\";\n public static final String I18N_INSPECTIONPANE_ADD_METADATA_ERROR_HEADER = \"InspectionPane.addMetadataError.header\";\n public static final String I18N_INSPECTIONPANE_ADD_METADATA_ERROR_TITLE = \"InspectionPane.addMetadataError.title\";\n public static final String I18N_INSPECTIONPANE_ADD_REPRESENTATION = \"InspectionPane.addRepresentation\";\n public static final String I18N_INSPECTIONPANE_CHANGE_TEMPLATE_CONTENT = \"InspectionPane.changeTemplate.content\";\n public static final String I18N_INSPECTIONPANE_CHANGE_TEMPLATE_HEADER = \"InspectionPane.changeTemplate.header\";\n public static final String I18N_INSPECTIONPANE_CHANGE_TEMPLATE_TITLE = \"InspectionPane.changeTemplate.title\";\n public static final String I18N_INSPECTIONPANE_DOCS_HELP_TITLE = \"InspectionPane.docsHelp.title\";\n public static final String I18N_INSPECTIONPANE_FORM = \"InspectionPane.form\";\n public static final String I18N_INSPECTIONPANE_HELP_RULE_LIST = \"InspectionPane.help.ruleList\";\n public static final String I18N_INSPECTIONPANE_HELP_TITLE = \"InspectionPane.help.title\";\n public static final String I18N_INSPECTIONPANE_METADATA = \"InspectionPane.metadata\";\n public static final String I18N_INSPECTIONPANE_MULTIPLE_SELECTED_APPLIED_MESSAGE = \"InspectionPane.multipleSelected.appliedMessage\";\n public static final String I18N_INSPECTIONPANE_MULTIPLE_SELECTED_CONFIRM = \"InspectionPane.multipleSelected.confirm\";\n public static final String I18N_INSPECTIONPANE_MULTIPLE_SELECTED_HELP = \"InspectionPane.multipleSelected.help\";\n public static final String I18N_INSPECTIONPANE_MULTIPLE_SELECTED_HELP_TITLE = \"InspectionPane.multipleSelected.helpTitle\";\n public static final String I18N_INSPECTIONPANE_ON_DROP = \"InspectionPane.onDrop\";\n public static final String I18N_INSPECTIONPANE_ON_DROP_DOCS = \"InspectionPane.onDropDocs\";\n public static final String I18N_INSPECTIONPANE_REMOVE_METADATA = \"InspectionPane.removeMetadata\";\n public static final String I18N_INSPECTIONPANE_REMOVE_METADATA_CONTENT = \"InspectionPane.removeMetadata.content\";\n public static final String I18N_INSPECTIONPANE_REMOVE_METADATA_HEADER = \"InspectionPane.removeMetadata.header\";\n public static final String I18N_INSPECTIONPANE_REMOVE_METADATA_TITLE = \"InspectionPane.removeMetadata.title\";\n public static final String I18N_INSPECTIONPANE_REPRESENTATION_TYPE_TOOLTIP = \"InspectionPane.representationTypeTooltip\";\n public static final String I18N_INSPECTIONPANE_RULES = \"InspectionPane.rules\";\n public static final String I18N_INSPECTIONPANE_SIP_TYPE_TOOLTIP = \"InspectionPane.sipTypeTooltip\";\n public static final String I18N_INSPECTIONPANE_TEXTCONTENT = \"InspectionPane.textContent\";\n public static final String I18N_INSPECTIONPANE_TITLE = \"InspectionPane.title\";\n public static final String I18N_INSPECTIONPANE_VALIDATE = \"InspectionPane.validate\";\n public static final String I18N_INSPECTIONPANE_IP_CONTENT_TYPE_PREFIX = \"IPContentType.\";\n public static final String I18N_INSPECTIONPANE_REPRESENTATION_CONTENT_TYPE_PREFIX = \"RepresentationContentType.\";\n public static final String I18N_MAIN_ADD_FOLDER = \"Main.addFolder\";\n public static final String I18N_MAIN_CHECK_VERSION = \"Main.checkVersion\";\n public static final String I18N_MAIN_CLASS_SCHEME = \"Main.classScheme\";\n public static final String I18N_MAIN_CONFIRM_RESET_CONTENT = \"Main.confirmReset.content\";\n public static final String I18N_MAIN_CONFIRM_RESET_HEADER = \"Main.confirmReset.header\";\n public static final String I18N_MAIN_CREATE_CS = \"Main.createCS\";\n public static final String I18N_MAIN_EDIT = \"Main.edit\";\n public static final String I18N_MAIN_EXPORT_CS = \"Main.exportCS\";\n public static final String I18N_MAIN_EXPORT_SIPS = \"Main.exportSips\";\n public static final String I18N_MAIN_FILE = \"Main.file\";\n public static final String I18N_MAIN_HELP = \"Main.help\";\n public static final String I18N_MAIN_HELP_PAGE = \"Main.helpPage\";\n public static final String I18N_MAIN_HIDE_FILES = \"Main.hideFiles\";\n public static final String I18N_MAIN_HIDE_HELP = \"Main.hideHelp\";\n public static final String I18N_MAIN_HIDE_IGNORED = \"Main.hideIgnored\";\n public static final String I18N_MAIN_HIDE_MAPPED = \"Main.hideMapped\";\n public static final String I18N_MAIN_IGNORE_ITEMS = \"Main.ignoreItems\";\n public static final String I18N_MAIN_LANGUAGE = \"Main.language\";\n public static final String I18N_MAIN_LOADCS = \"Main.loadCS\";\n public static final String I18N_MAIN_NEW_VERSION_HEADER = \"Main.newVersion.header\";\n public static final String I18N_MAIN_NO_UPDATES_CONTENT = \"Main.noUpdates.content\";\n public static final String I18N_MAIN_NO_UPDATES_HEADER = \"Main.noUpdates.header\";\n public static final String I18N_MAIN_OPEN_CONFIGURATION_FOLDER = \"Main.openConfigurationFolder\";\n public static final String I18N_MAIN_QUIT = \"Main.quit\";\n public static final String I18N_MAIN_RESET = \"Main.reset\";\n public static final String I18N_MAIN_SHOW_FILES = \"Main.showFiles\";\n public static final String I18N_MAIN_SHOW_HELP = \"Main.showHelp\";\n public static final String I18N_MAIN_SHOW_IGNORED = \"Main.showIgnored\";\n public static final String I18N_MAIN_SHOW_MAPPED = \"Main.showMapped\";\n public static final String I18N_MAIN_UPDATE_LANG_CONTENT = \"Main.updateLang.content\";\n public static final String I18N_MAIN_UPDATE_LANG_HEADER = \"Main.updateLang.header\";\n public static final String I18N_MAIN_UPDATE_LANG_TITLE = \"Main.updateLang.title\";\n public static final String I18N_MAIN_USE_JAVA8 = \"Main.useJava8\";\n public static final String I18N_MAIN_VIEW = \"Main.view\";\n public static final String I18N_METADATA_DIFF_FOLDER_DESCRIPTION = \"metadata.diffFolder.description\";\n public static final String I18N_METADATA_DIFF_FOLDER_TITLE = \"metadata.diffFolder.title\";\n public static final String I18N_METADATA_EMPTY_FILE_DESCRIPTION = \"metadata.emptyFile.description\";\n public static final String I18N_METADATA_EMPTY_FILE_TITLE = \"metadata.emptyFile.title\";\n public static final String I18N_METADATA_SAME_FOLDER_DESCRIPTION = \"metadata.sameFolder.description\";\n public static final String I18N_METADATA_SAME_FOLDER_TITLE = \"metadata.sameFolder.title\";\n public static final String I18N_METADATA_SINGLE_FILE_DESCRIPTION = \"metadata.singleFile.description\";\n public static final String I18N_METADATA_SINGLE_FILE_TITLE = \"metadata.singleFile.title\";\n public static final String I18N_METADATA_TEMPLATE_DESCRIPTION = \"metadata.template.description\";\n public static final String I18N_METADATA_TEMPLATE_TITLE = \"metadata.template.title\";\n public static final String I18N_RULECELL_CREATED_ITEM = \"RuleCell.createdItem\";\n public static final String I18N_RULEMODALPANE_ASSOCIATION_METHOD = \"RuleModalPane.associationMethod\";\n public static final String I18N_RULEMODALPANE_CHOOSE_DIRECTORY = \"RuleModalPane.chooseDirectory\";\n public static final String I18N_RULEMODALPANE_CHOOSE_FILE = \"RuleModalPane.chooseFile\";\n public static final String I18N_RULEMODALPANE_METADATA_METHOD = \"RuleModalPane.metadataMethod\";\n public static final String I18N_RULEMODALPANE_METADATA_PATTERN = \"RuleModalPane.metadataPattern\";\n public static final String I18N_RULEMODALPROCESSING_CREATED_PREVIEWS = \"RuleModalProcessing.createdPreviews\";\n public static final String I18N_RULEMODALPROCESSING_CREATING_PREVIEW = \"RuleModalProcessing.creatingPreview\";\n public static final String I18N_RULEMODALPROCESSING_PROCESSED_DIRS_FILES = \"RuleModalProcessing.processedDirsFiles\";\n public static final String I18N_RULEMODALREMOVING_REMOVED_FORMAT = \"RuleModalRemoving.removedFormat\";\n public static final String I18N_RULEMODALREMOVING_TITLE = \"RuleModalRemoving.title\";\n public static final String I18N_SCHEMAPANE_ADD = \"SchemaPane.add\";\n public static final String I18N_SCHEMAPANE_CONFIRM_NEW_SCHEME_CONTENT = \"SchemaPane.confirmNewScheme.content\";\n public static final String I18N_SCHEMAPANE_CONFIRM_NEW_SCHEME_HEADER = \"SchemaPane.confirmNewScheme.header\";\n public static final String I18N_SCHEMAPANE_CONFIRM_NEW_SCHEME_TITLE = \"SchemaPane.confirmNewScheme.title\";\n public static final String I18N_SCHEMAPANE_CONFIRM_REMOVE_CONTENT = \"SchemaPane.confirmRemove.content\";\n public static final String I18N_SCHEMAPANE_CONFIRM_REMOVE_HEADER = \"SchemaPane.confirmRemove.header\";\n public static final String I18N_SCHEMAPANE_CONFIRM_REMOVE_TITLE = \"SchemaPane.confirmRemove.title\";\n public static final String I18N_SCHEMAPANE_CREATE = \"SchemaPane.create\";\n public static final String I18N_SCHEMAPANE_DRAG_HELP = \"SchemaPane.dragHelp\";\n public static final String I18N_SCHEMAPANE_HELP_TITLE = \"SchemaPane.help.title\";\n public static final String I18N_SCHEMAPANE_NEW_NODE = \"SchemaPane.newNode\";\n public static final String I18N_SCHEMAPANE_OR = \"SchemaPane.or\";\n public static final String I18N_SCHEMAPANE_REMOVE = \"SchemaPane.remove\";\n public static final String I18N_SCHEMAPANE_TITLE = \"SchemaPane.title\";\n public static final String I18N_SCHEMAPANE_TOO_MANY_SELECTED_CONTENT = \"SchemaPane.tooManySelected.content\";\n public static final String I18N_SCHEMAPANE_TOO_MANY_SELECTED_HEADER = \"SchemaPane.tooManySelected.header\";\n public static final String I18N_SCHEMAPANE_TOO_MANY_SELECTED_TITLE = \"SchemaPane.tooManySelected.title\";\n public static final String I18N_SIMPLE_SIP_CREATOR_COPYING_DATA = \"SimpleSipCreator.copyingData\";\n public static final String I18N_SIMPLE_SIP_CREATOR_DOCUMENTATION = \"SimpleSipCreator.documentation\";\n public static final String I18N_SIMPLE_SIP_CREATOR_INIT_ZIP = \"SimpleSipCreator.initZIP\";\n public static final String I18N_SIMPLE_SIP_CREATOR_CREATING_STRUCTURE = \"SimpleSipCreator.creatingStructure\";\n public static final String I18N_SIMPLE_SIP_CREATOR_COPYING_METADATA = \"SimpleSipCreator.copyingMetadata\";\n public static final String I18N_SIMPLE_SIP_CREATOR_FINALIZING_SIP = \"SimpleSipCreator.finalizingSip\";\n public static final String I18N_SOURCE_TREE_CELL_REMOVE = \"SourceTreeCell.remove\";\n public static final String I18N_SOURCE_TREE_LOADING_TITLE = \"SourceTreeLoading.title\";\n public static final String I18N_SOURCE_TREE_LOAD_MORE_TITLE = \"SourceTreeLoadMore.title\";\n public static final String I18N_ADD = \"add\";\n public static final String I18N_AND = \"and\";\n public static final String I18N_APPLY = \"apply\";\n public static final String I18N_ASSOCIATE = \"associate\";\n public static final String I18N_BACK = \"back\";\n public static final String I18N_CANCEL = \"cancel\";\n public static final String I18N_CLEAR = \"clear\";\n public static final String I18N_CLOSE = \"close\";\n public static final String I18N_COLLAPSE = \"collapse\";\n public static final String I18N_CONFIRM = \"confirm\";\n public static final String I18N_CONTINUE = \"continue\";\n public static final String I18N_CREATIONMODALPROCESSING_REPRESENTATION = \"CreationModalProcessing.representation\";\n public static final String I18N_DATA = \"data\";\n public static final String I18N_DIRECTORIES = \"directories\";\n public static final String I18N_DIRECTORY = \"directory\";\n public static final String I18N_DOCUMENTATION = \"documentation\";\n public static final String I18N_DONE = \"done\";\n public static final String I18N_ERROR_VALIDATING_METADATA = \"errorValidatingMetadata\";\n public static final String I18N_EXPAND = \"expand\";\n public static final String I18N_EXPORT = \"export\";\n public static final String I18N_FILE = \"file\";\n public static final String I18N_FILES = \"files\";\n public static final String I18N_FOLDERS = \"folders\";\n public static final String I18N_HELP = \"help\";\n public static final String I18N_IGNORE = \"ignore\";\n public static final String I18N_INVALID_METADATA = \"invalidMetadata\";\n public static final String I18N_IP_CONTENT_TYPE = \"IPContentType.\";\n public static final String I18N_ITEMS = \"items\";\n public static final String I18N_LOAD = \"load\";\n public static final String I18N_LOADINGPANE_CREATE_ASSOCIATION = \"LoadingPane.createAssociation\";\n public static final String I18N_NAME = \"name\";\n public static final String I18N_REMOVE = \"remove\";\n public static final String I18N_REPRESENTATION_CONTENT_TYPE = \"RepresentationContentType.\";\n public static final String I18N_RESTART = \"restart\";\n public static final String I18N_ROOT = \"root\";\n public static final String I18N_SELECTED = \"selected\";\n public static final String I18N_SIP_NAME_STRATEGY = \"sipNameStrategy.\";\n public static final String I18N_START = \"start\";\n public static final String I18N_TYPE = \"type\";\n public static final String I18N_VALID_METADATA = \"validMetadata\";\n public static final String I18N_VERSION = \"version\";\n public static final String I18N_RENAME_REPRESENTATION = \"RenameModalProcessing.renameRepresentation\";\n public static final String I18N_RENAME = \"rename\";\n public static final String I18N_RENAME_REPRESENTATION_ALREADY_EXISTS = \"RenameModalProcessing.renameAlreadyExists\";\n\n public static final String CONF_K_REFERENCE_TRANSFORMER_LIST = \"reference.transformer.list[]\";\n public static final String CONF_K_REFERENCE_TRANSFORMER = \"reference.transformer.\";\n\n /*\n * ENUMs\n */\n // sip type\n public enum SipType {\n EARK(EarkSipCreator.getText(), EarkSipCreator.requiresMETSHeaderInfo(), EarkSipCreator.ipSpecificContentTypes(),\n EarkSipCreator.representationSpecificContentTypes(), SipNameStrategy.ID, SipNameStrategy.TITLE_ID,\n SipNameStrategy.TITLE_DATE),\n EARK2(EarkSip2Creator.getText(), EarkSip2Creator.requiresMETSHeaderInfo(), EarkSip2Creator.ipSpecificContentTypes(),\n EarkSip2Creator.representationSpecificContentTypes(), SipNameStrategy.ID, SipNameStrategy.TITLE_ID,\n SipNameStrategy.TITLE_DATE),\n BAGIT(BagitSipCreator.getText(), BagitSipCreator.requiresMETSHeaderInfo(), BagitSipCreator.ipSpecificContentTypes(),\n BagitSipCreator.representationSpecificContentTypes(), SipNameStrategy.ID, SipNameStrategy.TITLE_ID,\n SipNameStrategy.TITLE_DATE),\n HUNGARIAN(HungarianSipCreator.getText(), HungarianSipCreator.requiresMETSHeaderInfo(),\n HungarianSipCreator.ipSpecificContentTypes(), HungarianSipCreator.representationSpecificContentTypes(),\n SipNameStrategy.DATE_TRANSFERRING_SERIALNUMBER),\n EARK2S(ShallowSipCreator.getText(), ShallowSipCreator.requiresMETSHeaderInfo(),\n ShallowSipCreator.ipSpecificContentTypes(), ShallowSipCreator.representationSpecificContentTypes(),\n SipNameStrategy.ID, SipNameStrategy.TITLE_ID, SipNameStrategy.TITLE_DATE);\n\n private final String text;\n private Set<SipNameStrategy> sipNameStrategies;\n private boolean requiresMETSHeaderInfo;\n private List<IPContentType> ipContentTypes;\n private List<RepresentationContentType> representationContentTypes;\n\n private static SipType[] filteredValues = null;\n private static List<Pair<SipType, List<IPContentType>>> filteredIpContentTypes = null;\n private static List<Pair<SipType, List<RepresentationContentType>>> filteredRepresentationContentTypes = null;\n\n private SipType(final String text, boolean requiresMETSHeaderInfo, List<IPContentType> ipContentTypes,\n List<RepresentationContentType> representationContentTypes, SipNameStrategy... sipNameStrategies) {\n this.text = text;\n this.requiresMETSHeaderInfo = requiresMETSHeaderInfo;\n this.ipContentTypes = ipContentTypes;\n this.representationContentTypes = representationContentTypes;\n this.sipNameStrategies = new LinkedHashSet<>();\n for (SipNameStrategy sipNameStrategy : sipNameStrategies) {\n this.sipNameStrategies.add(sipNameStrategy);\n }\n }\n\n /**\n * Used instead of SipType#values to get the values of this enum that are\n * enabled (according to the configuration).\n *\n * @return a SipType list filtered according to configuration.\n */\n public static SipType[] getFilteredValues() {\n if (filteredValues == null) {\n List<SipType> list = Arrays.asList(SipType.values());\n List<String> allowedValues = Arrays\n .asList(ConfigurationManager.getConfigAsStringArray(CONF_K_ACTIVE_SIP_TYPES));\n filteredValues = list.stream().filter(m -> allowedValues.contains(m.name())).collect(Collectors.toList())\n .toArray(new SipType[] {});\n }\n return filteredValues;\n }\n\n public static List<Pair<SipType, List<IPContentType>>> getFilteredIpContentTypes() {\n if (filteredIpContentTypes == null) {\n filteredIpContentTypes = new ArrayList<Pair<SipType, List<IPContentType>>>();\n for (SipType sipType : getFilteredValues()) {\n filteredIpContentTypes.add(new Pair<>(sipType, sipType.getIpContentTypes()));\n }\n }\n return filteredIpContentTypes;\n }\n\n public static List<Pair<SipType, List<RepresentationContentType>>> getFilteredRepresentationContentTypes() {\n if (filteredRepresentationContentTypes == null) {\n filteredRepresentationContentTypes = new ArrayList<>();\n for (SipType sipType : getFilteredValues()) {\n filteredRepresentationContentTypes.add(new Pair<>(sipType, sipType.getRepresentationContentTypes()));\n }\n }\n return filteredRepresentationContentTypes;\n }\n\n public List<IPContentType> getIpContentTypes() {\n return ipContentTypes;\n }\n\n public List<RepresentationContentType> getRepresentationContentTypes() {\n return representationContentTypes;\n }\n\n public boolean requiresMETSHeaderInfo() {\n return this.requiresMETSHeaderInfo;\n }\n\n public Set<SipNameStrategy> getSipNameStrategies() {\n return this.sipNameStrategies;\n }\n\n @Override\n public String toString() {\n return text;\n }\n }\n\n // sip name strategy\n public enum SipNameStrategy {\n ID, TITLE_ID, TITLE_DATE, DATE_TRANSFERRING_SERIALNUMBER\n }\n\n // path state\n public enum PathState {\n NORMAL, IGNORED, MAPPED\n }\n\n public enum RuleType {\n SINGLE_SIP, SIP_PER_FILE, SIP_WITH_STRUCTURE, SIP_PER_SELECTION\n }\n\n public enum MetadataOption {\n SINGLE_FILE, SAME_DIRECTORY, DIFF_DIRECTORY, TEMPLATE, NEW_FILE;\n\n /**\n * Translates the value that was serialized to the Enum.\n * \n * @param value\n * The serialized value.\n * @return The translated value.\n */\n @JsonCreator\n public static MetadataOption getEnumFromValue(String value) {\n if (\"\".equals(value))\n return SINGLE_FILE;\n for (MetadataOption testEnum : values()) {\n if (testEnum.toString().equals(value)) {\n return testEnum;\n }\n }\n throw new IllegalArgumentException();\n }\n }\n\n public enum VisitorState {\n VISITOR_DONE, VISITOR_QUEUED, VISITOR_NOTSUBMITTED, VISITOR_RUNNING, VISITOR_CANCELLED\n }\n\n private Constants() {\n // do nothing\n }\n}",
"public enum MetadataOption {\n SINGLE_FILE, SAME_DIRECTORY, DIFF_DIRECTORY, TEMPLATE, NEW_FILE;\n\n /**\n * Translates the value that was serialized to the Enum.\n * \n * @param value\n * The serialized value.\n * @return The translated value.\n */\n @JsonCreator\n public static MetadataOption getEnumFromValue(String value) {\n if (\"\".equals(value))\n return SINGLE_FILE;\n for (MetadataOption testEnum : values()) {\n if (testEnum.toString().equals(value)) {\n return testEnum;\n }\n }\n throw new IllegalArgumentException();\n }\n}",
"public class Controller {\n private static final Logger LOGGER = LoggerFactory.getLogger(Controller.class.getName());\n private static final String SYSTEM_OS = System.getProperty(\"os.name\").toLowerCase();\n\n public Controller() {\n // do nothing\n }\n\n /**\n * Method that checks for updates (that is, if this is the latest app version\n * available).\n * \n * @param checkForEnvVariable\n * \n * @return empty if app is up to date or optional<string> with the message\n * explaining the version differences\n */\n public static Optional<String> checkForUpdates(boolean checkForEnvVariable) {\n Optional<String> res = Optional.empty();\n\n String rodaInEnv = System.getenv(Constants.RODAIN_ENV_VARIABLE);\n if (!(checkForEnvVariable && Constants.RODAIN_ENV_TESTING.equals(rodaInEnv))) {\n try {\n String currentVersion = getCurrentVersion();\n String latestVersion = getLatestVersion();\n\n if (currentVersion != null && latestVersion != null && !currentVersion.equals(latestVersion)) {\n String content = String.format(I18n.t(Constants.I18N_NEW_VERSION_CONTENT), currentVersion, latestVersion);\n res = Optional.ofNullable(content);\n }\n } catch (ConfigurationException e) {\n LOGGER.error(\"Could not retrieve application version from build.properties\", e);\n } catch (URISyntaxException e) {\n LOGGER.warn(\"The URI is malformed\", e);\n } catch (IOException e) {\n LOGGER.warn(\"Error accessing the GitHub API\", e);\n }\n }\n return res;\n }\n\n public static void exportClassificationScheme(Set<SchemaNode> nodes, String outputFile) {\n List<Sip> dobjs = new ArrayList<>();\n for (SchemaNode sn : nodes) {\n dobjs.add(sn.getDob());\n }\n ClassificationSchema cs = new ClassificationSchema();\n cs.setDos(dobjs);\n ControllerUtils.exportClassificationScheme(cs, outputFile);\n ConfigurationManager.setAppConfig(Constants.CONF_K_APP_LAST_CLASS_SCHEME, outputFile, true);\n }\n\n public static ClassificationSchema loadClassificationSchemaFile(String filePath) throws IOException {\n ConfigurationManager.setAppConfig(Constants.CONF_K_APP_LAST_CLASS_SCHEME, filePath, true);\n try (InputStream input = new FileInputStream(filePath)) {\n\n // create ObjectMapper instance\n ObjectMapper objectMapper = new ObjectMapper();\n\n // convert json string to object\n return objectMapper.readValue(input, ClassificationSchema.class);\n }\n }\n\n public static boolean validateSchema(Path fileToValidate, InputStream schemaInputStream)\n throws SAXException, IOException {\n String fileContent = ControllerUtils.readFile(fileToValidate);\n return validateSchema(fileContent, schemaInputStream);\n }\n\n public static boolean validateSchema(String content, InputStream schemaInputStream) throws SAXException {\n return ControllerUtils.validateSchema(content, schemaInputStream);\n }\n\n public static String loadMetadataFile(Path path) throws IOException {\n return ControllerUtils.readFile(path);\n }\n\n public static String getCurrentVersion() throws ConfigurationException {\n return ControllerUtils.getCurrentVersion();\n }\n\n public static Optional<String> getCurrentVersionSilently() {\n try {\n return Optional.ofNullable(ControllerUtils.getCurrentVersion());\n } catch (ConfigurationException e) {\n return Optional.empty();\n }\n }\n\n private static String getLatestVersion() throws URISyntaxException, IOException {\n return ControllerUtils.getLatestVersion();\n }\n\n private static Date getCurrentVersionBuildDate() throws ConfigurationException {\n return ControllerUtils.getCurrentVersionBuildDate();\n }\n\n private static Date getLatestVersionBuildDate() throws URISyntaxException, IOException {\n return ControllerUtils.getLatestVersionBuildDate();\n }\n\n public static String createID() {\n return ControllerUtils.createID();\n }\n\n public static String indentXML(String content) {\n return ControllerUtils.indentXML(content);\n }\n\n public static DescriptiveMetadata updateTemplate(DescriptiveMetadata dom) {\n return ControllerUtils.updateTemplate(dom);\n }\n\n /**\n * Formats a number to a readable size format (B, KB, MB, GB, etc)\n *\n * @param v\n * The value to be formatted\n * @return The formatted String\n */\n public static String formatSize(long size) {\n return ControllerUtils.formatSize(size);\n }\n\n /**\n * <p>\n * Encodes ID chars that are dangerous to file systems or jar files entries.\n * We will URLEncode, but just some chars that we think are dangerous.\n * </p>\n * \n * <p>\n * We will start by replacing all \"%\" => \"%25\", and then all the others\n * (forward slashes, etc.).\n * </p>\n * \n * @param unsafeId\n * non-null string to be encoded for safe use in file systems or jar\n * files\n * \n */\n public static String encodeId(String unsafeId) {\n return unsafeId.replaceAll(\"%\", \"%25\").replaceAll(\"/\", \"%2F\").replaceAll(\"\\\\\\\\\", \"%5C\");\n }\n\n public static boolean systemIsWindows() {\n return SYSTEM_OS.contains(\"win\");\n }\n\n public static boolean systemIsMac() {\n return SYSTEM_OS.contains(\"mac\");\n }\n\n public static boolean systemIsUnix() {\n return SYSTEM_OS.contains(\"nix\") || SYSTEM_OS.contains(\"nux\") || SYSTEM_OS.contains(\"aix\");\n }\n}",
"public class ContentFilter {\n private HashSet<String> ignored;\n private HashSet<String> mapped;\n\n /**\n * Creates a new ContentFilter object\n */\n public ContentFilter() {\n ignored = new HashSet<>();\n mapped = new HashSet<>();\n }\n\n /**\n * Adds the path to the ignored paths list.\n *\n * @param st\n * The path to be added to the ignored paths list.\n */\n public void addIgnored(String st) {\n ignored.add(st);\n }\n\n /**\n * Adds the all the paths in the collection to the ignored paths list.\n *\n * @param col\n * The collection of paths to be added to the ignored paths list.\n */\n public void addAllIgnored(Collection col) {\n ignored.addAll(col);\n }\n\n /**\n * Adds the path to the mapped paths list.\n *\n * @param st\n * The path to be added to the mapped paths list.\n */\n public void addMapped(String st) {\n mapped.add(st);\n }\n\n /**\n * Adds the all the paths in the collection to the mapped paths list.\n *\n * @param col\n * The collection of paths to be added to the mapped paths list.\n */\n public void addAllMapped(Collection col) {\n mapped.addAll(col);\n }\n\n /**\n * Checks the ignored and mapped path lists and the PathCollection to\n * determine if the path should be filtered.\n * <p/>\n * <p>\n * Additionally, checks if any ancestor of the path is in one of the lists.\n * </p>\n *\n * @param path\n * The path to be filtered\n * @return True if the path or any of its ancestors is in any of the lists, or\n * if the state of the path in the PathCollection isn't NORMAL, false\n * otherwise.\n */\n public boolean filter(String path) {\n boolean result = false;\n if (ignored.contains(path) || mapped.contains(path)\n || PathCollection.getState(Paths.get(path)) != PathState.NORMAL\n || IgnoredFilter.isIgnored(Paths.get(path))) {\n result = true;\n } else if (path.startsWith(\"\\\\\\\\\")) {\n //for UNC paths iterations throw the subs will bring an exception\n return false;\n } else {\n int index = 0, end = path.length(), fromIndex = 0;\n String separator = File.separator;\n\n while (index < end && !result) { // while we still have string to read and\n // haven't found a matching path\n index = path.indexOf(separator, fromIndex); // get the path until the\n // slash we're checking\n if (index == -1) {\n break;\n } else {\n String sub = path.substring(0, index);\n fromIndex = index + 1; // move the starting index for the next\n // iteration so it's after the slash\n if (ignored.contains(sub) || mapped.contains(sub) || IgnoredFilter.isIgnored(Paths.get(sub))) {\n result = true;\n }\n }\n }\n }\n return result;\n }\n\n}",
"@JsonIgnoreProperties({\"path\", \"loaded\", \"values\"})\npublic class DescriptiveMetadata {\n private static final Logger LOGGER = LoggerFactory.getLogger(DescriptiveMetadata.class.getName());\n private String id, content, contentEncoding, metadataType;\n private List<String> relatedTags = new ArrayList<>();\n private Map<String, Object> additionalProperties = new HashMap<>();\n private TreeSet<TemplateFieldValue> values;\n private Path path;\n private boolean loaded = false;\n\n // template\n private MetadataOption creatorOption;\n private String metadataVersion, templateType;\n\n public DescriptiveMetadata() {\n creatorOption = MetadataOption.NEW_FILE;\n }\n\n public DescriptiveMetadata(MetadataOption creatorOption, String templateType, String metadataType,\n String metadataVersion) {\n this.creatorOption = creatorOption;\n this.templateType = templateType;\n this.metadataVersion = metadataVersion;\n this.contentEncoding = Constants.ENCODING_BASE64;\n this.metadataType = metadataType;\n if (templateType != null) {\n this.id = templateType + Constants.MISC_XML_EXTENSION;\n } else {\n this.id = (metadataType != null ? metadataType : \"\") + (metadataVersion != null ? \"_\" + metadataVersion : \"\")\n + Constants.MISC_XML_EXTENSION;\n }\n }\n\n public DescriptiveMetadata(MetadataOption creatorOption, Path path, String metadataType, String metadataVersion,\n String templateType) {\n this.creatorOption = creatorOption;\n this.path = path;\n this.metadataType = metadataType;\n this.contentEncoding = Constants.ENCODING_BASE64;\n this.metadataVersion = metadataVersion;\n this.templateType = templateType;\n if (templateType != null) {\n this.id = templateType + Constants.MISC_XML_EXTENSION;\n } else if (path != null) {\n this.id = path.getFileName().toString();\n }\n }\n\n public static DescriptiveMetadata buildDefaultDescObjMetadata() {\n return new DescriptiveMetadata(MetadataOption.TEMPLATE, \"ead2002\", \"ead\", \"2002\");\n }\n\n @JsonIgnore\n public Path getPath() {\n return path;\n }\n\n public void setPath(Path p) {\n path = p;\n }\n\n public void setMetadataType(String metadataType) {\n this.metadataType = metadataType;\n }\n\n public void setMetadataVersion(String metadataVersion) {\n this.metadataVersion = metadataVersion;\n }\n\n public void setTemplateType(String templateType) {\n this.templateType = templateType;\n }\n\n @JsonIgnore\n public boolean isLoaded() {\n return loaded;\n }\n\n public MetadataOption getCreatorOption() {\n return creatorOption;\n }\n\n public String getMetadataType() {\n return metadataType;\n }\n\n public void setCreatorOption(MetadataOption creatorOption) {\n this.creatorOption = creatorOption;\n }\n\n /**\n * @return The set of MetadataValue objects. Used to create the form.\n */\n @JsonIgnore\n public Set<TemplateFieldValue> getValues() {\n if (values == null) {\n // TODO FIX\n values = TemplateUtils.getTemplateFields(this);\n }\n return values;\n }\n\n public void setValues(TreeSet<TemplateFieldValue> val) {\n this.values = val;\n }\n\n public String getMetadataVersion() {\n return metadataVersion;\n }\n\n public String getTemplateType() {\n return templateType;\n }\n\n /**\n * Gets the id of the description object metadata.\n *\n * @return The id\n */\n public String getId() {\n return id;\n }\n\n /**\n * Sets the id of the description object metadata.\n *\n * @param id\n * The id\n */\n public void setId(String id) {\n this.id = id;\n }\n\n /**\n * Gets the content of the description object metadata.\n *\n * @return The content\n */\n public String getContent() {\n return this.content;\n }\n\n /**\n * Gets the decoded content of the description object metadata.\n *\n * @return The content decoded\n */\n @JsonIgnore\n public String getContentDecoded() {\n if (!loaded) {\n loadMetadata();\n }\n if (content != null) {\n byte[] decoded = Base64.decodeBase64(content);\n return new String(decoded);\n } else {\n return \"\";\n }\n }\n\n private void loadMetadata() {\n try {\n if (creatorOption == MetadataOption.TEMPLATE) {\n if (getTemplateType() != null && getContent() == null) {\n String tempContent = ConfigurationManager.getTemplateContent(getTemplateType());\n setContentDecoded(TemplateUtils.getXMLFromTemplate(tempContent));\n loaded = true;\n } else {\n loaded = true;\n }\n } else if (path != null) {\n String tempContent = Controller.loadMetadataFile(path);\n setContentDecoded(tempContent);\n loaded = true;\n\n }\n } catch (IOException e) {\n LOGGER.error(\"Error reading metadata file\", e);\n }\n }\n\n /**\n * Sets the content of the description object metadata. Set\n * \n * @param content\n * The content encoded in Base64\n */\n public void setContent(String content) {\n this.content = content;\n }\n\n /**\n * Sets the content of the description object metadata.\n *\n * @param content\n * The decoded content\n */\n public void setContentDecoded(String content) {\n if (content != null) {\n byte[] encoded = Base64.encodeBase64(content.getBytes());\n this.content = new String(encoded);\n }\n }\n\n /**\n * Gets the content encoding of the description object metadata.\n *\n * @return The content encoding\n */\n public String getContentEncoding() {\n return contentEncoding;\n }\n\n /**\n * Sets the content encoding of the description object metadata.\n *\n * @param contentEncoding\n * The contentEncoding\n */\n public void setContentEncoding(String contentEncoding) {\n this.contentEncoding = contentEncoding;\n }\n\n @JsonIgnore\n public InputStream getSchema() {\n // FIXME 20170307 hsilva: possible NPE\n InputStream result = null;\n if (templateType != null) {\n result = ConfigurationManager.getSchemaFile(templateType);\n } else {\n if (path != null)\n result = ConfigurationManager.getSchemaFile(FilenameUtils.removeExtension(path.getFileName().toString()));\n }\n return result;\n }\n\n /**\n * Gets the additional properties map.\n *\n * @return The additional properties map.\n */\n public Map<String, Object> getAdditionalProperties() {\n return this.additionalProperties;\n }\n\n /**\n * Sets an additional property.\n *\n * @param name\n * The name of the property.\n * @param value\n * The value of the property.\n */\n public void setAdditionalProperty(String name, Object value) {\n this.additionalProperties.put(name, value);\n }\n\n public List<String> getRelatedTags() {\n return relatedTags;\n }\n\n public void setRelatedTags(List<String> relatedTags) {\n this.relatedTags = relatedTags;\n }\n\n @Override\n public DescriptiveMetadata clone() {\n DescriptiveMetadata result = new DescriptiveMetadata();\n result.setCreatorOption(creatorOption);\n result.setId(id);\n result.setContent(content);\n result.setContentEncoding(contentEncoding);\n result.setValues((TreeSet<TemplateFieldValue>) values.clone());\n result.setPath(path);\n result.setMetadataVersion(metadataVersion);\n result.setMetadataType(metadataType);\n result.setTemplateType(templateType);\n result.setRelatedTags(relatedTags);\n return result;\n }\n\n @Override\n public String toString() {\n return \"DescObjMetadata [id=\" + id + \", content=\" + content + \", contentEncoding=\" + contentEncoding\n + \", metadataType=\" + metadataType + \", additionalProperties=\" + additionalProperties + \", values=\" + values\n + \", path=\" + path + \", loaded=\" + loaded + \", creatorOption=\" + creatorOption + \", metadataVersion=\"\n + metadataVersion + \", templateType=\" + templateType + \", relatedTags=\" + relatedTags + \"]\";\n }\n\n public void initializeValues() {\n values = TemplateUtils.getTemplateFields(this);\n }\n\n}",
"public class SipRepresentation {\n private String name;\n private RepresentationContentType type;\n private Set<TreeNode> files;\n\n public SipRepresentation(String name) {\n this.name = name;\n files = new HashSet<>();\n this.type = RepresentationContentType.defaultRepresentationContentType();\n }\n\n /**\n * @return The name of the SipRepresentation\n */\n public String getName() {\n return name;\n }\n\n /**\n * Sets the name of the SipRepresentation\n * \n * @param name\n * The name to be set.\n */\n public void setName(String name) {\n this.name = name;\n }\n\n /**\n * @return The set of direct TreeNode that the SipRepresentation contains.\n * @see TreeNode\n */\n public Set<TreeNode> getFiles() {\n return files;\n }\n\n /**\n * Adds a new file to the SipRepresentation's set of files.\n * \n * @param file\n * The file to be added.\n */\n public void addFile(TreeNode file) {\n files.add(file);\n }\n\n /**\n * Adds a new file to the SipRepresentation's set of files.\n * \n * @param path\n * The path of the file to be added.\n */\n public void addFile(Path path) {\n files.add(new TreeNode(path));\n }\n\n /**\n * Sets the set of files of the SipRepresentation\n * \n * @param files\n * The set of files to be set.\n */\n public void setFiles(Set<TreeNode> files) {\n this.files = files;\n }\n\n /**\n * Removes the TreeNode with the path received as parameter.\n *\n * @param path\n * The path of the TreeNode to be removed\n * @return The removed TreeNode\n */\n public TreeNode remove(Path path) {\n TreeNode toRemove = null;\n for (TreeNode tn : files) {\n if (tn.getPath().equals(path)) {\n toRemove = tn;\n break;\n }\n }\n if (toRemove != null) {\n files.remove(toRemove);\n }\n return toRemove;\n }\n\n public RepresentationContentType getType() {\n return type;\n }\n\n public void setType(RepresentationContentType type) {\n this.type = type;\n }\n\n}"
] | import java.io.File;
import java.io.IOException;
import java.nio.file.AccessDeniedException;
import java.nio.file.FileSystems;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Observable;
import java.util.Set;
import org.apache.commons.io.FilenameUtils;
import org.roda.rodain.core.ConfigurationManager;
import org.roda.rodain.core.Constants;
import org.roda.rodain.core.Constants.MetadataOption;
import org.roda.rodain.core.Controller;
import org.roda.rodain.core.rules.TreeNode;
import org.roda.rodain.core.rules.filters.ContentFilter;
import org.roda.rodain.core.schema.DescriptiveMetadata;
import org.roda.rodain.core.sip.SipPreview;
import org.roda.rodain.core.sip.SipRepresentation;
import org.roda.rodain.core.utils.TreeVisitor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | package org.roda.rodain.core.sip.creators;
/**
* @author Andre Pereira [email protected]
* @since 20-10-2015.
*/
public class SipPreviewCreator extends Observable implements TreeVisitor {
private static final Logger LOGGER = LoggerFactory.getLogger(SipPreviewCreator.class.getName());
private String startPath;
// This map is returned, in full, to the SipPreviewNode when there's an update
protected Map<String, SipPreview> sipsMap;
// This ArrayList is used to keep the SIPs ordered.
// We need them ordered because we have to keep track of which SIPs have
// already been loaded
protected List<SipPreview> sips;
protected int added = 0, returned = 0;
protected Deque<TreeNode> nodes;
protected Set<TreeNode> files;
private String id; | private Set<ContentFilter> filters; | 4 |
dperezcabrera/jpoker | src/main/java/org/poker/sample/strategies/SlowlyStrategy.java | [
"@NotThreadSafe\npublic class BetCommand {\n\n private final BetCommandType type;\n private long chips;\n\n public BetCommand(BetCommandType type) {\n this(type, 0);\n }\n\n public BetCommand(BetCommandType type, long chips) {\n ExceptionUtil.checkNullArgument(type, \"type\");\n ExceptionUtil.checkMinValueArgument(chips, 0L, \"chips\");\n this.type = type;\n this.chips = chips;\n }\n\n public BetCommandType getType() {\n return type;\n }\n\n public long getChips() {\n return chips;\n }\n\n public void setChips(long chips) {\n this.chips = chips;\n }\n\n @Override\n public String toString() {\n return String.join(\"{class:'BetCommand', type:'\", type.toString(), \"', chips:\", Long.toString(chips), \"}\");\n }\n}",
"@NotThreadSafe\npublic class GameInfo<P extends PlayerInfo> {\n\n private int round;\n private int dealer;\n private int playerTurn;\n private GameState gameState;\n private final List<Card> communityCards = new ArrayList<>(COMMUNITY_CARDS);\n private List<P> players;\n private Settings settings;\n\n public Settings getSettings() {\n return settings;\n }\n\n public void setSettings(Settings settings) {\n this.settings = settings;\n }\n\n public int getRound() {\n return round;\n }\n\n public void setRound(int round) {\n this.round = round;\n }\n\n public int getDealer() {\n return dealer;\n }\n\n public void setDealer(int dealer) {\n this.dealer = dealer;\n }\n\n public int getPlayerTurn() {\n return playerTurn;\n }\n\n public void setPlayerTurn(int playerTurn) {\n this.playerTurn = playerTurn;\n }\n\n public TexasHoldEmUtil.GameState getGameState() {\n return gameState;\n }\n\n public void setGameState(TexasHoldEmUtil.GameState gameState) {\n this.gameState = gameState;\n }\n\n public List<Card> getCommunityCards() {\n return new ArrayList<>(communityCards);\n }\n\n public void setCommunityCards(List<Card> communityCards) {\n this.communityCards.clear();\n this.communityCards.addAll(communityCards);\n }\n\n public List<P> getPlayers() {\n return new ArrayList<>(players);\n }\n\n public P getPlayer(int index) {\n return players.get(index);\n }\n\n public void setPlayers(List<P> players) {\n this.players = new ArrayList<>(players);\n }\n\n public boolean addPlayer(P player) {\n return this.players.add(player);\n }\n\n public boolean removePlayer(P player) {\n return this.players.remove(player);\n }\n\n public int getNumPlayers() {\n return players.size();\n }\n\n public boolean addCommunityCard(Card card) {\n boolean result = false;\n if (communityCards.size() < COMMUNITY_CARDS) {\n result = communityCards.add(card);\n }\n return result;\n }\n\n public void clearCommunityCard() {\n this.communityCards.clear();\n }\n\n @Override\n public String toString() {\n return \"{class:'GameInfo', round:\" + round + \", dealer:\" + dealer + ((playerTurn < 0) ? \"\" : (\", playerTurn:\" + playerTurn)) + \", gameState:'\" + gameState + \"', communityCards:\" + communityCards + \", settings:\" + settings + \", players:\" + players + '}';\n }\n}",
"@FunctionalInterface\npublic interface IStrategy {\n\n public String getName();\n\n public default BetCommand getCommand(GameInfo<PlayerInfo> state) {\n return null;\n }\n\n public default void initHand(GameInfo<PlayerInfo> state) {\n }\n \n public default void endHand(GameInfo<PlayerInfo> state) {\n }\n \n public default void endGame(Map<String, Double> scores) {\n }\n\n public default void check(List<Card> communityCards) {\n }\n\n public default void onPlayerCommand(String player, BetCommand betCommand) {\n }\n}",
"@NotThreadSafe\npublic class PlayerInfo {\n \n private String name;\n private long chips;\n private long bet;\n private final Card[] cards = new Card[TexasHoldEmUtil.PLAYER_CARDS];\n private PlayerState state;\n private int errors;\n\n public boolean isActive() {\n return state.isActive();\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public long getChips() {\n return chips;\n }\n\n public void setChips(long chips) {\n this.chips = chips;\n }\n\n public void addChips(long chips) {\n this.chips += chips;\n }\n\n public long getBet() {\n return bet;\n }\n\n public void setBet(long bet) {\n this.bet = bet;\n }\n\n public Card[] getCards() {\n return new Card[]{cards[0], cards[1]};\n }\n\n public void setCards(Card[] cards) {\n this.cards[0] = cards[0];\n this.cards[1] = cards[1];\n }\n\n public PlayerState getState() {\n return state;\n }\n\n public void setState(PlayerState state) {\n this.state = state;\n }\n\n public int getErrors() {\n return errors;\n }\n\n public void setErrors(int errors) {\n this.errors = errors;\n }\n\n public Card getCard(int index) {\n return cards[index];\n }\n\n public void setCards(Card card0, Card card1) {\n this.cards[0] = card0;\n this.cards[1] = card1;\n }\n\n @Override\n public String toString() {\n return \"{class:'PlayerInfo', name:'\" + name + \"', chips:\" + chips + \", bet:\" + bet + \", cards:[\" + cards[0] + \", \" + cards[1] + \"], state:'\" + state + \"', errors:\" + errors + '}';\n }\n}",
"public final class TexasHoldEmUtil {\n\n public static final int MIN_PLAYERS = 2;\n public static final int PLAYER_CARDS = 2;\n public static final int MAX_PLAYERS = 10;\n public static final int COMMUNITY_CARDS = 5;\n private static final Map<BetCommandType, PlayerState> PLAYER_STATE_CONVERSOR = buildPlayerStateConversor();\n\n public enum BetCommandType {\n\n ERROR,\n TIMEOUT,\n FOLD,\n CHECK,\n CALL,\n RAISE,\n ALL_IN\n }\n\n public enum GameState {\n\n PRE_FLOP,\n FLOP,\n TURN,\n RIVER,\n SHOWDOWN,\n END,\n }\n\n public enum PlayerState {\n\n READY(true),\n OUT(false),\n FOLD(false),\n CHECK(true),\n CALL(true),\n RAISE(true),\n ALL_IN(false);\n\n private final boolean active;\n\n private PlayerState(boolean isActive) {\n this.active = isActive;\n }\n\n public boolean isActive() {\n return active;\n }\n }\n\n private TexasHoldEmUtil() {\n }\n\n private static Map<BetCommandType, PlayerState> buildPlayerStateConversor() {\n Map<BetCommandType, PlayerState> result = new EnumMap<>(BetCommandType.class);\n result.put(BetCommandType.FOLD, PlayerState.FOLD);\n result.put(BetCommandType.ALL_IN, PlayerState.ALL_IN);\n result.put(BetCommandType.CALL, PlayerState.CALL);\n result.put(BetCommandType.CHECK, PlayerState.CHECK);\n result.put(BetCommandType.RAISE, PlayerState.RAISE);\n result.put(BetCommandType.ERROR, PlayerState.FOLD);\n result.put(BetCommandType.TIMEOUT, PlayerState.FOLD);\n return result;\n }\n\n public static PlayerState convert(BetCommandType betCommand) {\n return PLAYER_STATE_CONVERSOR.get(betCommand);\n }\n}"
] | import org.poker.api.game.BetCommand;
import org.poker.api.game.GameInfo;
import org.poker.api.game.IStrategy;
import org.poker.api.game.PlayerInfo;
import org.poker.api.game.TexasHoldEmUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | /*
* Copyright (C) 2016 David Pérez Cabrera <[email protected]>
*
* 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 org.poker.sample.strategies;
/**
*
* @author David Pérez Cabrera <[email protected]>
*/
public class SlowlyStrategy implements IStrategy {
private static final Logger LOGGER = LoggerFactory.getLogger(SlowlyStrategy.class);
private final String name;
public SlowlyStrategy(String name) {
this.name = "Slowly-" + name;
}
@Override
public String getName() {
return name;
}
@Override | public BetCommand getCommand(GameInfo<PlayerInfo> state) { | 0 |
njustesen/hero-aicademy | src/ai/mcts/Mcts.java | [
"public class GameState {\n\t\n\tpublic static int TURN_LIMIT = 100;\n\tpublic static boolean RANDOMNESS = false;\n\tpublic static int STARTING_AP = 3;\n\tpublic static int ACTION_POINTS = 5;\n\t\n\tprivate static final int ASSAULT_BONUS = 300;\n\tprivate static final double INFERNO_DAMAGE = 350;\n\tprivate static final int REQUIRED_UNITS = 3;\n\tprivate static final int POTION_REVIVE = 100;\n\tprivate static final int POTION_HEAL = 1000;\n\tpublic static final boolean OPEN_HANDS = false;\n\n\tpublic HaMap map;\n\tpublic boolean p1Turn;\n\tpublic int turn;\n\tpublic int APLeft;\n\tpublic Unit[][] units;\n\tpublic CardSet p1Deck;\n\tpublic CardSet p2Deck;\n\tpublic CardSet p1Hand;\n\tpublic CardSet p2Hand;\n\tpublic boolean isTerminal;\n\n\tpublic List<Position> chainTargets;\n\n\tpublic GameState(HaMap map) {\n\t\tsuper();\n\t\tisTerminal = false;\n\t\tthis.map = map;\n\t\tp1Turn = true;\n\t\tturn = 1;\n\t\tAPLeft = STARTING_AP;\n\t\tp1Hand = new CardSet();\n\t\tp2Hand = new CardSet();\n\t\tp1Deck = new CardSet();\n\t\tp2Deck = new CardSet();\n\t\tchainTargets = new ArrayList<Position>();\n\t\tif (map != null)\n\t\t\tunits = new Unit[map.width][map.height];\n\t\telse\n\t\t\tunits = new Unit[0][0];\n\t}\n\n\tpublic GameState(HaMap map, boolean p1Turn, int turn, int APLeft,\n\t\t\tUnit[][] units, CardSet p1Hand, CardSet p2Hand, CardSet p1Deck,\n\t\t\tCardSet p2Deck, List<Position> chainTargets, boolean isTerminal) {\n\t\tsuper();\n\t\tthis.map = map;\n\t\tthis.p1Turn = p1Turn;\n\t\tthis.turn = turn;\n\t\tthis.APLeft = APLeft;\n\t\tthis.units = units;\n\t\tthis.p1Hand = p1Hand;\n\t\tthis.p2Hand = p2Hand;\n\t\tthis.p1Deck = p1Deck;\n\t\tthis.p2Deck = p2Deck;\n\t\tthis.chainTargets = chainTargets;\n\t\tthis.isTerminal = isTerminal;\n\t\t\n\t}\n\n\tpublic void init(DECK_SIZE deckSize) {\n\t\tp1Hand = new CardSet();\n\t\tp2Hand = new CardSet();\n\t\tp1Deck = new CardSet();\n\t\tp2Deck = new CardSet();\n\t\tshuffleDecks(deckSize);\n\t\tdealCards();\n\t\tfor (final Position pos : map.p1Crystals) {\n\t\t\tunits[pos.x][pos.y] = new Unit(Card.CRYSTAL, true);\n\t\t\tunits[pos.x][pos.y].init(Card.CRYSTAL, true);\n\t\t}\n\t\tfor (final Position pos : map.p2Crystals) {\n\t\t\tunits[pos.x][pos.y] = new Unit(Card.CRYSTAL, false);\n\t\t\tunits[pos.x][pos.y].init(Card.CRYSTAL, false);\n\t\t}\n\t}\n\n\tprivate void shuffleDecks(DECK_SIZE deckSize) {\n\t\tfor (final Card type : Council.deck(deckSize)) {\n\t\t\tp1Deck.add(type);\n\t\t\tp2Deck.add(type);\n\t\t}\n\t}\n\n\tpublic void possibleActions(List<Action> actions) {\n\n\t\tactions.clear();\n\n\t\tif (APLeft == 0) {\n\t\t\tactions.add(SingletonAction.endTurnAction);\n\t\t\treturn;\n\t\t}\n\n\t\tfor (int x = 0; x < map.width; x++)\n\t\t\tfor (int y = 0; y < map.height; y++)\n\t\t\t\tif (units[x][y] != null)\n\t\t\t\t\tpossibleActions(units[x][y], SingletonAction.positions[x][y], actions);\n\n\t\tfinal List<Card> visited = new ArrayList<Card>();\n\t\tfor (final Card card : Card.values())\n\t\t\tif (currentHand().contains(card)) {\n\t\t\t\tpossibleActions(card, actions);\n\t\t\t\tvisited.add(card);\n\t\t\t}\n\n\t}\n\n\tpublic void possibleActions(Card card, List<Action> actions) {\n\n\t\tif (APLeft == 0)\n\t\t\treturn;\n\n\t\tif (card.type == CardType.ITEM) {\n\t\t\tfor (int x = 0; x < map.width; x++)\n\t\t\t\tfor (int y = 0; y < map.height; y++)\n\t\t\t\t\tif (units[x][y] != null\n\t\t\t\t\t\t\t&& units[x][y].unitClass.card != Card.CRYSTAL) {\n\t\t\t\t\t\tif (units[x][y].equipment.contains(card))\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\tif (units[x][y].p1Owner == p1Turn) {\n\t\t\t\t\t\t\tif (card == Card.REVIVE_POTION\n\t\t\t\t\t\t\t\t\t&& units[x][y].fullHealth())\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\tif (card != Card.REVIVE_POTION\n\t\t\t\t\t\t\t\t\t&& units[x][y].hp == 0)\n\t\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t\tactions.add(new DropAction(card, SingletonAction.positions[x][y]));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t} else if (card.type == CardType.SPELL)\n\t\t\tfor (int x = 0; x < map.width; x++)\n\t\t\t\tfor (int y = 0; y < map.height; y++)\n\t\t\t\t\tactions.add(new DropAction(card, SingletonAction.positions[x][y]));\n\t\telse if (card.type == CardType.UNIT)\n\t\t\tif (p1Turn) {\n\t\t\t\tfor (final Position pos : map.p1DeploySquares)\n\t\t\t\t\tif (units[pos.x][pos.y] == null\n\t\t\t\t\t\t\t|| units[pos.x][pos.y].hp == 0)\n\t\t\t\t\t\tactions.add(new DropAction(card, SingletonAction.positions[pos.x][pos.y]));\n\t\t\t} else\n\t\t\t\tfor (final Position pos : map.p2DeploySquares)\n\t\t\t\t\tif (units[pos.x][pos.y] == null\n\t\t\t\t\t\t\t|| units[pos.x][pos.y].hp == 0)\n\t\t\t\t\t\tactions.add(new DropAction(card, SingletonAction.positions[pos.x][pos.y]));\n\n\t\tif (!currentDeck().isEmpty())\n\t\t\tactions.add(SingletonAction.swapActions.get(card));\n\n\t}\n\n\tpublic void possibleActions(Unit unit, Position from, List<Action> actions) {\n\n\t\tif (unit.unitClass.card == Card.CRYSTAL)\n\t\t\treturn;\n\n\t\tif (APLeft == 0 || unit.hp == 0 || APLeft == 0\n\t\t\t\t|| unit.p1Owner != p1Turn)\n\t\t\treturn;\n\n\t\t// Movement and attack\n\t\tint d = unit.unitClass.speed;\n\t\tif (unit.unitClass.heal != null && unit.unitClass.heal.range > d)\n\t\t\td = unit.unitClass.heal.range;\n\t\tif (unit.unitClass.attack != null && unit.unitClass.attack.range > d)\n\t\t\td = unit.unitClass.attack.range;\n\t\tif (unit.unitClass.swap)\n\t\t\td = Math.max(map.width, map.height);\n\t\tfor (int x = d * (-1); x <= d; x++)\n\t\t\tfor (int y = d * (-1); y <= d; y++) {\n\t\t\t\tif (from.x + x >= map.width || from.x + x < 0 || from.y + y >= map.height || from.y + y < 0)\n\t\t\t\t\tcontinue;\n\t\t\t\t\n\t\t\t\tfinal Position to = SingletonAction.positions[from.x + x][from.y +y];\n\t\t\t\t\n\t\t\t\tif (to.equals(from))\n\t\t\t\t\tcontinue;\n\n\t\t\t\tif (units[to.x][to.y] != null) {\n\n\t\t\t\t\tif (units[to.x][to.y].hp == 0) {\n\n\t\t\t\t\t\tif ((map.squares[to.x][to.y] == SquareType.DEPLOY_1 && !p1Turn)\n\t\t\t\t\t\t\t\t|| (map.squares[to.x][to.y] == SquareType.DEPLOY_2 && p1Turn)) {\n\t\t\t\t\t\t\t// NOT ALLOWED!\n\t\t\t\t\t\t} else if (unit.unitClass.heal != null\n\t\t\t\t\t\t\t\t&& from.distance(to) <= unit.unitClass.heal.range)\n\t\t\t\t\t\t\tactions.add(new UnitAction(from, to,\n\t\t\t\t\t\t\t\t\tUnitActionType.HEAL));\n\t\t\t\t\t\telse if (from.distance(to) <= unit.unitClass.speed)\n\t\t\t\t\t\t\tactions.add(new UnitAction(from, to,\n\t\t\t\t\t\t\t\t\tUnitActionType.MOVE));\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfinal int distance = from.distance(to);\n\t\t\t\t\t\tif (unit.p1Owner != units[to.x][to.y].p1Owner\n\t\t\t\t\t\t\t\t&& distance <= unit.unitClass.attack.range) {\n\t\t\t\t\t\t\tif (!(distance > 1 && losBlocked(p1Turn, from, to)))\n\t\t\t\t\t\t\t\tactions.add(new UnitAction(from, to,\n\t\t\t\t\t\t\t\t\t\tUnitActionType.ATTACK));\n\t\t\t\t\t\t} else if (unit.p1Owner == units[to.x][to.y].p1Owner\n\t\t\t\t\t\t\t\t&& unit.unitClass.heal != null\n\t\t\t\t\t\t\t\t&& from.distance(to) <= unit.unitClass.heal.range\n\t\t\t\t\t\t\t\t&& !units[to.x][to.y].fullHealth()\n\t\t\t\t\t\t\t\t&& units[to.x][to.y].unitClass.card != Card.CRYSTAL)\n\t\t\t\t\t\t\tactions.add(new UnitAction(from, to,\n\t\t\t\t\t\t\t\t\tUnitActionType.HEAL));\n\t\t\t\t\t\telse if (unit.p1Owner == units[to.x][to.y].p1Owner\n\t\t\t\t\t\t\t\t&& unit.unitClass.swap\n\t\t\t\t\t\t\t\t&& units[to.x][to.y].unitClass.card != Card.CRYSTAL)\n\t\t\t\t\t\t\tactions.add(new UnitAction(from, to,\n\t\t\t\t\t\t\t\t\tUnitActionType.SWAP));\n\t\t\t\t\t}\n\n\t\t\t\t} else if (from.distance(to) <= unit.unitClass.speed)\n\t\t\t\t\tif ((map.squares[to.x][to.y] == SquareType.DEPLOY_1 && !p1Turn)\n\t\t\t\t\t\t\t|| (map.squares[to.x][to.y] == SquareType.DEPLOY_2 && p1Turn)) {\n\t\t\t\t\t\t// NOT ALLOWED!\n\t\t\t\t\t} else\n\t\t\t\t\t\tactions.add(new UnitAction(from, to,\n\t\t\t\t\t\t\t\tUnitActionType.MOVE));\n\t\t\t}\n\t}\n\n\tpublic void update(List<Action> actions) {\n\t\tfor (final Action action : actions)\n\t\t\tupdate(action);\n\t}\n\n\tpublic void update(Action action) {\n\n\t\ttry {\n\t\t\tchainTargets.clear();\n\n\t\t\tif (action instanceof EndTurnAction || APLeft <= 0)\n\t\t\t\tendTurn();\n\n\t\t\tif (action instanceof DropAction) {\n\n\t\t\t\tfinal DropAction drop = (DropAction) action;\n\n\t\t\t\t// Not a type in current players hand\n\t\t\t\tif (!currentHand().contains(drop.type))\n\t\t\t\t\treturn;\n\n\t\t\t\t// Unit\n\t\t\t\tif (drop.type.type == CardType.UNIT) {\n\n\t\t\t\t\t// Not current players deploy square\n\t\t\t\t\tif (map.squares[drop.to.x][drop.to.y] == SquareType.DEPLOY_1\n\t\t\t\t\t\t\t&& !p1Turn)\n\t\t\t\t\t\treturn;\n\t\t\t\t\tif (map.squares[drop.to.x][drop.to.y] == SquareType.DEPLOY_2\n\t\t\t\t\t\t\t&& p1Turn)\n\t\t\t\t\t\treturn;\n\n\t\t\t\t\tdeploy(drop.type, drop.to);\n\n\t\t\t\t}\n\n\t\t\t\t// Equipment\n\t\t\t\tif (drop.type.type == CardType.ITEM) {\n\n\t\t\t\t\t// Not a unit square or crystal\n\t\t\t\t\tif (units[drop.to.x][drop.to.y] == null\n\t\t\t\t\t\t\t|| units[drop.to.x][drop.to.y].unitClass.card == Card.CRYSTAL)\n\t\t\t\t\t\treturn;\n\n\t\t\t\t\tif (units[drop.to.x][drop.to.y].p1Owner != p1Turn)\n\t\t\t\t\t\treturn;\n\n\t\t\t\t\tif (drop.type == Card.REVIVE_POTION\n\t\t\t\t\t\t\t&& (units[drop.to.x][drop.to.y].unitClass.card == Card.CRYSTAL || units[drop.to.x][drop.to.y]\n\t\t\t\t\t\t\t\t\t.fullHealth()))\n\t\t\t\t\t\treturn;\n\n\t\t\t\t\tif (drop.type != Card.REVIVE_POTION\n\t\t\t\t\t\t\t&& units[drop.to.x][drop.to.y].hp == 0)\n\t\t\t\t\t\treturn;\n\n\t\t\t\t\tif (units[drop.to.x][drop.to.y].equipment\n\t\t\t\t\t\t\t.contains(drop.type))\n\t\t\t\t\t\treturn;\n\n\t\t\t\t\tequip(drop.type, drop.to);\n\n\t\t\t\t}\n\n\t\t\t\t// Spell\n\t\t\t\tif (drop.type.type == CardType.SPELL)\n\t\t\t\t\tdropInferno(drop.to);\n\n\t\t\t\treturn;\n\n\t\t\t}\n\n\t\t\tif (action instanceof UnitAction) {\n\n\t\t\t\tfinal UnitAction ua = (UnitAction) action;\n\n\t\t\t\tif (units[ua.from.x][ua.from.y] == null)\n\t\t\t\t\treturn;\n\n\t\t\t\tfinal Unit unit = units[ua.from.x][ua.from.y];\n\n\t\t\t\tif (unit == null)\n\t\t\t\t\treturn;\n\t\t\t\t\n\t\t\t\tif (unit.p1Owner != p1Turn)\n\t\t\t\t\treturn;\n\n\t\t\t\tif (unit.hp == 0)\n\t\t\t\t\treturn;\n\n\t\t\t\t// Move\n\t\t\t\tif (units[ua.to.x][ua.to.y] == null\n\t\t\t\t\t\t|| (unit.p1Owner == units[ua.to.x][ua.to.y].p1Owner\n\t\t\t\t\t\t\t\t&& units[ua.to.x][ua.to.y].hp == 0 && unit.unitClass.heal == null)\n\t\t\t\t\t\t|| (unit.p1Owner != units[ua.to.x][ua.to.y].p1Owner && units[ua.to.x][ua.to.y].hp == 0)) {\n\n\t\t\t\t\tif (ua.from.distance(ua.to) > units[ua.from.x][ua.from.y].unitClass.speed)\n\t\t\t\t\t\treturn;\n\n\t\t\t\t\tif (map.squares[ua.to.x][ua.to.y] == SquareType.DEPLOY_1\n\t\t\t\t\t\t\t&& !unit.p1Owner)\n\t\t\t\t\t\treturn;\n\n\t\t\t\t\tif (map.squares[ua.to.x][ua.to.y] == SquareType.DEPLOY_2\n\t\t\t\t\t\t\t&& unit.p1Owner)\n\t\t\t\t\t\treturn;\n\n\t\t\t\t\tmove(unit, ua.from, ua.to);\n\t\t\t\t\treturn;\n\n\t\t\t\t} else {\n\n\t\t\t\t\tfinal Unit other = units[ua.to.x][ua.to.y];\n\n\t\t\t\t\t// Swap and heal\n\t\t\t\t\tif (unit.p1Owner == other.p1Owner) {\n\t\t\t\t\t\tif (unit.unitClass.swap\n\t\t\t\t\t\t\t\t&& units[ua.to.x][ua.to.y].unitClass.card != Card.CRYSTAL\n\t\t\t\t\t\t\t\t&& units[ua.to.x][ua.to.y].hp != 0) {\n\t\t\t\t\t\t\tswap(unit, ua.from, other, ua.to);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (unit.unitClass.heal == null)\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\tif (ua.from.distance(ua.to) > unit.unitClass.heal.range)\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\tif (other.fullHealth())\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\theal(unit, ua.from, other);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\t// Attack\n\t\t\t\t\tfinal int distance = ua.from.distance(ua.to);\n\t\t\t\t\tif (unit.unitClass.attack != null\n\t\t\t\t\t\t\t&& distance > unit.unitClass.attack.range)\n\t\t\t\t\t\treturn;\n\n\t\t\t\t\tif (distance > 1 && losBlocked(p1Turn, ua.from, ua.to))\n\t\t\t\t\t\treturn;\n\n\t\t\t\t\tif (other == null)\n\t\t\t\t\t\treturn;\n\t\t\t\t\t\n\t\t\t\t\tattack(unit, ua.from, other, ua.to);\n\t\t\t\t\treturn;\n\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (action instanceof SwapCardAction) {\n\n\t\t\t\tfinal Card card = ((SwapCardAction) action).card;\n\n\t\t\t\tif (currentHand().contains(card)) {\n\n\t\t\t\t\tcurrentDeck().add(card);\n\t\t\t\t\tcurrentHand().remove(card);\n\t\t\t\t\tAPLeft--;\n\n\t\t\t\t}\n\n\t\t\t}\n\t\t} catch (final Exception e) {\n\t\t\te.printStackTrace();\n\t\t}\n\n\t}\n\n\t/**\n\t * Using the Bresenham-based super-cover line algorithm\n\t * \n\t * @param from\n\t * @param to\n\t * @return\n\t */\n\tpublic boolean losBlocked(boolean p1, Position from, Position to) {\n\n\t\tif (from.distance(to) == 1\n\t\t\t\t|| (from.getDirection(to).isDiagonal() && from.distance(to) == 2))\n\t\t\treturn false;\n\n\t\tfor (final Position pos : CachedLines.supercover(from, to)) {\n\t\t\tif (pos.equals(from) || pos.equals(to))\n\t\t\t\tcontinue;\n\n\t\t\tif (units[pos.x][pos.y] != null\n\t\t\t\t\t&& units[pos.x][pos.y].p1Owner != p1\n\t\t\t\t\t&& units[pos.x][pos.y].hp != 0)\n\t\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\n\t}\n\n\tprivate void dropInferno(Position to) throws Exception {\n\n\t\tfor (int x = -1; x <= 1; x++)\n\t\t\tfor (int y = -1; y <= 1; y++) {\n\t\t\t\tif (to.x + x < 0 || to.x + x >= map.width || to.y + y < 0 || to.y + y >= map.height)\n\t\t\t\t\tcontinue;\n\t\t\t\tfinal Position pos = SingletonAction.positions[to.x + x][to.y + y];\n\t\t\t\tif (units[pos.x][pos.y] != null\n\t\t\t\t\t\t&& units[pos.x][pos.y].p1Owner != p1Turn) {\n\t\t\t\t\tif (units[pos.x][pos.y].hp == 0) {\n\t\t\t\t\t\tunits[pos.x][pos.y] = null;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tdouble damage = INFERNO_DAMAGE;\n\t\t\t\t\tif (units[pos.x][pos.y].unitClass.card == Card.CRYSTAL) {\n\t\t\t\t\t\tfinal int bonus = assaultBonus();\n\t\t\t\t\t\tdamage += bonus;\n\t\t\t\t\t}\n\t\t\t\t\tfinal double resistance = units[pos.x][pos.y].resistance(\n\t\t\t\t\t\t\tthis, pos, AttackType.Magical);\n\t\t\t\t\tdamage = damage * ((100d - resistance) / 100d);\n\t\t\t\t\tunits[pos.x][pos.y].hp -= damage;\n\t\t\t\t\tif (units[pos.x][pos.y].hp <= 0)\n\t\t\t\t\t\tif (units[pos.x][pos.y].unitClass.card == Card.CRYSTAL) {\n\t\t\t\t\t\t\tcheckWinOnCrystals(p1Turn ? 2 : 1);\n\t\t\t\t\t\t\tunits[pos.x][pos.y] = null;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tunits[pos.x][pos.y].hp = 0;\n\t\t\t\t\t\t\tcheckWinOnUnits(p1Turn ? 2 : 1);\n\t\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\tcurrentHand().remove(Card.INFERNO);\n\t\tAPLeft--;\n\n\t}\n\n\tprivate void attack(Unit attacker, Position attPos, Unit defender, Position defPos) throws Exception {\n\t\tif (attacker.unitClass.attack == null)\n\t\t\treturn;\n\t\tif (defender.hp == 0) {\n\t\t\tunits[defPos.x][defPos.y] = null;\n\t\t\tmove(attacker, attPos, defPos);\n\t\t\tcheckWinOnUnits(p1Turn ? 2 : 1);\n\t\t} else {\n\t\t\tint damage = attacker.damage(this, attPos, defender, defPos);\n\t\t\tif (defender.unitClass.card == Card.CRYSTAL) {\n\t\t\t\tfinal int bonus = assaultBonus();\n\t\t\t\tdamage += bonus;\n\t\t\t}\n\t\t\tdefender.hp -= damage;\n\t\t\tif (defender.hp <= 0) {\n\t\t\t\tdefender.hp = 0;\n\t\t\t\tif (defender.unitClass.card == Card.CRYSTAL) {\n\t\t\t\t\tunits[defPos.x][defPos.y] = null;\n\t\t\t\t\tcheckWinOnCrystals(p1Turn ? 2 : 1);\n\t\t\t\t} else {\n\t\t\t\t\tunits[defPos.x][defPos.y].hp = 0;\n\t\t\t\t\tcheckWinOnUnits(p1Turn ? 2 : 1);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (attacker.unitClass.attack.push)\n\t\t\t\tpush(defender, attPos, defPos);\n\t\t\tif (attacker.unitClass.attack.chain)\n\t\t\t\tchain(attacker,\n\t\t\t\t\t\tattPos,\n\t\t\t\t\t\tdefPos,\n\t\t\t\t\t\tDirection.direction(defPos.x - attPos.x, defPos.y\n\t\t\t\t\t\t\t\t- attPos.y), 1);\n\t\t}\n\t\tattacker.equipment.remove(Card.SCROLL);\n\t\tAPLeft--;\n\t}\n\n\tprivate void chain(Unit attacker, Position attPos, Position from,\n\t\t\tDirection dir, int jump) throws Exception {\n\n\t\tif (jump >= 3)\n\t\t\treturn;\n\n\t\tfinal Position bestPos = nextJump(from, dir);\n\n\t\t// Attack\n\t\tif (bestPos != null) {\n\t\t\tchainTargets.add(bestPos);\n\t\t\tint damage = attacker.damage(this, attPos,\n\t\t\t\t\tunits[bestPos.x][bestPos.y], bestPos);\n\t\t\tif (jump == 1)\n\t\t\t\tdamage = (int) (damage * 0.75);\n\t\t\telse if (jump == 2)\n\t\t\t\tdamage = (int) (damage * 0.56);\n\t\t\telse\n\t\t\t\tSystem.out.println(\"Illegal number of jumps!\");\n\n\t\t\tif (units[bestPos.x][bestPos.y].unitClass.card == Card.CRYSTAL)\n\t\t\t\tdamage += assaultBonus();\n\n\t\t\tunits[bestPos.x][bestPos.y].hp -= damage;\n\t\t\tif (units[bestPos.x][bestPos.y].hp <= 0) {\n\t\t\t\tunits[bestPos.x][bestPos.y].hp = 0;\n\t\t\t\tif (units[bestPos.x][bestPos.y].unitClass.card == Card.CRYSTAL) {\n\t\t\t\t\tcheckWinOnCrystals(p1Turn ? 2 : 1);\n\t\t\t\t\tunits[bestPos.x][bestPos.y] = null;\n\t\t\t\t} else {\n\t\t\t\t\tunits[bestPos.x][bestPos.y].hp = 0;\n\t\t\t\t\tcheckWinOnUnits(p1Turn ? 2 : 1);\n\t\t\t\t}\n\t\t\t}\n\t\t\tchain(attacker, attPos, bestPos, from.getDirection(bestPos),\n\t\t\t\t\tjump + 1);\n\t\t}\n\n\t}\n\n\tprivate Position nextJump(Position from, Direction dir) {\n\n\t\tint bestValue = 0;\n\t\tPosition bestPos = null;\n\n\t\t// Find best target\n\t\tfor (int newDirX = -1; newDirX <= 1; newDirX++)\n\t\t\tfor (int newDirY = -1; newDirY <= 1; newDirY++) {\n\t\t\t\tif (newDirX == 0 && newDirY == 0)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tif (from.x + newDirX < 0 || from.x + newDirX >= map.width || from.y + newDirY < 0 || from.y + newDirY >= map.height)\n\t\t\t\t\tcontinue;\n\t\t\t\t\n\t\t\t\tfinal Position newPos = SingletonAction.positions[from.x + newDirX][from.y + newDirY];\n\t\t\t\t\n\t\t\t\tif (units[newPos.x][newPos.y] != null\n\t\t\t\t\t\t&& units[newPos.x][newPos.y].p1Owner != p1Turn\n\t\t\t\t\t\t&& units[newPos.x][newPos.y].hp > 0) {\n\n\t\t\t\t\tfinal Direction newDir = Direction.direction(newDirX,\n\t\t\t\t\t\t\tnewDirY);\n\n\t\t\t\t\tif (newDir.opposite(dir))\n\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\tfinal int chainValue = chainValue(dir, newDir);\n\n\t\t\t\t\tif (chainValue > bestValue) {\n\t\t\t\t\t\tbestPos = newPos;\n\t\t\t\t\t\tbestValue = chainValue;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\treturn bestPos;\n\t}\n\n\tprivate int chainValue(Direction dir, Direction newDir) {\n\n\t\tif (dir.equals(newDir))\n\t\t\treturn 10;\n\n\t\tint value = 1;\n\n\t\tif (!newDir.isDiagonal())\n\t\t\tvalue += 4;\n\n\t\tif (newDir.isNorth())\n\t\t\tvalue += 2;\n\n\t\tif (newDir.isEast())\n\t\t\tvalue += 1;\n\n\t\treturn value;\n\n\t}\n\n\tprivate int assaultBonus() {\n\t\tint bonus = 0;\n\t\tfor (final Position pos : map.assaultSquares)\n\t\t\tif (units[pos.x][pos.y] != null\n\t\t\t\t\t&& units[pos.x][pos.y].p1Owner == p1Turn\n\t\t\t\t\t&& units[pos.x][pos.y].hp != 0)\n\t\t\t\tbonus += ASSAULT_BONUS;\n\t\treturn bonus;\n\t}\n\n\tprivate void checkWinOnUnits(int p) {\n\n\t\tif (!aliveOnUnits(p))\n\t\t\tisTerminal = true;\n\n\t}\n\n\tprivate void checkWinOnCrystals(int p) {\n\n\t\tif (!aliveOnCrystals(p))\n\t\t\tisTerminal = true;\n\n\t}\n\n\tpublic int getWinner() {\n\n\t\tif (turn >= TURN_LIMIT)\n\t\t\treturn 0;\n\t\t\n\t\tboolean p1Alive = true;\n\t\tboolean p2Alive = true;\n\n\t\tif (!aliveOnCrystals(1) || !aliveOnUnits(1))\n\t\t\tp1Alive = false;\n\n\t\tif (!aliveOnCrystals(2) || !aliveOnUnits(2))\n\t\t\tp2Alive = false;\n\n\t\tif (p1Alive == p2Alive)\n\t\t\treturn 0;\n\n\t\tif (p1Alive)\n\t\t\treturn 1;\n\n\t\tif (p2Alive)\n\t\t\treturn 2;\n\n\t\treturn 0;\n\n\t}\n\n\tprivate boolean aliveOnCrystals(int player) {\n\n\t\tfor (final Position pos : crystals(player))\n\t\t\tif (units[pos.x][pos.y] != null\n\t\t\t\t\t&& units[pos.x][pos.y].unitClass.card == Card.CRYSTAL\n\t\t\t\t\t&& units[pos.x][pos.y].hp > 0)\n\t\t\t\treturn true;\n\n\t\treturn false;\n\n\t}\n\n\tprivate List<Position> crystals(int player) {\n\t\tif (player == 1)\n\t\t\treturn map.p1Crystals;\n\t\tif (player == 2)\n\t\t\treturn map.p2Crystals;\n\t\treturn null;\n\t}\n\n\tprivate boolean aliveOnUnits(int player) {\n\n\t\tif (deck(player).hasUnits() || hand(player).hasUnits())\n\t\t\treturn true;\n\n\t\tfor (int x = 0; x < map.width; x++)\n\t\t\tfor (int y = 0; y < map.height; y++)\n\t\t\t\tif (units[x][y] != null && units[x][y].p1Owner == (player == 1)\n\t\t\t\t\t\t&& units[x][y].unitClass.card != Card.CRYSTAL)\n\t\t\t\t\treturn true;\n\n\t\treturn false;\n\n\t}\n\n\tprivate CardSet deck(int player) {\n\t\tif (player == 1)\n\t\t\treturn p1Deck;\n\t\tif (player == 2)\n\t\t\treturn p2Deck;\n\t\treturn null;\n\t}\n\n\tprivate CardSet hand(int player) {\n\t\tif (player == 1)\n\t\t\treturn p1Hand;\n\t\tif (player == 2)\n\t\t\treturn p2Hand;\n\t\treturn null;\n\t}\n\n\tprivate void push(Unit defender, Position attPos, Position defPos)\n\t\t\tthrows Exception {\n\n\t\tif (defender.unitClass.card == Card.CRYSTAL)\n\t\t\treturn;\n\n\t\tint x = 0;\n\t\tint y = 0;\n\n\t\tif (attPos.x > defPos.x)\n\t\t\tx = -1;\n\t\tif (attPos.x < defPos.x)\n\t\t\tx = 1;\n\t\tif (attPos.y > defPos.y)\n\t\t\ty = -1;\n\t\tif (attPos.y < defPos.y)\n\t\t\ty = 1;\n\n\t\tif (defPos.x + x >= map.width || defPos.x + x < 0 || defPos.y + y >= map.height || defPos.y + y < 0)\n\t\t\treturn;\n\n\t\tfinal Position newPos = SingletonAction.positions[defPos.x + x][defPos.y + y];\n\t\t\n\t\tif (units[newPos.x][newPos.y] != null\n\t\t\t\t&& units[newPos.x][newPos.y].hp > 0)\n\t\t\treturn;\n\n\t\tif (map.squareAt(newPos) == SquareType.DEPLOY_1 && !defender.p1Owner)\n\t\t\treturn;\n\n\t\tif (map.squareAt(newPos) == SquareType.DEPLOY_2 && defender.p1Owner)\n\t\t\treturn;\n\n\t\tif (units[defPos.x][defPos.y] != null) {\n\t\t\tunits[defPos.x][defPos.y] = null;\n\t\t}\n\n\t\tunits[newPos.x][newPos.y] = defender;\n\n\t}\n\n\tprivate void heal(Unit healer, Position pos, Unit unitTo) {\n\n\t\tint power = healer.power(this, pos);\n\n\t\tif (unitTo.hp == 0)\n\t\t\tpower *= healer.unitClass.heal.revive;\n\t\telse\n\t\t\tpower *= healer.unitClass.heal.heal;\n\t\t\n\t\tunitTo.heal(power);\n\t\thealer.equipment.remove(Card.SCROLL);\n\t\t\n\t\tAPLeft--;\n\n\t}\n\n\tprivate void swap(Unit unitFrom, Position from, Unit unitTo, Position to) {\n\t\tunits[from.x][from.y] = unitTo;\n\t\tunits[to.x][to.y] = unitFrom;\n\t\tAPLeft--;\n\t}\n\n\tprivate void move(Unit unit, Position from, Position to) throws Exception {\n\t\tunits[from.x][from.y] = null;\n\t\tunits[to.x][to.y] = unit;\n\t\tAPLeft--;\n\t}\n\n\tprivate void equip(Card card, Position pos) {\n\t\tif (card == Card.REVIVE_POTION) {\n\t\t\tif (units[pos.x][pos.y].hp == 0)\n\t\t\t\tunits[pos.x][pos.y].heal(POTION_REVIVE);\n\t\t\telse\n\t\t\t\tunits[pos.x][pos.y].heal(POTION_HEAL);\n\t\t} else\n\t\t\tunits[pos.x][pos.y].equip(card, this);\n\t\tcurrentHand().remove(card);\n\t\tAPLeft--;\n\t}\n\n\tprivate void deploy(Card card, Position pos) {\n\t\tunits[pos.x][pos.y] = new Unit(card, p1Turn);\n\t\tcurrentHand().remove(card);\n\t\tAPLeft--;\n\t}\n\n\tprivate void endTurn() throws Exception {\n\t\tremoveDying(p1Turn);\n\t\tcheckWinOnUnits(1);\n\t\tcheckWinOnUnits(2);\n\t\tcheckWinOnCrystals(p1Turn ? 2 : 1);\n\t\tif (turn >= TURN_LIMIT)\n\t\t\tisTerminal = true;\n\t\tif (!isTerminal) {\n\t\t\tdrawCards();\n\t\t\tp1Turn = !p1Turn;\n\t\t\tdrawCards();\n\t\t\tAPLeft = ACTION_POINTS;\n\t\t\tturn++;\n\t\t}\n\t\t\n\t}\n\n\tpublic void dealCards() {\n\t\twhile (!legalStartingHand(p1Hand))\n\t\t\tdealCards(1);\n\n\t\twhile (!legalStartingHand(p2Hand))\n\t\t\tdealCards(2);\n\t}\n\n\tprivate void dealCards(int player) {\n\t\tif (player == 1) {\n\t\t\tp1Deck.addAll(p1Hand);\n\t\t\tp1Hand.clear();\n\t\t\t// Collections.shuffle(p1Deck);\n\t\t\tdrawHandFrom(p1Deck, p1Hand);\n\t\t} else if (player == 2) {\n\t\t\tp2Deck.addAll(p2Hand);\n\t\t\tp2Hand.clear();\n\t\t\t// Collections.shuffle(p2Hand);\n\t\t\tdrawHandFrom(p2Deck, p2Hand);\n\t\t}\n\n\t}\n\n\tprivate boolean legalStartingHand(CardSet hand) {\n\t\tif (hand.size != 6)\n\t\t\treturn false;\n\n\t\tif (hand.units() == REQUIRED_UNITS)\n\t\t\treturn true;\n\n\t\treturn false;\n\n\t}\n\n\tprivate void drawHandFrom(CardSet deck, CardSet hand) {\n\n\t\tCard card = null;\n\t\twhile (!deck.isEmpty() && hand.size < 6) {\n\t\t\tif (RANDOMNESS)\n\t\t\t\tcard = deck.random();\n\t\t\telse\n\t\t\t\tcard = deck.determined();\n\t\t\thand.add(card);\n\t\t\tdeck.remove(card);\n\t\t}\n\n\t}\n\n\tprivate void drawCards() {\n\n\t\tdrawHandFrom(currentDeck(), currentHand());\n\n\t}\n\n\tpublic CardSet currentHand() {\n\t\tif (p1Turn)\n\t\t\treturn p1Hand;\n\t\treturn p2Hand;\n\t}\n\n\tpublic CardSet currentDeck() {\n\t\tif (p1Turn)\n\t\t\treturn p1Deck;\n\t\treturn p2Deck;\n\t}\n\n\tpublic void removeDying(boolean p1) throws Exception {\n\t\tfor (int x = 0; x < map.width; x++)\n\t\t\tfor (int y = 0; y < map.height; y++)\n\t\t\t\tif (units[x][y] != null && units[x][y].p1Owner == p1\n\t\t\t\t\t\t&& units[x][y].hp == 0) {\n\t\t\t\t\tunits[x][y] = null;\n\t\t\t\t}\n\t}\n\n\tpublic GameState copy() {\n\t\tfinal Unit[][] un = new Unit[map.width][map.height];\n\t\tfor (int x = 0; x < map.width; x++)\n\t\t\tfor (int y = 0; y < map.height; y++)\n\t\t\t\tif (units[x][y] != null)\n\t\t\t\t\tun[x][y] = units[x][y].copy();\n\t\tfinal CardSet p1h = new CardSet(p1Hand.seed);\n\t\tp1h.imitate(p1Hand);\n\t\tfinal CardSet p2h = new CardSet(p2Hand.seed);\n\t\tp2h.imitate(p2Hand);\n\t\tfinal CardSet p1d = new CardSet(p1Deck.seed);\n\t\tp1d.imitate(p1Deck);\n\t\tfinal CardSet p2d = new CardSet(p2Deck.seed);\n\t\tp2d.imitate(p2Deck);\n\n\t\treturn new GameState(map, p1Turn, turn, APLeft, un, p1h, p2h, p1d, p2d,\n\t\t\t\tchainTargets, isTerminal);\n\t}\n\n\tpublic void imitate(GameState state) {\n\n\t\tmap = state.map;\n\t\tif (units.length != state.units.length\n\t\t\t\t|| (state.units.length > 0 && units[0].length != state.units[0].length))\n\t\t\tunits = new Unit[map.width][map.height];\n\n\t\tfor (int x = 0; x < map.width; x++)\n\t\t\tfor (int y = 0; y < map.height; y++) {\n\t\t\t\tif (units[x][y] != null) \n\t\t\t\t\tunits[x][y] = null;\n\t\t\t\tif (state.units[x][y] != null) {\n\t\t\t\t\tunits[x][y] = new Unit(null, false);\n\t\t\t\t\tunits[x][y].imitate(state.units[x][y]);\n\t\t\t\t}\n\t\t\t}\n\t\tp1Hand.imitate(state.p1Hand);\n\t\tp2Hand.imitate(state.p2Hand);\n\t\tp1Deck.imitate(state.p1Deck);\n\t\tp2Deck.imitate(state.p2Deck);\n\t\tisTerminal = state.isTerminal;\n\t\tp1Turn = state.p1Turn;\n\t\tturn = state.turn;\n\t\tAPLeft = state.APLeft;\n\t\tmap = state.map;\n\t\t// chainTargets.clear();\n\t\t// chainTargets.addAll(state.chainTargets); // NOT NECESSARY\n\n\t}\n\t\n\tpublic long simpleHash() {\n\t\tfinal int prime = 1193;\n\t\tlong result = 1;\n\t\tresult = prime * result + (isTerminal ? 0 : 1);\n\t\tresult = prime * result + p1Hand.hashCode();\n\t\tresult = prime * result + p2Deck.hashCode();\n\t\tresult = prime * result + p2Hand.hashCode();\n\t\tresult = prime * result + p1Deck.hashCode();\n\n\t\tfor (int x = 0; x < map.width; x++)\n\t\t\tfor (int y = 0; y < map.height; y++)\n\t\t\t\tif (units[x][y] != null)\n\t\t\t\t\tresult = prime * result + units[x][y].hash(x, y);\n\n\t\treturn result;\n\t}\n\n\tpublic long hash() {\n\t\tfinal int prime = 1193;\n\t\tlong result = 1;\n\t\tresult = prime * result + APLeft;\n\t\tresult = prime * result + turn;\n\t\tresult = prime * result + (isTerminal ? 0 : 1);\n\t\tresult = prime * result + p1Hand.hashCode();\n\t\tresult = prime * result + p2Deck.hashCode();\n\t\tresult = prime * result + p2Hand.hashCode();\n\t\tresult = prime * result + p1Deck.hashCode();\n\n\t\tfor (int x = 0; x < map.width; x++)\n\t\t\tfor (int y = 0; y < map.height; y++)\n\t\t\t\tif (units[x][y] != null)\n\t\t\t\t\tresult = prime * result + units[x][y].hash(x, y);\n\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null)\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tfinal GameState other = (GameState) obj;\n\t\tif (APLeft != other.APLeft)\n\t\t\treturn false;\n\t\tif (isTerminal != other.isTerminal)\n\t\t\treturn false;\n\t\tif (map == null) {\n\t\t\tif (other.map != null)\n\t\t\t\treturn false;\n\t\t} else if (!map.equals(other.map))\n\t\t\treturn false;\n\t\tif (p1Deck == null) {\n\t\t\tif (other.p1Deck != null)\n\t\t\t\treturn false;\n\t\t} else if (!p1Deck.equals(other.p1Deck))\n\t\t\treturn false;\n\t\tif (p1Hand == null) {\n\t\t\tif (other.p1Hand != null)\n\t\t\t\treturn false;\n\t\t} else if (!p1Hand.equals(other.p1Hand))\n\t\t\treturn false;\n\t\tif (p1Turn != other.p1Turn)\n\t\t\treturn false;\n\t\tif (p2Deck == null) {\n\t\t\tif (other.p2Deck != null)\n\t\t\t\treturn false;\n\t\t} else if (!p2Deck.equals(other.p2Deck))\n\t\t\treturn false;\n\t\tif (p2Hand == null) {\n\t\t\tif (other.p2Hand != null)\n\t\t\t\treturn false;\n\t\t} else if (!p2Hand.equals(other.p2Hand))\n\t\t\treturn false;\n\t\tif (!Arrays.deepEquals(units, other.units))\n\t\t\treturn false;\n\t\tif (turn != other.turn)\n\t\t\treturn false;\n\t\treturn true;\n\t}\n\n\tpublic void print() {\n\t\tfinal List<Unit> p1Units = new ArrayList<Unit>();\n\t\tfinal List<Unit> p2Units = new ArrayList<Unit>();\n\t\tfor (int y = 0; y < units[0].length; y++) {\n\t\t\tSystem.out.print(\"|\");\n\t\t\tfor (int x = 0; x < units.length; x++)\n\t\t\t\tif (units[x][y] == null)\n\t\t\t\t\tSystem.out.print(\"__|\");\n\t\t\t\telse {\n\t\t\t\t\tSystem.out.print(units[x][y].unitClass.card.name()\n\t\t\t\t\t\t\t.substring(0, 2) + \"|\");\n\t\t\t\t\tif (units[x][y].p1Owner)\n\t\t\t\t\t\tp1Units.add(units[x][y]);\n\t\t\t\t\telse\n\t\t\t\t\t\tp2Units.add(units[x][y]);\n\t\t\t\t}\n\t\t\tSystem.out.print(\"\\n\");\n\t\t}\n\t\tSystem.out.println(p1Hand);\n\t\tfor (final Unit unit : p1Units)\n\t\t\tSystem.out.println(unit);\n\t\tSystem.out.println(p2Hand);\n\t\tfor (final Unit unit : p2Units)\n\t\t\tSystem.out.println(unit);\n\n\t}\n\n\tpublic SquareType squareAt(Position pos) {\n\t\treturn map.squares[pos.x][pos.y];\n\t}\n\n\tpublic Unit unitAt(Position pos) {\n\t\treturn units[pos.x][pos.y];\n\t}\n\n\tpublic Unit unitAt(int x, int y) {\n\t\treturn units[x][y];\n\t}\n\n\tpublic int cardsLeft(int p) {\n\t\tif (p == 1)\n\t\t\treturn p1Deck.size + p1Hand.size;\n\t\telse if (p == 2)\n\t\t\treturn p2Deck.size + p2Hand.size;\n\t\treturn -1;\n\t}\n\n\tpublic void returnUnits() {\n\t\tfor (int x = 0; x < map.width; x++)\n\t\t\tfor (int y = 0; y < map.height; y++)\n\t\t\t\tif (units[x][y] != null) \n\t\t\t\t\tunits[x][y] = null;\n\t}\n\n\tpublic void hideCards(boolean p1) {\n\t\tif (p1){\n\t\t\tfor(Card card : Card.values())\n\t\t\t\tfor(int i = 0; i < p1Hand.count(card); i++)\n\t\t\t\t\tp1Deck.add(card);\n\t\t\tp1Hand.clear();\n\t\t} else {\n\t\t\tfor(Card card : Card.values())\n\t\t\t\tfor(int i = 0; i < p2Hand.count(card); i++)\n\t\t\t\t\tp2Deck.add(card);\n\t\t\tp2Hand.clear();\n\t\t}\n\t}\n\n}",
"public class Statistics {\n\n\tpublic static double avgDouble(List<Double> vals){\n\t\t\n\t\tdouble sum = 0;\n\t\tfor(double d : vals)\n\t\t\tsum += d;\n\t\t\n\t\treturn sum / vals.size();\n\t\t\n\t}\n\t\n\tpublic static double avgInteger(List<Integer> vals){\n\t\t\n\t\tdouble sum = 0;\n\t\tfor(int d : vals)\n\t\t\tsum += d;\n\t\t\n\t\treturn sum / vals.size();\n\t\t\n\t}\n\t\n\tpublic static double stdDevDouble(List<Double> vals){\n\t\t\n\t\tdouble avg = avgDouble(vals);\n\t\t\n\t\tdouble sum = 0;\n\t\tfor(double d : vals)\n\t\t\tsum += (d - avg) * (d - avg);\n\t\t\n\t\tdouble davg = sum / vals.size();\n\t\t\n\t\treturn Math.sqrt(davg);\n\t\t\n\t}\n\t\n\tpublic static double stdDevInteger(List<Integer> vals){\n\t\t\n\t\tdouble avg = avgInteger(vals);\n\t\t\n\t\tdouble sum = 0;\n\t\tfor(double d : vals)\n\t\t\tsum += (d - avg) * (d - avg);\n\t\t\n\t\tdouble davg = sum / vals.size();\n\t\t\n\t\treturn Math.sqrt(davg);\n\t\t\n\t}\n\n\tpublic static int max(List<Integer> vals) {\n\t\t\n\t\tint min = Integer.MIN_VALUE;\n\t\t\n\t\tfor(int n : vals)\n\t\t\tif (n > min)\n\t\t\t\tmin = n;\n\t\t\n\t\treturn min;\n\t}\n\t\n}",
"public abstract class Action {\n\t\n}",
"public class SingletonAction {\n\n\tpublic static final EndTurnAction endTurnAction = new EndTurnAction();\n\tpublic static final PlayAgainAction playAgainAction = new PlayAgainAction();\n\tpublic static final UndoAction undoAction = new UndoAction();\n\tpublic static final Map<Card, SwapCardAction> swapActions = new HashMap<Card, SwapCardAction>();\n\tstatic {\n\t\tswapActions.put(Card.ARCHER, new SwapCardAction(Card.ARCHER));\n\t\tswapActions.put(Card.CLERIC, new SwapCardAction(Card.CLERIC));\n\t\tswapActions.put(Card.DRAGONSCALE, new SwapCardAction(Card.DRAGONSCALE));\n\t\tswapActions.put(Card.INFERNO, new SwapCardAction(Card.INFERNO));\n\t\tswapActions.put(Card.KNIGHT, new SwapCardAction(Card.KNIGHT));\n\t\tswapActions.put(Card.NINJA, new SwapCardAction(Card.NINJA));\n\t\tswapActions.put(Card.REVIVE_POTION, new SwapCardAction(\n\t\t\t\tCard.REVIVE_POTION));\n\t\tswapActions.put(Card.RUNEMETAL, new SwapCardAction(Card.RUNEMETAL));\n\t\tswapActions.put(Card.SCROLL, new SwapCardAction(Card.SCROLL));\n\t\tswapActions.put(Card.SHINING_HELM,\n\t\t\t\tnew SwapCardAction(Card.SHINING_HELM));\n\t\tswapActions.put(Card.WIZARD, new SwapCardAction(Card.WIZARD));\n\t}\n\t\n\tpublic static Position[][] positions;\n\t\n\tpublic static void init(HaMap map){\n\t\t\n\t\tpositions = new Position[map.width + 10][map.height + 10];\n\t\t\n\t\tfor(int x = 0; x < map.width; x++)\n\t\t\tfor(int y = 0; y < map.height; y++)\n\t\t\t\tpositions[x][y] = new Position(x,y);\n\t\t\n\t}\n\n}",
"public interface AI {\n\t\n\tpublic Action act(GameState state, long ms);\n\t\n\tpublic abstract void init(GameState state, long ms);\n\t\n\tpublic abstract AI copy();\n\t\n\tpublic abstract String header();\n\t\n\tpublic abstract String title();\n\t\n}",
"public interface IStateEvaluator {\n\n\tpublic double eval(GameState state, boolean p1);\n\n\tpublic double normalize(double delta);\n\n\tpublic String title();\n\n\tpublic IStateEvaluator copy();\n\t\n}",
"public abstract class ActionComparator implements Comparator<Action> {\n\n\tpublic GameState state;\n\n\t@Override\n\tpublic int compare(Action o1, Action o2) {\n\n\t\tfinal int val1 = value(o1);\n\t\tfinal int val2 = value(o2);\n\n\t\tif (val1 > val2)\n\t\t\treturn -1;\n\t\telse if (val2 > val1)\n\t\t\treturn 1;\n\t\telse if (o1.hashCode() > o2.hashCode())\n\t\t\treturn -1;\n\t\telse if (o1.hashCode() < o2.hashCode())\n\t\t\treturn 1;\n\t\telse\n\t\t\treturn 0;\n\t}\n\t\n\tpublic abstract int value(Action action);\n\n\tpublic void sort(List<Action> actions, GameState state) {\n\t\tthis.state = state;\n\t\tCollections.sort(actions, this);\n\t}\n\n}",
"public class ActionPruner {\n\n\tfinal Map<DropAction, List<Position>> spellTargets;\n\tfinal List<Action> pruned;\n\n\tpublic ActionPruner() {\n\t\tsuper();\n\t\tspellTargets = new HashMap<DropAction, List<Position>>();\n\t\tpruned = new ArrayList<Action>();\n\t}\n\n\tpublic void prune(List<Action> actions, GameState state) {\n\n\t\tpruned.clear();\n\t\tspellTargets.clear();\n\n\t\tfor (final Action action : actions)\n\t\t\tif (action instanceof DropAction) {\n\t\t\t\tfinal DropAction dropAction = ((DropAction) action);\n\t\t\t\tif (dropAction.type == Card.INFERNO)\n\t\t\t\t\tspellTargets.put(((DropAction) action),\n\t\t\t\t\t\t\tspellTargets(dropAction.to, state));\n\t\t\t} else if (action instanceof SwapCardAction)\n\t\t\t\tif (onlyCard(state, ((SwapCardAction)action).card))\n\t\t\t\t\tpruned.add(action);\n\n\t\tfor (final DropAction spell : spellTargets.keySet())\n\t\t\tif (spellTargets.get(spell).isEmpty())\n\t\t\t\tpruned.add(spell);\n\n\t\tfor (final DropAction spell : spellTargets.keySet())\n\t\t\tif (!pruned.contains(spell))\n\t\t\t\tif (sameOrBetterSpellEffect(spellTargets, spell, pruned))\n\t\t\t\t\tpruned.add(spell);\n\t\t\n\t\t/*\n\t\tSet<Integer> states = new HashSet<Integer>();\n\t\tfor (final Action action : actions){\n\t\t\tGameState next = state.copy();\n\t\t\tif (pruned.contains(action))\n\t\t\t\tcontinue;\n\t\t\tif (action instanceof UnitAction || action instanceof DropAction){\n\t\t\t\tnext.update(action);\n\t\t\t\tif (states.contains(next.hash())){\n\t\t\t\t\tpruned.add(action);\n\t\t\t\t} else {\n\t\t\t\t\tstates.add(next.hash());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t*/\t\n\t\tactions.removeAll(pruned);\n\n\t}\n\n\tprivate boolean onlyCard(GameState state, Card card) {\n\t\t\n\t\tif (state.p1Turn)\n\t\t\treturn state.p1Hand.count(card) == 1;\n\t\t\n\t\treturn state.p2Hand.count(card) == 1;\t\n\t\t\n\t}\n\n\tprivate boolean sameOrBetterSpellEffect(Map<DropAction, List<Position>> spellTargets, DropAction spell, List<Action> pruned) {\n\n\t\tint same = 0;\n\t\tfor (final Action action : spellTargets.keySet()) {\n\t\t\tif (action.equals(spell) || pruned.contains(action))\n\t\t\t\tcontinue;\n\t\t\tsame = 0;\n\t\t\tfor (final Position pos : spellTargets.get(spell))\n\t\t\t\tif (spellTargets.get(action).contains(pos))\n\t\t\t\t\tsame++;\n\t\t\tif (same == spellTargets.get(spell).size())\n\t\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tprivate List<Position> spellTargets(Position to, GameState state) {\n\t\tfinal List<Position> targets = new ArrayList<Position>();\n\t\tfor (int x = to.x - 1; x <= to.x + 1; x++)\n\t\t\tfor (int y = to.y - 1; y <= to.y + 1; y++)\n\t\t\t\tif (x >= 0 && x < state.map.width && y >= 0\n\t\t\t\t\t\t&& y < state.map.height) {\n\t\t\t\t\tfinal Unit unit = state.unitAt(x, y);\n\t\t\t\t\tif (unit != null && unit.p1Owner != state.p1Turn)\n\t\t\t\t\t\ttargets.add(new Position(x, y));\n\t\t\t\t}\n\t\treturn targets;\n\t}\n\n}",
"public class ComplexActionComparator extends ActionComparator {\n\n\tfinal List<Position> targets = new ArrayList<Position>();\n\n\t@Override\n\tpublic int value(Action action) {\n\n\t\tif (action instanceof EndTurnAction)\n\t\t\tif (state.APLeft == 0)\n\t\t\t\treturn 10000;\n\t\t\telse\n\t\t\t\treturn 0;\n\n\t\tif (action instanceof SwapCardAction)\n\t\t\treturn 0;\n\n\t\tif (action instanceof DropAction) {\n\t\t\tfinal DropAction drop = ((DropAction) action);\n\t\t\tif (drop.type == Card.INFERNO) {\n\t\t\t\ttargets.clear();\n\t\t\t\tspellTargets(drop.to, targets);\n\t\t\t\tint val = -500;\n\t\t\t\tfor (final Position pos : targets)\n\t\t\t\t\tif (state.units[pos.x][pos.y].hp == 0)\n\t\t\t\t\t\tval += state.units[pos.x][pos.y].maxHP() * 2;\n\t\t\t\t\telse\n\t\t\t\t\t\tval += 300;\n\t\t\t\treturn val;\n\t\t\t} else if (drop.type == Card.REVIVE_POTION) {\n\t\t\t\tif (state.units[drop.to.x][drop.to.y].hp == 0)\n\t\t\t\t\treturn state.units[drop.to.x][drop.to.y].maxHP()\n\t\t\t\t\t\t\t+ state.units[drop.to.x][drop.to.y].equipment.size() * 200;\n\t\t\t\telse\n\t\t\t\t\treturn state.units[drop.to.x][drop.to.y].maxHP() - state.units[drop.to.x][drop.to.y].hp - 300;\n\t\t\t} else if (drop.type == Card.SCROLL)\n\t\t\t\treturn state.units[drop.to.x][drop.to.y].power(state, drop.to) * (state.units[drop.to.x][drop.to.y].hp / state.units[drop.to.x][drop.to.y].maxHP());\n\t\t\telse if (drop.type == Card.DRAGONSCALE)\n\t\t\t\treturn state.units[drop.to.x][drop.to.y].power(state, drop.to) * (state.units[drop.to.x][drop.to.y].hp / state.units[drop.to.x][drop.to.y].maxHP());\n\t\t\telse if (drop.type == Card.RUNEMETAL)\n\t\t\t\treturn state.units[drop.to.x][drop.to.y].power(state, drop.to) * (state.units[drop.to.x][drop.to.y].hp / state.units[drop.to.x][drop.to.y].maxHP());\n\t\t\telse if (drop.type == Card.SHINING_HELM)\n\t\t\t\treturn state.units[drop.to.x][drop.to.y].power(state, drop.to) * (state.units[drop.to.x][drop.to.y].hp / state.units[drop.to.x][drop.to.y].maxHP());\n\t\t\telse\n\t\t\t\treturn 200;\n\t\t} else if (action instanceof UnitAction)\n\t\t\tif (((UnitAction) action).type == UnitActionType.ATTACK) {\n\t\t\t\tfinal Unit defender = state.units[((UnitAction) action).to.x][((UnitAction) action).to.y];\n\t\t\t\tfinal Unit attacker = state.units[((UnitAction) action).from.x][((UnitAction) action).from.y];\n\t\t\t\tif (attacker.unitClass.attack.chain) {\t\n\t\t\t\t\tif (defender.hp == 0)\n\t\t\t\t\t\treturn defender.maxHP() * 2 + 200;\n\t\t\t\t\telse\n\t\t\t\t\t\treturn attacker.power(state, ((UnitAction) action).from) + 200;\n\t\t\t\t} else if (defender.hp == 0)\n\t\t\t\t\treturn defender.maxHP() * 2;\n\t\t\t\telse\n\t\t\t\t\treturn attacker.power(state, ((UnitAction) action).from);\n\t\t\t} else if (((UnitAction) action).type == UnitActionType.HEAL) {\n\t\t\t\tfinal Unit target = state.units[((UnitAction) action).to.x][((UnitAction) action).to.y];\n\t\t\t\tif (target.hp == 0)\n\t\t\t\t\treturn 1400;\n\t\t\t\telse\n\t\t\t\t\treturn target.maxHP() - target.hp;\n\t\t\t} else if (((UnitAction) action).type == UnitActionType.SWAP)\n\t\t\t\treturn 0;\n\t\t\telse if (((UnitAction) action).type == UnitActionType.MOVE) {\n\t\t\t\tif (state.units[((UnitAction) action).to.x][((UnitAction) action).to.y] != null)\n\t\t\t\t\treturn state.units[((UnitAction) action).to.x][((UnitAction) action).to.y].maxHP() * 2;\n\t\t\t\tif (state.map.squares[((UnitAction) action).to.x][((UnitAction) action).to.y] == SquareType.NONE)\n\t\t\t\t\treturn 0;\n\t\t\t\telse\n\t\t\t\t\treturn 30;\n\t\t\t}\n\t\treturn 0;\n\t}\n\n\tprivate void spellTargets(Position to, List<Position> spellTargets) {\n\t\tfor (int x = to.x - 1; x <= to.x + 1; x++)\n\t\t\tfor (int y = to.y - 1; y <= to.y + 1; y++)\n\t\t\t\tif (x >= 0 && x < state.map.width && y >= 0\n\t\t\t\t\t\t&& y < state.map.height) {\n\t\t\t\t\tfinal Unit unit = state.unitAt(x, y);\n\t\t\t\t\tif (unit != null && unit.p1Owner != state.p1Turn)\n\t\t\t\t\t\tspellTargets.add(new Position(x, y));\n\t\t\t\t}\n\t}\n}"
] | import game.GameState;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import util.Statistics;
import action.Action;
import action.SingletonAction;
import ai.AI;
import ai.evaluation.IStateEvaluator;
import ai.util.ActionComparator;
import ai.util.ActionPruner;
import ai.util.ComplexActionComparator;
| ap--;
}
traversal.clear();
clone.imitate(state);
// SELECTION + EXPANSION
treePolicy(root, clone, traversal);
// SIMULATION
delta = defaultPolicy.eval(clone, state.p1Turn);
// BACKPROPAGATION
backupNegaMax(traversal, delta, state.p1Turn);
time = (start + budget) - System.currentTimeMillis();
rolls++;
fitnesses.put(rolls, bestMoveValue(root, state.p1Turn));
// saveTree();
}
// TODO: Runs out of memory -- of course..
/*
if (RECORD_DEPTHS){
root.depth(0, depths, new HashSet<MctsNode>());
avgDepths.add(Statistics.avgDouble(depths));
minDepths.add(Collections.min(depths));
maxDepths.add(Collections.max(depths));
depths.clear();
}
rollouts.add((double) rolls);
*/
//saveTree();
move = bestMove(state, rolls);
final Action action = move.get(0);
move.remove(0);
// Reset search
if (resetRoot)
root = null;
transTable.clear();
ends = 0;
return action;
}
private void saveTree() {
PrintWriter out = null;
try {
out = new PrintWriter("mcts.xml");
out.print(root.toXml(0, new HashSet<MctsNode>(), 12));
} catch (final FileNotFoundException e) {
e.printStackTrace();
} finally {
if (out != null)
out.close();
}
}
private void cut(MctsNode node, MctsEdge from, int depth, int cut) {
if (node == null)
return;
if (depth == cut) {
final MctsEdge best = best(node, false);
node.out.clear();
node.possible.clear();
if (best != null)
node.out.add(best);
node.in.clear();
if (from != null)
node.in.add(from);
} else
for (final MctsEdge edge : node.out)
cut(edge.to, edge, depth + 1, cut);
}
private MctsEdge best(MctsNode node, boolean urgent) {
double bestVal = -100000;
MctsEdge bestEdge = null;
for (final MctsEdge edge : node.out) {
final double val = uct(edge, node, urgent);
if (val > bestVal) {
bestVal = val;
bestEdge = edge;
}
}
return bestEdge;
}
/**
*
* @param edge
* takes the role as child node
* @param node
* takes the role as parent
* @param urgent
* whether to pick most urgent node or the best
* @return
*/
private double uct(MctsEdge edge, MctsNode node, boolean urgent) {
if (urgent)
return edge.avg() + 2 * c
* Math.sqrt((2 * Math.log(node.visits)) / (edge.visits));
return edge.avg();
}
private boolean collapse(MctsNode node) {
final List<MctsEdge> remove = new ArrayList<MctsEdge>();
boolean end = false;
for (final MctsEdge edge : node.out) {
| if (edge.action == SingletonAction.endTurnAction)
| 3 |
lumag/JBookReader | src/org/jbookreader/renderingengine/RenderEngineTest.java | [
"public class FB2FilesTestFilter implements FilenameFilter {\n\tpublic boolean accept(File dir, String name) {\n\t\tif (name.endsWith(\".fb2\")) {\n\t\t\treturn true;\n\t\t}\n\t\tif (name.endsWith(\".xml\")) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\t\n}",
"public class TestConfig implements ITestConfig {\n\t/**\n\t * The <code>File</code> representing a directory holding all test files.\n\t */\n\tprivate static final File TESTS_DIR = new File(\"tests\", \"tests\"); \n\n\t/**\n\t * The <code>File</code> representing a directory holding all expected result files.\n\t */\n\tprivate static final File EXPECTED_DIR = new File(\"tests\", \"expected\");\n\n\t/**\n\t * The <code>File</code> representing a directory holding all temporary files.\n\t */\n\tprivate static final File TEMP_DIR = new File(\"tests\", \"temp\");\n\n\tpublic File getExpectedDir() {\n\t\treturn EXPECTED_DIR;\n\t}\n\n\tpublic File getTestsDir() {\n\t\treturn TESTS_DIR;\n\t}\n\t\n\tpublic File getTempDir() {\n\t\treturn TEMP_DIR;\n\t}\n\n}",
"public interface IBook {\n\n\t/**\n\t * Creates new body node with give tag and node names.\n\t * @param tagName the tag name\n\t * @param name the name of new body or null if it's main node.\n\t * @return new body node.\n\t */\n\tIContainerNode newBody(String tagName, String name);\n\n\t/**\n\t * Returns the main (the first) body of the book.\n\t * @return the main body of the book\n\t */\n\tIContainerNode getMainBody();\n\n\t/**\n\t * Returns a collection of book bodies.\n\t * @return a collection of book bodies.\n\t */\n\tCollection<IContainerNode> getBodies();\n\n\t/**\n\t * Allocates new binary data.\n\t * @param id the id of given data\n\t * @param contentType the content type of the data.\n\t * @return new binary blob object.\n\t */\n\tIBinaryData newBinaryData(String id, String contentType);\n\n\t/**\n\t * Returns the binary blob associated with specified <code>id</code>.\n\t * If no corresponding blob is found, returns <code>null</code>.\n\t * @param id the id of the blob\n\t * @return the binary blob associated with specified id.\n\t */\n\tIBinaryData getBinaryData(String id);\n\n\t/**\n\t * Returns an id->binary data mapping.\n\t * @return an id->binary data mapping.\n\t */\n\tMap<String, ? extends IBinaryData> getBinaryMap();\n\n\t/**\n\t * Returns the system stylesheet for specified book.\n\t * @return the system stylesheet for specified book.\n\t */\n\tIStyleSheet getSystemStyleSheet();\n\t\n\t/**\n\t * Don't use this for now.\n\t * @param stylesheet\n\t */\n\tvoid setSystemStyleSheet(IStyleSheet stylesheet);\n\t\n\t/**\n\t * Returns the node with specified ID.\n\t * @param id the id of node\n\t * @return the node with specified ID.\n\t */\n\tINode getNodeByID(String id);\n\t\n\t/**\n\t * Returns the node corresponding to the string reference.\n\t * @see INode#getNodeReference()\n\t * @param reference the strign reference of the node\n\t * @return the node corresponding to the <code>reference</code>.\n\t */\n\tINode getNodeByReference(String reference);\n}",
"public class FB2Parser {\n\t/**\n\t * The namespace of FB2 tags\n\t */\n\tpublic static final String FB2_XMLNS_URI = \"http://www.gribuser.ru/xml/fictionbook/2.0\";\n\t\n\t/**\n\t * This parses the book located at the <code>uri</code>.\n\t * @param uri the location of book to parse\n\t * @return the parsed book representation\n\t * @throws IOException in case of I/O problem\n\t * @throws SAXException in case of XML parsing problem\n\t */\n\tpublic static IBook parse(String uri) throws IOException, SAXException {\n\t\treturn parse(new InputSource(uri));\n\t}\n\n\t/**\n\t * This parses the book at provided <code>InputStream</code>.\n\t * @param stream the stream with the book\n\t * @return the parsed book representation\n\t * @throws IOException in case of I/O problem\n\t * @throws SAXException in case of XML parsing problem\n\t */\n\tpublic static IBook parse(InputStream stream) throws IOException, SAXException {\n\t\treturn parse(new InputSource(new BufferedInputStream(stream)));\n\t}\n\n\t/**\n\t * This parses the book at provided <code>InputSource</code>.\n\t * @param source the source with the book\n\t * @return the parsed book representation\n\t * @throws IOException in case of I/O problem\n\t * @throws SAXException in case of XML parsing problem\n\t */\n\tprivate static IBook parse(InputSource source) throws IOException, SAXException {\n\t\tXMLReader reader;\n\t\t\n\t\treader = XMLReaderFactory.createXMLReader();\n\t\treader.setErrorHandler(new ParseErrorHandler());\n\n\t\tIBook book = new Book();\n\t\tbook.setSystemStyleSheet(getFB2StyleSheet());\n\t\t\n\t\treader.setContentHandler(new FB2ContentsHandler(book));\n\n\t\treader.parse(source);\n\n\t\treturn book;\t\n\t}\n\t\n\t/**\n\t * Parses specified book\n\t * @param file the file with the book\n\t * @return the parsed book representation\n\t * @throws IOException in case of I/O problem\n\t * @throws SAXException in case of XML parsing problem\n\t */\n\tpublic static IBook parse(File file) throws IOException, SAXException {\n\t\treturn parse(file.getAbsolutePath());\n\t}\n\t\n\t// FIXME: after finishing stylesheet loading, replace with reading of stylesheet.\n\t/**\n\t * The fb2 format stylesheet\n\t */\n\tprivate static IStyleSheet ssheet;\n\t/**\n\t * Returns FB2 system style sheet.\n\t * @return FB2 system style sheet.\n\t */\n\tprivate static IStyleSheet getFB2StyleSheet() {\n\t\tif (ssheet == null) {\n\t\t\tssheet = new FB2StyleSheet();\n\t\t}\n\t\treturn ssheet;\n\t}\n\n\t/**\n\t * This is a handler for SAX events for FB2 parser.\n\t * \n\t * @author Dmitry Baryshkov ([email protected])\n\t *\n\t */\n\tprivate static class FB2ContentsHandler extends DefaultHandler{\n\t\t/**\n\t\t * The locator of the parser.\n\t\t */\n\t\t@SuppressWarnings(\"unused\")\n\t\tprivate Locator myLocator;\n\t\t\n\t\t/**\n\t\t * The book being parsed.\n\t\t */\n\t\tprivate final IBook myBook;\n\t\t/**\n\t\t * Binary blob data being parsed.\n\t\t */\n\t\tprivate IBinaryData myBinaryData;\n\n\t\t/**\n\t\t * The container being parsed.\n\t\t */\n\t\tprivate IContainerNode myContainer;\n\n\t\t/**\n\t\t * Current text for #text nodes.\n\t\t */\n\t\tprivate StringBuilder myText = new StringBuilder();\n\t\t\n\t\t/**\n\t\t * Flag used for whitespace trimming.\n\t\t */\n\t\tprivate boolean hadOpenTag = false;\n\t\t\n\t\t/**\n\t\t * Flag used for whitespace trimming.\n\t\t */\n\t\tprivate boolean hadCloseTag;\n\t\t\n\t\t/**\n\t\t * FIXME: remove this!!!!!\n\t\t * it a workaround: we can't parseXML metadata currently. Only bodies and binary.\n\t\t */\n\t\tprivate boolean parseXML = false;\n\n\t\t/**\n\t\t * True if the current node can containt text.\n\t\t */\n\t\tprivate boolean myParseText = false;\n\n\t\t/**\n\t\t * This constructs new parser for given <code>book</code>\n\t\t * @param book the book being parsed.\n\t\t */\n\t\tpublic FB2ContentsHandler(IBook book) {\n\t\t\tthis.myBook = book;\n\t\t}\n\n\t\t@Override\n\t\tpublic void setDocumentLocator(Locator locator) {\n\t\t\tthis.myLocator = locator;\n\t\t}\n\n\t\t@Override\n\t\tpublic void characters(char[] ch, int start, int length) {\n\t\t\tif (!this.parseXML) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t\n\t\t\tif (!this.myParseText) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t\n\t\t\tthis.myText.append(ch, start, length);\n\t\t}\n\t\t\n\t\t/**\n\t\t * This processes information in <code>this.myText</code> into new #text node.\n\t\t * @see FB2ContentsHandler#myText\n\t\t */\n\t\tprivate void processTextNode() {\n\t\t\tif (!this.myParseText) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t\n\t\t\tString string = trimStringBuilder(this.myText, this.hadOpenTag, this.hadCloseTag);\n//\t\t\tString string = this.myText.toString();\n\t\t\tthis.myText.setLength(0);\n\t\t\t\n\t\t\tif (string.length() == 0) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthis.myContainer.newTextNode(string);\n\n//\t\t\tSystem.out.println(\"#text: '\" + string + \"'\");\n\t\t}\n\t\t\n\t\t/**\n\t\t * Returns true if passed tag name denotes start of paragraph.\n\t\t * @param tagName the name of the tag\n\t\t * @return whether passed tag name denotes start of paragraph.\n\t\t */\n\t\tprivate boolean isParagraphTag(String tagName) {\n\t\t\tif (tagName.equals(\"p\")\n\t\t\t || tagName.equals(\"subtitle\")\n\t\t\t || tagName.equals(\"text-author\")\n\t\t\t || tagName.equals(\"v\")) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\t\n\t\t\treturn false;\n\t\t}\n\n\t\t@Override\n\t\tpublic void endElement(String uri, String localName, String qName) {\n\t\t\tif (!this.parseXML) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t\n\t\t\t// System.out.println(\"</\" + localName + \":\" + ((this.myContainer!=null)?this.myContainer.getTagName():\"null\"));\n\t\t\tif (localName.equals(\"FictionBook\")) {\n\t\t\t\t// XXX: root node;\n\t\t\t} else if (localName.equals(\"binary\")) {\n\t\t\t\tthis.myBinaryData.setBase64Encoded(this.myText.toString().toCharArray());\n\t\t\t\tthis.myText.setLength(0);\n\t\t\t\tthis.myBinaryData = null;\n\t\t\t\tthis.myParseText = false;\n\t\t\t} else {\n\t\t\t\t// part of body\n\t\t\t\tthis.hadCloseTag = true;\n\t\t\t\tprocessTextNode();\n\t\t\t\tthis.hadOpenTag = false;\n\t\t\t\t\n\t\t\t\tif (isParagraphTag(localName)) {\n\t\t\t\t\tthis.myParseText = false;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (this.myContainer.getTagName().equals(localName)) {\n\t\t\t\t\tthis.myContainer = this.myContainer.getParentNode();\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t\t// System.out.println(\"</\" + localName);\n\t\t}\n\n\t\t@Override\n\t\tpublic void startElement(String uri, String localName, String qName, Attributes attributes) {\n\t\t\tif (!this.parseXML) {\n\t\t\t\tif (!localName.equals(\"body\")) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n//\t\t\t\tSystem.out.println(\"Got first body tag\");\n\t\t\t\t\n\t\t\t\tthis.parseXML = true;\n\t\t\t}\n\t\t\t\n\t\t\t// System.out.println(\"<\" + localName);\n\n\t\t\tif (localName.equals(\"FictionBook\")) {\n\t\t\t\t// XXX: root book node\n\t\t\t} else if (localName.equals(\"binary\")) {\n\t\t\t\tthis.myBinaryData = this.myBook.newBinaryData(attributes.getValue(\"id\"), attributes.getValue(\"content-type\"));\n\t\t\t\tthis.myParseText = true;\n\t\t\t\treturn;\n\t\t\t} else {\n\t\t\t\tINode node = null;\n\n\t\t\t\tthis.hadCloseTag = false;\n\t\t\t\tprocessTextNode();\n\t\t\t\tthis.hadOpenTag = true;\n\t\t\t\n\t\t\t\tif (localName.equals(\"body\")) {\n\t\t\t\t\tnode = this.myBook.newBody(\"body\", attributes.getValue(\"name\"));\n\t\t\t\t} else if (localName.equals(\"title\")) {\n\t\t\t\t\tnode = this.myContainer.newTitle(localName);\n\t\t\t\t} else if (localName.equals(\"image\")) {\n\t\t\t\t\tString href = null;\n\t\t\t\t\thref = attributes.getValue(\"http://www.w3.org/1999/xlink\", \"href\");\n\t\t\t\t\tif (href == null) {\n\t\t\t\t\t\thref = attributes.getValue(\"href\");\n\t\t\t\t\t}\n\t\t\t\t\tif (href == null) {\n\t\t\t\t\t\tSystem.err.println(\"Can'f find image href!\");\n\t\t\t\t\t}\n\t\t\t\t\tIImageNode image = this.myContainer.newImage(localName, href);\n\t\t\t\t\tString str;\n\t\t\t\t\tif ((str = attributes.getValue(\"alt\")) != null) {\n\t\t\t\t\t\timage.setText(str);\n\t\t\t\t\t}\n\t\t\t\t\tif ((str = attributes.getValue(\"title\")) != null) {\n\t\t\t\t\t\timage.setTitle(str);\n\t\t\t\t\t}\n\t\t\t\t\tnode = image;\n\t\t\t\t} else if (isParagraphTag(localName)) {\n\t\t\t\t\tnode = this.myContainer.newContainerNode(localName);\n\t\n\t\t\t\t\tthis.myParseText = true;\n\t\t\t\t} else {\n\t\t\t\t\t/*\n\t\t\t\t\t * Threat every unknown node as a simple container.\n\t\t\t\t\t */\n\t\t\t\t\tnode = this.myContainer.newContainerNode(localName);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tString classAttribute;\n\t\t\t\t\n\t\t\t\tif (localName.equals(\"p\")) {\n\t\t\t\t\tclassAttribute = \"style\";\n\t\t\t\t} else if (localName.equals(\"style\")) {\n\t\t\t\t\tclassAttribute = \"name\";\n\t\t\t\t} else {\n\t\t\t\t\tclassAttribute = \"class\";\n\t\t\t\t}\n\t\t\t\tnode.setNodeClass(attributes.getValue(classAttribute));\n\t\t\t\t\n\t\t\t\tif (node instanceof IContainerNode) {\n\t\t\t\t\tthis.myContainer = (IContainerNode)node;\n\t\t\t\t}\n\n\t\t\t\t{\n\t\t\t\t\tString id;\n\t\t\t\t\tif ((id = attributes.getValue(\"id\")) != null) {\n\t\t\t\t\t\tnode.setID(id);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\n\n\t\t}\n\t\t\n\t\t/**\n\t\t * An utitlity function. It generates a string from {@link java.lang.StringBuilder} with\n\t\t * starting and leading whitespace chars removed.\n\t\t * @param builder the <code>StringBuilder</code> to generate string\n\t\t * @param trimEnd \n\t\t * @param trimStart \n\t\t * @return a string from <code>builder</code>.\n\t\t */\n\t\tprivate static String trimStringBuilder(StringBuilder builder, boolean trimStart, boolean trimEnd) {\n\t\t\tint length = builder.length();\n\t\t\tif ((length == 0)\n\t\t\t\t\t|| (builder.charAt(0) > '\\u0020')\n\t\t\t\t\t&& (builder.charAt(length-1) > '\\u0020')) {\n\t\t\t\treturn builder.toString();\n\t\t\t}\n\n\t\t\tint begin = 0;\n\t\t\tint end = length-1;\n\t\t\tif (trimStart) {\n\t\t\t\twhile ((begin <= end) && (builder.charAt(begin) <= '\\u0020')) {\n\t\t\t\t\tbegin++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (trimEnd) {\n\t\t\t\twhile ((begin <= end) && (builder.charAt(end) <= '\\u0020')) {\n\t\t\t\t\tend--;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (begin > end) {\n\t\t\t\treturn \"\";\n\t\t\t}\n\t\t\treturn builder.substring(begin, end+1);\n\t\t}\n\t\t\n\t}\n\n}",
"public interface IBookPainter {\n\t/**\n\t * Clears the output device, if it makes sense.\n\t * \n\t */\n\tvoid clear();\n\n\t/**\n\t * Returns the width of the device.\n\t * \n\t * @return the width of the device.\n\t */\n\tdouble getWidth();\n\n\t/**\n\t * Returns the height of the device.\n\t * \n\t * @return the height of the device.\n\t */\n\tdouble getHeight();\n\n\t/**\n\t * This adds the horizontal space of given size.\n\t * \n\t * @param size the size of necessary horizontal space.\n\t */\n\tvoid addHorizontalStrut(double size);\n\n\t/**\n\t * This adds the vertical space of given size.\n\t * \n\t * @param size the size of necessary vertical space.\n\t */\n\tvoid addVerticalStrut(double size);\n\n\t/**\n\t * Allocates and returns specified font.\n\t * \n\t * @param name the name of the font\n\t * @param size font size\n\t * @return the allocated font object.\n\t */\n\tIFont getFont(String name, int size);\n\n\t/**\n\t * Returns current X coordinate.\n\t * \n\t * @return current X coordinate.\n\t */\n\tdouble getXCoordinate();\n\n\t/**\n\t * Returns current Y coordinate.\n\t * \n\t * @return current Y coordinate.\n\t */\n\tdouble getYCoordinate();\n\n\t/**\n\t * Returns a rendering object for the image or <code>null</code> if\n\t * the image can't be rendered.\n\t * @param node the node representing the image\n\t * @param contentType the content type of the image\n\t * @param stream the stream with the image\n\t * \n\t * @return a rendering object for the image.\n\t */\n\tIInlineRenderingObject getImage(INode node, String contentType, InputStream stream);\n}",
"public class FormatEngine implements IFormatEngine {\n\n\tprivate List<IRenderingObject> myResult;\n\tprivate Line myCurrentLine;\n\n\t/**\n\t * Skip all whitespace in the provided string and return the the index of\n\t * first non-whitespace char.\n\t * \n\t * @param text the string.\n\t * @param start the start of the string\n\t * @return the index of first non-whitespace character.\n\t */\n\tprivate int consumeWhitespace(String text, int start) {\n\t\twhile ((start < text.length()) && (text.charAt(start) <= '\\u0020')) {\n\t\t\tstart ++;\n\t\t}\n\t\treturn start;\n\t}\n\t\n\tprivate void formatNode(INode node, IStyleStack styleStack, double width) {\n\t\tif (node instanceof IContainerNode) {\n\t\t\tformatContainerNode((IContainerNode) node, styleStack, width);\n\t\t} else if (node instanceof IImageNode) {\n\t\t\tformatInlineImageNode((IImageNode) node, styleStack, width);\n\t\t} else {\n\t\t\tformatTextNode(node, styleStack, width);\n\t\t}\n\t}\n\t\n\tprivate void formatContainerNode(IContainerNode cnode, IStyleStack styleStack, double width) {\n\t\tfor (INode childNode : cnode.getChildNodes()) {\n\t\t\tstyleStack.pushTag(childNode.getTagName(), childNode.getNodeClass(), childNode.getID());\n\t\t\tformatNode(childNode, styleStack, width);\n\t\t\tstyleStack.popTag();\n\t\t}\n\t}\n\t\n\tprivate IInlineRenderingObject getImageObject(IBookPainter painter, IImageNode image) {\n\t\t// XXX: correct work with url's.\n\t\tIBinaryData blob = image.getBook().getBinaryData(image.getHyperRef().substring(1));\n\t\tIInlineRenderingObject robject = painter.getImage(\n\t\t\t\tnull,\n\t\t\t\tblob.getContentType(),\n\t\t\t\tnew ByteArrayInputStream(\n\t\t\t\t\t\tblob.getContentsArray(),\n\t\t\t\t\t\t0,\n\t\t\t\t\t\tblob.getContentsLength()\n\t\t\t\t\t\t)\n\t\t\t\t);\n\t\t\n\t\treturn robject;\n\t}\n\n\tprivate void formatInlineImageNode(IImageNode image, IStyleStack styleStack, double width) {\n\t\t\n\t\tIInlineRenderingObject robject = getImageObject(this.myCurrentLine.getPainter(), image);\n\n\t\tif (robject == null) {\n\t\t\tformatTextNode(image, styleStack, width);\n\t\t} else {\n\t\t\tappendRobject(robject, styleStack, width);\n\t\t}\n\t}\n\n\tprivate void formatImageNode(IBookPainter painter, IImageNode image, IStyleStack styleStack, double width) {\n\t\tIRenderingObject robject = getImageObject(painter, image);\n\n\t\tif (robject == null) {\n\t\t\tnewParagraph(painter, image, styleStack);\n\t\t\twidth -= styleStack.getMarginLeft() + styleStack.getMarginRight();\n\n\t\t\tformatTextNode(image, styleStack, width);\n\n\t\t\tthis.myResult.add(this.myCurrentLine);\n\t\t\tthis.myCurrentLine = null;\n\t\t} else {\n\t\t\t// TODO: format title, etc.\n\t\t\tthis.myResult.add(robject);\n\t\t}\n\t}\n\n\tprivate void formatTextNode(INode node, IStyleStack styleStack, double width) {\n\t\tString text = node.getText();\n\n\t\tif (text == null) {\n\t\t\tSystem.err.println(\"WARNING: node '\" + node.getTagName() + \"' doesn't has text\");\n\t\t\treturn;\n\t\t}\n\n\t\tIFont font = this.myCurrentLine.getPainter().getFont(styleStack.getFontFamily(), styleStack.getFontSize());\n\t\tint start = 0;\n\t\tint end = 0;\n\t\twhile (end < text.length()) {\n\t\t\tint newWord = consumeWhitespace(text, start);\n\t\t\tif (newWord > start) {\n\t\t\t\t// XXX: calculate more correct space size?\n\t\t\t\tdouble strut = font.getSpaceWidth();\n\t\t\t\tif (strut + this.myCurrentLine.getWidth() <= width) {\n\t\t\t\t\tthis.myCurrentLine.appendObject(new HorizontalGlue(this.myCurrentLine.getPainter(), node, strut));\n\t\t\t\t}\n\t\t\t}\n\t\t\tend = start = newWord;\n\n\t\t\tif (end >= text.length()) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\twhile ((end < text.length()) && (text.charAt(end) > '\\u0020')) {\n\t\t\t\tend ++;\n\t\t\t}\n\n\t\t\tIInlineRenderingObject string = new MetaString(this.myCurrentLine.getPainter(), node, styleStack.getLineHeight(), text, start, end, font);\n\t\t\tappendRobject(string, styleStack, width);\n\n\t\t\tstart = end;\n\t\t}\n\t}\n\n\tprivate void flushLine(boolean lastLine, double width, IStyleStack styleStack) {\n\t\tswitch (styleStack.getTextAlign()) {\n\t\t\tcase LEFT:\n\t\t\t\tthis.myCurrentLine.appendObject(new HorizontalGlue(this.myCurrentLine.getPainter(), this.myCurrentLine.getNode(), width - this.myCurrentLine.getWidth()));\n\t\t\t\tbreak;\n\t\t\tcase RIGHT:\n\t\t\t\tthis.myCurrentLine.prependObject(new HorizontalGlue(this.myCurrentLine.getPainter(), this.myCurrentLine.getNode(), width - this.myCurrentLine.getWidth()));\n\t\t\t\tbreak;\n\t\t\tcase CENTER:\n\t\t\t\tthis.myCurrentLine.prependObject(new HorizontalGlue(this.myCurrentLine.getPainter(), this.myCurrentLine.getNode(), (width - this.myCurrentLine.getWidth())/2));\n\t\t\t\tthis.myCurrentLine.appendObject(new HorizontalGlue(this.myCurrentLine.getPainter(), this.myCurrentLine.getNode(), width - this.myCurrentLine.getWidth()));\n\t\t\t\tbreak;\n\t\t\tcase JUSTIFY:\n\t\t\t\tif (!lastLine) {\n\t\t\t\t\tthis.myCurrentLine.adjustWidth(width - this.myCurrentLine.getWidth());\n\t\t\t\t}\n\t\t}\n\t\tthis.myResult.add(this.myCurrentLine);\n\t\tthis.myCurrentLine = null;\n\t}\n\t\n\tprivate void appendRobject (IInlineRenderingObject object, IStyleStack styleStack, double width) {\n\t\t// XXX: this is the main place for rendering decision\n\t\tif (this.myCurrentLine.getWidth() + object.getWidth() > width) {\n\t\t\tLine newLine = new Line(this.myCurrentLine.getPainter(), this.myCurrentLine.getNode());\n\t\t\tflushLine(false, width, styleStack);\n\t\t\tthis.myCurrentLine = newLine;\n\t\t}\n\t\tthis.myCurrentLine.appendObject(object);\n\t}\n\t\n\tprivate void newParagraph(IBookPainter painter, INode node, IStyleStack styleStack) {\n\t\tthis.myResult = new ArrayList<IRenderingObject>();\n\n\t\tthis.myCurrentLine = new Line(painter, node);\n\t\tthis.myCurrentLine.appendObject(new HorizontalGlue(painter, node, styleStack.getTextIndent()));\n\t}\n\n\tprivate void formatStyledText(IBookPainter painter, INode node, IStyleStack styleStack, double width) {\n\t\tnewParagraph(painter, node, styleStack);\n\t\twidth -= styleStack.getMarginLeft() + styleStack.getMarginRight();\n\n\t\tformatNode(node, styleStack, width);\n\n\t\t// XXX: hack to fix emty-line rendering\n\t\tif (this.myCurrentLine.getHeight() == 0\n\t\t\t&& this.myCurrentLine.getWidth() == 0) {\n\t\t\tthis.myCurrentLine.appendObject(\n\t\t\t\t\tnew HorizontalGlue(\n\t\t\t\t\t\t\tpainter,\n\t\t\t\t\t\t\tthis.myCurrentLine.getNode(),\n\t\t\t\t\t\t\t0,\n\t\t\t\t\t\t\tstyleStack.getLineHeight() * styleStack.getFontSize()\n\t\t\t\t\t\t\t)\n\t\t\t\t\t);\n\t\t}\n\t\tflushLine(true, width, styleStack);\n\t}\n\n\tpublic List<IRenderingObject> formatParagraphNode(IBookPainter painter, INode node, IStyleStack styleStack, double width) {\n\t\t\n\t\tthis.myResult = new ArrayList<IRenderingObject>();\n\t\t\n\t\tif (node instanceof IImageNode) {\n\t\t\tformatImageNode(painter, (IImageNode) node, styleStack, width);\n\t\t} else {\n\t\t\tformatStyledText(painter, node, styleStack, width);\n\t\t}\n\t\t\n\t\tthis.myResult.get(0).setMarginTop(styleStack.getMarginTop());\n\t\tthis.myResult.get(this.myResult.size()-1).setMarginBottom(styleStack.getMarginBottom());\n\t\t\n\t\tfor (IRenderingObject robject: this.myResult) {\n\t\t\trobject.setMarginLeft(styleStack.getMarginLeft());\n\t\t\trobject.setMarginRight(styleStack.getMarginRight());\n\t\t}\n\t\t\n\t\treturn this.myResult;\n\t}\n\n}",
"public class RenderingEngine {\n\t/**\n\t * Current book painter.\n\t */\n\tprivate IBookPainter myPainter;\n\n\t/**\n\t * Current book.\n\t */\n\tprivate IBook myBook;\n\t\n\tprivate final IFormatEngine myFormatEngine;\n\n\tprivate String myFontFamily;\n\n\tprivate int myFontSize;\n\t\n\tprivate INode myStartNode;\n\tprivate int myStartRenderingObject;\n\tprivate double myStartY;\n\tprivate double myPageHeight;\n\t\n\tprivate Map<INode, List<IRenderingObject>> myFormattedNodes = new WeakHashMap<INode, List<IRenderingObject>>();\n\t\n\t/**\n\t * This constructs new Rendering engine for the given format engine.\n\t * @param formatEngine the format engine to use for formatting\n\t */\n\tpublic RenderingEngine(IFormatEngine formatEngine) {\n\t\tthis.myFormatEngine = formatEngine;\n\t}\n\n\n\t/**\n\t * Sets <code>painter</code> as a new output device.\n\t * \n\t * @param painter painter representing new output device.\n\t */\n\tpublic void setPainter(IBookPainter painter) {\n\t\tthis.myPainter = painter;\n\t\tthis.myPageHeight = painter.getHeight();\n\t}\n\t\n\n\t/**\n\t * Sets the new book to be output.\n\t * \n\t * @param book new book to display.\n\t */\n\tpublic void setBook(IBook book) {\n\t\tthis.myBook = book;\n\t\tINode node = this.myBook.getMainBody();\n\t\tIStyleStack styleStack = replayStyleStack(node);\n\n\t\tthis.myStartNode = getParagraphNodeDown(node, styleStack, true);\n\t\tthis.myStartRenderingObject = 0;\n\n\t\tflush();\n\t}\n\n\t/**\n\t * Returns the paragraph node to be formatted right before or after\n\t * <code>node</code>\n\t * \n\t * @param node current node\n\t * @param styleStack the stack of style information corresponding to the\n\t * <code>node</code>\n\t * @param next whether to search next or previous node\n\t * @return next paragraph node.\n\t */\n\tprivate INode getParagraphNode(INode node, IStyleStack styleStack, boolean next) {\n\t\twhile (true) {\n\t\t\tIContainerNode pnode = node.getParentNode();\n\t\t\tstyleStack.popTag();\n\n\t\t\t// end of book\n\t\t\tif (pnode == null) {\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\tList<INode> children = pnode.getChildNodes();\n\t\t\tint index = children.indexOf(node);\n\t\t\tint nextindex = index + ((next) ? (+1) : (-1));\n\t\t\tif (index == -1) {\n\t\t\t\tthrow new IllegalStateException(\"Node '\" + node + \"' not found in it's parent list!!!!\");\n\t\t\t} else if (nextindex < children.size() && nextindex >= 0) {\n\t\t\t\tnode = children.get(nextindex);\n\t\t\t\tstyleStack.pushTag(node.getTagName(), node.getNodeClass(), node.getID());\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tnode = pnode;\n\t\t}\n\n\t\treturn getParagraphNodeDown(node, styleStack, next);\n\t}\n\n\t/**\n\t * Returns the first or the last paragraph node in the specified container\n\t * node.\n\t * \n\t * @param node the container node.\n\t * @param styleStack the stack of style information corresponding to the\n\t * <code>node</code>\n\t * @param first whether to search first or last node\n\t * @return the first paragraph node in the specified container node.\n\t */\n\tprivate INode getParagraphNodeDown(INode node, IStyleStack styleStack, boolean first) {\n\t\twhile (true) {\n\t\t\tif (! (node instanceof IContainerNode)) {\n\t\t\t\treturn node;\n\t\t\t}\n\t\t\tIContainerNode cnode = (IContainerNode)node;\n\n\t\t\tList<INode> children = cnode.getChildNodes();\n\t\t\tif (children.isEmpty()) {\n\t\t\t\treturn node;\n\t\t\t}\n\n\t\t\tint number = (first) ? 0 : (children.size() - 1);\n\n\t\t\tINode child = children.get(number);\n\t\t\tstyleStack.pushTag(child.getTagName(), child.getNodeClass(), child.getID());\n\t\t\tif (styleStack.getDisplay() == EDisplayType.INLINE) {\n\t\t\t\tstyleStack.popTag();\n\t\t\t\treturn node;\n\t\t\t}\n\n\t\t\tnode = child;\n\t\t}\n\t}\n\t\n//\tprivate int access;\n//\tprivate int misses;\n//\t\n\tprivate List<IRenderingObject> getFormattedNode(INode node, IStyleStack styleStack, double width) {\n\t\tList<IRenderingObject> robject = this.myFormattedNodes.get(node);\n//\t\tthis.access ++;\n\t\tif ((robject == null)/* || (robject.getWidth() != width)*/) {\n\t\t\trobject = this.myFormatEngine.formatParagraphNode(this.myPainter, node, styleStack, width);\n\t\t\tthis.myFormattedNodes.put(node, robject);\n//\t\t\tthis.misses ++;\n\t\t}\n\t\t\n\t\treturn robject;\n\t}\n\t\n\tprivate void fixupStartPosition() {\n\t\tINode node = this.myStartNode;\n\t\tIStyleStack styleStack = replayStyleStack(node);\n\n\t\tList<IRenderingObject> paragraph = getFormattedNode(node, styleStack, this.myPainter.getWidth());\n\t\tListIterator<IRenderingObject> robjectIterator = paragraph.listIterator(this.myStartRenderingObject);\n\n\t\t// FIXME: position handling (after I implement more correct node references)\n\n\t\tif (this.myStartY < 0) {\n\t\t\twhile (true) {\n\t\t\t\tif (!robjectIterator.hasNext()) {\n\t\t\t\t\tnode = getParagraphNode(node, styleStack, true);\n\t\t\t\t\tif (node == null) {\n\t\t\t\t\t\tnode = this.myStartNode;\n\t\t\t\t\t\tstyleStack = replayStyleStack(node);\n\t\t\t\t\t\tthis.myStartY = 0;\n\t\t\t\t\t\tthis.myStartRenderingObject --;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tparagraph = getFormattedNode(node, styleStack, this.myPainter.getWidth());\n\t\t\t\t\tthis.myStartRenderingObject = 0;\n\t\t\t\t\trobjectIterator = paragraph.listIterator(this.myStartRenderingObject);\n\t\t\t\t\tthis.myStartNode = node;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tIRenderingObject robject = robjectIterator.next();\n\t\t\t\t\n\t\t\t\tif (this.myStartY + robject.getHeight() >= 0) {\n\t\t\t\t\tif (robject.isSplittable() || this.myStartY == 0) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tthis.myStartY = 0;\n\t\t\t\t} else {\n\t\t\t\t\tthis.myStartY += robject.getHeight();\n\t\t\t\t}\n\t\t\t\tthis.myStartRenderingObject ++;\n\t\t\t}\n\t\t} else if (this.myStartY > 0) {\n\t\t\twhile (true) {\n\t\t\t\tif (!robjectIterator.hasPrevious()) {\n\t\t\t\t\tnode = getParagraphNode(node, styleStack, false);\n\t\t\t\t\tif (node == null) {\n\t\t\t\t\t\tnode = this.myStartNode;\n\t\t\t\t\t\tstyleStack = replayStyleStack(node);\n\t\t\t\t\t\tthis.myStartY = 0;\n\t\t\t\t\t\tthis.myStartRenderingObject = 0;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tparagraph = getFormattedNode(node, styleStack, this.myPainter.getWidth());\n\t\t\t\t\tthis.myStartRenderingObject = paragraph.size();\n\t\t\t\t\trobjectIterator = paragraph.listIterator(this.myStartRenderingObject);\n\t\t\t\t\tthis.myStartNode = node;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tIRenderingObject robject = robjectIterator.previous();\n\n\t\t\t\tthis.myStartY -= robject.getHeight();\n\t\t\t\tthis.myStartRenderingObject --;\n\t\t\t\tif (this.myStartY <= 0) {\n\t\t\t\t\tif (!robject.isSplittable()) {\n\t\t\t\t\t\tthis.myStartY = 0;\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Renders a page of text.\n\t */\n\tpublic void renderPage() {\n\t\tthis.myPainter.clear();\n\n\t\tif (this.myBook == null) {\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tthis.myPageHeight = this.myPainter.getHeight();\n\n//\t\tSystem.out.println(this.myStartNode.getNodeReference() + \" : \" + this.myStartRenderingObject + \" @ \" + this.myStartY);\n\t\tfixupStartPosition();\n\n//\t\tSystem.out.println(this.myStartNode.getNodeReference() + \" : \" + this.myStartRenderingObject + \" @ \" + this.myStartY);\n\n\t\tINode node = this.myStartNode;\n\t\tIStyleStack styleStack = replayStyleStack(node);\n\n\t\tthis.myPainter.addVerticalStrut(this.myStartY);\n\t\t\n\t\tint startObject = this.myStartRenderingObject;\n\t\t\n\t\trenderLoop:\n\t\twhile (node != null) {\n\t\t\tList<IRenderingObject> paragraph = getFormattedNode(node, styleStack, this.myPainter.getWidth());\n\n\t\t\tfor (ListIterator<IRenderingObject> it = paragraph.listIterator(startObject); it.hasNext();) {\n\t\t\t\tIRenderingObject robject = it.next();\n\t\t\t\t\n\t\t\t\tdouble currentY = this.myPainter.getYCoordinate();\n\n\t\t\t\tif ((currentY >= this.myPageHeight)\n\t\t\t\t\t|| (!robject.isSplittable()\n\t\t\t\t\t\t\t&& (currentY + robject.getHeight() > this.myPageHeight) )) {\n\t\t\t\t\tbreak renderLoop;\n\t\t\t\t}\n\t\t\t\t\n//\t\t\t\tSystem.out.println(this.myPainter.getXCoordinate() + \" : \" + robject.getWidth());\n\t\t\t\trobject.render();\n\t\t\t}\n\t\t\t\n\t\t\tnode = getParagraphNode(node, styleStack, true);\n\t\t\tstartObject = 0;\n\t\t}\n\n//\t\tSystem.out.println((1.0*this.misses)/this.access);\n\t}\n\n\tprivate IStyleStack replayStyleStack(INode node) {\n\t\tIStyleStack result = node.getBook().getSystemStyleSheet().newStyleStateStack();\n\t\tif (this.myFontFamily != null) {\n\t\t\tresult.setDefaultFontFamily(this.myFontFamily);\n\t\t}\n\t\tif (this.myFontSize != 0) {\n\t\t\tresult.setDefaultFontSize(this.myFontSize);\n\t\t}\n\n\t\tList<INode> backList = new ArrayList<INode>();\n\n\t\twhile (node != null) {\n\t\t\tbackList.add(node);\n\t\t\tnode = node.getParentNode();\n\t\t}\n\n\t\tfor (ListIterator<INode> iterator = backList.listIterator(backList.size()); iterator.hasPrevious();) {\n\t\t\tINode current = iterator.previous();\n\t\t\tresult.pushTag(current.getTagName(), current.getNodeClass(), current.getID());\n\t\t}\n\n\t\treturn result;\n\t}\n\n\t/**\n\t * Scrolls text down by specified number of pixels\n\t * \n\t * @param pixels the amount of lines to scroll\n\t */\n\tpublic void scroll(int pixels) {\n\t\tthis.myStartY -= pixels;\n\t}\n\n\t/**\n\t * Sets default font to be used for rendering.\n\t * @param family the family of the font\n\t * @param size font size\n\t */\n\tpublic void setDefaultFont(String family, int size) {\n\t\tthis.myFontFamily = family;\n\t\tthis.myFontSize = size;\n\t}\n\n\t/**\n\t * Flush all internal caches, etc.\n\t */\n\tpublic void flush() {\n\t\tthis.myFormattedNodes.clear();\n\t\tthis.myStartY = 0;\n\t}\n\n\tpublic String getDisplayNodeReference() {\n\t\tif (this.myStartNode == null) {\n\t\t\treturn null;\n\t\t}\n\n\t\treturn this.myStartNode.getNodeReference();\n\t}\n\n\n\tpublic void scrollToReference(String reference) {\n\t\tINode node = this.myBook.getNodeByReference(reference);\n\t\tif (node == null) {\n\t\t\tSystem.err.println(\"Bad book reference passed: \" + reference);\n\t\t\treturn;\n\t\t}\n\t\tthis.myStartNode = node;\n\t\t// FIXME: in-node position\n\t\tthis.myStartRenderingObject = 0;\n\t\tflush();\n\t}\n}",
"public class TextPainter implements IBookPainter {\n\t\n\tprivate static final double EMULATED_FONT_SIZE = 12.0;\n\n\tprivate static final double EMULATED_LINE_SKIP = 0.2 * EMULATED_FONT_SIZE;\n\n\t/**\n\t * Output device.\n\t */\n\tprivate final PrintWriter myOutput;\n\t\n\t/**\n\t * Current X coordinate.\n\t */\n\tprivate int myX;\n\n\t/**\n\t * The width of formatted text.\n\t */\n\tprivate double myWidth;\n\n\tprivate double myRealX;\n\tprivate double myIntY;\n\tprivate double myRealY;\n\n\t/**\n\t * This constructs new <code>TextPainter</code> with specified\n\t * <code>PrintWriter</code> as the output device.\n\t * @param output output stream\n\t * @param width the width of text stram\n\t */\n\tpublic TextPainter(PrintWriter output, int width) {\n\t\tthis.myOutput = output;\n\t\tthis.myWidth = width;\n\t}\n\n\tpublic void clear() {\n\t\tthis.myX = 0;\n\t\tthis.myRealX = 0;\n\t\tthis.myIntY = 0;\n\t\tthis.myRealY = 0;\n\t}\n\n\tpublic double getWidth() {\n\t\treturn this.myWidth;\n\t}\n\n\tpublic double getHeight() {\n\t\treturn Double.POSITIVE_INFINITY;\n\t}\n\t\n\tpublic void addHorizontalStrut(double size) {\n//\t\tnew Throwable(this.myRealX + \":\" + this.myX + \":\" + size).printStackTrace(this.myOutput);\n\t\tthis.myRealX += size;\n\t}\n\n\tpublic void addVerticalStrut(double size) {\n//\t\tnew Throwable(this.myRealY + \":\" + size).printStackTrace(this.myOutput);\n\t\tthis.myRealY += size;\n\t\twhile (this.myRealY >= (0.5 * (EMULATED_LINE_SKIP + EMULATED_FONT_SIZE))) {\n\t\t\tthis.myRealY -= EMULATED_FONT_SIZE + EMULATED_LINE_SKIP;\n\t\t\tthis.myIntY ++;\n\t\t\tthis.myOutput.println();\n\t\t\tthis.myX = 0;\n\t\t}\n\t}\n\n\t/**\n\t * This closes the writer.\n\t */\n\tpublic void close() {\n\t\tthis.myOutput.close();\n\t}\n\n\t/**\n\t * The w/a for the all font problems.\n\t */\n\tprivate IFont myFont; \n\tpublic IFont getFont(String name, int size) {\n\t\tif (this.myFont == null) {\n\t\t\tthis.myFont = new IFont() {\n\n\t\t\t\tpublic double getSpaceWidth() {\n\t\t\t\t\treturn 1;\n\t\t\t\t}\n\n\t\t\t\tpublic RenderingDimensions calculateStringDimensions(String s, int start, int end) {\n\t\t\t\t\treturn new RenderingDimensions(EMULATED_FONT_SIZE, 0, end - start);\n\t\t\t\t}\n\n\t\t\t\tpublic void renderString(String s, int start, int end) {\n\t\t\t\t\tTextPainter.this.renderString(s, start, end);\n\t\t\t\t}\n\n\t\t\t\tpublic String getFontFamily() {\n\t\t\t\t\treturn \"default\";\n\t\t\t\t}\n\n\t\t\t\tpublic double getFontSize() {\n\t\t\t\t\treturn EMULATED_FONT_SIZE;\n\t\t\t\t}\n\n\t\t\t};\n\t\t}\n\t\treturn this.myFont;\n\t}\n\n\tvoid renderString(String s, int start, int end) {\n\t\twhile (this.myX < this.myRealX -0.5) {\n\t\t\tthis.myOutput.append(' ');\n\t\t\tthis.myX ++;\n\t\t}\n\t\tthis.myOutput.append(s, start, end);\n\t\tthis.myX += end - start;\n\t\tthis.myRealX += end - start;\n\t}\n\n\tpublic double getXCoordinate() {\n\t\treturn this.myX;\n\t}\n\tpublic double getYCoordinate() {\n\t\treturn this.myRealY + this.myIntY * (EMULATED_FONT_SIZE + EMULATED_LINE_SKIP);\n\t}\n\n\tpublic IInlineRenderingObject getImage(INode node, String contentType, InputStream stream) {\n\t\t// allways null: we can't render images.\n\t\treturn null;\n\t}\n\n}"
] | import org.jbookreader.formatengine.IBookPainter;
import org.jbookreader.formatengine.impl.FormatEngine;
import org.jbookreader.renderingengine.RenderingEngine;
import org.jbookreader.util.TextPainter;
import org.lumag.filetest.FileTestCase;
import org.lumag.filetest.FileTestUtil;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import junit.framework.Test;
import org.jbookreader.FB2FilesTestFilter;
import org.jbookreader.TestConfig;
import org.jbookreader.book.bom.IBook;
import org.jbookreader.book.parser.FB2Parser; | /*
* JBookReader - Java FictionBook Reader
* Copyright (C) 2006 Dmitry Baryshkov
*
* 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 org.jbookreader.renderingengine;
/**
* This class is a test case generator for the {@link org.jbookreader.formatengine.impl.FormatEngine}.
* The engine is tested via formatting with {@link org.jbookreader.util.TextPainter}.
*
* @author Dmitry Baryshkov ([email protected])
*
*/
public class RenderEngineTest {
/**
* This is one {@link FormatEngine} <code>TestCase</code>.
*
* @author Dmitry Baryshkov ([email protected])
*
*/
public static class RenderEngineTestCase extends FileTestCase {
@Override
protected void generateOutput(File inFile, File outFile)
throws Exception {
IBook book = FB2Parser.parse(inFile);
PrintWriter pwr = new PrintWriter(new OutputStreamWriter(new BufferedOutputStream(new FileOutputStream(outFile))));
IBookPainter painter = new TextPainter(pwr, 80);
| RenderingEngine engine = new RenderingEngine(new FormatEngine()); | 5 |
JavaMoney/javamoney-shelter | retired/regions/src/main/java/org/javamoney/regions/internal/data/ISO3RegionTreeProvider.java | [
"public interface Region {\n\n\t/**\n\t * Get the region's type.\n\t * \n\t * @return the region's type, never {@code null}.\n\t */\n\tpublic RegionType getRegionType();\n\n\t/**\n\t * Access the region's code. The code is unique in combination with the\n\t * region type.\n\t * \n\t * @return the region's type, never {@code null}.\n\t */\n\tpublic String getRegionCode();\n\n\t/**\n\t * Get the region's numeric code. If not defined -1 is returned.\n\t * \n\t * @return the numeric region code, or {@code -1}.\n\t */\n\tpublic int getNumericRegionCode();\n\n\t/**\n\t * Return the time zones valid for this region (in the long form, e.g.\n\t * Europe/Berlin). If the region has subregions, by default, the timezones\n\t * returned should be the transitive closure of all timezones of all child\n\t * regions. Nevertheless there might be use cases were the child regions\n\t * must not transitively define the parents timezones, so transitivity is\n\t * not enforced by this JSR.<br/>\n\t * Additionally all ids returned should be known by {@link java.util.TimeZone}.\n\t * \n\t * @return the timezone ids of this region, never {@code null}.\n\t */\n\tpublic Collection<String> getTimezoneIds();\n\n\t/**\n\t * Return according {@link java.util.Locale}, if possible.\n\t * \n\t * @return the corresponding {@link java.util.Locale} for that {@link org.javamoney.regions.Region}, may\n\t * also return {@code null}.\n\t */\n\tpublic Locale getLocale();\n\n}",
"public interface RegionTreeNode {\n\n\t/**\n\t * Get the corresponding region.\n\t * \n\t * @return the region, never {@code null}.\n\t */\n\tpublic Region getRegion();\n\n\t/**\n\t * Get the direct parent region of this region.\n\t * \n\t * @return the parent region, or {@code null}, if this region has no parent\n\t * (is a root region).\n\t */\n\tpublic RegionTreeNode getParent();\n\n\t/**\n\t * Access all direct child regions.\n\t * \n\t * @return all direct child regions, never {@code null}.\n\t */\n\tpublic Collection<RegionTreeNode> getChildren();\n\n\t/**\n\t * Determines if the given region is contained within this region tree.\n\t * \n\t * @param region\n\t * the region being looked up, null hereby is never contained.\n\t * @return {@code true} if the given region is a direct or indirect child of\n\t * this region instance.\n\t */\n\tpublic boolean contains(Region region);\n\n\t/**\n\t * Select the parent region with the given type. This method will navigate\n\t * up the region tree and select the first parent encountered that has the\n\t * given region type.\n\t * \n\t * @param predicate\n\t * the selecting filter, {@code null} will return the direct\n\t * parent, if any.\n\t * @return the region found, or {@code null}.\n\t */\n\tpublic RegionTreeNode selectParent(MonetaryPredicate<Region> predicate);\n\n\t/**\n\t * Select a collection of regions selected by the given filter.\n\t * \n\t * @param predicate\n\t * the region selector, {@code null} will return all regions.\n\t * @return the regions selected.\n\t */\n\tpublic Collection<RegionTreeNode> select(MonetaryPredicate<Region> predicate);\n\n\t/**\n\t * Access a {@link Region} using the region path, which allows access of a\n\t * {@link Region} from the tree, e.g. {@code WORLD/EUROPE/GERMANY} or\n\t * {@code STANDARDS/ISO/GER}.\n\t * \n\t * @param path\n\t * the path to be accessed, not {@code null}.\n\t * @return the {@link Region} found, or {@code null}.\n\t */\n\tpublic RegionTreeNode getRegionTree(String path);\n\n}",
"public final class RegionType implements Serializable, Comparable<RegionType> {\n\n\t/**\n\t * serialVersionUID.\n\t */\n\tprivate static final long serialVersionUID = -921476180849747654L;\n\n\t/** Shared cache of types instantiated with the #of(String) method. */\n\tprivate static final Map<String, RegionType> TYPE_CACHE = new ConcurrentHashMap<String, RegionType>();\n\n\t/** Type representing a continent. */\n\tpublic static final RegionType CONTINENT = of(\"CONTINENT\");\n\n\t/**\n\t * Type representing a region whose code has been deprecated, usually due to\n\t * a country splitting into multiple territories or changing its name.\n\t */\n\tpublic static final RegionType DEPRECATED = of(\"DEPRECATED\");\n\t/**\n\t * Type representing a grouping of territories that is not to be used in the\n\t * normal WORLD/CONTINENT/SUBCONTINENT/TERRITORY containment tree.\n\t */\n\tpublic static final RegionType GROUPING = of(\"GROUPING\");\n\t/** Type representing a sub-continent. */\n\tpublic static final RegionType SUBCONTINENT = of(\"SUBCONTINENT\");\n\t/** Type representing a territory. */\n\tpublic static final RegionType TERRITORY = of(\"TERRITORY\");\n\t/** Type representing the unknown region. */\n\tpublic static final RegionType UNKNOWN = of(\"UNKNOWN\");\n\t/** Type representing the whole world. */\n\tpublic static final RegionType WORLD = of(\"WORLD\");\n\n\t/** The type's id. */\n\tprivate String id;\n\n\t/**\n\t * Constructor for the instance.\n\t * \n\t * @param id\n\t * The type's identifier, not {@code null}\n\t */\n\tpublic RegionType(String id) {\n\t\tif (id == null || id.isEmpty()) {\n\t\t\tthrow new IllegalArgumentException(\"id null or empty.\");\n\t\t}\n\t\tthis.id = id;\n\t}\n\n\t/**\n\t * Access an {@link org.javamoney.regions.RegionType} by id. Instances with the same id will be\n\t * shared.\n\t * \n\t * @param id\n\t * The rate's identifier.\n\t * @return the corresponding type, never {@code null}.\n\t */\n\tpublic static RegionType of(String id) {\n\t\tRegionType type = TYPE_CACHE.get(id);\n\t\tif (type != null) {\n\t\t\treturn type;\n\t\t}\n\t\ttype = new RegionType(id);\n\t\tTYPE_CACHE.put(id, type);\n\t\treturn type;\n\t}\n\n\t/**\n\t * Access all region types.\n\t * \n\t * @return\n\t */\n\tpublic static Collection<RegionType> getTypes() {\n\t\treturn TYPE_CACHE.values();\n\t}\n\n\t/**\n\t * Get the (non localized) identifier of the {@link ExchangeRateType}.\n\t * \n\t * @return The identifier, never null.\n\t */\n\tpublic String getId() {\n\t\treturn id;\n\t}\n\n\t/*\n\t * (non-Javadoc)\n\t * \n\t * @see java.lang.Object#hashCode()\n\t */\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = 1;\n\t\tresult = prime * result + ((id == null) ? 0 : id.hashCode());\n\t\treturn result;\n\t}\n\n\t/*\n\t * (non-Javadoc)\n\t * \n\t * @see java.lang.Object#equals(java.lang.Object)\n\t */\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null)\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tRegionType other = (RegionType) obj;\n\t\tif (id == null) {\n\t\t\tif (other.id != null)\n\t\t\t\treturn false;\n\t\t} else if (!id.equals(other.id))\n\t\t\treturn false;\n\t\treturn true;\n\t}\n\n\t/*\n\t * (non-Javadoc)\n\t * \n\t * @see java.lang.Object#toString()\n\t */\n\t@Override\n\tpublic String toString() {\n\t\treturn \"RegionType [id=\" + id + \"]\";\n\t}\n\n\t/*\n\t * (non-Javadoc)\n\t * \n\t * @see java.lang.Comparable#compareTo(java.lang.Object)\n\t */\n\t@Override\n\tpublic int compareTo(RegionType o) {\n\t\tif (o == null) {\n\t\t\treturn -1;\n\t\t}\n\t\treturn this.id.compareTo(o.id);\n\t}\n\n}",
"public class BuildableRegionNode extends AbstractRegionNode implements\n\t\tRegionTreeNode, Serializable,\n\t\tComparable<RegionTreeNode> {\n\n\t/**\n\t * serialID.\n\t */\n\tprivate static final long serialVersionUID = -8957470024522944264L;\n\n\t/**\n\t * Creates a region. Regions should only be accessed using the accessor\n\t * method {@link Monetary#getExtension(Class)}, passing\n\t * {@link RegionProvider} as type.\n\t * \n\t * @param id\n\t * the region's id, not null.\n\t * @param type\n\t * the region's type, not null.\n\t */\n\tpublic BuildableRegionNode(Region region) {\n\t\tsetRegion(region);\n\t}\n\n\t/**\n\t * Creates a region. Regions should only be accessed using the accessor\n\t * method {@link Monetary#getExtension(Class)}, passing\n\t * {@link RegionProvider} as type.\n\t * \n\t * @param id\n\t * the region's id, not null.\n\t * @param type\n\t * the region's type, not null.\n\t */\n\tpublic BuildableRegionNode(Region region, RegionTreeNode parent) {\n\t\tsetRegion(region);\n\t\tsetParent(parent);\n\t}\n\n\t/**\n\t * Creates a region. Regions should only be accessed using the accessor\n\t * method {@link Monetary#getExtension(Class)}, passing\n\t * {@link RegionProvider} as type.\n\t * \n\t * @param id\n\t * the region's id, not null.\n\t * @param type\n\t * the region's type, not null.\n\t */\n\tpublic BuildableRegionNode(Region region, RegionTreeNode parent,\n\t\t\tCollection<RegionTreeNode> childRegions) {\n\t\tsetRegion(region);\n\t\tsetParent(parent);\n\t\tif (childRegions != null) {\n\t\t\tgetChildNodes().addAll(childRegions);\n\t\t\tfor (RegionTreeNode regionNode : childRegions) {\n\t\t\t\tif (regionNode instanceof BuildableRegionNode) {\n\t\t\t\t\t((BuildableRegionNode) regionNode).setParent(this);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Regions can be used to segregate or access artifacts (e.g. currencies)\n\t * either based on geographical, or commercial aspects (e.g. legal units).\n\t * \n\t * @see <a href=\"http://unstats.un.org/unsd/methods/m49/m49regin.htm\">UN\n\t * M.49: UN Statistics Division Country or area & region codes</a>\n\t * \n\t * @author Anatole Tresch\n\t */\n\tpublic static class Builder {\n\n\t\t/** The region's type. */\n\t\tprivate Region region;\n\n\t\t/**\n\t\t * The parent region, or {@code null}.\n\t\t */\n\t\tprivate RegionTreeNode parent;\n\n\t\tprivate Set<RegionTreeNode> childRegions = new HashSet<RegionTreeNode>();\n\n\t\t/**\n\t\t * Creates a {@link RegionBuilder}. Regions should only be accessed\n\t\t * using the accessor method {@link Monetary#getExtension(Class)},\n\t\t * passing {@link RegionProvider} as type.\n\t\t * \n\t\t * @param regionCode\n\t\t * the region's id, not null.\n\t\t * @param type\n\t\t * the region's type, not null.\n\t\t */\n\t\tpublic Builder() {\n\t\t}\n\n\t\t/**\n\t\t * Creates a {@link RegionBuilder}. Regions should only be accessed\n\t\t * using the accessor method {@link Monetary#getExtension(Class)},\n\t\t * passing {@link RegionProvider} as type.\n\t\t * \n\t\t * @param id\n\t\t * the region's id, not null.\n\t\t * @param type\n\t\t * the region's type, not null.\n\t\t */\n\t\tpublic Builder(Region region) {\n\t\t\tthis.region = region;\n\t\t}\n\n\t\t/**\n\t\t * Access the region.\n\t\t * \n\t\t * @return the region, never null.\n\t\t */\n\t\tpublic Region getRegion() {\n\t\t\treturn this.region;\n\t\t}\n\n\t\t/*\n\t\t * (non-Javadoc)\n\t\t * \n\t\t * @see java.lang.Comparable#compareTo(java.lang.Object)\n\t\t */\n\t\tpublic int compareTo(BuildableRegionNode o) {\n\t\t\tint compare = ((Comparable<Region>) this.region).compareTo(o\n\t\t\t\t\t.getRegion());\n\t\t\treturn compare;\n\t\t}\n\n\t\t/*\n\t\t * (non-Javadoc)\n\t\t * \n\t\t * @see java.lang.Object#hashCode()\n\t\t */\n\t\t@Override\n\t\tpublic int hashCode() {\n\t\t\tfinal int prime = 31;\n\t\t\tint result = 1;\n\t\t\tresult = prime * result\n\t\t\t\t\t+ ((region == null) ? 0 : region.hashCode());\n\t\t\treturn result;\n\t\t}\n\n\t\tpublic Set<RegionTreeNode> getChildRegions() {\n\t\t\treturn childRegions;\n\t\t}\n\n\t\tpublic RegionTreeNode getParentRegion() {\n\t\t\treturn this.parent;\n\t\t}\n\n\t\tpublic Builder setRegion(Region region) {\n\t\t\tif (region == null) {\n\t\t\t\tthrow new IllegalArgumentException(\"Region may not be null.\");\n\t\t\t}\n\t\t\tthis.region = region;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic Builder addChildRegions(RegionTreeNode... regions) {\n\t\t\tthis.childRegions.addAll(Arrays.asList(regions));\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic Builder removeChildRegions(RegionTreeNode... regions) {\n\t\t\tthis.childRegions.removeAll(Arrays.asList(regions));\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic void clearChildren() {\n\t\t\tthis.childRegions.clear();\n\t\t}\n\n\t\tpublic Builder setParentRegion(RegionTreeNode parent) {\n\t\t\tthis.parent = parent;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic boolean isBuildable() {\n\t\t\treturn this.region != null;\n\t\t}\n\n\t\tpublic BuildableRegionNode build() {\n\t\t\treturn new BuildableRegionNode(this.region, this.parent,\n\t\t\t\t\tthis.childRegions);\n\t\t}\n\n\t\t/*\n\t\t * (non-Javadoc)\n\t\t * \n\t\t * @see java.lang.Object#toString()\n\t\t */\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\treturn \"RegionBuilderImpl [region=\" + region + \", parent=\" + parent\n\t\t\t\t\t+ \", childRegions=\" + childRegions\n\t\t\t\t\t+ \"]\";\n\t\t}\n\n\t}\n\n}",
"public interface RegionProviderSpi {\n\n\t/**\n\t * Returns all {@link RegionType}s provided by this\n\t * {@link org.javamoney.regions.spi.RegionProviderSpi} instance, hereby it is possible that several\n\t * providers may provide {@link Region}s for the same {@link RegionType}, as\n\t * long as they are unique related to its code and numderic id (if defined).\n\t * \n\t * @return the {@link RegionType}s for which this provider provides regions,\n\t * never {@code null}.\n\t */\n\tpublic Collection<RegionType> getRegionTypes();\n\n\t/**\n\t * Access all regions provided for the given {@link RegionType}.\n\t * \n\t * @param type\n\t * The required region type.\n\t * @return the regions to be provided, never {@code null}.\n\t */\n\tpublic Collection<Region> getRegions(RegionType type);\n\n\t/**\n\t * Access a {@link Region}.\n\t * \n\t * @param type\n\t * The required region type.\n\t * @param identifier\n\t * The region's id.\n\t * @return The corresponding region, or {@code null}.\n\t * \n\t */\n\tpublic Region getRegion(RegionType type, String identifier);\n\n\t/**\n\t * Access a {@link Region}.\n\t * \n\t * @param numericId\n\t * The region's numeric id.\n\t * @param type\n\t * The required region type.\n\t * @return The corresponding region, or {@code null}.\n\t */\n\tpublic Region getRegion(RegionType type, int numericId);\n\n\t/**\n\t * Access a region using a {@link java.util.Locale}.\n\t * \n\t * @param locale\n\t * The correspoding country {@link java.util.Locale}.\n\t * @return the corresponding region, or {@code null}.\n\t */\n\tpublic Region getRegion(Locale locale);\n\n}",
"public interface RegionTreeProviderSpi {\n\n\t/**\n\t * Get the id of the tree provided by this provider.\n\t * \n\t * @return the id of the tree, provided by this tree provider, never\n\t * {@code null} and not empty.\n\t */\n\tpublic String getTreeId();\n\n\t/**\n\t * Initialize the {@link org.javamoney.regions.spi.RegionTreeProviderSpi} provider.\n\t * \n\t * @param regionProviders\n\t * the region providers loaded, to be used for accessing\n\t * {@link Region} entries to be organized in a\n\t * {@link RegionTreeNode} tree structure.\n\t */\n\tpublic void init(Map<Class,RegionProviderSpi> regionProviders);\n\n\t/**\n\t * Access the root {@link RegionTreeNode} of the region tree provided.\n\t * \n\t * @return the root node, never {@code null}.\n\t */\n\tpublic RegionTreeNode getRegionTree();\n\n}",
"public static class Builder {\n\n\t/** The region's type. */\n\tprivate Region region;\n\n\t/**\n\t * The parent region, or {@code null}.\n\t */\n\tprivate RegionTreeNode parent;\n\n\tprivate Set<RegionTreeNode> childRegions = new HashSet<RegionTreeNode>();\n\n\t/**\n\t * Creates a {@link RegionBuilder}. Regions should only be accessed\n\t * using the accessor method {@link Monetary#getExtension(Class)},\n\t * passing {@link RegionProvider} as type.\n\t * \n\t * @param regionCode\n\t * the region's id, not null.\n\t * @param type\n\t * the region's type, not null.\n\t */\n\tpublic Builder() {\n\t}\n\n\t/**\n\t * Creates a {@link RegionBuilder}. Regions should only be accessed\n\t * using the accessor method {@link Monetary#getExtension(Class)},\n\t * passing {@link RegionProvider} as type.\n\t * \n\t * @param id\n\t * the region's id, not null.\n\t * @param type\n\t * the region's type, not null.\n\t */\n\tpublic Builder(Region region) {\n\t\tthis.region = region;\n\t}\n\n\t/**\n\t * Access the region.\n\t * \n\t * @return the region, never null.\n\t */\n\tpublic Region getRegion() {\n\t\treturn this.region;\n\t}\n\n\t/*\n\t * (non-Javadoc)\n\t * \n\t * @see java.lang.Comparable#compareTo(java.lang.Object)\n\t */\n\tpublic int compareTo(BuildableRegionNode o) {\n\t\tint compare = ((Comparable<Region>) this.region).compareTo(o\n\t\t\t\t.getRegion());\n\t\treturn compare;\n\t}\n\n\t/*\n\t * (non-Javadoc)\n\t * \n\t * @see java.lang.Object#hashCode()\n\t */\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = 1;\n\t\tresult = prime * result\n\t\t\t\t+ ((region == null) ? 0 : region.hashCode());\n\t\treturn result;\n\t}\n\n\tpublic Set<RegionTreeNode> getChildRegions() {\n\t\treturn childRegions;\n\t}\n\n\tpublic RegionTreeNode getParentRegion() {\n\t\treturn this.parent;\n\t}\n\n\tpublic Builder setRegion(Region region) {\n\t\tif (region == null) {\n\t\t\tthrow new IllegalArgumentException(\"Region may not be null.\");\n\t\t}\n\t\tthis.region = region;\n\t\treturn this;\n\t}\n\n\tpublic Builder addChildRegions(RegionTreeNode... regions) {\n\t\tthis.childRegions.addAll(Arrays.asList(regions));\n\t\treturn this;\n\t}\n\n\tpublic Builder removeChildRegions(RegionTreeNode... regions) {\n\t\tthis.childRegions.removeAll(Arrays.asList(regions));\n\t\treturn this;\n\t}\n\n\tpublic void clearChildren() {\n\t\tthis.childRegions.clear();\n\t}\n\n\tpublic Builder setParentRegion(RegionTreeNode parent) {\n\t\tthis.parent = parent;\n\t\treturn this;\n\t}\n\n\tpublic boolean isBuildable() {\n\t\treturn this.region != null;\n\t}\n\n\tpublic BuildableRegionNode build() {\n\t\treturn new BuildableRegionNode(this.region, this.parent,\n\t\t\t\tthis.childRegions);\n\t}\n\n\t/*\n\t * (non-Javadoc)\n\t * \n\t * @see java.lang.Object#toString()\n\t */\n\t@Override\n\tpublic String toString() {\n\t\treturn \"RegionBuilderImpl [region=\" + region + \", parent=\" + parent\n\t\t\t\t+ \", childRegions=\" + childRegions\n\t\t\t\t+ \"]\";\n\t}\n\n}"
] | import java.util.Locale;
import java.util.Map;
import javax.inject.Singleton;
import org.javamoney.regions.Region;
import org.javamoney.regions.RegionTreeNode;
import org.javamoney.regions.RegionType;
import org.javamoney.regions.spi.BuildableRegionNode;
import org.javamoney.regions.spi.RegionProviderSpi;
import org.javamoney.regions.spi.RegionTreeProviderSpi;
import org.javamoney.regions.spi.BuildableRegionNode.Builder; | /*
* CREDIT SUISSE IS WILLING TO LICENSE THIS SPECIFICATION TO YOU ONLY UPON THE
* CONDITION THAT YOU ACCEPT ALL OF THE TERMS CONTAINED IN THIS AGREEMENT.
* PLEASE READ THE TERMS AND CONDITIONS OF THIS AGREEMENT CAREFULLY. BY
* DOWNLOADING THIS SPECIFICATION, YOU ACCEPT THE TERMS AND CONDITIONS OF THE
* AGREEMENT. IF YOU ARE NOT WILLING TO BE BOUND BY IT, SELECT THE "DECLINE"
* BUTTON AT THE BOTTOM OF THIS PAGE. Specification: JSR-354 Money and Currency
* API ("Specification") Copyright (c) 2012-2013, Credit Suisse All rights
* reserved.
*/
package org.javamoney.regions.internal.data;
/**
* Region Tree provider that provides all ISO countries, defined by
* {@link java.util.Locale#getISOCountries()} using their 3-letter ISO country code under
* {@code ISO3}.
*
* @author Anatole Tresch
*/
@Singleton
public class ISO3RegionTreeProvider implements RegionTreeProviderSpi {
private BuildableRegionNode regionTree;
// ISO3/...
@Override
public String getTreeId() {
return "ISO3";
}
@Override
public void init(Map<Class, RegionProviderSpi> providers) {
Builder treeBuilder = new BuildableRegionNode.Builder(new SimpleRegion(
"ISO3"));
ISORegionProvider regionProvider = (ISORegionProvider) providers
.get(ISORegionProvider.class);
for (String country : Locale.getISOCountries()) {
Locale locale = new Locale("", country); | Region region = regionProvider.getRegion(RegionType.of("ISO"), | 0 |
magnusmickelsson/pokeraidbot | src/main/java/pokeraidbot/commands/PokemonVsCommand.java | [
"public class Utils {\n public static final DateTimeFormatter timeParseFormatter = DateTimeFormatter.ofPattern(\"H[:][.]mm\");\n public static final DateTimeFormatter dateAndTimeParseFormatter =\n DateTimeFormatter.ofPattern(\"yyyy-MM-dd HH[:][.]mm\");\n public static final DateTimeFormatter timePrintFormatter = DateTimeFormatter.ofPattern(\"HH:mm\");\n public static final DateTimeFormatter dateAndTimePrintFormatter = DateTimeFormatter.ofPattern(\"yyyy-MM-dd HH:mm\");\n public static final int HIGH_LIMIT_FOR_SIGNUPS = 20;\n public static final int RAID_DURATION_IN_MINUTES = 45;\n public static final int EX_RAID_DURATION_IN_MINUTES = 45;\n private static final String EX_RAID_BOSS = \"deoxys\";\n private static ClockService clockService = new ClockService();\n private static ResistanceTable resistanceTable = new ResistanceTable();\n\n public static ClockService getClockService() {\n return clockService;\n }\n\n public static void setClockService(ClockService clockService) {\n Utils.clockService = clockService;\n }\n\n public static String printDateTime(LocalDateTime dateTime) {\n return dateTime.format(dateAndTimePrintFormatter);\n }\n\n public static String printTime(LocalTime time) {\n return time.format(timePrintFormatter);\n }\n\n public static String printTimeIfSameDay(LocalDateTime dateAndTime) {\n if (dateAndTime.toLocalDate().isEqual(LocalDate.now())) {\n return dateAndTime.toLocalTime().format(timePrintFormatter);\n } else {\n return printDateTime(dateAndTime);\n }\n }\n\n public static boolean isTypeDoubleStrongVsPokemonWithTwoTypes(String pokemonTypeOne,\n String pokemonTypeTwo, String typeToCheck) {\n Validate.notEmpty(pokemonTypeOne);\n Validate.notEmpty(pokemonTypeTwo);\n Validate.notEmpty(typeToCheck);\n if (typeIsStrongVsPokemon(pokemonTypeOne, typeToCheck) && typeIsStrongVsPokemon(pokemonTypeTwo, typeToCheck)) {\n return true;\n } else {\n return false;\n }\n }\n\n public static Set<String> getWeaknessesFor(PokemonTypes pokemonType) {\n return resistanceTable.getWeaknesses(pokemonType);\n }\n\n public static boolean typeIsStrongVsPokemon(String pokemonType, String typeToCheck) {\n return resistanceTable.typeIsStrongVsPokemon(pokemonType, typeToCheck);\n }\n\n public static void assertSignupTimeNotBeforeRaidStartAndNow(User user, LocalDateTime dateAndTime,\n LocalDateTime endOfRaid, LocaleService localeService,\n boolean isExRaid) {\n final LocalDateTime startOfRaid = getStartOfRaid(endOfRaid, isExRaid);\n final LocalDateTime now = clockService.getCurrentDateTime();\n assertSignupTimeNotBeforeRaidStart(user, dateAndTime, endOfRaid, localeService, isExRaid);\n if (dateAndTime.isBefore(now)) {\n throw new UserMessedUpException(user,\n localeService.getMessageFor(LocaleService.SIGN_BEFORE_NOW, localeService.getLocaleForUser(user),\n printTimeIfSameDay(dateAndTime), printTimeIfSameDay(now)));\n }\n }\n\n public static LocalDateTime getStartOfRaid(LocalDateTime endOfRaid, boolean isExRaid) {\n return isExRaid ? endOfRaid.minusMinutes(EX_RAID_DURATION_IN_MINUTES) :\n endOfRaid.minusMinutes(RAID_DURATION_IN_MINUTES);\n }\n\n public static void assertSignupTimeNotBeforeRaidStart(User user, LocalDateTime dateAndTime,\n LocalDateTime endOfRaid, LocaleService localeService,\n boolean isExRaid) {\n final LocalDateTime startOfRaid = getStartOfRaid(endOfRaid, isExRaid);\n if (dateAndTime.isBefore(startOfRaid)) {\n throw new UserMessedUpException(user,\n localeService.getMessageFor(LocaleService.SIGN_BEFORE_RAID, localeService.getLocaleForUser(user),\n printTimeIfSameDay(dateAndTime), printTimeIfSameDay(startOfRaid)));\n }\n }\n\n public static void assertGroupTimeNotBeforeNow(User user, LocalDateTime dateAndTime,\n LocaleService localeService) {\n final LocalDateTime now = clockService.getCurrentDateTime();\n if (dateAndTime.isBefore(now)) {\n throw new UserMessedUpException(user,\n localeService.getMessageFor(LocaleService.NO_GROUP_BEFORE_NOW, localeService.getLocaleForUser(user),\n printTimeIfSameDay(dateAndTime), printTimeIfSameDay(now)));\n }\n }\n\n public static void assertCreateRaidTimeNotBeforeNow(User user, LocalDateTime dateAndTime,\n LocaleService localeService) {\n final LocalDateTime now = clockService.getCurrentDateTime();\n if (dateAndTime.isBefore(now)) {\n throw new UserMessedUpException(user,\n localeService.getMessageFor(LocaleService.TIMEZONE, localeService.getLocaleForUser(user),\n printTimeIfSameDay(dateAndTime), printTimeIfSameDay(now)));\n }\n }\n\n public static void assertTimeNotInNoRaidTimespan(User user, LocalTime time, LocaleService localeService) {\n if (time.isAfter(LocalTime.of(23, 0)) || time.isBefore(LocalTime.of(5, 0))) {\n throw new UserMessedUpException(user,\n localeService.getMessageFor(LocaleService.NO_RAIDS_NOW, localeService.getLocaleForUser(user),\n printTime(time)));\n }\n }\n\n public static void assertTimeNotMoreThanXHoursFromNow(User user, LocalTime time,\n LocaleService localeService, Integer hours) {\n final LocalTime now = clockService.getCurrentTime();\n if (now.isBefore(LocalTime.of(22, 0)) && now.plusHours(2).isBefore(time)) {\n throw new UserMessedUpException(user,\n localeService.getMessageFor(LocaleService.NO_RAID_TOO_LONG, localeService.getLocaleForUser(user),\n printTime(time), printTime(now), String.valueOf(hours)));\n }\n }\n\n public static void assertEtaNotAfterRaidEnd(User user, Raid raid, LocalDateTime eta, LocaleService localeService) {\n if (eta.isAfter(raid.getEndOfRaid())) {\n throw new UserMessedUpException(user,\n localeService.getMessageFor(LocaleService.NO_ETA_AFTER_RAID,\n localeService.getLocaleForUser(user), printTimeIfSameDay(eta),\n printTimeIfSameDay(raid.getEndOfRaid())));\n }\n }\n\n public static String getStaticMapUrl(Gym gym) {\n // todo: host marker png via pokeraidbot web\n String url = \"https://maps.googleapis.com/maps/api/staticmap?center=\" + gym.getX() + \",\" + gym.getY() +\n \"&zoom=14&size=400x400&maptype=roadmap&markers=icon:http://millert.se/pogo/marker_xsmall.png%7C\" +\n gym.getX() + \",\" + gym.getY() + \"&key=AIzaSyAZm7JLojr2KaUvkeHEpHh0Y-zPwP3dpCU\";\n return url;\n }\n\n public static String getNonStaticMapUrl(Gym gym) {\n String url = \"http://www.google.com/maps?q=\" + gym.getX() + \",\" + gym.getY();\n return url;\n }\n\n public static String printWeaknesses(Pokemon pokemon) {\n Set<String> weaknessesToPrint = new LinkedHashSet<>();\n final Set<String> typeSet = pokemon.getTypes().getTypeSet();\n for (String weakness : pokemon.getWeaknesses()) {\n if (typeSet.size() > 1) {\n final Iterator<String> iterator = typeSet.iterator();\n if (isTypeDoubleStrongVsPokemonWithTwoTypes(iterator.next(), iterator.next(), weakness)) {\n weaknessesToPrint.add(\"**\" + weakness + \"**\");\n } else {\n weaknessesToPrint.add(weakness);\n }\n } else {\n weaknessesToPrint.add(weakness);\n }\n }\n\n return StringUtils.join(weaknessesToPrint, \", \");\n }\n\n public static boolean isSamePokemon(String pokemonName, String existingEntityPokemon) {\n return pokemonName.equalsIgnoreCase(existingEntityPokemon);\n }\n\n public static boolean raidsCollide(LocalDateTime endOfRaid, boolean isExRaid, LocalDateTime endOfRaidTwo,\n boolean isExRaidTwo) {\n LocalDateTime startTime = getStartOfRaid(endOfRaid, isExRaid);\n LocalDateTime startTimeTwo = getStartOfRaid(endOfRaidTwo, isExRaidTwo);\n return isInInterval(startTime, endOfRaid, startTimeTwo, endOfRaidTwo) ||\n isInInterval(startTimeTwo, endOfRaidTwo, startTime, endOfRaid);\n }\n\n private static boolean isInInterval(LocalDateTime startTime, LocalDateTime endOfRaid,\n LocalDateTime startTimeTwo, LocalDateTime endOfRaidTwo) {\n return (startTime.isAfter(startTimeTwo) && startTime.isBefore(endOfRaidTwo)) ||\n (endOfRaid.isBefore(endOfRaidTwo) && endOfRaid.isAfter(startTimeTwo));\n }\n\n public static boolean isRaidExPokemon(String pokemonName, PokemonRaidStrategyService strategyService, PokemonRepository pokemonRepository) {\n Pokemon pokemon = pokemonRepository.getByName(pokemonName);\n return strategyService.getRaidInfo(pokemon).getBossTier() == 5;\n }\n\n public static LocalTime parseTime(User user, String timeString, LocaleService localeService) {\n LocalTime endsAtTime;\n try {\n timeString = preProcessTimeString(timeString);\n endsAtTime = LocalTime.parse(timeString, Utils.timeParseFormatter);\n } catch (DateTimeParseException | NullPointerException e) {\n throw new UserMessedUpException(user,\n localeService.getMessageFor(LocaleService.BAD_DATETIME_FORMAT, localeService.getLocaleForUser(user),\n \"HH:MM\", timeString));\n }\n return endsAtTime;\n }\n\n public static Integer assertNotTooManyOrNoNumber(User user, LocaleService localeService, String people) {\n Integer numberOfPeople;\n try {\n numberOfPeople = new Integer(people);\n if (numberOfPeople < 1 || numberOfPeople > HIGH_LIMIT_FOR_SIGNUPS) {\n throw new RuntimeException();\n }\n } catch (RuntimeException e) {\n throw new UserMessedUpException(user,\n localeService.getMessageFor(LocaleService.ERROR_PARSE_PLAYERS,\n localeService.getLocaleForUser(user),\n people, String.valueOf(HIGH_LIMIT_FOR_SIGNUPS)));\n }\n return numberOfPeople;\n }\n\n public static LocalDate parseDate(User user, String dateString, LocaleService localeService) {\n LocalDate theDate;\n try {\n theDate = LocalDate.parse(dateString);\n } catch (DateTimeException | NullPointerException e) {\n throw new UserMessedUpException(user,\n localeService.getMessageFor(LocaleService.BAD_DATETIME_FORMAT,\n localeService.getLocaleForUser(user), \"yyyy-MM-dd\", dateString));\n }\n return theDate;\n }\n\n public static Set<String> getNamesOfThoseWithSignUps(Set<SignUp> signUpsAt, boolean includeEta) {\n final Set<String> signUpNames;\n signUpNames = new LinkedHashSet<>();\n for (SignUp signUp : signUpsAt) {\n if (signUp.getHowManyPeople() > 0) {\n String text = signUp.getUserName() + \" (**\" + signUp.getHowManyPeople();\n if (includeEta) {\n text = text + \", ETA \" + printTime(signUp.getArrivalTime());\n }\n text = text + \"**)\";\n signUpNames.add(text);\n }\n }\n return signUpNames;\n }\n\n public static String getPokemonIcon(Pokemon pokemon) {\n if (!pokemon.isEgg()) {\n return \"https://pokemongohub.net/sprites/normal/\" + pokemon.getNumber() + \".png\";\n } else {\n return \"https://pokeraidbot2.herokuapp.com/img/\" + pokemon.getName().toLowerCase() + \".png\";\n }\n }\n\n public static String[] prepareArguments(CommandEvent commandEvent) {\n return commandEvent.getArgs().replaceAll(\"\\\\s{2,4}\", \" \").split(\" \");\n }\n\n public static boolean isRaidEx(Raid raid, PokemonRaidStrategyService strategyService, PokemonRepository pokemonRepository) {\n return isRaidExPokemon(raid.getPokemon().getName(), strategyService, pokemonRepository);\n }\n\n public static String preProcessTimeString(String timeString) {\n if (timeString != null && timeString.matches(\"[0-9]{3,4}\")) {\n return new StringBuilder(timeString).insert(timeString.length()-2, \":\").toString();\n } else {\n return timeString;\n }\n }\n\n public static void assertGroupStartNotBeforeRaidStart(LocalDateTime raidStart, LocalDateTime groupStart,\n User user, LocaleService localeService) {\n if (raidStart.isAfter(groupStart)) {\n throw new UserMessedUpException(user,\n localeService.getMessageFor(LocaleService.NO_GROUP_BEFORE_RAID,\n localeService.getLocaleForUser(user), printTimeIfSameDay(groupStart),\n printTimeIfSameDay(raidStart)));\n }\n }\n\n public static void assertTimeInRaidTimespan(User user, LocalDateTime dateTimeToCheck, Raid raid,\n LocaleService localeService) {\n final LocalDateTime startOfRaid = getStartOfRaid(raid.getEndOfRaid(), raid.isExRaid());\n final boolean timeIsSameOrBeforeEnd =\n raid.getEndOfRaid().isAfter(dateTimeToCheck) || raid.getEndOfRaid().equals(dateTimeToCheck);\n final boolean timeIsSameOrAfterStart =\n startOfRaid.isBefore(dateTimeToCheck) || startOfRaid.equals(dateTimeToCheck);\n if (!(timeIsSameOrBeforeEnd && timeIsSameOrAfterStart)) {\n throw new UserMessedUpException(user, localeService.getMessageFor(LocaleService.TIME_NOT_IN_RAID_TIMESPAN,\n localeService.getLocaleForUser(user), printDateTime(dateTimeToCheck),\n printDateTime(startOfRaid), printTimeIfSameDay(raid.getEndOfRaid())));\n }\n }\n\n public static Set<String> getResistantTo(PokemonTypes pokemonTypes) {\n return resistanceTable.getResistantTo(pokemonTypes);\n }\n\n public static boolean isExceptionOrCauseNetworkIssues(Throwable t) {\n return t != null && (t.getMessage().contains(\"SocketTimeoutException\") || (isInstanceOfSocketException(t) ||\n (t.getCause() != null && isInstanceOfSocketException(t.getCause()))));\n }\n\n private static boolean isInstanceOfSocketException(Throwable t) {\n return (t instanceof SocketException) || (t instanceof SocketTimeoutException);\n }\n}",
"public class LocaleService {\n private static final Logger LOGGER = LoggerFactory.getLogger(LocaleService.class);\n public static final String NEW_EX_RAID_HELP = \"NEW_EX_RAID_HELP\";\n public static final String RAIDSTATUS = \"RAIDSTATUS\";\n public static final String NO_RAID_AT_GYM = \"NO_RAID_AT_GYM\";\n public static final String REMOVE_SIGNUP_HELP = \"REMOVE_SIGNUP_HELP\";\n public static final String SIGNUP_REMOVED = \"SIGNUP_REMOVED\";\n public static final String NO_SIGNUP_AT_GYM = \"NO_SIGNUP_AT_GYM\";\n public static final String SIGNUP_HELP = \"SIGNUP_HELP\";\n public static final String ERROR_PARSE_PLAYERS = \"ERROR_PARSE_PLAYERS\";\n public static final String CURRENT_SIGNUPS = \"CURRENT_SIGNUPS\";\n public static final String SIGNUPS = \"SIGNUPS\";\n public static final String WHERE_GYM_HELP = \"WHERE_GYM_HELP\";\n public static final String ALREADY_SIGNED_UP = \"ALREADY_SIGNED_UP\";\n public static final String NO_POKEMON = \"NO_POKEMON\";\n public static final String TIMEZONE = \"TIMEZONE\";\n public static final String NO_RAIDS_NOW = \"NO_RAIDS_NOW\";\n public static final String NO_RAID_TOO_LONG = \"NO_RAID_TOO_LONG\";\n public static final String NO_ETA_AFTER_RAID = \"NO_ETA_AFTER_RAID\";\n public static final String GYM_SEARCH = \"GYM_SEARCH\";\n public static final String GYM_SEARCH_OPTIONS = \"GYM_SEARCH_OPTIONS\";\n public static final String GYM_SEARCH_MANY_RESULTS = \"GYM_SEARCH_MANY_RESULTS\";\n public static final String GYM_CONFIG_ERROR = \"GYM_CONFIG_ERROR\";\n public static final String SERVER_HELP = \"SERVER_HELP\";\n public static final String DONATE = \"DONATE\";\n public static final String TRACKING_EXISTS = \"TRACKING_EXISTS\";\n public static final String TRACKED_RAID = \"TRACKED_RAID\";\n public static final String TRACKING_ADDED = \"TRACKING_ADDED\";\n public static final String TRACKING_NOT_EXISTS = \"TRACKING_NOT_EXISTS\";\n public static final String TRACK_HELP = \"TRACK_HELP\";\n public static final String UNTRACK_HELP = \"UNTRACK_HELP\";\n public static final String TRACKING_REMOVED = \"TRACKING_REMOVED\";\n public static final String SIGN_BEFORE_RAID = \"SIGN_BEFORE_RAID\";\n public static final String GYM_NOT_FOUND = \"GYM_NOT_FOUND\";\n public static final String RAID_EXISTS = \"RAID_EXISTS\";\n public static final String USAGE = \"USAGE\";\n public static final String USAGE_HELP = \"USAGE_HELP\";\n public static final String AT_YOUR_SERVICE = \"AT_YOUR_SERVICE\";\n public static final String NEW_RAID_HELP = \"NEW_RAID_HELP\";\n public static final String NEW_RAID_CREATED = \"NEW_RAID_CREATED\";\n public static final String RAID_TOSTRING = \"RAID_TOSTRING\";\n public static final String VS_HELP = \"VS_HELP\";\n public static final String WEAKNESSES = \"WEAKNESSES\";\n public static final String RESISTANT = \"RESISTANT\";\n public static final String BEST_COUNTERS = \"BEST_COUNTERS\";\n public static final String OTHER_COUNTERS = \"OTHER_COUNTERS\";\n public static final String IF_CORRECT_MOVESET = \"IF_CORRECT_MOVESET\";\n public static final String LIST_HELP = \"LIST_HELP\";\n public static final String LIST_NO_RAIDS = \"LIST_NO_RAIDS\";\n public static final String RAID_BETWEEN = \"RAID_BETWEEN\";\n public static final String CURRENT_RAIDS = \"CURRENT_RAIDS\";\n public static final String SIGNED_UP = \"SIGNED_UP\";\n public static final String RAIDSTATUS_HELP = \"RAIDSTATUS_HELP\";\n public static final String GENERIC_USER_ERROR = \"GENERIC_USER_ERROR\";\n\n public static final Locale SWEDISH = new Locale(\"sv\");\n public static final String WHERE_GYM_IN_CHAT_HELP = \"WHERE_GYM_IN_CHAT_HELP\";\n public static final String NEXT_ETA = \"NEXT_ETA\";\n public static final String TRACKING_NONE_FREE = \"TRACKING_NONE_FREE\";\n public static final String LAST_UPDATE = \"LAST_UPDATE\";\n public static final String MOVED_GROUP = \"MOVED_GROUP\";\n public static final String OVERVIEW_HELP = \"OVERVIEW_HELP\";\n public static final String OVERVIEW_ATTACH = \"OVERVIEW_ATTACH\";\n public static final String OVERVIEW_DELETED = \"OVERVIEW_DELETED\";\n public static final String HELP_USER_CONFIG = \"HELP_USER_CONFIG\";\n public static final String USER_CONFIG_BAD_SYNTAX = \"USER_CONFIG_BAD_SYNTAX\";\n public static final String USER_CONFIG_BAD_PARAM = \"USER_CONFIG_BAD_PARAM\";\n public static final String UNSUPPORTED_LOCALE = \"UNSUPPORTED_LOCALE\";\n public static final String LOCALE_SET = \"LOCALE_SET\";\n public static final String MANUAL_CONFIG = \"MANUAL_CONFIG\";\n public static final String GETTING_STARTED_HELP = \"GETTING_STARTED_HELP\";\n public static final String PLUS_SIGNUP_FAIL = \"PLUS_SIGNUP_FAIL\";\n public static final String NO_RAID = \"NO_RAID\";\n public static final String GROUP_CLEANING_UP = \"GROUP_CLEANING_UP\";\n public static final String SIGN_BEFORE_NOW = \"SIGN_BEFORE_NOW\";\n public static final String NOT_EX_RAID = \"NOT_EX_RAID\";\n public static final String NO_GROUP_BEFORE_RAID = \"NO_GROUP_BEFORE_RAID\";\n public static final String NEW_RAID_START_HELP = \"NEW_RAID_START_HELP\";\n public static final String GROUP_NOT_ADDED = \"GROUP_NOT_ADDED\";\n public static final String MANY_GROUPS_FOR_RAID = \"MANY_GROUPS_FOR_RAID\";\n public static final String NO_SUCH_GROUP = \"NO_SUCH_GROUP\";\n public static final String OVERVIEW_EXISTS = \"OVERVIEW_EXISTS\";\n public static final String TIME_NOT_IN_RAID_TIMESPAN = \"TIME_NOT_IN_RAID_TIMESPAN\";\n public static final String TOO_MANY_GROUPS = \"TOO_MANY_GROUPS\";\n public static final String NO_GROUP_BEFORE_NOW = \"NO_GROUP_BEFORE_NOW\";\n public static final String UNSIGN = \"UNSIGN\";\n public static final String OVERVIEW_CLEARED = \"OVERVIEW_CLEARED\";\n public static final String EGG_HATCH_HELP = \"EGG_HATCH_HELP\";\n public static final String EGG_ALREADY_HATCHED = \"EGG_ALREADY_HATCHED\";\n public static final String EGG_WRONG_TIER = \"EGG_WRONG_TIER\";\n public static final String USER_NICK_INVALID = \"USER_NICK_INVALID\";\n public static final String RAID_CREATE_AND_GROUP_HELP = \"RAID_CREATE_AND_GROUP_HELP\";\n public static final String GROUP_DELETED = \"GROUP_DELETED\";\n public static final String CREATED_BY = \"CREATED_BY\";\n public static final String COULD_NOT_ADD_GYM = \"COULD_NOT_ADD_GYM\";\n public static final String HELP = \"HELP\";\n public static final String EX_WITHOUT_RAID = \"EX_WITHOUT_RAID\";\n public static final String ALL_EX = \"ALL_EX\";\n\n // Change this if you want another default locale, affects the usage texts etc\n public static Locale DEFAULT = Locale.ENGLISH;\n public static Locale[] SUPPORTED_LOCALES = {SWEDISH, Locale.ENGLISH};\n public static final String MANUAL_RAID = \"MANUAL_RAID\";\n public static final String MANUAL_SIGNUP = \"MANUAL_SIGNUP\";\n public static final String MANUAL_MAP = \"MANUAL_MAP\";\n public static final String MANUAL_INSTALL = \"MANUAL_INSTALL\";\n public static final String MANUAL_CHANGE = \"MANUAL_CHANGE\";\n public static final String WRONG_NUMBER_OF_ARGUMENTS = \"WRONG_NUMBER_OF_ARGUMENTS\";\n public static final String MANUAL_TRACKING = \"MANUAL_TRACKING\";\n public static final String ACTIVE = \"ACTIVE\";\n public static final String START_GROUP = \"START_GROUP\";\n public static final String FIND_YOUR_WAY = \"FIND_YOUR_WAY\";\n public static final String RAID_BOSS = \"RAID_BOSS\";\n public static final String FOR_HINTS = \"FOR_HINTS\";\n public static final String RAID_GROUP_HELP = \"RAID_GROUP_HELP\";\n public static final String CANT_CREATE_GROUP_LATE = \"CANT_CREATE_GROUP_LATE\";\n public static final String HANDLE_SIGNUP = \"HANDLE_SIGNUP\";\n public static final String REMOVED_GROUP = \"REMOVED_GROUP\";\n public static final String GROUP_HEADLINE = \"GROUP_HEADLINE\";\n public static final String POKEMON = \"POKEMON\";\n public static final String SIGNED_UP_TOTAL = \"SIGNED_UP_TOTAL\";\n public static final String SIGNED_UP_AT = \"SIGNED_UP_AT\";\n public static final String NO_EMOTES = \"NO_EMOTES\";\n public static final String MANUAL_GROUPS = \"MANUAL_GROUPS\";\n public static final String HELP_MANUAL_HELP_TEXT = \"HELP_MANUAL_HELP_TEXT\";\n public static final String EX_DATE_LIMITS = \"EX_DATE_LIMITS\";\n public static final String CHANGE_RAID_HELP = \"CHANGE_RAID_HELP\";\n public static final String EX_NO_CHANGE_POKEMON = \"EX_NO_CHANGE_POKEMON\";\n public static final String EX_CANT_CHANGE_RAID_TYPE = \"EX_CANT_CHANGE_RAID_TYPE\";\n public static final String SIGNUP_BAD_NUMBER = \"SIGNUP_BAD_NUMBER\";\n public static final String EMOTE_INSTALLED_ALREADY = \"EMOTE_INSTALLED_ALREADY\";\n public static final String GETTING_HERE = \"GETTING_HERE\";\n public static final String WHO_ARE_COMING = \"WHO_ARE_COMING\";\n public static final String ONLY_ADMINS_REMOVE_RAID = \"ONLY_ADMINS_REMOVE_RAID\";\n public static final String RAID_NOT_EXISTS = \"RAID_NOT_EXISTS\";\n public static final String BAD_SYNTAX = \"BAD_SYNTAX\";\n public static final String BAD_DATETIME_FORMAT = \"BAD_DATETIME_FORMAT\";\n public static final String RAID_DETAILS = \"RAID_DETAILS\";\n public static final String UPDATED_EVERY_X = \"UPDATED_EVERY_X\";\n public static final String NO_PERMISSION = \"NO_PERMISSION\";\n public static final String GOOGLE_MAPS = \"GOOGLE_MAPS\";\n public static final String KEEP_CHAT_CLEAN = \"KEEP_CHAT_CLEAN\";\n public static final String ERROR_KEEP_CHAT_CLEAN = \"ERROR_KEEP_CHAT_CLEAN\";\n public static final String WHATS_NEW_HELP = \"WHATS_NEW_HELP\";\n public static final String NO_CONFIG = \"NO_CONFIG\";\n private final UserConfigRepository userConfigRepository;\n\n private Map<I18nLookup, String> i18nMessages = new HashMap<>();\n\n public LocaleService(Map<I18nLookup, String> i18nMessages, UserConfigRepository userConfigRepository) {\n this.i18nMessages = i18nMessages;\n this.userConfigRepository = userConfigRepository;\n }\n\n public LocaleService(String locale, UserConfigRepository userConfigRepository) {\n this.userConfigRepository = userConfigRepository;\n LOGGER.info(\"Initialize with server default locale: \" + locale);\n final Locale forLanguageTag = Locale.forLanguageTag(locale);\n if (!new HashSet<>(Arrays.asList(SUPPORTED_LOCALES)).contains(forLanguageTag)) {\n throw new IllegalStateException(\"Given system locale \" + locale + \" is not in list of \" +\n \"supported locales (\" + SUPPORTED_LOCALES + \"). Add it, and associated texts!\");\n }\n DEFAULT = forLanguageTag;\n initTexts();\n LOGGER.info(\"Initialized. Got \" + i18nMessages.keySet().size() + \" texts for \" + SUPPORTED_LOCALES.length + \" locales.\");\n }\n\n private void initTexts() {\n i18nMessages.put(new I18nLookup(ALL_EX, Locale.ENGLISH),\n \"All EX-gyms for the region \");\n i18nMessages.put(new I18nLookup(ALL_EX, SWEDISH),\n \"Alla EX-gym för regionen \");\n\n i18nMessages.put(new I18nLookup(EX_WITHOUT_RAID, Locale.ENGLISH),\n \"Potential EX gyms without a scheduled EX-raid:\");\n i18nMessages.put(new I18nLookup(EX_WITHOUT_RAID, SWEDISH),\n \"Potentiella EX-gym som inte har en kommande EX-raid:\");\n\n i18nMessages.put(new I18nLookup(HELP, Locale.ENGLISH),\n \"Help\");\n i18nMessages.put(new I18nLookup(HELP, SWEDISH),\n \"Hjälp\");\n\n i18nMessages.put(new I18nLookup(COULD_NOT_ADD_GYM, Locale.ENGLISH),\n \"Could not add gym, it already exists for this region.\");\n i18nMessages.put(new I18nLookup(COULD_NOT_ADD_GYM, SWEDISH),\n \"Kunde inte lägga till gym, det finns redan för den här regionen.\");\n\n i18nMessages.put(new I18nLookup(CREATED_BY, Locale.ENGLISH),\n \"Created by\"\n );\n i18nMessages.put(new I18nLookup(CREATED_BY, SWEDISH),\n \"Skapad av\"\n );\n i18nMessages.put(new I18nLookup(GROUP_DELETED, Locale.ENGLISH),\n \"Group deleted, including any signups.\"\n );\n i18nMessages.put(new I18nLookup(GROUP_DELETED, SWEDISH),\n \"Grupp borttagen, inklusive alla eventuella anmälningar.\"\n );\n i18nMessages.put(new I18nLookup(NO_SUCH_GROUP, Locale.ENGLISH),\n \"No such group exists.\" );\n i18nMessages.put(new I18nLookup(NO_SUCH_GROUP, SWEDISH),\n \"Det fanns ingen sådan grupp.\"\n );\n\n i18nMessages.put(new I18nLookup(TOO_MANY_GROUPS, Locale.ENGLISH),\n \"There is already a group created for this raid by this user. In later releases, we may allow \" +\n \"creating many groups per raid per user again.\"\n );\n i18nMessages.put(new I18nLookup(TOO_MANY_GROUPS, SWEDISH),\n \"Det finns redan en grupp för denna raid av denna användare. I framtida releaser, kan vi komma att \" +\n \"tillåta att skapa flera grupper per raid per användare igen.\"\n );\n i18nMessages.put(new I18nLookup(MANY_GROUPS_FOR_RAID, Locale.ENGLISH),\n \"There are several groups this user can change for raid %1 - \" +\n \"Use *!raid change group remove {group starttime} {gym}* to remove the group.\"\n );\n i18nMessages.put(new I18nLookup(MANY_GROUPS_FOR_RAID, SWEDISH),\n \"Det finns flera grupper denna användare kan ändra för raiden %1 - \" +\n \"använd *!raid change group remove {grupptid} {gym}* för att ta bort gruppen.\"\n );\n i18nMessages.put(new I18nLookup(TIME_NOT_IN_RAID_TIMESPAN, Locale.ENGLISH),\n \"There were several possible groups to change, so couldn't perform this change. \" +\n \"Workaround: remove the group's discord messages and create a new group with the correct time.\"\n );\n i18nMessages.put(new I18nLookup(TIME_NOT_IN_RAID_TIMESPAN, SWEDISH),\n \"Det fanns flera möjliga grupper att ändra på, så kan inte göra detta. \" +\n \"Workaround: ta bort gruppens meddelanden och skapa en ny grupp med rätt tid.\"\n );\n i18nMessages.put(new I18nLookup(TIME_NOT_IN_RAID_TIMESPAN, Locale.ENGLISH),\n \"Time %1 is not within the timespan of the raid (%2 - %3)\"\n );\n i18nMessages.put(new I18nLookup(TIME_NOT_IN_RAID_TIMESPAN, SWEDISH),\n \"Tiden %1 är inte inom raidens giltiga tid (%2 - %3)\"\n );\n\n i18nMessages.put(new I18nLookup(OVERVIEW_CLEARED, Locale.ENGLISH),\n \"Server overview message ID cleared.\"\n );\n i18nMessages.put(new I18nLookup(OVERVIEW_CLEARED, SWEDISH),\n \"Serverns översiktmeddelande rensat från konfigurationen.\"\n );\n i18nMessages.put(new I18nLookup(OVERVIEW_EXISTS, Locale.ENGLISH),\n \"Server already has an overview command. Don't run this command again,\" +\n \" except if the overview message stops updating (saved ID can be cleared via *!raid overview reset*).\"\n );\n i18nMessages.put(new I18nLookup(OVERVIEW_EXISTS, SWEDISH),\n \"Servern har redan en översikt. Kör inte detta kommando igen, om inte översikten slutar uppdateras\" +\n \" (sparad ID kan rensas via *!raid overview reset*).\"\n );\n i18nMessages.put(new I18nLookup(GROUP_NOT_ADDED, Locale.ENGLISH),\n \"There is already a raidgroup at this time for %1\"\n );\n i18nMessages.put(new I18nLookup(GROUP_NOT_ADDED, SWEDISH),\n \"Det finns redan en grupp för denna tid för %1\"\n );\n i18nMessages.put(new I18nLookup(EGG_ALREADY_HATCHED, Locale.ENGLISH),\n \"This raid has already been reported as hatched, the pokemon is %1. \" +\n \"If it's wrong, change via *!raid change pokemon {pokemon name} {gym}*.\");\n i18nMessages.put(new I18nLookup(EGG_ALREADY_HATCHED, SWEDISH),\n \"Den här raiden har redan rapporterats som kläckt, bossen är %1. \" +\n \"Om det inte stämmer, ändra via *!raid change pokemon {pokemon name} {gym}* \" +\n \"(admins eller raidskapare).\");\n i18nMessages.put(new I18nLookup(EGG_WRONG_TIER, Locale.ENGLISH),\n \"Attempt to hatch a raid boss of a different tier than the reported egg!\");\n i18nMessages.put(new I18nLookup(EGG_WRONG_TIER, SWEDISH),\n \"Försök att kläcka en raidboss av annan nivå än det rapporterade ägget! Om det är fel typ av ägg, \" +\n \"ändra via *!raid change pokemon Egg{rätt nivå} {gym}* ..\");\n\n i18nMessages.put(new I18nLookup(EGG_HATCH_HELP, Locale.ENGLISH),\n \"Report the hatch of a reported egg - !raid hatch [Name of Pokemon] [Gym name]\");\n i18nMessages.put(new I18nLookup(EGG_HATCH_HELP, SWEDISH),\n \"Rapportera att ett rapporterat ägg kläckts - !raid hatch [Pokemon] [Gym]\");\n i18nMessages.put(new I18nLookup(NEW_RAID_START_HELP, Locale.ENGLISH),\n \"Create new raid starting at time - !raid start [Name of Pokemon] [Start (HH:MM)] [Gym name]\");\n i18nMessages.put(new I18nLookup(NEW_RAID_START_HELP, SWEDISH),\n \"Skapa ny raid som startar vid viss tid - !raid start [Pokemon] [Start klockan (HH:MM)] [Gym]\");\n i18nMessages.put(new I18nLookup(RAID_CREATE_AND_GROUP_HELP, Locale.ENGLISH),\n \"Create new raid and group starting at time - !raid start-group [Name of Pokemon] \" +\n \"[Start (HH:MM)] [Gym name]\");\n i18nMessages.put(new I18nLookup(RAID_CREATE_AND_GROUP_HELP, SWEDISH),\n \"Skapa ny raid och grupp som startar vid viss tid - !raid start-group [Pokemon] \" +\n \"[Start klockan (HH:MM)] [Gym]\");\n i18nMessages.put(new I18nLookup(NO_GROUP_BEFORE_NOW, Locale.ENGLISH),\n \"Can't set a raid group to start at %1, which is before current time %2.\"\n );\n i18nMessages.put(new I18nLookup(NO_GROUP_BEFORE_NOW, SWEDISH),\n \"Kan inte sätta en raidgrupp att börja vid %1, eftersom klockan är %2.\"\n );\n i18nMessages.put(new I18nLookup(NO_GROUP_BEFORE_RAID, Locale.ENGLISH),\n \"Can't set a raid group to start at %1, which is before raid start at %2.\"\n );\n i18nMessages.put(new I18nLookup(NO_GROUP_BEFORE_RAID, SWEDISH),\n \"Kan inte sätta en raidgrupp att börja vid %1, eftersom raiden börjar %2.\"\n );\n i18nMessages.put(new I18nLookup(NOT_EX_RAID, Locale.ENGLISH),\n \"%1 is not an EX raid boss. Use *!raid new* command instead to create a standard raid.\"\n );\n i18nMessages.put(new I18nLookup(NOT_EX_RAID, SWEDISH),\n \"%1 är inte en EX raid boss. Använd *!raid new* istället för att skapa en vanlig raid.\"\n );\n i18nMessages.put(new I18nLookup(GROUP_CLEANING_UP, Locale.ENGLISH),\n \"This group is about to be removed. \" +\n \"Create a new group via *!raid group {time (HH:MM)} {gym name}*\"\n );\n i18nMessages.put(new I18nLookup(GROUP_CLEANING_UP, SWEDISH),\n \"Detta meddelande är på gång att städas undan. \" +\n \"Skapa en ny grupp via *!raid group {tid (HH:MM)} {gym}*\"\n );\n i18nMessages.put(new I18nLookup(GETTING_STARTED_HELP, Locale.ENGLISH),\n \"Getting started guide for the bot\"\n );\n i18nMessages.put(new I18nLookup(GETTING_STARTED_HELP, SWEDISH),\n \"Kom-igång-guide för pokeraidbot\"\n );\n i18nMessages.put(new I18nLookup(LOCALE_SET, Locale.ENGLISH),\n \"Locale set to: %1\"\n );\n i18nMessages.put(new I18nLookup(LOCALE_SET, SWEDISH),\n \"Locale (språk) satt till: %1\"\n );\n i18nMessages.put(new I18nLookup(UNSUPPORTED_LOCALE, Locale.ENGLISH),\n \"You tried to set an unsupported locale: %1. Supported locales are: \" +\n StringUtils.join(LocaleService.SUPPORTED_LOCALES, \", \")\n );\n i18nMessages.put(new I18nLookup(UNSUPPORTED_LOCALE, SWEDISH),\n \"Du försökte sätta en locale som inte stödjs: %1. Tillgängliga locales är: \" +\n StringUtils.join(LocaleService.SUPPORTED_LOCALES, \", \")\n );\n\n i18nMessages.put(new I18nLookup(USER_NICK_INVALID, Locale.ENGLISH),\n \"Invalid nickname, needs to be between 2 and 11 chars.\"\n );\n i18nMessages.put(new I18nLookup(USER_NICK_INVALID, SWEDISH),\n \"Ogiltigt smeknamn, ska vara mellan 2 och 11 tecken.\"\n );\n i18nMessages.put(new I18nLookup(USER_CONFIG_BAD_PARAM, Locale.ENGLISH),\n \"The only parameters that can be changed right now via this command is locale and nick. \" +\n \"You tried to set %1.\"\n );\n i18nMessages.put(new I18nLookup(USER_CONFIG_BAD_PARAM, SWEDISH),\n \"De enda parametrarna som kan ändras just nu via detta kommando är språk (locale) och smeknamn. \" +\n \"Du försökte sätta parametern %1.\"\n );\n i18nMessages.put(new I18nLookup(USER_CONFIG_BAD_SYNTAX, Locale.ENGLISH),\n \"Bad syntax. To see user's configuration: *!raid config show*\\n\" +\n \"To change: *!raid config {param}={value}*\"\n );\n i18nMessages.put(new I18nLookup(USER_CONFIG_BAD_SYNTAX, SWEDISH),\n \"Felaktigt kommando. För att visa användarens konfiguration: *!raid config show*\\n\" +\n \"För att ändra den: *!raid config {param}={value}*\"\n );\n i18nMessages.put(new I18nLookup(HELP_USER_CONFIG, Locale.ENGLISH),\n \"Get or change user configuration - !raid config show to display, \" +\n \"!raid config {param}={value} to change.\"\n );\n i18nMessages.put(new I18nLookup(HELP_USER_CONFIG, SWEDISH),\n \"Användarkonfiguration - !raid config show för att visa, \" +\n \"!raid config {param}={value} för att ändra.\"\n );\n i18nMessages.put(new I18nLookup(MOVED_GROUP, Locale.ENGLISH),\n \"Moved group from %1 to %2 for raid at %3.\\n\" +\n \"**Note: all signups for this time are moved to the new time.** \" +\n \"Users who don't want to be moved have to run \" +\n \"*!raid remove %3* and then add their signup again.\"\n );\n i18nMessages.put(new I18nLookup(MOVED_GROUP, SWEDISH),\n \"Flyttade grupp från %1 till %2 för raid vid %3.\\n\" +\n \"**OBS: Alla gjorda anmälningar för denna tid flyttas med.** \" +\n \"Vill du inte det - ändra din anmälning, t.ex. via *!raid remove %3* och lägg till dig igen.\"\n );\n i18nMessages.put(new I18nLookup(OVERVIEW_DELETED, Locale.ENGLISH),\n \"Overview message has been removed by someone. \" +\n \"Run *!raid overview* again to create a new one.\"\n );\n i18nMessages.put(new I18nLookup(OVERVIEW_DELETED, SWEDISH),\n \"Översiktsmeddelandet har tagits bort av någon. \" +\n \"Kör *!raid overview* igen för att skapa ett nytt.\"\n );\n i18nMessages.put(new I18nLookup(LAST_UPDATE, Locale.ENGLISH),\n \"Last update: %1\"\n );\n i18nMessages.put(new I18nLookup(LAST_UPDATE, SWEDISH),\n \"Senast uppdaterad: %1\"\n );\n i18nMessages.put(new I18nLookup(OVERVIEW_ATTACH, Locale.ENGLISH),\n \"Pokeraidbot v\" + BotServerMain.version + \" is here. Raid overview will be updated in channel \" +\n \"#%1. For bot info, type: *!raid usage*\"\n );\n i18nMessages.put(new I18nLookup(OVERVIEW_ATTACH, SWEDISH),\n \"Pokeraidbot v\" + BotServerMain.version + \" är här. Raidöversikten uppdateras i kanalen \" +\n \"#%1. För info om botten: *!raid usage*\"\n );\n i18nMessages.put(new I18nLookup(OVERVIEW_HELP, Locale.ENGLISH),\n \"Create a message with a !raid list overview that automatically updates: !raid overview\"\n );\n i18nMessages.put(new I18nLookup(OVERVIEW_HELP, SWEDISH),\n \"Skapa ett meddelande med en !raid list översikt som automatiskt uppdateras: !raid overview\"\n );\n\n i18nMessages.put(new I18nLookup(TRACKING_NONE_FREE, Locale.ENGLISH),\n \"There are no free spots for pokemon tracking in your user configuration (3 spots filled). \" +\n \"Please remove one or more via *!raid untrack {pokemon}*\"\n );\n i18nMessages.put(new I18nLookup(TRACKING_NONE_FREE, SWEDISH),\n \"Alla dina 3 trackingpokemon är upptagna. Ta bort en eller fler via *!raid untrack*\"\n );\n\n i18nMessages.put(new I18nLookup(NEXT_ETA, Locale.ENGLISH),\n \"next ETA: %1\"\n );\n i18nMessages.put(new I18nLookup(NEXT_ETA, SWEDISH),\n \"närmaste ETA: %1\"\n );\n\n i18nMessages.put(new I18nLookup(NO_CONFIG, Locale.ENGLISH),\n \"There is no configuration setup for this server. Make sure an administrator runs the command\" +\n \" \\\"!raid install\\\".\"\n );\n i18nMessages.put(new I18nLookup(NO_CONFIG, SWEDISH),\n \"Det finns ingen konfiguration installerad för denna server. \" +\n \"Se till att en administratör kör kommandot \\\"!raid install\\\".\"\n );\n\n i18nMessages.put(new I18nLookup(WHATS_NEW_HELP, Locale.ENGLISH),\n \"Gives the version of the bot and what's new in this version.\"\n );\n i18nMessages.put(new I18nLookup(WHATS_NEW_HELP, SWEDISH),\n \"Ange vilken version av botten som körs, och vad som är nytt i denna version.\"\n );\n i18nMessages.put(new I18nLookup(ERROR_KEEP_CHAT_CLEAN, Locale.ENGLISH),\n \"This message, and the associated error, will be removed in %1 seconds to keep chat clean.\"\n );\n i18nMessages.put(new I18nLookup(ERROR_KEEP_CHAT_CLEAN, SWEDISH),\n \"Detta meddelande och tillhörande fel kommer tas bort om %1 sekunder \" +\n \"för att hålla chatten ren.\"\n );\n i18nMessages.put(new I18nLookup(KEEP_CHAT_CLEAN, Locale.ENGLISH),\n \"This message will be removed in %1 seconds to keep chat clean.\"\n );\n i18nMessages.put(new I18nLookup(KEEP_CHAT_CLEAN, SWEDISH),\n \"Detta meddelande kommer tas bort om %1 sekunder \" +\n \"för att hålla chatten ren.\"\n );\n i18nMessages.put(new I18nLookup(GOOGLE_MAPS, Locale.ENGLISH),\n \" click the message title for a Google Maps link.\"\n );\n i18nMessages.put(new I18nLookup(GOOGLE_MAPS, SWEDISH),\n \" klicka på meddelandetitel för Google Maps.\"\n );\n i18nMessages.put(new I18nLookup(NO_PERMISSION, Locale.ENGLISH),\n \"You lack the permissions to do what you're trying to do. Ask an admin for help.\"\n );\n i18nMessages.put(new I18nLookup(NO_PERMISSION, SWEDISH),\n \"Du saknar behörighet för att göra det du försökte göra. Be hjälp av en admin.\"\n );\n i18nMessages.put(new I18nLookup(UPDATED_EVERY_X, Locale.ENGLISH),\n \"Updated every %2 %1.\"\n );\n i18nMessages.put(new I18nLookup(UPDATED_EVERY_X, SWEDISH),\n \"Uppdateras var %2:e %1.\"\n );\n\n i18nMessages.put(new I18nLookup(RAID_DETAILS, Locale.ENGLISH),\n \"To see details for a raid: !raid status {gym name}\"\n );\n i18nMessages.put(new I18nLookup(RAID_DETAILS, SWEDISH),\n \"För att se detaljer för en raid: !raid status {gym-namn}\"\n );\n\n i18nMessages.put(new I18nLookup(BAD_DATETIME_FORMAT, Locale.ENGLISH),\n \"Could not parse your given time, should be format %1 but was: %2\"\n );\n i18nMessages.put(new I18nLookup(BAD_DATETIME_FORMAT, SWEDISH),\n \"Kunde inte tolka tiden du angav, ska vara format %1 men var: %2\"\n );\n\n i18nMessages.put(new I18nLookup(BAD_SYNTAX, Locale.ENGLISH),\n \"Bad syntax for command. Refer to *!raid man*. Correct command: %1\"\n );\n i18nMessages.put(new I18nLookup(BAD_SYNTAX, SWEDISH),\n \"Dålig syntax för kommandot. Se *!raid man* vid behov. Korrekt kommando ser ut som: %1\"\n );\n\n i18nMessages.put(new I18nLookup(RAID_NOT_EXISTS, Locale.ENGLISH),\n \"Could not delete raid since you tried to delete one that doesn't exist.\"\n );\n i18nMessages.put(new I18nLookup(RAID_NOT_EXISTS, SWEDISH),\n \"Kunde inte ta bort raid, eftersom den fanns inte.\" );\n\n i18nMessages.put(new I18nLookup(ONLY_ADMINS_REMOVE_RAID, Locale.ENGLISH),\n \"Only admins can remove raids with signups, sorry.\"\n );\n i18nMessages.put(new I18nLookup(ONLY_ADMINS_REMOVE_RAID, SWEDISH),\n \"Bara administratörer kan ta bort raids med gjorda anmälningar, tyvärr.\"\n );\n i18nMessages.put(new I18nLookup(WHO_ARE_COMING, Locale.ENGLISH),\n \"Who are coming\"\n );\n i18nMessages.put(new I18nLookup(WHO_ARE_COMING, SWEDISH),\n \"Vilka kommer\"\n );\n\n i18nMessages.put(new I18nLookup(GETTING_HERE, Locale.ENGLISH),\n \"Getting here:\"\n );\n i18nMessages.put(new I18nLookup(GETTING_HERE, SWEDISH),\n \"Hitta hit:\"\n );\n i18nMessages.put(new I18nLookup(EMOTE_INSTALLED_ALREADY, Locale.ENGLISH),\n \"You already have an icon with the name \\\"%1\\\".\"\n );\n i18nMessages.put(new I18nLookup(EMOTE_INSTALLED_ALREADY, SWEDISH),\n \"Du har redan installerat emote för: \\\"%1\\\".\"\n );\n i18nMessages.put(new I18nLookup(SIGNUP_BAD_NUMBER, Locale.ENGLISH),\n \"Number of people for a signup must be 1-20, you had %1 but tried to set %2.\"\n );\n i18nMessages.put(new I18nLookup(SIGNUP_BAD_NUMBER, SWEDISH),\n \"Antal personer för en signup måste vara 1-20, du hade %1 men försökte sätta %2.\"\n );\n i18nMessages.put(new I18nLookup(EX_CANT_CHANGE_RAID_TYPE, Locale.ENGLISH),\n \"Can't change a standard raid to be an EX raid. \" +\n \"Remove the standard raid and then create an EX raid instead. Refer to !raid man change\"\n );\n i18nMessages.put(new I18nLookup(EX_CANT_CHANGE_RAID_TYPE, SWEDISH),\n \"Kan inte ändra en vanlig raid till att bli en EX raid. \" +\n \"Ta bort den vanliga raiden och skapa en ny EX raid. Använd !raid man change\"\n );\n i18nMessages.put(new I18nLookup(EX_NO_CHANGE_POKEMON, Locale.ENGLISH),\n \"Can't change pokemon for an EX raid. If you want to change an EX raid, remove it and create a new \" +\n \"raid via: !raid change remove {gym}\"\n );\n i18nMessages.put(new I18nLookup(EX_NO_CHANGE_POKEMON, SWEDISH),\n \"Kan inte ändra pokemon för en EX raid. \" +\n \"Om du vill ändra EX raiden, ta bort den och skapa en ny. Använd !raid man change\"\n );\n i18nMessages.put(new I18nLookup(CHANGE_RAID_HELP, Locale.ENGLISH),\n \" Change something that went wrong during raid creation. Type \\\"!raid man change\\\" for details.\"\n );\n i18nMessages.put(new I18nLookup(CHANGE_RAID_HELP, SWEDISH),\n \" Ändra något som blev fel vid skapandet av en raid. Skriv \\\"!raid man change\\\" för detaljer.\"\n );\n\n i18nMessages.put(new I18nLookup(EX_DATE_LIMITS, Locale.ENGLISH),\n \"You can't create an EX raid more than 10 days ahead.\"\n );\n i18nMessages.put(new I18nLookup(EX_DATE_LIMITS, SWEDISH),\n \"Du kan inte skapa en EX raid mer än 10 dagar framåt tyvärr.\"\n );\n\n i18nMessages.put(new I18nLookup(NO_EMOTES, Locale.ENGLISH),\n \"Administrator has not installed pokeraidbot's emotes. \" +\n \"Ensure he/she runs the following command: !raid install-emotes\"\n );\n i18nMessages.put(new I18nLookup(NO_EMOTES, SWEDISH),\n \"Administratören för denna server har inte installerat pokeraidbot's emotes. \" +\n \"Se till att hen kör följande kommando: !raid install-emotes\"\n );\n\n i18nMessages.put(new I18nLookup(SIGNED_UP_AT, Locale.ENGLISH),\n \"Signed up\"\n );\n i18nMessages.put(new I18nLookup(SIGNED_UP_AT, SWEDISH),\n \"Anmälda\"\n );\n\n i18nMessages.put(new I18nLookup(SIGNED_UP_TOTAL, Locale.ENGLISH),\n \"Signed up for raid\"\n );\n i18nMessages.put(new I18nLookup(SIGNED_UP_TOTAL, SWEDISH),\n \"Anmälda totalt till raiden\"\n );\n\n i18nMessages.put(new I18nLookup(POKEMON, Locale.ENGLISH),\n \"Pokemon:\"\n );\n i18nMessages.put(new I18nLookup(POKEMON, SWEDISH),\n \"Pokemon:\"\n );\n\n i18nMessages.put(new I18nLookup(GROUP_HEADLINE, Locale.ENGLISH),\n \"%1 @ %2\" //, starts at %3\"\n );\n i18nMessages.put(new I18nLookup(GROUP_HEADLINE, SWEDISH),\n \"%1 @ %2\" //, startar %3\"\n );\n\n i18nMessages.put(new I18nLookup(HANDLE_SIGNUP, Locale.ENGLISH),\n \"To sign up, press emotes below for number of people to sign up.\");\n i18nMessages.put(new I18nLookup(HANDLE_SIGNUP, SWEDISH),\n \"För anmälan, tryck emotes nedan motsvarande antal som kommer.\");\n\n i18nMessages.put(new I18nLookup(CANT_CREATE_GROUP_LATE, Locale.ENGLISH),\n \"Can't create a group to raid after raid has ended. :(\"\n );\n i18nMessages.put(new I18nLookup(CANT_CREATE_GROUP_LATE, SWEDISH),\n \"Kan inte skapa en grupp som ska samlas efter att raiden slutat.\"\n );\n\n i18nMessages.put(new I18nLookup(RAID_GROUP_HELP, Locale.ENGLISH),\n \"Create a group which will start the raid together at a given time: \" +\n \"!raid group [start time (HH:MM)] [gym name]\");\n i18nMessages.put(new I18nLookup(RAID_GROUP_HELP, SWEDISH),\n \"Skapa ett tillfälle för en grupp att köra vid en skapad raid: \" +\n \"!raid group [start time (HH:MM)] [gym name]\");\n\n i18nMessages.put(new I18nLookup(FOR_HINTS, Locale.ENGLISH), \"For hints - type:\");\n i18nMessages.put(new I18nLookup(FOR_HINTS, SWEDISH), \"För tips - skriv:\");\n\n i18nMessages.put(new I18nLookup(RAID_BOSS, Locale.ENGLISH), \"Raidboss:\");\n i18nMessages.put(new I18nLookup(RAID_BOSS, SWEDISH), \"Raidboss:\");\n\n i18nMessages.put(new I18nLookup(FIND_YOUR_WAY, Locale.ENGLISH), \"Find your way here:\");\n i18nMessages.put(new I18nLookup(FIND_YOUR_WAY, SWEDISH), \"Hitta dit:\");\n\n i18nMessages.put(new I18nLookup(START_GROUP, Locale.ENGLISH), \"Start group - write (change the time)\");\n i18nMessages.put(new I18nLookup(START_GROUP, SWEDISH), \"Starta grupp - skriv (med egen tid)\");\n\n i18nMessages.put(new I18nLookup(ACTIVE, Locale.ENGLISH), \"Active\");\n i18nMessages.put(new I18nLookup(ACTIVE, SWEDISH), \"Aktiv\");\n\n i18nMessages.put(new I18nLookup(WRONG_NUMBER_OF_ARGUMENTS, Locale.ENGLISH),\n \"Wrong number of arguments for command, expected %1 but was %2. Write \\\"!raid man\\\" for help.\");\n i18nMessages.put(new I18nLookup(WRONG_NUMBER_OF_ARGUMENTS, SWEDISH),\n \"Fel antal argument, förväntade %1, men det var %2. \" +\n \"Skriv \\\"!raid man\\\" för att få hjälp\");\n\n i18nMessages.put(new I18nLookup(UNTRACK_HELP, Locale.ENGLISH),\n \"Remove an active Pokemon tracking - !raid untrack [Pokemon]\");\n i18nMessages.put(new I18nLookup(UNTRACK_HELP, SWEDISH),\n \"Ta bort övervakning för viss Pokemon - !raid untrack [Pokemon]\");\n\n i18nMessages.put(new I18nLookup(TRACK_HELP, Locale.ENGLISH),\n \"Track new raids for a certain Pokemon (message in DM) - !raid track [Pokemon]\");\n i18nMessages.put(new I18nLookup(TRACK_HELP, SWEDISH),\n \"Håll koll efter nya raider för en viss Pokemon (via DM) - !raid track [Pokemon]\");\n\n i18nMessages.put(new I18nLookup(TRACKING_ADDED, Locale.ENGLISH),\n \"Added tracking for pokemon %1 for user %2.\");\n i18nMessages.put(new I18nLookup(TRACKING_ADDED, SWEDISH),\n \"Lade till övervakning av pokemon %1 för %2.\");\n\n i18nMessages.put(new I18nLookup(TRACKING_REMOVED, Locale.ENGLISH),\n \"Removed tracking for %1 for user %2.\");\n i18nMessages.put(new I18nLookup(TRACKING_REMOVED, SWEDISH),\n \"Tog bort övervakning av %1 för %2.\");\n\n i18nMessages.put(new I18nLookup(TRACKED_RAID, Locale.ENGLISH),\n \"%3 by %2- raid track notification for server %1\");\n i18nMessages.put(new I18nLookup(TRACKED_RAID, SWEDISH),\n \"%3 av %2 - notifikation från %1\");\n\n i18nMessages.put(new I18nLookup(TRACKING_NOT_EXISTS, Locale.ENGLISH),\n \"There was no such tracking set for you.\");\n i18nMessages.put(new I18nLookup(TRACKING_NOT_EXISTS, SWEDISH),\n \"Det fanns ingen sådan övervakning för dig.\");\n\n i18nMessages.put(new I18nLookup(TRACKING_EXISTS, Locale.ENGLISH),\n \"You're already tracking that pokemon.\");\n i18nMessages.put(new I18nLookup(TRACKING_EXISTS, SWEDISH),\n \"Du har redan övervakning satt för det.\");\n\n i18nMessages.put(new I18nLookup(DONATE, Locale.ENGLISH),\n \"How to support development and maintenance of this bot via donating.\");\n i18nMessages.put(new I18nLookup(DONATE, SWEDISH),\n \"Hur kan man stödja utveckling och drift av botten?\");\n\n i18nMessages.put(new I18nLookup(GYM_CONFIG_ERROR, Locale.ENGLISH),\n \"There are no gyms for this region. \" +\n \"Please check configuration and/or notify administrator! You have imported the gymdata, right?\");\n i18nMessages.put(new I18nLookup(GYM_CONFIG_ERROR, SWEDISH),\n \"Det finns inga gym för din valda region. Meddela en administratör så de kan kontrollera \" +\n \"konfigurationen av servern. Ni har väl sett till att importera gymdata?\");\n i18nMessages.put(new I18nLookup(GYM_SEARCH_MANY_RESULTS, Locale.ENGLISH),\n \"Could not find one unique gym/pokestop, your query returned 5+ results. Try refine your search.\");\n i18nMessages.put(new I18nLookup(GYM_SEARCH_MANY_RESULTS, SWEDISH),\n \"Kunde inte hitta ett unikt gym/pokestop, din sökning returnerade mer än 5 resultat. \" +\n \"Försök vara mer precis.\");\n\n i18nMessages.put(new I18nLookup(GYM_SEARCH_OPTIONS, Locale.ENGLISH),\n \"Could not find one unique gym/pokestop. Did you want any of these? %1\");\n i18nMessages.put(new I18nLookup(GYM_SEARCH_OPTIONS, SWEDISH),\n \"Kunde inte hitta ett unikt gym/pokestop. Var det något av dessa du sökte efter? %1\");\n\n i18nMessages.put(new I18nLookup(GYM_SEARCH, Locale.ENGLISH),\n \"Empty input for gym name, try giving me a proper name to search for.\");\n i18nMessages.put(new I18nLookup(GYM_SEARCH, SWEDISH),\n \"Tom söksträng för gymnamn, ge mig något skoj att söka efter!\");\n\n i18nMessages.put(new I18nLookup(SIGN_BEFORE_NOW, Locale.ENGLISH),\n \"Can't sign up for this raid before current time. Your given time is %1, time is currently %2\");\n i18nMessages.put(new I18nLookup(SIGN_BEFORE_NOW, SWEDISH),\n \"Du kan inte anmäla dig att anlända innan nuvarande tid. Din ETA är %1, men klockan är %2.\");\n\n i18nMessages.put(new I18nLookup(SIGN_BEFORE_RAID, Locale.ENGLISH),\n \"Can't sign up for this raid before raid start. Your given time is %1, raid start is %2\");\n i18nMessages.put(new I18nLookup(SIGN_BEFORE_RAID, SWEDISH),\n \"Du kan inte anmäla dig att anlända innan raiden börjar. Din ETA är %1, men raiden börjar %2.\");\n\n i18nMessages.put(new I18nLookup(NO_ETA_AFTER_RAID, Locale.ENGLISH),\n \"Can't arrive after raid has ended. Your given time is %1, raid ends at %2\");\n i18nMessages.put(new I18nLookup(NO_ETA_AFTER_RAID, SWEDISH),\n \"Det är väl inte så lämpligt att anlända efter att raiden slutat? Din ETA är %1, raiden slutar %2.\");\n\n i18nMessages.put(new I18nLookup(NO_RAID_TOO_LONG, Locale.ENGLISH),\n \"You can't set an end of raid time which is later than %3 hours from the current time \" +\n \"%2 except for EX raids - your input would have yielded end time %1.\");\n i18nMessages.put(new I18nLookup(NO_RAID_TOO_LONG, SWEDISH),\n \"Du kan inte sätta en sluttid för raid senare än %3 timmar från vad klockan är nu (%2), \" +\n \"förutom för EX raider. Rapporterad sluttid skulle blivit %1.\");\n\n i18nMessages.put(new I18nLookup(NO_RAIDS_NOW, Locale.ENGLISH),\n \"You can't create raids between 22:00 and 06:00 - your time was %1.\");\n i18nMessages.put(new I18nLookup(NO_RAIDS_NOW, SWEDISH),\n \"Du kan inte skapa en raid som slutar mellan 22.00 och 06:00. Du angav %1.\");\n\n i18nMessages.put(new I18nLookup(TIMEZONE, Locale.ENGLISH),\n \"You seem to be living in a different timezone. Your input was %1, while it's currently %2.\");\n i18nMessages.put(new I18nLookup(TIMEZONE, SWEDISH),\n \"Fel tidszon? \" +\n \"Du angav %1, och klockan är just nu %2.\");\n\n i18nMessages.put(new I18nLookup(NO_POKEMON, Locale.ENGLISH), \"Could not find a pokemon with name \\\"%1\\\".\");\n i18nMessages.put(new I18nLookup(NO_POKEMON, SWEDISH), \"Kunde inte hitta pokemon med namn \\\"%1\\\".\");\n\n i18nMessages.put(new I18nLookup(ALREADY_SIGNED_UP, Locale.ENGLISH), \"You're already signed up for: %1 ... \" +\n \"%2 - remove your current signup then signup again.\");\n i18nMessages.put(new I18nLookup(ALREADY_SIGNED_UP, SWEDISH), \"Du har redan anmält dig till raid vid %1 ... \" +\n \"%2 - ta bort din anmälan och gör om som du vill ha det.\");\n\n i18nMessages.put(new I18nLookup(WHERE_GYM_IN_CHAT_HELP, Locale.ENGLISH), \"Get map link for gym in chat - !raid mapinchat [Gym name]\");\n i18nMessages.put(new I18nLookup(WHERE_GYM_IN_CHAT_HELP, SWEDISH), \"Visa karta för gym i chatten - !raid mapinchat [Gym]\");\n\n i18nMessages.put(new I18nLookup(WHERE_GYM_HELP, Locale.ENGLISH), \"Get map link for gym - !raid map [Gym name]\");\n i18nMessages.put(new I18nLookup(WHERE_GYM_HELP, SWEDISH), \"Visa karta för gym - !raid map [Gym]\");\n\n i18nMessages.put(new I18nLookup(SIGNUPS, Locale.ENGLISH), \"%1 sign up added to %2. %3\");\n i18nMessages.put(new I18nLookup(SIGNUPS, SWEDISH), \"Anmälan från %1 registrerad till %2. %3\");\n\n i18nMessages.put(new I18nLookup(UNSIGN, Locale.ENGLISH), \"%1 unsign from %2. %3\");\n i18nMessages.put(new I18nLookup(UNSIGN, SWEDISH), \"%1 avanmälde från %2. %3\");\n\n i18nMessages.put(new I18nLookup(CURRENT_SIGNUPS, Locale.ENGLISH), \"Current signups: \");\n i18nMessages.put(new I18nLookup(CURRENT_SIGNUPS, SWEDISH), \"Vilka kommer: \");\n\n i18nMessages.put(new I18nLookup(ERROR_PARSE_PLAYERS, Locale.ENGLISH),\n \"Can't parse this number of people: %1 - give a valid number 1-%2.\");\n i18nMessages.put(new I18nLookup(ERROR_PARSE_PLAYERS, SWEDISH),\n \"Felaktigt antal personer: %1 - ange ett korrekt antal 1-%2.\");\n\n i18nMessages.put(new I18nLookup(SERVER_HELP, Locale.ENGLISH),\n \"Info about your server's configuration: !raid server\");\n i18nMessages.put(new I18nLookup(SERVER_HELP, SWEDISH),\n \"Information om serverns konfiguration: !raid server\");\n\n i18nMessages.put(new I18nLookup(SIGNUP_HELP, Locale.ENGLISH),\n \"Sign up for a raid: !raid add [number of people] [ETA (HH:MM)] [Gym]\");\n i18nMessages.put(new I18nLookup(SIGNUP_HELP, SWEDISH),\n \"Anmäl dig till en raid: !raid add [antal spelare] [ETA (HH:MM)] [Gym]\");\n\n i18nMessages.put(new I18nLookup(NO_SIGNUP_AT_GYM, Locale.ENGLISH), \"%1 had no signup to remove for gym %2\");\n i18nMessages.put(new I18nLookup(NO_SIGNUP_AT_GYM, SWEDISH), \"%1 hade ingen anmälan att ta bort för raid vid %2\");\n\n i18nMessages.put(new I18nLookup(SIGNUP_REMOVED, Locale.ENGLISH), \"Signup removed for gym %1: %2\");\n i18nMessages.put(new I18nLookup(SIGNUP_REMOVED, SWEDISH), \"Tog bort din anmälan för gym %1: %2\");\n\n i18nMessages.put(new I18nLookup(REMOVE_SIGNUP_HELP, Locale.ENGLISH),\n \"Remove your signup for this gym: !raid remove [Gym]\");\n i18nMessages.put(new I18nLookup(REMOVE_SIGNUP_HELP, SWEDISH),\n \"Ta bort din anmälan för raid på ett gym: !raid remove [Gym]\");\n\n i18nMessages.put(new I18nLookup(NO_RAID_AT_GYM, Locale.ENGLISH),\n \"Could not find a raid for this gym: \\\"%1\\\".\");\n i18nMessages.put(new I18nLookup(NO_RAID_AT_GYM, SWEDISH),\n \"Kunde inte hitta någon aktuell raid för \\\"%1\\\".\");\n\n i18nMessages.put(new I18nLookup(NO_RAID, Locale.ENGLISH),\n \"Could not find the target raid.\");\n i18nMessages.put(new I18nLookup(NO_RAID, SWEDISH),\n \"Kunde inte hitta den aktuella raiden.\");\n\n i18nMessages.put(new I18nLookup(RAIDSTATUS, Locale.ENGLISH), \"%1:\");\n i18nMessages.put(new I18nLookup(RAIDSTATUS, SWEDISH), \"%1:\");\n\n i18nMessages.put(new I18nLookup(RAIDSTATUS_HELP, Locale.ENGLISH),\n \"Check status for raid - !raid status [Gym name].\");\n i18nMessages.put(new I18nLookup(RAIDSTATUS_HELP, SWEDISH),\n \"Se status för raid - !raid status [Gym].\");\n\n i18nMessages.put(new I18nLookup(SIGNED_UP, Locale.ENGLISH), \"Signed up\");\n i18nMessages.put(new I18nLookup(SIGNED_UP, SWEDISH), \"Anmäld(a)\");\n\n i18nMessages.put(new I18nLookup(CURRENT_RAIDS, Locale.ENGLISH), \"Current raids\");\n i18nMessages.put(new I18nLookup(CURRENT_RAIDS, SWEDISH), \"Aktuella raids\");\n\n i18nMessages.put(new I18nLookup(RAID_BETWEEN, Locale.ENGLISH), \"%1-%2\");\n i18nMessages.put(new I18nLookup(RAID_BETWEEN, SWEDISH), \"%1-%2\");\n\n i18nMessages.put(new I18nLookup(LIST_NO_RAIDS, Locale.ENGLISH), \"There are currently no active raids. \" +\n \"To register a raid, use the following command:\\n!raid new {pokemon} {ends at (HH:mm)} {gym}\\n\" +\n \"Example: !raid new Entei 09:45 Solna Platform\");\n i18nMessages.put(new I18nLookup(LIST_NO_RAIDS, SWEDISH),\n \"Det finns just nu inga registrerade raids. \" +\n \"För att registrera en raid, skriv:\\n\" +\n \"!raid new {pokemon} {sluttid (HH:mm)} {gym}\\n\" +\n \"Exempel: !raid new Entei 09:45 Solna Platform\");\n\n i18nMessages.put(new I18nLookup(LIST_HELP, Locale.ENGLISH),\n \"Check current raids - !raid list [optional: Pokemon]\");\n i18nMessages.put(new I18nLookup(LIST_HELP, SWEDISH), \"Visa aktuella raids - \" +\n \"!raid list [Pokemon (frivilligt att ange)]\");\n\n\n i18nMessages.put(new I18nLookup(IF_CORRECT_MOVESET, Locale.ENGLISH), \"(if correct moveset)\");\n i18nMessages.put(new I18nLookup(IF_CORRECT_MOVESET, SWEDISH), \"(om bra \\\"moves\\\")\");\n\n i18nMessages.put(new I18nLookup(OTHER_COUNTERS, Locale.ENGLISH), \"Other counters: \");\n i18nMessages.put(new I18nLookup(OTHER_COUNTERS, SWEDISH), \"Andra bra val: \");\n\n i18nMessages.put(new I18nLookup(BEST_COUNTERS, Locale.ENGLISH), \"Best counter: \");\n i18nMessages.put(new I18nLookup(BEST_COUNTERS, SWEDISH), \"Bästa valet: \");\n\n i18nMessages.put(new I18nLookup(RESISTANT, Locale.ENGLISH), \"Avoid using: \");\n i18nMessages.put(new I18nLookup(RESISTANT, SWEDISH), \"Undvik: \");\n\n i18nMessages.put(new I18nLookup(WEAKNESSES, Locale.ENGLISH), \"Use: \");\n i18nMessages.put(new I18nLookup(WEAKNESSES, SWEDISH), \"Använd: \");\n\n i18nMessages.put(new I18nLookup(VS_HELP, Locale.ENGLISH),\n \"List information about a pokemon, it's types, weaknesses etc. - !raid vs [Pokemon]\");\n i18nMessages.put(new I18nLookup(VS_HELP, SWEDISH),\n \"Se information om en pokemon, dess typ, svagheter etc. - !raid vs [Pokemon]\");\n\n i18nMessages.put(new I18nLookup(RAID_TOSTRING, Locale.ENGLISH), \"Raid for %1 at gym %2, from %3 to %4\");\n i18nMessages.put(new I18nLookup(RAID_TOSTRING, SWEDISH), \"%1 vid %2, från %3 till %4\");\n\n i18nMessages.put(new I18nLookup(NEW_RAID_CREATED, Locale.ENGLISH), \"Raid created: %1\");\n i18nMessages.put(new I18nLookup(NEW_RAID_CREATED, SWEDISH), \"Raid skapad: %1\");\n\n i18nMessages.put(new I18nLookup(NEW_RAID_HELP, Locale.ENGLISH),\n \"Create new raid - !raid new [Name of Pokemon] [Ends at (HH:MM)] [Gym name]\");\n i18nMessages.put(new I18nLookup(NEW_RAID_HELP, SWEDISH),\n \"Skapa ny raid - !raid new [Pokemon] [Slutar klockan (HH:MM)] [Gym]\");\n\n i18nMessages.put(new I18nLookup(NEW_EX_RAID_HELP, Locale.ENGLISH),\n \"Create new EX raid - !raid ex [Name of Pokemon] [Ends at (yyyy-mm-dd HH:MM)] [Gym name]\");\n i18nMessages.put(new I18nLookup(NEW_EX_RAID_HELP, SWEDISH),\n \"Skapa ny EX raid - !raid ex [Pokemon] [Slutar (yyyy-mm-dd HH:MM)] [Gym]\");\n\n i18nMessages.put(new I18nLookup(AT_YOUR_SERVICE, Locale.ENGLISH), \"PokeRaidBot reporting for duty!\");\n i18nMessages.put(new I18nLookup(AT_YOUR_SERVICE, SWEDISH), \"PokeRaidBot till er tjänst!\");\n\n i18nMessages.put(new I18nLookup(USAGE_HELP, Locale.ENGLISH), \"Shows usage of bot.\");\n i18nMessages.put(new I18nLookup(USAGE_HELP, SWEDISH), \"Visar hur man använder botten.\");\n\n i18nMessages.put(new I18nLookup(GENERIC_USER_ERROR, Locale.ENGLISH), \"%1: %2\");\n i18nMessages.put(new I18nLookup(GENERIC_USER_ERROR, SWEDISH), \"%1: %2\");\n\n i18nMessages.put(new I18nLookup(USAGE, Locale.ENGLISH), featuresString_EN);\n i18nMessages.put(new I18nLookup(USAGE, SWEDISH), featuresString_SV);\n\n i18nMessages.put(new I18nLookup(GYM_NOT_FOUND, Locale.ENGLISH), \"Could not find Gym with name \\\"%1\\\" in region %2\");\n i18nMessages.put(new I18nLookup(GYM_NOT_FOUND, SWEDISH), \"Kunde inte hitta gym med namn \\\"%1\\\" i regionen %2\");\n\n i18nMessages.put(new I18nLookup(RAID_EXISTS, Locale.ENGLISH),\n \"Sorry, %1, a raid at gym %2 already exists (for %3). Sign up for it!\");\n i18nMessages.put(new I18nLookup(RAID_EXISTS, SWEDISH),\n \"Tyvärr, %1, en raid vid gym %2 finns redan (för %3). Anmäl dig till den?\");\n\n i18nMessages.put(new I18nLookup(HELP_MANUAL_HELP_TEXT, Locale.ENGLISH),\n \" Help manual for different topics: !raid man {topic} {optional:chan/dm - \" +\n \"used when an admin wants to show a user the syntax of commands}\\n\" +\n \"Available topics: raid, signup, map, install, change, tracking, group, ALL.\\n\" +\n \"**Example (to get help about raid commands):** !raid man raid\"\n );\n i18nMessages.put(new I18nLookup(HELP_MANUAL_HELP_TEXT, SWEDISH),\n \" Hjälpmanual för olika ämnen: !raid man {ämne} {frivilligt:chan/dm - \" +\n \"om man t.ex. vill visa hjälpen i en textkanal för en användare}\\n\" +\n \"Möjliga ämnen: raid, signup, map, install, change, tracking, group, ALL.\\n\" +\n \"**Exempel (för att få hjälp angående raidkommandon):** !raid man raid\"\n );\n i18nMessages.put(new I18nLookup(MANUAL_CONFIG, Locale.ENGLISH),\n \"**Note: This command must be executed in a server text channel, not in DM!**\\n\\n\" +\n \"**To find out your configuration:**\\n!raid config show\\n\\n\" +\n \"**To change language:**\\n!raid config *[param=value]*\\n\" +\n \"*Example setting Swedish locale:* !raid config locale=sv\\n\" +\n \"*Example setting nickname:* !raid config nick=HelloWorld\"\n );\n i18nMessages.put(new I18nLookup(MANUAL_CONFIG, SWEDISH),\n \"**OBS: Detta kommando måste köras i en servers textkanal, inte i DM!**\\n\\n\" +\n \"**För att få reda på din konfiguration:**\\n!raid config show\\n\\n\" +\n \"**För att ändra språk:**\\n!raid config *[param=value]*\\n\" +\n \"*Exempel (set English as language):* !raid config locale=en\\n\" +\n \"*Exempel att sätta smeknamn:* !raid config nick=HelloWorld\"\n );\n i18nMessages.put(new I18nLookup(MANUAL_RAID, Locale.ENGLISH),\n \"**Note: All of these commands must be executed in a server text channel, not in DM!**\\n\\n\" +\n \"**To register a new raid:**\\n!raid new *[Pokemon]* *[Ends at (HH:MM)]* *[Gym name]*\\n\" +\n \"*Example:* !raid new entei 09:25 Solna Platform\\n\\n\" +\n \"**To register a new EX raid:**\\n!raid ex *[Pokemon]* *[Ends at (yyyy-mm-dd HH:MM)]* *[Gym name]*\\n\" +\n \"*Example:* !raid ex deoxys 2017-10-10 09:25 Solna Platform\\n\\n\" +\n \"**To register a new raid via start time:**\\n!raid start *[Pokemon]* \" +\n \"*[Starts at (HH:MM)]* *[Gym name]*\\n\" +\n \"*Example:* !raid start entei 08:40 Solna Platform\\n\\n\" +\n \"**To report a egg being hatched at some point:**\\n!raid start *[Egg1-5 depending on raid tier]* \" +\n \"*[Starts at (HH:MM)]* *[Gym name]*\\n\" +\n \"*Example:* !raid start Egg5 08:40 Solna Platform\\n\\n\" +\n \"**To report a reported egg having hatched:**\\n!raid hatch *[Pokemon]* \" +\n \"*[Gym name]*\\n\" +\n \"*Example:* !raid hatch entei Solna Platform\\n\\n\" +\n \"**Check status for a raid in a gym:**\\n!raid status *[Gym name]*\\n\" +\n \"*Example:* !raid status Solna Platform\\n\\n\" +\n \"**Get a list of all active raids:**\\n!raid list\\n\" +\n \"*Examples:* !raid list Entei - list all raids for Entei.\\n\" +\n \"!raid list - list all active raids.\\n\\n\" +\n \"**Info about a raid boss:**\\n!raid vs *[Pokemon]*\\n\" +\n \"*Example:* !raid vs Entei\"\n );\n i18nMessages.put(new I18nLookup(MANUAL_RAID, SWEDISH),\n \"**OBS: Alla dessa kommandon måste köras i en servers textkanal, inte i DM!**\\n\\n\" +\n \"**För att registrera en raid:**\\n!raid new *[Pokemon]* \" +\n \"*[Slutar klockan (HH:MM)]* *[Gym-namn]*\\n\" +\n \"*Exempel:* !raid new entei 09:25 Solna Platform\\n\\n\" +\n \"**För att registrera en EX raid:**\\n!raid ex *[Pokemon]* \" +\n \"*[Slutar (yyyy-mm-dd HH:MM)]* *[Gym-namn]*\\n\" +\n \"*Exempel:* !raid ex deoxys 2017-10-10 09:25 Solna Platform\\n\\n\" +\n \"**För att registrera en raid via starttid:**\\n!raid start *[Pokemon]* \" +\n \"*[Startar klockan (HH:MM)]* *[Gym-namn]*\\n\" +\n \"*Exempel:* !raid start entei 08:40 Solna Platform\\n\\n\" +\n \"**För att rapportera att ett raidägg kommer kläckas:**\\n!raid start \" +\n \"*[Egg1-5 beroende på nivå]* \" +\n \"*[Startar klockan (HH:MM)]* *[Gym-namn]*\\n\" +\n \"*Exempel:* !raid start Egg5 08:40 Solna Platform\\n\\n\" +\n \"**För att rapportera att ett rapporterat ägg kläckts:**\\n!raid hatch *[Pokemon]* \" +\n \"*[Gym-namn]*\\n\" +\n \"*Exempel:* !raid hatch entei Solna Platform\\n\\n\" +\n \"**Kolla status för en raid:**\\n!raid status *[Gym-namn]*\\n\" +\n \"*Exempel:* !raid status Solna Platform\\n\\n\" +\n \"**Visa alla registrerade raider:**\\n!raid list\\n\" +\n \"*Exempel:* !raid list Entei - visa alla aktuella raider med Entei som boss.\\n\" +\n \"!raid list - lista alla aktuella raider oavsett boss.\\n\\n\" +\n \"**Information om en raidboss:**\\n!raid vs *[Pokemon]*\\n\" +\n \"*Exempel:* !raid vs Entei\"\n );\n\n i18nMessages.put(new I18nLookup(MANUAL_CHANGE, Locale.ENGLISH),\n \"**Note: All of these commands must be executed in a server text channel, not in DM!**\\n\\n\" +\n \"**Change endtime for a raid:** !raid change when *[New end of raid (HH:MM)]* *[Pokestop name]* \" +\n \"(Only raid creator or server admins may do this)\\n\" +\n \"*Example:* !raid change when 09:45 Solna Platform\\n\\n\" +\n \"**Change start time for a raid group:** !raid change group *[New time (HH:MM)]* *[Pokestop name]*\" +\n \" (Only raid creator or server admin)\\n\" +\n \"*Example:* !raid change group 09:35 Solna Platform*\\n\\n\" +\n \"**Remove raid group:** !raid change group remove *[Time (HH:MM)]* *[Pokestop name]*\" +\n \" (Only group creator - if no signups - or server admin)\\n\" +\n \"*Example:* !raid change group remove 09:35 Solna Platform*\\n\" +\n \"You can also remove the group message to remove the raid group.\\n\\n\" +\n \"**Change raid boss:** !raid change pokemon *[Pokemon]* *[Pokestop name]* \" +\n \"(Only raid creator or server admin)\\n\" +\n \"*Example:* !raid change pokemon Suicune Solna Platform\\n\\n\" +\n \"**Delete a raid:** !raid change remove *[Pokestop name]* (Only server admin)\\n\" +\n \"*Example:* !raid change remove Solna Platform\"\n );\n i18nMessages.put(new I18nLookup(MANUAL_CHANGE, SWEDISH),\n \"**OBS: Alla dessa kommandon måste köras i en servers textkanal, inte i DM!**\\n\\n\" +\n \"**Ändra en raids sluttid:** !raid change when *[Ny sluttid (HH:MM)]* *[Gym-namn]* \" +\n \"(Endast raidskapare eller admin får göra detta)\\n\" +\n \"*Exempel:* !raid change when 09:45 Solna Platform\\n\\n\" +\n \"**Ändra tid för en raidgrupp:** !raid change group *[Ny tid (HH:MM)]* *[Gym-namn]*\" +\n \" (Endast raidskapare eller admin)\\n\" +\n \"*Exempel:* !raid change group 09:35 Solna Platform*\\n\\n\" +\n \"**Ta bort raidgrupp:** !raid change group remove *[Time (HH:MM)]* *[Pokestop name]*\" +\n \" (Bara gruppskapare - om det inte finns anmälningar - eller admin)\\n\" +\n \"*Exempel:* !raid change group remove 09:35 Solna Platform*\\n\" +\n \"*Man kan också ta bort gruppmeddelandet så rensas gruppen automatiskt.\\n\\n\" +\n \"**Ändra en raids boss:** !raid change pokemon *[Pokemon]* *[Pokestop name]* \" +\n \"(Endast raidskapare eller admin)\\n\" +\n \"*Exempel:* !raid change pokemon Suicune Solna Platform\\n\\n\" +\n \"**Ta bort en raid:** !raid change remove *[Pokestop name]* (Endast admin)\\n\" +\n \"*Exempel:* !raid change remove Solna Platform\"\n );\n\n i18nMessages.put(new I18nLookup(MANUAL_GROUPS, Locale.ENGLISH),\n \"**Note:This command must be executed in a server text channel, not in DM!**\\n\\n\" +\n \"**Create a group to run a raid at a certain time:** !raid group {time (HH:MM)} {gym name}\\n\" +\n \"*Example:* !raid group 09:45 Solna Platform\\n\\n\" +\n \"A user can sign up themselves and their group friends via emotes below the raid group message.\\n\\n\" +\n \"1-6 buttons signs up the corresponding amount of people. \" +\n \"You can combine numbers to get the correct total. \" +\n \"Press the same button(s) again to remove the signups.\\n\\n\" +\n \"The message will be automatically updated with new signups. When the raid group start time\" +\n \" is expired, the message will be removed, along with the associated signups.\\n\\n\" +\n \"Since this function is pretty new, feedback on how to improve it is welcome.\"\n );\n i18nMessages.put(new I18nLookup(MANUAL_GROUPS, SWEDISH),\n \"**OBS: Kommandot måste köras i en servers textkanal, inte i DM!**\\n\\n\" +\n \"**Skapa en grupp för att köra raid en viss tid:** !raid group {time (HH:MM)} {gym namn}\\n\" +\n \"*Exempel:* !raid group 09:45 Solna Platform\\n\\n\" +\n \"Man anmäler sig till en raid via emotes som dyker upp under svaret på kommandot ovan.\\n\\n\" +\n \"1-6 anmäler det antal som står på knappen. \" +\n \"Tryck samma knapp igen för att ta bort samma antal.\\n\\n\" +\n \"Meddelandet kommer uppdateras var 15:e sekund med alla som anmäler sig. När tiden gått \" +\n \"ut för gruppen, kommer meddelandet tas bort, tillsammans med alla relaterade anmälningar.\\n\\n\" +\n \"Eftersom denna funktion är tämligen ny, uppskattas feedback på hur man kan göra den bättre.\"\n );\n\n i18nMessages.put(new I18nLookup(MANUAL_INSTALL, Locale.ENGLISH),\n \"**Install configuration for this server:** !raid install - starts install process\\n\" +\n \"!raid install server=[server name];region=[region dataset reference];\" +\n \"replyInDm=[true or false];locale=[2 char language code]\\n\" +\n \"**Example:** !raid install server=My test server;region=stockholm;replyInDm=false;locale=sv\"\n );\n i18nMessages.put(new I18nLookup(MANUAL_INSTALL, SWEDISH),\n \"**Installera konfiguration för denna server:** !raid install - startar processen\\n\" +\n \"!raid install server=[servernamn];region=[region, datasetsreferens];\" +\n \"replyInDm=[true eller false];locale=[2 teckens språkkod, t.ex. sv]\\n\" +\n \"**Exempel:** !raid install server=My test server;region=stockholm;replyInDm=false;locale=sv\"\n );\n\n i18nMessages.put(new I18nLookup(MANUAL_MAP, Locale.ENGLISH),\n \"**Note: This command must be executed in a server text channel, not in DM!**\\n\\n\" +\n \"**Get map for a certain gym:**\\n!raid map *[Gym name]*\\n\" +\n \"*Example:* !raid map Solna Platform\\n\\n\" +\n \"Note: You can click the name of the gym to go to it in Google Maps. There, you \" +\n \"can get directions, estimated time of arrival etc.\"\n );\n i18nMessages.put(new I18nLookup(MANUAL_MAP, SWEDISH),\n \"**OBS: Detta kommando måste köras i en servers textkanal, inte i DM!**\\n\\n\" +\n \"**Hämta karta för gym:**\\n!raid map *[Gym-namn]*\\n\" +\n \"*Exempel:* !raid map Solna Platform\\n\\n\" +\n \"OBS: Du kan klicka på gymnamnet för att gå till det i Google Maps. Där kan du sedan få t.ex. \" +\n \"vägbeskrivning, beräknad ankomsttid och så vidare.\"\n );\n\n i18nMessages.put(new I18nLookup(MANUAL_SIGNUP, Locale.ENGLISH),\n \"**Note: All of these commands must be executed in a server text channel, not in DM!**\\n\\n\" +\n \"**Sign up for a raid:**\\n!raid add *[number of people] [ETA (HH:MM)] [Gym name]*\\n\" +\n \"*Example:* !raid add 3 09:15 Solna Platform\\n\\n\" +\n \"**You can also use an easier way:** \\\\+{number of people} {ETA (HH:MM)} {Gym name}\\n\" +\n \"*Example:* +3 09:15 Solna Platform\\n\\n\" +\n \"**Unsign raid:**\\n!raid remove *[Gym name]*\\n\" +\n \"*Example:* !raid remove Solna Platform\\n\\n\" +\n \"**You can also use an easier way:** \\\\-{number of people} {Gym name}\\n\" +\n \"*Example:* -2 Solna Platform\"\n );\n i18nMessages.put(new I18nLookup(MANUAL_SIGNUP, SWEDISH),\n \"**OBS: Alla dessa kommandon måste köras i en servers textkanal, inte i DM!**\\n\\n\" +\n \"**Säg att du kommer till en viss raid:**\\n!raid add *[antal som kommer] [ETA (HH:MM)] [Gym-namn]*\\n\" +\n \"*Exempel:* !raid add 3 09:15 Solna Platform\\n\" +\n \"**Man kan också använda:** \\\\+{antal} {ETA (HH:MM)} {Gym-namn}\\n\" +\n \"*Exempel:* +3 09:15 Solna Platform\\n\\n\" +\n \"**Ta bort din signup för en raid:**\\n!raid remove *[Gym-namn]*\\n\" +\n \"*Exempel:* !raid remove Solna Platform\\n\\n\" +\n \"**Man kan också använda:** \\\\-{antal} {Gym-namn}\\n\" +\n \"*Exempel:* -2 Solna Platform\"\n );\n\n i18nMessages.put(new I18nLookup(MANUAL_TRACKING, Locale.ENGLISH),\n \"**Note: All of these commands must be executed in a server text channel, not in DM!**\\n\\n\" +\n \"**Track new raids for raid boss:**\\n\" +\n \"!raid track *[Pokemon]*\\n\" +\n \"*Example:* !raid track Entei\\n\\n\" +\n \"**Untrack raids for raid boss:**\\n!raid untrack *[Pokemon]*\\n\" +\n \"*Example - remove your tracking of Entei:* !raid untrack Entei\\n\" +\n \"*Example - remove all your tracking:* !raid untrack\"\n );\n i18nMessages.put(new I18nLookup(MANUAL_TRACKING, SWEDISH),\n \"**OBS: Alla dessa kommandon måste köras i en servers textkanal, inte i DM!**\\n\\n\" +\n \"**Övervakning av nya raids för pokemon:\" +\n \"**\\n!raid track *[Pokemon]*\\n\" +\n \"*Exempel:* !raid track Entei\\n\\n\" +\n \"**Ta bort övervakning av nya raids för pokemon:**\\n!raid untrack *[Pokemon]*\\n\" +\n \"*Exempel - ta bort din övervakning för Entei:* !raid untrack Entei\\n\" +\n \"*Exempel - ta bort alla dina övervakningar:* !raid untrack\"\n );\n }\n\n public Locale getLocaleForUser(User user) {\n if (userConfigRepository == null || user == null || user.getId() == null) {\n return DEFAULT;\n }\n\n final UserConfig userConfig = userConfigRepository.findOne(user.getId());\n if (userConfig == null) {\n return DEFAULT;\n } else {\n final Locale userLocale = userConfig.getLocale();\n if (userLocale == null) {\n return DEFAULT;\n } else {\n return userLocale;\n }\n }\n }\n\n public Locale getLocaleForUser(String username) {\n return DEFAULT;\n }\n\n public void storeMessage(String messageKey, Locale locale, String message) {\n i18nMessages.put(new I18nLookup(messageKey.toUpperCase(), locale), message);\n }\n\n public String getMessageFor(String messageKey, Locale locale, String ... parameters) {\n String messageWithParameters = getMessageTextToInjectParametersIn(messageKey, locale);\n int i = 1;\n for (String param : parameters) {\n messageWithParameters = messageWithParameters.replaceAll(\"[%][\" + i + \"]\", param);\n i++;\n }\n return messageWithParameters;\n }\n\n private String getMessageTextToInjectParametersIn(String messageKey, Locale locale) {\n Locale actualLocale = locale;\n if (locale == null) {\n actualLocale = DEFAULT;\n }\n String message = i18nMessages.get(new I18nLookup(messageKey.toUpperCase(), actualLocale));\n if (message == null || message.length() < 1) {\n message = i18nMessages.get(new I18nLookup(messageKey.toUpperCase(), DEFAULT));\n }\n if (message == null || message.length() < 1) {\n throw new RuntimeException(\"Could not find text for message key \" + messageKey +\n \" - an admin needs to add it to the LocaleService!\");\n }\n return message;\n }\n\n public static boolean isSupportedLocale(Locale locale) {\n return Arrays.asList(SUPPORTED_LOCALES).contains(locale);\n }\n\n public static String asString(TimeUnit timeUnit, Locale locale) {\n switch (timeUnit) {\n case SECONDS:\n return (locale != null && locale.getLanguage().equals(SWEDISH.getLanguage()) ? \"sekund\" : \"second\");\n case MINUTES:\n return (locale != null && locale.getLanguage().equals(SWEDISH.getLanguage()) ? \"minut\" : \"minute\");\n default:\n return timeUnit.name().toLowerCase();\n }\n }\n\n private class I18nLookup {\n private String messageKey;\n private Locale locale;\n\n I18nLookup(String messageKey, Locale locale) {\n this.messageKey = messageKey;\n this.locale = locale;\n }\n\n public String getMessageKey() {\n return messageKey;\n }\n\n public Locale getLocale() {\n return locale;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (!(o instanceof I18nLookup)) return false;\n\n I18nLookup that = (I18nLookup) o;\n\n if (messageKey != null ? !messageKey.equals(that.messageKey) : that.messageKey != null) return false;\n return locale != null ? locale.equals(that.locale) : that.locale == null;\n }\n\n @Override\n public int hashCode() {\n int result = messageKey != null ? messageKey.hashCode() : 0;\n result = 31 * result + (locale != null ? locale.hashCode() : 0);\n return result;\n }\n }\n\n public static String featuresString_EN =\n \"Pokeraidbot - a Discord bot to help Pokémon Go raiders. Raid, map, pokemon info functions.\\n\\n\" +\n \"Getting started guide: \" +\n \"https://github.com/magnusmickelsson/pokeraidbot/blob/master/GETTING_STARTED_USER_en.md\\n\\n\" +\n \"**Get detailed help about how the bot works:**\\n!raid man\\n\\n\" +\n \"**To see one of its features, type the following:** \" +\n \"!raid map {name of a raid gym in your vicinity}\\n\" +\n \"*Example:* !raid map Solna Platform\\n\\n\" +\n \"https://github.com/magnusmickelsson/pokeraidbot to report errors, request features, \" +\n \"see screenshots of usage etc.\\n\\n\" +\n \"**How do I support development of this bot?**\\n!raid donate\";\n public static String featuresString_SV =\n \"Pokeraidbot - en Discord-bot för att hjälpa Pokémon Go raiders, med t.ex. kartor till gym, raidplanering\" +\n \" och information om pokemons.\\n\\n\" +\n \"Kom igång guide: \" +\n \"https://github.com/magnusmickelsson/pokeraidbot/blob/master/GETTING_STARTED_USER_sv.md\\n\\n\" +\n \"**Få detaljerad hjälp om hur botten fungerar:**\\n!raid man {frivilligt: ämne}\\n\" +\n \"*Exempel:* !raid man - berättar om hur man använder raid man och vilka hjälpämnen som finns\\n\\n\" +\n \"**För ett exempel på vad botten kan göra, skriv:** !raid map {namn på ett gym i området}\\n\" +\n \"*Exempel:* !raid map Solna Platform\\n\\n\" +\n \"https://github.com/magnusmickelsson/pokeraidbot för att rapportera fel, önska funktioner, \" +\n \"se screenshots av användning etc.\\n\\n\" +\n \"**Hur kan jag stödja utveckling av botten?**\\n!raid donate\\n\\n\" +\n \"**If you want this information in english:**\\n!raid usage en\";\n}",
"public class Pokemon {\n\n private String name;\n private PokemonTypes types;\n private Set<String> weaknesses;\n private Set<String> resistant;\n private Integer number;\n private String about;\n private String buddyDistance;\n\n public Pokemon(Integer number, String name, String about, PokemonTypes types, String buddyDistance,\n Set<String> weaknesses, Set<String> resistantTo) {\n Validate.notNull(number, \"Number is null!\");\n Validate.notNull(types, \"Types is null!\");\n Validate.notEmpty(name, \"Name is empty!\");\n if (types != PokemonTypes.NONE) {\n Validate.notEmpty(weaknesses, \"Weaknesses is empty!\");\n Validate.notEmpty(resistantTo, \"ResistantTo is empty!\");\n }\n\n this.number = number;\n this.name = name;\n this.about = about;\n this.types = types;\n this.buddyDistance = buddyDistance;\n this.weaknesses = weaknesses;\n resistant = resistantTo;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (!(o instanceof Pokemon)) return false;\n\n Pokemon pokemon = (Pokemon) o;\n\n if (name != null ? !name.equals(pokemon.name) : pokemon.name != null) return false;\n if (types != null ? !types.equals(pokemon.types) : pokemon.types != null) return false;\n if (weaknesses != null ? !weaknesses.equals(pokemon.weaknesses) : pokemon.weaknesses != null) return false;\n if (resistant != null ? !resistant.equals(pokemon.resistant) : pokemon.resistant != null) return false;\n if (number != null ? !number.equals(pokemon.number) : pokemon.number != null) return false;\n if (about != null ? !about.equals(pokemon.about) : pokemon.about != null) return false;\n return buddyDistance != null ? buddyDistance.equals(pokemon.buddyDistance) : pokemon.buddyDistance == null;\n }\n\n @Override\n public int hashCode() {\n int result = name != null ? name.hashCode() : 0;\n result = 31 * result + (types != null ? types.hashCode() : 0);\n result = 31 * result + (weaknesses != null ? weaknesses.hashCode() : 0);\n result = 31 * result + (resistant != null ? resistant.hashCode() : 0);\n result = 31 * result + (number != null ? number.hashCode() : 0);\n result = 31 * result + (about != null ? about.hashCode() : 0);\n result = 31 * result + (buddyDistance != null ? buddyDistance.hashCode() : 0);\n return result;\n }\n\n public PokemonTypes getTypes() {\n return types;\n }\n\n public Set<String> getWeaknesses() {\n return weaknesses;\n }\n\n public Set<String> getResistant() {\n return resistant;\n }\n\n public Integer getNumber() {\n return number;\n }\n\n public String getAbout() {\n return about;\n }\n\n public String getBuddyDistance() {\n return buddyDistance;\n }\n\n @Override\n public String toString() {\n return name + (types.getTypeSet().size() > 0 ? \" (\" + types + \")\" : \"\");\n }\n\n public String getName() {\n return name;\n }\n\n public boolean isEgg() {\n return StringUtils.containsIgnoreCase(name, \"egg\") && name.matches(\"[Ee][Gg][Gg][1-6]\");\n }\n}",
"public class PokemonRepository {\n private static final Logger LOGGER = LoggerFactory.getLogger(PokemonRepository.class);\n\n private final LocaleService localeService;\n public static final String EGG_1 = \"Egg1\";\n public static final String EGG_2 = \"Egg2\";\n public static final String EGG_3 = \"Egg3\";\n public static final String EGG_4 = \"Egg4\";\n public static final String EGG_5 = \"Egg5\";\n public static final String EGG_6 = \"Egg6\";\n private Map<String, Pokemon> pokemons = new LinkedHashMap<>();\n\n public PokemonRepository(String resourceName, LocaleService localeService) {\n this.localeService = localeService;\n try {\n CSVPokemonDataReader csvPokemonDataReader = new CSVPokemonDataReader(resourceName);\n final Set<Pokemon> pokemonsRead = csvPokemonDataReader.readAll();\n for (Pokemon p : pokemonsRead) {\n pokemons.put(p.getName().toUpperCase(), p);\n }\n // So we can handle eggs before they're hatched\n this.pokemons.put(\"EGG1\", new Pokemon(99999, EGG_1, \"Tier 1 egg\", PokemonTypes.NONE,\n \"\", new HashSet<>(),\n new HashSet<>()));\n this.pokemons.put(\"EGG2\", new Pokemon(99998, EGG_2, \"Tier 2 egg\", PokemonTypes.NONE,\n \"\", new HashSet<>(),\n new HashSet<>()));\n this.pokemons.put(\"EGG3\", new Pokemon(99997, EGG_3, \"Tier 3 egg\", PokemonTypes.NONE,\n \"\", new HashSet<>(),\n new HashSet<>()));\n this.pokemons.put(\"EGG4\", new Pokemon(99996, EGG_4, \"Tier 4 egg\", PokemonTypes.NONE,\n \"\", new HashSet<>(),\n new HashSet<>()));\n this.pokemons.put(\"EGG5\", new Pokemon(99995, EGG_5, \"Tier 5 egg\", PokemonTypes.NONE,\n \"\", new HashSet<>(),\n new HashSet<>()));\n this.pokemons.put(\"EGG6\", new Pokemon(99994, EGG_6, \"MEGA raid\", PokemonTypes.NONE,\n \"\", new HashSet<>(),\n new HashSet<>()));\n } catch (Throwable e) {\n throw new RuntimeException(e.getMessage());\n }\n }\n\n public Pokemon search(String name, User user) {\n final Pokemon pokemon = fuzzySearch(name);\n if (pokemon == null) {\n final Locale locale = user == null ? LocaleService.DEFAULT : localeService.getLocaleForUser(user);\n throw new RuntimeException(localeService.getMessageFor(LocaleService.NO_POKEMON, locale, name));\n }\n return pokemon;\n }\n\n public Pokemon getByName(String name) {\n if (name == null) {\n return null;\n }\n final String nameToGet = name.trim().toUpperCase();\n return pokemons.get(nameToGet);\n }\n\n // This method is a getter with fuzzy search that doesn't throw an exception if it doesn't find a pokemon, just returns null\n private Pokemon fuzzySearch(String name) {\n final Collection<Pokemon> allPokemons = pokemons.values();\n\n final String nameToSearchFor = name.trim().toUpperCase();\n final Optional<Pokemon> pokemon = Optional.ofNullable(pokemons.get(nameToSearchFor));\n if (pokemon.isPresent()) {\n return pokemon.get();\n } else {\n List<ExtractedResult> candidates = FuzzySearch.extractTop(nameToSearchFor,\n allPokemons.stream().map(p -> p.getName().toUpperCase()).collect(Collectors.toList()), 5, 50);\n if (candidates.size() == 1) {\n return pokemons.get(candidates.iterator().next().getString());\n } else if (candidates.size() < 1) {\n return null;\n } else {\n int score = 0;\n String highestScoreResultName = null;\n for (ExtractedResult result : candidates) {\n if (result.getScore() > score) {\n score = result.getScore();\n highestScoreResultName = result.getString();\n }\n }\n if (highestScoreResultName != null) {\n return pokemons.get(highestScoreResultName);\n } else {\n return null;\n }\n }\n }\n }\n\n public Set<Pokemon> getAll() {\n return Collections.unmodifiableSet(new HashSet<>(pokemons.values()));\n }\n\n public Pokemon getByNumber(Integer pokemonNumber) {\n for (Pokemon p : getAll()) {\n if (Objects.equals(p.getNumber(), pokemonNumber)) {\n return p;\n }\n }\n throw new RuntimeException(localeService.getMessageFor(LocaleService.NO_POKEMON, LocaleService.DEFAULT, \"\" +\n pokemonNumber));\n }\n}",
"public class PokemonRaidStrategyService {\n private static final Logger LOGGER = LoggerFactory.getLogger(PokemonRaidStrategyService.class);\n\n private Map<String, RaidBossCounters> counters = new HashMap<>();\n private Map<String, PokemonRaidInfo> pokemonRaidInfo = new HashMap<>();\n private static String[] raidBosses = {\n \"BAYLEEF\",\n \"CROCONAW\",\n \"MAGIKARP\",\n \"QUILAVA\",\n \"ELECTABUZZ\",\n \"EXEGGUTOR\",\n \"MAGMAR\",\n \"MUK\",\n \"WEEZING\",\n \"ALAKAZAM\",\n \"ARCANINE\",\n \"FLAREON\",\n \"GENGAR\",\n \"JOLTEON\",\n \"MACHAMP\",\n \"VAPOREON\",\n \"Blastoise\".toUpperCase(),\n \"Charizard\".toUpperCase(),\n \"Lapras\".toUpperCase(),\n \"Rhydon\".toUpperCase(), \"Snorlax\".toUpperCase(), \"Tyranitar\".toUpperCase(),\n \"Venusaur\".toUpperCase(), \"Entei\".toUpperCase(), \"Articuno\".toUpperCase(), \"Moltres\".toUpperCase(),\n \"Zapdos\".toUpperCase(), \"Lugia\".toUpperCase(),\n \"Raikou\".toUpperCase(), \"Suicune\".toUpperCase(),\n \"Mewtwo\".toUpperCase(),\n // Tier 1\n \"Ivysaur\".toUpperCase(),\n \"Metapod\".toUpperCase(),\n \"Charmeleon\".toUpperCase(),\n \"Wartortle\".toUpperCase(),\n \"egg1\".toUpperCase(),\n // Tier 2\n \"Magneton\".toUpperCase(),\n \"Sableye\".toUpperCase(),\n \"Sandslash\".toUpperCase(),\n \"Tentacruel\".toUpperCase(),\n \"Marowak\".toUpperCase(), // Note: Alolan is tier 4 and active right now because niantic sucks\n \"Cloyster\".toUpperCase(),\n \"egg2\".toUpperCase(),\n // Tier 3\n \"Ninetales\".toUpperCase(),\n \"Scyther\".toUpperCase(),\n \"Omastar\".toUpperCase(),\n \"Porygon\".toUpperCase(),\n \"egg3\".toUpperCase(),\n // Tier 4\n \"Poliwrath\".toUpperCase(),\n \"Victreebel\".toUpperCase(),\n \"Golem\".toUpperCase(),\n \"Nidoking\".toUpperCase(),\n \"Nidoqueen\".toUpperCase(),\n \"egg4\".toUpperCase(),\n // Tier 5 /EX\n \"egg5\".toUpperCase(),\n \"Ho-oh\".toUpperCase(),\n // ==== Generation 3+ ====\n // Tier 1\n \"Wailmer\".toUpperCase(),\n \"snorunt\".toUpperCase(),\n \"swablu\".toUpperCase(),\n \"duskull\".toUpperCase(),\n \"shuppet\".toUpperCase(),\n \"bulbasaur\".toUpperCase(),\n \"charmander\".toUpperCase(),\n \"squirtle\".toUpperCase(),\n \"makuhita\".toUpperCase(),\n \"meditite\".toUpperCase(),\n \"shinx\".toUpperCase(),\n \"buizel\".toUpperCase(),\n \"mareep\".toUpperCase(),\n \"magnemite\".toUpperCase(),\n \"minun\".toUpperCase(),\n \"plusle\".toUpperCase(),\n \"wingull\".toUpperCase(),\n \"dratini\".toUpperCase(),\n \"feebas\".toUpperCase(),\n \"lotad\".toUpperCase(),\n \"chikorita\".toUpperCase(),\n \"sunkern\".toUpperCase(),\n \"Kricketot\".toUpperCase(),\n \"Skorupi\".toUpperCase(),\n \"Caterpie\".toUpperCase(),\n \"Drifloon\".toUpperCase(),\n \"Bagon\".toUpperCase(),\n \"Bronzor\".toUpperCase(),\n \"Horsea\".toUpperCase(),\n \"Nidoran\".toUpperCase(),\n \"Sentret\".toUpperCase(),\n \"Murkrow\".toUpperCase(),\n \"snubbull\".toUpperCase(),\n \"patrat\".toUpperCase(),\n \"lillipup\".toUpperCase(),\n \"klink\".toUpperCase(),\n \"beldum\".toUpperCase(),\n \"zubat\".toUpperCase(),\n \"ekans\".toUpperCase(),\n \"cubone\".toUpperCase(),\n \"koffing\".toUpperCase(),\n \"drowzee\".toUpperCase(),\n \"ralts\".toUpperCase(),\n \"burmy\".toUpperCase(),\n \"yanma\".toUpperCase(),\n \"litwick\".toUpperCase(),\n \"pidove\".toUpperCase(),\n \"tepig\".toUpperCase(),\n \"ducklett\".toUpperCase(),\n \"espurr\".toUpperCase(),\n \"trapinch\".toUpperCase(),\n\n // Tier 2\n \"Mawile\".toUpperCase(),\n \"dewgong\".toUpperCase(),\n \"slowbro\".toUpperCase(),\n \"Manectric\".toUpperCase(),\n \"Sneasel\".toUpperCase(),\n \"Misdreavus\".toUpperCase(),\n \"lickitung\".toUpperCase(),\n \"venomoth\".toUpperCase(),\n \"combusken\".toUpperCase(),\n \"primeape\".toUpperCase(),\n \"kirlia\".toUpperCase(),\n \"roselia\".toUpperCase(),\n \"lanturn\".toUpperCase(),\n \"grovyle\".toUpperCase(),\n \"marshtomp\".toUpperCase(),\n \"monferno\".toUpperCase(),\n \"Combee\".toUpperCase(),\n \"Masquerain\".toUpperCase(),\n \"pineco\".toUpperCase(),\n \"houndour\".toUpperCase(),\n \"gligar\".toUpperCase(),\n \"feebas\".toUpperCase(),\n \"yamask\".toUpperCase(),\n \"anorith\".toUpperCase(),\n \"lileep\".toUpperCase(),\n \"kingler\".toUpperCase(),\n \"magneton\".toUpperCase(),\n \"grotle\".toUpperCase(),\n \"grumpig\".toUpperCase(),\n \"fearow\".toUpperCase(),\n \"swellow\".toUpperCase(),\n\n // Tier 3\n \"azumarill\".toUpperCase(),\n \"jynx\".toUpperCase(),\n \"piloswine\".toUpperCase(),\n \"Aerodactyl\".toUpperCase(),\n \"Starmie\".toUpperCase(),\n \"Claydol\".toUpperCase(),\n \"Granbull\".toUpperCase(),\n \"Pinsir\".toUpperCase(),\n \"aerodactyl\".toUpperCase(),\n \"kabutops\".toUpperCase(),\n \"onix\".toUpperCase(),\n \"hitmonlee\".toUpperCase(),\n \"hitmonchan\".toUpperCase(),\n \"breloom\".toUpperCase(),\n \"raichu\".toUpperCase(),\n \"donphan\".toUpperCase(),\n \"tangela\".toUpperCase(),\n \"Sharpedo\".toUpperCase(),\n \"Skarmory\".toUpperCase(),\n \"Espeon\".toUpperCase(),\n \"Umbreon\".toUpperCase(),\n \"Crawdaunt\".toUpperCase(),\n \"Lunatone\".toUpperCase(),\n \"Solrock\".toUpperCase(),\n \"Shuckle\".toUpperCase(),\n \"Skuntank\".toUpperCase(),\n \"Persian\".toUpperCase(),\n \"pidgeot\".toUpperCase(),\n \"mantine\".toUpperCase(),\n \"hippowdon\".toUpperCase(),\n \"meganium\".toUpperCase(),\n\n // Tier 4\n \"feraligatr\".toUpperCase(),\n \"Absol\".toUpperCase(),\n \"Salamence\".toUpperCase(),\n \"Aggron\".toUpperCase(),\n \"Walrein\".toUpperCase(),\n \"Houndoom\".toUpperCase(),\n \"Togetic\".toUpperCase(),\n \"Metagross\".toUpperCase(),\n \"Shiftry\".toUpperCase(),\n \"Ursaring\".toUpperCase(),\n \"ninjask\".toUpperCase(),\n \"Regice\".toUpperCase(),\n \"Regirock\".toUpperCase(),\n \"Registeel\".toUpperCase(),\n \"Meowth\".toUpperCase(),\n \"Excadrill\".toUpperCase(),\n \"Dragonite\".toUpperCase(),\n \"Staraptor\".toUpperCase(),\n\n // Tier 5\n \"Groudon\".toUpperCase(),\n \"Kyogre\".toUpperCase(),\n \"Rayquaza\".toUpperCase(),\n \"Latios\".toUpperCase(),\n \"Latias\".toUpperCase(),\n \"Mew\".toUpperCase(),\n \"Celebi\".toUpperCase(),\n \"Giratina\".toUpperCase(),\n \"palkia\".toUpperCase(),\n \"dialga\".toUpperCase(),\n \"cresselia\".toUpperCase(),\n \"heatran\".toUpperCase(),\n \"uxie\".toUpperCase(),\n \"mesprit\".toUpperCase(),\n \"azelf\".toUpperCase(),\n \"darkrai\".toUpperCase(),\n \"cobalion\".toUpperCase(),\n \"terrakion\".toUpperCase(),\n \"virizion\".toUpperCase(),\n \"regigigas\".toUpperCase(),\n \"tornadus\".toUpperCase(),\n \"thundurus\".toUpperCase(),\n \"landorus\".toUpperCase(),\n \"zacian\".toUpperCase(),\n \"zamazenta\".toUpperCase(),\n \"deoxys\".toUpperCase()\n };\n\n public PokemonRaidStrategyService(PokemonRepository pokemonRepository) {\n for (String raidBossName : raidBosses) {\n try {\n final CounterTextFileParser parser = new CounterTextFileParser(\"/counters\", raidBossName, pokemonRepository);\n final Pokemon raidBoss = pokemonRepository.getByName(raidBossName);\n if (raidBoss == null) {\n LOGGER.error(\"Could not find raidBoss in pokemon repository: \" + raidBossName);\n System.exit(-1);\n }\n final RaidBossCounters raidBossCounters = new RaidBossCounters(raidBoss, parser.getBestCounters(), parser.getGoodCounters());\n counters.put(raidBossName.toUpperCase(), raidBossCounters);\n } catch (RuntimeException e) {\n // No file for this boss, skip it\n }\n }\n LOGGER.info(\"Parsed \" + counters.size() + \" raid boss counters.\");\n\n populateRaidInfoForBoss(pokemonRepository, \"BAYLEEF\", \"740\", 1);\n\n populateRaidInfoForBoss(pokemonRepository, \"CROCONAW\", \"984\", 2);\n\n populateRaidInfoForBoss(pokemonRepository, \"MAGIKARP\", \"157\", 1);\n\n populateRaidInfoForBoss(pokemonRepository, \"QUILAVA\", \"847\", 1);\n\n populateRaidInfoForBoss(pokemonRepository, \"ELECTABUZZ\", \"1333\", 2);\n\n populateRaidInfoForBoss(pokemonRepository, \"EXEGGUTOR\", \"1722\", 2);\n\n populateRaidInfoForBoss(pokemonRepository, \"MAGMAR\", \"1288\", 2);\n\n populateRaidInfoForBoss(pokemonRepository, \"MUK\", \"1575\", 2);\n\n // Galarian version so temporarily changed\n populateRaidInfoForBoss(pokemonRepository, \"WEEZING\", \"1310\", 4);\n\n populateRaidInfoForBoss(pokemonRepository, \"ALAKAZAM\", \"1747\", 3);\n\n populateRaidInfoForBoss(pokemonRepository, \"ARCANINE\", \"1622\", 3);\n\n populateRaidInfoForBoss(pokemonRepository, \"FLAREON\", \"1730\", 3);\n\n populateRaidInfoForBoss(pokemonRepository, \"GENGAR\", \"1496\", 3);\n\n populateRaidInfoForBoss(pokemonRepository, \"JOLTEON\", \"1650\", 3);\n\n populateRaidInfoForBoss(pokemonRepository, \"MACHAMP\", \"1746\", 3);\n\n populateRaidInfoForBoss(pokemonRepository, \"VAPOREON\", \"1779\", 3);\n\n populateRaidInfoForBoss(pokemonRepository, \"Blastoise\", \"1309\", 4);\n\n populateRaidInfoForBoss(pokemonRepository, \"Charizard\", \"1535\", 4);\n\n populateRaidInfoForBoss(pokemonRepository, \"Lapras\", \"1487\", 4);\n\n populateRaidInfoForBoss(pokemonRepository, \"Rhydon\", \"1816\", 4);\n\n populateRaidInfoForBoss(pokemonRepository, \"Snorlax\", \"1917\", 4);\n\n populateRaidInfoForBoss(pokemonRepository, \"Tyranitar\", \"2191\", 4);\n\n populateRaidInfoForBoss(pokemonRepository, \"Venusaur\", \"1467\", 4);\n\n populateRaidInfoForBoss(pokemonRepository, \"Entei\", \"1930\", 5);\n\n populateRaidInfoForBoss(pokemonRepository, \"Articuno\", \"1676\", 5);\n\n populateRaidInfoForBoss(pokemonRepository, \"Moltres\", \"1870\", 5);\n\n populateRaidInfoForBoss(pokemonRepository, \"Zapdos\", \"1902\", 5);\n\n populateRaidInfoForBoss(pokemonRepository, \"Lugia\", \"2056\", 5);\n\n populateRaidInfoForBoss(pokemonRepository, \"Raikou\", \"1913\", 5);\n\n populateRaidInfoForBoss(pokemonRepository, \"Suicune\", \"1613\", 5);\n\n populateRaidInfoForBoss(pokemonRepository, \"Mewtwo\", \"2387\", 5);\n\n // New bosses after Niantic surprise attack :p\n // Tier 1\n populateRaidInfoForBoss(pokemonRepository, \"Ivysaur\", \"886\", 1);\n populateRaidInfoForBoss(pokemonRepository, \"Metapod\", \"239\", 1);\n populateRaidInfoForBoss(pokemonRepository, \"Charmeleon\", \"847\", 1);\n populateRaidInfoForBoss(pokemonRepository, \"Wartortle\", \"756\", 1);\n populateRaidInfoForBoss(pokemonRepository, \"egg1\", \"1\", 1);\n // Tier 2\n populateRaidInfoForBoss(pokemonRepository, \"Magneton\", \"1278\", 2);\n populateRaidInfoForBoss(pokemonRepository, \"Sableye\", \"843\", 2);\n populateRaidInfoForBoss(pokemonRepository, \"Sandslash\", \"1356\", 2);\n populateRaidInfoForBoss(pokemonRepository, \"Tentacruel\", \"1356\", 2);\n populateRaidInfoForBoss(pokemonRepository, \"Cloyster\", \"1414\", 2);\n populateRaidInfoForBoss(pokemonRepository, \"Kingler\", \"1616\", 2);\n populateRaidInfoForBoss(pokemonRepository, \"egg2\", \"1\", 2);\n // Normally tier 2 but alolan raid is tier 4 because niantic sucks in not letting different pokemons have different id's etc.\n populateRaidInfoForBoss(pokemonRepository, \"Marowak\", \"1048\", 4);\n // Tier 3\n populateRaidInfoForBoss(pokemonRepository, \"Ninetales\", \"1233\", 3);\n populateRaidInfoForBoss(pokemonRepository, \"Scyther\", \"1546\", 3);\n populateRaidInfoForBoss(pokemonRepository, \"Omastar\", \"1534\", 3);\n populateRaidInfoForBoss(pokemonRepository, \"Porygon\", \"895\", 3);\n populateRaidInfoForBoss(pokemonRepository, \"egg3\", \"1\", 3);\n\n // Tier 4\n populateRaidInfoForBoss(pokemonRepository, \"Poliwrath\", \"1395\", 4);\n populateRaidInfoForBoss(pokemonRepository, \"Victreebel\", \"1296\", 4);\n populateRaidInfoForBoss(pokemonRepository, \"Golem\", \"1685\", 4);\n populateRaidInfoForBoss(pokemonRepository, \"Nidoking\", \"1363\", 4);\n populateRaidInfoForBoss(pokemonRepository, \"Nidoqueen\", \"1336\", 4);\n populateRaidInfoForBoss(pokemonRepository, \"egg4\", \"1\", 4);\n\n // Tier 5 / EX\n populateRaidInfoForBoss(pokemonRepository, \"egg5\", \"1\", 5);\n populateRaidInfoForBoss(pokemonRepository, \"Ho-oh\", \"2222\", 5);\n\n // MEGA\n populateRaidInfoForBoss(pokemonRepository, \"egg6\", \"1\", 6);\n\n // ==== Gen 3+ ====\n // Tier 1\n populateRaidInfoForBoss(pokemonRepository, \"Wailmer\", \"838\", 1);\n populateRaidInfoForBoss(pokemonRepository, \"Snorunt\", \"441\", 1);\n populateRaidInfoForBoss(pokemonRepository, \"Swablu\", \"470\", 1);\n populateRaidInfoForBoss(pokemonRepository, \"Shuppet\", \"581\", 1);\n populateRaidInfoForBoss(pokemonRepository, \"Duskull\", \"403\", 1);\n populateRaidInfoForBoss(pokemonRepository, \"Bulbasaur\", \"637\", 1);\n populateRaidInfoForBoss(pokemonRepository, \"Charmander\", \"560\", 1);\n populateRaidInfoForBoss(pokemonRepository, \"Squirtle\", \"540\", 1);\n populateRaidInfoForBoss(pokemonRepository, \"Makuhita\", \"467\", 1);\n populateRaidInfoForBoss(pokemonRepository, \"Meditite\", \"396\", 1);\n populateRaidInfoForBoss(pokemonRepository, \"Shinx\", \"500\", 1);\n populateRaidInfoForBoss(pokemonRepository, \"Buizel\", \"602\", 1);\n populateRaidInfoForBoss(pokemonRepository, \"Mareep\", \"566\", 1);\n populateRaidInfoForBoss(pokemonRepository, \"Magnemite\", \"778\", 1);\n populateRaidInfoForBoss(pokemonRepository, \"Minun\", \"968\", 1);\n populateRaidInfoForBoss(pokemonRepository, \"Plusle\", \"1016\", 1);\n populateRaidInfoForBoss(pokemonRepository, \"Wingull\", \"437\", 1);\n populateRaidInfoForBoss(pokemonRepository, \"Dratini\", \"574\", 1);\n populateRaidInfoForBoss(pokemonRepository, \"Feebas\", \"157\", 1);\n populateRaidInfoForBoss(pokemonRepository, \"Lotad\", \"342\", 1);\n populateRaidInfoForBoss(pokemonRepository, \"Sunkern\", \"226\", 1);\n populateRaidInfoForBoss(pokemonRepository, \"Chikorita\", \"534\", 1);\n populateRaidInfoForBoss(pokemonRepository, \"Skorupi\", \"576\", 1);\n populateRaidInfoForBoss(pokemonRepository, \"Kricketot\", \"229\", 1);\n populateRaidInfoForBoss(pokemonRepository, \"Caterpie\", \"249\", 1);\n populateRaidInfoForBoss(pokemonRepository, \"Drifloon\", \"684\", 1);\n populateRaidInfoForBoss(pokemonRepository, \"Bagon\", \"660\", 1);\n populateRaidInfoForBoss(pokemonRepository, \"Bronzor\", \"344\", 1);\n populateRaidInfoForBoss(pokemonRepository, \"Horsea\", \"603\", 1);\n populateRaidInfoForBoss(pokemonRepository, \"Nidoran\", \"491\", 1);\n populateRaidInfoForBoss(pokemonRepository, \"Murkrow\", \"892\", 1);\n populateRaidInfoForBoss(pokemonRepository, \"Sentret\", \"353\", 1);\n populateRaidInfoForBoss(pokemonRepository, \"Snubbull\", \"656\", 1);\n populateRaidInfoForBoss(pokemonRepository, \"Patrat\", \"452\", 1);\n populateRaidInfoForBoss(pokemonRepository, \"Lillipup\", \"523\", 1);\n populateRaidInfoForBoss(pokemonRepository, \"Klink\", \"546\", 1);\n populateRaidInfoForBoss(pokemonRepository, \"Beldum\", \"513\", 1);\n populateRaidInfoForBoss(pokemonRepository, \"Koffing\", \"694\", 1);\n populateRaidInfoForBoss(pokemonRepository, \"Zubat\", \"381\", 1);\n populateRaidInfoForBoss(pokemonRepository, \"Ekans\", \"529\", 1);\n populateRaidInfoForBoss(pokemonRepository, \"Cubone\", \"536\", 1);\n populateRaidInfoForBoss(pokemonRepository, \"Drowzee\", \"594\", 1);\n populateRaidInfoForBoss(pokemonRepository, \"Burmy\", \"279\", 1);\n populateRaidInfoForBoss(pokemonRepository, \"Ralts\", \"308\", 1);\n populateRaidInfoForBoss(pokemonRepository, \"Yanma\", \"840\", 1);\n populateRaidInfoForBoss(pokemonRepository, \"Litwick\", \"575\", 1);\n populateRaidInfoForBoss(pokemonRepository, \"Pidove\", \"484\", 1);\n populateRaidInfoForBoss(pokemonRepository, \"Tepig\", \"618\", 1);\n populateRaidInfoForBoss(pokemonRepository, \"Trapinch\", \"728\", 1);\n populateRaidInfoForBoss(pokemonRepository, \"Ducklett\", \"489\", 1);\n populateRaidInfoForBoss(pokemonRepository, \"Espurr\", \"719\", 1);\n\n // Tier 2\n populateRaidInfoForBoss(pokemonRepository, \"Mawile\", \"934\", 2);\n populateRaidInfoForBoss(pokemonRepository, \"Dewgong\", \"1082\", 2);\n populateRaidInfoForBoss(pokemonRepository, \"Slowbro\", \"1418\", 2);\n populateRaidInfoForBoss(pokemonRepository, \"Manectric\", \"1337\", 2);\n populateRaidInfoForBoss(pokemonRepository, \"Sneasel\", \"1067\", 2);\n populateRaidInfoForBoss(pokemonRepository, \"Misdreavus\", \"1100\", 2);\n populateRaidInfoForBoss(pokemonRepository, \"Lickitung\", \"806\", 2);\n populateRaidInfoForBoss(pokemonRepository, \"Venomoth\", \"1107\", 2);\n populateRaidInfoForBoss(pokemonRepository, \"Combusken\", \"841\", 2);\n populateRaidInfoForBoss(pokemonRepository, \"Primeape\", \"1203\", 2);\n populateRaidInfoForBoss(pokemonRepository, \"Kirlia\", \"481\", 2);\n populateRaidInfoForBoss(pokemonRepository, \"Roselia\", \"1068\", 2);\n populateRaidInfoForBoss(pokemonRepository, \"Lanturn\", \"1191\", 2);\n populateRaidInfoForBoss(pokemonRepository, \"Grovyle\", \"956\", 2);\n populateRaidInfoForBoss(pokemonRepository, \"Marshtomp\", \"1015\", 2);\n populateRaidInfoForBoss(pokemonRepository, \"Monferno\", \"899\", 2);\n populateRaidInfoForBoss(pokemonRepository, \"Pineco\", \"633\", 2);\n populateRaidInfoForBoss(pokemonRepository, \"Masquerain\", \"1297\", 2);\n populateRaidInfoForBoss(pokemonRepository, \"Combee\", \"282\", 2);\n populateRaidInfoForBoss(pokemonRepository, \"Gligar\", \"1061\", 2);\n populateRaidInfoForBoss(pokemonRepository, \"Houndour\", \"705\", 2);\n populateRaidInfoForBoss(pokemonRepository, \"Feebas\", \"157\", 2);\n populateRaidInfoForBoss(pokemonRepository, \"Yamask\", \"561\", 2);\n populateRaidInfoForBoss(pokemonRepository, \"Anorith\", \"874\", 2);\n populateRaidInfoForBoss(pokemonRepository, \"Lileep\", \"738\", 2);\n populateRaidInfoForBoss(pokemonRepository, \"Kingler\", \"1616\", 2);\n populateRaidInfoForBoss(pokemonRepository, \"Magneton\", \"1420\", 2);\n populateRaidInfoForBoss(pokemonRepository, \"Grotle\", \"1080\", 2);\n populateRaidInfoForBoss(pokemonRepository, \"Grumpig\", \"1354\", 2);\n populateRaidInfoForBoss(pokemonRepository, \"Swellow\", \"1097\", 2);\n populateRaidInfoForBoss(pokemonRepository, \"Fearow\", \"1141\", 2);\n\n // Tier 3\n populateRaidInfoForBoss(pokemonRepository, \"Azumarill\", \"849\", 3);\n populateRaidInfoForBoss(pokemonRepository, \"Aerodactyl\", \"1490\", 3);\n populateRaidInfoForBoss(pokemonRepository, \"Jynx\", \"1435\", 3);\n populateRaidInfoForBoss(pokemonRepository, \"Piloswine\", \"1305\", 3);\n populateRaidInfoForBoss(pokemonRepository, \"Starmie\", \"1476\", 3);\n populateRaidInfoForBoss(pokemonRepository, \"Claydol\", \"1126\", 3);\n populateRaidInfoForBoss(pokemonRepository, \"Pinsir\", \"1583\", 3);\n populateRaidInfoForBoss(pokemonRepository, \"Granbull\", \"1394\", 3);\n populateRaidInfoForBoss(pokemonRepository, \"Aerodactyl\", \"1490\", 3);\n populateRaidInfoForBoss(pokemonRepository, \"Kabutops\", \"1438\", 3);\n populateRaidInfoForBoss(pokemonRepository, \"Onix\", \"572\", 3);\n populateRaidInfoForBoss(pokemonRepository, \"Breloom\", \"1375\", 2);\n populateRaidInfoForBoss(pokemonRepository, \"Hitmonlee\", \"1375\", 3);\n populateRaidInfoForBoss(pokemonRepository, \"Hitmonchan\", \"1199\", 3);\n populateRaidInfoForBoss(pokemonRepository, \"Raichu\", \"1247\", 3);\n populateRaidInfoForBoss(pokemonRepository, \"Donphan\", \"1722\", 3);\n populateRaidInfoForBoss(pokemonRepository, \"Tangela\", \"1262\", 3);\n populateRaidInfoForBoss(pokemonRepository, \"Sharpedo\", \"1246\", 3);\n populateRaidInfoForBoss(pokemonRepository, \"Skarmory\", \"1204\", 3);\n populateRaidInfoForBoss(pokemonRepository, \"Espeon\", \"1811\", 3);\n populateRaidInfoForBoss(pokemonRepository, \"Umbreon\", \"1221\", 3);\n populateRaidInfoForBoss(pokemonRepository, \"Crawdaunt\", \"1413\", 3);\n populateRaidInfoForBoss(pokemonRepository, \"Lunatone\", \"1330\", 3);\n populateRaidInfoForBoss(pokemonRepository, \"Solrock\", \"1330\", 3);\n populateRaidInfoForBoss(pokemonRepository, \"Shuckle\", \"231\", 3);\n populateRaidInfoForBoss(pokemonRepository, \"Skuntank\", \"1347\", 3);\n populateRaidInfoForBoss(pokemonRepository, \"Persian\", \"965\", 3);\n populateRaidInfoForBoss(pokemonRepository, \"Mantine\", \"1204\", 3);\n populateRaidInfoForBoss(pokemonRepository, \"Pidgeot\", \"1216\", 3);\n populateRaidInfoForBoss(pokemonRepository, \"Hippowdon\", \"1763\", 3);\n populateRaidInfoForBoss(pokemonRepository, \"Meganium\", \"1377\", 3);\n\n // Tier 4\n populateRaidInfoForBoss(pokemonRepository, \"Feraligatr\", \"1554\", 4);\n populateRaidInfoForBoss(pokemonRepository, \"Absol\", \"1443\", 4);\n populateRaidInfoForBoss(pokemonRepository, \"Aggron\", \"1714\", 4);\n populateRaidInfoForBoss(pokemonRepository, \"Salamence\", \"2018\", 4);\n populateRaidInfoForBoss(pokemonRepository, \"Walrein\", \"1489\", 4);\n populateRaidInfoForBoss(pokemonRepository, \"Houndoom\", \"1445\", 4);\n populateRaidInfoForBoss(pokemonRepository, \"Togetic\", \"881\", 4);\n populateRaidInfoForBoss(pokemonRepository, \"Metagross\", \"2166\", 4);\n populateRaidInfoForBoss(pokemonRepository, \"Shiftry\", \"1333\", 4);\n populateRaidInfoForBoss(pokemonRepository, \"Ursaring\", \"1682\", 4);\n populateRaidInfoForBoss(pokemonRepository, \"Ninjask\", \"1125\", 4);\n populateRaidInfoForBoss(pokemonRepository, \"Registeel\", \"1398\", 4);\n populateRaidInfoForBoss(pokemonRepository, \"Regice\", \"1784\", 4);\n populateRaidInfoForBoss(pokemonRepository, \"Regirock\", \"1784\", 4);\n populateRaidInfoForBoss(pokemonRepository, \"Meowth\", \"427\", 4);\n populateRaidInfoForBoss(pokemonRepository, \"Excadrill\", \"1853\", 4);\n populateRaidInfoForBoss(pokemonRepository, \"Staraptor\", \"1614\", 4);\n populateRaidInfoForBoss(pokemonRepository, \"Dragonite\", \"2167\", 4);\n\n // Tier 5\n populateRaidInfoForBoss(pokemonRepository, \"Groudon\", \"2328\", 5);\n populateRaidInfoForBoss(pokemonRepository, \"Latios\", \"2082\", 5);\n populateRaidInfoForBoss(pokemonRepository, \"Kyogre\", \"2328\", 5);\n populateRaidInfoForBoss(pokemonRepository, \"Rayquaza\", \"2083\", 5);\n populateRaidInfoForBoss(pokemonRepository, \"Latias\", \"1929\", 5);\n populateRaidInfoForBoss(pokemonRepository, \"Mew\", \"1766\", 5);\n populateRaidInfoForBoss(pokemonRepository, \"Celebi\", \"1766\", 5);\n populateRaidInfoForBoss(pokemonRepository, \"Giratina\", \"2105\", 5);\n populateRaidInfoForBoss(pokemonRepository, \"Palkia\", \"2280\", 5);\n populateRaidInfoForBoss(pokemonRepository, \"Dialga\", \"2307\", 5);\n populateRaidInfoForBoss(pokemonRepository, \"Cresselia\", \"1633\", 5);\n populateRaidInfoForBoss(pokemonRepository, \"Heatran\", \"2145\", 5);\n populateRaidInfoForBoss(pokemonRepository, \"Deoxys\", \"1645\", 5);\n populateRaidInfoForBoss(pokemonRepository, \"Uxie\", \"1442\", 5);\n populateRaidInfoForBoss(pokemonRepository, \"Mesprit\", \"1669\", 5);\n populateRaidInfoForBoss(pokemonRepository, \"Azelf\", \"1834\", 5);\n populateRaidInfoForBoss(pokemonRepository, \"Darkrai\", \"2136\", 5);\n populateRaidInfoForBoss(pokemonRepository, \"Cobalion\", \"1727\", 5);\n populateRaidInfoForBoss(pokemonRepository, \"Terrakion\", \"2113\", 5);\n populateRaidInfoForBoss(pokemonRepository, \"Virizion\", \"1727\", 5);\n populateRaidInfoForBoss(pokemonRepository, \"Regigigas\", \"2478\", 5);\n populateRaidInfoForBoss(pokemonRepository, \"Tornadus\", \"1911\", 5);\n populateRaidInfoForBoss(pokemonRepository, \"Thundurus\", \"1911\", 5);\n populateRaidInfoForBoss(pokemonRepository, \"Landorus\", \"2050\", 5);\n populateRaidInfoForBoss(pokemonRepository, \"Zacian\", \"2188\", 5);\n populateRaidInfoForBoss(pokemonRepository, \"Zamazenta\", \"2188\", 5);\n\n LOGGER.info(\"Configured \" + pokemonRaidInfo.size() + \" raid boss information entries.\");\n }\n\n private void populateRaidInfoForBoss(PokemonRepository pokemonRepository, String pokemonName, String maxCp, int bossTier) {\n final Pokemon pokemon = pokemonRepository.getByName(pokemonName.toUpperCase());\n if (pokemon == null) {\n LOGGER.warn(\"Exception when getting pokemon by name \" + pokemonName + \" - needs to be added to repo data file.\");\n return;\n }\n pokemonRaidInfo.put(pokemonName.toUpperCase(), new PokemonRaidInfo(pokemon, maxCp, bossTier));\n }\n\n public RaidBossCounters getCounters(Pokemon pokemon) {\n Validate.notNull(pokemon, \"Input pokemon cannot be null!\");\n final RaidBossCounters counters = this.counters.get(pokemon.getName().toUpperCase());\n return counters;\n }\n\n public String getMaxCp(Pokemon pokemon) {\n final PokemonRaidInfo pokemonRaidInfo = this.pokemonRaidInfo.get(pokemon.getName().toUpperCase());\n if (pokemonRaidInfo == null) {\n return null;\n }\n final String maxCp = String.valueOf(pokemonRaidInfo.getMaxCp());\n if (maxCp != null && (!maxCp.isEmpty())) {\n return maxCp;\n } else {\n return null;\n }\n }\n\n public PokemonRaidInfo getRaidInfo(Pokemon pokemon) {\n final String pokemonName = pokemon.getName().toUpperCase();\n return pokemonRaidInfo.get(pokemonName);\n }\n}",
"public class RaidBossCounters {\n private Pokemon pokemon;\n private Set<CounterPokemon> supremeCounters = new LinkedHashSet<>();\n private Set<CounterPokemon> goodCounters = new LinkedHashSet<>();\n\n public RaidBossCounters(Pokemon pokemon, Set<CounterPokemon> supremeCounters, Set<CounterPokemon> goodCounters) {\n this.pokemon = pokemon;\n this.supremeCounters.addAll(supremeCounters);\n this.goodCounters.addAll(goodCounters);\n }\n\n public Set<CounterPokemon> getSupremeCounters() {\n if (supremeCounters != null) {\n return Collections.unmodifiableSet(supremeCounters);\n } else {\n return Collections.EMPTY_SET;\n }\n\n }\n\n public Set<CounterPokemon> getGoodCounters() {\n if (goodCounters != null) {\n return Collections.unmodifiableSet(goodCounters);\n } else {\n return Collections.EMPTY_SET;\n }\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (!(o instanceof RaidBossCounters)) return false;\n\n RaidBossCounters that = (RaidBossCounters) o;\n\n if (pokemon != null ? !pokemon.equals(that.pokemon) : that.pokemon != null) return false;\n if (supremeCounters != null ? !supremeCounters.equals(that.supremeCounters) : that.supremeCounters != null)\n return false;\n return goodCounters != null ? goodCounters.equals(that.goodCounters) : that.goodCounters == null;\n }\n\n @Override\n public int hashCode() {\n int result = pokemon != null ? pokemon.hashCode() : 0;\n result = 31 * result + (supremeCounters != null ? supremeCounters.hashCode() : 0);\n result = 31 * result + (goodCounters != null ? goodCounters.hashCode() : 0);\n return result;\n }\n\n @Override\n public String toString() {\n return \"RaidBossCounters{\" +\n \"pokemon=\" + pokemon +\n \", supremeCounters=\" + supremeCounters +\n \", goodCounters=\" + goodCounters +\n '}';\n }\n}",
"public class CounterPokemon {\n private final String counterPokemonName;\n private final Set<String> moves;\n\n public CounterPokemon(String counterPokemonName, Set<String> moves) {\n this.counterPokemonName = counterPokemonName;\n this.moves = moves;\n }\n\n public String getCounterPokemonName() {\n return counterPokemonName;\n }\n\n public Set<String> getMoves() {\n return moves;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (!(o instanceof CounterPokemon)) return false;\n\n CounterPokemon that = (CounterPokemon) o;\n\n if (counterPokemonName != null ? !counterPokemonName.equals(that.counterPokemonName) : that.counterPokemonName != null)\n return false;\n return moves != null ? moves.equals(that.moves) : that.moves == null;\n }\n\n @Override\n public int hashCode() {\n int result = counterPokemonName != null ? counterPokemonName.hashCode() : 0;\n result = 31 * result + (moves != null ? moves.hashCode() : 0);\n return result;\n }\n\n @Override\n public String toString() {\n return counterPokemonName;\n }\n}",
"@Entity\n@Table(indexes = @Index(columnList = \"server\"), name=\"config\")\npublic class Config {\n @Id\n @Column(nullable = false, unique = true)\n private String id;\n @Column(nullable = false, unique = true)\n private String server;\n @Column(nullable = false)\n private String region;\n @Column(nullable = false)\n private Boolean replyInDmWhenPossible = false;\n @Column(nullable = false)\n private String locale;\n @Column\n private Boolean giveHelp = false;\n @Column\n private Boolean pinGroups = true;\n @Column\n private String overviewMessageId;\n @Column\n private String modPermissionGroup;\n @Column\n private FeedbackStrategy feedbackStrategy = FeedbackStrategy.DEFAULT;\n @Column\n private RaidGroupCreationStrategy groupCreationStrategy = RaidGroupCreationStrategy.SAME_CHANNEL;\n @Column\n private String groupCreationChannel;\n @Column\n private Boolean useBotIntegration = false;\n\n // For JPA\n protected Config() {\n }\n\n public Config(String region, Boolean replyInDmWhenPossible, Locale locale, String server) {\n id = UUID.randomUUID().toString();\n Validate.notEmpty(region);\n Validate.notEmpty(server);\n this.region = region.toLowerCase();\n this.replyInDmWhenPossible = replyInDmWhenPossible;\n setLocale(locale);\n this.server = server.toLowerCase();\n }\n\n public Config(String region, Boolean replyInDmWhenPossible, String server) {\n this(region, replyInDmWhenPossible, LocaleService.DEFAULT, server);\n }\n\n public Config(String region, String server) {\n this(region, false, server);\n }\n\n public String getServer() {\n return server;\n }\n\n public void setServer(String server) {\n this.server = server;\n }\n\n public String getRegion() {\n return region;\n }\n\n public void setRegion(String region) {\n this.region = region;\n }\n\n public Boolean getReplyInDmWhenPossible() {\n return replyInDmWhenPossible;\n }\n\n public void setReplyInDmWhenPossible(Boolean replyInDmWhenPossible) {\n this.replyInDmWhenPossible = replyInDmWhenPossible;\n }\n\n public Boolean getGiveHelp() {\n return giveHelp;\n }\n\n public void setGiveHelp(Boolean giveHelp) {\n this.giveHelp = giveHelp;\n }\n\n public Boolean isPinGroups() {\n return pinGroups;\n }\n\n public void setPinGroups(Boolean pinGroups) {\n this.pinGroups = pinGroups;\n }\n\n public Boolean useBotIntegration() {\n if (useBotIntegration != null) {\n return useBotIntegration;\n } else {\n return false;\n }\n }\n\n public void setUseBotIntegration(Boolean useBotIntegration) {\n this.useBotIntegration = useBotIntegration;\n }\n\n public Locale getLocale() {\n if (locale != null) {\n return new Locale(locale);\n } else {\n return LocaleService.DEFAULT;\n }\n }\n\n public void setLocale(Locale locale) {\n Validate.notNull(locale);\n this.locale = locale.getLanguage();\n }\n\n public String getId() {\n return id;\n }\n\n public void setOverviewMessageId(String overviewMessageId) {\n this.overviewMessageId = overviewMessageId;\n }\n\n public String getOverviewMessageId() {\n return overviewMessageId;\n }\n\n public String getModPermissionGroup() {\n return modPermissionGroup;\n }\n\n public void setModPermissionGroup(String modPermissionGroup) {\n this.modPermissionGroup = modPermissionGroup;\n }\n\n public FeedbackStrategy getFeedbackStrategy() {\n return feedbackStrategy == null ? FeedbackStrategy.DEFAULT : feedbackStrategy;\n }\n\n public void setFeedbackStrategy(FeedbackStrategy feedbackStrategy) {\n this.feedbackStrategy = feedbackStrategy;\n }\n\n public RaidGroupCreationStrategy getGroupCreationStrategy() {\n return groupCreationStrategy;\n }\n\n public void setGroupCreationStrategy(RaidGroupCreationStrategy groupCreationStrategy) {\n this.groupCreationStrategy = groupCreationStrategy;\n }\n\n public String getGroupCreationChannel() {\n return groupCreationChannel;\n }\n\n public void setGroupCreationChannel(String groupCreationChannel) {\n this.groupCreationChannel = groupCreationChannel;\n }\n\n public MessageChannel getGroupCreationChannel(Guild guild) {\n if (guild == null) {\n return null;\n }\n for (MessageChannel c : guild.getTextChannels()) {\n if (c.getName().equalsIgnoreCase(groupCreationChannel)) {\n return c;\n }\n }\n return null;\n }\n\n public enum FeedbackStrategy {\n DEFAULT, KEEP_ALL, REMOVE_ALL_EXCEPT_MAP // This actually also removes maps, but after some time (after wishes from users)\n }\n\n public enum RaidGroupCreationStrategy {\n SAME_CHANNEL, NAMED_CHANNEL // Create group in named group, not necessarily the channel where command originated\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (!(o instanceof Config)) return false;\n\n Config config = (Config) o;\n\n if (id != null ? !id.equals(config.id) : config.id != null) return false;\n if (server != null ? !server.equals(config.server) : config.server != null) return false;\n if (region != null ? !region.equals(config.region) : config.region != null) return false;\n if (replyInDmWhenPossible != null ? !replyInDmWhenPossible.equals(config.replyInDmWhenPossible) : config.replyInDmWhenPossible != null)\n return false;\n if (locale != null ? !locale.equals(config.locale) : config.locale != null) return false;\n if (giveHelp != null ? !giveHelp.equals(config.giveHelp) : config.giveHelp != null) return false;\n if (pinGroups != null ? !pinGroups.equals(config.pinGroups) : config.pinGroups != null) return false;\n if (overviewMessageId != null ? !overviewMessageId.equals(config.overviewMessageId) : config.overviewMessageId != null)\n return false;\n if (modPermissionGroup != null ? !modPermissionGroup.equals(config.modPermissionGroup) : config.modPermissionGroup != null)\n return false;\n if (feedbackStrategy != config.feedbackStrategy) return false;\n if (groupCreationStrategy != config.groupCreationStrategy) return false;\n if (groupCreationChannel != null ? !groupCreationChannel.equals(config.groupCreationChannel) : config.groupCreationChannel != null)\n return false;\n return useBotIntegration != null ? useBotIntegration.equals(config.useBotIntegration) : config.useBotIntegration == null;\n }\n\n @Override\n public int hashCode() {\n int result = id != null ? id.hashCode() : 0;\n result = 31 * result + (server != null ? server.hashCode() : 0);\n result = 31 * result + (region != null ? region.hashCode() : 0);\n result = 31 * result + (replyInDmWhenPossible != null ? replyInDmWhenPossible.hashCode() : 0);\n result = 31 * result + (locale != null ? locale.hashCode() : 0);\n result = 31 * result + (giveHelp != null ? giveHelp.hashCode() : 0);\n result = 31 * result + (pinGroups != null ? pinGroups.hashCode() : 0);\n result = 31 * result + (overviewMessageId != null ? overviewMessageId.hashCode() : 0);\n result = 31 * result + (modPermissionGroup != null ? modPermissionGroup.hashCode() : 0);\n result = 31 * result + (feedbackStrategy != null ? feedbackStrategy.hashCode() : 0);\n result = 31 * result + (groupCreationStrategy != null ? groupCreationStrategy.hashCode() : 0);\n result = 31 * result + (groupCreationChannel != null ? groupCreationChannel.hashCode() : 0);\n result = 31 * result + (useBotIntegration != null ? useBotIntegration.hashCode() : 0);\n return result;\n }\n\n @Override\n public String toString() {\n return \"Config{\" +\n \"server='\" + server + '\\'' +\n \", region='\" + region + '\\'' +\n \", replyInDm=\" + replyInDmWhenPossible +\n \", locale='\" + locale + '\\'' +\n \", giveHelp=\" + giveHelp +\n \", pinGroups=\" + pinGroups +\n \", overview='\" + overviewMessageId + '\\'' +\n \", modGroup='\" + modPermissionGroup + '\\'' +\n \", feedback=\" + feedbackStrategy +\n \", groupCreationStrategy=\" + groupCreationStrategy +\n \", groupCreationChannel='\" + groupCreationChannel + '\\'' +\n \", useBotIntegration=\" + useBotIntegration +\n '}';\n }\n}",
"@Transactional(propagation = Propagation.REQUIRES_NEW)\npublic interface ServerConfigRepository extends JpaRepository<Config, String> {\n Config findByServer(String server);\n\n default Config getConfigForServer(String server) {\n final Config config = findByServer(server);\n return config;\n }\n\n default Map<String, Config> getAllConfig() {\n Map<String, Config> configs = new HashMap<>();\n for (Config config : findAll()) {\n configs.put(config.getServer(), config);\n }\n return configs;\n }\n\n @Transactional(propagation = Propagation.REQUIRES_NEW)\n default void setOverviewMessageIdForServer(String server, String overviewMessageId) {\n final Config config = findByServer(server);\n config.setOverviewMessageId(overviewMessageId);\n save(config);\n }\n}"
] | import com.jagrosh.jdautilities.command.CommandEvent;
import com.jagrosh.jdautilities.command.CommandListener;
import org.apache.commons.lang3.StringUtils;
import pokeraidbot.Utils;
import pokeraidbot.domain.config.LocaleService;
import pokeraidbot.domain.pokemon.Pokemon;
import pokeraidbot.domain.pokemon.PokemonRepository;
import pokeraidbot.domain.raid.PokemonRaidStrategyService;
import pokeraidbot.domain.raid.RaidBossCounters;
import pokeraidbot.infrastructure.CounterPokemon;
import pokeraidbot.infrastructure.jpa.config.Config;
import pokeraidbot.infrastructure.jpa.config.ServerConfigRepository;
import java.util.*;
import java.util.stream.Collectors; | package pokeraidbot.commands;
/**
* !raid vs (boss name)
*/
public class PokemonVsCommand extends ConfigAwareCommand {
private final PokemonRaidStrategyService raidInfoService;
private final LocaleService localeService;
private final PokemonRepository repo;
public PokemonVsCommand(PokemonRepository repo, PokemonRaidStrategyService raidInfoService,
LocaleService localeService, ServerConfigRepository serverConfigRepository, CommandListener commandListener) {
super(serverConfigRepository, commandListener, localeService);
this.raidInfoService = raidInfoService;
this.localeService = localeService;
this.name = "vs";
this.help = localeService.getMessageFor(LocaleService.VS_HELP, LocaleService.DEFAULT);
this.repo = repo;
}
@Override | protected void executeWithConfig(CommandEvent commandEvent, Config config) { | 7 |
feedzai/fos-core | fos-api/src/main/java/com/feedzai/fos/server/remote/api/FOSManagerAdapter.java | [
"public class FOSException extends Exception {\n public FOSException(String message) {\n super(message);\n }\n\n /**\n * Create an exception with a nested throwable and customized message\n * @param message exception message\n * @param t nested throable\n */\n public FOSException(String message, Throwable t) {\n super(message, t);\n }\n\n /**\n * Create an exception with a nested throwable. Throwable message used as exception message\n * @param e\n */\n\n public FOSException(Throwable e) {\n super(e.getMessage(), e);\n }\n}",
"public class KryoScorer implements Scorer {\n private final static Logger logger = LoggerFactory.getLogger(KryoScorer.class);\n\n List<RemoteConnection> remoteConnections = new ArrayList<>();\n private final String host;\n private final int port;\n\n\n public KryoScorer(String host, int port) {\n this.host = host;\n this.port = port;\n }\n\n @Override\n public List<double[]> score(List<UUID> modelIds, Object[] scorable) throws FOSException {\n RemoteConnection con = null;\n try {\n con = getConnection();\n List<double[]> scores = con.score(modelIds, scorable);\n return scores;\n } catch (Exception e) {\n throw new FOSException(e.getMessage(), e);\n } finally {\n releaseConnection(con);\n }\n }\n\n @Override\n public List<double[]> score(UUID modelId, List<Object[]> scorables) throws FOSException {\n RemoteConnection con = null;\n try {\n con = getConnection();\n List<double[]> scores = con.score(modelId, scorables);\n return scores;\n } catch (Exception e) {\n throw new FOSException(e.getMessage(), e);\n } finally {\n releaseConnection(con);\n }\n }\n\n @Override\n public double[] score(UUID modelId, Object[] scorable) throws FOSException {\n RemoteConnection con = null;\n try {\n con = getConnection();\n double[] scores = con.score(modelId, scorable);\n return scores;\n } catch (Exception e) {\n throw new FOSException(e.getMessage(), e);\n } finally {\n releaseConnection(con);\n }\n }\n\n\n @Override\n public void close() throws FOSException {\n try {\n for (RemoteConnection connection : remoteConnections) {\n connection.close();\n }\n } catch (Exception e) {\n throw new FOSException(e.getMessage(), e);\n }\n }\n\n /**\n * Gets a connection from the connection pool or creates a new connection\n * if needed\n * @return RemoteConnection\n * @throws IOException if unable to create a new connection\n */\n private RemoteConnection getConnection() throws IOException {\n synchronized (remoteConnections) {\n int size = remoteConnections.size();\n if (size != 0) {\n return remoteConnections.remove(size - 1);\n }\n }\n return new RemoteConnection(host, port);\n }\n\n /**\n * Returns a connection back to the pool\n * to be reused later on.\n *\n * @param con RemoteConnection to be returned to the pool. Null values are ignored\n */\n private void releaseConnection(RemoteConnection con) {\n if (con == null) {\n return;\n }\n synchronized (remoteConnections) {\n remoteConnections.add(con);\n }\n }\n\n /**\n * This class implements the internal Kryo scoring backend\n */\n private static class RemoteConnection implements Scorer {\n /*\n * Buffer size in bytes to be used for Kryo i/o.\n * It should be noted that (beyond reasonable values)\n * this does not impose any limits to the size of objects to be read/written\n * if the internal buffer is exausted/underflows, kryo will flush or read\n * more data from the associated inputstream.\n *\n */\n public static final int BUFFER_SIZE = 1024; // bytes\n final Socket s; // socket that represents client connection\n InputStream is;\n OutputStream os;\n Kryo kryo;\n Input input;\n Output output;\n\n\n RemoteConnection(String host, int port) throws IOException {\n s = new Socket(host, port);\n // Disable naggle Algorithm to decrease latency\n s.setTcpNoDelay(true);\n is = s.getInputStream();\n os = s.getOutputStream();\n kryo = new Kryo();\n kryo.addDefaultSerializer(UUID.class, new CustomUUIDSerializer());\n input = new Input(BUFFER_SIZE);\n output = new Output(BUFFER_SIZE);\n input.setInputStream(is);\n output.setOutputStream(os);\n }\n\n\n @Override\n public List<double[]> score(List<UUID> modelIds, Object[] scorable) throws FOSException {\n try {\n ScoringRequestEnvelope envelope = new ScoringRequestEnvelope(modelIds, scorable);\n kryo.writeObject(output, envelope);\n output.flush();\n os.flush();\n return kryo.readObject(input, ArrayList.class);\n } catch (Exception e) {\n throw new FOSException(\"Unable to score\", e);\n }\n }\n\n @Override\n public List<double[]> score(UUID modelId, List<Object[]> scorables) throws FOSException {\n throw new FOSException(\"Not implemented\");\n }\n\n @Override\n public double[] score(UUID modelId, Object[] scorabl) throws FOSException {\n throw new FOSException(\"Not implemented\");\n }\n\n @Override\n public void close() throws FOSException {\n input.close();\n output.close();\n try {\n s.close();\n } catch (IOException e) {\n throw new FOSException(e.getMessage(), e);\n }\n }\n }\n}",
"public interface Manager {\n\n /**\n * Adds a new model with the given configuration and using the given serialized classifier.\n *\n * @param config The configuration of the model.\n * @param model A {@link Model representation of the model}.\n * @return the id of the new model\n * @throws FOSException when creating the classifier was not possible\n */\n UUID addModel(ModelConfig config, Model model) throws FOSException;\n\n /**\n * Adds a new model with the given configuration and using a local classifier source.\n *\n * @param config The configuration of the model.\n * @param descriptor the {@link ModelDescriptor} describing the classifier\n * @return the id of the new models\n * @throws FOSException when creating the classifier was not possible\n */\n UUID addModel(ModelConfig config, @NotBlank ModelDescriptor descriptor) throws FOSException;\n\n /**\n * Removes the model identified by <code>modelId</code> from the list of active scorers (does not delete classifier file).\n *\n * @param modelId the id of the model to remove\n * @throws FOSException when removing the model was not possible\n */\n void removeModel(UUID modelId) throws FOSException;\n\n /**\n * Reconfigures the model identified by <code>modelId</code> with the given configuration.\n *\n * @param modelId the id of the model to update\n * @param config the new configuration of the model\n * @throws FOSException when reconfiguring the model was not possible\n */\n void reconfigureModel(UUID modelId,ModelConfig config) throws FOSException;\n\n /**\n * Reconfigures the model identified by <code>modelId</code> with the given configuration.\n * <p/>\n * Reloads the model now using the classifier <code>model</code> (does not delete previous classifier file).\n *\n * @param modelId The id of the model to update.\n * @param config The new configuration of the model.\n * @param model A {@link Model representation of the model}.\n * @throws FOSException when reconfiguring the model was not possible\n */\n void reconfigureModel(UUID modelId,ModelConfig config, Model model) throws FOSException;\n\n /**\n * Reconfigures the model identified by <code>modelId</code> with the given configuration.\n * <p/>\n * Reloads the model now using the classifier in the local file <code>localFileName</code> (does not delete previous classifier file).\n *\n * @param modelId the id of the model to update\n * @param config the new configuration of the model\n * @param descriptor the {@link ModelDescriptor} describing the classifier\n * @throws FOSException when reconfiguring the model was not possible\n */\n void reconfigureModel(UUID modelId,ModelConfig config, @NotBlank ModelDescriptor descriptor) throws FOSException;\n\n /**\n * Lists the models configured in the system.\n *\n * @return a map of <code>modelId</code> to model configuration\n * @throws FOSException when listing the maps was not possible\n */\n @NotNull\n Map<UUID, ? extends ModelConfig> listModels() throws FOSException;\n\n /**\n * Gets a scorer loaded with all the active models.\n *\n * @return a scorer\n * @throws FOSException when loading the scorer was not possible\n */\n @NotNull\n Scorer getScorer() throws FOSException;\n\n /**\n * Trains a new classifier with the given configuration and using the givren <code>instances</code>.\n * <p/> Automatically add the new model to the existing scorer.\n *\n * @param config the model configuration\n * @param instances the training instances\n * @return the id of the new model\n * @throws FOSException when training was not possible\n */\n UUID trainAndAdd(ModelConfig config, List<Object[]> instances) throws FOSException;\n\n\n /**\n * Trains a new classifier with the given configuration and using the <code>instances</code>.\n * in a CSV encoded file\n * <p/> Automatically add the new model to the existing scorer.\n *\n * @param config the model configuration\n * @param path the training instances\n * @return the id of the new model\n * @throws FOSException when training was not possible\n */\n UUID trainAndAddFile(ModelConfig config, String path) throws FOSException;\n\n /**\n * Trains a new classifier with the given configuration and using the given <code>instances</code>.\n *\n * @param config the model configuration\n * @param instances the training instances\n * @return A {@link Model representation of the model}.\n * @throws FOSException when training was not possible\n */\n @NotNull\n Model train(ModelConfig config, List<Object[]> instances) throws FOSException;\n\n /**\n * Compute the feature importance for the model.\n *\n * @param uuid The uuid of the model whose feature importance should be computed.\n * @param instances An optional set of instances that can be used to compute feature importance.\n * This set of instances should not be the ones used for training.\n * @param seed The random number generator seed.\n * @return Aan array with the feature importance, one element for each feature.\n * @throws FOSException If the underlying model does not support computing feature importance.\n * @since 1.0.9\n */\n @NotNull\n double[] featureImportance(UUID uuid, Optional<List<Object[]>> instances, long seed) throws FOSException;\n\n /**\n * Trains a new classifier with the given configuration and using the given <code>instances</code>.\n *\n * @param config the model configuration\n * @param path File with the training instances\n * @return A {@link Model representation of the model}.\n * @throws FOSException when training was not possible\n */\n @NotNull\n public Model trainFile(ModelConfig config, String path) throws FOSException;\n\n\n /**\n * Frees any resources allocated to this manager.\n *\n * @throws FOSException when closing resources was not possible\n */\n void close() throws FOSException;\n\n\n /**\n * Saves a UUID identified classifier to a given savepath\n * @param uuid model uuid\n * @param savepath export model path\n */\n void save(UUID uuid, String savepath) throws FOSException;\n\n /**\n * Saves a UUID identified classifier as PMML to a given {@code filePath}.\n * </p>\n * The {@code filePath} will be the absolute file path where the model will be saved to.\n * <p/>\n * If the {@code compress} flag is set to {@code true}, the file will be saved in a GZipped compressed format.\n * Concrete implementations may differ on how they handle the compression.\n *\n * @param uuid The classifier's UUID.\n * @param filePath The absolute file path to which save the PMML representation of the classifier.\n * @param compress {@code true} to compress the resulting file to GZip, or {@code false} to save it as a raw PMML file.\n * @throws FOSException If if failed to read the classifier or export it to PMML.\n * @since @since 1.0.4\n */\n void saveAsPMML(UUID uuid, String filePath, boolean compress) throws FOSException;\n}",
"public interface Model extends Serializable {\n\n}",
"public final class ModelConfig implements Serializable {\n private List<Attribute> attributes = new ArrayList<>();\n private Map<String, String> properties = new HashMap<>();\n /**\n * Flag to indicate if the model should be stored by FOS.\n */\n private boolean storeModel = true;\n\n public ModelConfig() {\n }\n\n /**\n * Creates a new configuration with the given <code>attributes</code> and <code>properties</code>.\n *\n * @param attributes the list of instances this model supports\n * @param properties a list of custom properties to send to the concrete implementation )\n */\n public ModelConfig(@NotEmpty List<Attribute> attributes, Map<String, String> properties) {\n checkNotNull(properties, \"Custom properties cannot be null\");\n notEmpty(attributes, \"Instance fields cannot be empty\");\n\n this.attributes.addAll(attributes);\n this.properties.putAll(properties);\n }\n\n /**\n * Gets the instance fields of this configuration (unmodifiable).\n *\n * @return the list of fields\n */\n @NotEmpty\n public List<Attribute> getAttributes() {\n if (attributes == null) {\n this.attributes = new ArrayList<>();\n }\n return attributes;\n }\n\n /**\n * Gets the custom properties of this configuration (unmodifiable).\n *\n * @return a map from custom property name to custom property value\n */\n @NotNull\n public Map<String, String> getProperties() {\n if (this.properties == null) {\n this.properties = new HashMap<>();\n }\n return properties;\n }\n\n /**\n * Updates this model with inputs from the given <code>ModelConfig</code>.\n * <p/>\n * For the <code>InstanceFields</code>, the internal state is clean and the provided <code>ModelConfig.attributes</code> are copied over.\n * For the <code>Properties</code>, the provided <code>ModelConfig.properties</code> overwrite matching existing values (non matching values are kept as is).\n *\n * @param modelConfig the model config that has the information to update this instance\n */\n public void update(ModelConfig modelConfig) {\n checkNotNull(modelConfig, \"Model config cannot be null\");\n\n if (this.equals(modelConfig)) {\n // nothing to update!\n return;\n }\n\n // if the new model instances is empty then do not update\n if (modelConfig.getAttributes().size() != 0) {\n this.attributes.clear();\n this.attributes.addAll(modelConfig.attributes);\n }\n\n /* does not clear properties, only adds */\n this.properties.putAll(modelConfig.getProperties());\n }\n\n /**\n * Add the given property to the current custom properties.\n *\n * @param key the key of the property\n * @param value the value of the property\n * @return the already existing value in the map (or null if it doesn't exist).\n */\n @Nullable\n public String setProperty(@NotBlank String key, String value) {\n return this.properties.put(key, value);\n }\n\n /**\n * Remove the given property from the current custom properties.\n *\n * @param key the key of the property\n * @return the already existing value in the map (or null if it doesn't exist).\n */\n @Nullable\n public String removeProperty(@NotBlank String key) {\n return this.properties.remove(key);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(attributes, properties, storeModel);\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj) {\n return true;\n }\n if (obj == null || getClass() != obj.getClass()) {\n return false;\n }\n final ModelConfig other = (ModelConfig) obj;\n return Objects.equals(this.attributes, other.attributes) && Objects.equals(this.properties, other.properties) && Objects.equals(this.storeModel, other.storeModel);\n }\n\n @Override\n public String toString() {\n return toStringHelper(this)\n .add(\"attributes\", attributes)\n .add(\"properties\", properties)\n .add(\"storeModel\", storeModel)\n .toString();\n }\n\n /**\n * Returns properties as an integer value\n *\n * @param name property name\n * @return property value\n */\n public int getIntProperty(String name, int defaultValue) {\n try {\n return getIntProperty(name);\n } catch (Exception e) {\n return defaultValue;\n }\n }\n\n /**\n * Returns properties as an integer value\n *\n * @param name property name\n * @return property value\n * @throws FOSException if property name is invalid or if it wasn't possible to parse an integer from the value\n */\n public int getIntProperty(String name) throws FOSException {\n checkNotNull(name, \"Configuration option must be defined\");\n notEmpty(name, \"Configuration option must not be blank\");\n String svalue = properties.get(name);\n checkNotNull(svalue, \"Configuration option '\" + name + \"' does not exist\");\n notEmpty(name, \"Configuration option '\" + name + \"' must not be blank\");\n\n int value = 0;\n try {\n value = Integer.parseInt(svalue);\n } catch (NumberFormatException e) {\n throw new FOSException(e.getMessage(), e);\n }\n\n return value;\n }\n\n /**\n * Returns a model property value\n *\n * @param name property name\n * @return property value\n * @throws FOSException if property name is null or empty\n */\n public String getProperty(String name) throws FOSException {\n checkNotNull(name, \"Configuration option must be defined\");\n notEmpty(name, \"Configuration option must not be blank\");\n String svalue = properties.get(name);\n return svalue;\n }\n\n\n /**\n * Gets flag to indicate if the model should be stored by FOS.\n *\n * @return {@code true} if FOS is storing the model, {@code false} otherwise.\n */\n public boolean isStoreModel() {\n return storeModel;\n }\n\n /**\n * Sets flag to indicate if the model should be stored by FOS.\n *\n * @param storeModel {@code true} if FOS should the model, {@code false} otherwise.\n */\n public void setStoreModel(boolean storeModel) {\n this.storeModel = storeModel;\n }\n\n\n /**\n * Reads a model configuration from a file.\n *\n * @param path configuration file path\n * @return ModelConfig read from a file\n * @throws FOSException if it wasn't possible to parse a file\n */\n public static ModelConfig fromFile(String path) throws FOSException {\n ObjectMapper mapper = new ObjectMapper();\n ModelConfig deserialized;\n\n try {\n deserialized = mapper.readValue(new File(path), ModelConfig.class);\n } catch (IOException e) {\n throw new FOSException(e.getMessage(), e);\n }\n\n return deserialized;\n\n }\n\n}",
"public class ModelDescriptor implements Serializable {\n\n /**\n * The absolute path to the file with the model representation.\n */\n private String modelFilePath;\n\n /**\n * The format in which the model is represented (binary, PMML, etc).\n */\n private Format format;\n\n\n /**\n * Private constructor.\n *\n * @param format The {@link Format} in which the model is represented (binary, PMML, etc).\n * @param modelFilePath The path to the file containing the model.\n */\n public ModelDescriptor(Format format, String modelFilePath) {\n this.format = format;\n this.modelFilePath = modelFilePath;\n }\n\n /**\n * Retrieves the path to the file with the model.\n *\n * @return The path to the file with the model.\n */\n public String getModelFilePath() {\n return modelFilePath;\n }\n\n /**\n * Retrieves the format in which the model is represented (binary, PMML, etc).\n *\n * @return The format in which the model is represented (binary, PMML, etc).\n */\n public Format getFormat() {\n return format;\n }\n\n\n /**\n * Possible model representation formats.\n */\n public enum Format {\n /**\n * Binary representation as a serialized byte array.\n */\n BINARY,\n\n /**\n * An XML file containing the PMML representation of the model.\n */\n PMML\n }\n}",
"public interface Scorer {\n /**\n * Score the <code>scorable</code> against the given <code>modelIds</code>.\n * <p/> The score must be between 0 and 1.\n * <p/> The resulting scores are returned by the same order as the <code>modelIds</code> (modelsIds(pos) » return(pos)).\n *\n * @param modelIds the list of models to score\n * @param scorable the instance data to score\n * @return a list of scores double[] where each list position contains the score for each classifier\n * @throws FOSException when scoring was not possible\n */\n @NotNull\n default List<double[]> score(List<UUID> modelIds, Object[] scorable) throws FOSException {\n ImmutableList.Builder<double[]> resultsBuilder = ImmutableList.builder();\n\n for (UUID modelId : modelIds) {\n resultsBuilder.add(score(modelId, scorable));\n }\n\n return resultsBuilder.build();\n }\n\n /**\n * Score all <code>scorables against</code> the given <code>modelId</code>.\n * <p/> The score must be between 0 and 1.\n * <p/> The resulting scores are returned in the same order as the <code>scorables</code> (scorables(pos) » return(pos)).\n *\n * @param modelId the id of the model\n * @param scorables an array of instances to score\n * @return a list of scores double[] where each list position contains the score for each <code>scorable</code>.\n * @throws FOSException when scoring was not possible\n */\n @NotNull\n default List<double[]> score(UUID modelId, List<Object[]> scorables) throws FOSException {\n ImmutableList.Builder<double[]> resultsBuilder = ImmutableList.builder();\n\n for (Object[] scorable : scorables) {\n resultsBuilder.add(score(modelId, scorable));\n }\n\n return resultsBuilder.build();\n }\n\n /**\n * Score a single <code>scorable</code> against the given <code>modelId</code>.\n *\n * <p/> The score must be between 0 and 1.\n *\n * @param modelId the id of the model\n * @param scorable the instance to score\n * @return the scores\n * @throws FOSException when scoring was not possible\n */\n @NotNull\n double[] score(UUID modelId, Object[] scorable) throws FOSException;\n\n /**\n * Frees any resources allocated to this scorer.\n *\n * @throws FOSException when closing resources was not possible\n */\n void close() throws FOSException;\n}"
] | import com.google.common.base.Optional;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import com.feedzai.fos.api.FOSException;
import com.feedzai.fos.api.KryoScorer;
import com.feedzai.fos.api.Manager;
import com.feedzai.fos.api.Model;
import com.feedzai.fos.api.ModelConfig;
import com.feedzai.fos.api.ModelDescriptor;
import com.feedzai.fos.api.Scorer;
import com.feedzai.fos.common.validation.NotBlank; | /*
* $#
* FOS API
*
* Copyright (C) 2013 Feedzai SA
*
* This software is licensed under the Apache License, Version 2.0 (the "Apache License") or the GNU
* Lesser General Public License version 3 (the "GPL License"). You may choose either license to govern
* your use of this software only upon the condition that you accept all of the terms of either the Apache
* License or the LGPL License.
*
* You may obtain a copy of the Apache License and the LGPL License at:
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
* http://www.gnu.org/licenses/lgpl-3.0.txt
*
* Unless required by applicable law or agreed to in writing, software distributed under the Apache License
* or the LGPL License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the Apache License and the LGPL License for the specific language governing
* permissions and limitations under the Apache License and the LGPL License.
* #$
*/
package com.feedzai.fos.server.remote.api;
/**
* FOS Remote manager local adapter.
*
* @author Miguel Duarte ([email protected])
* @since 0.3.0
* @since 0.3.0
*/
public class FOSManagerAdapter implements Manager {
private final KryoScorer kryoScorer;
IRemoteManager manager;
public FOSManagerAdapter(IRemoteManager manager, KryoScorer kryoScorer) {
this.manager = manager;
this.kryoScorer = kryoScorer;
}
@Override
public UUID addModel(ModelConfig modelConfig, Model binary) throws FOSException {
try {
return manager.addModel(modelConfig, binary);
} catch (RemoteException e) {
throw new FOSException(e);
}
}
@Override | public UUID addModel(ModelConfig modelConfig, @NotBlank ModelDescriptor descriptor) throws FOSException { | 5 |
jclehner/AppOpsXposed | src/at/jclehner/appopsxposed/AppListFragment.java | [
"@TargetApi(19)\npublic class AppOpsManagerWrapper extends ObjectWrapper\n{\n\t// These are all ops included in AOSP Lollipop\n\tpublic static final int OP_NONE = getOpInt(\"OP_NONE\");\n\tpublic static final int OP_COARSE_LOCATION = getOpInt(\"OP_COARSE_LOCATION\");\n\tpublic static final int OP_FINE_LOCATION = getOpInt(\"OP_FINE_LOCATION\");\n\tpublic static final int OP_GPS = getOpInt(\"OP_GPS\");\n\tpublic static final int OP_VIBRATE = getOpInt(\"OP_VIBRATE\");\n\tpublic static final int OP_READ_CONTACTS = getOpInt(\"OP_READ_CONTACTS\");\n\tpublic static final int OP_WRITE_CONTACTS = getOpInt(\"OP_WRITE_CONTACTS\");\n\tpublic static final int OP_READ_CALL_LOG = getOpInt(\"OP_READ_CALL_LOG\");\n\tpublic static final int OP_WRITE_CALL_LOG = getOpInt(\"OP_WRITE_CALL_LOG\");\n\tpublic static final int OP_READ_CALENDAR = getOpInt(\"OP_READ_CALENDAR\");\n\tpublic static final int OP_WRITE_CALENDAR = getOpInt(\"OP_WRITE_CALENDAR\");\n\tpublic static final int OP_WIFI_SCAN = getOpInt(\"OP_WIFI_SCAN\");\n\tpublic static final int OP_POST_NOTIFICATION = getOpInt(\"OP_POST_NOTIFICATION\");\n\tpublic static final int OP_NEIGHBORING_CELLS = getOpInt(\"OP_NEIGHBORING_CELLS\");\n\tpublic static final int OP_CALL_PHONE = getOpInt(\"OP_CALL_PHONE\");\n\tpublic static final int OP_READ_SMS = getOpInt(\"OP_READ_SMS\");\n\tpublic static final int OP_WRITE_SMS = getOpInt(\"OP_WRITE_SMS\");\n\tpublic static final int OP_RECEIVE_SMS = getOpInt(\"OP_RECEIVE_SMS\");\n\tpublic static final int OP_RECEIVE_EMERGECY_SMS = getOpInt(\"OP_RECEIVE_EMERGECY_SMS\");\n\tpublic static final int OP_RECEIVE_MMS = getOpInt(\"OP_RECEIVE_MMS\");\n\tpublic static final int OP_RECEIVE_WAP_PUSH = getOpInt(\"OP_RECEIVE_WAP_PUSH\");\n\tpublic static final int OP_SEND_SMS = getOpInt(\"OP_SEND_SMS\");\n\tpublic static final int OP_READ_ICC_SMS = getOpInt(\"OP_READ_ICC_SMS\");\n\tpublic static final int OP_WRITE_ICC_SMS = getOpInt(\"OP_WRITE_ICC_SMS\");\n\tpublic static final int OP_WRITE_SETTINGS = getOpInt(\"OP_WRITE_SETTINGS\");\n\tpublic static final int OP_SYSTEM_ALERT_WINDOW = getOpInt(\"OP_SYSTEM_ALERT_WINDOW\");\n\tpublic static final int OP_ACCESS_NOTIFICATIONS = getOpInt(\"OP_ACCESS_NOTIFICATIONS\");\n\tpublic static final int OP_CAMERA = getOpInt(\"OP_CAMERA\");\n\tpublic static final int OP_RECORD_AUDIO = getOpInt(\"OP_RECORD_AUDIO\");\n\tpublic static final int OP_PLAY_AUDIO = getOpInt(\"OP_PLAY_AUDIO\");\n\tpublic static final int OP_READ_CLIPBOARD = getOpInt(\"OP_READ_CLIPBOARD\");\n\tpublic static final int OP_WRITE_CLIPBOARD = getOpInt(\"OP_WRITE_CLIPBOARD\");\n\tpublic static final int OP_TAKE_MEDIA_BUTTONS = getOpInt(\"OP_TAKE_MEDIA_BUTTONS\");\n\tpublic static final int OP_TAKE_AUDIO_FOCUS = getOpInt(\"OP_TAKE_AUDIO_FOCUS\");\n\tpublic static final int OP_AUDIO_MASTER_VOLUME = getOpInt(\"OP_AUDIO_MASTER_VOLUME\");\n\tpublic static final int OP_AUDIO_VOICE_VOLUME = getOpInt(\"OP_AUDIO_VOICE_VOLUME\");\n\tpublic static final int OP_AUDIO_RING_VOLUME = getOpInt(\"OP_AUDIO_RING_VOLUME\");\n\tpublic static final int OP_AUDIO_MEDIA_VOLUME = getOpInt(\"OP_AUDIO_MEDIA_VOLUME\");\n\tpublic static final int OP_AUDIO_ALARM_VOLUME = getOpInt(\"OP_AUDIO_ALARM_VOLUME\");\n\tpublic static final int OP_AUDIO_NOTIFICATION_VOLUME = getOpInt(\"OP_AUDIO_NOTIFICATION_VOLUME\");\n\tpublic static final int OP_AUDIO_BLUETOOTH_VOLUME = getOpInt(\"OP_AUDIO_BLUETOOTH_VOLUME\");\n\tpublic static final int OP_WAKE_LOCK = getOpInt(\"OP_WAKE_LOCK\");\n\tpublic static final int OP_MONITOR_LOCATION = getOpInt(\"OP_MONITOR_LOCATION\");\n\tpublic static final int OP_MONITOR_HIGH_POWER_LOCATION = getOpInt(\"OP_MONITOR_HIGH_POWER_LOCATION\");\n\tpublic static final int OP_GET_USAGE_STATS = getOpInt(\"OP_GET_USAGE_STATS\");\n\tpublic static final int OP_MUTE_MICROPHONE = getOpInt(\"OP_MUTE_MICROPHONE\");\n\tpublic static final int OP_TOAST_WINDOW = getOpInt(\"OP_TOAST_WINDOW\");\n\tpublic static final int OP_PROJECT_MEDIA = getOpInt(\"OP_PROJECT_MEDIA\");\n\tpublic static final int OP_ACTIVATE_VPN = getOpInt(\"OP_ACTIVATE_VPN\");\n\tpublic static final int OP_WRITE_WALLPAPER = getOpInt(\"OP_WRITE_WALLPAPER\");\n\tpublic static final int OP_ASSIST_STRUCTURE = getOpInt(\"OP_ASSIST_STRUCTURE\");\n\tpublic static final int OP_ASSIST_SCREENSHOT = getOpInt(\"OP_ASSIST_SCREENSHOT\");\n\tpublic static final int OP_READ_PHONE_STATE = getOpInt(\"OP_READ_PHONE_STATE\");\n\tpublic static final int OP_ADD_VOICEMAIL = getOpInt(\"OP_ADD_VOICEMAIL\");\n\tpublic static final int OP_USE_SIP = getOpInt(\"OP_USE_SIP\");\n\tpublic static final int OP_PROCESS_OUTGOING_CALLS = getOpInt(\"OP_PROCESS_OUTGOING_CALLS\");\n\tpublic static final int OP_USE_FINGERPRINT = getOpInt(\"OP_USE_FINGERPRINT\");\n\tpublic static final int OP_BODY_SENSORS = getOpInt(\"OP_BODY_SENSORS\");\n\tpublic static final int OP_READ_CELL_BROADCASTS = getOpInt(\"OP_READ_CELL_BROADCASTS\");\n\tpublic static final int OP_MOCK_LOCATION = getOpInt(\"OP_MOCK_LOCATION\");\n\tpublic static final int OP_READ_EXTERNAL_STORAGE = getOpInt(\"OP_READ_EXTERNAL_STORAGE\");\n\tpublic static final int OP_WRITE_EXTERNAL_STORAGE = getOpInt(\"OP_WRITE_EXTERNAL_STORAGE\");\n\tpublic static final int OP_TURN_SCREEN_ON = getOpInt(\"OP_TURN_SCREEN_ON\");\n\tpublic static final int OP_GET_ACCOUNTS = getOpInt(\"OP_GET_ACCOUNTS\");\n\n\t// CyanogenMod (also seen on some Xperia ROMs!)\n\tpublic static final int OP_WIFI_CHANGE = getOpInt(\"OP_WIFI_CHANGE\");\n\tpublic static final int OP_BLUETOOTH_CHANGE = getOpInt(\"OP_BLUETOOTH_CHANGE\");\n\tpublic static final int OP_DATA_CONNECT_CHANGE = getOpInt(\"OP_DATA_CONNECT_CHANGE\");\n\tpublic static final int OP_SEND_MMS = getOpInt(\"OP_SEND_MMS\");\n\tpublic static final int OP_READ_MMS = getOpInt(\"OP_READ_MMS\");\n\tpublic static final int OP_WRITE_MMS = getOpInt(\"OP_WRITE_MMS\");\n\tpublic static final int OP_ALARM_WAKEUP = getOpInt(\"OP_ALARM_WAKEUP\");\n\tpublic static final int OP_NFC_CHANGE = getOpInt(\"OP_NFC_CHANGE\");\n\n\t// MiUi\n\tpublic static final int OP_AUDIO_FM_VOLUME = getOpInt(\"OP_AUDIO_FM_VOLUME\");\n\tpublic static final int OP_AUDIO_MATV_VOLUME = getOpInt(\"OP_AUDIO_MATV_VOLUME\");\n\tpublic static final int OP_AUTO_START = getOpInt(\"OP_AUTO_START\");\n\tpublic static final int OP_DELETE_SMS = getOpInt(\"OP_DELETE_SMS\");\n\tpublic static final int OP_DELETE_MMS = getOpInt(\"OP_DELETE_MMS\");\n\tpublic static final int OP_DELETE_CONTACTS = getOpInt(\"OP_DELETE_CONTACTS\");\n\tpublic static final int OP_DELETE_CALL_LOG = getOpInt(\"OP_DELETE_CALL_LOG\");\n\tpublic static final int OP_EXACT_ALARM = getOpInt(\"OP_EXACT_ALARM\");\n\tpublic static final int OP_ACCESS_XIAOMI_ACCOUNT = getOpInt(\"OP_ACCESS_XIAOMI_ACCOUNT\");\n\tpublic static final int OP_WAKEUP_ALARM = getOpInt(\"OP_WAKEUP_ALARM\");\n\n\t/**\n\t * @deprecated In module code, use #getBootCompletedOp() instead!\n\t */\n\tpublic static final int OP_BOOT_COMPLETED = getBootCompletedOp();\n\n\tpublic static final int _NUM_OP = getNumOp();\n\n\tpublic static final int MODE_ALLOWED = getOpInt(\"MODE_ALLOWED\");\n\tpublic static final int MODE_IGNORED = getOpInt(\"MODE_IGNORED\");\n\tpublic static final int MODE_ERRORED = getOpInt(\"MODE_ERRORED\");\n\tpublic static final int MODE_DEFAULT = getOpInt(\"MODE_DEFAULT\");\n\tpublic static final int MODE_HINT = getOpInt(\"MODE_HINT\");\n\n\t// CyanogenMod, Sony ROMs, etc.\n\tpublic static final int MODE_ASK = getOpInt(\"MODE_ASK\");\n\n\tprivate final Context mContext;\n\n\tpublic static AppOpsManagerWrapper from(Context context) {\n\t\treturn new AppOpsManagerWrapper(context);\n\t}\n\n\t@TargetApi(19)\n\tprivate AppOpsManagerWrapper(Context context) {\n\t\tsuper(context.getSystemService(Context.APP_OPS_SERVICE));\n\t\tmContext = context;\n\t}\n\n\tpublic List<PackageOpsWrapper> getOpsForPackage(int uid, String packageName, int[] ops)\n\t{\n\t\treturn PackageOpsWrapper.convertList((List<?>) call(\"getOpsForPackage\",\n\t\t\t\tnew Class<?>[] { int.class, String.class, int[].class },\n\t\t\t\tuid, packageName, ops));\n\t}\n\n\tpublic List<PackageOpsWrapper> getPackagesForOps(int[] ops)\n\t{\n\t\treturn PackageOpsWrapper.convertList((List<?>) call(\n\t\t\t\t\"getPackagesForOps\", new Class<?>[] { int[].class }, ops));\n\t}\n\n\tpublic List<PackageOpsWrapper> getAllPackagesForOps(int[] ops)\n\t{\n\t\tfinal List<PackageOpsWrapper> pkgs = new ArrayList<>();\n\n\t\tfor(PackageInfo pi : mContext.getPackageManager().getInstalledPackages(0))\n\t\t{\n\t\t\tfinal List<PackageOpsWrapper> pkg = getOpsForPackage(pi.applicationInfo.uid,\n\t\t\t\t\tpi.packageName, ops);\n\n\t\t\tif(pkg.size() == 1)\n\t\t\t\tpkgs.add(pkg.get(0));\n\t\t\telse\n\t\t\t\tUtil.log(pi.packageName + \": pkg.size()=\" + pkg.size());\n\t\t}\n\n\t\treturn pkgs;\n\t}\n\n\tpublic List<PackageOpsWrapper> getPackagesForOpsMerged(int[] ops)\n\t{\n\t\tfinal HashMap<String, PackageOpsWrapper> pkgMap = new HashMap<>();\n\t\tfor(PackageOpsWrapper pkg : getPackagesForOps(ops))\n\t\t{\n\t\t\tPackageOpsWrapper pow = pkgMap.get(pkg.getPackageName());\n\t\t\tif(pow == null)\n\t\t\t{\n\t\t\t\tpow = new PackageOpsWrapper(pkg.getPackageName(), pkg.getUid(), pkg.getOps());\n\t\t\t\tpkgMap.put(pkg.getPackageName(), pow);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tUtil.debug(pkg.getPackageName() + \": merging uid \" + pkg.getUid() + \" with \" + pow.getUid());\n\t\t\t\tmergeOpEntryWrappers(pow.getOps(), pkg.getOps());\n\t\t\t}\n\t\t}\n\n\t\treturn new ArrayList<>(pkgMap.values());\n\t}\n\n\tpublic List<PackageOpsWrapper> getAllOpsForPackage(int uid, String packageName, int[] ops)\n\t{\n\t\tfinal List<PackageOpsWrapper> pkgs = getPackagesForOps(ops);\n\t\tfinal List<PackageOpsWrapper> ret = new ArrayList<>();\n\n\t\tUtil.debug(\"getAllOpsForPackage(\" + uid + \", \" + packageName + \")\");\n\n\t\tfor(PackageOpsWrapper pkg : pkgs)\n\t\t{\n\t\t\tUtil.debug(\" uid=\" + pkg.getUid() + \", pkg=\" + pkg.getPackageName()\n\t\t\t\t\t+ \", count=\" + pkg.getOps().size());\n\t\t\tif(packageName.equals(pkg.getPackageName()) || uid == pkg.getUid())\n\t\t\t{\n\t\t\t\tUtil.debug(\" added to list\");\n\t\t\t\tret.add(pkg);\n\t\t\t}\n\t\t}\n\n\t\treturn ret;\n\t}\n\n\tpublic int checkOpNoThrow(int op, int uid, String packageName)\n\t{\n\t\treturn call(\"checkOpNoThrow\", new Class<?>[] { int.class, int.class, String.class },\n\t\t\t\top, uid, packageName);\n\t}\n\n\tpublic void setMode(int code, int uid, String packageName, int mode)\n\t{\n\t\tcall(\"setMode\", new Class<?>[] { int.class, int.class, String.class, int.class },\n\t\t\t\tcode, uid, packageName, mode);\n\t}\n\n\tpublic static String opToName(int op) {\n\t\treturn callStatic(AppOpsManager.class, \"opToName\", new Class<?>[] { int.class }, op);\n\t}\n\n\tpublic static String opToPermission(int op) {\n\t\treturn callStatic(AppOpsManager.class, \"opToPermission\", new Class<?>[] { int.class }, op);\n\t}\n\n\tpublic static int opToSwitch(int op) {\n\t\treturn callStatic(AppOpsManager.class, \"opToSwitch\", new Class<?>[] { int.class }, op);\n\t}\n\n\t// 0 AppOpsManager.opToDefaultMode(op)\n\t// 1 AppOpsManager.opToDefaultMode(op, false)\n\t// 2 AppOpsManager.sOpDefaultMode[op]\n\t// 3 (disabled)\n\tprivate static int sOpToDefaultModeType = 0;\n\tprivate static int[] sOpDefaultModes;\n\n\tpublic static int opToDefaultMode(int op)\n\t{\n\t\t// default op modes were introduced in KitKat\n\t\tif(Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT)\n\t\t\treturn MODE_ALLOWED;\n\n\t\ttry\n\t\t{\n\t\t\tswitch(sOpToDefaultModeType)\n\t\t\t{\n\t\t\t\tcase 0:\n\t\t\t\t\treturn callStatic(AppOpsManager.class, \"opToDefaultMode\",\n\t\t\t\t\t\t\tnew Class[]{ int.class }, op);\n\t\t\t\tcase 1:\n\t\t\t\t\treturn callStatic(AppOpsManager.class, \"opToDefaultMode\",\n\t\t\t\t\t\t\tnew Class[]{ int.class, boolean.class }, op, false);\n\t\t\t\tcase 2:\n\t\t\t\t\tsOpDefaultModes = getStatic(AppOpsManager.class, \"sOpDefaultMode\");\n\t\t\t\t\t// fall through\n\t\t\t\tdefault:\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tcatch(ReflectiveException e)\n\t\t{\n\t\t\tUtil.debug(e);\n\t\t\t++sOpToDefaultModeType;\n\t\t\treturn opToDefaultMode(op);\n\t\t}\n\t\tcatch(Exception e)\n\t\t{\n\t\t\tUtil.log(e);\n\t\t}\n\n\t\tif(sOpDefaultModes == null)\n\t\t\tsOpDefaultModes = getFallbackDefaultModes();\n\n\t\tif(op < sOpDefaultModes.length)\n\t\t\treturn sOpDefaultModes[op];\n\n\t\treturn MODE_ALLOWED;\n\t}\n\n\tprivate static boolean sUseOpAllowsReset = true;\n\n\tpublic static boolean opAllowsReset(int op)\n\t{\n\t\tif(sUseOpAllowsReset)\n\t\t{\n\t\t\ttry\n\t\t\t{\n\t\t\t\treturn callStatic(AppOpsManager.class, \"opAllowsReset\", new Class<?>[] { int.class }, op);\n\t\t\t}\n\t\t\tcatch(ReflectiveException e)\n\t\t\t{\n\t\t\t\tUtil.debug(e);\n\t\t\t\tsUseOpAllowsReset = false;\n\t\t\t}\n\t\t}\n\n\t\t// This op is used to control which app is the current\n\t\t// SMS app, so we don't reset it. At the moment, this\n\t\t// is the only op in AOSP which doesn't allow a reset.\n\t\treturn op != OP_WRITE_SMS;\n\t}\n\n\tpublic static int opFromName(String opName)\n\t{\n\t\tif(!opName.startsWith(\"OP_\"))\n\t\t\topName = \"OP_\" + opName;\n\n\t\treturn getStatic(AppOpsManagerWrapper.class, opName, -1);\n\t}\n\n\tpublic static String modeToName(int mode)\n\t{\n\t\tif(mode >= 0)\n\t\t{\n\t\t\tif(mode == MODE_ALLOWED)\n\t\t\t\treturn \"ALLOWED\";\n\t\t\tif(mode == MODE_ERRORED)\n\t\t\t\treturn \"ERRORED\";\n\t\t\tif(mode == MODE_IGNORED)\n\t\t\t\treturn \"IGNORED\";\n\t\t\tif(mode == MODE_DEFAULT)\n\t\t\t\treturn \"DEFAULT\";\n\t\t\tif(mode == MODE_ASK)\n\t\t\t\treturn \"ASK\";\n\t\t\tif(mode == MODE_HINT)\n\t\t\t\treturn \"HINT\";\n\t\t}\n\n\t\treturn \"mode #\" + mode;\n\t}\n\n\tpublic static boolean hasTrueBootCompletedOp() {\n\t\treturn getOpInt(\"OP_BOOT_COMPLETED\") != -1;\n\t}\n\n\tpublic static boolean isValidOp(int op)\n\t{\n\t\treturn op >= 0 && op < _NUM_OP;\n\t}\n\n\tprivate static int getOpInt(String opName)\n\t{\n\t\ttry\n\t\t{\n\t\t\treturn getStatic(AppOpsManager.class, opName);\n\t\t}\n\t\tcatch(ReflectiveException e)\n\t\t{\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\tprivate static int getOpWithPermission(String permission)\n\t{\n\t\t// Must not use _NUM_OP here, has this will causes problems\n\t\t// with static initialization order\n\t\tfor(int op = 0; op < getNumOp(); ++op)\n\t\t{\n\t\t\tif(permission.equals(opToPermission(op)))\n\t\t\t{\n\t\t\t\t//Util.debug(\"Found op #\" + op + \" with permission \" + permission);\n\t\t\t\treturn op;\n\t\t\t}\n\t\t}\n\n\t\t//Util.debug(\"No op found for permission \" + permission);\n\n\t\treturn -1;\n\t}\n\n\tpublic static int getBootCompletedOp()\n\t{\n\t\tfinal int op = getOpInt(\"OP_BOOT_COMPLETED\");\n\t\treturn op == -1 ? getOpWithPermission(Manifest.permission.RECEIVE_BOOT_COMPLETED) : op;\n\t}\n\n\tprivate static int getNumOp()\n\t{\n\t\tif(Util.containsManufacturer(\"HTC\"))\n\t\t{\n\t\t\t// Some HTC ROMs have added ops, prefixed with HTC_OP_. These ops are\n\t\t\t// offset by 1000, so our usual assumption of op doubling as an array\n\t\t\t// index is not valid anymore; HTC has added an opToIndex method to\n\t\t\t// AppOpsManager which takes care of this problem.\n\t\t\t// On these ROMs, _NUM_OP == _NUM_GOOGLE_OP + _NUM_HTC_OP!\n\t\t\t//\n\t\t\t// For now, we only use _NUM_GOOGLE_OP.\n\n\t\t\tint numGoogle = getOpInt(\"_NUM_GOOGLE_OP\");\n\t\t\tif(numGoogle != -1)\n\t\t\t\treturn numGoogle;\n\t\t}\n\n\t\treturn getOpInt(\"_NUM_OP\");\n\t}\n\n\tprivate static int[] getFallbackDefaultModes()\n\t{\n\t\tfinal int[] defaults = new int[_NUM_OP];\n\t\tfor(int op = 0; op != defaults.length; ++op)\n\t\t\tdefaults[op] = opToDefaultModeInternal(op);\n\n\t\treturn defaults;\n\t}\n\n\tprivate static int opToDefaultModeInternal(int op)\n\t{\n\t\tif(op == OP_WRITE_SETTINGS || op == OP_SYSTEM_ALERT_WINDOW)\n\t\t\treturn Build.VERSION.SDK_INT < Build.VERSION_CODES.M ? MODE_ALLOWED : MODE_DEFAULT;\n\n\t\tif(op == OP_WRITE_SMS)\n\t\t\treturn MODE_IGNORED;\n\n\t\tif(op == OP_PROJECT_MEDIA || op == OP_ACTIVATE_VPN || op == OP_GET_USAGE_STATS)\n\t\t\treturn MODE_DEFAULT;\n\n\t\tif(op == OP_MOCK_LOCATION)\n\t\t\treturn MODE_ERRORED;\n\n\t\treturn MODE_ALLOWED;\n\t}\n\n\tprivate static void mergeOpEntryWrappers(List<OpEntryWrapper> dest, List<OpEntryWrapper> src)\n\t{\n\t\tfinal BitSet bs = new BitSet(_NUM_OP);\n\t\tfor(OpEntryWrapper oew : dest)\n\t\t\tbs.set(oew.getOp());\n\n\t\tfor(OpEntryWrapper oew : src)\n\t\t{\n\t\t\tif(!bs.get(oew.getOp()))\n\t\t\t\tdest.add(oew);\n\t\t}\n\t}\n\n\tpublic static class PackageOpsWrapper extends ObjectWrapper\n\t{\n\t\tprivate String mPackageName;\n\t\tprivate int mUid;\n\t\tprivate List<OpEntryWrapper> mEntries;\n\n\t\tprivate PackageOpsWrapper(Object obj) {\n\t\t\tsuper(obj);\n\t\t}\n\n\t\tpublic PackageOpsWrapper(String packageName, int uid, List<OpEntryWrapper> entries)\n\t\t{\n\t\t\tsuper(null);\n\n\t\t\tmPackageName = packageName;\n\t\t\tmUid = uid;\n\t\t\tmEntries = entries;\n\t\t}\n\n\t\tpublic static List<PackageOpsWrapper> convertList(List<?> list)\n\t\t{\n\t\t\tfinal List<PackageOpsWrapper> converted = new ArrayList<PackageOpsWrapper>();\n\t\t\tif(list != null)\n\t\t\t{\n\t\t\t\tfor(Object o : list)\n\t\t\t\t\tconverted.add(new PackageOpsWrapper(o));\n\t\t\t}\n\n\t\t\treturn converted;\n\t\t}\n\n\t\tpublic String getPackageName()\n\t\t{\n\t\t\tif(mObj != null)\n\t\t\t\treturn call(\"getPackageName\");\n\n\t\t\treturn mPackageName;\n\t\t}\n\n\t\tpublic int getUid()\n\t\t{\n\t\t\tif(mObj != null)\n\t\t\t\treturn (Integer) call(\"getUid\");\n\n\t\t\treturn mUid;\n\t\t}\n\n\t\tpublic List<OpEntryWrapper> getOps()\n\t\t{\n\t\t\tif(mObj != null)\n\t\t\t\treturn OpEntryWrapper.convertList((List<?>) call(\"getOps\"));\n\n\t\t\treturn mEntries;\n\t\t}\n\t}\n\n\tpublic static class OpEntryWrapper extends ObjectWrapper\n\t{\n\t\tprivate OpEntryWrapper(Object obj) {\n\t\t\tsuper(obj);\n\t\t}\n\n\t\tprivate int mOp;\n\t\tprivate int mMode;\n\t\tprivate long mTime;\n\t\tprivate long mRejectTime;\n\t\tprivate int mDuration;\n\t\tprivate int mProxyUid = -1;\n\t\tprivate String mProxyPackageName = null;\n\n\t\tpublic OpEntryWrapper(int op, int mode, long time, long rejectTime, int duration)\n\t\t{\n\t\t\tsuper(null);\n\n\t\t\tmOp = op;\n\t\t\tmMode = mode;\n\t\t\tmTime = time;\n\t\t\tmRejectTime = rejectTime;\n\t\t\tmDuration = duration;\n\t\t}\n\n\t\tpublic OpEntryWrapper(int op, int mode, long time, long rejectTime, int duration, int proxyId, String proxyPackageName)\n\t\t{\n\t\t\tthis(op, mode, time, rejectTime, duration);\n\n\t\t\tmProxyUid = proxyId;\n\t\t\tmProxyPackageName = proxyPackageName;\n\t\t}\n\n\t\tpublic static List<OpEntryWrapper> convertList(List<?> list)\n\t\t{\n\t\t\tfinal List<OpEntryWrapper> converted = new ArrayList<OpEntryWrapper>();\n\t\t\tif(list != null)\n\t\t\t{\n\t\t\t\tfor(Object o : list)\n\t\t\t\t\tconverted.add(new OpEntryWrapper(o));\n\t\t\t}\n\n\t\t\treturn converted;\n\t\t}\n\n\t\tpublic int getOp()\n\t\t{\n\t\t\tif(mObj != null)\n\t\t\t\treturn (Integer) call(\"getOp\");\n\n\t\t\treturn mOp;\n\t\t}\n\n\t\tpublic int getMode()\n\t\t{\n\t\t\tif(mObj != null)\n\t\t\t\treturn (Integer) call(\"getMode\");\n\n\t\t\treturn mMode;\n\t\t}\n\n\t\tpublic long getTime()\n\t\t{\n\t\t\tif(mObj != null)\n\t\t\t\treturn (Long) call(\"getTime\");\n\n\t\t\treturn mTime;\n\t\t}\n\n\t\tpublic long getRejectTime()\n\t\t{\n\t\t\tif(mObj != null)\n\t\t\t\treturn (Long) call(\"getRejectTime\");\n\n\t\t\treturn mRejectTime;\n\t\t}\n\n\t\tpublic boolean isRunning()\n\t\t{\n\t\t\tif(mObj != null)\n\t\t\t\treturn (Boolean) call(\"isRunning\");\n\n\t\t\treturn mDuration == -1;\n\t\t}\n\n\t\tpublic int getDuration()\n\t\t{\n\t\t\tif(mObj != null)\n\t\t\t\treturn (Integer) call(\"getDuration\");\n\n\t\t\treturn mDuration == -1 ? (int)(System.currentTimeMillis() - mTime) : mDuration;\n\t\t}\n\n\t\tpublic int getProxyUid()\n\t\t{\n\t\t\tif(Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP_MR1)\n\t\t\t\treturn -1;\n\n\t\t\tif(mObj != null)\n\t\t\t\treturn (Integer) call(\"getProxyUid\");\n\n\t\t\treturn mProxyUid;\n\t\t}\n\n\t\tpublic String getProxyPackageName()\n\t\t{\n\t\t\tif(Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP_MR1)\n\t\t\t\treturn null;\n\n\t\t\tif(mObj != null)\n\t\t\t\treturn (String) call(\"getProxyPackageName\");\n\n\t\t\treturn mProxyPackageName;\n\t\t}\n\t}\n}",
"public static class OpEntryWrapper extends ObjectWrapper\n{\n\tprivate OpEntryWrapper(Object obj) {\n\t\tsuper(obj);\n\t}\n\n\tprivate int mOp;\n\tprivate int mMode;\n\tprivate long mTime;\n\tprivate long mRejectTime;\n\tprivate int mDuration;\n\tprivate int mProxyUid = -1;\n\tprivate String mProxyPackageName = null;\n\n\tpublic OpEntryWrapper(int op, int mode, long time, long rejectTime, int duration)\n\t{\n\t\tsuper(null);\n\n\t\tmOp = op;\n\t\tmMode = mode;\n\t\tmTime = time;\n\t\tmRejectTime = rejectTime;\n\t\tmDuration = duration;\n\t}\n\n\tpublic OpEntryWrapper(int op, int mode, long time, long rejectTime, int duration, int proxyId, String proxyPackageName)\n\t{\n\t\tthis(op, mode, time, rejectTime, duration);\n\n\t\tmProxyUid = proxyId;\n\t\tmProxyPackageName = proxyPackageName;\n\t}\n\n\tpublic static List<OpEntryWrapper> convertList(List<?> list)\n\t{\n\t\tfinal List<OpEntryWrapper> converted = new ArrayList<OpEntryWrapper>();\n\t\tif(list != null)\n\t\t{\n\t\t\tfor(Object o : list)\n\t\t\t\tconverted.add(new OpEntryWrapper(o));\n\t\t}\n\n\t\treturn converted;\n\t}\n\n\tpublic int getOp()\n\t{\n\t\tif(mObj != null)\n\t\t\treturn (Integer) call(\"getOp\");\n\n\t\treturn mOp;\n\t}\n\n\tpublic int getMode()\n\t{\n\t\tif(mObj != null)\n\t\t\treturn (Integer) call(\"getMode\");\n\n\t\treturn mMode;\n\t}\n\n\tpublic long getTime()\n\t{\n\t\tif(mObj != null)\n\t\t\treturn (Long) call(\"getTime\");\n\n\t\treturn mTime;\n\t}\n\n\tpublic long getRejectTime()\n\t{\n\t\tif(mObj != null)\n\t\t\treturn (Long) call(\"getRejectTime\");\n\n\t\treturn mRejectTime;\n\t}\n\n\tpublic boolean isRunning()\n\t{\n\t\tif(mObj != null)\n\t\t\treturn (Boolean) call(\"isRunning\");\n\n\t\treturn mDuration == -1;\n\t}\n\n\tpublic int getDuration()\n\t{\n\t\tif(mObj != null)\n\t\t\treturn (Integer) call(\"getDuration\");\n\n\t\treturn mDuration == -1 ? (int)(System.currentTimeMillis() - mTime) : mDuration;\n\t}\n\n\tpublic int getProxyUid()\n\t{\n\t\tif(Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP_MR1)\n\t\t\treturn -1;\n\n\t\tif(mObj != null)\n\t\t\treturn (Integer) call(\"getProxyUid\");\n\n\t\treturn mProxyUid;\n\t}\n\n\tpublic String getProxyPackageName()\n\t{\n\t\tif(Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP_MR1)\n\t\t\treturn null;\n\n\t\tif(mObj != null)\n\t\t\treturn (String) call(\"getProxyPackageName\");\n\n\t\treturn mProxyPackageName;\n\t}\n}",
"public static class PackageOpsWrapper extends ObjectWrapper\n{\n\tprivate String mPackageName;\n\tprivate int mUid;\n\tprivate List<OpEntryWrapper> mEntries;\n\n\tprivate PackageOpsWrapper(Object obj) {\n\t\tsuper(obj);\n\t}\n\n\tpublic PackageOpsWrapper(String packageName, int uid, List<OpEntryWrapper> entries)\n\t{\n\t\tsuper(null);\n\n\t\tmPackageName = packageName;\n\t\tmUid = uid;\n\t\tmEntries = entries;\n\t}\n\n\tpublic static List<PackageOpsWrapper> convertList(List<?> list)\n\t{\n\t\tfinal List<PackageOpsWrapper> converted = new ArrayList<PackageOpsWrapper>();\n\t\tif(list != null)\n\t\t{\n\t\t\tfor(Object o : list)\n\t\t\t\tconverted.add(new PackageOpsWrapper(o));\n\t\t}\n\n\t\treturn converted;\n\t}\n\n\tpublic String getPackageName()\n\t{\n\t\tif(mObj != null)\n\t\t\treturn call(\"getPackageName\");\n\n\t\treturn mPackageName;\n\t}\n\n\tpublic int getUid()\n\t{\n\t\tif(mObj != null)\n\t\t\treturn (Integer) call(\"getUid\");\n\n\t\treturn mUid;\n\t}\n\n\tpublic List<OpEntryWrapper> getOps()\n\t{\n\t\tif(mObj != null)\n\t\t\treturn OpEntryWrapper.convertList((List<?>) call(\"getOps\"));\n\n\t\treturn mEntries;\n\t}\n}",
"public class OpsLabelHelper\n{\n\tprivate static String[] sOpLabels;\n\tprivate static String[] sOpSummaries;\n\n\tpublic static CharSequence getPermissionLabel(Context context, String permission) {\n\t\treturn getPermissionLabel(context, permission, permission);\n\t}\n\n\tpublic static String getOpLabel(Context context, int op) {\n\t\treturn getOpLabelOrSummary(context, null, op, true);\n\t}\n\n\tpublic static String getOpLabel(Context context, String opName) {\n\t\treturn getOpLabelOrSummary(context, opName, -1, true);\n\t}\n\n\tpublic static String getOpSummary(Context context, int op) {\n\t\treturn getOpLabelOrSummary(context, null, op, false);\n\t}\n\n\tpublic static String getOpSummary(Context context, String opName) {\n\t\treturn getOpLabelOrSummary(context, opName, -1, false);\n\t}\n\n\tpublic static String[] getOpSummaries(Context context) {\n\t\treturn getOpLabelsOrSummaries(context, false);\n\t}\n\n\tpublic static String[] getOpLabels(Context context) {\n\t\treturn getOpLabelsOrSummaries(context, true);\n\t}\n\n\tprivate static String[] getOpLabelsOrSummaries(Context context, boolean getLabels)\n\t{\n\t\tfinal SparseArray<String> strings = new SparseArray<String>();\n\t\tfinal boolean hasFakeBootCompleted = Util.isBootCompletedHackWorking() &&\n\t\t\t\tAppOpsManagerWrapper.OP_POST_NOTIFICATION == AppOpsManagerWrapper.getBootCompletedOp();\n\t\tint maxOp = 0;\n\n\t\tfor(Field field : AppOpsManagerWrapper.class.getDeclaredFields())\n\t\t{\n\t\t\tfinal String opName = field.getName();\n\t\t\tif(!opName.startsWith(\"OP_\") || \"OP_NONE\".equals(opName))\n\t\t\t\tcontinue;\n\n\t\t\tfinal int op = AppOpsManagerWrapper.opFromName(opName);\n\t\t\tif(op == -1)\n\t\t\t\tcontinue;\n\t\t\telse if(op > maxOp)\n\t\t\t\tmaxOp = op;\n\n\t\t\tif(hasFakeBootCompleted)\n\t\t\t{\n\t\t\t\t// Don't use op == because that would be true for\n\t\t\t\t// OP_BOOT_COMPLETED as well in this case\n\t\t\t\tif(\"OP_POST_NOTIFICATION\".equals(opName))\n\t\t\t\t\tcontinue;\n\t\t\t\telse if(op == AppOpsManagerWrapper.OP_VIBRATE)\n\t\t\t\t{\n\t\t\t\t\tstrings.append(op, context.getString(R.string.app_ops_labels_vibrate) + \"/\" +\n\t\t\t\t\t\t\tcontext.getString(R.string.app_ops_labels_post_notification));\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\t/*else if(op == AppOpsManagerWrapper.OP_BOOT_COMPLETED)\n\t\t\t\t{\n\t\t\t\t\tstrings.append(op, context.getString(getLabels ? R.string.app_ops_labels_boot_completed :\n\t\t\t\t\t\tR.string.app_ops_summaries_boot_completed));\n\n\t\t\t\t\tLog.d(\"AOX\", \"OP_BOOT_COMPLETED!\");\n\t\t\t\t\tcontinue;\n\t\t\t\t}*/\n\t\t\t}\n\n\t\t\tfinal String str = getAppOpsString(context, opName, getLabels);\n\t\t\tif(str != null)\n\t\t\t\tstrings.append(op, str);\n\t\t\telse\n\t\t\t\tUtil.debug(\"No ops string for \" + opName);\n\t\t}\n\n\t\tfinal String[] ret = new String[AppOpsManagerWrapper._NUM_OP];\n\n\t\tfor(int op = 0; op <= maxOp; ++op)\n\t\t\tret[op] = strings.get(op, AppOpsManagerWrapper.opToName(op));\n\n\t\tif(maxOp + 1 != AppOpsManagerWrapper._NUM_OP)\n\t\t{\n\t\t\tfor(int op = maxOp + 1; op != AppOpsManagerWrapper._NUM_OP; ++op)\n\t\t\t{\n\t\t\t\tfinal String opName = AppOpsManagerWrapper.opToName(op);\n\t\t\t\tif (opName != null)\n\t\t\t\t\tret[op] = getAppOpsString(context, opName, true);\n\n\t\t\t\tif(ret[op] == null)\n\t\t\t\t\tret[op] = opName != null ? opName : \"OP #\" + op;\n\t\t\t}\n\t\t}\n\n\t\treturn ret;\n\t}\n\n\tprivate static String getAppOpsString(Context context, String opName, boolean getLabel)\n\t{\n\t\tfinal String str = getAppOpsString(context, opName, getLabel, true);\n\t\treturn str != null ? Util.capitalizeFirst(str) : null;\n\t}\n\n\tprivate static String getAppOpsString(Context context, String opName, boolean getLabel, boolean tryOther)\n\t{\n\t\tif(opName.startsWith(\"OP_\"))\n\t\t\topName = opName.substring(3);\n\n\t\tfinal String id = \"app_ops_\" + (getLabel ? \"labels\" : \"summaries\") + \"_\" +\n\t\t\t\topName.toLowerCase(Locale.US);\n\n\t\tfinal Resources res;\n\n\t\ttry\n\t\t{\n\t\t\tif(Constants.MODULE_PACKAGE.equals(context.getPackageName()))\n\t\t\t\tres = context.getResources();\n\t\t\telse\n\t\t\t\tres = context.getPackageManager().getResourcesForApplication(\"at.jclehner.appopsxposed\");\n\t\t}\n\t\tcatch(NameNotFoundException e)\n\t\t{\n\t\t\tLog.w(\"AOX\", e);\n\t\t\treturn opName;\n\t\t}\n\n\t\tfinal int resId = res.getIdentifier(Constants.MODULE_PACKAGE + \":string/\" + id, null, null);\n\t\tif(resId != 0)\n\t\t{\n\t\t\ttry\n\t\t\t{\n\t\t\t\tfinal String str = context.getString(resId);\n\t\t\t\tif(str != null)\n\t\t\t\t\treturn str;\n\t\t\t}\n\t\t\tcatch(NotFoundException e)\n\t\t\t{\n\t\t\t\t//Util.debug(e);\n\t\t\t}\n\n\t\t\tUtil.debug(\"Failed to get string \" + id);\n\t\t}\n\n\t\treturn getFallbackString(context, opName, getLabel, tryOther);\n\t}\n\n\tprivate static String getOpLabelOrSummary(Context context, String opName, int op, boolean getLabel)\n\t{\n\t\tif(opName == null && op == -1)\n\t\t\tthrow new IllegalArgumentException(\"Must specify either opName or op\");\n\n\t\tif(op == -1)\n\t\t{\n\t\t\top = getOpValue(opName);\n\t\t\tif(op == -1)\n\t\t\t\treturn opName;\n\t\t}\n\n\t\tif(sOpLabels == null)\n\t\t{\n\t\t\tsOpLabels = getOpLabels(context);\n\t\t\tsOpSummaries = getOpSummaries(context);\n\t\t}\n\n\t\tfinal String[] array = getLabel ? sOpLabels : sOpSummaries;\n\t\tif(op < array.length && !TextUtils.isEmpty(array[op]))\n\t\t\treturn array[op];\n\n\t\t// Now that getOpLabelsOrSummaries has been fixed, this shouldn't happen\n\t\tUtil.log(\"op #\" + op + \" (\" + opName +\") has no valid array entry\");\n\t\treturn opName != null ? opName : \"OP #\" + op;\n\t}\n\n\tprivate static String getFallbackString(Context context, String opName, boolean getLabel, boolean tryOther)\n\t{\n\t\tif(tryOther)\n\t\t{\n\t\t\tfinal String other = getAppOpsString(context, opName, !getLabel, false);\n\t\t\tif(other != null)\n\t\t\t\treturn other;\n\t\t}\n\n\t\tfinal String fromPerm = opLabelFromPermission(context, opName);\n\t\treturn fromPerm != null ? fromPerm : opName;\n\t}\n\n\tpublic static int getOpValue(String name)\n\t{\n\t\ttry\n\t\t{\n\t\t\tfinal Field f = AppOpsManager.class.getField(name);\n\t\t\tf.setAccessible(true);\n\t\t\treturn f.getInt(null);\n\t\t}\n\t\tcatch (IllegalAccessException e)\n\t\t{\n\t\t\t// ignore\n\t\t}\n\t\tcatch (IllegalArgumentException e)\n\t\t{\n\t\t\t// ignore\n\t\t}\n\t\tcatch (NoSuchFieldException e)\n\t\t{\n\t\t\t// ignore\n\t\t}\n\n\t\treturn -1;\n\t}\n\n\tprivate static String opLabelFromPermission(Context context, String opName)\n\t{\n\t\tfinal int op = AppOpsManagerWrapper.opFromName(opName);\n\t\tif (op == -1) {\n\t\t\treturn null;\n\t\t}\n\t\tfinal String perm = AppOpsManagerWrapper.opToPermission(op);\n\t\treturn perm != null ? getPermissionLabel(context, perm, null) : null;\n\t}\n\n\tprivate static String getPermissionLabel(Context context, String permission, String defValue)\n\t{\n\t\ttry\n\t\t{\n\t\t\tfinal PackageManager pm = context.getPackageManager();\n\t\t\tfinal PermissionInfo pi = pm.getPermissionInfo(permission, 0);\n\n\t\t\tfinal CharSequence label = pi.loadLabel(pm);\n\t\t\tif(label != null && !label.toString().equals(permission))\n\t\t\t\treturn label.toString();\n\t\t}\n\t\tcatch(NameNotFoundException e)\n\t\t{\n\t\t\t// om nom nom\n\t\t}\n\n\t\treturn defValue;\n\t}\n}",
"public class AppOpsDetails extends Fragment {\n static final String TAG = \"AppOpsDetails\";\n\n public static final String ARG_PACKAGE_NAME = \"package\";\n\n private AppOpsState mState;\n private PackageManager mPm;\n private AppOpsManagerWrapper mAppOps;\n private PackageInfo mPackageInfo;\n private LayoutInflater mInflater;\n private View mRootView;\n private TextView mAppVersion;\n private LinearLayout mOperationsSection;\n\n // Utility method to set application label and icon.\n private void setAppLabelAndIcon(PackageInfo pkgInfo) {\n final View appSnippet = mRootView.findViewById(R.id.app_snippet);\n appSnippet.setPaddingRelative(0, appSnippet.getPaddingTop(), 0, appSnippet.getPaddingBottom());\n\n ImageView icon = (ImageView) appSnippet.findViewById(R.id.app_icon);\n icon.setImageDrawable(mPm.getApplicationIcon(pkgInfo.applicationInfo));\n // Set application name.\n TextView label = (TextView) appSnippet.findViewById(R.id.app_name);\n label.setText(mPm.getApplicationLabel(pkgInfo.applicationInfo));\n // Version number of application\n mAppVersion = (TextView) appSnippet.findViewById(R.id.app_size);\n\n final StringBuilder sb = new StringBuilder(pkgInfo.packageName);\n\n if (pkgInfo.versionName != null) {\n sb.append(\"\\n\");\n sb.append(getActivity().getString(R.string.version_text, pkgInfo.versionName));\n }\n\n mAppVersion.setText(sb);\n }\n\n private String retrieveAppEntry() {\n final Bundle args = getArguments();\n String packageName = (args != null) ? args.getString(ARG_PACKAGE_NAME) : null;\n if (packageName == null) {\n Intent intent = (args == null) ?\n getActivity().getIntent() : (Intent) args.getParcelable(\"intent\");\n if (intent != null) {\n packageName = intent.getData().getSchemeSpecificPart();\n }\n }\n try {\n mPackageInfo = mPm.getPackageInfo(packageName,\n PackageManager.GET_DISABLED_COMPONENTS |\n PackageManager.GET_UNINSTALLED_PACKAGES);\n } catch (NameNotFoundException e) {\n Log.e(TAG, \"Exception when retrieving package:\" + packageName, e);\n mPackageInfo = null;\n }\n\n if (getActivity().getPackageName().equals(packageName)) {\n Toast.makeText(getActivity(), \"\\uD83D\\uDE22\", Toast.LENGTH_SHORT).show();\n }\n\n return packageName;\n }\n\n private boolean refreshUi() {\n if (mPackageInfo == null) {\n return false;\n }\n\n setAppLabelAndIcon(mPackageInfo);\n\n Resources res = getActivity().getResources();\n\n mOperationsSection.removeAllViews();\n boolean hasBootupSwitch = false;\n String lastPermGroup = \"\";\n for (AppOpsState.OpsTemplate tpl : AppOpsState.ALL_TEMPLATES) {\n List<AppOpsState.AppOpEntry> entries = mState.buildState(tpl,\n mPackageInfo.applicationInfo.uid, mPackageInfo.packageName);\n for (final AppOpsState.AppOpEntry entry : entries) {\n final OpEntryWrapper firstOp = entry.getOpEntry(0);\n final View view = mInflater.inflate(R.layout.app_ops_details_item,\n mOperationsSection, false);\n String perm = AppOpsManagerWrapper.opToPermission(firstOp.getOp());\n if (perm != null) {\n if (Manifest.permission.RECEIVE_BOOT_COMPLETED.equals(perm)) {\n if (!hasBootupSwitch) {\n hasBootupSwitch = true;\n } else {\n Log.i(TAG, \"Skipping second bootup switch\");\n continue;\n }\n }\n try {\n PermissionInfo pi = mPm.getPermissionInfo(perm, 0);\n if (pi.group != null && !lastPermGroup.equals(pi.group)) {\n lastPermGroup = pi.group;\n PermissionGroupInfo pgi = mPm.getPermissionGroupInfo(pi.group, 0);\n if (pgi.icon != 0) {\n ((ImageView)view.findViewById(R.id.op_icon)).setImageDrawable(\n pgi.loadIcon(mPm));\n }\n }\n } catch (NameNotFoundException e) {\n }\n }\n ((TextView)view.findViewById(R.id.op_name)).setText(\n entry.getSwitchText(getActivity(), mState));\n ((TextView)view.findViewById(R.id.op_time)).setText(\n entry.getTimeText(res, true));\n\n Switch sw = (Switch)view.findViewById(R.id.switchWidget);\n final int switchOp = AppOpsManagerWrapper.opToSwitch(firstOp.getOp());\n sw.setChecked(modeToChecked(switchOp, entry.getPackageOps()));\n sw.setOnCheckedChangeListener(new Switch.OnCheckedChangeListener() {\n @Override\n public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {\n mAppOps.setMode(switchOp, entry.getPackageOps().getUid(),\n entry.getPackageOps().getPackageName(), isChecked\n ? AppOpsManagerWrapper.MODE_ALLOWED : AppOpsManagerWrapper.MODE_IGNORED);\n }\n });\n mOperationsSection.addView(view);\n }\n }\n\n return true;\n }\n\n private boolean modeToChecked(int switchOp, PackageOpsWrapper ops) {\n return modeToChecked(mAppOps.checkOpNoThrow(switchOp, ops.getUid(), ops.getPackageName()));\n }\n\n static boolean modeToChecked(int mode) {\n if (mode == AppOpsManagerWrapper.MODE_ALLOWED)\n return true;\n if (mode == AppOpsManagerWrapper.MODE_DEFAULT)\n return true;\n if (mode == AppOpsManagerWrapper.MODE_ASK)\n return true;\n if (mode == AppOpsManagerWrapper.MODE_HINT)\n return true;\n\n return false;\n }\n\n private void setIntentAndFinish(boolean finish, boolean appChanged) {\n Intent intent = new Intent();\n intent.putExtra(\"chg\", appChanged);\n PreferenceActivity pa = (PreferenceActivity)getActivity();\n pa.finishPreferencePanel(this, Activity.RESULT_OK, intent);\n }\n\n /** Called when the activity is first created. */\n @Override\n public void onCreate(Bundle icicle) {\n super.onCreate(icicle);\n\n mState = new AppOpsState(getActivity());\n mPm = getActivity().getPackageManager();\n mInflater = (LayoutInflater)getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);\n mAppOps = AppOpsManagerWrapper.from(getActivity());\n\n retrieveAppEntry();\n\n setHasOptionsMenu(true);\n }\n\n @Override\n public View onCreateView(\n LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {\n final View view = inflater.inflate(R.layout.app_ops_details, container, false);\n //Utils.prepareCustomPreferencesList(container, view, view, false);\n\n mRootView = view;\n mOperationsSection = (LinearLayout)view.findViewById(R.id.operations_section);\n return view;\n }\n\n @Override\n public void onResume() {\n super.onResume();\n if (!refreshUi()) {\n setIntentAndFinish(true, true);\n }\n }\n}",
"public class AppOpsState {\n static final String TAG = \"AppOpsState\";\n static final boolean DEBUG = false;\n\n final Context mContext;\n final AppOpsManagerWrapper mAppOps;\n final PackageManager mPm;\n final CharSequence[] mOpSummaries;\n final CharSequence[] mOpLabels;\n\n List<AppOpEntry> mApps;\n\n @TargetApi(19)\n public AppOpsState(Context context) {\n mContext = context;\n mAppOps = AppOpsManagerWrapper.from(context);\n mPm = context.getPackageManager();\n //mOpSummaries = context.getResources().getTextArray(R.array.app_ops_summaries);\n mOpSummaries = OpsLabelHelper.getOpSummaries(context);\n //mOpLabels = context.getResources().getTextArray(R.array.app_ops_labels);\n mOpLabels = OpsLabelHelper.getOpLabels(context);\n\n /*if (AppOpsManagerWrapper.hasFakeBootCompletedOp()) {\n mOpSummaries[AppOpsManagerWrapper.OP_VIBRATE] = mOpSummaries[AppOpsManagerWrapper.OP_VIBRATE]\n + \"/\" + mOpSummaries[AppOpsManagerWrapper.OP_POST_NOTIFICATION];\n\n mOpLabels[AppOpsManagerWrapper.OP_VIBRATE] = mOpLabels[AppOpsManagerWrapper.OP_VIBRATE]\n + \"/\" + mOpLabels[AppOpsManagerWrapper.OP_POST_NOTIFICATION];\n\n final CharSequence summary = OpsLabelHelper.getPermissionLabel(context,\n android.Manifest.permission.RECEIVE_BOOT_COMPLETED);\n\n mOpSummaries[AppOpsManagerWrapper.OP_POST_NOTIFICATION] = summary;\n mOpLabels[AppOpsManagerWrapper.OP_POST_NOTIFICATION] = Util.capitalizeFirst(summary);\n }*/\n }\n\n public static class OpsTemplate implements Parcelable {\n public final int[] ops;\n public final boolean[] showPerms;\n\n public OpsTemplate(int[] _ops, boolean[] _showPerms) {\n ops = _ops;\n showPerms = _showPerms;\n }\n\n OpsTemplate(Parcel src) {\n ops = src.createIntArray();\n showPerms = src.createBooleanArray();\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel dest, int flags) {\n dest.writeIntArray(ops);\n dest.writeBooleanArray(showPerms);\n }\n\n public static final Creator<OpsTemplate> CREATOR = new Creator<OpsTemplate>() {\n @Override public OpsTemplate createFromParcel(Parcel source) {\n return new OpsTemplate(source);\n }\n\n @Override public OpsTemplate[] newArray(int size) {\n return new OpsTemplate[size];\n }\n };\n }\n\n public static final OpsTemplate LOCATION_TEMPLATE = new OpsTemplate(\n new int[] { AppOpsManagerWrapper.OP_COARSE_LOCATION,\n AppOpsManagerWrapper.OP_FINE_LOCATION,\n AppOpsManagerWrapper.OP_GPS,\n AppOpsManagerWrapper.OP_WIFI_SCAN,\n AppOpsManagerWrapper.OP_NEIGHBORING_CELLS,\n AppOpsManagerWrapper.OP_MONITOR_LOCATION,\n AppOpsManagerWrapper.OP_MONITOR_HIGH_POWER_LOCATION,\n AppOpsManagerWrapper.OP_MOCK_LOCATION, },\n new boolean[] { true,\n true,\n false,\n false,\n false,\n false,\n false,\n true}\n );\n\n public static final OpsTemplate PERSONAL_TEMPLATE = new OpsTemplate(\n new int[] { AppOpsManagerWrapper.OP_READ_CONTACTS,\n AppOpsManagerWrapper.OP_WRITE_CONTACTS,\n AppOpsManagerWrapper.OP_READ_CALL_LOG,\n AppOpsManagerWrapper.OP_WRITE_CALL_LOG,\n AppOpsManagerWrapper.OP_READ_CALENDAR,\n AppOpsManagerWrapper.OP_WRITE_CALENDAR,\n AppOpsManagerWrapper.OP_DELETE_CALL_LOG,\n AppOpsManagerWrapper.OP_DELETE_CONTACTS,\n AppOpsManagerWrapper.OP_ACCESS_XIAOMI_ACCOUNT,\n AppOpsManagerWrapper.OP_READ_PHONE_STATE,\n AppOpsManagerWrapper.OP_PROCESS_OUTGOING_CALLS,\n AppOpsManagerWrapper.OP_USE_FINGERPRINT,\n AppOpsManagerWrapper.OP_BODY_SENSORS,\n AppOpsManagerWrapper.OP_READ_EXTERNAL_STORAGE,\n AppOpsManagerWrapper.OP_WRITE_EXTERNAL_STORAGE,\n AppOpsManagerWrapper.OP_GET_ACCOUNTS,\n AppOpsManagerWrapper.OP_READ_CLIPBOARD,\n AppOpsManagerWrapper.OP_WRITE_CLIPBOARD },\n new boolean[] { true,\n true,\n true,\n true,\n true,\n true,\n true,\n true,\n true,\n true,\n true,\n true,\n true,\n true,\n true,\n true,\n false,\n false }\n );\n\n public static final OpsTemplate MESSAGING_TEMPLATE = new OpsTemplate(\n new int[] { AppOpsManagerWrapper.OP_READ_SMS,\n AppOpsManagerWrapper.OP_RECEIVE_SMS,\n AppOpsManagerWrapper.OP_RECEIVE_EMERGECY_SMS,\n AppOpsManagerWrapper.OP_RECEIVE_MMS,\n AppOpsManagerWrapper.OP_RECEIVE_WAP_PUSH,\n AppOpsManagerWrapper.OP_WRITE_SMS,\n AppOpsManagerWrapper.OP_SEND_SMS,\n AppOpsManagerWrapper.OP_READ_ICC_SMS,\n AppOpsManagerWrapper.OP_WRITE_ICC_SMS,\n AppOpsManagerWrapper.OP_SEND_MMS,\n AppOpsManagerWrapper.OP_READ_MMS,\n AppOpsManagerWrapper.OP_DELETE_SMS,\n AppOpsManagerWrapper.OP_DELETE_MMS,\n AppOpsManagerWrapper.OP_WRITE_MMS },\n new boolean[] { true,\n true,\n true,\n true,\n true,\n true,\n true,\n true,\n true,\n true,\n true,\n true,\n true,\n true }\n );\n\n public static final OpsTemplate MEDIA_TEMPLATE = new OpsTemplate(\n new int[] { AppOpsManagerWrapper.OP_VIBRATE,\n AppOpsManagerWrapper.OP_CAMERA,\n AppOpsManagerWrapper.OP_RECORD_AUDIO,\n AppOpsManagerWrapper.OP_PLAY_AUDIO,\n AppOpsManagerWrapper.OP_TAKE_MEDIA_BUTTONS,\n AppOpsManagerWrapper.OP_TAKE_AUDIO_FOCUS,\n AppOpsManagerWrapper.OP_AUDIO_MASTER_VOLUME,\n AppOpsManagerWrapper.OP_AUDIO_VOICE_VOLUME,\n AppOpsManagerWrapper.OP_AUDIO_RING_VOLUME,\n AppOpsManagerWrapper.OP_AUDIO_MEDIA_VOLUME,\n AppOpsManagerWrapper.OP_AUDIO_ALARM_VOLUME,\n AppOpsManagerWrapper.OP_AUDIO_NOTIFICATION_VOLUME,\n AppOpsManagerWrapper.OP_AUDIO_BLUETOOTH_VOLUME,\n AppOpsManagerWrapper.OP_AUDIO_FM_VOLUME,\n AppOpsManagerWrapper.OP_AUDIO_MATV_VOLUME,\n AppOpsManagerWrapper.OP_WRITE_WALLPAPER,\n AppOpsManagerWrapper.OP_ASSIST_SCREENSHOT,\n AppOpsManagerWrapper.OP_ASSIST_STRUCTURE,\n AppOpsManagerWrapper.OP_MUTE_MICROPHONE, },\n new boolean[] { false,\n true,\n true,\n false,\n false,\n false,\n false,\n false,\n false,\n false,\n false,\n false,\n false,\n true,\n true,\n true,\n true,\n true,\n true, }\n );\n\n private static final int OP_POST_NOTIFICATION;\n\n static {\n if (AppOpsManagerWrapper.OP_POST_NOTIFICATION == AppOpsManagerWrapper.OP_BOOT_COMPLETED) {\n OP_POST_NOTIFICATION = -1;\n } else {\n OP_POST_NOTIFICATION = AppOpsManagerWrapper.OP_POST_NOTIFICATION;\n }\n }\n\n public static final OpsTemplate DEVICE_TEMPLATE = new OpsTemplate(\n new int[] { OP_POST_NOTIFICATION,\n AppOpsManagerWrapper.OP_ACCESS_NOTIFICATIONS,\n AppOpsManagerWrapper.OP_CALL_PHONE,\n AppOpsManagerWrapper.OP_ADD_VOICEMAIL,\n AppOpsManagerWrapper.OP_USE_SIP,\n AppOpsManagerWrapper.OP_READ_CELL_BROADCASTS,\n AppOpsManagerWrapper.OP_TURN_SCREEN_ON,\n AppOpsManagerWrapper.OP_WRITE_SETTINGS,\n AppOpsManagerWrapper.OP_SYSTEM_ALERT_WINDOW,\n AppOpsManagerWrapper.OP_WAKE_LOCK,\n AppOpsManagerWrapper.OP_ALARM_WAKEUP,\n AppOpsManagerWrapper.OP_WIFI_CHANGE,\n AppOpsManagerWrapper.OP_BLUETOOTH_CHANGE,\n AppOpsManagerWrapper.OP_DATA_CONNECT_CHANGE,\n AppOpsManagerWrapper.OP_NFC_CHANGE,\n AppOpsManagerWrapper.OP_PROJECT_MEDIA,\n AppOpsManagerWrapper.OP_ACTIVATE_VPN,\n AppOpsManagerWrapper.OP_GET_USAGE_STATS,\n AppOpsManagerWrapper.OP_EXACT_ALARM,\n AppOpsManagerWrapper.OP_WAKEUP_ALARM,\n AppOpsManagerWrapper.OP_TOAST_WINDOW, },\n new boolean[] { false,\n true,\n true,\n true,\n true,\n true,\n true,\n true,\n true,\n true,\n true,\n true,\n true,\n true,\n true,\n true,\n true,\n true,\n true,\n true,\n true, }\n );\n\n public static final OpsTemplate BOOTUP_TEMPLATE = new OpsTemplate(\n new int[] { AppOpsManagerWrapper.OP_BOOT_COMPLETED,\n AppOpsManagerWrapper.OP_AUTO_START },\n new boolean[] { true,\n true }\n );\n\n public static final OpsTemplate[] ALL_TEMPLATES = new OpsTemplate[] {\n LOCATION_TEMPLATE, PERSONAL_TEMPLATE, MESSAGING_TEMPLATE,\n MEDIA_TEMPLATE, DEVICE_TEMPLATE, BOOTUP_TEMPLATE\n };\n\n /**\n * This class holds the per-item data in our Loader.\n */\n public static class AppEntry {\n private final AppOpsState mState;\n private final ApplicationInfo mInfo;\n private final File mApkFile;\n private final SparseArray<OpEntryWrapper> mOps\n = new SparseArray<OpEntryWrapper>();\n private final SparseArray<AppOpEntry> mOpSwitches\n = new SparseArray<AppOpEntry>();\n private String mLabel;\n private Drawable mIcon;\n private boolean mMounted;\n private boolean mHasDisallowedOps = false;\n\n public AppEntry(AppOpsState state, ApplicationInfo info) {\n mState = state;\n mInfo = info;\n mApkFile = new File(info.sourceDir);\n }\n\n public void addOp(AppOpEntry entry, OpEntryWrapper op) {\n mOps.put(op.getOp(), op);\n mHasDisallowedOps |= op.getMode() != AppOpsManagerWrapper.MODE_ALLOWED;\n mOpSwitches.put(opToSwitch(op.getOp()), entry);\n }\n\n public boolean hasOp(int op) {\n return mOps.indexOfKey(op) >= 0;\n }\n\n public AppOpEntry getOpSwitch(int op) {\n return mOpSwitches.get(opToSwitch(op));\n }\n\n public ApplicationInfo getApplicationInfo() {\n return mInfo;\n }\n\n public String getLabel() {\n return mLabel;\n }\n\n public Drawable getIcon() {\n if (mIcon == null) {\n if (mApkFile.exists()) {\n mIcon = mInfo.loadIcon(mState.mPm);\n return mIcon;\n } else {\n mMounted = false;\n }\n } else if (!mMounted) {\n // If the app wasn't mounted but is now mounted, reload\n // its icon.\n if (mApkFile.exists()) {\n mMounted = true;\n mIcon = mInfo.loadIcon(mState.mPm);\n return mIcon;\n }\n } else {\n return mIcon;\n }\n\n return mState.mContext.getResources().getDrawable(\n android.R.drawable.sym_def_app_icon);\n }\n\n @Override public String toString() {\n return mLabel;\n }\n\n void loadLabel(Context context) {\n if (mLabel == null || !mMounted) {\n if (!mApkFile.exists()) {\n mMounted = false;\n mLabel = mInfo.packageName;\n } else {\n mMounted = true;\n CharSequence label = mInfo.loadLabel(context.getPackageManager());\n mLabel = label != null ? label.toString() : mInfo.packageName;\n }\n }\n }\n }\n\n /**\n * This class holds the per-item data in our Loader.\n */\n public static class AppOpEntry {\n private final AppOpsManagerWrapper.PackageOpsWrapper mPkgOps;\n private final ArrayList<OpEntryWrapper> mOps\n = new ArrayList<OpEntryWrapper>();\n private final ArrayList<OpEntryWrapper> mSwitchOps\n = new ArrayList<OpEntryWrapper>();\n private final AppEntry mApp;\n private final int mSwitchOrder;\n\n public AppOpEntry(PackageOpsWrapper pkg, OpEntryWrapper op, AppEntry app,\n int switchOrder) {\n mPkgOps = pkg;\n mApp = app;\n mSwitchOrder = switchOrder;\n mApp.addOp(this, op);\n mOps.add(op);\n mSwitchOps.add(op);\n }\n\n private static void addOp(ArrayList<OpEntryWrapper> list, OpEntryWrapper op) {\n for (int i=0; i<list.size(); i++) {\n OpEntryWrapper pos = list.get(i);\n if (pos.isRunning() != op.isRunning()) {\n if (op.isRunning()) {\n list.add(i, op);\n return;\n }\n continue;\n }\n if (pos.getTime() < op.getTime()) {\n list.add(i, op);\n return;\n }\n }\n list.add(op);\n }\n\n public void addOp(OpEntryWrapper op) {\n mApp.addOp(this, op);\n addOp(mOps, op);\n if (mApp.getOpSwitch(opToSwitch(op.getOp())) == null) {\n addOp(mSwitchOps, op);\n }\n }\n\n public AppEntry getAppEntry() {\n return mApp;\n }\n\n public int getSwitchOrder() {\n return mSwitchOrder;\n }\n\n public PackageOpsWrapper getPackageOps() {\n return mPkgOps;\n }\n\n public int getNumOpEntry() {\n return mOps.size();\n }\n\n public OpEntryWrapper getOpEntry(int pos) {\n return mOps.get(pos);\n }\n\n public boolean hasDisallowedOps() {\n return mApp.mHasDisallowedOps;\n }\n\n private static boolean isSwitchChecked(List<OpEntryWrapper> ops, int op) {\n int opSwitch = AppOpsManagerWrapper.opToSwitch(op);\n for (OpEntryWrapper wrapper : ops) {\n if (wrapper.getOp() == opSwitch) {\n return AppOpsDetails.modeToChecked(wrapper.getMode());\n }\n }\n return true;\n }\n\n private CharSequence getCombinedText(Context context, ArrayList<OpEntryWrapper> ops,\n CharSequence[] items, boolean isSummary) {\n SpannableStringBuilder builder = new SpannableStringBuilder();\n Set<String> strings = new HashSet<>();\n for (int i=0; i<ops.size(); i++) {\n int op = ops.get(i).getOp();\n SpannableString ss;\n if (op < items.length && !TextUtils.isEmpty(items[op])) {\n ss = new SpannableString(items[op]);\n } else if (isSummary) {\n ss = new SpannableString(OpsLabelHelper.getOpSummary(context, op));\n } else {\n ss = new SpannableString(OpsLabelHelper.getOpLabel(context, op));\n }\n\n if (!strings.add(ss.toString())) {\n continue;\n }\n\n if (isSummary && !isSwitchChecked(ops, op)) {\n ss.setSpan(new StrikethroughSpan(), 0, ss.length(), 0);\n }\n\n if (i > 0) {\n builder.append(\", \");\n }\n\n builder.append(ss);\n }\n\n return builder;\n }\n\n public CharSequence getSummaryText(Context context, AppOpsState state) {\n return getCombinedText(context, mOps, state.mOpSummaries, true);\n }\n\n public CharSequence getSwitchText(Context context, AppOpsState state) {\n if (mSwitchOps.size() > 0) {\n return getCombinedText(context, mSwitchOps, state.mOpLabels, false);\n } else {\n return getCombinedText(context, mOps, state.mOpLabels, false);\n }\n }\n\n public CharSequence getTimeText(Resources res, boolean showEmptyText) {\n if (isRunning()) {\n return res.getText(R.string.app_ops_running);\n }\n if (getTime() > 0) {\n return DateUtils.getRelativeTimeSpanString(getTime(),\n System.currentTimeMillis(),\n DateUtils.MINUTE_IN_MILLIS,\n DateUtils.FORMAT_ABBREV_RELATIVE);\n }\n return showEmptyText ? res.getText(R.string.app_ops_never_used) : \"\";\n }\n\n public boolean isRunning() {\n return mOps.get(0).isRunning();\n }\n\n public long getTime() {\n return mOps.get(0).getTime();\n }\n\n @Override public String toString() {\n return mApp.getLabel();\n }\n }\n\n /**\n * Perform alphabetical comparison of application entry objects.\n */\n public static final Comparator<AppOpEntry> APP_OP_COMPARATOR = new Comparator<AppOpEntry>() {\n private final Collator sCollator = Collator.getInstance();\n @Override\n public int compare(AppOpEntry object1, AppOpEntry object2) {\n if (object1.getSwitchOrder() != object2.getSwitchOrder()) {\n return object1.getSwitchOrder() < object2.getSwitchOrder() ? -1 : 1;\n }\n if (object1.isRunning() != object2.isRunning()) {\n // Currently running ops go first.\n return object1.isRunning() ? -1 : 1;\n }\n if (object1.getTime() != object2.getTime()) {\n // More recent times go first.\n return object1.getTime() > object2.getTime() ? -1 : 1;\n }\n if (object1.hasDisallowedOps() != object2.hasDisallowedOps()) {\n // Disallowed ops go first.\n return object1.hasDisallowedOps() ? -1 : 1;\n }\n return sCollator.compare(object1.getAppEntry().getLabel(),\n object2.getAppEntry().getLabel());\n }\n };\n\n private void addOp(List<AppOpEntry> entries, PackageOpsWrapper pkgOps,\n AppEntry appEntry, OpEntryWrapper opEntry, boolean allowMerge, int switchOrder) {\n if (allowMerge && entries.size() > 0) {\n AppOpEntry last = entries.get(entries.size()-1);\n if (last.getAppEntry() == appEntry) {\n boolean lastExe = last.getTime() != 0;\n boolean entryExe = opEntry.getTime() != 0;\n if (lastExe == entryExe) {\n if (DEBUG) Log.d(TAG, \"Add op \" + opEntry.getOp() + \" to package \"\n + pkgOps.getPackageName() + \": append to \" + last);\n last.addOp(opEntry);\n return;\n }\n }\n }\n AppOpEntry entry = appEntry.getOpSwitch(opEntry.getOp());\n if (entry != null) {\n entry.addOp(opEntry);\n return;\n }\n entry = new AppOpEntry(pkgOps, opEntry, appEntry, switchOrder);\n if (DEBUG) Log.d(TAG, \"Add op \" + opEntry.getOp() + \" to package \"\n + pkgOps.getPackageName() + \": making new \" + entry);\n entries.add(entry);\n }\n\n public List<AppOpEntry> buildState(OpsTemplate tpl) {\n return buildState(tpl, 0, null);\n }\n\n private AppEntry getAppEntry(final Context context, final HashMap<String, AppEntry> appEntries,\n final String packageName, ApplicationInfo appInfo) {\n AppEntry appEntry = appEntries.get(packageName);\n if (appEntry == null) {\n if (appInfo == null) {\n try {\n appInfo = mPm.getApplicationInfo(packageName,\n PackageManager.GET_DISABLED_COMPONENTS\n | PackageManager.GET_UNINSTALLED_PACKAGES);\n } catch (PackageManager.NameNotFoundException e) {\n Log.w(TAG, \"Unable to find info for package \" + packageName);\n return null;\n }\n }\n appEntry = new AppEntry(this, appInfo);\n appEntry.loadLabel(context);\n appEntries.put(packageName, appEntry);\n }\n return appEntry;\n }\n\n public List<AppOpEntry> buildStateWithChangedOpsOnly() {\n final List<PackageOpsWrapper> pkgs = mAppOps.getPackagesForOps(null);\n final HashMap<String, AppEntry> appEntries = new HashMap<String, AppEntry>();\n final List<AppOpEntry> entries = new ArrayList<AppOpEntry>();\n for (PackageOpsWrapper pkg : pkgs) {\n for (OpEntryWrapper op : pkg.getOps()) {\n if (op.getMode() != AppOpsManagerWrapper.MODE_ALLOWED) {\n final ApplicationInfo appInfo;\n try {\n appInfo= mContext.getPackageManager().getApplicationInfo(\n pkg.getPackageName(), PackageManager.GET_DISABLED_COMPONENTS\n | PackageManager.GET_UNINSTALLED_PACKAGES);\n } catch (PackageManager.NameNotFoundException e) {\n continue;\n }\n final AppEntry app = getAppEntry(mContext, appEntries, appInfo.packageName, appInfo);\n if (app == null) {\n continue;\n }\n addOp(entries, pkg, app, op, true, 0);\n //entries.add(new AppOpEntry(pkg, op, new AppEntry(this, appInfo), 0));\n }\n }\n }\n return entries;\n }\n\n public List<AppOpEntry> buildState(OpsTemplate tpl, int uid, String packageName) {\n final Context context = mContext;\n\n final HashMap<String, AppEntry> appEntries = new HashMap<String, AppEntry>();\n final List<AppOpEntry> entries = new ArrayList<AppOpEntry>();\n\n final ArrayList<String> perms = new ArrayList<String>();\n final ArrayList<Integer> permOps = new ArrayList<Integer>();\n final int[] opToOrder = new int[AppOpsManagerWrapper._NUM_OP];\n for (int i=0; i<tpl.ops.length; i++) {\n if (isValidOp(tpl.ops[i]) && tpl.showPerms[i]) {\n String perm = AppOpsManagerWrapper.opToPermission(tpl.ops[i]);\n if (perm != null && !perms.contains(perm)) {\n perms.add(perm);\n permOps.add(tpl.ops[i]);\n opToOrder[tpl.ops[i]] = i;\n }\n }\n }\n\n List<PackageOpsWrapper> pkgs;\n if (packageName != null) {\n pkgs = mAppOps.getOpsForPackage(uid, packageName, tpl.ops);\n } else {\n pkgs = mAppOps.getPackagesForOpsMerged(tpl.ops);\n }\n\n if (pkgs != null) {\n for (int i=0; i<pkgs.size(); i++) {\n PackageOpsWrapper pkgOps = pkgs.get(i);\n AppEntry appEntry = getAppEntry(context, appEntries, pkgOps.getPackageName(), null);\n if (appEntry == null) {\n continue;\n }\n for (int j=0; j<pkgOps.getOps().size(); j++) {\n OpEntryWrapper opEntry = pkgOps.getOps().get(j);\n addOp(entries, pkgOps, appEntry, opEntry, packageName == null,\n packageName == null ? 0 : opToOrder[opEntry.getOp()]);\n }\n }\n }\n\n List<PackageInfo> apps;\n if (packageName != null) {\n apps = new ArrayList<PackageInfo>();\n try {\n PackageInfo pi = mPm.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS);\n apps.add(pi);\n } catch (NameNotFoundException e) {\n }\n } else {\n String[] permsArray = new String[perms.size()];\n perms.toArray(permsArray);\n apps = mPm.getPackagesHoldingPermissions(permsArray, 0);\n }\n\n for (int i=0; i<apps.size(); i++) {\n PackageInfo appInfo = apps.get(i);\n AppEntry appEntry = getAppEntry(context, appEntries, appInfo.packageName,\n appInfo.applicationInfo);\n if (appEntry == null) {\n continue;\n }\n List<OpEntryWrapper> dummyOps = null;\n PackageOpsWrapper pkgOps = null;\n if (appInfo.requestedPermissions != null) {\n for (int j=0; j<appInfo.requestedPermissions.length; j++) {\n if (appInfo.requestedPermissionsFlags != null) {\n if ((appInfo.requestedPermissionsFlags[j]\n & PackageInfo.REQUESTED_PERMISSION_GRANTED) == 0) {\n if (DEBUG) Log.d(TAG, \"Pkg \" + appInfo.packageName + \" perm \"\n + appInfo.requestedPermissions[j] + \" not granted; skipping\");\n continue;\n }\n }\n if (DEBUG) Log.d(TAG, \"Pkg \" + appInfo.packageName + \": requested perm \"\n + appInfo.requestedPermissions[j]);\n for (int k=0; k<perms.size(); k++) {\n if (!perms.get(k).equals(appInfo.requestedPermissions[j])) {\n continue;\n }\n if (DEBUG) Log.d(TAG, \"Pkg \" + appInfo.packageName + \" perm \" + perms.get(k)\n + \" has op \" + permOps.get(k) + \": \" + appEntry.hasOp(permOps.get(k)));\n if (appEntry.hasOp(permOps.get(k))) {\n continue;\n }\n if (dummyOps == null) {\n dummyOps = new ArrayList<OpEntryWrapper>();\n pkgOps = new PackageOpsWrapper(\n appInfo.packageName, appInfo.applicationInfo.uid, dummyOps);\n\n }\n int mode = mAppOps.checkOpNoThrow(permOps.get(k), appInfo.applicationInfo.uid, appInfo.packageName);\n OpEntryWrapper opEntry = new OpEntryWrapper(\n permOps.get(k), mode, 0, 0, 0);\n dummyOps.add(opEntry);\n addOp(entries, pkgOps, appEntry, opEntry, packageName == null,\n packageName == null ? 0 : opToOrder[opEntry.getOp()]);\n }\n }\n }\n }\n\n // Sort the list.\n Collections.sort(entries, APP_OP_COMPARATOR);\n\n // Done!\n return entries;\n }\n\n private boolean isValidOp(int op)\n {\n if (op >= 0 && op < AppOpsManagerWrapper._NUM_OP) {\n try {\n //mAppOps.checkOp(op, Process.SYSTEM_UID, \"android\");\n return true;\n } catch (IllegalArgumentException e) {\n Log.w(TAG, \"Skipping #\" + op + \" even though it is within valid range\");\n }\n }\n\n return false;\n }\n\n private static int opToSwitch(int op)\n {\n // TODO Implement something like expert mode?\n\n if (true) {\n return AppOpsManagerWrapper.opToSwitch(op);\n }\n\n return op;\n }\n}"
] | import java.lang.reflect.Field;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import android.annotation.TargetApi;
import android.app.AppOpsManager;
import android.app.Fragment;
import android.app.ListFragment;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.AsyncTaskLoader;
import android.content.Context;
import android.content.Loader;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.style.StrikethroughSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import at.jclehner.appopsxposed.util.AppOpsManagerWrapper;
import at.jclehner.appopsxposed.util.AppOpsManagerWrapper.OpEntryWrapper;
import at.jclehner.appopsxposed.util.AppOpsManagerWrapper.PackageOpsWrapper;
import at.jclehner.appopsxposed.util.OpsLabelHelper;
import com.android.settings.applications.AppOpsDetails;
import com.android.settings.applications.AppOpsState; | convertView = mInflater.inflate(R.layout.app_ops_item, parent, false);
holder = new ViewHolder();
holder.appIcon = (ImageView) convertView.findViewById(R.id.app_icon);
holder.appLine2 = (TextView) convertView.findViewById(R.id.op_name);
holder.appName = (TextView) convertView.findViewById(R.id.app_name);
convertView.findViewById(R.id.op_time).setVisibility(View.GONE);
convertView.setTag(holder);
}
else
holder = (ViewHolder) convertView.getTag();
holder.appIcon.setImageDrawable(null);
holder.appName.setText(data.label);
holder.appLine2.setText(data.line2);
if(true && !data.packageInfo.packageName.equals(holder.packageName))
{
if(holder.task != null)
holder.task.cancel(true);
holder.task = new AsyncTask<Void, Void, Object[]>() {
@Override
protected Object[] doInBackground(Void... params)
{
final Object[] result = new Object[2];
result[0] = appInfo.loadIcon(mPm);
//result[1] = appInfo.loadLabel(mPm);
return result;
}
@Override
protected void onPostExecute(Object[] result)
{
holder.appIcon.setImageDrawable((Drawable) result[0]);
/*holder.appName.setText((CharSequence) result[1]);
if(!appInfo.packageName.equals(result[1].toString()))
{
holder.appLine2.setText(appInfo.packageName);
holder.appLine2.setVisibility(View.VISIBLE);
}
else
holder.appLine2.setVisibility(View.GONE);*/
}
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
holder.packageName = appInfo.packageName;
}
else
{
holder.appIcon.setImageDrawable(appInfo.loadIcon(mPm));
holder.appName.setText(appInfo.loadLabel(mPm));
holder.packageName = appInfo.packageName;
}
return convertView;
}
}
static class ViewHolder
{
String packageName;
AsyncTask<Void, Void, Object[]> task;
ImageView appIcon;
TextView appName;
TextView appLine2;
}
static class LoaderDataComparator implements Comparator<PackageInfoData>
{
private static Collator sCollator = Collator.getInstance();
@Override
public int compare(PackageInfoData lhs, PackageInfoData rhs) {
return sCollator.compare(lhs.label, rhs.label);
}
}
static class PackageInfoData
{
final PackageInfo packageInfo;
final CharSequence label;
CharSequence line2;
List<OpEntryWrapper> changedOps;
PackageInfoData(PackageInfo packageInfo, CharSequence label)
{
this.packageInfo = packageInfo;
this.label = label;
line2 = packageInfo.packageName;
}
}
static class AppListLoader extends AsyncTaskLoader<List<PackageInfoData>>
{
private static String[] sOpPerms = getOpPermissions();
private final AppOpsState mState;
private final PackageManager mPm;
private List<PackageInfoData> mData;
private final boolean mRemoveAppsWithUnchangedOps;
public AppListLoader(Context context, boolean removeAppsWithUnchangedOps)
{
super(context);
mState = new AppOpsState(context);
mPm = context.getPackageManager();
mRemoveAppsWithUnchangedOps = removeAppsWithUnchangedOps;
}
@Override
public List<PackageInfoData> loadInBackground()
{
final List<PackageInfoData> data = new ArrayList<PackageInfoData>();
| final AppOpsManagerWrapper appOps = AppOpsManagerWrapper.from(getContext()); | 0 |
AlexanderMisel/gnubridge | src/main/java/org/gnubridge/core/bidding/rules/Respond1ColorWithNewSuit.java | [
"public class Hand {\n\tList<Card> cards;\n\n\t/**\n\t * Caching optimization for pruning played cards\n\t * and perhaps others\n\t */\n\tList<Card> orderedCards;\n\tSuit color;\n\tList<Card> colorInOrder;\n\n\tpublic Hand() {\n\t\tthis.cards = new ArrayList<Card>();\n\t}\n\n\tpublic Hand(Card... cards) {\n\t\tthis();\n\t\tfor (Card card : cards) {\n\t\t\tthis.cards.add(card);\n\t\t}\n\t}\n\n\tpublic Hand(List<Card> cards) {\n\t\tthis();\n\t\tthis.cards.addAll(cards);\n\t}\n\n\tpublic Hand(String... colorSuits) {\n\t\tthis();\n\t\tint i = 0;\n\t\tfor (String colorSuit : colorSuits) {\n\t\t\tcards.addAll(createCards(colorSuit, Suit.list[i]));\n\t\t\ti++;\n\t\t}\n\n\t}\n\n\tpublic void add(Card c) {\n\t\tcards.add(c);\n\t\torderedCards = null;\n\t\tif (c.getDenomination().equals(color)) {\n\t\t\tcolorInOrder = null;\n\t\t}\n\n\t}\n\n\tprivate Collection<? extends Card> createCards(String colorSuit, Suit color) {\n\t\tList<Card> results = new ArrayList<Card>();\n\t\tif (!\"\".equals(colorSuit.trim())) {\n\n\t\t\tString[] cardTokens = colorSuit.split(\",\");\n\t\t\tfor (String cardToken : cardTokens) {\n\t\t\t\tresults.add(new Card(cardToken, color));\n\t\t\t}\n\t\t}\n\t\treturn results;\n\t}\n\n\tpublic List<Card> getSuitHi2Low(Suit suit) {\n\t\tif (suit.equals(this.color) && colorInOrder != null) {\n\t\t\treturn colorInOrder;\n\t\t}\n\t\tList<Card> result = new ArrayList<Card>();\n\t\tfor (Card card : cards) {\n\t\t\tif (card.getDenomination().equals(suit)) {\n\t\t\t\tinsertInOrder(result, card);\n\n\t\t\t}\n\t\t}\n\t\tthis.color = suit;\n\t\tcolorInOrder = result;\n\t\treturn result;\n\t}\n\n\tprivate void insertInOrder(List<Card> ordered, Card x) {\n\t\tif (ordered.isEmpty()) {\n\t\t\tordered.add(x);\n\t\t} else {\n\t\t\tint i = 0;\n\t\t\tboolean inserted = false;\n\t\t\tfor (Card card : ordered) {\n\t\t\t\tif (!card.hasGreaterValueThan(x)) {\n\t\t\t\t\tordered.add(i, x);\n\t\t\t\t\tinserted = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\ti++;\n\t\t\t}\n\t\t\tif (!inserted) {\n\t\t\t\tordered.add(x);\n\t\t\t}\n\t\t}\n\n\t}\n\n\tpublic int getSuitLength(Suit suit) {\n\t\treturn getSuitHi2Low(suit).size();\n\t}\n\n\tpublic List<Card> getCardsHighToLow() {\n\t\tif (orderedCards != null) {\n\t\t\tList<Card> copyOfOrderedCards = new ArrayList<Card>();\n\t\t\tcopyOfOrderedCards.addAll(orderedCards);\n\t\t\treturn copyOfOrderedCards;\n\t\t}\n\t\tList<Card> orderedCards = new ArrayList<Card>();\n\t\tfor (Suit color : Suit.list) {\n\t\t\torderedCards.addAll(getSuitHi2Low(color));\n\t\t}\n\t\tthis.orderedCards = orderedCards;\n\t\treturn getCardsHighToLow();\n\t}\n\n\tpublic Suit getLongestSuit() {\n\t\tint longest = 0;\n\t\tSuit result = null;\n\t\tfor (Suit suit : Suit.list) {\n\t\t\tif (longest < getSuitLength(suit)) {\n\t\t\t\tlongest = getSuitLength(suit);\n\t\t\t\tresult = suit;\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\n\tpublic int getLongestColorLength() {\n\t\tint result = 0;\n\t\tfor (Suit color : Suit.list) {\n\t\t\tif (result < getSuitLength(color)) {\n\t\t\t\tresult = getSuitLength(color);\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\n\tpublic boolean contains(Card card) {\n\t\tif (cards.size() == 0 && card == null) {\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn cards.contains(card);\n\t\t}\n\t}\n\n\tpublic boolean isEmpty() {\n\t\treturn cards.isEmpty();\n\t}\n\n\tpublic boolean matchesSuitLengthsLongToShort(int suitLength1, int suitLength2, int suitLength3, int suitLength4) {\n\t\tList<Integer> suitLengths = new ArrayList<Integer>();\n\t\tfor (Suit color : Suit.list) {\n\t\t\tsuitLengths.add(getSuitLength(color));\n\t\t}\n\t\tCollections.sort(suitLengths);\n\t\tCollections.reverse(suitLengths);\n\t\tif (suitLengths.get(0) == suitLength1 && suitLengths.get(1) == suitLength2 && suitLengths.get(2) == suitLength3\n\t\t\t\t&& suitLengths.get(3) == suitLength4) {\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tpublic List<Suit> getSuitsWithAtLeastCards(int minimumSuitLength) {\n\t\tList<Suit> results = new ArrayList<Suit>();\n\t\tfor (Suit suit : Suit.mmList) {\n\t\t\tif (getSuitLength(suit) >= minimumSuitLength) {\n\t\t\t\tresults.add(suit);\n\t\t\t}\n\t\t}\n\t\treturn results;\n\t}\n\n\tpublic List<Suit> getSuitsWithCardCount(int suitLength) {\n\t\tList<Suit> results = new ArrayList<Suit>();\n\t\tfor (Suit suit : Suit.list) {\n\t\t\tif (getSuitLength(suit) == suitLength) {\n\t\t\t\tresults.add(suit);\n\t\t\t}\n\t\t}\n\t\treturn results;\n\t}\n\n\t//at least AQJXXX or KQTXXX\n\t//Pavlicek, lesson 7 online bridge basics\n\tpublic Collection<Suit> getGood5LengthSuits() {\n\t\tCollection<Suit> result = new ArrayList<Suit>();\n\t\tfor (Suit suit : Suit.list) {\n\t\t\tif (isGood5LengthSuits(suit)) {\n\t\t\t\tresult.add(suit);\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\n\tpublic boolean isGood5LengthSuits(Suit suit) {\n\t\tList<Card> cardsInSuit = getSuitHi2Low(suit);\n\t\treturn getSuitLength(suit) >= 5 &&\n\t\t\t\t(isAtLeastAQJXX(cardsInSuit) || isAtLeastKQTXX(cardsInSuit));\n\t}\n\n\t//at least QJXXX\n\t//Pavlicek, lesson 7 online bridge basics\n\tpublic Collection<Suit> getDecent5LengthSuits() {\n\t\tCollection<Suit> result = new ArrayList<Suit>();\n\t\tfor (Suit suit : Suit.list) {\n\t\t\tif (isDecent5LengthSuits(suit)) {\n\t\t\t\tresult.add(suit);\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\n\tpublic boolean isDecent5LengthSuits(Suit suit) {\n\t\tList<Card> cardsInSuit = getSuitHi2Low(suit);\n\t\treturn getSuitLength(suit) >= 5 &&\n\t\t\t\tisAtLeastQJXXX(cardsInSuit);\n\t}\n\n\tprivate boolean isAtLeastQJXXX(List<Card> fiveCards) {\n\t\tif (fiveCards.get(0).getValue() >= Card.QUEEN && // keep Eclipse from formatting\n\t\t\t\tfiveCards.get(1).getValue() >= Card.JACK //\n\n\t\t) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tprivate boolean isAtLeastKQTXX(List<Card> fiveCards) {\n\t\tif (fiveCards.get(0).getValue() >= Card.KING && // \n\t\t\t\tfiveCards.get(1).getValue() >= Card.QUEEN && // \n\t\t\t\tfiveCards.get(2).getValue() >= Card.TEN //\n\n\t\t) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tprivate boolean isAtLeastAQJXX(List<Card> fiveCards) {\n\t\tif (fiveCards.get(0).getValue() >= Card.ACE && //\n\t\t\t\tfiveCards.get(1).getValue() >= Card.QUEEN && //\n\t\t\t\tfiveCards.get(2).getValue() >= Card.JACK //\n\n\t\t) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tpublic boolean haveStopper(Suit suit) {\n\t\tList<Card> cardsInSuit = getSuitHi2Low(suit);\n\t\tif (cardsInSuit.size() > 0 && cardsInSuit.get(0).getValue() == Card.ACE) {\n\t\t\treturn true;\n\t\t}\n\t\tif (cardsInSuit.size() > 1 && cardsInSuit.get(0).getValue() == Card.KING) {\n\t\t\treturn true;\n\t\t}\n\t\tif (cardsInSuit.size() > 2 && cardsInSuit.get(0).getValue() == Card.QUEEN) {\n\t\t\treturn true;\n\t\t}\n\t\tif (cardsInSuit.size() > 3 && cardsInSuit.get(0).getValue() == Card.JACK) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tpublic boolean haveStrongStopper(Suit suit) {\n\t\tList<Card> cardsInSuit = getSuitHi2Low(suit);\n\t\tint size = cardsInSuit.size();\n\t\tif (size < 2) {\n\t\t\treturn false;\n\t\t} else if (size <= 3) {\n\t\t\tif (cardsInSuit.get(0).getValue() != Card.ACE && cardsInSuit.get(0).getValue() != Card.KING) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t} else {\n\t\t\tint bigThree = 0, bigFive = 0;\n\t\t\tfor (int i = 0; i < size; ++i) {\n\t\t\t\tint value = cards.get(i).getValue();\n\t\t\t\tif (value >= Card.QUEEN) {\n\t\t\t\t\tbigThree++;\n\t\t\t\t}\n\t\t\t\tif (value >= Card.TEN) {\n\t\t\t\t\tbigFive++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (bigThree < 2 && bigFive < 3) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n\n\tpublic boolean AisStronger(Suit A, Suit B) {\n\t\treturn (B == null || getSuitLength(A) > getSuitLength(B));\n\t}\n\n}",
"public class Auctioneer {\n\tprivate Direction nextToBid;\n\tprivate int passCount;\n\tprivate Bid highBid;\n\tprivate int bidCount;\n\tprivate Call last;\n\tprivate Call beforeLast;\n\tprivate final List<Call> calls;\n\tprivate Vulnerability vulnerability;\n\n\tpublic Auctioneer(Direction firstToBid) {\n\t\tthis.nextToBid = firstToBid;\n\t\tbidCount = 0;\n\t\tlast = null;\n\t\tbeforeLast = null;\n\t\tcalls = new ArrayList<Call>();\n\t}\n\n\tpublic void setVulnerability(Vulnerability v) {\n\t\tvulnerability = v;\n\t}\n\n\tpublic Direction getNextToBid() {\n\t\treturn nextToBid;\n\t}\n\n\tpublic int getVulnerabilityIndex() {\n\t\tint result = 0;\n\t\tif (nextToBid.getValue() == Direction.NORTH_DEPRECATED || nextToBid.getValue() == Direction.SOUTH_DEPRECATED) {\n\t\t\tresult += vulnerability.isDeclarerVulnerable() ? 2 : 0;\n\t\t\tresult += vulnerability.isDefenderVulnerable() ? 1 : 0;\n\t\t} else {\n\t\t\tresult += vulnerability.isDefenderVulnerable() ? 2 : 0;\n\t\t\tresult += vulnerability.isDeclarerVulnerable() ? 1 : 0;\n\t\t}\n\t\treturn result;\n\t}\n\n\tpublic List<Call> getCalls() {\n\t\tArrayList<Call> result = new ArrayList<Call>();\n\t\tresult.addAll(calls);\n\t\treturn result;\n\t}\n\n\tpublic void bid(Bid b) {\n\t\tBid bid = Bid.cloneBid(b);\n\t\tbeforeLast = last;\n\t\tlast = new Call(bid, nextToBid);\n\t\tcalls.add(last);\n\t\tbidCount++;\n\t\tif (bid.isPass()) {\n\t\t\tpassCount++;\n\t\t} else {\n\t\t\tpassCount = 0;\n\t\t\tif (DOUBLE.equals(bid)) {\n\t\t\t\tgetHighBid().makeDoubled();\n\t\t\t} else {\n\t\t\t\thighBid = bid;\n\t\t\t}\n\t\t}\n\n\t\tnextToBid = nextToBid.clockwise();\n\t}\n\n\tpublic boolean biddingFinished() {\n\t\treturn (passCount == 3 && highBid != null) || passCount == 4;\n\t}\n\n\tpublic Bid getHighBid() {\n\t\treturn highBid;\n\t}\n\n\tpublic boolean isOpeningBid() {\n\t\tfor (Call call : calls) {\n\t\t\tif (!call.isPass()) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n\n\tpublic Call getPartnersLastCall() {\n\t\treturn beforeLast;\n\t}\n\n\tpublic Call getPartnersCall(Call playerCall) {\n\t\tint current = calls.indexOf(playerCall);\n\t\tif (current >= 2) {\n\t\t\treturn calls.get(current - 2);\n\t\t} else {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tpublic Call getLastCall() {\n\t\treturn last;\n\t}\n\n\tpublic boolean isValid(Bid candidate) {\n\t\tboolean result = false;\n\t\tif (candidate != null) {\n\t\t\tif (candidate.equals(DOUBLE)) {\n\t\t\t\tif (getHighCall() != null && !getHighCall().pairMatches(nextToBid) && !getHighBid().isDoubled()) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t} else if (candidate.isPass() || candidate.greaterThan(getHighBid())) {\n\t\t\t\tresult = true;\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\n\tpublic Direction getDummy() {\n\t\tDirection result = null;\n\t\tif (biddingFinished() && getHighCall() != null) {\n\t\t\tfor (Call call : calls) {\n\t\t\t\tif (call.getBid().hasTrump() && call.getTrump().equals(getHighCall().getTrump())\n\t\t\t\t\t\t&& call.pairMatches(getHighCall().getDirection())) {\n\t\t\t\t\tresult = call.getDirection().opposite();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\n\tpublic Call getHighCall() {\n\t\tBid highBid = this.highBid;\n\t\tfor (Call call : calls) {\n\t\t\tif (call.getBid().equals(highBid)) {\n\t\t\t\treturn call;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic Call enemyCallBeforePartner(Bid myBid) {\n\t\tint myOrder;\n\t\tif (myBid == null) {\n\t\t\tmyOrder = bidCount;\n\t\t} else {\n\t\t\tmyOrder = getCallOrderZeroBased(myBid);\n\t\t}\n\t\treturn getDirectEnemyCall(myOrder - 2);\n\t}\n\t\n\tprivate Call getDirectEnemyCall(int callOrder) {\n\t\tCall enemyCall = calls.get(callOrder - 1);\n\t\tif (enemyCall.isPass()) {\n\t\t\tenemyCall = calls.get(callOrder - 3);\n\t\t}\n\t\treturn enemyCall;\n\t}\n\n\t/**\n\t * The parties in bidding are referred to by directions of the world, but\n\t * these are not the same directions as the ones during play. This method\n\t * provides a way to find the offset from what this class considers a\n\t * direction and what direction ends up being when the contract is played.\n\t * \n\t * ie: if auction's West becomes the dummy (South during play), the offset\n\t * is 1 move clockwise, and when given South as parameter, this method \n\t * returns West.\n\t */\n\tpublic Direction getDummyOffsetDirection(Direction original) {\n\t\tDirection d = getDummy();\n\t\tDirection offset = original;\n\t\tfor (int i = 0; i < 4; i++) {\n\t\t\tif (d.equals(NORTH)) {\n\t\t\t\tbreak;\n\t\t\t} else {\n\t\t\t\td = d.clockwise();\n\t\t\t\toffset = offset.clockwise();\n\t\t\t}\n\t\t}\n\t\treturn offset;\n\t}\n\n\tpublic boolean may2ndOvercall() {\n\t\tif (bidCount == 0 || bidCount > 6) {\n\t\t\treturn false;\n\t\t}\n\t\tBid opening = calls.get(bidCount - 1).getBid();\n\t\tif (opening.getValue() == 1) {\n\t\t\tif (bidCount >= 3) {\n\t\t\t\tif(!calls.get(bidCount - 3).isPass()) {\n\t\t\t\t\topening = calls.get(bidCount - 3).getBid();\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn isOpening(opening);\n\t\t}\n\t\treturn false;\n\t}\n\n\tpublic boolean may4thOvercall() {\n\t\tif (passCount != 2 || bidCount < 3 || bidCount > 6) {\n\t\t\treturn false;\n\t\t}\n\t\tBid opening = calls.get(bidCount - 3).getBid();\n\t\tif (isOpening(opening) && opening.getValue() == 1) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tprivate int getCallOrderZeroBased(Bid bid) {\n\t\tint result = -1;\n\t\tfor (Call call : calls) {\n\t\t\tresult++;\n\t\t\tif (bid.equals(call.getBid())) {\n\t\t\t\treturn result;\n\t\t\t}\n\t\t}\n\t\treturn -1;\n\t}\n\n\tprivate int OvercallIndex(Bid bid) {\n\t\tif (PASS.equals(bid)) {\n\t\t\treturn 0;\n\t\t}\n\t\tint countPass = 0;\n\t\tint callOrder = getCallOrderZeroBased(bid);\n\t\tif (isOpening(calls.get(callOrder).getBid())) {\n\t\t\treturn 0;\n\t\t}\n\t\tboolean ourBid = false;\n\t\twhile (callOrder != 0) {\n\t\t\tcallOrder--;\n\t\t\tCall call = calls.get(callOrder);\n\t\t\tif (!call.isPass()) {\n\t\t\t\tif (ourBid) {\n\t\t\t\t\tcountPass = -1;\n\t\t\t\t\tbreak;\n\t\t\t\t} else if (isOpening(call.getBid())) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (callOrder >= 2) {\n\t\t\t\t\tif (calls.get(callOrder - 1).isPass() && isOpening(calls.get(callOrder - 2).getBid())) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcountPass = -1;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcountPass++;\n\t\t\tourBid = !ourBid;\n\t\t}\n\t\tif (countPass == 0) {\n\t\t\treturn 1;\n\t\t} else if (countPass == 2) {\n\t\t\treturn -1;\n\t\t} else {\n\t\t\treturn 0;\n\t\t}\n\t}\n\n\tpublic boolean isOvercall(Bid bid) {\n\t\treturn OvercallIndex(bid) != 0;\n\t}\n\n\tpublic boolean isFourthOvercall(Bid bid) {\n\t\treturn OvercallIndex(bid) == -1;\n\t}\n\n\tpublic Set<Trump> getEnemyTrumps() {\n\t\tSet<Trump> result = new HashSet<Trump>();\n\t\tList<Call> reversedCalls = getCalls();\n\t\tCollections.reverse(reversedCalls);\n\t\tboolean enemyBid = true;\n\t\tfor (Call call : reversedCalls) {\n\t\t\tif (call.getBid().hasTrump() && enemyBid) {\n\t\t\t\tresult.add(call.getTrump());\n\t\t\t}\n\t\t\tenemyBid = !enemyBid;\n\t\t}\n\n\t\treturn result;\n\t}\n\t\n\tpublic int biddingSequenceLength() {\n\t\tList<Call> reversedCalls = getCalls();\n\t\tCollections.reverse(reversedCalls);\n\t\tboolean ourBid = false;\n\t\tint seqLength = 0;\n\t\tfor (Call call : reversedCalls) {\n\t\t\tif (ourBid) {\n\t\t\t\tif (call.getBid().hasTrump()) {\n\t\t\t\t\tseqLength++;\n\t\t\t\t} else {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tourBid = !ourBid;\n\t\t}\n\t\treturn seqLength;\n\t}\n\n\tpublic boolean isOpening(Bid bidWithTrump) {\n\t\tint index = getCallOrderZeroBased(bidWithTrump);\n\t\tif (index > 3) {\n\t\t\treturn false;\n\t\t}\n\t\tif (index == 0) {\n\t\t\treturn true;\n\t\t}\n\t\tif (index == 1 && calls.get(0).isPass()) {\n\t\t\treturn true;\n\t\t}\n\t\tif (index == 2 && calls.get(0).isPass() && calls.get(1).isPass()) {\n\t\t\treturn true;\n\t\t}\n\t\tif (index == 3 && calls.get(0).isPass() && calls.get(1).isPass() && calls.get(2).isPass()) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n}",
"public class Bid {\n\tpublic static Bid PASS = new Pass();\n\tpublic static Bid DOUBLE = new Double();\n\tpublic static Bid REDOUBLE = new Redouble();\n\n\tpublic static Bid ONE_NOTRUMP = new Bid(1, NOTRUMP);\n\tpublic static Bid ONE_SPADES = new Bid(1, SPADES);\n\tpublic static Bid ONE_HEARTS = new Bid(1, HEARTS);\n\tpublic static Bid ONE_DIAMONDS = new Bid(1, DIAMONDS);\n\tpublic static Bid ONE_CLUBS = new Bid(1, CLUBS);\n\n\tpublic static Bid TWO_NOTRUMP = new Bid(2, NOTRUMP);\n\tpublic static Bid TWO_SPADES = new Bid(2, SPADES);\n\tpublic static Bid TWO_HEARTS = new Bid(2, HEARTS);\n\tpublic static Bid TWO_DIAMONDS = new Bid(2, DIAMONDS);\n\tpublic static Bid TWO_CLUBS = new Bid(2, CLUBS);\n\n\tpublic static Bid THREE_NOTRUMP = new Bid(3, NOTRUMP);\n\tpublic static Bid THREE_SPADES = new Bid(3, SPADES);\n\tpublic static Bid THREE_HEARTS = new Bid(3, HEARTS);\n\tpublic static Bid THREE_DIAMONDS = new Bid(3, DIAMONDS);\n\tpublic static Bid THREE_CLUBS = new Bid(3, CLUBS);\n\n\tpublic static Bid FOUR_NOTRUMP = new Bid(4, NOTRUMP);\n\tpublic static Bid FOUR_SPADES = new Bid(4, SPADES);\n\tpublic static Bid FOUR_HEARTS = new Bid(4, HEARTS);\n\tpublic static Bid FOUR_DIAMONDS = new Bid(4, DIAMONDS);\n\tpublic static Bid FOUR_CLUBS = new Bid(4, CLUBS);\n\n\tpublic static Bid FIVE_NOTRUMP = new Bid(5, NOTRUMP);\n\tpublic static Bid FIVE_SPADES = new Bid(5, SPADES);\n\tpublic static Bid FIVE_HEARTS = new Bid(5, HEARTS);\n\tpublic static Bid FIVE_DIAMONDS = new Bid(5, DIAMONDS);\n\tpublic static Bid FIVE_CLUBS = new Bid(5, CLUBS);\n\n\tpublic static Bid SIX_NOTRUMP = new Bid(6, NOTRUMP);\n\tpublic static Bid SIX_SPADES = new Bid(6, SPADES);\n\tpublic static Bid SIX_HEARTS = new Bid(6, HEARTS);\n\tpublic static Bid SIX_DIAMONDS = new Bid(6, DIAMONDS);\n\tpublic static Bid SIX_CLUBS = new Bid(6, CLUBS);\n\n\tpublic static Bid SEVEN_NOTRUMP = new Bid(7, NOTRUMP);\n\tpublic static Bid SEVEN_SPADES = new Bid(7, SPADES);\n\tpublic static Bid SEVEN_HEARTS = new Bid(7, HEARTS);\n\tpublic static Bid SEVEN_DIAMONDS = new Bid(7, DIAMONDS);\n\tpublic static Bid SEVEN_CLUBS = new Bid(7, CLUBS);\n\n\tprivate final int value;\n\tprivate final Trump trump;\n\tprivate boolean forcing = false;\n\tprivate boolean gameForcing = false;\n\tprivate boolean doubled = false;\n\n\tpublic Bid(int v, Trump c) {\n\t\tvalue = v;\n\t\ttrump = c;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object other) {\n\t\tif (!(other instanceof Bid)) {\n\t\t\treturn super.equals(other);\n\t\t} else {\n\t\t\treturn value == ((Bid) other).getValue() && trump == ((Bid) other).getTrump();\n\t\t}\n\t}\n\n\tpublic int getValue() {\n\t\treturn value;\n\t}\n\n\tpublic Trump getTrump() {\n\t\treturn trump;\n\t}\n\n\tpublic boolean greaterThan(Bid other) {\n\t\tif (other == null) {\n\t\t\treturn true;\n\t\t}\n\t\tif (this.equals(new Pass())) {\n\t\t\treturn false;\n\t\t}\n\t\tif (new Pass().equals(other)) {\n\t\t\treturn true;\n\t\t}\n\t\tif (getValue() > other.getValue()) {\n\t\t\treturn true;\n\t\t} else if (getValue() < other.getValue()) {\n\t\t\treturn false;\n\t\t} else {\n\t\t\treturn isColorGreater(other);\n\t\t}\n\t}\n\n\tprivate boolean isColorGreater(Bid other) {\n\t\tif (Clubs.i().equals(trump)) {\n\t\t\treturn false;\n\t\t}\n\t\tif (trump.equals(Diamonds.i())) {\n\t\t\tif (other.getTrump().equals(Clubs.i())) {\n\t\t\t\treturn true;\n\t\t\t} else {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\tif (trump.equals(Hearts.i())) {\n\t\t\tif (other.getTrump().equals(Clubs.i()) || other.getTrump().equals(Diamonds.i())) {\n\t\t\t\treturn true;\n\t\t\t} else {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\tif (trump.equals(Spades.i())) {\n\t\t\tif (other.getTrump().equals(Clubs.i()) || other.getTrump().equals(Diamonds.i())\n\t\t\t\t\t|| other.getTrump().equals(Hearts.i())) {\n\t\t\t\treturn true;\n\t\t\t} else {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\tif (!NoTrump.i().equals(other.getTrump())) {\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn Integer.toString(getValue()) + \" \" + trump.toString();\n\t}\n\n\tpublic static Bid makeBid(int bidSize, String t) {\n\t\tif (Pass.stringValue().equals(t.toUpperCase())) {\n\t\t\treturn new Pass();\n\n\t\t} else if (Double.stringValue().equals(t.toUpperCase())) {\n\t\t\treturn new Double();\n\t\t}\n\t\treturn new Bid(bidSize, Trump.instance(t));\n\t}\n\n\tpublic boolean isPass() {\n\t\treturn PASS.equals(this);\n\t}\n\n\tpublic boolean isForcing() {\n\t\treturn forcing;\n\t}\n\n\tpublic boolean isGameForcing() {\n\t\treturn gameForcing;\n\t}\n\n\tpublic void makeForcing() {\n\t\tforcing = true;\n\n\t}\n\n\tpublic void makeGameForcing() {\n\t\tforcing = true;\n\t\tgameForcing = true;\n\n\t}\n\n\tpublic boolean is1Suit() {\n\t\tif (getValue() == 1 && getTrump().isSuit()) {\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tpublic Bid makeDoubled() {\n\t\tdoubled = true;\n\t\treturn this;\n\t}\n\n\tpublic boolean isDoubled() {\n\t\treturn doubled;\n\t}\n\n\t/**\n\t * @return false if the bid is Pass, Double, or Redouble;\n\t * otherwise true\n\t */\n\tpublic boolean hasTrump() {\n\t\treturn getTrump() != null;\n\t}\n\n\tpublic static Bid cloneBid(Bid b) {\n\t\tif (b.hasTrump()) {\n\t\t\treturn new Bid(b.getValue(), b.getTrump());\n\t\t} else if (b.isPass()) {\n\t\t\treturn new Pass();\n\t\t} else if (b.isDouble()) {\n\t\t\treturn new Double();\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic boolean isDouble() {\n\t\treturn DOUBLE.equals(this);\n\t}\n\n\tpublic String longDescription() {\n\t\tString result = toString();\n\t\tif (isDoubled()) {\n\t\t\tresult += \" (Doubled)\";\n\t\t}\n\t\treturn result;\n\t}\n}",
"public class ResponseCalculator extends PointCalculator {\n\n\tprivate Bid partnersBid = null;\n\n\tprivate ResponseCalculator(Hand hand) {\n\t\tsuper(hand);\n\t}\n\n\tpublic ResponseCalculator(Hand hand, Bid partnersBid) {\n\t\tthis(hand);\n\t\tthis.partnersBid = partnersBid;\n\t}\n\n\t@Override\n\tprotected int distributionalValueForCardsInSuit(Suit suit) {\n\t\tif (!partnersBidIsASuit()) {\n\t\t\treturn super.distributionalValueForCardsInSuit(suit);\n\t\t}\n\t\tif (suit.equals(partnersBid.getTrump())) {\n\t\t\treturn 0;\n\t\t}\n\t\tint result = super.distributionalValueForCardsInSuit(suit);\n\t\tif (4 <= hand.getSuitLength(partnersBid.getTrump().asSuit())) {\n\t\t\tint colorLength = hand.getSuitLength(suit);\n\t\t\tif (colorLength == 0) {\n\t\t\t\tresult += 2;\n\t\t\t} else if (colorLength == 1) {\n\t\t\t\tresult += 1;\n\t\t\t}\n\t\t}\n\n\t\treturn result;\n\t}\n\n\tprivate boolean partnersBidIsASuit() {\n\t\treturn partnersBid.getTrump() instanceof Suit;\n\t}\n\n}",
"public class NoTrump extends Trump {\n\n\tprivate static NoTrump instance = new NoTrump();\n\n\tprivate NoTrump() {\n\t\tsuper();\n\t}\n\t\n\tpublic static NoTrump i() {\n\t\treturn instance ;\n\t}\t\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"NT\";\n\t}\n\n\t@Override\n\tpublic String toDebugString() {\n\t\treturn \"NoTrump.i()\";\n\t}\n\n}",
"public abstract class Suit extends Trump {\n\n\t//note, DO NOT USE statics from Trump here, ie SPADES instead of Spades.i()\n\tpublic static final Suit[] list = { Spades.i(), Hearts.i(), Diamonds.i(), Clubs.i() };\n\tpublic static final Suit[] reverseList = { Clubs.i(), Diamonds.i(), Hearts.i(), Spades.i(), };\n\tpublic static final Suit[] mmList = { Hearts.i(), Spades.i(), Clubs.i(), Diamonds.i() };\n\n\tpublic static int getIndex(Suit denomination) {\n\t\tint result = -1;\n\t\tfor (Suit suit : reverseList) {\n\t\t\tresult++;\n\t\t\tif (suit.equals(denomination)) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic abstract String toDebugString();\n\n\tpublic boolean isLowerRankThan(Trump other) {\n\t\tif (other.isNoTrump()) {\n\t\t\treturn true;\n\t\t}\n\t\treturn getIndex(this) < getIndex(other.asSuit());\n\t}\n\n\tpublic static Suit get(String s) {\n\t\tif (\"S\".equals(s)) {\n\t\t\treturn Spades.i();\n\t\t} else if (\"H\".equals(s)) {\n\t\t\treturn Hearts.i();\n\t\t} else if (\"D\".equals(s)) {\n\t\t\treturn Diamonds.i();\n\t\t} else if (\"C\".equals(s)) {\n\t\t\treturn Clubs.i();\n\t\t} else {\n\t\t\tthrow new RuntimeException(\"do not know how to translate string '\" + s\n\t\t\t\t\t+ \"' to a suit (need one of: S,H,D,C)\");\n\t\t}\n\t}\n}"
] | import org.gnubridge.core.Hand;
import org.gnubridge.core.bidding.Auctioneer;
import org.gnubridge.core.bidding.Bid;
import org.gnubridge.core.bidding.ResponseCalculator;
import org.gnubridge.core.deck.Clubs;
import org.gnubridge.core.deck.Diamonds;
import org.gnubridge.core.deck.NoTrump;
import org.gnubridge.core.deck.Suit; | package org.gnubridge.core.bidding.rules;
public class Respond1ColorWithNewSuit extends Response {
private ResponseCalculator pc;
private Suit unbidSuit;
| public Respond1ColorWithNewSuit(Auctioneer a, Hand h) { | 1 |
angusmacdonald/wordbrain-solver | src/test/nyc/angus/wordgrid/test/SolverTests.java | [
"public class DictionaryLoader {\n\tprivate final static Logger LOGGER = Logger.getLogger(DictionaryLoader.class.getName());\n\n\tprivate DictionaryLoader() {\n\t\t// Static methods. Should not be instantiated.\n\t}\n\n\t/**\n\t * Load the dictionary from the given location into memory.\n\t * <p>\n\t * The dictionary should be a text file, where each word is on its own line in the file.\n\t * \n\t * @param fileLocation\n\t * Path to the dictionary on disk.\n\t * @return The dictionary of words in a set.\n\t * @throws IOException\n\t * If the dictionary could not be loaded, including if the file could not be found.\n\t */\n\tpublic static Set<String> loadDictionary(final String fileLocation) throws IOException {\n\t\tLOGGER.log(Level.FINE, \"Reading dictionary...\");\n\n\t\tfinal InputStream inputStream = DictionaryLoader.class.getResourceAsStream(fileLocation);\n\n\t\tif (inputStream != null) {\n\n\t\t\treturn readLinesFromInputStream(inputStream);\n\n\t\t} else {\n\t\t\tthrow new IOException(\"Could not create input stream.\");\n\t\t}\n\t}\n\n\tprivate static Set<String> readLinesFromInputStream(final InputStream inputStream) throws IOException {\n\t\ttry (InputStreamReader inputStreamReader = new InputStreamReader(inputStream);\n\t\t\t\tBufferedReader bufferedReader = new BufferedReader(inputStreamReader)) {\n\n\t\t\tfinal Set<String> lines = new HashSet<String>();\n\n\t\t\tString line;\n\n\t\t\twhile ((line = bufferedReader.readLine()) != null) {\n\t\t\t\tlines.add(line);\n\t\t\t}\n\n\t\t\tLOGGER.log(Level.FINE, \"Finished reading dictionary...\");\n\n\t\t\treturn lines;\n\t\t}\n\t}\n}",
"public class TrieDictionary implements Dictionary {\n\tprivate final TrieNode root = new TrieNode(' ', false);\n\n\tprivate TrieDictionary() {\n\t\t// Private constructor, use createTrie instead.\n\t}\n\n\t/**\n\t * Create a trie by initializing it with the provided dictionary.\n\t */\n\tpublic static TrieDictionary createTrie(@Nonnull final Set<String> dictionary) {\n\t\tPreconditions.checkNotNull(dictionary);\n\n\t\tfinal TrieDictionary trie = new TrieDictionary();\n\n\t\tfor (final String word : dictionary) {\n\t\t\ttrie.addWord(word);\n\t\t}\n\n\t\treturn trie;\n\t}\n\n\t/**\n\t * Add the given word to the trie by iterating through each character in the word and ensuring it exists at the\n\t * corresponding branch of the trie.\n\t */\n\tprivate void addWord(final String word) {\n\n\t\tTrieNode nextNode = root;\n\n\t\tfor (int i = 0; i < word.length(); i++) {\n\t\t\tfinal char c = word.charAt(i);\n\n\t\t\tTrieNode newNext = nextNode.getChild(c);\n\n\t\t\tif (newNext == null) {\n\t\t\t\tnewNext = new TrieNode(c, i == word.length() - 1);\n\t\t\t\tnextNode.addChild(newNext);\n\t\t\t} else if (i == word.length() - 1) {\n\t\t\t\tnewNext.setWord(true);\n\t\t\t}\n\n\t\t\tnextNode = newNext;\n\t\t}\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t */\n\t@Override\n\tpublic boolean isPrefix(final String potentialPrefix) {\n\t\tTrieNode nextNode = root;\n\n\t\tfor (int i = 0; i < potentialPrefix.length(); i++) {\n\t\t\tfinal char c = potentialPrefix.charAt(i);\n\n\t\t\tfinal TrieNode child = nextNode.getChild(c);\n\n\t\t\tif (child == null) {\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tnextNode = child;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t */\n\t@Override\n\tpublic boolean isWord(final String potentialWord) {\n\t\tTrieNode nextNode = root;\n\n\t\tfor (int i = 0; i < potentialWord.length(); i++) {\n\t\t\tfinal char c = potentialWord.charAt(i);\n\n\t\t\tfinal TrieNode child = nextNode.getChild(c);\n\n\t\t\tif (child == null) {\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tnextNode = child;\n\t\t}\n\n\t\treturn nextNode.isWord();\n\t}\n\n\t/**\n\t * A node in the {@link TrieDictionary} data structure.\n\t */\n\tprivate class TrieNode {\n\n\t\t/**\n\t\t * The character this node represents in the trie.\n\t\t */\n\t\tprivate final char character;\n\n\t\t/**\n\t\t * Does a traversal ending at this node produce a full word?\n\t\t * <p>\n\t\t * If not, this node will have children, because it is part of a word, but not the end of it.\n\t\t */\n\t\tprivate boolean isWord;\n\n\t\t/**\n\t\t * The characters that can be added to the current traversal and still make up a prefix of a word or a complete\n\t\t * word.\n\t\t */\n\t\tprivate final Map<Character, TrieNode> children = new HashMap<>();\n\n\t\tpublic TrieNode(final char character, final boolean isWord) {\n\t\t\tthis.character = character;\n\t\t\tthis.isWord = isWord;\n\t\t}\n\n\t\tpublic void addChild(final TrieNode child) {\n\t\t\tchildren.put(child.getChar(), child);\n\t\t}\n\n\t\tpublic TrieNode getChild(final char c) {\n\t\t\treturn children.get(c);\n\t\t}\n\n\t\tpublic char getChar() {\n\t\t\treturn character;\n\t\t}\n\n\t\tpublic boolean isWord() {\n\t\t\treturn isWord;\n\t\t}\n\n\t\tpublic void setWord(final boolean isWord) {\n\t\t\tthis.isWord = isWord;\n\t\t}\n\t}\n\n}",
"public class WordGridSolver {\n\n\t/**\n\t * The dictionary of words that may exist in the grid.\n\t */\n\tprivate final Dictionary dictionary;\n\n\tpublic WordGridSolver(@Nonnull final Dictionary dictionary) {\n\t\tPreconditions.checkNotNull(dictionary);\n\t\tthis.dictionary = dictionary;\n\t}\n\n\t/**\n\t * Find all valid WordBrain words in the given grid that are the specified length.\n\t * \n\t * @param caseSensitiveGrid\n\t * Word grid.\n\t * @param wordLengths\n\t * The lengths of the words we are looking for. This is ordered, as some words may only become accessible\n\t * once one word is found and removed from the grid.\n\t * @return The list of word combinations that complete the grid. The sub-list contains the words that, used\n\t * together, complete the grid.\n\t */\n\tpublic List<GridSolution> findWords(final char[][] caseSensitiveGrid, final Queue<Integer> wordLengths) {\n\t\tPreconditions.checkNotNull(caseSensitiveGrid);\n\t\tPreconditions.checkArgument(caseSensitiveGrid.length > 0 && caseSensitiveGrid[0].length > 0);\n\n\t\tif (wordLengths == null || wordLengths.size() == 0) {\n\t\t\treturn Collections.emptyList();\n\t\t}\n\n\t\tfinal char[][] lowerCaseGrid = Grids.toLowerCase(caseSensitiveGrid);\n\n\t\tfinal List<GridSolution> wordsFound = new LinkedList<>();\n\n\t\t/*\n\t\t * Start looking for words from each position in the grid.\n\t\t */\n\t\tfor (int y = 0; y < lowerCaseGrid.length; y++) {\n\t\t\tfor (int x = 0; x < lowerCaseGrid[0].length; x++) {\n\n\t\t\t\t// Start with no words seen, and empty string.\n\t\t\t\twordsFound.addAll(findWord(lowerCaseGrid, x, y, \"\", new LinkedList<>(), wordLengths));\n\n\t\t\t}\n\t\t}\n\n\t\treturn wordsFound;\n\t}\n\n\t/**\n\t * Recursively called to build up words. If a word is of the desired length, check if it is in the dictionary.\n\t * <p>\n\t * Starting with an empty string, it recursively calls out to the (up to) 8 characters next to the given character,\n\t * stopping where it has already used a character as part of the word, or at the edge of the grid.\n\t * <p>\n\t * When it finds a valid word, it moves on in another recursive call to {@link #findWords(char[][], Queue)} to find\n\t * another valid word, matching the next word length in <tt>lengthOfWord</tt>.\n\t * \n\t * @param grid\n\t * The word grid.\n\t * @param xPos\n\t * The current position in the grid, x axis.\n\t * @param yPos\n\t * The current position in the grid, y axis.\n\t * @param currentWord\n\t * The word being built up as part of this call.\n\t * @param positionsUsedInWord\n\t * Set of positions already seen.\n\t * @param wordLengthsRequired\n\t * The length of the word we are looking for.\n\t * \n\t * @return The list of word combinations that complete the grid. The sub-list contains the words that, used\n\t * together, complete the grid.\n\t */\n\tprivate List<GridSolution> findWord(final char[][] grid, final int xPos, final int yPos, @Nonnull final String currentWord,\n\t\t\tfinal List<Position> positionsUsedInWord, final Queue<Integer> wordLengthsRequired) {\n\n\t\t// Check terminating conditions (co-ordinates off grid, grid position already used, or grid position empty):\n\t\tif (notAValidPosition(grid, xPos, yPos, positionsUsedInWord)) {\n\t\t\treturn Collections.emptyList();\n\t\t}\n\n\t\tfinal List<GridSolution> solutions = new LinkedList<>();\n\n\t\tfinal String newWord = currentWord + grid[yPos][xPos];\n\t\tfinal Integer wordLengthRequired = wordLengthsRequired.peek();\n\n\t\tif (newWord.length() == wordLengthRequired && dictionary.isWord(newWord)) {\n\t\t\tsolutions.addAll(markSolutionAndStartNextWord(grid, xPos, yPos, positionsUsedInWord, wordLengthsRequired, newWord));\n\t\t} else if (newWord.length() < wordLengthRequired && dictionary.isPrefix(newWord)) {\n\t\t\tsolutions.addAll(findNextCharacterInWord(grid, xPos, yPos, positionsUsedInWord, wordLengthsRequired, newWord));\n\t\t}\n\n\t\treturn solutions;\n\t}\n\n\t/**\n\t * A grid position is not valid if one of the co-ordinates is off the grid (e.g. a negative co-ordinate), the grid\n\t * position has already been used for the current word, or the grid position does not contain a character (in which\n\t * case the ' ' char is found).\n\t */\n\tprivate boolean notAValidPosition(final char[][] grid, final int xPos, final int yPos, final List<Position> positionsUsedInWord) {\n\t\treturn xPos < 0 || yPos < 0 || yPos >= grid.length || xPos >= grid[0].length\n\t\t\t\t|| positionsUsedInWord.contains(new Position(xPos, yPos)) || grid[yPos][xPos] == ' ';\n\t}\n\n\t/**\n\t * The current word is not large enough, as we haven't reached the desired word size yet. Fan out the search by\n\t * recursively calling {@link #findWord(char[][], int, int, String, List, Queue)}, adding every combination of\n\t * remaining characters adjacent to the current character.\n\t */\n\tprivate List<GridSolution> findNextCharacterInWord(final char[][] grid, final int xPos, final int yPos,\n\t\t\tfinal List<Position> positionsUsedInWord, final Queue<Integer> wordLengthsRequired, final String word) {\n\n\t\tfinal List<Position> newPosSeen = clonePositionsSet(positionsUsedInWord);\n\t\tnewPosSeen.add(new Position(xPos, yPos));\n\n\t\tfinal List<GridSolution> solutions = new LinkedList<>();\n\n\t\tsolutions.addAll(findWord(grid, xPos - 1, yPos, word, newPosSeen, wordLengthsRequired));\n\t\tsolutions.addAll(findWord(grid, xPos, yPos - 1, word, newPosSeen, wordLengthsRequired));\n\t\tsolutions.addAll(findWord(grid, xPos - 1, yPos - 1, word, newPosSeen, wordLengthsRequired));\n\t\tsolutions.addAll(findWord(grid, xPos + 1, yPos, word, newPosSeen, wordLengthsRequired));\n\t\tsolutions.addAll(findWord(grid, xPos, yPos + 1, word, newPosSeen, wordLengthsRequired));\n\t\tsolutions.addAll(findWord(grid, xPos + 1, yPos + 1, word, newPosSeen, wordLengthsRequired));\n\t\tsolutions.addAll(findWord(grid, xPos + 1, yPos - 1, word, newPosSeen, wordLengthsRequired));\n\t\tsolutions.addAll(findWord(grid, xPos - 1, yPos + 1, word, newPosSeen, wordLengthsRequired));\n\n\t\treturn solutions;\n\t}\n\n\t/**\n\t * We have found a valid word.\n\t * <p>\n\t * If there are no more words to find, add this word to a result list and return it.\n\t * <p>\n\t * If there are more valid words to find, remove the characters in the discovered word from the grid and recursively\n\t * call {@link #findWords(char[][], Queue)} to find the next word.\n\t * <p>\n\t * If these recursive calls terminate without finding the next required work, this discovered word can be ignored,\n\t * as it is not part of a complete solution.\n\t */\n\tprivate List<GridSolution> markSolutionAndStartNextWord(final char[][] grid, final int xPos, final int yPos,\n\t\t\tfinal List<Position> positionsUsedInWord, final Queue<Integer> wordLengthsRequired, final String validWord) {\n\t\tfinal List<GridSolution> solutions = new LinkedList<>();\n\n\t\t/*\n\t\t * We've found a potential first word. Move on to second word.\n\t\t */\n\t\tfinal Queue<Integer> newWordLengthsRequired = cloneQueue(wordLengthsRequired);\n\t\tnewWordLengthsRequired.remove();\n\n\t\tfinal List<Position> finalPositionsInWord = clonePositionsSet(positionsUsedInWord);\n\t\tfinalPositionsInWord.add(new Position(xPos, yPos));\n\n\t\tfinal GridWord word = new GridWord(validWord, finalPositionsInWord, grid);\n\n\t\tfinal GridSolution solution = new GridSolution(word);\n\n\t\tif (newWordLengthsRequired.isEmpty()) {\n\t\t\t// No more words to find after this.\n\t\t\tsolutions.add(solution);\n\t\t} else {\n\t\t\tfinal char[][] updatedGrid = removeWordFromGrid(grid, finalPositionsInWord);\n\n\t\t\tsolutions.addAll(startSearchForNextWord(updatedGrid, word, newWordLengthsRequired));\n\t\t}\n\n\t\treturn solutions;\n\t}\n\n\t/**\n\t * Start searching for the next word in the grid by removing characters used as part of the first word and\n\t * recursively calling {@link #findWords(char[][], Queue)} to begin the search anew.\n\t */\n\tprivate List<GridSolution> startSearchForNextWord(final char[][] grid, final GridWord word, final Queue<Integer> newWordLengthsRequired) {\n\n\t\tfinal List<GridSolution> solutions = new LinkedList<>();\n\n\t\t// Start searching again in new grid for the next word:\n\t\tfinal List<GridSolution> nextWords = findWords(grid, newWordLengthsRequired);\n\n\t\t// If more words were found, add the whole result to the solution set:\n\t\tif (!nextWords.isEmpty()) {\n\t\t\tfor (final GridSolution solution : nextWords) {\n\t\t\t\tsolution.addFirst(word);\n\t\t\t}\n\n\t\t\tsolutions.addAll(nextWords);\n\t\t}\n\n\t\treturn solutions;\n\t}\n\n\t/**\n\t * Create a copy of the grid and update it to remove the characters from the recently discovered grid.\n\t * <p>\n\t * A copy is made of the positions used to make this word, because sibling calls (in the recursive call structure)\n\t * to {@link #startSearchForNextWord(char[][], String, Queue)} can also find valid words and also try to update this\n\t * structure, which leads to an incorrect position being added.\n\t */\n\tprivate char[][] removeWordFromGrid(final char[][] grid, final Collection<Position> positionsUsedInWord) {\n\t\treturn Grids.removeElementsAndApplyGravity(grid, positionsUsedInWord);\n\t}\n\n\tprivate Queue<Integer> cloneQueue(final Queue<Integer> wordLengthsRequired) {\n\t\treturn new LinkedList<>(wordLengthsRequired);\n\t}\n\n\tprivate List<Position> clonePositionsSet(final List<Position> positionsUsedInWord) {\n\t\treturn new LinkedList<>(positionsUsedInWord);\n\t}\n}",
"public class GridSolution {\n\tprivate final LinkedList<GridWord> words = new LinkedList<>();\n\n\t/**\n\t * Start creating a new solution by adding the first word in that solution.\n\t */\n\tpublic GridSolution(final GridWord word) {\n\t\tadd(word);\n\t}\n\n\t/**\n\t * Add a word to the solution set.\n\t */\n\tpublic void add(final GridWord validWord) {\n\t\twords.add(validWord);\n\t}\n\n\t/**\n\t * Add a word to the start of the solution set.\n\t */\n\tpublic void addFirst(final GridWord word) {\n\t\twords.addFirst(word);\n\t}\n\n\t/**\n\t * Get the words, ordered, from the solution.\n\t */\n\tpublic LinkedList<GridWord> getWords() {\n\t\treturn words;\n\t}\n\n\t/**\n\t * Check if a given word is in the solution.\n\t */\n\tpublic boolean containsWord(final String string) {\n\t\tfor (final GridWord word : words) {\n\t\t\tif (word.getString().equals(string)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Objects.hashCode(words);\n\t}\n\n\t@Override\n\tpublic boolean equals(final Object object) {\n\t\tif (object instanceof GridSolution) {\n\t\t\tfinal GridSolution that = (GridSolution) object;\n\t\t\treturn Objects.equal(this.words, that.words);\n\t\t}\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn Joiner.on(\", \").join(words);\n\t}\n\n}",
"public class Printers {\n\n\tpublic static String solutionToString(final List<GridSolution> wordsFound) {\n\n\t\tfinal StringBuffer ret = new StringBuffer(\"Solutions found: \");\n\n\t\tif (!wordsFound.isEmpty()) {\n\t\t\tfor (final GridSolution result : wordsFound) {\n\t\t\t\tret.append(Joiner.on(\", \").join(result.getWords()));\n\t\t\t}\n\t\t} else {\n\t\t\tret.append(\"<none>\");\n\t\t}\n\n\t\treturn ret.toString();\n\t}\n}"
] | import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import nyc.angus.wordgrid.dictionary.DictionaryLoader;
import nyc.angus.wordgrid.dictionary.trie.TrieDictionary;
import nyc.angus.wordgrid.solver.WordGridSolver;
import nyc.angus.wordgrid.solver.solution.GridSolution;
import nyc.angus.wordgrid.ui.Printers;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test; | package nyc.angus.wordgrid.test;
/**
* Tests of {@link WordGridSolver}.
*/
public class SolverTests {
private final static Logger LOGGER = Logger.getLogger(SolverTests.class.getName());
private static Set<String> wordSet; | private static TrieDictionary trieDictionary; | 1 |
cyriux/mpcmaid | MpcMaid/src/com/mpcmaid/gui/WaveformPanel.java | [
"public final class Marker implements Comparable {\n\tprivate int location;\n\n\tpublic Marker(int location) {\n\t\tthis.location = location;\n\t}\n\n\tpublic int getLocation() {\n\t\treturn location;\n\t}\n\n\tpublic void setLocation(int location) {\n\t\tthis.location = location;\n\t}\n\n\tpublic int move(final int ticks) {\n\t\tif (location + ticks >= 0) {\n\t\t\tthis.location += ticks;\n\t\t}\n\t\treturn this.location;\n\t}\n\n\tpublic Marker duplicate() {\n\t\treturn new Marker(location);\n\t}\n\n\tpublic int compareTo(Object o) {\n\t\tfinal Marker other = (Marker) o;\n\t\treturn location - other.location;\n\t}\n\n\tpublic String toString() {\n\t\treturn \"Marker location=\" + location;\n\t}\n\n}",
"public class Markers {\n\n\tpublic static final int NONE = -1;\n\n\tprivate final List<Marker> markers = new ArrayList<Marker>();\n\n\tprivate int selectedMarker = 0;\n\n\tprivate int maxLocation = 0;\n\n\tprivate int samplingRate = 0;\n\n\t/**\n\t * @param maxLocation\n\t * The Frame Length\n\t */\n\tpublic void clear(int maxLocation, int samplingRate) {\n\t\tmarkers.clear();\n\t\tselectedMarker = 0;\n\t\tthis.maxLocation = maxLocation;\n\t\tthis.samplingRate = samplingRate;\n\t}\n\n\tpublic void add(int adjustedZc) {\n\t\tmarkers.add(new Marker(adjustedZc));\n\t}\n\n\tpublic List<Marker> getMarkers() {\n\t\treturn markers;\n\t}\n\n\tpublic int size() {\n\t\treturn markers.size();\n\t}\n\n\tpublic void selectMarker(final int shift) {\n\t\tif (isUnset()) {\n\t\t\treturn;\n\t\t}\n\t\tint sel = selectedMarker;\n\t\tsel += shift;\n\t\tif (sel < 0) {\n\t\t\tsel = markers.size() - 1;\n\t\t}\n\t\tselectedMarker = sel % markers.size();\n\t}\n\n\t/**\n\t * Select the closest marker to given location.\n\t * @param location\n\t * location in samples\n\t */\n\tpublic void selectClosestMarker(final int location) {\n\t\tif (isUnset()) {\n\t\t\treturn;\n\t\t}\n\t\tint distance = Math.abs(markers.get(0).getLocation() - location);\n\t\tint idx = 0;\n\t\tfor (int c = 1; c < markers.size(); c++) {\n\t\t\tint cdistance = Math.abs(markers.get(c).getLocation() - location);\n\t\t\tif (cdistance < distance) {\n\t\t\t\tidx = c;\n\t\t\t\tdistance = cdistance;\n\t\t\t}\n\t\t}\n\t\tselectedMarker = idx;\n\t}\n\n\tpublic void nudgeMarker(final int ticks, Slicer adjustor) {\n\t\tfinal Marker marker = getSelectedMarker();\n\t\tint max = maxLocation;\n\t\tint min = 0;\n\t\tif (marker != null) {\n\t\t\tif (markers.size() > selectedMarker + 1) {\n\t\t\t\tfinal Marker nextMarker = (Marker) markers.get(selectedMarker + 1);\n\t\t\t\tmax = nextMarker.getLocation();\n\t\t\t}\n\t\t\tif (selectedMarker > 0) {\n\t\t\t\tfinal Marker previousMarker = (Marker) markers.get(selectedMarker - 1);\n\t\t\t\tmin = previousMarker.getLocation();\n\t\t\t}\n\t\t\tint location = marker.move(ticks);\n\t\t\tif (marker.getLocation() + ticks >= max) {\n\t\t\t location = max;\n\t\t\t}\n\t\t\tif (marker.getLocation() + ticks <= min) {\n\t\t\t\tlocation = min;\n\t\t\t}\n\t\t\tfinal int excursion = ticks / 2;\n\t\t\tfinal int adjustedZc = adjustor.adjustNearestZeroCrossing(location, excursion);\n\t\t\tmarker.setLocation(adjustedZc);\n\t\t}\n\t}\n\n\tpublic Marker getSelectedMarker() {\n\t\tfinal Marker marker = (Marker) markers.get(selectedMarker);\n\t\treturn marker;\n\t}\n\n\tpublic boolean isUnset() {\n\t\treturn markers.size() == 0;\n\t}\n\n\tpublic void deleteSelectedMarker() {\n\t\tif (selectedMarker > 0) {\n\t\t\tmarkers.remove(selectedMarker);\n\t\t\tselectedMarker--;\n\t\t}\n\t}\n\n\tpublic void insertMarker() {\n\t\tfinal int markerIndex = getSelectedMarkerIndex();\n\t\tfinal LocationRange range = getRangeFrom(markerIndex);\n\t\tmarkers.add(markerIndex, new Marker(range.getMidLocation()));\n\t\tCollections.sort(markers);\n\t\tselectedMarker++;\n\t}\n\n\tpublic int getSelectedMarkerIndex() {\n\t\treturn selectedMarker;\n\t}\n\n\tpublic int getSelectedMarkerLocation() {\n\t\treturn getLocation(selectedMarker);\n\t}\n\n\tpublic float getDuration() {\n\t\tfinal float duration = (float) maxLocation / samplingRate;\n\t\treturn duration;\n\t}\n\n\tpublic int getLocation(final int markerIndex) {\n\t\tif (markerIndex < 0) {\n\t\t\treturn 0;\n\t\t}\n\t\tif (markerIndex >= markers.size()) {\n\t\t\treturn maxLocation;\n\t\t}\n\t\tfinal Marker marker = (Marker) markers.get(markerIndex);\n\t\tif (marker == null) {\n\t\t\treturn 0;\n\t\t}\n\t\treturn marker.getLocation();\n\t}\n\n\tpublic LocationRange getRangeFrom(final int markerIndex) {\n\t\tCollections.sort(markers);\n\n\t\tfinal int from = getLocation(markerIndex);\n\t\tfinal int to = getLocation(markerIndex + 1);\n\t\treturn new LocationRange(from, to);\n\t}\n\n\t/**\n\t * @param ppq\n\t * The MIDI PPQ\n\t */\n\tpublic int getLocationInTicks(final int markerIndex, final int ppq) {\n\t\tfinal double tempoBps = (double) getTempo() / 60.0;\n\t\tfinal int location = getLocation(markerIndex);\n\t\treturn (int) Math.round(ppq * tempoBps * location / samplingRate);\n\t}\n\n\tpublic String displayTempo() {\n\t\tfinal float tempo = getTempo();\n\t\tfinal String format = \" Estimated tempo: ##0.##BPM\";\n\t\treturn tempo > 0 ? new DecimalFormat(format).format(tempo) : \"\";\n\t}\n\n\tpublic boolean hasBeat() {\n\t\treturn getTempo() != NONE;\n\t}\n\n\tpublic float getTempo() {\n\t\treturn getTempo(8);\n\t}\n\n\tpublic float getTempo(final int numberOfBeats) {\n\t\tfinal float duration = getDuration();\n\t\tfinal float tempo = 60 * numberOfBeats / duration;\n\t\tif (tempo > 250 || tempo < 40) {\n\t\t\treturn NONE;\n\t\t}\n\t\treturn tempo;\n\t}\n\n\t/**\n\t * Exports the location of each slice into a MIDI file\n\t */\n\tpublic Sequence exportMidiSequence(final File file, final int ppq) throws IOException {\n\t\tfinal double tempoBps = (double) getTempo() / 60.0;\n\t\tfinal MidiSequenceBuilder builder = new MidiSequenceBuilder(ppq);\n\t\tfinal Track track = builder.getTrack();\n\t\tfinal int n = markers.size();\n\t\tint startTick = 0;\n\t\tint key = 35;\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tfinal int location = getLocation(i);\n\t\t\tstartTick = (int) Math.round(ppq * tempoBps * location / samplingRate);\n\t\t\tint tickLength = 32;\n\t\t\tbuilder.addNote(track, startTick, tickLength, key++);\n\t\t}\n\t\tif (file != null) {\n\t\t\tbuilder.save(file);\n\t\t}\n\t\treturn builder.getSequence();\n\t}\n\n\tpublic String toString() {\n\t\treturn \"Markers: \" + markers.size() + \" markers, selected: \" + selectedMarker;\n\t}\n}",
"public class Sample {\n\n\tprivate final byte[] bytes;\n\n\tprivate final AudioFormat format;\n\n\tprivate final int frameLength;\n\n\tpublic static Sample open(final File file) throws Exception {\n\t\tfinal AudioInputStream audioStream = AudioSystem.getAudioInputStream(file);\n\t\treturn open(audioStream);\n\t}\n\n\tprotected static Sample open(final InputStream is) throws Exception {\n\t\tfinal AudioInputStream audioStream = AudioSystem.getAudioInputStream(is);\n\t\treturn open(audioStream);\n\t}\n\n\tprivate static Sample open(final AudioInputStream audioStream) throws LineUnavailableException, IOException {\n\t\tfinal int frameLength = (int) audioStream.getFrameLength();\n\t\tif (frameLength > 44100 * 8 * 2) {\n\t\t\tthrow new IllegalArgumentException(\"The audio file is too long (must be shorter than 4 bars at 50BPM)\");\n\t\t}\n\t\tfinal AudioFormat format = audioStream.getFormat();\n\t\tfinal int frameSize = (int) format.getFrameSize();\n\t\tfinal byte[] bytes = new byte[frameLength * frameSize];\n\t\tfinal int result = audioStream.read(bytes);\n\t\tif (result < 0) {\n\t\t\treturn null;\n\t\t}\n\n\t\taudioStream.close();\n\n\t\treturn new Sample(bytes, format, frameLength);\n\t}\n\n\tpublic void play() throws Exception {\n\t\tSamplePlayer.getInstance().play(this);\n\t}\n\n\tpublic void save(File file) throws Exception {\n\t\tfinal Type fileType = AudioFileFormat.Type.WAVE;\n\t\tfinal AudioInputStream stream = new AudioInputStream(new ByteArrayInputStream(bytes), format, frameLength);\n\t\tAudioSystem.write(stream, fileType, file);\n\t}\n\n\tpublic Sample(byte[] buffer, AudioFormat format, int frameLength) {\n\t\tthis.bytes = buffer;\n\t\tthis.format = format;\n\t\tthis.frameLength = frameLength;\n\t}\n\n\tpublic int[][] asSamples() {\n\t\tfinal int numChannels = format.getChannels();\n\t\tfinal int[][] toReturn = new int[numChannels][frameLength];\n\t\tint sampleIndex = 0;\n\t\tfor (int t = 0; t < bytes.length;) {\n\t\t\tfor (int channel = 0; channel < numChannels; channel++) {\n\t\t\t\tint low = (int) bytes[t];\n\t\t\t\tt++;\n\t\t\t\tint high = (int) bytes[t];\n\t\t\t\tt++;\n\t\t\t\tint sample = (high << 8) + (low & 0x00ff);\n\t\t\t\ttoReturn[channel][sampleIndex] = sample;\n\t\t\t}\n\t\t\tsampleIndex++;\n\t\t}\n\t\treturn toReturn;\n\t}\n\n\tpublic byte[] getBytes() {\n\t\treturn bytes;\n\t}\n\n\tpublic AudioFormat getFormat() {\n\t\treturn format;\n\t}\n\n\tpublic int getFrameLength() {\n\t\treturn frameLength;\n\t}\n\n\t/**\n\t * \n\t */\n\tpublic Sample subRegion(int from, int to) {\n\t\tfinal int frameLength = to - from;\n\t\tfinal int frameSize = (int) format.getFrameSize();\n\t\tfinal byte[] region = new byte[frameLength * frameSize];\n\t\tfor (int i = 0; i < region.length; i++) {\n\t\t\tregion[i] = bytes[from * frameSize + i];\n\t\t}\n\t\treturn new Sample(region, format, region.length);\n\t}\n\n\tpublic String toString() {\n\t\treturn \"Sample \" + format + \" (\" + frameLength + \" frames)\";\n\t}\n\n}",
"public class Slicer {\n\n\tprivate final int windowSize;\n\n\tprivate final int overlapRatio;\n\n\tprivate final int localEnergyWindowSize;\n\n\tprivate final Sample sample;\n\n\t// cache\n\tprivate int[][] channels;\n\n\tprivate int sensitivity = 130;\n\n\tprivate final Markers markers = new Markers();\n\n\tpublic Slicer(Sample sample, final int windowSize, int overlapRatio, int localEnergyWindowSize) {\n\t\tthis.sample = sample;\n\t\tthis.windowSize = windowSize;\n\t\tthis.overlapRatio = overlapRatio;\n\t\tthis.localEnergyWindowSize = localEnergyWindowSize;\n\t\tchannels = sample.asSamples();\n\n\t\textractMarkers(channels);\n\t}\n\n\t/**\n\t * Main method\n\t */\n\tpublic void extractMarkers() {\n\t\textractMarkers(channels);\n\t}\n\n\t/**\n\t * Process L+R samples to compute the energy over a sliding window, then\n\t * compare the energy of each window against the average local energy on a\n\t * number of neighbor windows; when this comparison is greater enough, we\n\t * got a beat.\n\t * \n\t * To reduce the number of fake beats, we also use a toggle state so that no\n\t * beat can be found immediately after a beat already found.\n\t * \n\t * When a beat has been found, its exact location is then adjusted to the\n\t * nearest zero-crossing location in the past.\n\t * \n\t * For each beat found, a corresponding marker is added to the list of\n\t * markers.\n\t */\n\tpublic void extractMarkers(final int[][] channels) {\n\t\tmarkers.clear(getFrameLength(), (int) sample.getFormat().getFrameRate());\n\n\t\tfinal int step = windowSize / overlapRatio;\n\n\t\tfinal long[] energyHistory = energyHistory(channels, windowSize, overlapRatio);\n\t\tif (energyHistory == null || energyHistory.length < localEnergyWindowSize) {\n\t\t\t// when nothing is found, insert marker at 0 position\n\t\t\tmarkers.add(0);\n\t\t\treturn;\n\t\t}\n\n\t\tboolean lastState = false;\n\t\tfor (int i = 0; i < energyHistory.length; i++) {\n\t\t\tfinal long e = energyHistory[i];\n\t\t\tfinal long localE = localEnergy(i, energyHistory);\n\t\t\tfinal double C = (double) sensitivity / 100.0;\n\t\t\tif (e > C * localE) {\n\t\t\t\t// got a beat\n\t\t\t\tfinal int location = i * step;\n\t\t\t\tif (!lastState) {\n\t\t\t\t\tfinal int[] samplesL = getSamplesL(channels);\n\t\t\t\t\tfinal int adjustedZc = nearestZeroCrossing(samplesL, location, windowSize);\n\t\t\t\t\tmarkers.add(adjustedZc);\n\t\t\t\t\tlastState = true;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tlastState = false;\n\t\t\t}\n\t\t}\n\t}\n\n\tprotected int[] getSamplesL(final int[][] channels) {\n\t\treturn channels[0];\n\t}\n\n\tprivate long localEnergy(int i, long[] energyHistory) {\n\t\tfinal int n = energyHistory.length;\n\t\tfinal int m = localEnergyWindowSize;\n\t\tint from = 0;\n\t\tint to = m;\n\t\tif (i < m) {\n\t\t\tfrom = 0;\n\t\t\tto = m;\n\t\t} else if (i + m < n) {\n\t\t\tfrom = i;\n\t\t\tto = i + m;\n\t\t} else {\n\t\t\tfrom = n - m;\n\t\t\tto = n;\n\t\t}\n\t\tlong sum = 0;\n\t\tfor (int j = from; j < to; j++) {\n\t\t\tsum += Math.pow(energyHistory[j], 1);\n\t\t}\n\t\treturn sum / m;\n\t}\n\n\tprivate long[] energyHistory(final int[][] channels, final int windowSize, final int overlapRatio) {\n\t\tfinal int[] samplesL = getSamplesL(channels);\n\t\tfinal int[] samplesR = channels.length > 1 ? channels[1] : samplesL;\n\t\tfinal int n = samplesL.length;\n\t\tfinal int step = windowSize / overlapRatio;\n\n\t\tfinal int energyFrameNumber = n / step;\n\t\tif (energyFrameNumber < 1) {\n\t\t\treturn null;\n\t\t}\n\t\tfinal long[] energy = new long[energyFrameNumber];\n\t\tint windowIndex = 0;\n\t\t// for each sliding window (ignore last broken period window...)\n\t\tfor (int i = 0; i + windowSize < n; i += step) {\n\t\t\tlong sum = 0;\n\t\t\t// for the window size, cumulate energy\n\t\t\tfor (int j = 0; j < windowSize; j++) {\n\t\t\t\tsum += Math.pow(samplesL[i + j], 2);\n\t\t\t\tsum += Math.pow(samplesR[i + j], 2);\n\t\t\t}\n\t\t\tenergy[windowIndex++] = sum;\n\t\t}\n\t\treturn energy;\n\t}\n\n\tprivate final static int nearestZeroCrossing(final int[] samples, final int index, final int excursion) {\n\t\tif (index == 0) {\n\t\t\treturn 0;\n\t\t}\n\t\tint i = index;\n\t\tfinal int min = index - excursion >= 0 ? index - excursion : 0;\n\t\twhile (!isZeroCross(samples, i) && i > min) {\n\t\t\ti--;\n\t\t}\n\t\treturn i;\n\t}\n\n\tprivate final static boolean isZeroCross(final int[] samples, final int index) {\n\t\tif (index == 0) {\n\t\t\treturn true;\n\t\t}\n\t\tif (index >= samples.length - 1) {\n\t\t\treturn true;\n\t\t}\n\t\tfinal int a = samples[index - 1];\n\t\tfinal int b = samples[index];\n\t\treturn a > 0 && b < 0 || a < 0 && b > 0 || a == 0 && b != 0;\n\t}\n\n\tpublic int[][] getChannels() {\n\t\treturn channels;\n\t}\n\n\tpublic Sample getSample() {\n\t\treturn sample;\n\t}\n\n\tpublic int getFrameLength() {\n\t\treturn sample.getFrameLength();\n\t}\n\n\tpublic void setSensitivity(final int sensitivity) {\n\t\tthis.sensitivity = sensitivity;\n\t\textractMarkers();\n\t}\n\n\tpublic int getSensitivity() {\n\t\treturn sensitivity;\n\t}\n\n\tpublic int adjustNearestZeroCrossing(int location, final int excursion) {\n\t\tfinal int[] samplesL = channels[0];\n\t\tfinal int adjustedZc = nearestZeroCrossing(samplesL, location, excursion);\n\t\treturn adjustedZc;\n\t}\n\n\t// ------------------------------\n\n\tpublic Markers getMarkers() {\n\t\treturn markers;\n\t}\n\n\tpublic Sample getSelectedSlice() {\n\t\tfinal int markerIndex = markers.getSelectedMarkerIndex();\n\t\treturn getSlice(markerIndex);\n\t}\n\n\tpublic Sample getSlice(final int markerIndex) {\n\t\tfinal LocationRange range = markers.getRangeFrom(markerIndex);\n\t\treturn sample.subRegion(range.getFrom(), range.getTo());\n\t}\n\n\t/**\n\t * Exports each slice as defined by the markers into a slice file\n\t */\n\tpublic List exportSlices(File path, String prefix) throws Exception {\n\t\tfinal List files = new ArrayList();\n\t\tfinal int n = markers.size();\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tfinal Sample slice = getSlice(i);\n\t\t\tfinal File file = new File(path, prefix + i + \".wav\");\n\t\t\tfiles.add(file);\n\t\t\tslice.save(file);\n\t\t}\n\t\treturn files;\n\t}\n\n\tpublic String toString() {\n\t\treturn \"Slicer: \" + markers.getDuration() + \"s (\" + getFrameLength() + \" samples), \" + markers.size()\n\t\t\t\t+ \" markers\";\n\t}\n}",
"public final class Pad extends BaseElement {\n\n\t// /0-127 m=Pad Number (0 to 63). Value of character is the MIDI note number\n\t// associated with Pad Number m ; m + 0x2918\n\tpublic static final Parameter PAD_MIDI_NOTE_VALUE = Parameter.enumType(\"Note\", 0x2918, notes());\n\n\t// 0=\"Poly\", 1=\"Mono\"\n\tprivate static final Parameter VOICE_OVERLAP = Parameter.enumType(\"Voice Overlap\", 0x62, new String[] { \"Poly\",\n\t\t\t\"Mono\" });\n\n\t// 0=\"Off\", 1 to 32\n\tprivate static final Parameter MUTE_GROUP = Parameter.intOrOff(\"Mute Group\", 0x63, 0, 32);\n\n\tprivate final static Parameter[] PARAMETERS = { PAD_MIDI_NOTE_VALUE, VOICE_OVERLAP, MUTE_GROUP };\n\n\t// ----\n\tprivate static final int PAD_SECTION = 0x14 + 4;// start of pad section\n\n\tprivate static final int PAD_LENGTH = 0xA4;// length of pad section\n\n\tprotected Pad(final Program parent, int padIndex) {\n\t\tsuper(parent, PAD_SECTION, padIndex, PAD_LENGTH);\n\t\tProgram.assertIn(0, padIndex, 63, \"pad\");\n\t}\n\n\tpublic Pad copy() {\n\t\treturn new Pad((Program) getParent(), getPadIndex());\n\n\t}\n\n\tpublic Parameter[] getParameters() {\n\t\treturn PARAMETERS;\n\t}\n\n\tpublic int getPadIndex() {\n\t\treturn getElementIndex();\n\t}\n\n\tpublic PadEnvelope getEnvelope() {\n\t\treturn new PadEnvelope(this);\n\t}\n\n\tpublic BaseElement getFilter(int i) {\n\t\treturn (i == 0) ? (BaseElement) getFilter1() : (BaseElement) getFilter2();\n\t}\n\n\tpublic PadFilter1 getFilter1() {\n\t\treturn new PadFilter1(this);\n\t}\n\n\tpublic PadFilter2 getFilter2() {\n\t\treturn new PadFilter2(this);\n\t}\n\n\tpublic PadMixer getMixer() {\n\t\treturn new PadMixer(this);\n\t}\n\n\tpublic BaseElement[] getPages() {\n\t\treturn new BaseElement[] { getEnvelope(), getFilter1(), getFilter2(), getMixer() };\n\t}\n\n\tpublic Layer getLayer(final int layerIndex) {\n\t\treturn new Layer(this, layerIndex);\n\t}\n\n\tpublic short getVoiceOverlap() {\n\t\treturn getByte(VOICE_OVERLAP.getOffset());\n\t}\n\n\tpublic short getPadMidiNote() {\n\t\treturn getParentBuffer().getByte(PAD_MIDI_NOTE_VALUE.getOffset() + getPadIndex());\n\t}\n\n\tpublic void setPadMidiNote(final int midiNote) {\n\t\tProgram.assertIn(0, midiNote, 127, \"Pad MidiNote\");\n\t\tgetParentBuffer().setByte(PAD_MIDI_NOTE_VALUE.getOffset() + getPadIndex(), midiNote);\n\t}\n\n\t// public short getMidiNotePad() {\n\t// return parent.getParameter(MIDI_NOTE_PAD_VALUE + pad);\n\t// }\n\t//\n\t// public void setMidiNotePad(final short midiNote) {\n\t// assertIn(0, midiNote, 64, \"MidiNote Pad\");\n\t// parent.setParameter(MIDI_NOTE_PAD_VALUE + pad, (byte) midiNote);\n\t// }\n\n\tpublic Object get(Parameter parameter) {\n\t\tif (parameter.equals(PAD_MIDI_NOTE_VALUE)) {\n\t\t\treturn new Integer(getPadMidiNote() - 35);\n\t\t}\n\t\treturn super.get(parameter);\n\t}\n\n\tpublic void set(Parameter parameter, Object value) {\n\t\tif (parameter.equals(PAD_MIDI_NOTE_VALUE)) {\n\t\t\tsetPadMidiNote((short) (((Integer) value).shortValue() + 35));\n\t\t\treturn;\n\t\t}\n\t\tsuper.set(parameter, value);\n\t}\n\n\t/**\n\t * Copies every parameter from the given source element, ignoring parameters given in the Set ignoreParams\n\t */\n\tpublic void copyFrom(BaseElement source, Set ignoreParams) {\n\t\tfinal Pad sourcePad = (Pad) source;\n\n\t\tsuper.copyFrom(sourcePad, ignoreParams);\n\n\t\tfinal BaseElement[] pages = getPages();\n\t\tfinal BaseElement[] sourcePages = sourcePad.getPages();\n\t\tfor (int j = 0; j < pages.length; j++) {\n\t\t\tfinal BaseElement page = pages[j];\n\t\t\tpage.copyFrom(sourcePages[j], ignoreParams);\n\t\t}\n\t\tfor (int j = 0; j < getLayerNumber(); j++) {\n\t\t\tLayer layer = getLayer(j);\n\t\t\tfinal Layer sourceLayer = sourcePad.getLayer(j);\n\t\t\tlayer.copyFrom(sourceLayer, ignoreParams);\n\t\t}\n\t}\n\n\tpublic int getLayerNumber() {\n\t\treturn 4;\n\t}\n\n\tprivate final static String[] notes() {\n\t\tfinal String[] noteNames = { \"C\", \"C#\", \"D\", \"D#\", \"E\", \"F\", \"F#\", \"G\", \"G#\", \"A\", \"A#\", \"B\" };\n\t\tfinal String[] notes = new String[64];\n\t\tfor (int i = 0; i < notes.length; i++) {\n\t\t\tfinal int k = 35 + i;\n\t\t\tfinal int chromatic = (k - 24) % 12;\n\t\t\tfinal int octave = (k - 24) / 12;\n\t\t\tnotes[i] = \"(\" + k + \") - \" + noteNames[chromatic] + octave;\n\t\t}\n\t\treturn notes;\n\t}\n\n\tpublic String toString() {\n\t\treturn \"Pad\" + (getPadIndex() + 1);\n\t}\n\n}",
"public class Program extends BaseElement {\n\n\t// ------------- HEADER ------\n\tprivate static final short FILE_LENGTH = 0x2A04;\n\n\tprivate static final int FILE_SIZE = 0x00; // value is always FILE_LENGTH;\n\n\tprivate static final int FILE_TYPE = 0x04;// set to FILE_VERSION\n\n\tprivate static final String FILE_VERSION = \"MPC1000 PGM 1.00\";\n\n\t// ------------ MIDI ---------------\n\t// 0-64 n=MIDI Note Number (0 to 127). Value is the Pad Number (0 to 63)\n\t// associated with the MIDI note number, n. Value is 64 for unassigned MIDI\n\t// Note Numbers.\n\tprivate static final int MIDI_NOTE_PAD_VALUE = 0x2918; // n + 0x2958\n\n\tpublic final static Parameter MIDI_PROGRAM_CHANGE = Parameter.intOrOff(\"MIDI Program Change\", 0x29D8, 0, 128);\n\n\tpublic Program(byte[] bytes) {\n\t\tthis(new ByteBuffer(bytes));\n\t}\n\n\tpublic Program(final ByteBuffer buffer) {\n\t\tsuper(buffer);\n\t}\n\n\tpublic Program(final Program other) {\n\t\tsuper(new ByteBuffer((ByteBuffer) other.getBuffer()));\n\t}\n\n\tpublic Parameter[] getParameters() {\n\t\treturn new Parameter[] { MIDI_PROGRAM_CHANGE };\n\t}\n\n\tprotected static final void assertIn(final int min, final int value, final int max, String param) {\n\t\tif (value < min || value > max) {\n\t\t\tfinal String msg = \"Invalid \" + param + \" value: \" + value + \"; must be in [\" + min + \"..\" + max + \"]\";\n\t\t\tthrow new IllegalArgumentException(msg);\n\t\t}\n\t}\n\n\tpublic Pad getPad(final int pad) {\n\t\treturn new Pad(this, pad);\n\t}\n\n\tpublic int getPadNumber() {\n\t\treturn 64;\n\t}\n\n\tpublic Slider getSlider(final int slider) {\n\t\tassertIn(0, slider, 1, \"Slider\");\n\t\treturn new Slider(this, slider);\n\t}\n\n\tpublic int getSlideNumber() {\n\t\treturn 2;\n\t}\n\n\tpublic short getMidiProgramChange() {\n\t\treturn getByte(MIDI_PROGRAM_CHANGE.getOffset());\n\t}\n\n\tpublic void setMidiProgramChange(final short midiProgramChange) {\n\t\tassertIn(0, midiProgramChange, 128, \"MidiProgramChange\");\n\t\tsetByte(MIDI_PROGRAM_CHANGE.getOffset(), midiProgramChange);\n\t}\n\n\tpublic static Program open(final File file) {\n\t\ttry {\n\t\t\tfinal ByteBuffer buffer = ByteBuffer.open(new FileInputStream(file), FILE_LENGTH);\n\t\t\treturn new Program(buffer);\n\t\t} catch (Exception e) {\n\t\t\tthrow new IllegalArgumentException(\"The file \" + file.getName() + \" is not a valid MPC1000 pgm file.\");\n\t\t}\n\t}\n\n\tpublic static Program open(final InputStream is) {\n\t\ttry {\n\t\t\tfinal ByteBuffer buffer = ByteBuffer.open(is, FILE_LENGTH);\n\t\t\treturn new Program(buffer);\n\t\t} catch (Exception e) {\n\t\t\tthrow new IllegalArgumentException(\"Resource is not a valid MPC1000 pgm file.\");\n\t\t}\n\t}\n\n\tpublic void save(final File file) {\n\t\ttry {\n\t\t\tfinal ByteBuffer byteBuffer = (ByteBuffer) getBuffer();\n\t\t\tbyteBuffer.save(new FileOutputStream(file));\n\t\t} catch (Exception e) {\n\t\t\tthrow new IllegalArgumentException(\"The file \" + file.getName() + \" is not a valid MPC1000 pgm file.\");\n\t\t}\n\t}\n\n\tpublic String toString() {\n\t\treturn \"Program\";\n\t}\n\n}"
] | import java.awt.Color;
import java.awt.Graphics;
import java.awt.Polygon;
import java.io.File;
import java.util.Iterator;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.JPanel;
import com.mpcmaid.audio.Marker;
import com.mpcmaid.audio.Markers;
import com.mpcmaid.audio.Sample;
import com.mpcmaid.audio.Slicer;
import com.mpcmaid.pgm.Pad;
import com.mpcmaid.pgm.Program; | package com.mpcmaid.gui;
/**
* A panel dedicated to display a waveform. It actually contains a Slicer that
* must be initialized before using any delegate method.
*
* @author cyrille martraire
*/
public class WaveformPanel extends JPanel {
private static final int AVERAGE_ENERGY_WINDOW = 43;
private static final int OVERLAP_RATIO = 1;
private static final int WINDOW_SIZE = 1024;
private static final int MIDI_PPQ = 96;
public static final String DEFAULT_FILE_DETAILS = "Drag and Drop a sample file below";
| private Slicer slicer; | 3 |
yarolegovich/MaterialPreferences | library/src/main/java/com/yarolegovich/mp/AbsMaterialPreference.java | [
"public class MaterialPreferences {\n\n private static final MaterialPreferences instance = new MaterialPreferences();\n\n public static MaterialPreferences instance() {\n return instance;\n }\n\n public static UserInputModule getUserInputModule(Context context) {\n return instance.userInputModuleFactory.create(context);\n }\n\n public static StorageModule getStorageModule(Context context) {\n return instance.storageModuleFactory.create(context);\n }\n\n private UserInputModule.Factory userInputModuleFactory;\n private StorageModule.Factory storageModuleFactory;\n\n private MaterialPreferences() {\n userInputModuleFactory = new StandardUserInputFactory();\n storageModuleFactory = new SharedPrefsStorageFactory(null);\n }\n\n public MaterialPreferences setUserInputModule(UserInputModule.Factory factory) {\n userInputModuleFactory = factory;\n return this;\n }\n\n public MaterialPreferences setStorageModule(StorageModule.Factory factory) {\n storageModuleFactory = factory;\n return this;\n }\n\n public void setDefault() {\n userInputModuleFactory = new StandardUserInputFactory();\n storageModuleFactory = new SharedPrefsStorageFactory(null);\n }\n\n\n private static class StandardUserInputFactory implements UserInputModule.Factory {\n @Override\n public UserInputModule create(Context context) {\n return new StandardUserInputModule(context);\n }\n }\n}",
"public interface StorageModule {\n\n void saveBoolean(String key, boolean value);\n\n void saveString(String key, String value);\n\n void saveInt(String key, int value);\n\n void saveStringSet(String key, Set<String> value);\n\n boolean getBoolean(String key, boolean defaultVal);\n\n String getString(String key, String defaultVal);\n\n int getInt(String key, int defaultVal);\n\n Set<String> getStringSet(String key, Set<String> defaultVal);\n\n void onSaveInstanceState(Bundle outState);\n\n void onRestoreInstanceState(Bundle savedState);\n\n interface Factory {\n StorageModule create(Context context);\n }\n}",
"public interface UserInputModule {\n\n void showEditTextInput(\n String key,\n CharSequence title,\n CharSequence defaultValue,\n Listener<String> listener);\n\n void showSingleChoiceInput(\n String key,\n CharSequence title,\n CharSequence[] displayItems,\n CharSequence[] values,\n int selected,\n Listener<String> listener);\n\n void showMultiChoiceInput(\n String key,\n CharSequence title,\n CharSequence[] displayItems,\n CharSequence[] values,\n boolean[] defaultSelection,\n Listener<Set<String>> listener);\n\n void showColorSelectionInput(\n String key,\n CharSequence title,\n int defaultColor,\n Listener<Integer> color);\n\n interface Factory {\n UserInputModule create(Context context);\n }\n\n interface Listener<T> {\n void onInput(T value);\n }\n}",
"public class CompositeClickListener implements View.OnClickListener {\n\n private List<View.OnClickListener> listeners;\n\n public CompositeClickListener() {\n listeners = new ArrayList<>();\n }\n\n @Override\n public void onClick(View v) {\n for (int i = listeners.size() - 1; i >= 0; i--) {\n listeners.get(i).onClick(v);\n }\n }\n\n public int addListener(View.OnClickListener listener) {\n listeners.add(listener);\n return listeners.size() - 1;\n }\n\n public void removeListener(View.OnClickListener listener) {\n listeners.remove(listener);\n }\n\n public void removeListener(int index) {\n listeners.remove(index);\n }\n}",
"public class Utils {\n\n private Utils() {}\n\n public static int dpToPixels(Context context, int dp) {\n Resources resources = context.getResources();\n DisplayMetrics metrics = resources.getDisplayMetrics();\n return Math.round(dp * ((float)metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT));\n }\n\n public static int clickableBackground(Context context) {\n TypedValue outValue = new TypedValue();\n context.getTheme().resolveAttribute(android.R.attr.selectableItemBackground, outValue, true);\n return outValue.resourceId;\n }\n}"
] | import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.ColorInt;
import androidx.annotation.ColorRes;
import androidx.annotation.DrawableRes;
import androidx.annotation.LayoutRes;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.core.content.ContextCompat;
import com.yarolegovich.mp.io.MaterialPreferences;
import com.yarolegovich.mp.io.StorageModule;
import com.yarolegovich.mp.io.UserInputModule;
import com.yarolegovich.mp.util.CompositeClickListener;
import com.yarolegovich.mp.util.Utils; | } finally {
ta.recycle();
}
onCollectAttributes(attrs);
onConfigureSelf();
inflate(getContext(), getLayout(), this);
title = (TextView) findViewById(R.id.mp_title);
summary = (TextView) findViewById(R.id.mp_summary);
icon = (ImageView) findViewById(R.id.mp_icon);
setTitle(titleText);
setSummary(summaryText);
setIcon(iconDrawable);
if (iconTintColor != -1) {
setIconColor(iconTintColor);
}
onViewCreated();
}
public abstract T getValue();
public abstract void setValue(T value);
public void setTitle(@StringRes int textRes) {
setTitle(string(textRes));
}
public void setTitle(CharSequence text) {
title.setVisibility(visibility(text));
title.setText(text);
}
public void setSummary(@StringRes int textRes) {
setSummary(string(textRes));
}
public void setSummary(CharSequence text) {
summary.setVisibility(visibility(text));
summary.setText(text);
}
public void setIcon(@DrawableRes int drawableRes) {
setIcon(drawable(drawableRes));
}
public void setIcon(Drawable iconDrawable) {
icon.setVisibility(iconDrawable != null ? VISIBLE : GONE);
icon.setImageDrawable(iconDrawable);
}
public void setIconColorRes(@ColorRes int colorRes) {
icon.setColorFilter(color(colorRes));
}
public void setIconColor(@ColorInt int color) {
icon.setColorFilter(color);
}
public String getTitle() {
return title.getText().toString();
}
public String getSummary() {
return summary.getText().toString();
}
/*
* Returns index of listener. Index may change, so better do not rely heavily on it.
* It is not a key.
*/
public int addPreferenceClickListener(View.OnClickListener listener) {
return compositeClickListener.addListener(listener);
}
@Override
public void setOnClickListener(OnClickListener l) {
if (compositeClickListener == null) {
super.setOnClickListener(l);
} else {
compositeClickListener.addListener(l);
}
}
public void removePreferenceClickListener(View.OnClickListener listener) {
compositeClickListener.removeListener(listener);
}
public void removePreferenceClickListener(int index) {
compositeClickListener.removeListener(index);
}
public void setUserInputModule(UserInputModule userInputModule) {
this.userInputModule = userInputModule;
}
public void setStorageModule(StorageModule storageModule) {
this.storageModule = storageModule;
}
@Nullable
public String getKey() {
return key;
}
@LayoutRes
protected abstract int getLayout();
/*
* Template methods
*/
protected void onCollectAttributes(AttributeSet attrs) {
}
protected void onConfigureSelf() { | setBackgroundResource(Utils.clickableBackground(getContext())); | 4 |
mikelewis0/easyccg | src/uk/ac/ed/easyccg/rebanking/CCGBankParseReader.java | [
"public abstract class Category {\n private final String asString;\n private final int id;\n private final static String WILDCARD_FEATURE = \"X\"; \n private final static Set<String> bracketAndQuoteCategories = ImmutableSet.of(\"LRB\", \"RRB\", \"LQU\", \"RQU\");\n\n private Category(String asString, String semanticAnnotation) {\n this.asString = asString + (semanticAnnotation == null ? \"\" : \"{\" + semanticAnnotation + \"}\");\n this.id = numCats.getAndIncrement();\n }\n\n public enum Slash {\n FWD, BWD, EITHER;\n public String toString()\n {\n String result = \"\";\n\n switch (this)\n {\n case FWD: result = \"/\"; break;\n case BWD: result = \"\\\\\"; break;\n case EITHER: result = \"|\"; break;\n\n }\n\n return result;\n }\n\n public static Slash fromString(String text) {\n if (text != null) {\n for (Slash slash : values()) {\n if (text.equalsIgnoreCase(slash.toString())) \n {\n return slash;\n }\n }\n }\n throw new IllegalArgumentException(\"Invalid slash: \" + text);\n }\n\n public boolean matches(Slash other)\n {\n return this == EITHER || this == other;\n }\n }\n\n private static AtomicInteger numCats = new AtomicInteger();\n private final static Map<String, Category> cache = new HashMap<String, Category>();\n public static final Category COMMA = Category.valueOf(\",\");\n public static final Category SEMICOLON = Category.valueOf(\";\");\n public static final Category CONJ = Category.valueOf(\"conj\");\n public final static Category N = valueOf(\"N\"); \n public static final Category LQU = Category.valueOf(\"LQU\");\n public static final Category LRB = Category.valueOf(\"LRB\");\n public static final Category NP = Category.valueOf(\"NP\");\n public static final Category PP = Category.valueOf(\"PP\");\n public static final Category PREPOSITION = Category.valueOf(\"PP/NP\");\n public static final Category PR = Category.valueOf(\"PR\");\n\n public static Category valueOf(String cat) {\n\n Category result = cache.get(cat);\n if (result == null) {\n\n String name = Util.dropBrackets(cat);\n result = cache.get(name);\n\n if (result == null) {\n result = Category.valueOfUncached(name);\n if (name != cat) {\n synchronized(cache) {\n cache.put(name, result);\n }\n }\n }\n\n synchronized(cache) {\n cache.put(cat, result);\n }\n }\n\n return result;\n }\n\n /**\n * Builds a category from a string representation.\n */\n private static Category valueOfUncached(String source)\n {\n // Categories have the form: ((X/Y)\\Z[feature]){ANNOTATION}\n String newSource = source;\n\n String semanticAnnotation;\n if (newSource.endsWith(\"}\")) {\n int openIndex = newSource.lastIndexOf(\"{\");\n semanticAnnotation = newSource.substring(openIndex + 1, newSource.length() - 1);\n newSource = newSource.substring(0, openIndex);\n } else {\n semanticAnnotation = null;\n }\n\n if (newSource.startsWith(\"(\"))\n {\n int closeIndex = Util.findClosingBracket(newSource);\n\n if (Util.indexOfAny(newSource.substring(closeIndex), \"/\\\\|\") == -1)\n {\n // Simplify (X) to X\n newSource = newSource.substring(1, closeIndex);\n Category result = valueOfUncached(newSource);\n\n return result;\n }\n }\n\n int endIndex = newSource.length();\n\n int opIndex = Util.findNonNestedChar(newSource, \"/\\\\|\");\n\n\n if (opIndex == -1)\n {\n // Atomic Category\n int featureIndex = newSource.indexOf(\"[\");\n List<String> features = new ArrayList<String>();\n\n String base = (featureIndex == -1 ? newSource : newSource.substring(0, featureIndex));\n\n while (featureIndex > -1)\n {\n features.add(newSource.substring(featureIndex + 1, newSource.indexOf(\"]\", featureIndex)));\n featureIndex = newSource.indexOf(\"[\", featureIndex + 1);\n }\n\n if (features.size() > 1) {\n throw new RuntimeException(\"Can only handle single features: \" + source);\n }\n\n Category c = new AtomicCategory(base, features.size() == 0 ? null : features.get(0), semanticAnnotation);\n return c;\n }\n else\n {\n // Functor Category\n\n Category left = valueOf(newSource.substring(0, opIndex));\n Category right = valueOf(newSource.substring(opIndex + 1, endIndex));\n return new FunctorCategory(left, \n Slash.fromString(newSource.substring(opIndex, opIndex + 1)), \n right,\n semanticAnnotation\n );\n }\n } \n\n public String toString() {\n return asString;\n }\n\n @Override\n public boolean equals(Object other) {\n return this == other;\n }\n\n @Override \n public int hashCode() {\n return id;\n }\n\n abstract boolean isTypeRaised();\n abstract boolean isForwardTypeRaised();\n abstract boolean isBackwardTypeRaised();\n\n public abstract boolean isModifier();\n public abstract boolean matches(Category other);\n public abstract Category getLeft();\n public abstract Category getRight();\n abstract Slash getSlash();\n abstract String getFeature();\n\n abstract String toStringWithBrackets();\n public abstract Category dropPPandPRfeatures();\n\n static class FunctorCategory extends Category {\n private final Category left;\n private final Category right;\n private final Slash slash;\n private final boolean isMod;\n\n private FunctorCategory(Category left, Slash slash, Category right, String semanticAnnotation) {\n super(left.toStringWithBrackets() + slash + right.toStringWithBrackets(), semanticAnnotation);\n this.left = left;\n this.right = right;\n this.slash = slash;\n this.isMod = left.equals(right);\n\n // X|(X|Y)\n this.isTypeRaised = right.isFunctor() && right.getLeft().equals(left);\n }\n\n @Override\n public boolean isModifier()\n {\n return isMod;\n }\n\n @Override\n public boolean matches(Category other)\n {\n return other.isFunctor() && left.matches(other.getLeft()) && right.matches(other.getRight()) && slash.matches(other.getSlash());\n }\n\n @Override\n public Category getLeft()\n {\n return left;\n }\n\n @Override\n public Category getRight()\n {\n return right;\n }\n\n @Override\n Slash getSlash()\n {\n return slash;\n }\n\n @Override\n String getFeature()\n {\n throw new UnsupportedOperationException();\n }\n\n @Override\n String toStringWithBrackets()\n {\n return \"(\" + toString() + \")\";\n }\n\n @Override\n public boolean isFunctor()\n {\n return true;\n }\n\n @Override\n public boolean isPunctuation()\n {\n return false;\n }\n\n @Override\n String getType()\n {\n throw new UnsupportedOperationException();\n }\n\n @Override\n String getSubstitution(Category other)\n {\n String result = getRight().getSubstitution(other.getRight());\n if (result == null) {\n // Bit of a hack, but seems to reproduce CCGBank in cases of clashing features.\n result = getLeft().getSubstitution(other.getLeft());\n }\n return result;\n }\n\n private final boolean isTypeRaised;\n @Override\n public boolean isTypeRaised()\n {\n return isTypeRaised;\n }\n\n @Override\n public boolean isForwardTypeRaised()\n {\n // X/(X\\Y)\n return isTypeRaised() && getSlash() == Slash.FWD;\n }\n\n @Override\n public boolean isBackwardTypeRaised()\n {\n // X\\(X/Y)\n return isTypeRaised() && getSlash() == Slash.BWD;\n }\n\n @Override\n boolean isNounOrNP()\n {\n return false;\n }\n\n @Override\n public Category addFeature(String preposition)\n {\n throw new RuntimeException(\"Functor categories cannot take features\");\n }\n\n @Override\n public int getNumberOfArguments()\n {\n return 1 + left.getNumberOfArguments();\n }\n\n @Override\n public Category replaceArgument(int argNumber, Category newCategory)\n {\n if (argNumber == getNumberOfArguments()) {\n return Category.make(left, slash, newCategory);\n } else {\n return Category.make(left.replaceArgument(argNumber, newCategory), slash, right);\n }\n }\n\n @Override\n public Category getArgument(int argNumber)\n {\n if (argNumber == getNumberOfArguments()) {\n return right;\n } else {\n return left.getArgument(argNumber);\n }\n }\n\n @Override\n public Category getHeadCategory()\n {\n return left.getHeadCategory();\n }\n\n @Override\n public boolean isFunctionIntoModifier()\n {\n return isModifier() || left.isModifier();\n }\n\n @Override\n public boolean isFunctionInto(Category into)\n {\n return into.matches(this) || left.isFunctionInto(into);\n }\n\n @Override\n public Category dropPPandPRfeatures()\n {\n return Category.make(left.dropPPandPRfeatures(), slash, right.dropPPandPRfeatures());\n }\n }\n\n abstract String getSubstitution(Category other);\n\n\n static class AtomicCategory extends Category {\n\n private AtomicCategory(String type, String feature, String semanticAnnotation)\n {\n super(type + (feature == null ? \"\" : \"[\" + feature + \"]\"), semanticAnnotation);\n this.type = type;\n this.feature = feature;\n isPunctuation = !type.matches(\"[A-Za-z]+\") || bracketAndQuoteCategories.contains(type);\n }\n\n private final String type;\n private final String feature;\n @Override\n public boolean isModifier()\n {\n return false;\n }\n\n @Override\n public boolean matches(Category other)\n {\n return !other.isFunctor() && type.equals(other.getType()) && \n (feature == null || feature.equals(other.getFeature()) || WILDCARD_FEATURE.equals(getFeature()) || WILDCARD_FEATURE.equals(other.getFeature())\n || feature.equals(\"nb\") // Ignoring the NP[nb] feature, which isn't very helpful. For example, it stops us coordinating \"John and a girl\",\n // because \"and a girl\" ends up with a NP[nb]\\NP[nb] tag.\n );\n }\n\n @Override\n public Category getLeft()\n {\n throw new UnsupportedOperationException();\n }\n\n @Override\n public Category getRight()\n {\n throw new UnsupportedOperationException();\n }\n\n @Override\n Slash getSlash()\n {\n throw new UnsupportedOperationException();\n }\n\n @Override\n String getFeature()\n {\n return feature;\n }\n\n @Override\n String toStringWithBrackets()\n {\n return toString();\n }\n\n @Override\n public boolean isFunctor()\n {\n return false;\n }\n\n private final boolean isPunctuation;\n @Override\n public boolean isPunctuation()\n {\n return isPunctuation ;\n }\n\n @Override\n String getType()\n {\n return type;\n }\n\n @Override\n String getSubstitution(Category other)\n {\n if (WILDCARD_FEATURE.equals(getFeature())) {\n return other.getFeature();\n } else if (WILDCARD_FEATURE.equals(other.getFeature())) {\n return feature;\n }\n return null;\n }\n\n @Override\n public boolean isTypeRaised()\n {\n return false;\n }\n\n public boolean isForwardTypeRaised()\n {\n return false;\n }\n\n public boolean isBackwardTypeRaised()\n {\n return false;\n }\n\n @Override\n boolean isNounOrNP()\n {\n return type.equals(\"N\") || type.equals(\"NP\");\n }\n\n @Override\n public Category addFeature(String newFeature)\n {\n if (feature != null) throw new RuntimeException(\"Only one feature allowed. Can't add feature: \" + newFeature + \" to category: \" + this);\n newFeature = newFeature.replaceAll(\"/\", \"\");\n newFeature = newFeature.replaceAll(\"\\\\\\\\\", \"\");\n return valueOf(type + \"[\" + newFeature + \"]\");\n }\n\n @Override\n public int getNumberOfArguments()\n {\n return 0;\n }\n\n @Override\n public Category replaceArgument(int argNumber, Category newCategory)\n {\n if (argNumber == 0) return newCategory;\n throw new RuntimeException(\"Error replacing argument of category\");\n }\n\n @Override\n public Category getArgument(int argNumber)\n {\n if (argNumber == 0) return this;\n throw new RuntimeException(\"Error getting argument of category\");\n }\n\n @Override\n public Category getHeadCategory()\n {\n return this;\n }\n\n @Override\n public boolean isFunctionIntoModifier()\n {\n return false;\n }\n\n @Override\n public boolean isFunctionInto(Category into)\n {\n return into.matches(this);\n }\n\n @Override\n public Category dropPPandPRfeatures()\n {\n if (type.equals(\"PP\") || type.equals(\"PP\")) {\n return valueOf(type);\n } else {\n return this;\n }\n } \n }\n\n public static Category make(Category left, Slash op, Category right)\n {\n return valueOf(left.toStringWithBrackets() + op + right.toStringWithBrackets());\n }\n\n abstract String getType();\n\n abstract boolean isFunctor();\n\n abstract boolean isPunctuation();\n\n /**\n * Returns the Category created by substituting all [X] wildcard features with the supplied argument.\n */\n Category doSubstitution(String substitution)\n {\n if (substitution == null) return this;\n return valueOf(toString().replaceAll(WILDCARD_FEATURE, substitution));\n }\n\n /**\n * A unique numeric identifier for this category.\n */\n int getID()\n {\n return id;\n }\n\n abstract boolean isNounOrNP();\n\n public abstract Category addFeature(String preposition);\n\n public abstract int getNumberOfArguments();\n public abstract Category getHeadCategory();\n public abstract boolean isFunctionInto(Category into);\n\n\n /**\n * Replaces the argument with the given index with the new Category. Arguments are count from the left, starting with 0 for the head Category.\n * e.g. (((S\\NP)/NP)/PP)/PR @replaceArgument(3, PP[in]) = (((S\\NP)/NP)/PP[in])/PR\n */\n public abstract Category replaceArgument(int argNumber, Category newCategory);\n\n public abstract Category getArgument(int argNumber);\n public abstract boolean isFunctionIntoModifier();\n\n\n}",
"public enum Slash {\n FWD, BWD, EITHER;\n public String toString()\n {\n String result = \"\";\n\n switch (this)\n {\n case FWD: result = \"/\"; break;\n case BWD: result = \"\\\\\"; break;\n case EITHER: result = \"|\"; break;\n\n }\n\n return result;\n }\n\n public static Slash fromString(String text) {\n if (text != null) {\n for (Slash slash : values()) {\n if (text.equalsIgnoreCase(slash.toString())) \n {\n return slash;\n }\n }\n }\n throw new IllegalArgumentException(\"Invalid slash: \" + text);\n }\n\n public boolean matches(Slash other)\n {\n return this == EITHER || this == other;\n }\n}",
"public abstract class SyntaxTreeNode implements Comparable<SyntaxTreeNode> {\n \n private final Category category;\n final double probability;\n final int hash;\n final int totalDependencyLength;\n private final int headIndex;\n \n abstract SyntaxTreeNodeLeaf getHead();\n \n private SyntaxTreeNode(\n Category category, \n double probability, \n int hash, \n int totalDependencyLength,\n int headIndex\n )\n {\n this.category = category;\n this.probability = probability;\n this.hash = hash;\n this.totalDependencyLength = totalDependencyLength;\n this.headIndex = headIndex;\n }\n \n static class SyntaxTreeNodeBinary extends SyntaxTreeNode {\n final RuleType ruleType;\n final boolean headIsLeft;\n final SyntaxTreeNode leftChild;\n final SyntaxTreeNode rightChild;\n private SyntaxTreeNodeBinary(Category category, double probability, int hash, int totalDependencyLength, int headIndex,\n RuleType ruleType, boolean headIsLeft, SyntaxTreeNode leftChild, SyntaxTreeNode rightChild)\n {\n super(category, probability, hash, totalDependencyLength, headIndex);\n this.ruleType = ruleType;\n this.headIsLeft = headIsLeft;\n this.leftChild = leftChild;\n this.rightChild = rightChild;\n }\n @Override\n void accept(SyntaxTreeNodeVisitor v)\n {\n v.visit(this);\n }\n @Override\n public RuleType getRuleType()\n {\n return ruleType;\n }\n @Override\n public List<SyntaxTreeNode> getChildren()\n {\n return Arrays.asList(leftChild, rightChild);\n }\n @Override\n SyntaxTreeNodeLeaf getHead()\n {\n return headIsLeft ? leftChild.getHead() : rightChild.getHead();\n }\n @Override\n int dimension()\n {\n int left = leftChild.dimension();\n int right = rightChild.dimension();\n if (left == right) {\n return 1 + left;\n } else {\n return Math.max(left, right);\n }\n \n \n }\n \n }\n \n public static class SyntaxTreeNodeLeaf extends SyntaxTreeNode {\n private SyntaxTreeNodeLeaf(\n String word, String pos, String ner, \n Category category, double probability, int hash, int totalDependencyLength, int headIndex\n )\n {\n super(category, probability, hash, totalDependencyLength, headIndex);\n this.pos = pos;\n this.ner = ner;\n this.word = word;\n }\n private final String pos;\n private final String ner;\n private final String word; \n @Override\n void accept(SyntaxTreeNodeVisitor v)\n {\n v.visit(this);\n }\n @Override\n public RuleType getRuleType()\n {\n return RuleType.LEXICON;\n }\n @Override\n public List<SyntaxTreeNode> getChildren()\n {\n return Collections.emptyList();\n }\n \n @Override\n public boolean isLeaf()\n {\n return true;\n }\n \n @Override\n void getWords(List<SyntaxTreeNodeLeaf> result) {\n result.add(this);\n }\n public String getPos()\n {\n return pos;\n }\n public String getNER()\n {\n return ner;\n }\n public String getWord()\n {\n return word;\n }\n @Override\n SyntaxTreeNodeLeaf getHead()\n {\n return this;\n }\n @Override\n int dimension()\n {\n return 0;\n }\n public int getSentencePosition()\n {\n return getHeadIndex();\n }\n }\n \n static class SyntaxTreeNodeUnary extends SyntaxTreeNode {\n private SyntaxTreeNodeUnary(Category category, double probability, int hash, int totalDependencyLength, int headIndex, SyntaxTreeNode child)\n {\n super(category, probability, hash, totalDependencyLength, headIndex);\n\n this.child = child;\n }\n\n final SyntaxTreeNode child;\n\n @Override\n void accept(SyntaxTreeNodeVisitor v)\n {\n v.visit(this);\n }\n\n @Override\n public RuleType getRuleType()\n {\n return RuleType.UNARY;\n }\n\n @Override\n public List<SyntaxTreeNode> getChildren()\n {\n return Arrays.asList(child);\n }\n\n @Override\n SyntaxTreeNodeLeaf getHead()\n {\n return child.getHead();\n }\n\n @Override\n int dimension()\n {\n return child.dimension();\n }\n }\n\n public String toString() {\n return ParsePrinter.CCGBANK_PRINTER.print(this, -1);\n }\n \n abstract int dimension();\n \n public int getHeadIndex() {\n return headIndex;\n }\n \n @Override\n public int compareTo(SyntaxTreeNode o)\n {\n return Double.compare(o.probability, probability); \n }\n \n /**\n * Factory for SyntaxTreeNode. Using a factory so we can have different hashing/caching behaviour when N-best parsing.\n */\n public static class SyntaxTreeNodeFactory {\n private final int[][] categoryHash;\n private final int[][] dependencyHash;\n private final boolean hashWords;\n \n /**\n * These parameters are needed so that it can pre-compute some hash values. \n * @param maxSentenceLength\n * @param numberOfLexicalCategories\n */\n public SyntaxTreeNodeFactory(int maxSentenceLength, int numberOfLexicalCategories) {\n \n hashWords = numberOfLexicalCategories > 0;\n categoryHash = makeRandomArray(maxSentenceLength, numberOfLexicalCategories + 1);\n dependencyHash = makeRandomArray(maxSentenceLength, maxSentenceLength);\n }\n\n private int[][] makeRandomArray(int x, int y) {\n Random random = new Random();\n int[][] result = new int[x][y]; \n for (int i=0; i<x; i++) {\n for (int j=0; j<y; j++) {\n result[i][j] = random.nextInt();\n }\n }\n \n return result;\n }\n \n public SyntaxTreeNodeLeaf makeTerminal(String word, Category category, String pos, String ner, double probability, int sentencePosition) {\n return new SyntaxTreeNodeLeaf(\n word, pos, ner, category, probability, \n hashWords ? categoryHash[sentencePosition][category.getID()] : 0, 0, sentencePosition);\n }\n \n public SyntaxTreeNode makeUnary(Category category, SyntaxTreeNode child) {\n return new SyntaxTreeNodeUnary(category, child.probability, child.hash, child.totalDependencyLength, child.getHeadIndex(), child);\n }\n \n public SyntaxTreeNode makeBinary(Category category, SyntaxTreeNode left, SyntaxTreeNode right, RuleType ruleType, boolean headIsLeft) {\n \n int totalDependencyLength = (right.getHeadIndex() - left.getHeadIndex())\n + left.totalDependencyLength + right.totalDependencyLength;\n\n int hash;\n if (right.getCategory().isPunctuation()) {\n // Ignore punctuation when calculating the hash, because we don't really care where a full-stop attaches.\n hash = left.hash;\n } else if (left.getCategory().isPunctuation()) {\n // Ignore punctuation when calculating the hash, because we don't really care where a full-stop attaches.\n hash = right.hash;\n } else {\n // Combine the hash codes in a commutive way, so that left and right branching derivations can still be equivalent.\n hash = left.hash ^ right.hash ^ dependencyHash[left.getHeadIndex()][right.getHeadIndex()];\n }\n \n SyntaxTreeNode result = new SyntaxTreeNodeBinary(\n category, \n left.probability + right.probability, // log probabilities \n hash, \n totalDependencyLength,\n headIsLeft ? left.getHeadIndex() : right.getHeadIndex(),\n ruleType, \n headIsLeft,\n left, \n right);\n \n \n return result;\n } \n }\n\n abstract void accept(SyntaxTreeNodeVisitor v);\n \n public interface SyntaxTreeNodeVisitor {\n void visit(SyntaxTreeNodeBinary node);\n void visit(SyntaxTreeNodeUnary node);\n void visit(SyntaxTreeNodeLeaf node);\n }\n\n public abstract RuleType getRuleType();\n\n public abstract List<SyntaxTreeNode> getChildren();\n\n public boolean isLeaf()\n {\n return false;\n }\n\n /**\n * Returns all the terminal nodes in the sentence, from left to right. \n */\n public List<SyntaxTreeNodeLeaf> getWords()\n {\n List<SyntaxTreeNodeLeaf> result = new ArrayList<SyntaxTreeNodeLeaf>();\n getWords(result);\n return result;\n }\n \n void getWords(List<SyntaxTreeNodeLeaf> result) {\n for (SyntaxTreeNode child : getChildren()) {\n child.getWords(result);\n }\n }\n\n public Category getCategory()\n {\n return category;\n }\n}",
"public static class SyntaxTreeNodeFactory {\n private final int[][] categoryHash;\n private final int[][] dependencyHash;\n private final boolean hashWords;\n \n /**\n * These parameters are needed so that it can pre-compute some hash values. \n * @param maxSentenceLength\n * @param numberOfLexicalCategories\n */\n public SyntaxTreeNodeFactory(int maxSentenceLength, int numberOfLexicalCategories) {\n \n hashWords = numberOfLexicalCategories > 0;\n categoryHash = makeRandomArray(maxSentenceLength, numberOfLexicalCategories + 1);\n dependencyHash = makeRandomArray(maxSentenceLength, maxSentenceLength);\n }\n\n private int[][] makeRandomArray(int x, int y) {\n Random random = new Random();\n int[][] result = new int[x][y]; \n for (int i=0; i<x; i++) {\n for (int j=0; j<y; j++) {\n result[i][j] = random.nextInt();\n }\n }\n \n return result;\n }\n \n public SyntaxTreeNodeLeaf makeTerminal(String word, Category category, String pos, String ner, double probability, int sentencePosition) {\n return new SyntaxTreeNodeLeaf(\n word, pos, ner, category, probability, \n hashWords ? categoryHash[sentencePosition][category.getID()] : 0, 0, sentencePosition);\n }\n \n public SyntaxTreeNode makeUnary(Category category, SyntaxTreeNode child) {\n return new SyntaxTreeNodeUnary(category, child.probability, child.hash, child.totalDependencyLength, child.getHeadIndex(), child);\n }\n \n public SyntaxTreeNode makeBinary(Category category, SyntaxTreeNode left, SyntaxTreeNode right, RuleType ruleType, boolean headIsLeft) {\n \n int totalDependencyLength = (right.getHeadIndex() - left.getHeadIndex())\n + left.totalDependencyLength + right.totalDependencyLength;\n\n int hash;\n if (right.getCategory().isPunctuation()) {\n // Ignore punctuation when calculating the hash, because we don't really care where a full-stop attaches.\n hash = left.hash;\n } else if (left.getCategory().isPunctuation()) {\n // Ignore punctuation when calculating the hash, because we don't really care where a full-stop attaches.\n hash = right.hash;\n } else {\n // Combine the hash codes in a commutive way, so that left and right branching derivations can still be equivalent.\n hash = left.hash ^ right.hash ^ dependencyHash[left.getHeadIndex()][right.getHeadIndex()];\n }\n \n SyntaxTreeNode result = new SyntaxTreeNodeBinary(\n category, \n left.probability + right.probability, // log probabilities \n hash, \n totalDependencyLength,\n headIsLeft ? left.getHeadIndex() : right.getHeadIndex(),\n ruleType, \n headIsLeft,\n left, \n right);\n \n \n return result;\n } \n}",
"public class Util\n{\n public static int indexOfAny(String haystack, String needles) {\n for (int i=0; i<haystack.length(); i++) {\n for (int j=0; j<needles.length(); j++) {\n if (haystack.charAt(i) == needles.charAt(j)) {\n return i;\n }\n } \n }\n \n return -1;\n }\n\n public static Iterable<String> readFile(final File filePath)\n throws java.io.IOException\n {\n return new Iterable<String>() \n {\n\n public Iterator<String> iterator() {\n \n try\n {\n return readFileLineByLine(filePath);\n }\n catch (IOException e)\n {\n throw new RuntimeException(e);\n }\n }\n };\n \n }\n \n public static String executeCommand(String command) throws IOException\n {\n Process process = Runtime.getRuntime().exec(new String[] { \"/bin/sh\", \"-c\", command });\n \n BufferedReader input =\n new BufferedReader\n (new InputStreamReader(process.getInputStream()));\n\n StringBuilder output = new StringBuilder();\n String line;\n while ((line = input.readLine()) != null) {\n output.append(line);\n output.append(\"\\n\");\n }\n input.close();\n \n return output.toString(); \n \n }\n \n public static void writeStringToFile(String text, File filePath)\n throws java.io.IOException{\n BufferedWriter out = new BufferedWriter(new FileWriter(filePath));\n out.write(text);\n out.close();\n }\n\n public static Iterator<String> readFileLineByLine(final File filePath)\n throws java.io.IOException\n {\n return new Iterator<String>()\n {\n\n // Open the file that is the first \n // command line parameter\n InputStream fstream = new FileInputStream(filePath);\n {\n if (filePath.getName().endsWith(\".gz\")) {\n // Automatically unzip zipped files.\n fstream = new GZIPInputStream(fstream);\n }\n }\n \n // Get the object of DataInputStream\n DataInputStream in = new DataInputStream(fstream);\n BufferedReader br = new BufferedReader(new InputStreamReader(in));\n\n String next = br.readLine();\n\n @Override\n public boolean hasNext()\n {\n \n boolean result = (next != null);\n if(!result) {\n try\n {\n br.close();\n }\n catch (IOException e)\n {\n throw new RuntimeException(e); \n }\n }\n \n return result;\n }\n\n @Override\n public String next()\n {\n String result = next;\n try\n {\n next = br.readLine();\n }\n catch (IOException e)\n {\n throw new RuntimeException(e);\n }\n return result;\n }\n\n @Override\n public void remove()\n {\n throw new UnsupportedOperationException();\n }\n };\n }\n\n static String dropBrackets(String cat) {\n if (cat.startsWith(\"(\") && cat.endsWith(\")\") && findClosingBracket(cat) == cat.length() - 1) {\n return cat.substring(1, cat.length() - 1);\n } else {\n return cat; \n } \n }\n\n public static int findClosingBracket(String source)\n {\n return findClosingBracket(source, 0);\n }\n\n public static int findClosingBracket(String source, int startIndex)\n {\n int openBrackets = 0;\n for (int i = startIndex; i < source.length(); i++)\n {\n if (source.charAt(i) == '(')\n {\n openBrackets++;\n }\n else if (source.charAt(i) == ')')\n {\n openBrackets--;\n }\n \n if (openBrackets==0)\n {\n return i;\n }\n }\n \n throw new Error(\"Mismatched brackets in string: \" + source);\n }\n\n /**\n * Finds the first index of a needle character in the haystack, that is not nested in brackets.\n */\n public static int findNonNestedChar(String haystack, String needles)\n {\n int openBrackets = 0;\n\n for (int i=0; i<haystack.length(); i++) {\n if (haystack.charAt(i) == '(')\n {\n openBrackets++;\n }\n else if (haystack.charAt(i) == ')')\n {\n openBrackets--;\n } else if (openBrackets == 0) {\n for (int j=0; j<needles.length(); j++) {\n if (haystack.charAt(i) == needles.charAt(j)) {\n return i;\n }\n } \n }\n }\n \n return -1;\n }\n \n public static List<File> findAllFiles(File folder, final String regex) {\n return Util.findAllFiles(folder,\n new FilenameFilter() {\n @Override\n public boolean accept(File dir, String name) {\n return name.matches(regex);\n }\n }); \n }\n \n public static List<File> findAllFiles(File folder, FilenameFilter filter) {\n List<File> result = new ArrayList<File>();\n \n findAllFiles(folder, filter, result);\n return result;\n }\n\n private static void findAllFiles(File folder, FilenameFilter filter, List<File> result) {\n for (File file : folder.listFiles()) {\n if (file.isDirectory()) {\n findAllFiles(file, filter, result);\n } else if (filter.accept(file, file.getName())) {\n result.add(file.getAbsoluteFile());\n }\n }\n }\n}"
] | import java.util.concurrent.atomic.AtomicInteger;
import uk.ac.ed.easyccg.syntax.Category;
import uk.ac.ed.easyccg.syntax.Category.Slash;
import uk.ac.ed.easyccg.syntax.SyntaxTreeNode;
import uk.ac.ed.easyccg.syntax.SyntaxTreeNode.SyntaxTreeNodeFactory;
import uk.ac.ed.easyccg.syntax.Util; | package uk.ac.ed.easyccg.rebanking;
/**
* Reads in gold-standard parses from CCGBank.
*/
public class CCGBankParseReader
{
public final static SyntaxTreeNodeFactory factory = new SyntaxTreeNodeFactory(1000, 10000);
private final static String OPEN_BRACKET = "(<";
private final static String OPEN_LEAF = "(<L ";
private final static String SPLIT_REGEX = " |>\\)";
public static SyntaxTreeNode parse(String input) {
return parse(input, new AtomicInteger(0));
}
private static SyntaxTreeNode parse(String input, AtomicInteger wordIndex)
{
int closeBracket = Util.findClosingBracket(input, 0);
int nextOpenBracket = input.indexOf(OPEN_BRACKET, 1);
SyntaxTreeNode result;
if (input.startsWith(OPEN_LEAF))
{
//LEAF NODE
String[] parse = input.split(SPLIT_REGEX);
if (parse.length < 6) {
return null;
}
| result = factory.makeTerminal(new String(parse[4]), Category.valueOf(parse[1]), new String(parse[2]), null, 1.0, wordIndex.getAndIncrement()); | 0 |
Whiley/WhileyTheoremProver | src/main/java/wyal/util/TypeChecker.java | [
"public static interface Named extends Declaration {\n\n\tpublic Name getName();\n\n\tpublic Tuple<VariableDeclaration> getParameters();\n\n\tpublic static abstract class FunctionOrMacro extends AbstractSyntacticItem implements Named {\n\t\tpublic FunctionOrMacro(Name name, Tuple<VariableDeclaration> parameters, Stmt.Block body) {\n\t\t\tsuper(DECL_macro, name, parameters, body);\n\t\t}\n\n\t\tpublic FunctionOrMacro(Name name, Tuple<VariableDeclaration> parameters,\n\t\t\t\tTuple<VariableDeclaration> returns) {\n\t\t\tsuper(DECL_fun, name, parameters, returns);\n\t\t}\n\n\t\t@Override\n\t\tpublic Name getName() {\n\t\t\treturn (Name) get(0);\n\t\t}\n\n\t\t@Override\n\t\tpublic Tuple<VariableDeclaration> getParameters() {\n\t\t\treturn (Tuple) get(1);\n\t\t}\n\n\t\tpublic abstract WyalFile.Type.FunctionOrMethodOrProperty getSignatureType();\n\t}\n\n\t// ============================================================\n\t// Function Declaration\n\t// ============================================================\n\tpublic static class Function extends FunctionOrMacro {\n\n\t\tpublic Function(Name name, VariableDeclaration[] parameters, VariableDeclaration[] returns) {\n\t\t\tsuper(name, new Tuple(parameters), new Tuple(returns));\n\t\t}\n\n\t\tpublic Function(Name name, Tuple<VariableDeclaration> parameters,\n\t\t\t\tTuple<VariableDeclaration> returns) {\n\t\t\tsuper(name, parameters, returns);\n\t\t}\n\n\t\tpublic Tuple<VariableDeclaration> getReturns() {\n\t\t\treturn (Tuple<VariableDeclaration>) get(2);\n\t\t}\n\n\t\t@Override\n\t\tpublic WyalFile.Type.Function getSignatureType() {\n\t\t\treturn new WyalFile.Type.Function(projectTypes(getParameters()), projectTypes(getReturns()));\n\t\t}\n\n\t\t@Override\n\t\tpublic Function clone(SyntacticItem[] operands) {\n\t\t\treturn new Function((Name) operands[0], (Tuple) operands[1], (Tuple) operands[2]);\n\t\t}\n\t}\n\n\t// ============================================================\n\t// Macro Declaration\n\t// ============================================================\n\tpublic static class Macro extends FunctionOrMacro {\n\t\tpublic Macro(Name name, VariableDeclaration[] parameters, Stmt.Block body) {\n\t\t\tsuper(name, new Tuple<>(parameters), body);\n\t\t}\n\n\t\tprivate Macro(Name name, Tuple<VariableDeclaration> parameters, Stmt.Block body) {\n\t\t\tsuper(name, parameters, body);\n\t\t}\n\n\t\tpublic Stmt.Block getBody() {\n\t\t\treturn (Stmt.Block) get(2);\n\t\t}\n\n\t\t@Override\n\t\tpublic WyalFile.Type.Property getSignatureType() {\n\t\t\treturn new WyalFile.Type.Property(projectTypes(getParameters()));\n\t\t}\n\n\t\t@Override\n\t\tpublic Macro clone(SyntacticItem[] operands) {\n\t\t\treturn new Macro((Name) operands[0], (Tuple<VariableDeclaration>) operands[1],\n\t\t\t\t\t(Stmt.Block) operands[2]);\n\t\t}\n\t}\n\n\t// ============================================================\n\t// Type Declaration\n\t// ============================================================\n\tpublic static class Type extends AbstractSyntacticItem implements Named {\n\n\t\tpublic Type(Name name, VariableDeclaration vardecl, Stmt.Block... invariant) {\n\t\t\tsuper(DECL_type, name, vardecl, new Tuple(invariant));\n\t\t}\n\n\t\tprivate Type(Name name, VariableDeclaration vardecl, Tuple<Stmt.Block> invariant) {\n\t\t\tsuper(DECL_type, name, vardecl, invariant);\n\t\t}\n\n\t\t@Override\n\t\tpublic Name getName() {\n\t\t\treturn (Name) get(0);\n\t\t}\n\n\t\tpublic VariableDeclaration getVariableDeclaration() {\n\t\t\treturn (VariableDeclaration) get(1);\n\t\t}\n\n\t\tpublic Tuple<Stmt.Block> getInvariant() {\n\t\t\treturn (Tuple) get(2);\n\t\t}\n\n\t\t@Override\n\t\tpublic Type clone(SyntacticItem[] operands) {\n\t\t\treturn new Type((Name) operands[0], (VariableDeclaration) operands[1], (Tuple) operands[2]);\n\t\t}\n\n\t\t@Override\n\t\tpublic Tuple<VariableDeclaration> getParameters() {\n\t\t\treturn new Tuple<>(getVariableDeclaration());\n\t\t}\n\t}\n}",
"public interface Environment {\n\t/**\n\t * Return the current type associated with a given variable. It is\n\t * generally assumed that this either matches its declared type, or is a\n\t * refinement thereof.\n\t *\n\t * @param var\n\t * @return\n\t */\n\tWyalFile.Type getType(WyalFile.VariableDeclaration var);\n\n\t/**\n\t * Refine the type associated with a given variable declaration in this\n\t * environment, which produces a completely new environment containing\n\t * the refined type. Observe that the variable need not have been\n\t * previously declared for this to make sense. Also, observe that the\n\t * resulting type for a given variable is the intersection of its\n\t * original type and the refined type.\n\t *\n\t * @param var\n\t * @param type\n\t * @return\n\t */\n\tEnvironment refineType(WyalFile.VariableDeclaration var, Type type);\n\n\tSet<WyalFile.VariableDeclaration> getRefinedVariables();\n}",
"public class StdTypeEnvironment implements TypeInferer.Environment {\n\tprivate final Map<WyalFile.VariableDeclaration,Type> refinements;\n\n\tpublic StdTypeEnvironment() {\n\t\tthis.refinements = new HashMap<>();\n\t}\n\n\tpublic StdTypeEnvironment(Map<WyalFile.VariableDeclaration,Type> refinements) {\n\t\tthis.refinements = new HashMap<>(refinements);\n\t}\n\n\t@Override\n\tpublic Type getType(VariableDeclaration var) {\n\t\tType refined = refinements.get(var);\n\t\tif(refined != null) {\n\t\t\treturn refined;\n\t\t} else {\n\t\t\treturn var.getType();\n\t\t}\n\t}\n\n\t@Override\n\tpublic Environment refineType(VariableDeclaration var, Type refinement) {\n\t\tType type = intersect(getType(var),refinement);\n\t\tStdTypeEnvironment r = new StdTypeEnvironment(this.refinements);\n\t\tr.refinements.put(var,type);\n\t\treturn r;\n\t}\n\n\n\t@Override\n\tpublic Set<VariableDeclaration> getRefinedVariables() {\n\t\treturn refinements.keySet();\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\tString r = \"{\";\n\t\tboolean firstTime = true;\n\t\tfor(WyalFile.VariableDeclaration var : refinements.keySet()) {\n\t\t\tif(!firstTime) {\n\t\t\t\tr += \", \";\n\t\t\t}\n\t\t\tfirstTime=false;\n\t\t\tr += var.getVariableName() + \"->\" + getType(var);\n\t\t}\n\t\treturn r + \"}\";\n\t}\n\n\n\tprivate Type intersect(Type left, Type right) {\n\t\t// FIXME: a more comprehensive simplification strategy would make sense\n\t\t// here.\n\t\tif(left == right || left.equals(right)) {\n\t\t\treturn left;\n\t\t} else {\n\t\t\treturn new Type.Intersection(new Type[]{left,right});\n\t\t}\n\t}\n}",
"public class TypeSystem {\n\t/**\n\t * The \"null\" environment provides a simple environment which simply falls\n\t * back to using the declared type for a given variable.\n\t */\n\tpublic final static TypeInferer.Environment NULL_ENVIRONMENT = new StdTypeEnvironment();\n\t//\n\tprivate final NameResolver resolver;\n\tprivate final SubtypeOperator coerciveSubtypeOperator;\n\tprivate final TypeExtractor<Type.Record,Object> readableRecordExtractor;\n\tprivate final TypeExtractor<Type.Array,Object> readableArrayExtractor;\n\tprivate final TypeExtractor<Type.Reference,Object> readableReferenceExtractor;\n\tprivate final TypeInvariantExtractor typeInvariantExtractor;\n\tprivate final TypeInferer typeInfererence;\n\tprivate final TypeRewriter typeSimplifier;\n\n\tpublic TypeSystem(Build.Project project) {\n\t\tthis.resolver = new WyalFileResolver(project);\n\t\tthis.coerciveSubtypeOperator = new CoerciveSubtypeOperator(resolver);\n\t\tthis.readableRecordExtractor = new ReadableRecordExtractor(resolver,this);\n\t\tthis.readableArrayExtractor = new ReadableArrayExtractor(resolver,this);\n\t\tthis.readableReferenceExtractor = new ReadableReferenceExtractor(resolver,this);\n\t\tthis.typeInvariantExtractor = new TypeInvariantExtractor(resolver);\n\t\tthis.typeInfererence = new StdTypeInfererence(this);\n\t\tthis.typeSimplifier = new StdTypeRewriter();\n\t}\n\n\t/**\n\t * <p>\n\t * Determine whether one type is a <i>raw subtype</i> of another.\n\t * Specifically, whether the raw type of <code>rhs</code> is a subtype of\n\t * <code>lhs</code>'s raw type (i.e.\n\t * \"<code>⌊lhs⌋ :> ⌊rhs⌋</code>\"). The raw type\n\t * is that which ignores any type invariants involved. Thus, one must be\n\t * careful when interpreting the meaning of this operation. Specifically,\n\t * \"<code>⌊lhs⌋ :> ⌊rhs⌋</code>\" <b>does not\n\t * imply</b> that \"<code>lhs :> rhs</code>\" holds. However, if\n\t * \"<code>⌊lhs⌋ :> ⌊rhs⌋</code>\" does not hold,\n\t * then it <b>does follow</b> that \"<code>lhs :> rhs</code>\" also does not\n\t * hold.\n\t * </p>\n\t *\n\t * <p>\n\t * Depending on the exact language of types involved, this can be a\n\t * surprisingly complex operation. For example, in the presence of\n\t * <i>union</i>, <i>intersection</i> and <i>negation</i> types, the subtype\n\t * algorithm is surprisingly intricate.\n\t * </p>\n\t *\n\t * @param lhs\n\t * The candidate \"supertype\". That is, lhs's raw type may be a\n\t * supertype of <code>rhs</code>'s raw type.\n\t * @param rhs\n\t * The candidate \"subtype\". That is, rhs's raw type may be a\n\t * subtype of <code>lhs</code>'s raw type.\n\t * @return\n\t * @throws ResolutionError\n\t * Occurs when a nominal type is encountered whose name cannot\n\t * be resolved properly. For example, it resolves to more than\n\t * one possible matching declaration, or it cannot be resolved\n\t * to a corresponding type declaration.\n\t */\n\tpublic boolean isRawSubtype(Type lhs, Type rhs) throws ResolutionError {\n\t\treturn coerciveSubtypeOperator.isSubtype(lhs,rhs) != SubtypeOperator.Result.False;\n\t}\n\n\t/**\n\t * For a given type, extract its effective record type. For example, the\n\t * type <code>({int x, int y}|{int x, int z})</code> has effective record\n\t * type <code>{int x, ...}</code>. The following illustrates some more\n\t * cases:\n\t *\n\t * <pre>\n\t * {int x, int y} | null ==> null\n\t * {int x, int y} | {int x} ==> null\n\t * {int x, int y} | {int x, bool y} ==> {int x, int|bool y}\n\t * {int x, int y} & null ==> null\n\t * {int x, int y} & {int x} ==> null\n\t * {int x, int y} & {int x, int|bool y} ==> {int x, int y}\n\t * </pre>\n\t *\n\t * @param type\n\t * @return\n\t * @throws ResolutionError\n\t */\n\tpublic Type.Record extractReadableRecord(Type type) throws ResolutionError {\n\t\treturn readableRecordExtractor.extract(type,null);\n\t}\n\n\t/**\n\t * Extract the readable array type from a given type. For example, the type\n\t * <code>(int[])|(bool[])</code> has a readable array type of\n\t * <code>(int|bool)[]</code>.\n\t *\n\t * @param type\n\t * @return\n\t * @throws ResolutionError\n\t */\n\tpublic Type.Array extractReadableArray(Type type) throws ResolutionError {\n\t\treturn readableArrayExtractor.extract(type,null);\n\t}\n\n\t/**\n\t * Extract the readable reference type from a given type. This is relatively\n\t * straightforward. For example, <code>&int</code> is extracted as\n\t * <code>&int</code>. However, <code>(&int)|(&bool)</code> is not extracted\n\t * as as <code>&(int|bool)</code>.\n\t *\n\t * @param type\n\t * @return\n\t * @throws ResolutionError\n\t */\n\tpublic Type.Reference extractReadableReference(Type type) throws ResolutionError {\n\t\treturn readableReferenceExtractor.extract(type,null);\n\t}\n\n\t/**\n\t * Extracting the invariant (if any) from a given type. For example,\n\t * consider the following type declaration:\n\t *\n\t * <pre>\n\t * type nat is (int x) where x >= 0\n\t * </pre>\n\t *\n\t * Then, extracting the invariant from type <code>nat</code> gives\n\t * <code>x >= 0</code>. Likewise, extracting the invariant from the type\n\t * <code>bool|int</code> gives the invariant\n\t * <code>(x is int) ==> (x >= 0)</code>. Finally, extracting the invariant\n\t * from the type <code>nat[]</code> gives the invariant\n\t * <code>forall(int i).(0 <= i\n\t * && i < |xs| ==> xs[i] >= 0)</code>.\n\t *\n\t *\n\t */\n\tpublic Formula extractInvariant(Type type, Expr root) throws ResolutionError {\n\t\treturn typeInvariantExtractor.extract(type,root);\n\t}\n\n\t// ========================================================================\n\t// Inference\n\t// ========================================================================\n\n\t/**\n\t * Get the type inferred for a given expression in a given environment.\n\t *\n\t * @param environment\n\t * @param expression\n\t * @return\n\t * @throws ResolutionError\n\t * Occurs when a particular named type cannot be resolved.\n\t */\n\tpublic Type inferType(TypeInferer.Environment environment, Expr expression) throws ResolutionError {\n\t\treturn typeInfererence.getInferredType(environment, expression);\n\t}\n\n\t// ========================================================================\n\t// Resolution\n\t// ========================================================================\n\n\tpublic <T extends Declaration.Named> T resolveExactly(Name name, Class<T> kind)\n\t\t\tthrows ResolutionError {\n\t\treturn resolver.resolveExactly(name,kind);\n\t}\n\n\tpublic <T extends Declaration.Named> List<T> resolveAll(Name name, Class<T> kind)\n\t\t\tthrows ResolutionError {\n\t\treturn resolver.resolveAll(name,kind);\n\t}\n\n\t// ========================================================================\n\t// Simplification\n\t// ========================================================================\n\n\tpublic Type simplify(Type type) {\n\t\treturn typeSimplifier.rewrite(type);\n\t}\n}",
"public interface Expr extends Stmt {\n\n\t// =========================================================================\n\t// General Expressions\n\t// =========================================================================\n\n\t/**\n\t * Represents a cast expression of the form \"<code>(T) e</code>\" where\n\t * <code>T</code> is the <i>cast type</i> and <code>e</code> the\n\t * <i>casted expression</i>.\n\t *\n\t * @author David J. Pearce\n\t *\n\t */\n\tpublic static class Cast extends AbstractSyntacticItem implements Expr {\n\t\tpublic Cast(Type type, Expr rhs) {\n\t\t\tsuper(EXPR_cast, type, rhs);\n\t\t}\n\n\t\tpublic Type getCastType() {\n\t\t\treturn (Type) super.get(0);\n\t\t}\n\n\t\tpublic Expr getCastedExpr() {\n\t\t\treturn (Expr) super.get(1);\n\t\t}\n\n\t\t@Override\n\t\tpublic Cast clone(SyntacticItem[] operands) {\n\t\t\treturn new Cast((Type) operands[0], (Expr) operands[1]);\n\t\t}\n\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\treturn \"(\" + getCastType() + \") \" + getCastedExpr();\n\t\t}\n\t}\n\n\t/**\n\t * Represents the use of a constant within some expression. For example,\n\t * in <code>x + 1</code> the expression <code>1</code> is a constant\n\t * expression.\n\t *\n\t * @author David J. Pearce\n\t *\n\t */\n\tpublic static class Constant extends AbstractSyntacticItem implements Expr {\n\t\tpublic Constant(Value value) {\n\t\t\tsuper(EXPR_const, value);\n\t\t}\n\n\t\tpublic Value getValue() {\n\t\t\treturn (Value) get(0);\n\t\t}\n\n\t\t@Override\n\t\tpublic Constant clone(SyntacticItem[] operands) {\n\t\t\treturn new Constant((Value) operands[0]);\n\t\t}\n\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\treturn getValue().toString();\n\t\t}\n\t}\n\n\t/**\n\t * Represents a <i>type test expression</i> of the form\n\t * \"<code>e is T</code>\" where <code>e</code> is the <i>test\n\t * expression</i> and <code>T</code> is the <i>test type</i>.\n\t *\n\t * @author David J. Pearce\n\t *\n\t */\n\tpublic static class Is extends AbstractSyntacticItem implements Expr {\n\t\tpublic Is(Expr lhs, Type rhs) {\n\t\t\tsuper(EXPR_is, lhs, rhs);\n\t\t}\n\n\t\tpublic Expr getTestExpr() {\n\t\t\treturn (Expr) get(0);\n\t\t}\n\n\t\tpublic Type getTestType() {\n\t\t\treturn (Type) get(1);\n\t\t}\n\n\t\t@Override\n\t\tpublic Is clone(SyntacticItem[] operands) {\n\t\t\treturn new Is((Expr) operands[0], (Type) operands[1]);\n\t\t}\n\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\treturn getTestExpr() + \" is \" + getTestType();\n\t\t}\n\t}\n\n\t/**\n\t * Represents an invocation of the form \"<code>x.y.f(e1,..en)</code>\".\n\t * Here, <code>x.y.f</code> constitute a <i>partially-</i> or\n\t * <i>fully-qualified name</i> and <code>e1</code> ... <code>en</code>\n\t * are the <i>argument expressions</i>.\n\t *\n\t * @author David J. Pearce\n\t *\n\t */\n\tpublic static class Invoke extends AbstractSyntacticItem implements Expr {\n\n\t\tpublic Invoke(Type.FunctionOrMacroOrInvariant type, Name name, Integer selector, Expr[] arguments) {\n\t\t\tsuper(EXPR_invoke, new SyntacticItem[] { type, name,\n\t\t\t\t\tselector != null ? new Value.Int(selector) : null, new Tuple<>(arguments) });\n\t\t}\n\n\t\tpublic Invoke(Type.FunctionOrMacroOrInvariant type, Name name, Value.Int selector, Tuple<Expr> arguments) {\n\t\t\tsuper(EXPR_invoke, new SyntacticItem[] { type, name, selector, arguments });\n\t\t}\n\n\t\tpublic Type.FunctionOrMacroOrInvariant getSignatureType() {\n\t\t\treturn (Type.FunctionOrMacroOrInvariant) get(0);\n\t\t}\n\n\t\tpublic void setSignatureType(Type.FunctionOrMacroOrInvariant type) {\n\t\t\tthis.setOperand(0, type);\n\t\t}\n\n\t\tpublic Name getName() {\n\t\t\treturn (Name) get(1);\n\t\t}\n\n\t\tpublic Value.Int getSelector() {\n\t\t\treturn (Value.Int) get(2);\n\t\t}\n\n\t\tpublic Tuple<Expr> getArguments() {\n\t\t\treturn (Tuple) get(3);\n\t\t}\n\n\t\t@Override\n\t\tpublic Invoke clone(SyntacticItem[] operands) {\n\t\t\treturn new Invoke((Type.FunctionOrMacroOrInvariant) operands[0], (Name) operands[1],\n\t\t\t\t\t(Value.Int) operands[2], (Tuple) operands[3]);\n\t\t}\n\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\tString r = getName().toString();\n\t\t\tr += getArguments();\n\t\t\tr += \"#\" + getSelector();\n\t\t\treturn r;\n\t\t}\n\t}\n\n\t/**\n\t * Represents an abstract operator expression over one or more\n\t * <i>operand expressions</i>. For example. in <code>arr[i+1]</code> the\n\t * expression <code>i+1</code> is an operator expression.\n\t *\n\t * @author David J. Pearce\n\t *\n\t */\n\tpublic abstract static class Operator extends AbstractSyntacticItem implements Expr {\n\t\tpublic Operator(int opcode, Expr... operands) {\n\t\t\tsuper(opcode, operands);\n\t\t}\n\n\t\t@Override\n\t\tpublic Expr get(int i) {\n\t\t\treturn (Expr) super.get(i);\n\t\t}\n\n\t\t@Override\n\t\tpublic Expr[] getAll() {\n\t\t\treturn (Expr[]) super.getAll();\n\t\t}\n\n\t\t@Override\n\t\tpublic abstract Expr clone(SyntacticItem[] operands);\n\t}\n\n\t/**\n\t * Represents an abstract quantified expression of the form\n\t * \"<code>forall(T v1, ... T vn).e</code>\" or\n\t * \"<code>exists(T v1, ... T vn).e</code>\" where <code>T1 v1</code> ...\n\t * <code>Tn vn</code> are the <i>quantified variable declarations</i>\n\t * and <code>e</code> is the body.\n\t *\n\t * @author David J. Pearce\n\t *\n\t */\n\tpublic abstract static class Quantifier extends AbstractSyntacticItem implements Expr {\n\t\tpublic Quantifier(int opcode, VariableDeclaration[] parameters, Expr body) {\n\t\t\tsuper(opcode, new Tuple<>(parameters), body);\n\t\t}\n\n\t\tpublic Quantifier(int opcode, Tuple<VariableDeclaration> parameters, Expr body) {\n\t\t\tsuper(opcode, parameters, body);\n\t\t}\n\n\t\tpublic Tuple<VariableDeclaration> getParameters() {\n\t\t\treturn (Tuple<VariableDeclaration>) get(0);\n\t\t}\n\n\t\tpublic Expr getBody() {\n\t\t\treturn (Expr) get(1);\n\t\t}\n\n\t\t@Override\n\t\tpublic abstract Expr clone(SyntacticItem[] operands);\n\t}\n\n\t/**\n\t * Represents an unbounded universally quantified expression of the form\n\t * \"<code>forall(T v1, ... T vn).e</code>\" where <code>T1 v1</code> ...\n\t * <code>Tn vn</code> are the <i>quantified variable declarations</i>\n\t * and <code>e</code> is the body.\n\t *\n\t * @author David J. Pearce\n\t *\n\t */\n\tpublic static class UniversalQuantifier extends Quantifier {\n\t\tpublic UniversalQuantifier(VariableDeclaration[] parameters, Expr body) {\n\t\t\tsuper(EXPR_forall, new Tuple<>(parameters), body);\n\t\t}\n\n\t\tpublic UniversalQuantifier(Tuple<VariableDeclaration> parameters, Expr body) {\n\t\t\tsuper(EXPR_forall, parameters, body);\n\t\t}\n\n\t\t@Override\n\t\tpublic Expr clone(SyntacticItem[] operands) {\n\t\t\treturn new UniversalQuantifier((Tuple<VariableDeclaration>) operands[0],\n\t\t\t\t\t(Expr) operands[1]);\n\t\t}\n\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\tString r = \"forall\";\n\t\t\tr += getParameters();\n\t\t\tr += \".\";\n\t\t\tr += getBody();\n\t\t\treturn r;\n\t\t}\n\t}\n\n\t/**\n\t * Represents an unbounded existentially quantified expression of the\n\t * form \"<code>some(T v1, ... T vn).e</code>\" where <code>T1 v1</code>\n\t * ... <code>Tn vn</code> are the <i>quantified variable\n\t * declarations</i> and <code>e</code> is the body.\n\t *\n\t * @author David J. Pearce\n\t *\n\t */\n\tpublic static class ExistentialQuantifier extends Quantifier {\n\t\tpublic ExistentialQuantifier(VariableDeclaration[] parameters, Expr body) {\n\t\t\tsuper(EXPR_exists, new Tuple<>(parameters), body);\n\t\t}\n\n\t\tpublic ExistentialQuantifier(Tuple<VariableDeclaration> parameters, Expr body) {\n\t\t\tsuper(EXPR_exists, parameters, body);\n\t\t}\n\n\t\t@Override\n\t\tpublic Expr clone(SyntacticItem[] operands) {\n\t\t\treturn new ExistentialQuantifier((Tuple<VariableDeclaration>) operands[0], (Expr) operands[1]);\n\t\t}\n\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\tString r = \"exists\";\n\t\t\tr += getParameters();\n\t\t\tr += \".\";\n\t\t\tr += getBody();\n\t\t\treturn r;\n\t\t}\n\t}\n\n\t/**\n\t * Represents a use of some variable within an expression. For example,\n\t * in <code>x + 1</code> the expression <code>x</code> is a variable\n\t * access expression. Every variable access is associated with a\n\t * <i>variable declaration</i> that unique identifies which variable is\n\t * being accessed.\n\t *\n\t * @author David J. Pearce\n\t *\n\t */\n\tpublic static class VariableAccess extends AbstractSyntacticItem implements Expr {\n\t\tpublic VariableAccess(VariableDeclaration decl) {\n\t\t\tsuper(EXPR_varcopy, decl);\n\t\t}\n\n\t\tpublic VariableDeclaration getVariableDeclaration() {\n\t\t\treturn (VariableDeclaration) get(0);\n\t\t}\n\n\t\t@Override\n\t\tpublic VariableAccess clone(SyntacticItem[] operands) {\n\t\t\treturn new VariableAccess((VariableDeclaration) operands[0]);\n\t\t}\n\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\treturn getVariableDeclaration().getVariableName().toString();\n\t\t}\n\t}\n\n\n\tpublic abstract static class InfixOperator extends Operator {\n\t\tpublic InfixOperator(int opcode, Expr... operands) {\n\t\t\tsuper(opcode, operands);\n\t\t}\n\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\tString str = getOperatorString();\n\t\t\tString r = \"\";\n\t\t\tfor (int i = 0; i != size(); ++i) {\n\t\t\t\tif (i != 0) {\n\t\t\t\t\tr += str;\n\t\t\t\t}\n\t\t\t\tr += get(i);\n\t\t\t}\n\t\t\treturn r;\n\t\t}\n\n\t\tprotected abstract String getOperatorString();\n\t}\n\n\t// =========================================================================\n\t// Logical Expressions\n\t// =========================================================================\n\t/**\n\t * Represents a <i>logical conjunction</i> of the form\n\t * \"<code>e1 && .. && en</code>\" where <code>e1</code> ...\n\t * <code>en</code> are the <i>operand expressions</i>.\n\t *\n\t * @author David J. Pearce\n\t *\n\t */\n\tpublic static class LogicalAnd extends InfixOperator {\n\t\tpublic LogicalAnd(Expr... operands) {\n\t\t\tsuper(EXPR_and, operands);\n\t\t}\n\n\t\t@Override\n\t\tpublic Expr clone(SyntacticItem[] operands) {\n\t\t\tif(operands.length <= 1) {\n\t\t\t\tthrow new IllegalArgumentException(\"invalid number of operands\");\n\t\t\t}\n\t\t\treturn new LogicalAnd(ArrayUtils.toArray(Expr.class, operands));\n\t\t}\n\n\t\t@Override\n\t\tprotected String getOperatorString() {\n\t\t\treturn \" && \";\n\t\t}\n\t}\n\n\t/**\n\t * Represents a <i>logical disjunction</i> of the form\n\t * \"<code>e1 || .. || en</code>\" where <code>e1</code> ...\n\t * <code>en</code> are the <i>operand expressions</i>.\n\t *\n\t * @author David J. Pearce\n\t *\n\t */\n\tpublic static class LogicalOr extends InfixOperator {\n\t\tpublic LogicalOr(Expr... operands) {\n\t\t\tsuper(EXPR_or, operands);\n\t\t}\n\n\t\t@Override\n\t\tpublic Expr clone(SyntacticItem[] operands) {\n\t\t\tif(operands.length <= 1) {\n\t\t\t\tthrow new IllegalArgumentException(\"invalid number of operands\");\n\t\t\t}\n\t\t\treturn new LogicalOr(ArrayUtils.toArray(Expr.class, operands));\n\t\t}\n\n\n\t\t@Override\n\t\tprotected String getOperatorString() {\n\t\t\treturn \" && \";\n\t\t}\n\t}\n\n\t/**\n\t * Represents a <i>logical implication</i> of the form\n\t * \"<code>e1 ==> ... ==> en</code>\" where <code>e1</code> ...\n\t * <code>en</code> are the <i>operand expressions</i>.\n\t *\n\t * @author David J. Pearce\n\t *\n\t */\n\tpublic static class LogicalImplication extends InfixOperator {\n\t\tpublic LogicalImplication(Expr... operands) {\n\t\t\tsuper(EXPR_implies, operands);\n\t\t}\n\n\t\t@Override\n\t\tpublic Expr clone(SyntacticItem[] operands) {\n\t\t\tif(operands.length <= 1) {\n\t\t\t\tthrow new IllegalArgumentException(\"invalid number of operands\");\n\t\t\t}\n\t\t\treturn new LogicalImplication(ArrayUtils.toArray(Expr.class, operands));\n\t\t}\n\n\n\t\t@Override\n\t\tprotected String getOperatorString() {\n\t\t\treturn \" ==> \";\n\t\t}\n\t}\n\n\t/**\n\t * Represents a <i>logical biconditional</i> of the form\n\t * \"<code>e1 <==> ... <==> en</code>\" where <code>e1</code> ...\n\t * <code>en</code> are the <i>operand expressions</i>.\n\t *\n\t * @author David J. Pearce\n\t *\n\t */\n\tpublic static class LogicalIff extends InfixOperator {\n\t\tpublic LogicalIff(Expr... operands) {\n\t\t\tsuper(EXPR_iff, operands);\n\t\t}\n\n\t\t@Override\n\t\tpublic Expr clone(SyntacticItem[] operands) {\n\t\t\tif(operands.length <= 1) {\n\t\t\t\tthrow new IllegalArgumentException(\"invalid number of operands\");\n\t\t\t}\n\t\t\treturn new LogicalIff(ArrayUtils.toArray(Expr.class, operands));\n\t\t}\n\n\n\t\t@Override\n\t\tprotected String getOperatorString() {\n\t\t\treturn \" <==> \";\n\t\t}\n\t}\n\n\t/**\n\t * Represents a <i>logical negation</i> of the form \"<code>!e</code>\"\n\t * where <code>e</code> is the <i>operand expression</i>.\n\t *\n\t * @author David J. Pearce\n\t *\n\t */\n\tpublic static class LogicalNot extends Operator {\n\t\tpublic LogicalNot(Expr operand) {\n\t\t\tsuper(EXPR_not, operand);\n\t\t}\n\n\t\tpublic Expr getOperand() {\n\t\t\treturn get(0);\n\t\t}\n\n\t\t@Override\n\t\tpublic Expr clone(SyntacticItem[] operands) {\n\t\t\tif(operands.length != 1) {\n\t\t\t\tthrow new IllegalArgumentException(\"invalid number of operands\");\n\t\t\t}\n\t\t\treturn new LogicalNot((Expr) operands[0]);\n\t\t}\n\t}\n\n\t// =========================================================================\n\t// Comparator Expressions\n\t// =========================================================================\n\n\t/**\n\t * Represents an equality expression of the form\n\t * \"<code>e1 == ... == en</code>\" where <code>e1</code> ...\n\t * <code>en</code> are the <i>operand expressions</i>.\n\t *\n\t * @author David J. Pearce\n\t *\n\t */\n\tpublic static class Equal extends InfixOperator {\n\t\tpublic Equal(Expr... operands) {\n\t\t\tsuper(EXPR_eq, operands);\n\t\t}\n\n\t\t@Override\n\t\tpublic Expr clone(SyntacticItem[] operands) {\n\t\t\tif(operands.length <= 1) {\n\t\t\t\tthrow new IllegalArgumentException(\"invalid number of operands\");\n\t\t\t}\n\t\t\treturn new Equal(ArrayUtils.toArray(Expr.class, operands));\n\t\t}\n\n\t\t@Override\n\t\tpublic String getOperatorString() {\n\t\t\treturn \" == \";\n\t\t}\n\t}\n\n\t/**\n\t * Represents an unequality expression of the form\n\t * \"<code>e1 != ... != en</code>\" where <code>e1</code> ...\n\t * <code>en</code> are the <i>operand expressions</i>.\n\t *\n\t * @author David J. Pearce\n\t *\n\t */\n\tpublic static class NotEqual extends InfixOperator {\n\t\tpublic NotEqual(Expr... operands) {\n\t\t\tsuper(EXPR_neq, operands);\n\t\t}\n\n\t\t@Override\n\t\tpublic Expr clone(SyntacticItem[] operands) {\n\t\t\tif(operands.length <= 1) {\n\t\t\t\tthrow new IllegalArgumentException(\"invalid number of operands\");\n\t\t\t}\n\t\t\treturn new NotEqual(ArrayUtils.toArray(Expr.class, operands));\n\t\t}\n\n\t\t@Override\n\t\tprotected String getOperatorString() {\n\t\t\treturn \" != \";\n\t\t}\n\t}\n\n\t/**\n\t * Represents a strict <i>inequality expression</i> of the form\n\t * \"<code>e1 < ... < en</code>\" where <code>e1</code> ...\n\t * <code>en</code> are the <i>operand expressions</i>.\n\t *\n\t * @author David J. Pearce\n\t *\n\t */\n\tpublic static class LessThan extends InfixOperator {\n\t\tpublic LessThan(Expr... operands) {\n\t\t\tsuper(EXPR_lt, operands);\n\t\t}\n\n\t\t@Override\n\t\tpublic Expr clone(SyntacticItem[] operands) {\n\t\t\tif (operands.length <= 1) {\n\t\t\t\tthrow new IllegalArgumentException(\"invalid number of operands\");\n\t\t\t}\n\t\t\treturn new LessThan(ArrayUtils.toArray(Expr.class, operands));\n\t\t}\n\n\t\t@Override\n\t\tprotected String getOperatorString() {\n\t\t\treturn \" < \";\n\t\t}\n\t}\n\n\t/**\n\t * Represents a non-strict <i>inequality expression</i> of the form\n\t * \"<code>e1 <= ... <= en</code>\" where <code>e1</code> ...\n\t * <code>en</code> are the <i>operand expressions</i>.\n\t *\n\t * @author David J. Pearce\n\t *\n\t */\n\tpublic static class LessThanOrEqual extends InfixOperator {\n\t\tpublic LessThanOrEqual(Expr... operands) {\n\t\t\tsuper(EXPR_lteq, operands);\n\t\t}\n\n\t\t@Override\n\t\tpublic Expr clone(SyntacticItem[] operands) {\n\t\t\tif (operands.length <= 1) {\n\t\t\t\tthrow new IllegalArgumentException(\"invalid number of operands\");\n\t\t\t}\n\t\t\treturn new LessThanOrEqual(ArrayUtils.toArray(Expr.class, operands));\n\t\t}\n\n\t\t@Override\n\t\tprotected String getOperatorString() {\n\t\t\treturn \" <= \";\n\t\t}\n\t}\n\n\t/**\n\t * Represents a strict <i>inequality expression</i> of the form\n\t * \"<code>e1 > ... > en</code>\" where <code>e1</code> ...\n\t * <code>en</code> are the <i>operand expressions</i>.\n\t *\n\t * @author David J. Pearce\n\t *\n\t */\n\tpublic static class GreaterThan extends InfixOperator {\n\t\tpublic GreaterThan(Expr... operands) {\n\t\t\tsuper(EXPR_gt, operands);\n\t\t}\n\n\t\t@Override\n\t\tpublic Expr clone(SyntacticItem[] operands) {\n\t\t\tif (operands.length <= 1) {\n\t\t\t\tthrow new IllegalArgumentException(\"invalid number of operands\");\n\t\t\t}\n\t\t\treturn new GreaterThan(ArrayUtils.toArray(Expr.class, operands));\n\t\t}\n\n\t\t@Override\n\t\tprotected String getOperatorString() {\n\t\t\treturn \" > \";\n\t\t}\n\t}\n\n\t/**\n\t * Represents a non-strict <i>inequality expression</i> of the form\n\t * \"<code>e1 >= ... >= en</code>\" where <code>e1</code> ...\n\t * <code>en</code> are the <i>operand expressions</i>.\n\t *\n\t * @author David J. Pearce\n\t *\n\t */\n\tpublic static class GreaterThanOrEqual extends InfixOperator {\n\t\tpublic GreaterThanOrEqual(Expr... operands) {\n\t\t\tsuper(EXPR_gteq, operands);\n\t\t}\n\n\t\t@Override\n\t\tpublic Expr clone(SyntacticItem[] operands) {\n\t\t\tif (operands.length <= 1) {\n\t\t\t\tthrow new IllegalArgumentException(\"invalid number of operands\");\n\t\t\t}\n\t\t\treturn new GreaterThanOrEqual(ArrayUtils.toArray(Expr.class, operands));\n\t\t}\n\n\t\t@Override\n\t\tprotected String getOperatorString() {\n\t\t\treturn \" >= \";\n\t\t}\n\t}\n\n\t// =========================================================================\n\t// Arithmetic Expressions\n\t// =========================================================================\n\n\t/**\n\t * Represents an arithmetic <i>addition expression</i> of the form\n\t * \"<code>e1 + ... + en</code>\" where <code>e1</code> ...\n\t * <code>en</code> are the <i>operand expressions</i>.\n\t *\n\t * @author David J. Pearce\n\t *\n\t */\n\tpublic static class Addition extends InfixOperator {\n\t\tpublic Addition(Expr... operands) {\n\t\t\tsuper(EXPR_add, operands);\n\t\t}\n\n\t\t@Override\n\t\tpublic Expr clone(SyntacticItem[] operands) {\n\t\t\tif (operands.length <= 1) {\n\t\t\t\tthrow new IllegalArgumentException(\"invalid number of operands\");\n\t\t\t}\n\t\t\treturn new Addition(ArrayUtils.toArray(Expr.class, operands));\n\t\t}\n\n\t\t@Override\n\t\tprotected String getOperatorString() {\n\t\t\treturn \" + \";\n\t\t}\n\t}\n\n\t/**\n\t * Represents an arithmetic <i>subtraction expression</i> of the form\n\t * \"<code>e1 - ... - en</code>\" where <code>e1</code> ...\n\t * <code>en</code> are the <i>operand expressions</i>.\n\t *\n\t * @author David J. Pearce\n\t *\n\t */\n\tpublic static class Subtraction extends InfixOperator {\n\t\tpublic Subtraction(Expr... operands) {\n\t\t\tsuper(EXPR_sub, operands);\n\t\t}\n\n\t\t@Override\n\t\tpublic Expr clone(SyntacticItem[] operands) {\n\t\t\tif (operands.length <= 1) {\n\t\t\t\tthrow new IllegalArgumentException(\"invalid number of operands\");\n\t\t\t}\n\t\t\treturn new Subtraction(ArrayUtils.toArray(Expr.class, operands));\n\t\t}\n\n\t\t@Override\n\t\tprotected String getOperatorString() {\n\t\t\treturn \" - \";\n\t\t}\n\t}\n\n\t/**\n\t * Represents an arithmetic <i>multiplication expression</i> of the form\n\t * \"<code>e1 * ... * en</code>\" where <code>e1</code> ...\n\t * <code>en</code> are the <i>operand expressions</i>.\n\t *\n\t * @author David J. Pearce\n\t *\n\t */\n\tpublic static class Multiplication extends InfixOperator {\n\t\tpublic Multiplication(Expr... operands) {\n\t\t\tsuper(EXPR_mul, operands);\n\t\t}\n\n\t\t@Override\n\t\tpublic Expr clone(SyntacticItem[] operands) {\n\t\t\tif (operands.length <= 1) {\n\t\t\t\tthrow new IllegalArgumentException(\"invalid number of operands\");\n\t\t\t}\n\t\t\treturn new Multiplication(ArrayUtils.toArray(Expr.class, operands));\n\t\t}\n\n\t\t@Override\n\t\tprotected String getOperatorString() {\n\t\t\treturn \" * \";\n\t\t}\n\t}\n\n\t/**\n\t * Represents an arithmetic <i>division expression</i> of the form\n\t * \"<code>e1 / ... / en</code>\" where <code>e1</code> ...\n\t * <code>en</code> are the <i>operand expressions</i>.\n\t *\n\t * @author David J. Pearce\n\t *\n\t */\n\tpublic static class Division extends InfixOperator {\n\t\tpublic Division(Expr... operands) {\n\t\t\tsuper(EXPR_div, operands);\n\t\t}\n\n\t\t@Override\n\t\tpublic Expr clone(SyntacticItem[] operands) {\n\t\t\tif (operands.length <= 1) {\n\t\t\t\tthrow new IllegalArgumentException(\"invalid number of operands\");\n\t\t\t}\n\t\t\treturn new Division(ArrayUtils.toArray(Expr.class, operands));\n\t\t}\n\n\t\t@Override\n\t\tprotected String getOperatorString() {\n\t\t\treturn \" / \";\n\t\t}\n\t}\n\n\t/**\n\t * Represents an arithmetic <i>remainder expression</i> of the form\n\t * \"<code>e1 / ... / en</code>\" where <code>e1</code> ...\n\t * <code>en</code> are the <i>operand expressions</i>.\n\t *\n\t * @author David J. Pearce\n\t *\n\t */\n\tpublic static class Remainder extends InfixOperator {\n\t\tpublic Remainder(Expr... operands) {\n\t\t\tsuper(EXPR_rem, operands);\n\t\t}\n\n\t\t@Override\n\t\tpublic Expr clone(SyntacticItem[] operands) {\n\t\t\tif (operands.length <= 1) {\n\t\t\t\tthrow new IllegalArgumentException(\"invalid number of operands\");\n\t\t\t}\n\t\t\treturn new Remainder(ArrayUtils.toArray(Expr.class, operands));\n\t\t}\n\n\t\t@Override\n\t\tprotected String getOperatorString() {\n\t\t\treturn \" % \";\n\t\t}\n\t}\n\n\t/**\n\t * Represents an arithmetic <i>negation expression</i> of the form\n\t * \"<code>-e</code>\" where <code>e</code> is the <i>operand\n\t * expression</i>.\n\t *\n\t * @author David J. Pearce\n\t *\n\t */\n\tpublic static class Negation extends Operator {\n\t\tpublic Negation(Expr operand) {\n\t\t\tsuper(EXPR_neg, operand);\n\t\t}\n\n\t\tpublic Expr getOperand() {\n\t\t\treturn get(0);\n\t\t}\n\n\t\t@Override\n\t\tpublic Expr clone(SyntacticItem[] operands) {\n\t\t\tif (operands.length != 1) {\n\t\t\t\tthrow new IllegalArgumentException(\"invalid number of operands\");\n\t\t\t}\n\t\t\treturn new Negation((Expr) operands[0]);\n\t\t}\n\n\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\treturn \"-\" + getOperand();\n\t\t}\n\t}\n\n\t// =========================================================================\n\t// Reference Expressions\n\t// =========================================================================\n\tpublic static class Dereference extends Operator {\n\t\tpublic Dereference(Expr operand) {\n\t\t\tsuper(EXPR_deref, operand);\n\t\t}\n\n\t\tpublic Expr getOperand() {\n\t\t\treturn get(0);\n\t\t}\n\n\t\t@Override\n\t\tpublic Expr clone(SyntacticItem[] operands) {\n\t\t\tif (operands.length != 1) {\n\t\t\t\tthrow new IllegalArgumentException(\"invalid number of operands\");\n\t\t\t}\n\t\t\treturn new Dereference((Expr) operands[0]);\n\t\t}\n\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\treturn \"*\" + getOperand();\n\t\t}\n\t}\n\n\t// =========================================================================\n\t// Array Expressions\n\t// =========================================================================\n\n\t/**\n\t * Represents an <i>array access expression</i> of the form\n\t * \"<code>arr[e]</code>\" where <code>arr</code> is the <i>source\n\t * array</i> and <code>e</code> the <i>subscript expression</i>. This\n\t * returns the value held in the element determined by <code>e</code>.\n\t *\n\t * @author David J. Pearce\n\t *\n\t */\n\tpublic static class ArrayAccess extends Expr.Operator {\n\t\tpublic ArrayAccess(Expr src, Expr index) {\n\t\t\tsuper(EXPR_arridx, src, index);\n\t\t}\n\n\t\tpublic Expr getSource() {\n\t\t\treturn get(0);\n\t\t}\n\n\t\tpublic Expr getSubscript() {\n\t\t\treturn get(1);\n\t\t}\n\n\t\t@Override\n\t\tpublic ArrayAccess clone(SyntacticItem[] operands) {\n\t\t\treturn new ArrayAccess((Expr) operands[0], (Expr) operands[1]);\n\t\t}\n\t}\n\n\t/**\n\t * Represents an <i>array update expression</i> of the form\n\t * \"<code>arr[e1:=e2]</code>\" where <code>arr</code> is the <i>source\n\t * array</i>, <code>e1</code> the <i>subscript expression</i> and\n\t * <code>e2</code> is the value expression. This returns a new array\n\t * which is equivalent to <code>arr</code> but where the element\n\t * determined by <code>e1</code> has the value resulting from\n\t * <code>e2</code>.\n\t *\n\t * @author David J. Pearce\n\t *\n\t */\n\tpublic static class ArrayUpdate extends Expr.Operator {\n\t\tpublic ArrayUpdate(Expr src, Expr index, Expr value) {\n\t\t\tsuper(EXPR_arrupdt, src, index, value);\n\t\t}\n\n\t\tpublic Expr getSource() {\n\t\t\treturn get(0);\n\t\t}\n\n\t\tpublic Expr getSubscript() {\n\t\t\treturn get(1);\n\t\t}\n\n\t\tpublic Expr getValue() {\n\t\t\treturn get(2);\n\t\t}\n\n\t\t@Override\n\t\tpublic ArrayUpdate clone(SyntacticItem[] operands) {\n\t\t\treturn new ArrayUpdate((Expr) operands[0], (Expr) operands[1], (Expr) operands[2]);\n\t\t}\n\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\treturn getSource() + \"[\" + getSubscript() + \":=\" + getValue() + \"]\";\n\t\t}\n\t}\n\n\t/**\n\t * Represents an <i>array initialiser expression</i> of the form\n\t * \"<code>[e1,...,en]</code>\" where <code>e1</code> ... <code>en</code>\n\t * are the <i>initialiser expressions</i>. Thus returns a new array made\n\t * up from those values resulting from the initialiser expressions.\n\t *\n\t * @author David J. Pearce\n\t *\n\t */\n\tpublic static class ArrayInitialiser extends Expr.Operator {\n\t\tpublic ArrayInitialiser(Expr... elements) {\n\t\t\tsuper(EXPR_arrinit, elements);\n\t\t}\n\n\t\t@Override\n\t\tpublic ArrayInitialiser clone(SyntacticItem[] operands) {\n\t\t\treturn new ArrayInitialiser(ArrayUtils.toArray(Expr.class, operands));\n\t\t}\n\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\treturn Arrays.toString(getAll());\n\t\t}\n\t}\n\n\t/**\n\t * Represents an <i>array generator expression</i> of the form\n\t * \"<code>[e1;e2]</code>\" where <code>e1</code> is the <i>element\n\t * expression</i> and <code>e2</code> is the <i>length expression</i>.\n\t * This returns a new array whose length is determined by\n\t * <code>e2</code> and where every element has contains the value\n\t * determined by <code>e1</code>.\n\t *\n\t * @author David J. Pearce\n\t *\n\t */\n\tpublic static class ArrayGenerator extends Expr.Operator {\n\t\tpublic ArrayGenerator(Expr value, Expr length) {\n\t\t\tsuper(EXPR_arrgen, value, length);\n\t\t}\n\n\t\tpublic Expr getValue() {\n\t\t\treturn get(0);\n\t\t}\n\n\t\tpublic Expr getLength() {\n\t\t\treturn get(1);\n\t\t}\n\n\t\t@Override\n\t\tpublic ArrayGenerator clone(SyntacticItem[] operands) {\n\t\t\treturn new ArrayGenerator((Expr) operands[0], (Expr) operands[1]);\n\t\t}\n\t}\n\n\t/**\n\t * Represents an <i>array length expression</i> of the form\n\t * \"<code>|arr|</code>\" where <code>arr</code> is the <i>source\n\t * array</i>. This simply returns the length of array <code>arr</code>.\n\t * <code>e</code>.\n\t *\n\t * @author David J. Pearce\n\t *\n\t */\n\tpublic static class ArrayLength extends Expr.Operator {\n\t\tpublic ArrayLength(Expr src) {\n\t\t\tsuper(EXPR_arrlen, src);\n\t\t}\n\n\t\tpublic Expr getSource() {\n\t\t\treturn get(0);\n\t\t}\n\n\t\t@Override\n\t\tpublic ArrayLength clone(SyntacticItem[] operands) {\n\t\t\treturn new ArrayLength((Expr) operands[0]);\n\t\t}\n\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\treturn \"|\" + getSource() + \"|\";\n\t\t}\n\t}\n\n\t// =========================================================================\n\t// Record Expressions\n\t// =========================================================================\n\n\t/**\n\t * Represents a <i>record access expression</i> of the form\n\t * \"<code>rec.f</code>\" where <code>rec</code> is the <i>source record</i>\n\t * and <code>f</code> is the <i>field</i>.\n\t *\n\t * @author David J. Pearce\n\t *\n\t */\n\tpublic static class RecordAccess extends AbstractSyntacticItem implements Expr {\n\t\tpublic RecordAccess(Expr lhs, Identifier rhs) {\n\t\t\tsuper(EXPR_recfield, lhs, rhs);\n\t\t}\n\n\t\tpublic Expr getSource() {\n\t\t\treturn (Expr) get(0);\n\t\t}\n\n\t\tpublic Identifier getField() {\n\t\t\treturn (Identifier) get(1);\n\t\t}\n\n\t\t@Override\n\t\tpublic RecordAccess clone(SyntacticItem[] operands) {\n\t\t\treturn new RecordAccess((Expr) operands[0], (Identifier) operands[1]);\n\t\t}\n\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\treturn getSource() + \".\" + getField();\n\t\t}\n\t}\n\n\t/**\n\t * Represents a <i>record initialiser</i> expression of the form\n\t * <code>{ f1: e1, ..., fn: en }</code> where <code>f1: e1</code> ...\n\t * <code>fn: en</code> are <i>field initialisers</code>. This returns a\n\t * new record where each field holds the value resulting from its\n\t * corresponding expression.\n\t *\n\t * @author David J. Pearce\n\t *\n\t */\n\tpublic static class RecordInitialiser extends AbstractSyntacticItem implements Expr {\n\t\tpublic RecordInitialiser(Pair<Identifier, Expr>... fields) {\n\t\t\tsuper(EXPR_recinit, fields);\n\t\t}\n\n\t\tpublic Pair<Identifier, Expr>[] getFields() {\n\t\t\treturn ArrayUtils.toArray(Pair.class, getAll());\n\t\t}\n\n\t\t@Override\n\t\tpublic RecordInitialiser clone(SyntacticItem[] operands) {\n\t\t\treturn new RecordInitialiser(ArrayUtils.toArray(Pair.class, operands));\n\t\t}\n\t}\n\n\t/**\n\t * Represents a <i>record update expression</i> of the form\n\t * \"<code>rec[f:=e]</code>\" where <code>rec</code> is the <i>source\n\t * record</i>, <code>f</code> is the <i>field</i> and <code>e</code> is\n\t * the <i>value expression</i>. This returns a new record which is\n\t * equivalent to <code>rec</code> but where the element in field\n\t * <code>f</code> has the value resulting from <code>e</code>.\n\t *\n\t * @author David J. Pearce\n\t *\n\t */\n\tpublic static class RecordUpdate extends AbstractSyntacticItem implements Expr {\n\t\tpublic RecordUpdate(Expr lhs, Identifier mhs, Expr rhs) {\n\t\t\tsuper(EXPR_recupdt, lhs, mhs, rhs);\n\t\t}\n\n\t\tpublic Expr getSource() {\n\t\t\treturn (Expr) get(0);\n\t\t}\n\n\t\tpublic Identifier getField() {\n\t\t\treturn (Identifier) get(1);\n\t\t}\n\n\t\tpublic Expr getValue() {\n\t\t\treturn (Expr) get(2);\n\t\t}\n\n\t\t@Override\n\t\tpublic RecordUpdate clone(SyntacticItem[] operands) {\n\t\t\treturn new RecordUpdate((Expr) operands[0], (Identifier) operands[1], (Expr) operands[2]);\n\t\t}\n\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\treturn getSource() + \"{\" + getField() + \":=\" + getValue() + \"}\";\n\t\t}\n\t}\n}",
"public static class FieldDeclaration extends AbstractSyntacticItem {\n\tpublic FieldDeclaration(Type type, Identifier name) {\n\t\tsuper(STMT_vardecl, type, name);\n\t}\n\n\tpublic Type getType() {\n\t\treturn (Type) get(0);\n\t}\n\n\tpublic Identifier getVariableName() {\n\t\treturn (Identifier) get(1);\n\t}\n\n\t@Override\n\tpublic FieldDeclaration clone(SyntacticItem[] operands) {\n\t\treturn new FieldDeclaration((Type) operands[0], (Identifier) operands[1]);\n\t}\n}",
"public interface NameResolver {\n\n\t/**\n\t * <p>\n\t * Resolve a given name which occurs at some position in a compilation unit\n\t * into exactly one named declaration. Depending on the context, we may be\n\t * looking for a specific kind of declaration. For example, for a variable\n\t * declaration, we may be looking for the corresponding type declaration.\n\t * </p>\n\t * <p>\n\t * Observe that this method is expecting to find <b>exactly</b> one\n\t * corresponding declaration. If it find no such matches or if it finds more\n\t * than one match, then a corresponding error will be reported.\n\t * </p>\n\t * <p>\n\t * Resolution is determined by the context in which a given name is used.\n\t * For example, what imports are active in the enclosing file, as in the\n\t * following:\n\t * </p>\n\t *\n\t * <pre>\n\t * import std.*\n\t *\n\t * type nat is integer.uint\n\t * </pre>\n\t *\n\t * <p>\n\t * In resolving the name <code>integer.uint</code>, the resolver will\n\t * examine the package <code>std</code> to see whether a compilation unit\n\t * named \"integer\" exists. If so, it will then resolve the name\n\t * <code>integer.uint</code> to <code>std.integer.uint</code>.\n\t * </p>\n\t *\n\t * @param name\n\t * The name to be resolved in the given context.\n\t * @param kind\n\t * The kind of declaration we are looking for, which can simply\n\t * be <code>Declaration.Named</code> in the case we are looking\n\t * for any kind of declaration.\n\t * @return\n\t */\n\tpublic <T extends Declaration> T resolveExactly(Name name, Class<T> kind) throws ResolutionError;\n\n\t/**\n\t * <p>\n\t * Resolve a given name which occurs at some position in a compilation unit\n\t * into one or more named declarations. Depending on the context, we may be\n\t * looking for a specific kind of declaration. For example, for a function\n\t * invocation expression, we are looking for the corresponding function\n\t * declaration.\n\t * </p>\n\t * <p>\n\t * Resolution is determined by the context in which a given name is used.\n\t * For example, what imports are active in the enclosing file, as in the\n\t * following:\n\t * </p>\n\t *\n\t * <pre>\n\t * import std.*\n\t *\n\t * type nat is integer.uint\n\t * </pre>\n\t *\n\t * <p>\n\t * In resolving the name <code>integer.uint</code>, the resolver will\n\t * examine the package <code>std</code> to see whether a compilation unit\n\t * named \"integer\" exists. If so, it will then resolve the name\n\t * <code>integer.uint</code> to <code>std.integer.uint</code>.\n\t * </p>\n\t *\n\t * @param name\n\t * The name to be resolved in the given context.\n\t * @param kind\n\t * The kind of declaration we are looking for, which can simply\n\t * be <code>Declaration.Named</code> in the case we are looking\n\t * for any kind of declaration.\n\t * @return\n\t */\n\tpublic <T extends Declaration> List<T> resolveAll(Name name, Class<T> kind) throws ResolutionError;\n\n\t/**\n\t * A resolution error occurs when a given name cannot be successfully\n\t * resolved. Such errors are typically propagated out of the current\n\t * processing method to some kind of generic handler (e.g. for reporting\n\t * errors).\n\t *\n\t * @author David J. Pearce\n\t *\n\t */\n\tpublic static class ResolutionError extends Exception {\n\t\t/**\n\t\t *\n\t\t */\n\t\tprivate static final long serialVersionUID = 1L;\n\t\tprivate final Name name;\n\n\t\tpublic ResolutionError(Name name, String message) {\n\t\t\tsuper(message);\n\t\t\tif (name == null) {\n\t\t\t\tthrow new IllegalArgumentException(\"name is null\");\n\t\t\t}\n\t\t\tthis.name = name;\n\t\t}\n\n\t\t/**\n\t\t * Get the name being resolved that lead to this error.\n\t\t *\n\t\t * @return\n\t\t */\n\t\tpublic Name getName() {\n\t\t\treturn name;\n\t\t}\n\t}\n\n\t/**\n\t * This error is reported in the case that no matching name can be\n\t * identified.\n\t *\n\t * @author David J. Pearce\n\t *\n\t */\n\tpublic static class NameNotFoundError extends ResolutionError {\n\t\t/**\n\t\t *\n\t\t */\n\t\tprivate static final long serialVersionUID = 1L;\n\n\t\tpublic NameNotFoundError(Name name) {\n\t\t\tsuper(name, \"name \\\"\" + name + \"\\\" not found\");\n\t\t}\n\t}\n\n\t/**\n\t * This error is reported in the case that exactly one match was sought, but\n\t * more than one match was found.\n\t *\n\t * @author David J. Pearce\n\t *\n\t */\n\tpublic static class AmbiguousNameError extends ResolutionError {\n\t\t/**\n\t\t *\n\t\t */\n\t\tprivate static final long serialVersionUID = 1L;\n\n\t\tpublic AmbiguousNameError(Name name) {\n\t\t\tsuper(name, \"name \\\"\" + name + \"\\\" is ambiguous\");\n\t\t}\n\t}\n}",
"public static class ResolutionError extends Exception {\n\t/**\n\t *\n\t */\n\tprivate static final long serialVersionUID = 1L;\n\tprivate final Name name;\n\n\tpublic ResolutionError(Name name, String message) {\n\t\tsuper(message);\n\t\tif (name == null) {\n\t\t\tthrow new IllegalArgumentException(\"name is null\");\n\t\t}\n\t\tthis.name = name;\n\t}\n\n\t/**\n\t * Get the name being resolved that lead to this error.\n\t *\n\t * @return\n\t */\n\tpublic Name getName() {\n\t\treturn name;\n\t}\n}",
"public class WyalFile extends AbstractCompilationUnit<WyalFile> {\n\n\t// =========================================================================\n\t// Content Type\n\t// =========================================================================\n\n\tpublic static final Content.Type<WyalFile> ContentType = new Content.Type<WyalFile>() {\n\t\tpublic Path.Entry<WyalFile> accept(Path.Entry<?> e) {\n\t\t\tif (e.contentType() == this) {\n\t\t\t\treturn (Path.Entry<WyalFile>) e;\n\t\t\t}\n\t\t\treturn null;\n\t\t}\n\n\t\t@Override\n\t\tpublic WyalFile read(Path.Entry<WyalFile> e, InputStream input) throws IOException {\n\t\t\tWyalFileLexer wlexer = new WyalFileLexer(e);\n\t\t\tWyalFileParser wfr = new WyalFileParser(new WyalFile(e), wlexer.scan());\n\t\t\treturn wfr.read();\n\t\t}\n\n\t\t@Override\n\t\tpublic void write(OutputStream output, WyalFile module) throws IOException {\n\t\t\tnew WyalFilePrinter(output).write(module);\n\t\t}\n\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\treturn \"Content-Type: wyal\";\n\t\t}\n\n\t\t@Override\n\t\tpublic String getSuffix() {\n\t\t\treturn \"wyal\";\n\t\t}\n\t};\n\n\tpublic static final Content.Type<WyalFile> BinaryContentType = new Content.Type<WyalFile>() {\n\t\tpublic Path.Entry<WyalFile> accept(Path.Entry<?> e) {\n\t\t\tif (e.contentType() == this) {\n\t\t\t\treturn (Path.Entry<WyalFile>) e;\n\t\t\t}\n\t\t\treturn null;\n\t\t}\n\n\t\t@Override\n\t\tpublic WyalFile read(Path.Entry<WyalFile> e, InputStream input) throws IOException {\n\t\t\tthrow new RuntimeException(\"Implement me!\");\n\t\t}\n\n\t\t@Override\n\t\tpublic void write(OutputStream output, WyalFile module) throws IOException {\n\t\t\t// FIXME: this is screwed\n\t\t\t//throw new RuntimeException(\"Implement me!\");\n\t\t}\n\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\treturn \"Content-Type: wycs\";\n\t\t}\n\n\t\t@Override\n\t\tpublic String getSuffix() {\n\t\t\treturn \"wycs\";\n\t\t}\n\t};\n\n\t// =========================================================================\n\t// Item Kinds\n\t// =========================================================================\n\t// DECLARATIONS: 00010000 (16) -- 00011111 (31)\n\tpublic static final int DECL_mask = 0b00010000;\n\tpublic static final int DECL_linecomment = DECL_mask + 0;\n\tpublic static final int DECL_blkcomment = DECL_mask + 1;\n\tpublic static final int DECL_import = DECL_mask + 2;\n\tpublic static final int DECL_assert = DECL_mask + 3;\n\tpublic static final int DECL_type = DECL_mask + 4;\n\tpublic static final int DECL_fun = DECL_mask + 5;\n\tpublic static final int DECL_macro = DECL_mask + 6;\n\t// ERRORS\n\tpublic static final int ERR_verify = DECL_mask + 7;\n\t// TYPES: 00100000 (32) -- 00111111 (63)\n\tpublic static final int TYPE_mask = 0b000100000;\n\tpublic static final int TYPE_void = TYPE_mask + 0;\n\tpublic static final int TYPE_any = TYPE_mask + 1;\n\tpublic static final int TYPE_null = TYPE_mask + 2;\n\tpublic static final int TYPE_bool = TYPE_mask + 3;\n\tpublic static final int TYPE_int = TYPE_mask + 4;\n\tpublic static final int TYPE_nom = TYPE_mask + 5;\n\tpublic static final int TYPE_ref = TYPE_mask + 6;\n\tpublic static final int TYPE_arr = TYPE_mask + 8;\n\tpublic static final int TYPE_rec = TYPE_mask + 9;\n\tpublic static final int TYPE_fun = TYPE_mask + 10;\n\tpublic static final int TYPE_meth = TYPE_mask + 11;\n\tpublic static final int TYPE_property = TYPE_mask + 12;\n\tpublic static final int TYPE_inv = TYPE_mask + 13;\n\tpublic static final int TYPE_or = TYPE_mask + 14;\n\tpublic static final int TYPE_and = TYPE_mask + 15;\n\tpublic static final int TYPE_not = TYPE_mask + 16;\n\tpublic static final int TYPE_byte = TYPE_mask + 17;\n\t// STATEMENTS: 01000000 (64) -- 001011111 (95)\n\tpublic static final int STMT_mask = 0b01000000;\n\tpublic static final int STMT_block = STMT_mask + 0;\n\tpublic static final int STMT_vardecl = STMT_mask + 1;\n\tpublic static final int STMT_ifthen = STMT_mask + 2;\n\tpublic static final int STMT_caseof = STMT_mask + 3;\n\tpublic static final int STMT_exists = STMT_mask + 4;\n\tpublic static final int STMT_forall = STMT_mask + 5;\n\t// EXPRESSIONS: 01100000 (96) -- 10011111 (159)\n\tpublic static final int EXPR_mask = 0b01100000;\n\tpublic static final int EXPR_varcopy = EXPR_mask + 0;\n\tpublic static final int EXPR_varmove = EXPR_mask + 1;\n\tpublic static final int EXPR_staticvar = EXPR_mask + 2;\n\tpublic static final int EXPR_const = EXPR_mask + 3;\n\tpublic static final int EXPR_cast = EXPR_mask + 4;\n\tpublic static final int EXPR_invoke = EXPR_mask + 5;\n\tpublic static final int EXPR_qualifiedinvoke = EXPR_mask + 6;\n\tpublic static final int EXPR_indirectinvoke = EXPR_mask + 7;\n\t// LOGICAL\n\tpublic static final int EXPR_not = EXPR_mask + 8;\n\tpublic static final int EXPR_and = EXPR_mask + 9;\n\tpublic static final int EXPR_or = EXPR_mask + 10;\n\tpublic static final int EXPR_implies = EXPR_mask + 11;\n\tpublic static final int EXPR_iff = EXPR_mask + 12;\n\tpublic static final int EXPR_exists = EXPR_mask + 13;\n\tpublic static final int EXPR_forall = EXPR_mask + 14;\n\t// COMPARATORS\n\tpublic static final int EXPR_eq = EXPR_mask + 16;\n\tpublic static final int EXPR_neq = EXPR_mask + 17;\n\tpublic static final int EXPR_lt = EXPR_mask + 18;\n\tpublic static final int EXPR_lteq = EXPR_mask + 19;\n\tpublic static final int EXPR_gt = EXPR_mask + 20;\n\tpublic static final int EXPR_gteq = EXPR_mask + 21;\n\tpublic static final int EXPR_is = EXPR_mask + 22;\n\t// ARITHMETIC\n\tpublic static final int EXPR_neg = EXPR_mask + 24;\n\tpublic static final int EXPR_add = EXPR_mask + 25;\n\tpublic static final int EXPR_sub = EXPR_mask + 26;\n\tpublic static final int EXPR_mul = EXPR_mask + 27;\n\tpublic static final int EXPR_div = EXPR_mask + 28;\n\tpublic static final int EXPR_rem = EXPR_mask + 29;\n\t// BITWISE\n\tpublic static final int EXPR_bitwisenot = EXPR_mask + 32;\n\tpublic static final int EXPR_bitwiseand = EXPR_mask + 33;\n\tpublic static final int EXPR_bitwiseor = EXPR_mask + 34;\n\tpublic static final int EXPR_bitwisexor = EXPR_mask + 35;\n\tpublic static final int EXPR_bitwiseshl = EXPR_mask + 36;\n\tpublic static final int EXPR_bitwiseshr = EXPR_mask + 37;\n\t// REFERENCES\n\tpublic static final int EXPR_deref = EXPR_mask + 40;\n\tpublic static final int EXPR_new = EXPR_mask + 41;\n\tpublic static final int EXPR_qualifiedlambda = EXPR_mask + 42;\n\tpublic static final int EXPR_lambda = EXPR_mask + 43;\n\t// RECORDS\n\tpublic static final int EXPR_recfield = EXPR_mask + 48;\n\tpublic static final int EXPR_recupdt = EXPR_mask + 49;\n\tpublic static final int EXPR_recinit = EXPR_mask + 50;\n\t// ARRAYS\n\tpublic static final int EXPR_arridx = EXPR_mask + 56;\n\tpublic static final int EXPR_arrlen = EXPR_mask + 57;\n\tpublic static final int EXPR_arrupdt = EXPR_mask + 58;\n\tpublic static final int EXPR_arrgen = EXPR_mask + 59;\n\tpublic static final int EXPR_arrinit = EXPR_mask + 60;\n\tpublic static final int EXPR_arrrange = EXPR_mask + 61;\n\n\t// =========================================================================\n\t// Constructors\n\t// =========================================================================\n\n\tpublic WyalFile(Path.Entry<WyalFile> entry) {\n\t\tsuper(entry);\n\t}\n\n\t@Override\n\tpublic Path.Entry<WyalFile> getEntry() {\n\t\treturn entry;\n\t}\n\n\t@Override\n\tpublic SyntacticHeap getParent() {\n\t\treturn null;\n\t}\n\n\t// ============================================================\n\t// Fundamental Items\n\t// ============================================================\n\n\n\t// ============================================================\n\t// Declarations\n\t// ============================================================\n\tpublic static interface Declaration extends CompilationUnit.Declaration {\n\n\t\tpublic static class Assert extends AbstractSyntacticItem implements Declaration {\n\t\t\tprivate String message;\n\t\t\tprivate SyntacticItem context;\n\n\t\t\tpublic Assert(Stmt.Block body, String message, SyntacticItem context) {\n\t\t\t\tsuper(DECL_assert, body);\n\t\t\t\tthis.message = message;\n\t\t\t\tthis.context = context;\n\t\t\t}\n\n\t\t\tpublic Stmt.Block getBody() {\n\t\t\t\treturn (Stmt.Block) get(0);\n\t\t\t}\n\n\t\t\tpublic SyntacticItem getContext() {\n\t\t\t\treturn context;\n\t\t\t}\n\n\t\t\tpublic String getMessage() {\n\t\t\t\treturn message;\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Assert clone(SyntacticItem[] operands) {\n\t\t\t\treturn new Assert((Stmt.Block) operands[0], message, context);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic String toString() {\n\t\t\t\treturn \"assert \" + getBody();\n\t\t\t}\n\t\t}\n\n\t\tpublic static interface Named extends Declaration {\n\n\t\t\tpublic Name getName();\n\n\t\t\tpublic Tuple<VariableDeclaration> getParameters();\n\n\t\t\tpublic static abstract class FunctionOrMacro extends AbstractSyntacticItem implements Named {\n\t\t\t\tpublic FunctionOrMacro(Name name, Tuple<VariableDeclaration> parameters, Stmt.Block body) {\n\t\t\t\t\tsuper(DECL_macro, name, parameters, body);\n\t\t\t\t}\n\n\t\t\t\tpublic FunctionOrMacro(Name name, Tuple<VariableDeclaration> parameters,\n\t\t\t\t\t\tTuple<VariableDeclaration> returns) {\n\t\t\t\t\tsuper(DECL_fun, name, parameters, returns);\n\t\t\t\t}\n\n\t\t\t\t@Override\n\t\t\t\tpublic Name getName() {\n\t\t\t\t\treturn (Name) get(0);\n\t\t\t\t}\n\n\t\t\t\t@Override\n\t\t\t\tpublic Tuple<VariableDeclaration> getParameters() {\n\t\t\t\t\treturn (Tuple) get(1);\n\t\t\t\t}\n\n\t\t\t\tpublic abstract WyalFile.Type.FunctionOrMethodOrProperty getSignatureType();\n\t\t\t}\n\n\t\t\t// ============================================================\n\t\t\t// Function Declaration\n\t\t\t// ============================================================\n\t\t\tpublic static class Function extends FunctionOrMacro {\n\n\t\t\t\tpublic Function(Name name, VariableDeclaration[] parameters, VariableDeclaration[] returns) {\n\t\t\t\t\tsuper(name, new Tuple(parameters), new Tuple(returns));\n\t\t\t\t}\n\n\t\t\t\tpublic Function(Name name, Tuple<VariableDeclaration> parameters,\n\t\t\t\t\t\tTuple<VariableDeclaration> returns) {\n\t\t\t\t\tsuper(name, parameters, returns);\n\t\t\t\t}\n\n\t\t\t\tpublic Tuple<VariableDeclaration> getReturns() {\n\t\t\t\t\treturn (Tuple<VariableDeclaration>) get(2);\n\t\t\t\t}\n\n\t\t\t\t@Override\n\t\t\t\tpublic WyalFile.Type.Function getSignatureType() {\n\t\t\t\t\treturn new WyalFile.Type.Function(projectTypes(getParameters()), projectTypes(getReturns()));\n\t\t\t\t}\n\n\t\t\t\t@Override\n\t\t\t\tpublic Function clone(SyntacticItem[] operands) {\n\t\t\t\t\treturn new Function((Name) operands[0], (Tuple) operands[1], (Tuple) operands[2]);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// ============================================================\n\t\t\t// Macro Declaration\n\t\t\t// ============================================================\n\t\t\tpublic static class Macro extends FunctionOrMacro {\n\t\t\t\tpublic Macro(Name name, VariableDeclaration[] parameters, Stmt.Block body) {\n\t\t\t\t\tsuper(name, new Tuple<>(parameters), body);\n\t\t\t\t}\n\n\t\t\t\tprivate Macro(Name name, Tuple<VariableDeclaration> parameters, Stmt.Block body) {\n\t\t\t\t\tsuper(name, parameters, body);\n\t\t\t\t}\n\n\t\t\t\tpublic Stmt.Block getBody() {\n\t\t\t\t\treturn (Stmt.Block) get(2);\n\t\t\t\t}\n\n\t\t\t\t@Override\n\t\t\t\tpublic WyalFile.Type.Property getSignatureType() {\n\t\t\t\t\treturn new WyalFile.Type.Property(projectTypes(getParameters()));\n\t\t\t\t}\n\n\t\t\t\t@Override\n\t\t\t\tpublic Macro clone(SyntacticItem[] operands) {\n\t\t\t\t\treturn new Macro((Name) operands[0], (Tuple<VariableDeclaration>) operands[1],\n\t\t\t\t\t\t\t(Stmt.Block) operands[2]);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// ============================================================\n\t\t\t// Type Declaration\n\t\t\t// ============================================================\n\t\t\tpublic static class Type extends AbstractSyntacticItem implements Named {\n\n\t\t\t\tpublic Type(Name name, VariableDeclaration vardecl, Stmt.Block... invariant) {\n\t\t\t\t\tsuper(DECL_type, name, vardecl, new Tuple(invariant));\n\t\t\t\t}\n\n\t\t\t\tprivate Type(Name name, VariableDeclaration vardecl, Tuple<Stmt.Block> invariant) {\n\t\t\t\t\tsuper(DECL_type, name, vardecl, invariant);\n\t\t\t\t}\n\n\t\t\t\t@Override\n\t\t\t\tpublic Name getName() {\n\t\t\t\t\treturn (Name) get(0);\n\t\t\t\t}\n\n\t\t\t\tpublic VariableDeclaration getVariableDeclaration() {\n\t\t\t\t\treturn (VariableDeclaration) get(1);\n\t\t\t\t}\n\n\t\t\t\tpublic Tuple<Stmt.Block> getInvariant() {\n\t\t\t\t\treturn (Tuple) get(2);\n\t\t\t\t}\n\n\t\t\t\t@Override\n\t\t\t\tpublic Type clone(SyntacticItem[] operands) {\n\t\t\t\t\treturn new Type((Name) operands[0], (VariableDeclaration) operands[1], (Tuple) operands[2]);\n\t\t\t\t}\n\n\t\t\t\t@Override\n\t\t\t\tpublic Tuple<VariableDeclaration> getParameters() {\n\t\t\t\t\treturn new Tuple<>(getVariableDeclaration());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// ============================================================\n\t// Types\n\t// ============================================================\n\tpublic static interface Type extends SyntacticItem {\n\n\t\tpublic static final Any Any = new Any();\n\t\tpublic static final Void Void = new Void();\n\t\tpublic static final Bool Bool = new Bool();\n\t\tpublic static final Int Int = new Int();\n\t\tpublic static final Null Null = new Null();\n\n\t\tpublic interface Primitive extends Type {\n\n\t\t}\n\n\t\tpublic static abstract class Atom extends AbstractSyntacticItem implements Type {\n\t\t\tpublic Atom(int opcode) {\n\t\t\t\tsuper(opcode);\n\t\t\t}\n\n\t\t\tpublic Atom(int opcode, SyntacticItem item) {\n\t\t\t\tsuper(opcode, item);\n\t\t\t}\n\n\t\t\tpublic Atom(int opcode, SyntacticItem first, SyntacticItem second) {\n\t\t\t\tsuper(opcode, first, second);\n\t\t\t}\n\n\t\t\tpublic Atom(int opcode, SyntacticItem[] items) {\n\t\t\t\tsuper(opcode, items);\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * The type <code>any</code> represents the type whose variables may hold\n\t\t * any possible value. <b>NOTE:</b> the any type is top in the type lattice.\n\t\t *\n\t\t * @author David J. Pearce\n\t\t *\n\t\t */\n\t\tpublic static class Any extends Atom implements Primitive {\n\t\t\tpublic Any() {\n\t\t\t\tsuper(TYPE_any);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Any clone(SyntacticItem[] operands) {\n\t\t\t\treturn new Any();\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic String toString() {\n\t\t\t\treturn \"any\";\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * A void type represents the type whose variables cannot exist! That is,\n\t\t * they cannot hold any possible value. Void is used to represent the return\n\t\t * type of a function which does not return anything. However, it is also\n\t\t * used to represent the element type of an empty list of set. <b>NOTE:</b>\n\t\t * the void type is a subtype of everything; that is, it is bottom in the\n\t\t * type lattice.\n\t\t *\n\t\t * @author David J. Pearce\n\t\t *\n\t\t */\n\t\tpublic static class Void extends Atom implements Primitive {\n\t\t\tpublic Void() {\n\t\t\t\tsuper(TYPE_void);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Void clone(SyntacticItem[] operands) {\n\t\t\t\treturn new Void();\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic String toString() {\n\t\t\t\treturn \"void\";\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * The null type is a special type which should be used to show the absence\n\t\t * of something. It is distinct from void, since variables can hold the\n\t\t * special <code>null</code> value (where as there is no special \"void\"\n\t\t * value). With all of the problems surrounding <code>null</code> and\n\t\t * <code>NullPointerException</code>s in languages like Java and C, it may\n\t\t * seem that this type should be avoided. However, it remains a very useful\n\t\t * abstraction to have around and, in Whiley, it is treated in a completely\n\t\t * safe manner (unlike e.g. Java).\n\t\t *\n\t\t * @author David J. Pearce\n\t\t *\n\t\t */\n\t\tpublic static class Null extends Atom implements Primitive {\n\t\t\tpublic Null() {\n\t\t\t\tsuper(TYPE_null);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Null clone(SyntacticItem[] operands) {\n\t\t\t\treturn new Null();\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic String toString() {\n\t\t\t\treturn \"null\";\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Represents the set of boolean values (i.e. true and false)\n\t\t * @author David J. Pearce\n\t\t *\n\t\t */\n\t\tpublic static class Bool extends Atom implements Primitive {\n\t\t\tpublic Bool() {\n\t\t\t\tsuper(TYPE_bool);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Bool clone(SyntacticItem[] operands) {\n\t\t\t\treturn new Bool();\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic String toString() {\n\t\t\t\treturn \"bool\";\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Represents a sequence of 8 bits. Note that, unlike many languages, there\n\t\t * is no representation associated with a byte. For example, to extract an\n\t\t * integer value from a byte, it must be explicitly decoded according to\n\t\t * some representation (e.g. two's compliment) using an auxillary function\n\t\t * (e.g. <code>Byte.toInt()</code>).\n\t\t *\n\t\t * @author David J. Pearce\n\t\t *\n\t\t */\n\t\tpublic static class Byte extends Atom implements Primitive {\n\t\t\tpublic Byte() {\n\t\t\t\tsuper(TYPE_byte);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Null clone(SyntacticItem[] operands) {\n\t\t\t\treturn new Null();\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic String toString() {\n\t\t\t\treturn \"byte\";\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Represents the set of (unbound) integer values. Since integer types in\n\t\t * Whiley are unbounded, there is no equivalent to Java's\n\t\t * <code>MIN_VALUE</code> and <code>MAX_VALUE</code> for <code>int</code>\n\t\t * types.\n\t\t *\n\t\t * @author David J. Pearce\n\t\t *\n\t\t */\n\t\tpublic static class Int extends Atom implements Primitive {\n\t\t\tpublic Int() {\n\t\t\t\tsuper(TYPE_int);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Int clone(SyntacticItem[] operands) {\n\t\t\t\treturn new Int();\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic String toString() {\n\t\t\t\treturn \"int\";\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Represents a list type, which is of the form:\n\t\t *\n\t\t * <pre>\n\t\t * ArrayType ::= Type '[' ']'\n\t\t * </pre>\n\t\t *\n\t\t * @return\n\t\t */\n\t\tpublic static class Array extends Atom {\n\t\t\tpublic Array(Type element) {\n\t\t\t\tsuper(TYPE_arr, element);\n\t\t\t}\n\n\t\t\tpublic Type getElement() {\n\t\t\t\treturn (Type) get(0);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Array clone(SyntacticItem[] operands) {\n\t\t\t\treturn new Array((Type) operands[0]);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic String toString() {\n\t\t\t\treturn \"(\" + getElement() + \")[]\";\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Parse a reference type, which is of the form:\n\t\t *\n\t\t * <pre>\n\t\t * ReferenceType ::= '&' Type\n\t\t * </pre>\n\t\t *\n\t\t * @return\n\t\t */\n\t\tpublic static class Reference extends Atom {\n\t\t\tpublic Reference(Type element, Identifier lifetime) {\n\t\t\t\tsuper(TYPE_ref, element, lifetime);\n\t\t\t}\n\n\t\t\tpublic Type getElement() {\n\t\t\t\treturn (Type) get(0);\n\t\t\t}\n\t\t\tpublic Identifier getLifetime() {\n\t\t\t\treturn (Identifier) get(1);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Reference clone(SyntacticItem[] operands) {\n\t\t\t\treturn new Reference((Type) operands[0], (Identifier) operands[1]);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic String toString() {\n\t\t\t\tIdentifier lifetime = getLifetime();\n\t\t\t\tif (lifetime != null) {\n\t\t\t\t\treturn \"&(\" + getElement() + \")\";\n\t\t\t\t} else {\n\t\t\t\t\treturn \"&\" + lifetime + \":(\" + getElement() + \")\";\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Represents record type, which is of the form:\n\t\t *\n\t\t * <pre>\n\t\t * RecordType ::= '{' Type Identifier (',' Type Identifier)* [ ',' \"...\" ] '}'\n\t\t * </pre>\n\t\t *\n\t\t * @return\n\t\t */\n\t\tpublic static class Record extends Atom {\n\t\t\tpublic Record(boolean isOpen, FieldDeclaration[] fields) {\n\t\t\t\tsuper(TYPE_rec, ArrayUtils.append(SyntacticItem.class, new Value.Bool(isOpen), fields));\n\t\t\t}\n\n\t\t\tprivate Record(SyntacticItem[] operands) {\n\t\t\t\tsuper(TYPE_rec, operands);\n\t\t\t}\n\n\t\t\tpublic boolean isOpen() {\n\t\t\t\tValue.Bool flag = (Value.Bool) get(0);\n\t\t\t\treturn flag.get();\n\t\t\t}\n\n\t\t\tpublic FieldDeclaration[] getFields() {\n\t\t\t\t// FIXME: this should be packed as a Tuple and return a Tuple\n\t\t\t\tSyntacticItem[] operands = getAll();\n\t\t\t\tFieldDeclaration[] fields = new FieldDeclaration[size() - 1];\n\t\t\t\tSystem.arraycopy(operands, 1, fields, 0, fields.length);\n\t\t\t\treturn fields;\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Record clone(SyntacticItem[] operands) {\n\t\t\t\treturn new Record(operands);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic String toString() {\n\t\t\t\tString r = \"{\";\n\t\t\t\tFieldDeclaration[] fields = getFields();\n\t\t\t\tfor (int i = 0; i != fields.length; ++i) {\n\t\t\t\t\tif (i != 0) {\n\t\t\t\t\t\tr += \",\";\n\t\t\t\t\t}\n\t\t\t\t\tFieldDeclaration field = fields[i];\n\t\t\t\t\tr += field.getType() + \" \" + field.getVariableName();\n\t\t\t\t}\n\t\t\t\tif (isOpen()) {\n\t\t\t\t\tif (fields.length > 0) {\n\t\t\t\t\t\tr += \", ...\";\n\t\t\t\t\t} else {\n\t\t\t\t\t\tr += \"...\";\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn r + \"}\";\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Represents a nominal type, which is of the form:\n\t\t *\n\t\t * <pre>\n\t\t * NominalType ::= Identifier ('.' Identifier)*\n\t\t * </pre>\n\t\t *\n\t\t * A nominal type specifies the name of a type defined elsewhere. In some\n\t\t * cases, this type can be expanded (or \"inlined\"). However, visibility\n\t\t * modifiers can prevent this and, thus, give rise to true nominal types.\n\t\t *\n\t\t * @return\n\t\t */\n\t\tpublic static class Nominal extends AbstractSyntacticItem implements Type {\n\t\t\tpublic Nominal(Name name) {\n\t\t\t\tsuper(TYPE_nom, name);\n\t\t\t}\n\n\t\t\tpublic Name getName() {\n\t\t\t\treturn (Name) get(0);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Nominal clone(SyntacticItem[] operands) {\n\t\t\t\treturn new Nominal((Name) operands[0]);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic String toString() {\n\t\t\t\treturn getName().toString();\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Parse a negation type, which is of the form:\n\t\t *\n\t\t * <pre>\n\t\t * ReferenceType ::= '!' Type\n\t\t * </pre>\n\t\t *\n\t\t * @return\n\t\t */\n\t\tpublic static class Negation extends AbstractSyntacticItem implements Type {\n\t\t\tpublic Negation(Type element) {\n\t\t\t\tsuper(TYPE_not, element);\n\t\t\t}\n\n\t\t\tpublic Type getElement() {\n\t\t\t\treturn (Type) get(0);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Negation clone(SyntacticItem[] operands) {\n\t\t\t\treturn new Negation((Type) operands[0]);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic String toString() {\n\t\t\t\treturn \"!(\" + getElement() + \")\";\n\t\t\t}\n\t\t}\n\n\t\tpublic abstract static class UnionOrIntersection extends AbstractSyntacticItem implements Type {\n\t\t\tpublic UnionOrIntersection(int kind, Type[] types) {\n\t\t\t\tsuper(kind, types);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Type get(int i) {\n\t\t\t\treturn (Type) super.get(i);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Type[] getAll() {\n\t\t\t\treturn (Type[]) super.getAll();\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Represents a union type, which is of the form:\n\t\t *\n\t\t * <pre>\n\t\t * UnionType ::= IntersectionType ('|' IntersectionType)*\n\t\t * </pre>\n\t\t *\n\t\t * Union types are used to compose types together. For example, the type\n\t\t * <code>int|null</code> represents the type which is either an\n\t\t * <code>int</code> or <code>null</code>.\n\t\t *\n\t\t * @return\n\t\t */\n\t\tpublic static class Union extends UnionOrIntersection {\n\t\t\tpublic Union(Type[] types) {\n\t\t\t\tsuper(TYPE_or, types);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Union clone(SyntacticItem[] operands) {\n\t\t\t\treturn new Union(ArrayUtils.toArray(Type.class,operands));\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic String toString() {\n\t\t\t\tString r = \"\";\n\t\t\t\tfor (int i = 0; i != size(); ++i) {\n\t\t\t\t\tif (i != 0) {\n\t\t\t\t\t\tr += \"|\";\n\t\t\t\t\t}\n\t\t\t\t\tr += get(i);\n\t\t\t\t}\n\t\t\t\treturn \"(\" + r + \")\";\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Represents an intersection type, which is of the form:\n\t\t *\n\t\t * <pre>\n\t\t * IntersectionType ::= BaseType ('&' BaseType)*\n\t\t * </pre>\n\t\t *\n\t\t * Intersection types are used to unify types together. For example, the\n\t\t * type <code>{int x, int y}&MyType</code> represents the type which is both\n\t\t * an instanceof of <code>{int x, int y}</code> and an instance of\n\t\t * <code>MyType</code>.\n\t\t *\n\t\t * @return\n\t\t */\n\t\tpublic static class Intersection extends UnionOrIntersection {\n\t\t\tpublic Intersection(Type[] types) {\n\t\t\t\tsuper(TYPE_and, types);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Intersection clone(SyntacticItem[] operands) {\n\t\t\t\treturn new Intersection(ArrayUtils.toArray(Type.class, operands));\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic String toString() {\n\t\t\t\tString r = \"\";\n\t\t\t\tfor (int i = 0; i != size(); ++i) {\n\t\t\t\t\tif (i != 0) {\n\t\t\t\t\t\tr += \"&\";\n\t\t\t\t\t}\n\t\t\t\t\tr += get(i);\n\t\t\t\t}\n\t\t\t\treturn \"(\" + r + \")\";\n\t\t\t}\n\t\t}\n\n\t\tpublic static abstract class FunctionOrMacroOrInvariant extends Atom implements Type {\n\t\t\tpublic FunctionOrMacroOrInvariant(int opcode, Tuple<Type> parameters, Tuple<Type> returns) {\n\t\t\t\tsuper(opcode, parameters, returns);\n\t\t\t}\n\t\t\tpublic FunctionOrMacroOrInvariant(int opcode, SyntacticItem[] items) {\n\t\t\t\tsuper(opcode, items);\n\t\t\t}\n\t\t\tpublic Tuple<Type> getParameters() {\n\t\t\t\treturn (Tuple<Type>) get(0);\n\t\t\t}\n\n\t\t\tpublic Tuple<Type> getReturns() {\n\t\t\t\treturn (Tuple<Type>) get(1);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic String toString() {\n\t\t\t\treturn getParameters() + \"->\" + getReturns();\n\t\t\t}\n\t\t}\n\n\t\tpublic static abstract class FunctionOrMethodOrProperty extends FunctionOrMacroOrInvariant {\n\t\t\tpublic FunctionOrMethodOrProperty(int opcode, Tuple<Type> parameters, Tuple<Type> returns) {\n\t\t\t\tsuper(opcode, parameters, returns);\n\t\t\t}\n\t\t\tpublic FunctionOrMethodOrProperty(int opcode, SyntacticItem[] operands) {\n\t\t\t\tsuper(opcode, operands);\n\t\t\t}\n\t\t}\n\n\t\tpublic static class Function extends FunctionOrMethodOrProperty implements Type {\n\t\t\tpublic Function(Type[] parameters, Type[] returns) {\n\t\t\t\tsuper(TYPE_fun, new Tuple(parameters), new Tuple(returns));\n\t\t\t}\n\t\t\tpublic Function(Tuple<Type> parameters, Tuple<Type> returns) {\n\t\t\t\tsuper(TYPE_fun, parameters, returns);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Function clone(SyntacticItem[] operands) {\n\t\t\t\treturn new Function((Tuple<Type>) operands[0], (Tuple<Type>) operands[1]);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic String toString() {\n\t\t\t\treturn \"function\" + super.toString();\n\t\t\t}\n\t\t}\n\n\t\tpublic static class Method extends FunctionOrMethodOrProperty implements Type {\n\n\t\t\tpublic Method(Tuple<Type> parameters, Tuple<Type> returns, Tuple<Identifier> contextLifetimes,\n\t\t\t\t\tTuple<Identifier> lifetimeParameters) {\n\t\t\t\tsuper(TYPE_meth,\n\t\t\t\t\t\tnew SyntacticItem[] { parameters, returns, contextLifetimes, lifetimeParameters });\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Method clone(SyntacticItem[] operands) {\n\t\t\t\treturn new Method((Tuple<Type>) operands[0], (Tuple<Type>) operands[1],\n\t\t\t\t\t\t(Tuple<Identifier>) operands[2], (Tuple<Identifier>) operands[3]);\n\t\t\t}\n\n\t\t\tpublic Tuple<Identifier> getContextLifetimes() {\n\t\t\t\treturn (Tuple<Identifier>) get(2);\n\t\t\t}\n\n\t\t\tpublic Tuple<Identifier> getLifetimeParameters() {\n\t\t\t\treturn (Tuple<Identifier>) get(3);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic String toString() {\n\t\t\t\treturn \"method\" + super.toString();\n\t\t\t}\n\t\t}\n\n\t\tpublic static class Property extends FunctionOrMethodOrProperty implements Type {\n\t\t\tpublic Property(Tuple<Type> parameters) {\n\t\t\t\tsuper(TYPE_property, parameters, new Tuple<>(new Type.Bool()));\n\t\t\t}\n\n\t\t\tprivate Property(Tuple<Type> parameters, Tuple<Type> returns) {\n\t\t\t\tsuper(TYPE_property, parameters, returns);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Property clone(SyntacticItem[] operands) {\n\t\t\t\treturn new Property((Tuple<Type>) operands[0], (Tuple<Type>) operands[1]);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic String toString() {\n\t\t\t\treturn \"macro\" + super.toString();\n\t\t\t}\n\t\t}\n\n\t\tpublic static class Invariant extends FunctionOrMacroOrInvariant implements Type {\n\t\t\tpublic Invariant(Tuple<Type> parameters) {\n\t\t\t\tsuper(TYPE_inv, parameters, new Tuple<Type>(new Bool()));\n\t\t\t}\n\n\t\t\tprivate Invariant(Tuple<Type> parameters, Tuple<Type> returns) {\n\t\t\t\tsuper(TYPE_inv, parameters, returns);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Invariant clone(SyntacticItem[] operands) {\n\t\t\t\treturn new Invariant((Tuple<Type>) operands[0], (Tuple<Type>) operands[1]);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic String toString() {\n\t\t\t\treturn \"invariant\" + super.toString();\n\t\t\t}\n\t\t}\n\t}\n\n\t// ============================================================\n\t// Variable Declaration\n\t// ============================================================\n\n\tpublic static class VariableDeclaration extends AbstractSyntacticItem {\n\t\tpublic VariableDeclaration(Type type, Identifier name) {\n\t\t\tsuper(STMT_vardecl, type, name);\n\t\t}\n\n\t\tpublic Type getType() {\n\t\t\treturn (Type) get(0);\n\t\t}\n\n\t\tpublic Identifier getVariableName() {\n\t\t\treturn (Identifier) get(1);\n\t\t}\n\n\t\t@Override\n\t\tpublic boolean equals(Object o) {\n\t\t\t// The reason for this is that we want to treat variable\n\t\t\t// declarations specially. The only way that two variable\n\t\t\t// declarations can be considered equal is if they are the same.\n\t\t\treturn o == this;\n\t\t}\n\n\t\t@Override\n\t\tpublic VariableDeclaration clone(SyntacticItem[] operands) {\n\t\t\treturn new VariableDeclaration((Type) operands[0], (Identifier) operands[1]);\n\t\t}\n\t}\n\n\tpublic static class FieldDeclaration extends AbstractSyntacticItem {\n\t\tpublic FieldDeclaration(Type type, Identifier name) {\n\t\t\tsuper(STMT_vardecl, type, name);\n\t\t}\n\n\t\tpublic Type getType() {\n\t\t\treturn (Type) get(0);\n\t\t}\n\n\t\tpublic Identifier getVariableName() {\n\t\t\treturn (Identifier) get(1);\n\t\t}\n\n\t\t@Override\n\t\tpublic FieldDeclaration clone(SyntacticItem[] operands) {\n\t\t\treturn new FieldDeclaration((Type) operands[0], (Identifier) operands[1]);\n\t\t}\n\t}\n\n\t// ============================================================\n\t// Stmt\n\t// ============================================================\n\n\tpublic interface Stmt extends SyntacticItem {\n\n\t\tpublic static class Block extends AbstractSyntacticItem implements Stmt {\n\t\t\tpublic Block(Stmt... stmts) {\n\t\t\t\tsuper(STMT_block, stmts);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Stmt get(int i) {\n\t\t\t\treturn (Stmt) super.get(i);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Stmt[] getAll() {\n\t\t\t\treturn (Stmt[]) super.getAll();\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Block clone(SyntacticItem[] operands) {\n\t\t\t\treturn new Block(ArrayUtils.toArray(Stmt.class, operands));\n\t\t\t}\n\t\t}\n\n\t\tpublic static abstract class Quantifier extends AbstractSyntacticItem implements Stmt {\n\t\t\tpublic Quantifier(int opcode, VariableDeclaration[] parameters, Block body) {\n\t\t\t\tsuper(opcode, new Tuple<>(parameters), body);\n\t\t\t}\n\n\t\t\tpublic Quantifier(int opcode, Tuple<VariableDeclaration> parameters, Block body) {\n\t\t\t\tsuper(opcode, parameters, body);\n\t\t\t}\n\n\t\t\tpublic Tuple<VariableDeclaration> getParameters() {\n\t\t\t\treturn (Tuple<VariableDeclaration>) get(0);\n\t\t\t}\n\n\t\t\tpublic Block getBody() {\n\t\t\t\treturn (Block) get(1);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic abstract Quantifier clone(SyntacticItem[] operands);\n\t\t}\n\n\t\t/**\n\t\t * Represents an unbounded universally quantified expression of the form\n\t\t * \"<code>forall(T v1, ... T vn): block</code>\" where\n\t\t * <code>T1 v1</code> ... <code>Tn vn</code> are the <i>quantified\n\t\t * variable declarations</i> and <code>block</code> is the body\n\t\t * consisting of a statement block\n\t\t *\n\t\t * @author David J. Pearce\n\t\t *\n\t\t */\n\t\tpublic static class UniversalQuantifier extends Quantifier {\n\t\t\tpublic UniversalQuantifier(VariableDeclaration[] parameters, Block body) {\n\t\t\t\tsuper(STMT_forall, new Tuple<>(parameters), body);\n\t\t\t}\n\n\t\t\tpublic UniversalQuantifier(Tuple<VariableDeclaration> parameters, Block body) {\n\t\t\t\tsuper(STMT_forall, parameters, body);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Quantifier clone(SyntacticItem[] operands) {\n\t\t\t\treturn new UniversalQuantifier((Tuple<VariableDeclaration>) operands[0],\n\t\t\t\t\t\t(Block) operands[1]);\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Represents an unbounded existentially quantified expression of the\n\t\t * form \"<code>some(T v1, ... T vn): block</code>\" where\n\t\t * <code>T1 v1</code> ... <code>Tn vn</code> are the <i>quantified\n\t\t * variable declarations</i> and <code>block</code> is the body\n\t\t * consisting of a statement block.\n\t\t *\n\t\t * @author David J. Pearce\n\t\t *\n\t\t */\n\t\tpublic static class ExistentialQuantifier extends Quantifier {\n\t\t\tpublic ExistentialQuantifier(VariableDeclaration[] parameters, Block body) {\n\t\t\t\tsuper(STMT_exists, new Tuple<>(parameters), body);\n\t\t\t}\n\n\t\t\tpublic ExistentialQuantifier(Tuple<VariableDeclaration> parameters, Block body) {\n\t\t\t\tsuper(STMT_exists, parameters, body);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Quantifier clone(SyntacticItem[] operands) {\n\t\t\t\treturn new ExistentialQuantifier((Tuple<VariableDeclaration>) operands[0], (Block) operands[1]);\n\t\t\t}\n\t\t}\n\n\t\tpublic static class IfThen extends AbstractSyntacticItem implements Stmt {\n\t\t\tpublic IfThen(Block ifBlock, Block thenBlock) {\n\t\t\t\tsuper(STMT_ifthen, ifBlock, thenBlock);\n\t\t\t}\n\n\t\t\tpublic Block getIfBody() {\n\t\t\t\treturn (Block) get(0);\n\t\t\t}\n\n\t\t\tpublic Block getThenBody() {\n\t\t\t\treturn (Block) get(1);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic IfThen clone(SyntacticItem[] operands) {\n\t\t\t\treturn new IfThen((Block) operands[0], (Block) operands[1]);\n\t\t\t}\n\t\t}\n\n\t\tpublic static class CaseOf extends AbstractSyntacticItem implements Stmt {\n\t\t\tpublic CaseOf(Block... cases) {\n\t\t\t\tsuper(STMT_caseof, cases);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Block get(int i) {\n\t\t\t\treturn (Block) super.get(i);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Block[] getAll() {\n\t\t\t\treturn (Block[]) super.getAll();\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic CaseOf clone(SyntacticItem[] operands) {\n\t\t\t\treturn new CaseOf(ArrayUtils.toArray(Block.class, operands));\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic interface Expr extends Stmt {\n\n\t\t// =========================================================================\n\t\t// General Expressions\n\t\t// =========================================================================\n\n\t\t/**\n\t\t * Represents a cast expression of the form \"<code>(T) e</code>\" where\n\t\t * <code>T</code> is the <i>cast type</i> and <code>e</code> the\n\t\t * <i>casted expression</i>.\n\t\t *\n\t\t * @author David J. Pearce\n\t\t *\n\t\t */\n\t\tpublic static class Cast extends AbstractSyntacticItem implements Expr {\n\t\t\tpublic Cast(Type type, Expr rhs) {\n\t\t\t\tsuper(EXPR_cast, type, rhs);\n\t\t\t}\n\n\t\t\tpublic Type getCastType() {\n\t\t\t\treturn (Type) super.get(0);\n\t\t\t}\n\n\t\t\tpublic Expr getCastedExpr() {\n\t\t\t\treturn (Expr) super.get(1);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Cast clone(SyntacticItem[] operands) {\n\t\t\t\treturn new Cast((Type) operands[0], (Expr) operands[1]);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic String toString() {\n\t\t\t\treturn \"(\" + getCastType() + \") \" + getCastedExpr();\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Represents the use of a constant within some expression. For example,\n\t\t * in <code>x + 1</code> the expression <code>1</code> is a constant\n\t\t * expression.\n\t\t *\n\t\t * @author David J. Pearce\n\t\t *\n\t\t */\n\t\tpublic static class Constant extends AbstractSyntacticItem implements Expr {\n\t\t\tpublic Constant(Value value) {\n\t\t\t\tsuper(EXPR_const, value);\n\t\t\t}\n\n\t\t\tpublic Value getValue() {\n\t\t\t\treturn (Value) get(0);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Constant clone(SyntacticItem[] operands) {\n\t\t\t\treturn new Constant((Value) operands[0]);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic String toString() {\n\t\t\t\treturn getValue().toString();\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Represents a <i>type test expression</i> of the form\n\t\t * \"<code>e is T</code>\" where <code>e</code> is the <i>test\n\t\t * expression</i> and <code>T</code> is the <i>test type</i>.\n\t\t *\n\t\t * @author David J. Pearce\n\t\t *\n\t\t */\n\t\tpublic static class Is extends AbstractSyntacticItem implements Expr {\n\t\t\tpublic Is(Expr lhs, Type rhs) {\n\t\t\t\tsuper(EXPR_is, lhs, rhs);\n\t\t\t}\n\n\t\t\tpublic Expr getTestExpr() {\n\t\t\t\treturn (Expr) get(0);\n\t\t\t}\n\n\t\t\tpublic Type getTestType() {\n\t\t\t\treturn (Type) get(1);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Is clone(SyntacticItem[] operands) {\n\t\t\t\treturn new Is((Expr) operands[0], (Type) operands[1]);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic String toString() {\n\t\t\t\treturn getTestExpr() + \" is \" + getTestType();\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Represents an invocation of the form \"<code>x.y.f(e1,..en)</code>\".\n\t\t * Here, <code>x.y.f</code> constitute a <i>partially-</i> or\n\t\t * <i>fully-qualified name</i> and <code>e1</code> ... <code>en</code>\n\t\t * are the <i>argument expressions</i>.\n\t\t *\n\t\t * @author David J. Pearce\n\t\t *\n\t\t */\n\t\tpublic static class Invoke extends AbstractSyntacticItem implements Expr {\n\n\t\t\tpublic Invoke(Type.FunctionOrMacroOrInvariant type, Name name, Integer selector, Expr[] arguments) {\n\t\t\t\tsuper(EXPR_invoke, new SyntacticItem[] { type, name,\n\t\t\t\t\t\tselector != null ? new Value.Int(selector) : null, new Tuple<>(arguments) });\n\t\t\t}\n\n\t\t\tpublic Invoke(Type.FunctionOrMacroOrInvariant type, Name name, Value.Int selector, Tuple<Expr> arguments) {\n\t\t\t\tsuper(EXPR_invoke, new SyntacticItem[] { type, name, selector, arguments });\n\t\t\t}\n\n\t\t\tpublic Type.FunctionOrMacroOrInvariant getSignatureType() {\n\t\t\t\treturn (Type.FunctionOrMacroOrInvariant) get(0);\n\t\t\t}\n\n\t\t\tpublic void setSignatureType(Type.FunctionOrMacroOrInvariant type) {\n\t\t\t\tthis.setOperand(0, type);\n\t\t\t}\n\n\t\t\tpublic Name getName() {\n\t\t\t\treturn (Name) get(1);\n\t\t\t}\n\n\t\t\tpublic Value.Int getSelector() {\n\t\t\t\treturn (Value.Int) get(2);\n\t\t\t}\n\n\t\t\tpublic Tuple<Expr> getArguments() {\n\t\t\t\treturn (Tuple) get(3);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Invoke clone(SyntacticItem[] operands) {\n\t\t\t\treturn new Invoke((Type.FunctionOrMacroOrInvariant) operands[0], (Name) operands[1],\n\t\t\t\t\t\t(Value.Int) operands[2], (Tuple) operands[3]);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic String toString() {\n\t\t\t\tString r = getName().toString();\n\t\t\t\tr += getArguments();\n\t\t\t\tr += \"#\" + getSelector();\n\t\t\t\treturn r;\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Represents an abstract operator expression over one or more\n\t\t * <i>operand expressions</i>. For example. in <code>arr[i+1]</code> the\n\t\t * expression <code>i+1</code> is an operator expression.\n\t\t *\n\t\t * @author David J. Pearce\n\t\t *\n\t\t */\n\t\tpublic abstract static class Operator extends AbstractSyntacticItem implements Expr {\n\t\t\tpublic Operator(int opcode, Expr... operands) {\n\t\t\t\tsuper(opcode, operands);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Expr get(int i) {\n\t\t\t\treturn (Expr) super.get(i);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Expr[] getAll() {\n\t\t\t\treturn (Expr[]) super.getAll();\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic abstract Expr clone(SyntacticItem[] operands);\n\t\t}\n\n\t\t/**\n\t\t * Represents an abstract quantified expression of the form\n\t\t * \"<code>forall(T v1, ... T vn).e</code>\" or\n\t\t * \"<code>exists(T v1, ... T vn).e</code>\" where <code>T1 v1</code> ...\n\t\t * <code>Tn vn</code> are the <i>quantified variable declarations</i>\n\t\t * and <code>e</code> is the body.\n\t\t *\n\t\t * @author David J. Pearce\n\t\t *\n\t\t */\n\t\tpublic abstract static class Quantifier extends AbstractSyntacticItem implements Expr {\n\t\t\tpublic Quantifier(int opcode, VariableDeclaration[] parameters, Expr body) {\n\t\t\t\tsuper(opcode, new Tuple<>(parameters), body);\n\t\t\t}\n\n\t\t\tpublic Quantifier(int opcode, Tuple<VariableDeclaration> parameters, Expr body) {\n\t\t\t\tsuper(opcode, parameters, body);\n\t\t\t}\n\n\t\t\tpublic Tuple<VariableDeclaration> getParameters() {\n\t\t\t\treturn (Tuple<VariableDeclaration>) get(0);\n\t\t\t}\n\n\t\t\tpublic Expr getBody() {\n\t\t\t\treturn (Expr) get(1);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic abstract Expr clone(SyntacticItem[] operands);\n\t\t}\n\n\t\t/**\n\t\t * Represents an unbounded universally quantified expression of the form\n\t\t * \"<code>forall(T v1, ... T vn).e</code>\" where <code>T1 v1</code> ...\n\t\t * <code>Tn vn</code> are the <i>quantified variable declarations</i>\n\t\t * and <code>e</code> is the body.\n\t\t *\n\t\t * @author David J. Pearce\n\t\t *\n\t\t */\n\t\tpublic static class UniversalQuantifier extends Quantifier {\n\t\t\tpublic UniversalQuantifier(VariableDeclaration[] parameters, Expr body) {\n\t\t\t\tsuper(EXPR_forall, new Tuple<>(parameters), body);\n\t\t\t}\n\n\t\t\tpublic UniversalQuantifier(Tuple<VariableDeclaration> parameters, Expr body) {\n\t\t\t\tsuper(EXPR_forall, parameters, body);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Expr clone(SyntacticItem[] operands) {\n\t\t\t\treturn new UniversalQuantifier((Tuple<VariableDeclaration>) operands[0],\n\t\t\t\t\t\t(Expr) operands[1]);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic String toString() {\n\t\t\t\tString r = \"forall\";\n\t\t\t\tr += getParameters();\n\t\t\t\tr += \".\";\n\t\t\t\tr += getBody();\n\t\t\t\treturn r;\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Represents an unbounded existentially quantified expression of the\n\t\t * form \"<code>some(T v1, ... T vn).e</code>\" where <code>T1 v1</code>\n\t\t * ... <code>Tn vn</code> are the <i>quantified variable\n\t\t * declarations</i> and <code>e</code> is the body.\n\t\t *\n\t\t * @author David J. Pearce\n\t\t *\n\t\t */\n\t\tpublic static class ExistentialQuantifier extends Quantifier {\n\t\t\tpublic ExistentialQuantifier(VariableDeclaration[] parameters, Expr body) {\n\t\t\t\tsuper(EXPR_exists, new Tuple<>(parameters), body);\n\t\t\t}\n\n\t\t\tpublic ExistentialQuantifier(Tuple<VariableDeclaration> parameters, Expr body) {\n\t\t\t\tsuper(EXPR_exists, parameters, body);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Expr clone(SyntacticItem[] operands) {\n\t\t\t\treturn new ExistentialQuantifier((Tuple<VariableDeclaration>) operands[0], (Expr) operands[1]);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic String toString() {\n\t\t\t\tString r = \"exists\";\n\t\t\t\tr += getParameters();\n\t\t\t\tr += \".\";\n\t\t\t\tr += getBody();\n\t\t\t\treturn r;\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Represents a use of some variable within an expression. For example,\n\t\t * in <code>x + 1</code> the expression <code>x</code> is a variable\n\t\t * access expression. Every variable access is associated with a\n\t\t * <i>variable declaration</i> that unique identifies which variable is\n\t\t * being accessed.\n\t\t *\n\t\t * @author David J. Pearce\n\t\t *\n\t\t */\n\t\tpublic static class VariableAccess extends AbstractSyntacticItem implements Expr {\n\t\t\tpublic VariableAccess(VariableDeclaration decl) {\n\t\t\t\tsuper(EXPR_varcopy, decl);\n\t\t\t}\n\n\t\t\tpublic VariableDeclaration getVariableDeclaration() {\n\t\t\t\treturn (VariableDeclaration) get(0);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic VariableAccess clone(SyntacticItem[] operands) {\n\t\t\t\treturn new VariableAccess((VariableDeclaration) operands[0]);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic String toString() {\n\t\t\t\treturn getVariableDeclaration().getVariableName().toString();\n\t\t\t}\n\t\t}\n\n\n\t\tpublic abstract static class InfixOperator extends Operator {\n\t\t\tpublic InfixOperator(int opcode, Expr... operands) {\n\t\t\t\tsuper(opcode, operands);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic String toString() {\n\t\t\t\tString str = getOperatorString();\n\t\t\t\tString r = \"\";\n\t\t\t\tfor (int i = 0; i != size(); ++i) {\n\t\t\t\t\tif (i != 0) {\n\t\t\t\t\t\tr += str;\n\t\t\t\t\t}\n\t\t\t\t\tr += get(i);\n\t\t\t\t}\n\t\t\t\treturn r;\n\t\t\t}\n\n\t\t\tprotected abstract String getOperatorString();\n\t\t}\n\n\t\t// =========================================================================\n\t\t// Logical Expressions\n\t\t// =========================================================================\n\t\t/**\n\t\t * Represents a <i>logical conjunction</i> of the form\n\t\t * \"<code>e1 && .. && en</code>\" where <code>e1</code> ...\n\t\t * <code>en</code> are the <i>operand expressions</i>.\n\t\t *\n\t\t * @author David J. Pearce\n\t\t *\n\t\t */\n\t\tpublic static class LogicalAnd extends InfixOperator {\n\t\t\tpublic LogicalAnd(Expr... operands) {\n\t\t\t\tsuper(EXPR_and, operands);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Expr clone(SyntacticItem[] operands) {\n\t\t\t\tif(operands.length <= 1) {\n\t\t\t\t\tthrow new IllegalArgumentException(\"invalid number of operands\");\n\t\t\t\t}\n\t\t\t\treturn new LogicalAnd(ArrayUtils.toArray(Expr.class, operands));\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tprotected String getOperatorString() {\n\t\t\t\treturn \" && \";\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Represents a <i>logical disjunction</i> of the form\n\t\t * \"<code>e1 || .. || en</code>\" where <code>e1</code> ...\n\t\t * <code>en</code> are the <i>operand expressions</i>.\n\t\t *\n\t\t * @author David J. Pearce\n\t\t *\n\t\t */\n\t\tpublic static class LogicalOr extends InfixOperator {\n\t\t\tpublic LogicalOr(Expr... operands) {\n\t\t\t\tsuper(EXPR_or, operands);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Expr clone(SyntacticItem[] operands) {\n\t\t\t\tif(operands.length <= 1) {\n\t\t\t\t\tthrow new IllegalArgumentException(\"invalid number of operands\");\n\t\t\t\t}\n\t\t\t\treturn new LogicalOr(ArrayUtils.toArray(Expr.class, operands));\n\t\t\t}\n\n\n\t\t\t@Override\n\t\t\tprotected String getOperatorString() {\n\t\t\t\treturn \" && \";\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Represents a <i>logical implication</i> of the form\n\t\t * \"<code>e1 ==> ... ==> en</code>\" where <code>e1</code> ...\n\t\t * <code>en</code> are the <i>operand expressions</i>.\n\t\t *\n\t\t * @author David J. Pearce\n\t\t *\n\t\t */\n\t\tpublic static class LogicalImplication extends InfixOperator {\n\t\t\tpublic LogicalImplication(Expr... operands) {\n\t\t\t\tsuper(EXPR_implies, operands);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Expr clone(SyntacticItem[] operands) {\n\t\t\t\tif(operands.length <= 1) {\n\t\t\t\t\tthrow new IllegalArgumentException(\"invalid number of operands\");\n\t\t\t\t}\n\t\t\t\treturn new LogicalImplication(ArrayUtils.toArray(Expr.class, operands));\n\t\t\t}\n\n\n\t\t\t@Override\n\t\t\tprotected String getOperatorString() {\n\t\t\t\treturn \" ==> \";\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Represents a <i>logical biconditional</i> of the form\n\t\t * \"<code>e1 <==> ... <==> en</code>\" where <code>e1</code> ...\n\t\t * <code>en</code> are the <i>operand expressions</i>.\n\t\t *\n\t\t * @author David J. Pearce\n\t\t *\n\t\t */\n\t\tpublic static class LogicalIff extends InfixOperator {\n\t\t\tpublic LogicalIff(Expr... operands) {\n\t\t\t\tsuper(EXPR_iff, operands);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Expr clone(SyntacticItem[] operands) {\n\t\t\t\tif(operands.length <= 1) {\n\t\t\t\t\tthrow new IllegalArgumentException(\"invalid number of operands\");\n\t\t\t\t}\n\t\t\t\treturn new LogicalIff(ArrayUtils.toArray(Expr.class, operands));\n\t\t\t}\n\n\n\t\t\t@Override\n\t\t\tprotected String getOperatorString() {\n\t\t\t\treturn \" <==> \";\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Represents a <i>logical negation</i> of the form \"<code>!e</code>\"\n\t\t * where <code>e</code> is the <i>operand expression</i>.\n\t\t *\n\t\t * @author David J. Pearce\n\t\t *\n\t\t */\n\t\tpublic static class LogicalNot extends Operator {\n\t\t\tpublic LogicalNot(Expr operand) {\n\t\t\t\tsuper(EXPR_not, operand);\n\t\t\t}\n\n\t\t\tpublic Expr getOperand() {\n\t\t\t\treturn get(0);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Expr clone(SyntacticItem[] operands) {\n\t\t\t\tif(operands.length != 1) {\n\t\t\t\t\tthrow new IllegalArgumentException(\"invalid number of operands\");\n\t\t\t\t}\n\t\t\t\treturn new LogicalNot((Expr) operands[0]);\n\t\t\t}\n\t\t}\n\n\t\t// =========================================================================\n\t\t// Comparator Expressions\n\t\t// =========================================================================\n\n\t\t/**\n\t\t * Represents an equality expression of the form\n\t\t * \"<code>e1 == ... == en</code>\" where <code>e1</code> ...\n\t\t * <code>en</code> are the <i>operand expressions</i>.\n\t\t *\n\t\t * @author David J. Pearce\n\t\t *\n\t\t */\n\t\tpublic static class Equal extends InfixOperator {\n\t\t\tpublic Equal(Expr... operands) {\n\t\t\t\tsuper(EXPR_eq, operands);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Expr clone(SyntacticItem[] operands) {\n\t\t\t\tif(operands.length <= 1) {\n\t\t\t\t\tthrow new IllegalArgumentException(\"invalid number of operands\");\n\t\t\t\t}\n\t\t\t\treturn new Equal(ArrayUtils.toArray(Expr.class, operands));\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic String getOperatorString() {\n\t\t\t\treturn \" == \";\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Represents an unequality expression of the form\n\t\t * \"<code>e1 != ... != en</code>\" where <code>e1</code> ...\n\t\t * <code>en</code> are the <i>operand expressions</i>.\n\t\t *\n\t\t * @author David J. Pearce\n\t\t *\n\t\t */\n\t\tpublic static class NotEqual extends InfixOperator {\n\t\t\tpublic NotEqual(Expr... operands) {\n\t\t\t\tsuper(EXPR_neq, operands);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Expr clone(SyntacticItem[] operands) {\n\t\t\t\tif(operands.length <= 1) {\n\t\t\t\t\tthrow new IllegalArgumentException(\"invalid number of operands\");\n\t\t\t\t}\n\t\t\t\treturn new NotEqual(ArrayUtils.toArray(Expr.class, operands));\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tprotected String getOperatorString() {\n\t\t\t\treturn \" != \";\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Represents a strict <i>inequality expression</i> of the form\n\t\t * \"<code>e1 < ... < en</code>\" where <code>e1</code> ...\n\t\t * <code>en</code> are the <i>operand expressions</i>.\n\t\t *\n\t\t * @author David J. Pearce\n\t\t *\n\t\t */\n\t\tpublic static class LessThan extends InfixOperator {\n\t\t\tpublic LessThan(Expr... operands) {\n\t\t\t\tsuper(EXPR_lt, operands);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Expr clone(SyntacticItem[] operands) {\n\t\t\t\tif (operands.length <= 1) {\n\t\t\t\t\tthrow new IllegalArgumentException(\"invalid number of operands\");\n\t\t\t\t}\n\t\t\t\treturn new LessThan(ArrayUtils.toArray(Expr.class, operands));\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tprotected String getOperatorString() {\n\t\t\t\treturn \" < \";\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Represents a non-strict <i>inequality expression</i> of the form\n\t\t * \"<code>e1 <= ... <= en</code>\" where <code>e1</code> ...\n\t\t * <code>en</code> are the <i>operand expressions</i>.\n\t\t *\n\t\t * @author David J. Pearce\n\t\t *\n\t\t */\n\t\tpublic static class LessThanOrEqual extends InfixOperator {\n\t\t\tpublic LessThanOrEqual(Expr... operands) {\n\t\t\t\tsuper(EXPR_lteq, operands);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Expr clone(SyntacticItem[] operands) {\n\t\t\t\tif (operands.length <= 1) {\n\t\t\t\t\tthrow new IllegalArgumentException(\"invalid number of operands\");\n\t\t\t\t}\n\t\t\t\treturn new LessThanOrEqual(ArrayUtils.toArray(Expr.class, operands));\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tprotected String getOperatorString() {\n\t\t\t\treturn \" <= \";\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Represents a strict <i>inequality expression</i> of the form\n\t\t * \"<code>e1 > ... > en</code>\" where <code>e1</code> ...\n\t\t * <code>en</code> are the <i>operand expressions</i>.\n\t\t *\n\t\t * @author David J. Pearce\n\t\t *\n\t\t */\n\t\tpublic static class GreaterThan extends InfixOperator {\n\t\t\tpublic GreaterThan(Expr... operands) {\n\t\t\t\tsuper(EXPR_gt, operands);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Expr clone(SyntacticItem[] operands) {\n\t\t\t\tif (operands.length <= 1) {\n\t\t\t\t\tthrow new IllegalArgumentException(\"invalid number of operands\");\n\t\t\t\t}\n\t\t\t\treturn new GreaterThan(ArrayUtils.toArray(Expr.class, operands));\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tprotected String getOperatorString() {\n\t\t\t\treturn \" > \";\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Represents a non-strict <i>inequality expression</i> of the form\n\t\t * \"<code>e1 >= ... >= en</code>\" where <code>e1</code> ...\n\t\t * <code>en</code> are the <i>operand expressions</i>.\n\t\t *\n\t\t * @author David J. Pearce\n\t\t *\n\t\t */\n\t\tpublic static class GreaterThanOrEqual extends InfixOperator {\n\t\t\tpublic GreaterThanOrEqual(Expr... operands) {\n\t\t\t\tsuper(EXPR_gteq, operands);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Expr clone(SyntacticItem[] operands) {\n\t\t\t\tif (operands.length <= 1) {\n\t\t\t\t\tthrow new IllegalArgumentException(\"invalid number of operands\");\n\t\t\t\t}\n\t\t\t\treturn new GreaterThanOrEqual(ArrayUtils.toArray(Expr.class, operands));\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tprotected String getOperatorString() {\n\t\t\t\treturn \" >= \";\n\t\t\t}\n\t\t}\n\n\t\t// =========================================================================\n\t\t// Arithmetic Expressions\n\t\t// =========================================================================\n\n\t\t/**\n\t\t * Represents an arithmetic <i>addition expression</i> of the form\n\t\t * \"<code>e1 + ... + en</code>\" where <code>e1</code> ...\n\t\t * <code>en</code> are the <i>operand expressions</i>.\n\t\t *\n\t\t * @author David J. Pearce\n\t\t *\n\t\t */\n\t\tpublic static class Addition extends InfixOperator {\n\t\t\tpublic Addition(Expr... operands) {\n\t\t\t\tsuper(EXPR_add, operands);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Expr clone(SyntacticItem[] operands) {\n\t\t\t\tif (operands.length <= 1) {\n\t\t\t\t\tthrow new IllegalArgumentException(\"invalid number of operands\");\n\t\t\t\t}\n\t\t\t\treturn new Addition(ArrayUtils.toArray(Expr.class, operands));\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tprotected String getOperatorString() {\n\t\t\t\treturn \" + \";\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Represents an arithmetic <i>subtraction expression</i> of the form\n\t\t * \"<code>e1 - ... - en</code>\" where <code>e1</code> ...\n\t\t * <code>en</code> are the <i>operand expressions</i>.\n\t\t *\n\t\t * @author David J. Pearce\n\t\t *\n\t\t */\n\t\tpublic static class Subtraction extends InfixOperator {\n\t\t\tpublic Subtraction(Expr... operands) {\n\t\t\t\tsuper(EXPR_sub, operands);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Expr clone(SyntacticItem[] operands) {\n\t\t\t\tif (operands.length <= 1) {\n\t\t\t\t\tthrow new IllegalArgumentException(\"invalid number of operands\");\n\t\t\t\t}\n\t\t\t\treturn new Subtraction(ArrayUtils.toArray(Expr.class, operands));\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tprotected String getOperatorString() {\n\t\t\t\treturn \" - \";\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Represents an arithmetic <i>multiplication expression</i> of the form\n\t\t * \"<code>e1 * ... * en</code>\" where <code>e1</code> ...\n\t\t * <code>en</code> are the <i>operand expressions</i>.\n\t\t *\n\t\t * @author David J. Pearce\n\t\t *\n\t\t */\n\t\tpublic static class Multiplication extends InfixOperator {\n\t\t\tpublic Multiplication(Expr... operands) {\n\t\t\t\tsuper(EXPR_mul, operands);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Expr clone(SyntacticItem[] operands) {\n\t\t\t\tif (operands.length <= 1) {\n\t\t\t\t\tthrow new IllegalArgumentException(\"invalid number of operands\");\n\t\t\t\t}\n\t\t\t\treturn new Multiplication(ArrayUtils.toArray(Expr.class, operands));\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tprotected String getOperatorString() {\n\t\t\t\treturn \" * \";\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Represents an arithmetic <i>division expression</i> of the form\n\t\t * \"<code>e1 / ... / en</code>\" where <code>e1</code> ...\n\t\t * <code>en</code> are the <i>operand expressions</i>.\n\t\t *\n\t\t * @author David J. Pearce\n\t\t *\n\t\t */\n\t\tpublic static class Division extends InfixOperator {\n\t\t\tpublic Division(Expr... operands) {\n\t\t\t\tsuper(EXPR_div, operands);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Expr clone(SyntacticItem[] operands) {\n\t\t\t\tif (operands.length <= 1) {\n\t\t\t\t\tthrow new IllegalArgumentException(\"invalid number of operands\");\n\t\t\t\t}\n\t\t\t\treturn new Division(ArrayUtils.toArray(Expr.class, operands));\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tprotected String getOperatorString() {\n\t\t\t\treturn \" / \";\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Represents an arithmetic <i>remainder expression</i> of the form\n\t\t * \"<code>e1 / ... / en</code>\" where <code>e1</code> ...\n\t\t * <code>en</code> are the <i>operand expressions</i>.\n\t\t *\n\t\t * @author David J. Pearce\n\t\t *\n\t\t */\n\t\tpublic static class Remainder extends InfixOperator {\n\t\t\tpublic Remainder(Expr... operands) {\n\t\t\t\tsuper(EXPR_rem, operands);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Expr clone(SyntacticItem[] operands) {\n\t\t\t\tif (operands.length <= 1) {\n\t\t\t\t\tthrow new IllegalArgumentException(\"invalid number of operands\");\n\t\t\t\t}\n\t\t\t\treturn new Remainder(ArrayUtils.toArray(Expr.class, operands));\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tprotected String getOperatorString() {\n\t\t\t\treturn \" % \";\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Represents an arithmetic <i>negation expression</i> of the form\n\t\t * \"<code>-e</code>\" where <code>e</code> is the <i>operand\n\t\t * expression</i>.\n\t\t *\n\t\t * @author David J. Pearce\n\t\t *\n\t\t */\n\t\tpublic static class Negation extends Operator {\n\t\t\tpublic Negation(Expr operand) {\n\t\t\t\tsuper(EXPR_neg, operand);\n\t\t\t}\n\n\t\t\tpublic Expr getOperand() {\n\t\t\t\treturn get(0);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Expr clone(SyntacticItem[] operands) {\n\t\t\t\tif (operands.length != 1) {\n\t\t\t\t\tthrow new IllegalArgumentException(\"invalid number of operands\");\n\t\t\t\t}\n\t\t\t\treturn new Negation((Expr) operands[0]);\n\t\t\t}\n\n\n\t\t\t@Override\n\t\t\tpublic String toString() {\n\t\t\t\treturn \"-\" + getOperand();\n\t\t\t}\n\t\t}\n\n\t\t// =========================================================================\n\t\t// Reference Expressions\n\t\t// =========================================================================\n\t\tpublic static class Dereference extends Operator {\n\t\t\tpublic Dereference(Expr operand) {\n\t\t\t\tsuper(EXPR_deref, operand);\n\t\t\t}\n\n\t\t\tpublic Expr getOperand() {\n\t\t\t\treturn get(0);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic Expr clone(SyntacticItem[] operands) {\n\t\t\t\tif (operands.length != 1) {\n\t\t\t\t\tthrow new IllegalArgumentException(\"invalid number of operands\");\n\t\t\t\t}\n\t\t\t\treturn new Dereference((Expr) operands[0]);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic String toString() {\n\t\t\t\treturn \"*\" + getOperand();\n\t\t\t}\n\t\t}\n\n\t\t// =========================================================================\n\t\t// Array Expressions\n\t\t// =========================================================================\n\n\t\t/**\n\t\t * Represents an <i>array access expression</i> of the form\n\t\t * \"<code>arr[e]</code>\" where <code>arr</code> is the <i>source\n\t\t * array</i> and <code>e</code> the <i>subscript expression</i>. This\n\t\t * returns the value held in the element determined by <code>e</code>.\n\t\t *\n\t\t * @author David J. Pearce\n\t\t *\n\t\t */\n\t\tpublic static class ArrayAccess extends Expr.Operator {\n\t\t\tpublic ArrayAccess(Expr src, Expr index) {\n\t\t\t\tsuper(EXPR_arridx, src, index);\n\t\t\t}\n\n\t\t\tpublic Expr getSource() {\n\t\t\t\treturn get(0);\n\t\t\t}\n\n\t\t\tpublic Expr getSubscript() {\n\t\t\t\treturn get(1);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic ArrayAccess clone(SyntacticItem[] operands) {\n\t\t\t\treturn new ArrayAccess((Expr) operands[0], (Expr) operands[1]);\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Represents an <i>array update expression</i> of the form\n\t\t * \"<code>arr[e1:=e2]</code>\" where <code>arr</code> is the <i>source\n\t\t * array</i>, <code>e1</code> the <i>subscript expression</i> and\n\t\t * <code>e2</code> is the value expression. This returns a new array\n\t\t * which is equivalent to <code>arr</code> but where the element\n\t\t * determined by <code>e1</code> has the value resulting from\n\t\t * <code>e2</code>.\n\t\t *\n\t\t * @author David J. Pearce\n\t\t *\n\t\t */\n\t\tpublic static class ArrayUpdate extends Expr.Operator {\n\t\t\tpublic ArrayUpdate(Expr src, Expr index, Expr value) {\n\t\t\t\tsuper(EXPR_arrupdt, src, index, value);\n\t\t\t}\n\n\t\t\tpublic Expr getSource() {\n\t\t\t\treturn get(0);\n\t\t\t}\n\n\t\t\tpublic Expr getSubscript() {\n\t\t\t\treturn get(1);\n\t\t\t}\n\n\t\t\tpublic Expr getValue() {\n\t\t\t\treturn get(2);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic ArrayUpdate clone(SyntacticItem[] operands) {\n\t\t\t\treturn new ArrayUpdate((Expr) operands[0], (Expr) operands[1], (Expr) operands[2]);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic String toString() {\n\t\t\t\treturn getSource() + \"[\" + getSubscript() + \":=\" + getValue() + \"]\";\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Represents an <i>array initialiser expression</i> of the form\n\t\t * \"<code>[e1,...,en]</code>\" where <code>e1</code> ... <code>en</code>\n\t\t * are the <i>initialiser expressions</i>. Thus returns a new array made\n\t\t * up from those values resulting from the initialiser expressions.\n\t\t *\n\t\t * @author David J. Pearce\n\t\t *\n\t\t */\n\t\tpublic static class ArrayInitialiser extends Expr.Operator {\n\t\t\tpublic ArrayInitialiser(Expr... elements) {\n\t\t\t\tsuper(EXPR_arrinit, elements);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic ArrayInitialiser clone(SyntacticItem[] operands) {\n\t\t\t\treturn new ArrayInitialiser(ArrayUtils.toArray(Expr.class, operands));\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic String toString() {\n\t\t\t\treturn Arrays.toString(getAll());\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Represents an <i>array generator expression</i> of the form\n\t\t * \"<code>[e1;e2]</code>\" where <code>e1</code> is the <i>element\n\t\t * expression</i> and <code>e2</code> is the <i>length expression</i>.\n\t\t * This returns a new array whose length is determined by\n\t\t * <code>e2</code> and where every element has contains the value\n\t\t * determined by <code>e1</code>.\n\t\t *\n\t\t * @author David J. Pearce\n\t\t *\n\t\t */\n\t\tpublic static class ArrayGenerator extends Expr.Operator {\n\t\t\tpublic ArrayGenerator(Expr value, Expr length) {\n\t\t\t\tsuper(EXPR_arrgen, value, length);\n\t\t\t}\n\n\t\t\tpublic Expr getValue() {\n\t\t\t\treturn get(0);\n\t\t\t}\n\n\t\t\tpublic Expr getLength() {\n\t\t\t\treturn get(1);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic ArrayGenerator clone(SyntacticItem[] operands) {\n\t\t\t\treturn new ArrayGenerator((Expr) operands[0], (Expr) operands[1]);\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Represents an <i>array length expression</i> of the form\n\t\t * \"<code>|arr|</code>\" where <code>arr</code> is the <i>source\n\t\t * array</i>. This simply returns the length of array <code>arr</code>.\n\t\t * <code>e</code>.\n\t\t *\n\t\t * @author David J. Pearce\n\t\t *\n\t\t */\n\t\tpublic static class ArrayLength extends Expr.Operator {\n\t\t\tpublic ArrayLength(Expr src) {\n\t\t\t\tsuper(EXPR_arrlen, src);\n\t\t\t}\n\n\t\t\tpublic Expr getSource() {\n\t\t\t\treturn get(0);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic ArrayLength clone(SyntacticItem[] operands) {\n\t\t\t\treturn new ArrayLength((Expr) operands[0]);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic String toString() {\n\t\t\t\treturn \"|\" + getSource() + \"|\";\n\t\t\t}\n\t\t}\n\n\t\t// =========================================================================\n\t\t// Record Expressions\n\t\t// =========================================================================\n\n\t\t/**\n\t\t * Represents a <i>record access expression</i> of the form\n\t\t * \"<code>rec.f</code>\" where <code>rec</code> is the <i>source record</i>\n\t\t * and <code>f</code> is the <i>field</i>.\n\t\t *\n\t\t * @author David J. Pearce\n\t\t *\n\t\t */\n\t\tpublic static class RecordAccess extends AbstractSyntacticItem implements Expr {\n\t\t\tpublic RecordAccess(Expr lhs, Identifier rhs) {\n\t\t\t\tsuper(EXPR_recfield, lhs, rhs);\n\t\t\t}\n\n\t\t\tpublic Expr getSource() {\n\t\t\t\treturn (Expr) get(0);\n\t\t\t}\n\n\t\t\tpublic Identifier getField() {\n\t\t\t\treturn (Identifier) get(1);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic RecordAccess clone(SyntacticItem[] operands) {\n\t\t\t\treturn new RecordAccess((Expr) operands[0], (Identifier) operands[1]);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic String toString() {\n\t\t\t\treturn getSource() + \".\" + getField();\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Represents a <i>record initialiser</i> expression of the form\n\t\t * <code>{ f1: e1, ..., fn: en }</code> where <code>f1: e1</code> ...\n\t\t * <code>fn: en</code> are <i>field initialisers</code>. This returns a\n\t\t * new record where each field holds the value resulting from its\n\t\t * corresponding expression.\n\t\t *\n\t\t * @author David J. Pearce\n\t\t *\n\t\t */\n\t\tpublic static class RecordInitialiser extends AbstractSyntacticItem implements Expr {\n\t\t\tpublic RecordInitialiser(Pair<Identifier, Expr>... fields) {\n\t\t\t\tsuper(EXPR_recinit, fields);\n\t\t\t}\n\n\t\t\tpublic Pair<Identifier, Expr>[] getFields() {\n\t\t\t\treturn ArrayUtils.toArray(Pair.class, getAll());\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic RecordInitialiser clone(SyntacticItem[] operands) {\n\t\t\t\treturn new RecordInitialiser(ArrayUtils.toArray(Pair.class, operands));\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Represents a <i>record update expression</i> of the form\n\t\t * \"<code>rec[f:=e]</code>\" where <code>rec</code> is the <i>source\n\t\t * record</i>, <code>f</code> is the <i>field</i> and <code>e</code> is\n\t\t * the <i>value expression</i>. This returns a new record which is\n\t\t * equivalent to <code>rec</code> but where the element in field\n\t\t * <code>f</code> has the value resulting from <code>e</code>.\n\t\t *\n\t\t * @author David J. Pearce\n\t\t *\n\t\t */\n\t\tpublic static class RecordUpdate extends AbstractSyntacticItem implements Expr {\n\t\t\tpublic RecordUpdate(Expr lhs, Identifier mhs, Expr rhs) {\n\t\t\t\tsuper(EXPR_recupdt, lhs, mhs, rhs);\n\t\t\t}\n\n\t\t\tpublic Expr getSource() {\n\t\t\t\treturn (Expr) get(0);\n\t\t\t}\n\n\t\t\tpublic Identifier getField() {\n\t\t\t\treturn (Identifier) get(1);\n\t\t\t}\n\n\t\t\tpublic Expr getValue() {\n\t\t\t\treturn (Expr) get(2);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic RecordUpdate clone(SyntacticItem[] operands) {\n\t\t\t\treturn new RecordUpdate((Expr) operands[0], (Identifier) operands[1], (Expr) operands[2]);\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic String toString() {\n\t\t\t\treturn getSource() + \"{\" + getField() + \":=\" + getValue() + \"}\";\n\t\t\t}\n\t\t}\n\t}\n\n\t// ============================================================\n\t// Attributes\n\t// ============================================================\n\tpublic interface Attribute {\n//\t\tpublic class Proof implements wybs.lang.Attribute {\n//\t\t\tprivate final wytp.proof.Proof proof;\n//\n//\t\t\tpublic Proof(wytp.proof.Proof proof) {\n//\t\t\t\tthis.proof = proof;\n//\t\t\t}\n//\n//\t\t\tpublic wytp.proof.Proof getProof() {\n//\t\t\t\treturn proof;\n//\t\t\t}\n//\t\t}\n\t}\n\t// ===========================================================\n\t// Errors\n\t// ===========================================================\n\tpublic static class VerificationError extends AbstractSyntacticItem {\n\n\t\tpublic VerificationError(Declaration.Assert parent) {\n\t\t\tsuper(ERR_verify, parent);\n\t\t}\n\n\t\t@Override\n\t\tpublic SyntacticItem clone(SyntacticItem[] operands) {\n\t\t\treturn new VerificationError((Declaration.Assert) operands[0]);\n\t\t}\n\n\t}\n\n\t// ===========================================================\n\t// Misc\n\t// ===========================================================\n\tpublic static Tuple<Type> projectTypes(Tuple<VariableDeclaration> decls) {\n\t\tType[] types = new Type[decls.size()];\n\t\tfor (int i = 0; i != types.length; ++i) {\n\t\t\ttypes[i] = decls.get(i).getType();\n\t\t}\n\t\treturn new Tuple<>(types);\n\t}\n\n\t// ===========================================================\n\t// DEBUGGING SUPPORT\n\t// ===========================================================\n\n\tpublic static void println(Proof.Delta delta) {\n\t\tprint(delta);\n\t\tSystem.out.println();\n\t}\n\n\tpublic static void print(Proof.Delta delta) {\n\t\tProof.Delta.Set additions = delta.getAdditions();\n\t\tProof.Delta.Set removals = delta.getRemovals();\n\t\tfor (int i = 0; i != additions.size(); ++i) {\n\t\t\tif (i != 0) {\n\t\t\t\tSystem.out.print(\", \");\n\t\t\t}\n\t\t\tSystem.out.print(\"+\");\n\t\t\tprint(additions.get(i));\n\t\t}\n\t\tfor (int i = 0; i != removals.size(); ++i) {\n\t\t\tif (i != 0 || additions.size() > 0) {\n\t\t\t\tSystem.out.print(\", \");\n\t\t\t}\n\t\t\tSystem.out.print(\"-\");\n\t\t\tprint(removals.get(i));\n\t\t}\n\t}\n\n\tpublic static void println(SyntacticItem... items) {\n\t\tprint(items);\n\t\tSystem.out.println();\n\t}\n\n\tpublic static void print(SyntacticItem... items) {\n\t\tPrintWriter out = new PrintWriter(System.out);\n\t\tWyalFilePrinter printer = new WyalFilePrinter(out);\n\t\tfor (int i = 0; i != items.length; ++i) {\n\t\t\tif (i != 0) {\n\t\t\t\tout.print(\", \");\n\t\t\t}\n\t\t\tSyntacticItem item = items[i];\n\t\t\tif (item instanceof WyalFile.Expr) {\n\t\t\t\tprinter.writeExpression((Expr) item);\n\t\t\t} else if (item instanceof WyalFile.Stmt) {\n\t\t\t\tprinter.writeStatement((Stmt) item, 0);\n\t\t\t} else if (item instanceof WyalFile.Type) {\n\t\t\t\tprinter.writeType((Type) item);\n\t\t\t} else if (item instanceof WyalFile.VariableDeclaration) {\n\t\t\t\tprinter.writeVariableDeclaration((WyalFile.VariableDeclaration) item);\n\t\t\t} else if (item instanceof WyalFile.Tuple) {\n\t\t\t\tWyalFile.Tuple tuple = (WyalFile.Tuple) item;\n\t\t\t\tout.print(\"(\");\n\t\t\t\tfor (int j = 0; j != tuple.size(); ++j) {\n\t\t\t\t\tif (j != 0) {\n\t\t\t\t\t\tout.print(\",\");\n\t\t\t\t\t}\n\t\t\t\t\tout.flush();\n\t\t\t\t\tprint(tuple.get(j));\n\t\t\t\t}\n\t\t\t\tout.print(\")\");\n\t\t\t} else if (item == null) {\n\t\t\t\tout.print(\"null\");\n\t\t\t} else {\n\t\t\t\tout.print(item);\n\t\t\t}\n\t\t}\n\t\tout.flush();\n\t}\n}"
] | import wybs.lang.SyntacticItem;
import static wyal.lang.WyalFile.*;
import java.util.List;
import wyal.lang.*;
import wyal.lang.WyalFile.Declaration.Named;
import wyfs.util.ArrayUtils;
import wyfs.util.Pair;
import wyfs.lang.Path;
import wytp.types.TypeInferer.Environment;
import wytp.types.util.StdTypeEnvironment;
import wytp.types.TypeSystem;
import wyal.lang.WyalFile.Expr;
import wyal.lang.WyalFile.FieldDeclaration;
import wybs.lang.CompilationUnit;
import wybs.lang.SyntacticException;
import wyal.util.NameResolver;
import wyal.util.NameResolver.ResolutionError; | // Copyright 2011 The Whiley Project Developers
//
// 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 wyal.util;
/**
* <p>
* Implements a <i>flow-sensitive</i> type checker for WyAL source files which
* performs various tasks: firstly, it checks that the various kinds of
* expression are used correctly using flow typing to help; secondly, it checks
* that declarations are "sensible"; finally, it resolves function and macro
* invocations based on their type signature. Let's consider each of these in
* turn.
* </p>
*
* <p>
* <b>Type checking expressions</b>. The primary function of the type checker is
* to check that expressions are used correctly. For example, we expect
* arithmetic operators to operator on integer types. Likewise, we cannot
* perform an "array access" on an integer. The following illustrates such an
* incorrect program:
*
* <pre>
* assert:
* forall(int i, int j):
* i[j] == i[j]
* </pre>
*
* The above program is not "type safe" because variable <code>i</code> is used
* in a position where an array is expected. Another similar example is the
* following:
*
* <pre>
* assert:
* forall(int[] xs, bool i):
* xs[i] == xs[i]
* </pre>
*
* Arrays can only be accessed using integer values and, hence, the above fails
* because we are attempting to access array <code>xs</code> using a bool.
* </p>
* <p>
* To illustrate flow-sensitive typing (a.k.a <i>flow typing</i>), consider the
* following
*
* <pre>
* forall(int|null x):
* if:
* x is int
* x > 0
* then:
* x >= 0
* </pre>
*
* If the type checker only considered the declated type of <code>x</code> when
* typing the expression <code>x gt; 0</code> then it would report an error
* (i.e. because <code>int|null</code> is not of the expected type
* <code>int</code>). To resolve this, the type checker maintains a typing
* environment at each point in the program which includes any "refinements"
* which are known to be true at that point (for example, that
* <code>x is int</code> above). The current environment is used when type
* checking a given expression, meaning that the above does indeed type check.
* </p>
*
* <p>
* <b>Sanity checking declarations</b>. When declaring a type, function, macro
* or variable, it is possible to use a type which simply doesn't make sense. In
* such case, we want the type checker to report a problem (as we might not have
* been aware of this). The following illustrates such a case:
*
* <pre>
* type empty is ((int&!int) x)
* </pre>
*
* Here, the type <code>empty</code> defines a type which is equivalent to
* <code>void</code> and, as such, it is impossible to use this type! The type
* checker simply reports an error for any such types it encounters.
* </p>
*
* <p>
* <b>Resolving function or macro invocations</b>. The WyAL language supports
* <i>overloading</i> of functions and macros. It does this primarily because
* the Whiley language (for which WyAL is designed) supports this feature and we
* wish WyAL programs to "look like" whiley programs as much as possible. A
* simple example of this would be:
*
* <pre>
* function id(int x) -> (int r)
* function id(bool b) -> (bool r)
*
* assert:
* forall(int x, int y, int[] arr):
* if:
* id(x) == id(y)
* then:
* arr[id(x)] == arr[id(y)]
* </pre>
*
* We can see here that the correct type for <code>id()</code> must be
* determined in order of the expression <code>arr[id(x)]</code> to type check.
* When deciding which is the appropriate type signature for an invocation,
* there are several factors. Firstly, any candidates which are obviously
* nonsense must be discarded (e.g. <code>id(bool)</code> above, since
* <code>x</code> has type <code>int</code>). However, it is possible that there
* are multiple candidates and the type checker will always choose the "most
* precise" (or give up with an error if none exists). The following
* illustrates:
*
* <pre>
* function id(int x) -> (int r)
* function id(int|null xn) -> (bool r)
*
* assert:
* forall(int x, int y, int[] arr):
* if:
* id(x) == id(y)
* then:
* arr[id(x)] == arr[id(y)]
* </pre>
*
* In this example, the type checker will determine the signature
* <code>id(int)</code> for the invocation. This is because that is the most
* precise type which matches the given arguments.
* </p>
*
* @author David J. Pearce
*
*/
public class TypeChecker {
/**
* The enclosing WyAL file being checked.
*/
private final WyalFile parent;
/**
* The originating source of this file (which may be itself). The need for
* this is somewhat questionable.
*/
private final Path.Entry<? extends CompilationUnit> originatingEntry;
/**
* The type system encapsulates the core algorithms for type simplification
* and subtyping testing.
*/ | private TypeSystem types; | 3 |
Tonius/E-Mobile | src/main/java/tonius/emobile/network/message/MessageCellphoneHome.java | [
"public class EMConfig {\n \n public static Configuration config;\n public static List<ConfigSection> configSections = new ArrayList<ConfigSection>();\n \n public static final ConfigSection sectionGeneral = new ConfigSection(\"General Settings\", \"general\");\n public static final ConfigSection sectionTweaks = new ConfigSection(\"Tweaks Settings\", \"tweaks\");\n public static final ConfigSection sectionFluxCellphone = new ConfigSection(\"Fluxed Ender Cellphone Settings\", \"fluxCellphone\");\n \n // general default\n public static final boolean allowTeleportPlayers_default = true;\n public static final boolean allowTeleportHome_default = true;\n public static final boolean allowTeleportSpawn_default = true;\n public static final int[] dimensionsBlacklist_default = new int[0];\n public static final boolean dimensionsWhitelist_default = false;\n public static final String[] bedBlocks_default = new String[] { \"com.carpentersblocks.block.BlockCarpentersBed\" };\n \n // tweaks default\n public static final int enderPearlStackSize_default = 16;\n \n // fluxCellphone default\n public static final boolean fluxCellphoneEnabled_default = true;\n public static final int fluxCellphoneMaxEnergy_default = 600000;\n public static final int fluxCellphoneMaxInput_default = 2000;\n public static final int fluxCellphoneEnergyPerUse_default = 30000;\n \n // general\n public static boolean allowTeleportPlayers = allowTeleportHome_default;\n public static boolean allowTeleportHome = allowTeleportHome_default;\n public static boolean allowTeleportSpawn = allowTeleportHome_default;\n public static int[] dimensionsBlacklist = dimensionsBlacklist_default;\n public static boolean dimensionsWhitelist = dimensionsWhitelist_default;\n public static List<String> bedBlocks = Arrays.asList(bedBlocks_default);\n \n // tweaks\n public static int enderPearlStackSize = enderPearlStackSize_default;\n \n // fluxCellphone\n public static boolean fluxCellphoneEnabled = fluxCellphoneEnabled_default;\n public static int fluxCellphoneMaxEnergy = fluxCellphoneMaxEnergy_default;\n public static int fluxCellphoneMaxInput = fluxCellphoneMaxInput_default;\n public static int fluxCellphoneEnergyPerUse = fluxCellphoneEnergyPerUse_default;\n \n public static void preInit(FMLPreInitializationEvent evt) {\n FMLCommonHandler.instance().bus().register(new EMConfig());\n config = new Configuration(evt.getSuggestedConfigurationFile());\n EMobile.logger.info(\"Loading configuration file\");\n syncConfig();\n }\n \n public static void syncConfig() {\n try {\n processConfig();\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n config.save();\n }\n if (EMobile.cellphoneRF != null) {\n EMobile.cellphoneRF.maxEnergy = fluxCellphoneMaxEnergy;\n EMobile.cellphoneRF.maxInput = fluxCellphoneMaxInput;\n EMobile.cellphoneRF.energyPerUse = fluxCellphoneEnergyPerUse;\n }\n }\n \n @SubscribeEvent\n public void onConfigChanged(OnConfigChangedEvent evt) {\n onConfigChanged(evt.modID);\n }\n \n public static void onConfigChanged(String modID) {\n if (modID.equals(\"emobile\")) {\n EMobile.logger.info(\"Updating configuration file\");\n syncConfig();\n }\n }\n \n public static void processConfig() {\n allowTeleportPlayers = config.get(sectionGeneral.name, \"Allow teleporting to players\", allowTeleportPlayers_default, \"When enabled, the Ender Cellphone may be used to teleport to other players.\").getBoolean(allowTeleportPlayers_default);\n allowTeleportHome = config.get(sectionGeneral.name, \"Allow teleporting home\", allowTeleportHome_default, \"When enabled, the Ender Cellphone may be used by players to teleport to their beds.\").getBoolean(allowTeleportHome_default);\n allowTeleportSpawn = config.get(sectionGeneral.name, \"Allow teleporting to spawn\", allowTeleportSpawn_default, \"When enabled, the Ender Cellphone may be used to teleport to the world spawn.\").getBoolean(allowTeleportSpawn_default);\n dimensionsBlacklist = config.get(sectionGeneral.name, \"Dimensions Blacklist\", dimensionsBlacklist_default, \"The blacklist of dimension ids that can be teleported to or from using the Ender Cellphone. These dimensions may not be teleported to or from.\").getIntList();\n dimensionsWhitelist = config.get(sectionGeneral.name, \"Dimensions Whitelist\", dimensionsWhitelist_default, \"If enabled, the blacklist of dimension ids will be treated as a whitelist instead. The dimensions will then be the only dimensions that may be teleported to or from.\").getBoolean(dimensionsWhitelist_default);\n bedBlocks = Arrays.asList(config.get(sectionGeneral.name, \"Bed Blocks\", bedBlocks_default, \"A list of full class names of Blocks that count as beds. Use this to add support for beds from mods.\").getStringList());\n \n enderPearlStackSize = config.get(sectionTweaks.name, \"Ender Pearl stack size\", enderPearlStackSize_default, \"This config option can be used to change the maximum stack size of Ender Pearls.\").setMinValue(1).setMaxValue(512).setRequiresMcRestart(true).getInt(enderPearlStackSize_default);\n \n fluxCellphoneEnabled = config.get(sectionFluxCellphone.name, \"Enabled\", fluxCellphoneEnabled_default, \"Whether the Fluxed Ender Cellphone is enabled at all.\").setRequiresMcRestart(true).getBoolean();\n fluxCellphoneMaxEnergy = config.get(sectionFluxCellphone.name, \"Max Energy\", fluxCellphoneMaxEnergy_default, \"The maximum amount of RF that a Fluxed Ender Cellphone can store.\").setMinValue(1).getInt(fluxCellphoneMaxEnergy_default);\n fluxCellphoneMaxInput = config.get(sectionFluxCellphone.name, \"Max Input\", fluxCellphoneMaxInput_default, \"The maximum RF/t rate that the Fluxed Ender Cellphone can be charged with.\").setMinValue(0).getInt(fluxCellphoneMaxInput_default);\n fluxCellphoneEnergyPerUse = config.get(sectionFluxCellphone.name, \"Energy Per Use\", fluxCellphoneEnergyPerUse_default, \"The amount of RF that the Fluxed Ender Cellphone consumes when teleporting.\").setMinValue(0).getInt(fluxCellphoneEnergyPerUse_default);\n }\n \n public static class ConfigSection {\n \n public String name;\n public String id;\n \n public ConfigSection(String name, String id) {\n this.name = name;\n this.id = id;\n EMConfig.configSections.add(this);\n }\n \n public String toLowerCase() {\n return this.name.toLowerCase();\n }\n \n }\n \n}",
"public class ItemCellphone extends Item {\n \n public ItemCellphone() {\n this.setMaxStackSize(1);\n this.setUnlocalizedName(\"emobile.cellphone\");\n this.setTextureName(\"emobile:cellphone\");\n this.setCreativeTab(CreativeTabs.tabTools);\n }\n \n public boolean useFuel(ItemStack cellphone, EntityPlayer player) {\n return new InventoryCellphone(cellphone).useFuel();\n }\n \n @Override\n public ItemStack onItemRightClick(ItemStack cellphone, World world, EntityPlayer player) {\n if (!world.isRemote) {\n player.openGui(EMobile.instance, EMGuiHandler.CELLPHONE_PEARL, world, 0, 0, 0);\n }\n \n return cellphone;\n }\n \n @Override\n @SideOnly(Side.CLIENT)\n public void addInformation(ItemStack itemStack, EntityPlayer player, List list, boolean bool) {\n list.add(String.format(StringUtils.translate(\"tooltip.cellphone.pearls\"), new InventoryCellphone(itemStack).getStoredPearls()));\n }\n \n}",
"public class CellphoneSessionLocation extends CellphoneSessionBase {\n \n protected EntityPlayerMP player;\n protected String unlocalizedLocation;\n protected int dimension;\n protected int posX;\n protected int posY;\n protected int posZ;\n \n public CellphoneSessionLocation(int duration, String unlocalizedLocation, EntityPlayerMP player, int dimension, int posX, int posY, int posZ) {\n super(duration);\n this.unlocalizedLocation = unlocalizedLocation;\n this.player = player;\n this.posX = posX;\n this.posY = posY;\n this.posZ = posZ;\n \n ServerUtils.sendChatToPlayer(player.getCommandSenderName(), String.format(StringUtils.translate(\"chat.cellphone.start.location\"), StringUtils.translate(unlocalizedLocation)), EnumChatFormatting.GOLD);\n }\n \n @Override\n public void tick() {\n if (!ServerUtils.canPlayerTeleport(this.player)) {\n this.invalidate();\n return;\n } else if (!TeleportUtils.isDimTeleportAllowed(this.player.dimension, this.dimension)) {\n String msg = String.format(StringUtils.translate(\"chat.cellphone.cancel.dimension\"), this.player.worldObj.provider.getDimensionName(), this.player.mcServer.worldServerForDimension(this.dimension).provider.getDimensionName());\n ServerUtils.sendChatToPlayer(this.player.getCommandSenderName(), msg, EnumChatFormatting.RED);\n this.invalidate();\n return;\n }\n \n if (this.ticks % Math.max(this.countdownSecs - 2, 1) == 0) {\n ServerUtils.sendDiallingParticles(this.player);\n ServerUtils.sendDiallingParticles(this.dimension, this.posX, this.posY, this.posZ);\n }\n \n super.tick();\n }\n \n @Override\n public void onCountdownSecond() {\n if (this.countdownSecs <= 3 || this.countdownSecs % 2 == 0) {\n this.player.addChatMessage(new ChatComponentText(StringUtils.PINK + String.format(StringUtils.translate(\"chat.cellphone.countdown\"), this.countdownSecs)));\n }\n }\n \n @Override\n public void onCountdownFinished() {\n this.player.worldObj.playSoundAtEntity(this.player, \"mob.endermen.portal\", 1.0F, 1.0F);\n ServerUtils.sendTeleportParticles(this.player);\n TeleportUtils.teleportPlayerToPos(this.player, this.dimension, this.posX, this.posY, this.posZ, false);\n this.player.worldObj.playSoundAtEntity(this.player, \"mob.endermen.portal\", 1.0F, 1.0F);\n ServerUtils.sendTeleportParticles(this.player);\n ServerUtils.sendChatToPlayer(this.player.getCommandSenderName(), String.format(StringUtils.translate(\"chat.cellphone.success.location\"), StringUtils.translate(this.unlocalizedLocation)), EnumChatFormatting.GOLD);\n }\n \n @Override\n public boolean isPlayerInSession(EntityPlayer player) {\n return this.player.equals(player);\n }\n \n @Override\n public void cancel(String canceledBy) {\n super.cancel(canceledBy);\n ServerUtils.sendChatToPlayer(this.player.getCommandSenderName(), StringUtils.translate(\"chat.cellphone.cancel\"), EnumChatFormatting.RED);\n }\n \n}",
"public class CellphoneSessionsHandler {\n \n private static List<CellphoneSessionBase> sessions = new ArrayList<CellphoneSessionBase>();\n private static Map<EntityPlayerMP, Map<EntityPlayerMP, Boolean>> acceptedPlayers = new HashMap<EntityPlayerMP, Map<EntityPlayerMP, Boolean>>();\n \n public static void addSession(CellphoneSessionBase session) {\n sessions.add(session);\n }\n \n public static void clearSessions() {\n sessions.clear();\n acceptedPlayers.clear();\n }\n \n public static boolean isPlayerInSession(EntityPlayerMP player) {\n for (CellphoneSessionBase session : sessions) {\n if (session.isPlayerInSession(player)) {\n return true;\n }\n }\n return false;\n }\n \n public static Map<EntityPlayerMP, Boolean> getAcceptedPlayersForPlayer(EntityPlayerMP player) {\n Map<EntityPlayerMP, Boolean> players = acceptedPlayers.get(player);\n if (players == null) {\n players = new HashMap<EntityPlayerMP, Boolean>();\n }\n acceptedPlayers.put(player, players);\n \n return players;\n }\n \n public static boolean acceptPlayer(EntityPlayerMP accepting, EntityPlayerMP accepted, boolean perma) {\n if (!isPlayerAccepted(accepting, accepted)) {\n getAcceptedPlayersForPlayer(accepting).put(accepted, perma);\n if (perma) {\n NBTTagList permaAccepted = accepting.getEntityData().getTagList(\"EMobile.PermaAccepted\", 8);\n permaAccepted.appendTag(new NBTTagString(accepted.getCommandSenderName()));\n accepting.getEntityData().setTag(\"EMobile.PermaAccepted\", permaAccepted);\n }\n return true;\n } else {\n return false;\n }\n }\n \n public static boolean deacceptPlayer(EntityPlayerMP deaccepting, EntityPlayerMP deaccepted, boolean force) {\n if (isPlayerAccepted(deaccepting, deaccepted)) {\n if (!getAcceptedPlayersForPlayer(deaccepting).get(deaccepted) || force) {\n getAcceptedPlayersForPlayer(deaccepting).remove(deaccepted);\n String deacceptedName = deaccepted.getCommandSenderName();\n NBTTagList permaAccepted = deaccepting.getEntityData().getTagList(\"EMobile.PermaAccepted\", 8);\n for (int i = 0; i < permaAccepted.tagCount(); i++) {\n if (permaAccepted.getStringTagAt(i).equals(deacceptedName)) {\n permaAccepted.removeTag(i);\n }\n }\n deaccepting.getEntityData().setTag(\"EMobile.PermaAccepted\", permaAccepted);\n }\n return true;\n } else {\n return false;\n }\n }\n \n public static boolean isPlayerAccepted(EntityPlayerMP acceptor, EntityPlayerMP query) {\n String queryName = query.getCommandSenderName();\n NBTTagList permaAccepted = acceptor.getEntityData().getTagList(\"EMobile.PermaAccepted\", 8);\n for (int i = 0; i < permaAccepted.tagCount(); i++) {\n if (permaAccepted.getStringTagAt(i).equals(queryName)) {\n getAcceptedPlayersForPlayer(acceptor).put(query, true);\n return true;\n }\n }\n return getAcceptedPlayersForPlayer(acceptor).containsKey(query);\n }\n \n public static void cancelSessionsForPlayer(EntityPlayer player) {\n for (CellphoneSessionBase session : sessions) {\n if (session.isPlayerInSession(player)) {\n session.cancel(player.getCommandSenderName());\n }\n }\n }\n \n @SubscribeEvent\n public void tickEnd(ServerTickEvent evt) {\n if (evt.phase == Phase.END) {\n Iterator<CellphoneSessionBase> itr = sessions.iterator();\n while (itr.hasNext()) {\n CellphoneSessionBase session = itr.next();\n session.tick();\n if (!session.isValid()) {\n itr.remove();\n }\n }\n }\n }\n \n}",
"public class ServerUtils {\n \n public static EntityPlayerMP getPlayerOnServer(String name) {\n return MinecraftServer.getServer().getConfigurationManager().func_152612_a(name);\n }\n \n public static boolean isPlayerConnected(EntityPlayerMP player) {\n return MinecraftServer.getServer().getConfigurationManager().playerEntityList.contains(player);\n }\n \n public static boolean canPlayerTeleport(EntityPlayerMP player) {\n return player != null && isPlayerConnected(player) && !player.isDead;\n }\n \n public static void sendGlobalChat(String chat) {\n MinecraftServer.getServer().getConfigurationManager().sendChatMsg(new ChatComponentText(chat));\n }\n \n public static void sendChatToPlayer(String player, String chat, EnumChatFormatting color) {\n EntityPlayerMP playerEntity = getPlayerOnServer(player);\n if (playerEntity != null) {\n ChatComponentText component = new ChatComponentText(chat);\n component.getChatStyle().setColor(color);\n playerEntity.addChatMessage(component);\n }\n }\n \n public static void sendChatToPlayer(String player, String chat) {\n sendChatToPlayer(player, chat, EnumChatFormatting.WHITE);\n }\n \n public static void sendDiallingSound(EntityPlayer player) {\n PacketHandler.instance.sendToAllAround(new MessageDiallingSound(player.getEntityId()), new TargetPoint(player.dimension, player.posX, player.posY, player.posZ, 256));\n }\n \n public static void sendDiallingParticles(EntityPlayer player) {\n PacketHandler.instance.sendToAllAround(new MessageDiallingParticles(player.posX, player.posY + 0.8D, player.posZ), new TargetPoint(player.dimension, player.posX, player.posY, player.posZ, 256));\n }\n \n public static void sendDiallingParticles(int dimension, int posX, int posY, int posZ) {\n PacketHandler.instance.sendToAllAround(new MessageDiallingParticles(posX + 0.5D, posY + 0.5D, posZ + 0.5D), new TargetPoint(dimension, posX + 0.5D, posY + 0.5D, posZ + 0.5D, 256));\n }\n \n public static void sendTeleportParticles(EntityPlayer player) {\n PacketHandler.instance.sendToAllAround(new MessageTeleportParticles(player.posX, player.posY + 0.8D, player.posZ), new TargetPoint(player.dimension, player.posX, player.posY, player.posZ, 256));\n }\n \n}",
"public class StringUtils {\n private static DecimalFormat formatter = new DecimalFormat(\"###,###\");\n \n public static final String BLACK = (char) 167 + \"0\";\n public static final String BLUE = (char) 167 + \"1\";\n public static final String GREEN = (char) 167 + \"2\";\n public static final String TEAL = (char) 167 + \"3\";\n public static final String RED = (char) 167 + \"4\";\n public static final String PURPLE = (char) 167 + \"5\";\n public static final String ORANGE = (char) 167 + \"6\";\n public static final String LIGHT_GRAY = (char) 167 + \"7\";\n public static final String GRAY = (char) 167 + \"8\";\n public static final String LIGHT_BLUE = (char) 167 + \"9\";\n public static final String BRIGHT_GREEN = (char) 167 + \"a\";\n public static final String BRIGHT_BLUE = (char) 167 + \"b\";\n public static final String LIGHT_RED = (char) 167 + \"c\";\n public static final String PINK = (char) 167 + \"d\";\n public static final String YELLOW = (char) 167 + \"e\";\n public static final String WHITE = (char) 167 + \"f\";\n \n public static final String OBFUSCATED = (char) 167 + \"k\";\n public static final String BOLD = (char) 167 + \"l\";\n public static final String STRIKETHROUGH = (char) 167 + \"m\";\n public static final String UNDERLINE = (char) 167 + \"n\";\n public static final String ITALIC = (char) 167 + \"o\";\n public static final String END = (char) 167 + \"r\";\n \n public static boolean isAltKeyDown() {\n return Keyboard.isKeyDown(Keyboard.KEY_LMENU) || Keyboard.isKeyDown(Keyboard.KEY_RMENU);\n }\n \n public static boolean isControlKeyDown() {\n return Keyboard.isKeyDown(Keyboard.KEY_LCONTROL) || Keyboard.isKeyDown(Keyboard.KEY_RCONTROL);\n }\n \n public static boolean isShiftKeyDown() {\n return Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) || Keyboard.isKeyDown(Keyboard.KEY_RSHIFT);\n }\n \n public static String getScaledNumber(int number) {\n return getScaledNumber(number, 2);\n }\n \n public static String getScaledNumber(int number, int minDigits) {\n String numString = \"\";\n \n int numMod = 10 * minDigits;\n \n if (number > 100000 * numMod) {\n numString += number / 1000000 + \"M\";\n } else if (number > 100 * numMod) {\n numString += number / 1000 + \"k\";\n } else {\n numString += number;\n }\n return numString;\n }\n \n public static String getFormattedNumber(int number) {\n return formatter.format(number);\n }\n \n public static String getShiftText() {\n return LIGHT_GRAY + String.format(translate(\"tooltip.holdShift\"), YELLOW + ITALIC + \"Shift\" + END + LIGHT_GRAY);\n }\n \n public static String translate(String unlocalized) {\n return translate(unlocalized, true);\n }\n \n public static String translate(String unlocalized, boolean prefix) {\n if (prefix) {\n return StatCollector.translateToLocal(\"emobile.\" + unlocalized);\n }\n return StatCollector.translateToLocal(unlocalized);\n }\n \n public static void addGaugeTooltip(List lines, String name, String unit, int amount, int maxAmount) {\n if (name != null) {\n lines.add(name);\n }\n if (maxAmount > 0) {\n lines.add(amount + \" / \" + maxAmount + \" \" + unit);\n } else {\n lines.add(amount + \" \" + unit);\n }\n }\n \n}",
"public class TeleportUtils {\n \n public static void teleportPlayerToPlayer(EntityPlayerMP from, EntityPlayerMP to) {\n from.mountEntity(null);\n if (from.riddenByEntity != null) {\n from.riddenByEntity.mountEntity(null);\n }\n if (from.dimension != to.dimension) {\n teleportPlayerToDimension(from, to.dimension, to.mcServer.getConfigurationManager());\n }\n from.setPositionAndUpdate(to.posX + 0.5D, to.posY + 0.5D, to.posZ + 0.5D);\n }\n \n public static boolean teleportPlayerToPos(EntityPlayerMP player, int dimension, int posX, int posY, int posZ, boolean simulate) {\n if (!DimensionManager.isDimensionRegistered(dimension)) {\n return false;\n }\n \n if (!simulate) {\n player.mountEntity(null);\n if (player.riddenByEntity != null) {\n player.riddenByEntity.mountEntity(null);\n }\n if (player.dimension != dimension) {\n teleportPlayerToDimension(player, dimension, player.mcServer.getConfigurationManager());\n }\n player.setPositionAndUpdate(posX + 0.5D, posY + 0.5D, posZ + 0.5D);\n }\n \n return true;\n }\n \n public static boolean isDimTeleportAllowed(int from, int to) {\n if (from == to) {\n return true;\n }\n \n if (!EMConfig.dimensionsWhitelist) {\n if (configContainsDim(from) || configContainsDim(to)) {\n return false;\n }\n return true;\n } else {\n if (configContainsDim(from) && configContainsDim(to)) {\n return true;\n }\n return false;\n }\n }\n \n public static boolean configContainsDim(int dim) {\n for (int i : EMConfig.dimensionsBlacklist) {\n if (i == dim) {\n return true;\n }\n }\n return false;\n }\n \n public static void teleportEntityToWorld(Entity entity, WorldServer oldWorld, WorldServer newWorld) {\n WorldProvider pOld = oldWorld.provider;\n WorldProvider pNew = newWorld.provider;\n double moveFactor = pOld.getMovementFactor() / pNew.getMovementFactor();\n double x = entity.posX * moveFactor;\n double z = entity.posZ * moveFactor;\n \n oldWorld.theProfiler.startSection(\"placing\");\n x = MathHelper.clamp_double(x, -29999872, 29999872);\n z = MathHelper.clamp_double(z, -29999872, 29999872);\n \n if (entity.isEntityAlive()) {\n entity.setLocationAndAngles(x, entity.posY, z, entity.rotationYaw, entity.rotationPitch);\n newWorld.spawnEntityInWorld(entity);\n newWorld.updateEntityWithOptionalForce(entity, false);\n }\n \n oldWorld.theProfiler.endSection();\n \n entity.setWorld(newWorld);\n }\n \n public static void teleportPlayerToDimension(EntityPlayerMP player, int dimension, ServerConfigurationManager manager) {\n int oldDim = player.dimension;\n WorldServer worldserver = manager.getServerInstance().worldServerForDimension(player.dimension);\n player.dimension = dimension;\n WorldServer worldserver1 = manager.getServerInstance().worldServerForDimension(player.dimension);\n player.playerNetServerHandler.sendPacket(new S07PacketRespawn(player.dimension, player.worldObj.difficultySetting, player.worldObj.getWorldInfo().getTerrainType(), player.theItemInWorldManager.getGameType()));\n worldserver.removePlayerEntityDangerously(player);\n player.isDead = false;\n teleportEntityToWorld(player, worldserver, worldserver1);\n manager.func_72375_a(player, worldserver);\n player.playerNetServerHandler.setPlayerLocation(player.posX, player.posY, player.posZ, player.rotationYaw, player.rotationPitch);\n player.theItemInWorldManager.setWorld(worldserver1);\n manager.updateTimeAndWeatherForPlayer(player, worldserver1);\n manager.syncPlayerInventory(player);\n Iterator<PotionEffect> iterator = player.getActivePotionEffects().iterator();\n \n while (iterator.hasNext()) {\n PotionEffect potioneffect = iterator.next();\n player.playerNetServerHandler.sendPacket(new S1DPacketEntityEffect(player.getEntityId(), potioneffect));\n }\n FMLCommonHandler.instance().firePlayerChangedDimensionEvent(player, oldDim, dimension);\n }\n \n}"
] | import io.netty.buffer.ByteBuf;
import net.minecraft.block.Block;
import net.minecraft.block.BlockBed;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ChunkCoordinates;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.world.World;
import tonius.emobile.config.EMConfig;
import tonius.emobile.item.ItemCellphone;
import tonius.emobile.session.CellphoneSessionLocation;
import tonius.emobile.session.CellphoneSessionsHandler;
import tonius.emobile.util.ServerUtils;
import tonius.emobile.util.StringUtils;
import tonius.emobile.util.TeleportUtils;
import cpw.mods.fml.common.network.ByteBufUtils;
import cpw.mods.fml.common.network.simpleimpl.IMessage;
import cpw.mods.fml.common.network.simpleimpl.IMessageHandler;
import cpw.mods.fml.common.network.simpleimpl.MessageContext; | package tonius.emobile.network.message;
public class MessageCellphoneHome implements IMessage, IMessageHandler<MessageCellphoneHome, IMessage> {
private String player;
public MessageCellphoneHome() {
}
public MessageCellphoneHome(String player) {
this.player = player;
}
@Override
public void fromBytes(ByteBuf buf) {
this.player = ByteBufUtils.readUTF8String(buf);
}
@Override
public void toBytes(ByteBuf buf) {
ByteBufUtils.writeUTF8String(buf, this.player);
}
@Override
public IMessage onMessage(MessageCellphoneHome msg, MessageContext ctx) { | if (EMConfig.allowTeleportHome) { | 0 |
tsauvine/omr | src/omr/gui/calibration/CalibratePanel.java | [
"public class AnalyzeSheetsTask extends Task {\n\n private Project project;\n\n public AnalyzeSheetsTask(Project project, Observer observer) {\n super(observer);\n \n this.project = project;\n }\n \n @Override\n public void run() {\n SheetStructure structure = project.getSheetStructure();\n SheetsContainer sheets = project.getSheetsContainer();\n\n Histogram histogram = project.getHistogram(); \n histogram.reset();\n \n this.setEstimatedOperationsCount(sheets.size());\n this.setStatusText(\"Processing sheets\");\n \n for (Sheet sheet : sheets) {\n try {\n sheet.analyze(structure, project.getHistogram());\n } catch (OutOfMemoryError e) {\n System.err.println(\"Out of memory when analyzing sheets.\");\n return;\n } catch (IOException e) {\n System.err.println(e);\n break;\n }\n \n // Publish progress\n this.increaseCompletedOperationsCount();\n }\n \n // Calculate answers\n project.calculateThreshold();\n project.calculateAnswers();\n \n this.finished();\n }\n\n}",
"public class Project implements Observer {\n /**\n * Thresholding modes.\n * PER_SHEET: thresholds are set to each sheet independently \n * GLOBAL: all sheets have same thresholds\n */\n public enum ThresholdingStrategy {PER_SHEET, GLOBAL};\n \n private SheetsContainer answerSheets;\n private SheetStructure sheetStructure; // Contains information about the positions of question groups etc.\n \n private Histogram histogram; // Global histogram\n private ThresholdingStrategy thresholdingStrategy;\n private GradingScheme gradingScheme;\n \n public Project() {\n this.answerSheets = new SheetsContainer();\n \n this.sheetStructure = new SheetStructure();\n this.sheetStructure.addObserver(this);\n \n this.histogram = new Histogram();\n this.thresholdingStrategy = ThresholdingStrategy.PER_SHEET;\n this.gradingScheme = new GradingScheme();\n }\n \n /**\n * Tells whether the project has unsaved modifications or is it safe to quit.\n */\n public boolean isChanged() {\n \t// TODO\n return true;\n }\n \n /**\n * Adds answer sheets to the project.\n * @param files Array of files to add\n */\n public void addAnswerSheets(File[] files) throws IOException {\n this.answerSheets.importSheets(files);\n }\n \n /**\n * Removes answer sheets from the project.\n */\n public void removeAnswerSheets(Sheet[] sheets) {\n this.answerSheets.removeSheets(sheets);\n }\n \n /**\n * Returns the list of answer sheets.\n */\n public AbstractList<Sheet> getAnswerSheets() {\n return this.answerSheets.getSheets();\n }\n\n /**\n * Returns the SheetsContainer which contains all answer sheets and is iterable.\n * @return\n */\n public SheetsContainer getSheetsContainer() {\n return this.answerSheets;\n }\n \n /**\n * Returns the SheetStructure which contains information about the positions and properties of question groups and registration markers.\n */\n public SheetStructure getSheetStructure() {\n return this.sheetStructure;\n }\n\n /**\n * Returns the GradingScheme that can be used to convert answers into points.\n */\n public GradingScheme getGradingScheme() {\n return this.gradingScheme;\n }\n \n /**\n * Returns the global histogram of all bubbles in all answer sheets.\n */\n public Histogram getHistogram() {\n return this.histogram;\n }\n \n /**\n * Returns the current thresholding mode. See enum ThresholdingStrategy.\n */\n public ThresholdingStrategy getThresholdingStrategy() {\n return thresholdingStrategy;\n }\n\n /**\n * Sets thresholding mode. See enum ThresholdingStrategy.\n */\n public void setThresholdingStrategy(ThresholdingStrategy thresholdingStrategy) {\n this.thresholdingStrategy = thresholdingStrategy;\n }\n \n \n /** \n * Automatically sets thresholds to sensible values. \n */\n public void calculateThreshold() {\n histogram.guessThreshold();\n }\n \n /**\n * Calculates all answers using the global black and white thresholds (set in the global histogram).\n */\n public void calculateAnswers() {\n int blackThreshold = histogram.getBlackThreshold();\n int whiteThreshold = histogram.getWhiteThreshold();\n \n for (Sheet sheet : answerSheets) {\n if (thresholdingStrategy == ThresholdingStrategy.GLOBAL) { \n for (QuestionGroup group : sheetStructure.getQuestionGroups()) {\n sheet.calculateAnswers(group, blackThreshold, whiteThreshold);\n }\n } else {\n for (QuestionGroup group : sheetStructure.getQuestionGroups()) {\n sheet.calculateAnswers(group, sheet.getHistogram().getBlackThreshold(), sheet.getHistogram().getWhiteThreshold());\n }\n }\n }\n }\n \n /**\n * Notified by sheet structure when it changes.\n */\n public void update(Observable source, Object event) {\n \tif (SheetStructureEvent.STRUCTURE_CHANGED == event || \n \t SheetStructureEvent.BUBBLE_POSITIONS_CHANGED == event) {\n \t this.answerSheets.invalidateBrightnesses();\n \t} else if (SheetStructureEvent.REGISTRATION_CHANGED == event) {\n \t this.answerSheets.invalidateRegistration();\n \t}\n }\n \n}",
"public class Sheet extends Observable {\n\n protected String id; // Unique id of this sheet\n protected String fileName; // e.g. AnswerSheet001.jpg\n protected String filePath; // e.g. /home/teacher/AnswerSheet001.jpg\n\n protected String studentId; // The whole student id with number and letter\n protected String studentIdNumber; // Number part of the student id\n protected String studentIdLetter; // Check letter of the student id\n\n private HashMap<QuestionGroup, int[][]> brightness; // [row][column]\n private HashMap<RegistrationMarker, Point> markers; // Detected marker positions\n private HashMap<QuestionGroup, int[][]> choices; // Choices for each question group. [row][column] negative = black, 0 = uncertain, postive = white\n private HashMap<QuestionGroup, int[][]> overrideChoices; // negative = force black, 0 = auto, postive = force white\n protected String userId; // Id of the student\n\n private Histogram histogram;\n\n protected int rotation; // Rotation in degrees. 0, 90, 180 or 270\n protected AffineTransform transformation; // Transformation that aligns the image with the reference sheet\n protected BufferedImage rawBuffer; // Unaligned, un-zoomed buffer. The buffer is kept cached as long as the sheet has registered observers. Always TYPE_INT_RGB\n\n\n public Dimension dimension(){\n if ( rawBuffer == null ){\n return new Dimension(0,0);\n }\n return new Dimension( rawBuffer.getWidth(), rawBuffer.getHeight());\n }\n\n public enum SheetStatus {\n NOT_ANALYZED(\"?\"),\n ANALYZED_WITH_ERRORS(\"!\"),\n ANALYZED(\"OK\");\n\n private String text;\n\n private SheetStatus(String text) {\n this.text = text;\n }\n\n @Override\n public String toString() {\n return this.text;\n }\n }\n\n ;\n\n private boolean answersValid; // True if the sheet does not contain uncertain answers\n\n\n public Sheet(String filePath, String fileName) {\n this.fileName = fileName;\n this.filePath = filePath;\n this.id = fileName;\n this.rotation = 0;\n\n this.studentId = \"\";\n this.studentIdNumber = \"\";\n this.studentIdLetter = \"\";\n\n this.histogram = new Histogram(false);\n\n this.transformation = new AffineTransform();\n\n this.answersValid = false;\n }\n\n /**\n * Sets the unique id of this sheet. This is used in serialization.\n */\n public void setId(String id) {\n this.id = id;\n }\n\n /**\n * Returns the unique id of this sheet. This is used in serialization.\n */\n public String getId() {\n return this.id;\n }\n\n /**\n * Sets the student id.\n */\n public void setStudentId(String studentId) {\n this.studentId = studentId;\n }\n\n /**\n * Returns the student id.\n */\n public String getStudentId() {\n return this.studentId;\n }\n\n /**\n * Returns true if the loaded file can be read by the OMR algorithm, ie. the file is in a proper format.\n */\n public boolean isValidFile() {\n // TODO: validate file\n return true;\n }\n\n /**\n * Returns the name of the sheet image file without the path, e.g. AnswerSheet001.jpg\n */\n public String getFileName() {\n return fileName;\n }\n\n /**\n * Returns the full path of the sheet image file, e.g. /home/teacher/AnswerSheet001.jpg\n */\n public String getFilePath() {\n return filePath;\n }\n\n /**\n * Sets the name of the sheet image file without the path.\n *\n * @param fileName e.g. AnswerSheet001.jpg\n */\n public void setFileName(String fileName) {\n this.fileName = fileName;\n }\n\n /**\n * Returns the histogram of this sheet. The histogram is empty until the sheet has been analyzed.\n */\n public Histogram getHistogram() {\n return this.histogram;\n }\n\n /**\n * Returns the page of a multi-page document that this sheet represents.\n *\n * @return Page [0,n]. 0 if this is not a multi-page document.\n */\n public int getPage() {\n return 0; // Multi-page versions will override this\n }\n\n /**\n * Returns a text representation of this sheet. Use for debugging only. For serious purposes, use getStudentId(), getFileName(), etc.\n */\n @Override\n public String toString() {\n return this.id;\n }\n\n /**\n * Returns information whether the sheet has been analyzed and does it contain uncertain bubbles. See enum SheetStatus.\n */\n public SheetStatus getStatus() {\n if (answersValid) {\n return SheetStatus.ANALYZED;\n } else if (this.choices != null) {\n return SheetStatus.ANALYZED_WITH_ERRORS;\n } else {\n return SheetStatus.NOT_ANALYZED;\n }\n }\n\n /**\n * Sets the rotation of this sheet.\n *\n * @param degrees Degrees to rotate clockwise, will be rounded with 90 interval.\n */\n public void setRotation(int degrees) {\n // Round to 0, 90, 180, 270\n this.rotation = ((degrees / 90) * 90) % 360;\n\n if (this.rotation < 0) {\n this.rotation += 360;\n }\n\n // Invalidate cache\n this.rawBuffer = null;\n }\n\n /**\n * Returs the rotation of the sheet.\n *\n * @return How many degrees the sheet is rotated clockwise: 0, 90, 180 or 270.\n */\n public int getRotation() {\n return this.rotation;\n }\n\n\n @Override\n synchronized public void deleteObserver(Observer observer) {\n super.deleteObserver(observer);\n\n if (this.countObservers() < 2) { // 2 because SheetsContainer is always listening. FIXME: this isn't robust. Use a different mechanism for keeping track of buffer users.\n // Release buffer\n this.rawBuffer = null;\n }\n }\n\n @Override\n synchronized public void deleteObservers() {\n super.deleteObservers();\n\n if (this.countObservers() < 2) { // 2 because SheetsContainer is always listening\n // Release buffer\n this.rawBuffer = null;\n }\n }\n\n /**\n * Invalidates image registration so that it will be recalculated next time analyze() is called.\n */\n public void invalidateRegistration() {\n this.markers = null;\n invalidateBrightnesses();\n }\n\n /**\n * Invalidates bubble brighnesses so that they will be recalculated next time analyze() is called.\n */\n public void invalidateBrightnesses() {\n this.brightness = null;\n invalidateAnswers();\n }\n\n /**\n * Invalidates answers so that they will be recalculated next time analyze() is called.\n * Bubble brightnesses are not invalidated, so the only reason to call this is when the answer key is changed.\n */\n public void invalidateAnswers() {\n this.choices = null;\n }\n\n /**\n * Returns an aligned buffer in the original resolution.\n * The aligned buffer is not cached. Instead, it is generated on the fly\n * from the raw buffer which may be cached.\n */\n public BufferedImage getAlignedBuffer() throws OutOfMemoryError, IOException {\n return this.getAlignedBuffer(this.getUnalignedBuffer());\n }\n\n /**\n * Returns an aligned, unzoomed buffer. The result is not cached.\n *\n * @param unalignedBuffer Raw buffer\n */\n private BufferedImage getAlignedBuffer(BufferedImage unalignedBuffer) throws OutOfMemoryError, IOException {\n // Transform the unaligned buffer\n BufferedImage transformedBuffer = new BufferedImage(unalignedBuffer.getWidth(), unalignedBuffer.getHeight(), BufferedImage.TYPE_INT_RGB);\n Graphics2D g = transformedBuffer.createGraphics();\n g.drawRenderedImage(unalignedBuffer, this.transformation);\n g.dispose();\n\n return transformedBuffer;\n }\n\n /**\n * Returns an aligned buffer at the given zoom level.\n * The aligned buffer is not cached. Instead, it is generated on the fly\n * from the raw buffer which may be cached.\n */\n public BufferedImage getAlignedBuffer(double zoomLevel) throws OutOfMemoryError, IOException {\n BufferedImage tempBuffer = this.getUnalignedBuffer();\n\n // Scale the image\n AffineTransform transform = AffineTransform.getScaleInstance(zoomLevel, zoomLevel);\n transform.concatenate(this.transformation);\n\n BufferedImage transformedBuffer = new BufferedImage((int) (tempBuffer.getWidth() * zoomLevel), (int) (tempBuffer.getHeight() * zoomLevel), BufferedImage.TYPE_INT_RGB);\n Graphics2D g = transformedBuffer.createGraphics();\n g.drawRenderedImage(tempBuffer, transform);\n g.dispose();\n\n return transformedBuffer;\n }\n\n\n /**\n * Returns the original unaligned buffer in the original resolution.\n * The buffer is cached as long as this sheet has registered observers.\n * First call to this method is very slow because the image file must be decoded.\n */\n public BufferedImage getUnalignedBuffer() throws OutOfMemoryError, IOException {\n // Return the cached buffer if available\n if (this.rawBuffer != null) {\n return this.rawBuffer;\n }\n\n // Load image\n BufferedImage tempBuffer = ImageIO.read(new File(filePath)); // read() returns null if image format is unsupported\n\n if (tempBuffer == null) {\n throw new IOException(\"Image \" + fileName + \" cannot be opened. Unsupported format.\");\n }\n\n // Convert to the required bit format and rotate\n BufferedImage convertedBuffer;\n AffineTransform transform;\n\n if (this.rotation == 90) {\n convertedBuffer = new BufferedImage(tempBuffer.getHeight(), tempBuffer.getWidth(), BufferedImage.TYPE_INT_RGB);\n transform = AffineTransform.getTranslateInstance(tempBuffer.getHeight(), 0);\n } else if (this.rotation == 180) {\n convertedBuffer = new BufferedImage(tempBuffer.getWidth(), tempBuffer.getHeight(), BufferedImage.TYPE_INT_RGB);\n transform = AffineTransform.getTranslateInstance(tempBuffer.getWidth(), tempBuffer.getHeight());\n } else if (this.rotation == 270) {\n convertedBuffer = new BufferedImage(tempBuffer.getHeight(), tempBuffer.getWidth(), BufferedImage.TYPE_INT_RGB);\n transform = AffineTransform.getTranslateInstance(0, tempBuffer.getWidth());\n } else {\n convertedBuffer = new BufferedImage(tempBuffer.getWidth(), tempBuffer.getHeight(), BufferedImage.TYPE_INT_RGB);\n transform = new AffineTransform();\n }\n\n transform.concatenate(AffineTransform.getRotateInstance(Math.toRadians(this.rotation)));\n\n // Rotate\n Graphics2D g = convertedBuffer.createGraphics();\n g.drawRenderedImage(tempBuffer, transform);\n g.dispose();\n\n // Cache buffer if there are observers\n if (this.countObservers() > 1) { // 1 beacause SheetsContainer is always observing. FIXME: this isn't robust\n this.rawBuffer = convertedBuffer;\n }\n\n return convertedBuffer;\n }\n\n /**\n * http://stackoverflow.com/questions/4216123/how-to-scale-a-bufferedimage\n *\n * @param newWidth\n * @param newHeight\n * @return\n * @throws OutOfMemoryError\n * @throws IOException\n */\n public BufferedImage getUnalignedBuffer(int newWidth, int newHeight) throws OutOfMemoryError, IOException {\n BufferedImage originalImage = getUnalignedBuffer();\n // now scale it...\n BufferedImage newImage =\n Scalr.resize(originalImage, Scalr.Method.BALANCED, newWidth, newHeight);\n return newImage ;\n }\n\n /**\n * Returns the original unaligned buffer at the given zoom level.\n * The zoomed buffer is not cached. Instead, it is generated on the fly\n * from the raw buffer which may be cached.\n */\n public BufferedImage getUnalignedBuffer(double zoomLevel) throws OutOfMemoryError, IOException {\n BufferedImage tempBuffer = this.getUnalignedBuffer();\n BufferedImage scaledBuffer = new BufferedImage((int) (tempBuffer.getWidth() * zoomLevel), (int) (tempBuffer.getHeight() * zoomLevel), BufferedImage.TYPE_INT_RGB);\n\n AffineTransform zoom = AffineTransform.getScaleInstance(zoomLevel, zoomLevel);\n Graphics2D g = scaledBuffer.createGraphics();\n g.drawRenderedImage(tempBuffer, zoom);\n g.dispose();\n\n return scaledBuffer;\n }\n\n /**\n * Tells whether a bubble is selected or not. If the answer has been overridden by the operator, the manually set value is returned instead of the calculated one.\n * Answers are available after they have been calculated with calculateAnswers().\n *\n * @param group Question group\n * @param row Local row number [0,n]\n * @param column Column number [0,n]\n * @return negative number if the bubble is clearly filled, 0 if uncertain, positive if the bubble is clearly unfilled\n */\n public int getAnswer(QuestionGroup group, int row, int column) {\n if (this.choices == null) {\n return 0;\n }\n\n int[][] choices = this.choices.get(group);\n if (choices == null) {\n return 0;\n }\n\n int[][] overrideChoices = null;\n if (this.overrideChoices != null) {\n overrideChoices = this.overrideChoices.get(group);\n }\n\n if (overrideChoices != null && overrideChoices[row][column] != 0) {\n return overrideChoices[row][column];\n } else {\n return choices[row][column];\n }\n }\n\n /**\n * Returns the answer override status\n *\n * @param group QuestionGroup from SheetStructure\n * @param row Local question number [0,n] in the given group (0 is the first question in the group regardless of index offset)\n * @param column Alternative number [0,n]\n * @return negative = force black, 0 = auto, postive = force white\n */\n public int getAnswerOverride(QuestionGroup group, int row, int column) {\n if (this.overrideChoices == null) {\n return 0;\n }\n\n int[][] overrideChoices = this.overrideChoices.get(group);\n if (overrideChoices == null) {\n return 0;\n }\n\n return overrideChoices[row][column];\n }\n\n /**\n * Toggles the answer override between \"force black\", \"force white\" and \"auto\".\n */\n public void toggleAnswer(QuestionGroup group, int row, int column) {\n // Create override array if it doesn't exist\n if (this.overrideChoices == null) {\n this.overrideChoices = new HashMap<QuestionGroup, int[][]>();\n }\n\n // Create override array for this group if necessary\n int[][] overrideChoices = this.overrideChoices.get(group);\n if (overrideChoices == null) {\n overrideChoices = new int[group.getRowCount()][group.getColumnCount()];\n this.overrideChoices.put(group, overrideChoices);\n }\n\n // Toggle between 1, 0, -1\n overrideChoices[row][column]--;\n if (overrideChoices[row][column] < -1) {\n overrideChoices[row][column] = 1;\n }\n\n // Update answer validity\n validateAnswers(group);\n\n // Notify observers\n setChanged();\n notifyObservers();\n }\n\n /**\n * Checks if all answers are either detected with certainty or manually overridden.\n * Use getStatus() to get the result.\n */\n private void validateAnswers(QuestionGroup group) {\n if (this.choices == null) {\n this.answersValid = false;\n return;\n }\n\n for (QuestionGroup key : this.choices.keySet()) {\n int[][] choices = this.choices.get(key);\n if (choices == null) {\n this.answersValid = false;\n return;\n }\n\n int[][] overrideChoices = null;\n if (this.overrideChoices != null) {\n overrideChoices = this.overrideChoices.get(key);\n }\n\n for (int row = 0; row < choices.length; row++) {\n for (int col = 0; col < choices[row].length; col++) {\n // Check that all uncertain answers are overridden\n if (choices[row][col] == 0 && (overrideChoices == null || overrideChoices[row][col] == 0)) {\n this.answersValid = false;\n return;\n }\n }\n }\n }\n\n this.answersValid = true;\n }\n\n /**\n * Returns the selected alternatives as a string.\n *\n * @param group Question group\n * @param question Number of the question in the group [0,n].\n * @return e.g. \"AC\", null if choices have not been calculated by calling analyze().\n */\n public String getChoices(QuestionGroup group, int question) {\n if (this.choices == null) {\n return null;\n }\n\n int[][] choices = this.choices.get(group);\n if (choices == null) {\n return null;\n }\n\n String result = \"\";\n\n if (group.getOrientation() == Orientation.CHECK_LETTER) {\n // FIXME: this should be in QuestionGroup\n String[] row0 = {\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"H\", \"J\", \"K\", \"L\"};\n String[] row1 = {\"M\", \"N\", \"P\", \"R\", \"S\", \"T\", \"U\", \"V\", \"W\", \"\"};\n\n if (group.getRowCount() < 2 || group.getColumnCount() < 10) {\n return \"\";\n }\n\n for (int alternative = 0; alternative < group.getAlternativesCount(); alternative++) {\n if (getAnswer(group, 0, alternative) < 0) {\n return row0[alternative];\n }\n if (getAnswer(group, 1, alternative) < 0) {\n return row1[alternative];\n }\n }\n\n } else {\n for (int alternative = 0; alternative < group.getAlternativesCount(); alternative++) {\n int answer;\n if (group.getOrientation() == Orientation.VERTICAL || group.getOrientation() == Orientation.STUDENT_NUMBER) {\n answer = getAnswer(group, question, alternative);\n } else {\n answer = getAnswer(group, alternative, question);\n }\n\n if (answer < 0) {\n result += group.getAlternative(alternative);\n }\n }\n }\n\n return result;\n }\n\n /**\n * Returns the average brightness of a bubble.\n * Brightnesses are available after the sheet has been analyzed with analyze().\n *\n * @param group Question group\n * @param row Bubble row number [0,n]\n * @param column Bubble column number [0,n]\n * @return average value of the pixels contained by the bubble [0...255]. 255 if the sheet has not been analyzed.\n */\n public int getBubbleBrightness(QuestionGroup group, int row, int column) {\n if (this.brightness == null) {\n return 255;\n }\n\n int[][] brightnessArray = this.brightness.get(group);\n if (brightnessArray == null) {\n return 255;\n }\n\n return brightnessArray[row][column];\n }\n\n /**\n * Returns the location of a given alignment marker in this sheet.\n * Markers are available after the sheet has been analyzed with analyze().\n *\n * @param marker Marker form SheetStructure\n * @return Point which contains the coordinates of the marker relative to the upper left corner of this sheet. Null if marker location is not known.\n */\n public Point getRegistrationMarkerLocation(RegistrationMarker marker) {\n if (this.markers == null) {\n return null;\n }\n\n return this.markers.get(marker);\n }\n\n\n /**\n * Locates registration markers, aligns the sheet, calculates brightness values of the bubbles, and calcualtes answers.\n * Results are cached. Use invalidate*() to flush cache.\n *\n * @param structure Sheet structure that contains positions of the markers and bubbles.\n */\n public void analyze(SheetStructure structure, Histogram globalHistogram) throws OutOfMemoryError, IOException {\n\n Dimension dim = structure.getReferenceSheet().dimension();\n\n BufferedImage unalignedBuffer = getUnalignedBuffer( dim.width, dim.height );\n\n // Locate registration markers\n if (this.markers == null) {\n // Invalidate everything when alignemnt changes\n this.invalidateBrightnesses();\n\n this.markers = new HashMap<RegistrationMarker, Point>();\n for (RegistrationMarker marker : structure.getRegistrationMarkers()) {\n locateMarker(unalignedBuffer, marker);\n }\n }\n\n // Calculate transformation\n calculateTransformation(structure);\n\n // Calculate bubble brightnesses\n if (this.brightness == null) {\n // Invalidate answers when brightnesses change\n this.invalidateAnswers();\n\n this.histogram.reset();\n this.brightness = new HashMap<QuestionGroup, int[][]>();\n\n BufferedImage alignedBuffer = getAlignedBuffer(unalignedBuffer);\n\n unalignedBuffer = null; // Not needed any more\n for (QuestionGroup group : structure.getQuestionGroups()) {\n calculateBrightnesses(alignedBuffer, group, globalHistogram);\n }\n\n // Calculate threshold\n this.histogram.guessThreshold();\n }\n }\n\n /**\n * Calculates the transformation matrix for aligning the sheet. Markers should be located by analyze() before calling this.\n *\n * @param structure\n */\n private void calculateTransformation(SheetStructure structure) {\n AbstractList<RegistrationMarker> markers = structure.getRegistrationMarkers();\n\n Point referenceMarker1 = null; // Original marker positions in the referece sheet\n Point referenceMarker2 = null;\n Point translatedMarker1 = null; // Translated marker positions in this sheet\n Point translatedMarker2 = null;\n this.transformation = new AffineTransform();\n\n if (markers.size() < 1) {\n // No markers available. Don't translate.\n return;\n }\n\n if (markers.size() >= 1) {\n // At least one marker available\n referenceMarker1 = markers.get(0).getPoint();\n translatedMarker1 = this.getRegistrationMarkerLocation(markers.get(0));\n\n if (translatedMarker1 == null) {\n return; // Marker location not calculated. Don't do anything.\n }\n }\n if (markers.size() >= 2) {\n // Two markers available\n referenceMarker2 = markers.get(1).getPoint();\n translatedMarker2 = this.getRegistrationMarkerLocation(markers.get(1));\n }\n\n\n final double translationX = translatedMarker1.getX() - referenceMarker1.getX();\n final double translationY = translatedMarker1.getY() - referenceMarker1.getY();\n\n if (translatedMarker2 != null) {\n // Calculate translation, rotation and scaling of the sheet\n final double originalDx = referenceMarker2.getX() - referenceMarker1.getX(); // X distance between reference markers\n final double originalDy = referenceMarker2.getY() - referenceMarker1.getY(); // Y distance between reference markers\n final double translatedDx = translatedMarker2.getX() - translatedMarker1.getX(); // X distance between translated markers\n final double translatedDy = translatedMarker2.getY() - translatedMarker1.getY(); // Y distance between translated markers\n\n final double angle = Math.atan2(translatedDy, translatedDx) - Math.atan2(originalDy, originalDx);\n final double scale = Math.sqrt(originalDx * originalDx + originalDy * originalDy) / Math.sqrt(translatedDx * translatedDx + translatedDy * translatedDy);\n\n // Multiple markers available. Do translation, rotation and scaling.\n // Generate a transformation matrix\n // 4. Translate back\n transformation.translate(referenceMarker1.getX() - translationX, referenceMarker1.getY() - translationY);\n\n // 3. Scale\n transformation.scale(scale, scale);\n\n // 2. Rotate\n transformation.rotate(-angle);\n\n // 1. Translate first marker to origin to rotate around that point\n transformation.translate(-referenceMarker1.getX(), -referenceMarker1.getY());\n\n } else {\n // One marker available. Do translation only.\n transformation.translate(-translationX, -translationY);\n }\n }\n\n /**\n * Calculates average bubble brightnesses in the given group.\n *\n * @param group QuestionGroup from SheetStructure.\n */\n private void calculateBrightnesses(final BufferedImage buffer, final QuestionGroup group, Histogram globalHistogram) {\n final int[] array = ((DataBufferInt) buffer.getRaster().getDataBuffer()).getData(); // Image buffer\n\n // Initialize the array where brightness values are saved\n int[][] brightnessArray = new int[group.getRowCount()][group.getColumnCount()];\n this.brightness.put(group, brightnessArray);\n\n // Prepare histogram\n BufferedImage[] histogramExamples = globalHistogram.getExamples();\n\n final int bufferWidth = buffer.getWidth();\n final int bufferHeight = buffer.getHeight();\n final int columnCount = group.getColumnCount();\n final int rowCount = group.getRowCount();\n final int bubbleWidth = group.getBubbleWidth();\n final int bubbleHeight = group.getBubbleHeight();\n\n final double exampleScale = 24.0 / Math.max(bubbleWidth, bubbleHeight);\n final int exampleWidth = (int) (bubbleWidth * exampleScale);\n final int exampleHeight = (int) (bubbleHeight * exampleScale);\n\n final double columnSpacing = columnCount <= 1 ? 0 : (double) group.getWidth() / (columnCount - 1);\n final double rowSpacing = rowCount <= 1 ? 0 : (double) group.getHeight() / (rowCount - 1);\n\n // Iterate through bubble rows\n for (int row = 0; row < rowCount; row++) {\n final int bubbleY = Math.max((int) (group.getTopY() - bubbleHeight / 2 + row * rowSpacing), 0); // Top edge y coordinate\n\n // Iterate through each bubble on the row\n for (int col = 0; col < columnCount; col++) {\n final int bubbleX = Math.max((int) (group.getLeftX() - bubbleWidth / 2 + col * columnSpacing), 0); // Left edge x coordinate\n\n // Read every pixel in the bubble\n long sum = 0;\n final int bubbleBottomY = Math.min(bubbleY + bubbleHeight, bufferHeight - 1); // Bottom edge y coordinate\n final int bubbleRightX = Math.min(bubbleX + bubbleWidth, bufferWidth); // Right edge x coordinate\n\n for (int y = bubbleY; y < bubbleBottomY; y++) {\n int offset = y * bufferWidth;\n\n for (int x = bubbleX; x < bubbleRightX; x++) {\n final int index = offset + x;\n sum += ((array[index] & 0x00FF0000) >> 16)\n + ((array[index] & 0x0000FF00) >> 8)\n + ((array[index] & 0x000000FF));\n }\n }\n\n final int brightness = (int) ((double) sum / (bubbleWidth * bubbleHeight * 3));\n\n // Save brightness value\n brightnessArray[row][col] = brightness;\n\n // Update histogram\n if (brightness < 0) {\n globalHistogram.increase(0);\n this.histogram.increase(0);\n } else if (brightness > 255) {\n globalHistogram.increase(255);\n this.histogram.increase(255);\n } else {\n globalHistogram.increase(brightness);\n this.histogram.increase(brightness);\n\n // Copy example bubble\n if (histogramExamples[brightness] == null) {\n BufferedImage example = new BufferedImage(exampleWidth, exampleHeight, BufferedImage.TYPE_INT_RGB);\n histogramExamples[brightness] = example;\n\n // Copy bubble\n Graphics g = example.createGraphics();\n g.drawImage(buffer,\n 0, 0, exampleWidth, exampleHeight,\n bubbleX, bubbleY, bubbleRightX, bubbleBottomY,\n null);\n g.dispose();\n }\n }\n }\n }\n }\n\n /**\n * Locates registration markers.\n *\n * @param marker RegistrationMarker from SheetStructure.\n */\n private void locateMarker(final BufferedImage sheetBuffer, final RegistrationMarker marker) {\n if (sheetBuffer == null) {\n System.err.println(\"locateMarker: sheet buffer not available\");\n return;\n }\n\n BufferedImage markerBuffer = marker.getBuffer();\n if (markerBuffer == null) {\n System.err.println(\"locateMarker: marker buffer not available\");\n return;\n }\n\n final int[] sheetArray = ((DataBufferInt) sheetBuffer.getRaster().getDataBuffer()).getData();\n final int sheetWidth = sheetBuffer.getWidth();\n final int sheetHeight = sheetBuffer.getHeight();\n\n final int[] markerArray = ((DataBufferInt) markerBuffer.getRaster().getDataBuffer()).getData();\n final int markerX = marker.getX();\n final int markerY = marker.getY();\n final int markerWidth = markerBuffer.getWidth();\n final int markerHeight = markerBuffer.getHeight();\n final int searchRadius = marker.getSearchRadius();\n\n long minDifference = Long.MAX_VALUE;\n int foundX = markerX;\n int foundY = markerY;\n\n final int searchStartY = Math.max(markerY - searchRadius - markerHeight / 2, 0);\n final int searchStartX = Math.max(markerX - searchRadius - markerWidth / 2, 0);\n final int searchEndY = Math.min(searchStartY + 2 * searchRadius, sheetHeight - markerHeight);\n final int searchEndX = Math.min(searchStartX + 2 * searchRadius, sheetWidth - markerWidth);\n\n for (int searchY = searchStartY; searchY < searchEndY; searchY++) {\n for (int searchX = searchStartX; searchX < searchEndX; searchX++) {\n long difference = 0;\n\n // Calculate difference between marker and the sheet\n for (int y = 0; y < markerHeight; y++) {\n final int markerOffset = y * markerWidth;\n final int sheetOffset = (y + searchY) * sheetWidth + searchX;\n\n for (int x = 0; x < markerWidth; x++) {\n final int markerIndex = markerOffset + x;\n final int sheetIndex = sheetOffset + x;\n\n // Sum the absolute differences in red, green and blue component\n difference += Math.abs(((markerArray[markerIndex] & 0x00FF0000) >> 16) - ((sheetArray[sheetIndex] & 0x00FF0000) >> 16))\n + Math.abs(((markerArray[markerIndex] & 0x0000FF00) >> 8) - ((sheetArray[sheetIndex] & 0x0000FF00) >> 8))\n + Math.abs((markerArray[markerIndex] & 0x000000FF) - (markerArray[markerIndex] & 0x000000FF));\n\n\t\t \t\t\t/*\n\t\t \t\t\tint d = ((markerArray[markerIndex] & 0x00FF0000) >> 16) - ((sheetArray[sheetIndex] & 0x00FF0000) >> 16)\n\t\t \t\t\t\t+ ((markerArray[markerIndex] & 0x0000FF00) >> 8) - ((sheetArray[sheetIndex] & 0x0000FF00) >> 8)\n\t \t+ (markerArray[markerIndex] & 0x000000FF) - (markerArray[markerIndex] & 0x000000FF);\n\t // Don't need to divide by 3, because it doesn't change the sign nor the minimum position\n\t \n\t if (d < 0) {\n\t\t \t\t\t\tdifference -= d;\n\t\t \t\t\t}\n\t */\n }\n }\n\n // Store minimum\n if (difference < minDifference) {\n minDifference = difference;\n foundX = searchX;\n foundY = searchY;\n }\n }\n }\n\n // Store the location of the marker\n Point location = new Point(foundX + markerWidth / 2, foundY + markerHeight / 2);\n this.markers.put(marker, location);\n }\n\n /**\n * Updates answers based on bubble brightnesses and the given thresholds.\n * Does nothing if has no effect if sheet has not been analyzed.\n *\n * @param group QuestionGroup from SheetStructure\n */\n public void calculateAnswers(QuestionGroup group, int blackThreshold, int whiteThreshold) {\n // Don't do anything if bubbles have not been analyzed\n if (this.brightness == null) {\n return;\n }\n\n int[][] brightnessArray = this.brightness.get(group);\n if (brightnessArray == null) {\n return;\n }\n\n int rowCount = group.getRowCount();\n int columnCount = group.getColumnCount();\n\n // Reset choice array\n if (this.choices == null) {\n this.choices = new HashMap<QuestionGroup, int[][]>();\n }\n\n int[][] choices = new int[rowCount][columnCount];\n this.choices.put(group, choices);\n\n // Populate the choices array based on bubble brightnesses\n for (int row = 0; row < rowCount; row++) {\n for (int col = 0; col < columnCount; col++) {\n int brightness = brightnessArray[row][col];\n\n if (brightness < blackThreshold) {\n choices[row][col] = -1;\n } else if (brightness >= whiteThreshold) {\n choices[row][col] = 1;\n } else {\n choices[row][col] = 0;\n }\n }\n }\n\n // Set student number\n if (group.getOrientation() == Orientation.STUDENT_NUMBER) {\n this.studentIdNumber = \"\";\n for (int row = 0; row < choices.length; row++) {\n this.studentIdNumber += getChoices(group, row);\n }\n }\n\n // Set check letter\n if (group.getOrientation() == Orientation.CHECK_LETTER) {\n this.studentIdLetter = getChoices(group, 0);\n }\n\n this.studentId = this.studentIdNumber + this.studentIdLetter;\n\n // Validate answers\n validateAnswers(group);\n\n // Notify observers\n setChanged();\n notifyObservers();\n }\n\n /**\n * Creates a JPEG picture with an annotated answer sheet that can be shown to the student.\n *\n * @return byte array (blob) containing a JPEG\n */\n public byte[] getFeedbackJpeg(SheetStructure structure) throws IOException {\n ByteArrayOutputStream out = new ByteArrayOutputStream();\n\n Sheet sheet = this;\n BufferedImage sheetBuffer = sheet.getAlignedBuffer();\n Graphics2D g = sheetBuffer.createGraphics();\n\n // Draw registration markers\n for (RegistrationMarker marker : structure.getRegistrationMarkers()) {\n Point markerLocation = sheet.getRegistrationMarkerLocation(marker);\n\n if (markerLocation == null) {\n g.setColor(Color.RED); // Marker location not known\n } else {\n g.setColor(Color.BLUE); // Marker location known\n }\n\n g.drawRect((int) ((marker.getX() - marker.getImageWidth() / 2.0)),\n (int) ((marker.getY() - marker.getImageHeight() / 2.0)),\n (marker.getImageWidth()),\n (marker.getImageHeight()));\n }\n\n // Draw bubbles\n for (QuestionGroup group : structure.getQuestionGroups()) {\n int columnCount = group.getColumnCount();\n int rowCount = group.getRowCount();\n int bubbleWidth = (group.getBubbleWidth());\n int bubbleHeight = (group.getBubbleHeight());\n int xOffset = (int) ((group.getLeftX() - group.getBubbleWidth() / 2.0));\n int yOffset = (int) ((group.getTopY() - group.getBubbleHeight() / 2.0));\n double columnSpacing = columnCount <= 1 ? 0 : group.getWidth() / (columnCount - 1);\n double rowSpacing = rowCount <= 1 ? 0 : group.getHeight() / (rowCount - 1);\n\n for (int row = 0; row < rowCount; row++) {\n int bubbleTopY = (int) (row * rowSpacing) + yOffset;\n int bubbleBottomY = bubbleTopY + bubbleHeight;\n\n for (int col = 0; col < columnCount; col++) {\n int bubbleLeftX = (int) (col * columnSpacing) + xOffset;\n int bubbleRightX = bubbleLeftX + bubbleWidth;\n\n int answer = sheet.getAnswer(group, row, col);\n\n if (answer < 0) {\n // Selected bubble\n g.setColor(Color.BLUE);\n g.drawRect(bubbleLeftX, bubbleTopY, bubbleWidth, bubbleHeight);\n } else if (answer > 0) {\n // Unselected bubble\n g.setColor(Color.GRAY);\n\n // Draw corners\n g.drawLine(bubbleLeftX, bubbleTopY, bubbleLeftX + 4, bubbleTopY);\n g.drawLine(bubbleLeftX, bubbleBottomY, bubbleLeftX + 4, bubbleBottomY);\n g.drawLine(bubbleRightX - 4, bubbleTopY, bubbleRightX, bubbleTopY);\n g.drawLine(bubbleRightX - 4, bubbleBottomY, bubbleRightX, bubbleBottomY);\n g.drawLine(bubbleLeftX, bubbleTopY, bubbleLeftX, bubbleTopY + 4);\n g.drawLine(bubbleRightX, bubbleTopY, bubbleRightX, bubbleTopY + 4);\n g.drawLine(bubbleLeftX, bubbleBottomY - 4, bubbleLeftX, bubbleBottomY);\n g.drawLine(bubbleRightX, bubbleBottomY - 4, bubbleRightX, bubbleBottomY);\n } else {\n // Uncertain bubble\n g.setColor(Color.RED);\n g.drawRect(bubbleLeftX - 2, bubbleTopY - 2, bubbleWidth + 4, bubbleHeight + 4);\n g.drawRect(bubbleLeftX, bubbleTopY, bubbleWidth, bubbleHeight);\n\n g.drawString(\"?\", bubbleRightX + 5, bubbleBottomY);\n }\n }\n }\n }\n\n g.dispose();\n\n // Write the JPEG\n ImageIO.write(sheetBuffer, \"jpeg\", out);\n\n return out.toByteArray();\n }\n}",
"abstract public class Task extends Observable implements Runnable {\n \n //private LinkedList<ProgressListener> listeners;\n private StatusBar statusBar;\n \n private int estimatedOperationsCount;\n private int completedOperationsCount;\n \n public Task() {\n //this.listeners = new LinkedList<ProgressListener>();\n this.estimatedOperationsCount = 1;\n this.completedOperationsCount = 0;\n }\n \n /**\n * Constructor\n * @param observer Observer to be notified when task is finished\n */\n public Task(Observer observer) {\n super();\n \n if (observer != null) {\n \tthis.addObserver(observer);\n }\n }\n \n /**\n * Sets the statusbar for showing progress to the user.\n */\n public void setStatusBar(StatusBar statusBar) {\n this.statusBar = statusBar;\n }\n \n /*\n public void addProgressListener(ProgressListener listener) {\n this.listeners.add(listener);\n }\n */\n \n /**\n * Updates the statusbar text.\n */\n protected void setStatusText(String text) {\n if (statusBar != null) {\n statusBar.setStatusText(text);\n }\n }\n \n /**\n * Sets the number of operations needed to complete the task. Progress bar will show completedOperationsCount / estimatedOperationsCount. \n */\n protected void setEstimatedOperationsCount(int n) {\n this.estimatedOperationsCount = n;\n \n if (statusBar != null) {\n statusBar.setProgressTarget(n);\n }\n }\n \n /**\n * Returns the total number of operations needed to complete the task. \n */\n public int getEstimatedOperationsCount() {\n return estimatedOperationsCount;\n }\n \n /**\n * Sets the number of completed operation.\n */\n protected void setCompletedOperationsCount(int n) {\n this.completedOperationsCount = n;\n this.updateProgressBar();\n }\n \n /**\n * Increases the number of completed operations by one.\n */\n synchronized protected void increaseCompletedOperationsCount() {\n this.completedOperationsCount++;\n this.updateProgressBar();\n }\n \n private void updateProgressBar() {\n if (statusBar == null) {\n return;\n }\n \n statusBar.setProgress(completedOperationsCount);\n }\n \n /**\n * Called when the task is finished.\n */\n protected void finished() {\n if (statusBar != null) {\n statusBar.setStatusText(null);\n statusBar.setProgress(0);\n }\n \n // Notify observers\n setChanged();\n notifyObservers();\n }\n\n abstract public void run();\n}",
"public enum ThresholdingStrategy {PER_SHEET, GLOBAL};",
"public class Gui extends JFrame {\n private static final long serialVersionUID = 1L;\n \n private Project project; // Project being edited\n private File projectFile; // Currently open project file\n \n private UndoSupport undoSupport;\n private Executor executor; // Background tasks executor\n \n // Tabs\n private StructurePanel structurePanel;\n private CalibratePanel calibratePanel;\n private ResultsPanel resultsPanel;\n \n private StatusBar statusBar;\n\n private File myDir ;\n /**\n * Initializes the GUI and shows the main window.\n */\n public Gui() {\n super(\"Optical Mark Recognition\");\n\n // Background tasks executor\n this.executor = Executors.newSingleThreadExecutor();\n \n this.reset();\n\n this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n this.setSize(new Dimension(800, 600));\n\n //Add widgets\n addWidgets();\n \n // Initialize a new project\n this.setProject(new Project());\n\n //Display the window\n //this.pack();\n this.setVisible(true);\n\n myDir = new File(\".\");\n }\n \n private void reset() {\n // Create undo manager\n this.undoSupport = new UndoSupport();\n }\n \n /**\n * Adds widgets to the main window.\n */\n private void addWidgets() {\n //this.setLayout(new BorderLayout());\n\n // Tabs\n JTabbedPane tabs = new JTabbedPane();\n this.add(tabs, BorderLayout.CENTER);\n \n structurePanel = new StructurePanel(this);\n tabs.addTab(\"Structure\", null, structurePanel, \"Define answer form structure\");\n // setMnemonicAt(0, KeyEvent.VK_1);\n\n calibratePanel = new CalibratePanel(this);\n tabs.addTab(\"Calibrate\", null, calibratePanel, \"Calibrate OMR\");\n // setMnemonicAt(0, KeyEvent.VK_1);\n tabs.addChangeListener(calibratePanel); // Listen to tab change events\n \n resultsPanel = new ResultsPanel(this);\n tabs.addTab(\"Results\", null, resultsPanel, \"Results\");\n // setMnemonicAt(0, KeyEvent.VK_1);\n tabs.addChangeListener(resultsPanel);\n \n // Statusbar at the bottom\n statusBar = new StatusBar();\n this.add(statusBar, BorderLayout.PAGE_END);\n \n \n // Menu\n setJMenuBar(new Menu(this));\n }\n \n /**\n * Sets the active project.\n * @param project Project to be edited. Never set to null.\n */\n private void setProject(Project project) {\n this.project = project;\n structurePanel.setProject(project);\n calibratePanel.setProject(project);\n resultsPanel.setProject(project);\n }\n \n public UndoSupport getUndoSupport() {\n return this.undoSupport;\n }\n\n /**\n * Executes the given Runnable task in a thread. Tasks are queued and executed sequentially.\n */\n public void execute(Task task) {\n task.setStatusBar(statusBar);\n executor.execute(task);\n }\n \n /**\n * Starts a new project. If current project has unsaved changes, user is prompted for confirmation.\n */\n public void newProject() {\n \tif (project.isChanged()) {\n \t\t// Prompt for confirmation\n \t\t// TODO: offer \"Save as\" option\n Object[] options = {\"Discard\", \"Cancel\"};\n int answer = JOptionPane.showOptionDialog(this,\n \"The project has been modified. Do you want to discard changes?\",\n \"Discard changes?\",\n JOptionPane.YES_NO_OPTION,\n JOptionPane.WARNING_MESSAGE,\n null,\n options,\n options[0]);\n \n if (answer != 0) {\n // Cancel\n return;\n }\n \t}\n \t\n \t// Create new project\n \tthis.setProject(new Project());\n this.projectFile = null;\n }\n \n /**\n * Shows an \"Open file\" dialog, then loads the selected file as the current project.\n */\n public void openProject() {\n JFileChooser chooser = new JFileChooser(myDir);\n //chooser.addChoosableFileFilter(new OmrFileFilter()); \n int returnVal = chooser.showOpenDialog(this);\n\n if (returnVal != JFileChooser.APPROVE_OPTION) {\n // Cancel\n return;\n }\n \n File file = chooser.getSelectedFile();\n \n // Load project\n try {\n Deserializer deserializer = new Deserializer();\n Project loadedProject = deserializer.loadProject(file);\n this.setProject(loadedProject);\n this.projectFile = file;\n } catch (Exception e) {\n // Show an error dialog\n JOptionPane.showMessageDialog(this,\n \"Failed to load the project.\\n\" + e,\n \"Error\",\n JOptionPane.ERROR_MESSAGE);\n }\n }\n \n /**\n * Saves the current project to the same file where it was previously saved or where it was loaded from.\n * If current project is a new one (has not been saved), the \"Save as\" dialog is shown. \n */\n public boolean saveProject() {\n if (this.projectFile == null) {\n return saveProjectAs(); \n } else {\n return save(this.projectFile);\n }\n }\n \n /**\n * Shows a \"Save as\" dialog, then saves the current project to the chosen file. If the file exists, user is prompted for confirmation.\n * @return True if file was succesfully saved. False if user cancels or an saving fails.\n */\n public boolean saveProjectAs() {\n File file = showSaveAsDialog();\n if (file == null) {\n return false;\n }\n \n return this.save(file);\n }\n \n /**\n * Shows a \"save as\" dialog and prompts for confimation if selected file exists.\n * @return Selected file. Null if user cancels.\n */\n private File showSaveAsDialog() {\n JFileChooser chooser = new JFileChooser(myDir);\n //chooser.addChoosableFileFilter(new OmrFileFilter()); \n\n int returnVal = chooser.showSaveDialog(this);\n if (returnVal != JFileChooser.APPROVE_OPTION) {\n // Cancel\n return null;\n }\n \n File file = chooser.getSelectedFile();\n\n // Prompt overwrite\n if (file.exists()) {\n Object[] options = {\"Overwrite\", \"Cancel\"};\n int answer = JOptionPane.showOptionDialog(this,\n \"A file named \" + file.getName() + \" already exists. Are you sure you want to overwrite it?\",\n \"Overwrite file?\",\n JOptionPane.YES_NO_OPTION,\n JOptionPane.WARNING_MESSAGE,\n null,\n options,\n options[0]);\n \n if (answer != 0) {\n // Cancel overwrite\n return null;\n }\n }\n \n return file;\n }\n\n /**\n * Saves the current project to the given file. Shows an error message if something goes wrong.\n */\n private boolean save(File file) {\n \t// Try to save the file\n try {\n Serializer serializer = new Serializer();\n serializer.saveProject(this.project, file);\n this.projectFile = file;\n } catch (Exception e) {\n // Show an error dialog\n JOptionPane.showMessageDialog(this,\n \"Failed to save the project.\\n\" + e.getMessage(),\n \"Error\",\n JOptionPane.ERROR_MESSAGE);\n \n return false;\n }\n \n return true;\n }\n \n /**\n * Shows an \"open files\" dialog for selecting answer sheets to be imported, then imports the selected files.\n */\n public void importSheets() {\n JFileChooser chooser = new JFileChooser(myDir);\n chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);\n chooser.addChoosableFileFilter(new ImageFileFilter()); \n chooser.setMultiSelectionEnabled(true);\n //chooser.setDialogTitle(\"\");\n int returnVal = chooser.showOpenDialog(this);\n\n if (returnVal != JFileChooser.APPROVE_OPTION) {\n // Cancel\n return;\n }\n \n File[] files = chooser.getSelectedFiles();\n \n try {\n project.addAnswerSheets(files);\n } catch (Exception e) {\n // Show an error dialog\n JOptionPane.showMessageDialog(this,\n \"Failed to import sheets.\\n\" + e.getMessage(),\n \"Error\",\n JOptionPane.ERROR_MESSAGE);\n \n e.printStackTrace();\n }\n }\n \n /**\n * Shows a \"save as\" dialog for exporting answers as CSV, then performs the export.\n */\n public void exportAnswers() {\n File file = showSaveAsDialog();\n if (file == null) {\n // Cancel\n return;\n }\n \n // Try to save the file\n try {\n CsvSerializer serializer = new CsvSerializer();\n serializer.saveAnswers(this.project, file);\n } catch (Exception e) {\n // Show an error dialog\n JOptionPane.showMessageDialog(this,\n \"Failed to export answers.\\n\" + e.getMessage(),\n \"Error\",\n JOptionPane.ERROR_MESSAGE);\n }\n }\n \n /**\n * Shows a \"save as\" dialog for exporting results as CSV, then performs the export.\n */\n public void exportResults() {\n File file = showSaveAsDialog();\n if (file == null) {\n return;\n }\n \n // Try to save the file\n try {\n CsvSerializer serializer = new CsvSerializer();\n serializer.saveResults(this.project, file);\n } catch (Exception e) {\n // Show an error dialog\n JOptionPane.showMessageDialog(this,\n \"Failed to export results.\\n\" + e.getMessage(),\n \"Error\",\n JOptionPane.ERROR_MESSAGE);\n }\n \n }\n \n /**\n * Sends all feedback emails.\n */\n public void mailFeedback() {\n \tSendFeedbacksTask mailerTask = new SendFeedbacksTask(project);\n\n // Send emails in a background process\n execute(mailerTask);\n }\n \n}"
] | import java.awt.BorderLayout;
import java.util.Observable;
import java.util.Observer;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JToolBar;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import omr.AnalyzeSheetsTask;
import omr.Project;
import omr.Sheet;
import omr.Task;
import omr.Project.ThresholdingStrategy;
import omr.gui.Gui; | package omr.gui.calibration;
public class CalibratePanel extends JPanel implements ListSelectionListener, ChangeListener, Observer {
private static final long serialVersionUID = 1L;
private Gui gui; | private Project project; | 1 |
BottleRocketStudios/Android-GroundControl | GroundControlSample/app/src/main/java/com/bottlerocketstudios/groundcontrolsample/config/agent/RegionConfigurationAgent.java | [
"public class GroundControl {\n private static final String TAG = GroundControl.class.getSimpleName();\n\n private static final ConcurrentHashMap<String, ExecutionBuilderFactory> sExecutionBuilderFactoryMap = new ConcurrentHashMap<>();\n private static final ConcurrentHashMap<String, UiInformationContainer> sUiInformationContainerMap = new ConcurrentHashMap<>();\n\n private static String sDefaultAgentExecutorId = AgentExecutor.DEFAULT_AGENT_EXECUTOR_ID;\n private static boolean sDefaultAgentExecutorSet;\n\n /**\n * You can optionally supply a new ExecutionBuilderFactory for the specified AgentExecutor.\n */\n public static void setExecutionBuilderFactory(String agentExecutorId, ExecutionBuilderFactory executionBuilderFactory) {\n sExecutionBuilderFactoryMap.put(agentExecutorId, executionBuilderFactory);\n }\n\n private static ExecutionBuilderFactory getExecutionBuilderFactory(String agentExecutorId) {\n ExecutionBuilderFactory executionBuilderFactory = sExecutionBuilderFactoryMap.get(agentExecutorId);\n if (executionBuilderFactory == null) {\n Log.i(TAG, \"Created a new default instance of the StandardExecutionBuilderFactory for AgentExecutorId \" + agentExecutorId);\n executionBuilderFactory = createDefaultExecutionBuilderFactory(agentExecutorId);\n }\n return executionBuilderFactory;\n }\n\n /**\n * Guarantee that only one instance of the ExecutionBuilderFactory is built per agentExecutorId.\n */\n private static ExecutionBuilderFactory createDefaultExecutionBuilderFactory(String agentExecutorId) {\n synchronized (sExecutionBuilderFactoryMap) {\n ExecutionBuilderFactory executionBuilderFactory = sExecutionBuilderFactoryMap.get(agentExecutorId);\n if (executionBuilderFactory == null) {\n executionBuilderFactory = new StandardExecutionBuilderFactory(agentExecutorId);\n sExecutionBuilderFactoryMap.put(agentExecutorId, executionBuilderFactory);\n }\n return executionBuilderFactory;\n }\n }\n\n private static UiInformationContainer getUiInformationContainer(String agentExecutorId) {\n UiInformationContainer uiInformationContainer = sUiInformationContainerMap.get(agentExecutorId);\n if (uiInformationContainer == null) {\n Log.i(TAG, \"Created a new default instance of the StandardExecutionBuilderFactory for AgentExecutorId \" + agentExecutorId);\n uiInformationContainer = createDefaultUiInformationContainer(agentExecutorId);\n }\n return uiInformationContainer;\n }\n\n /**\n * Guarantee that only one instance of the UiInformationContainer is built per agentExecutorId.\n */\n private static UiInformationContainer createDefaultUiInformationContainer(String agentExecutorId) {\n synchronized (sUiInformationContainerMap) {\n UiInformationContainer uiInformationContainer = sUiInformationContainerMap.get(agentExecutorId);\n if (uiInformationContainer == null) {\n uiInformationContainer = new UiInformationContainer();\n sUiInformationContainerMap.put(agentExecutorId, uiInformationContainer);\n }\n return uiInformationContainer;\n }\n }\n\n /**\n * Register a new policy in the policy map for the default agent executor.\n *\n * @see GroundControl#setDefaultAgentExecutorId(String)\n */\n public static void registerPolicy(String policyIdentifier, AgentPolicy policy) {\n registerPolicy(sDefaultAgentExecutorId, policyIdentifier, policy);\n }\n\n /**\n * Register a new policy in the specified AgentExecutor.\n */\n public static void registerPolicy(String agentExecutorId, String policyIdentifier, AgentPolicy policy) {\n getExecutionBuilderFactory(agentExecutorId).registerPolicy(policyIdentifier, policy);\n }\n\n /**\n * Get the policy with the supplied id for the default agent executor.\n *\n * @see GroundControl#setDefaultAgentExecutorId(String)\n */\n public static AgentPolicy getPolicy(String policyIdentifier) {\n return getPolicy(sDefaultAgentExecutorId, policyIdentifier);\n }\n\n /**\n * Get the policy with the supplied id for the specified AgentExecutor.\n */\n public static AgentPolicy getPolicy(String agentExecutorId, String policyIdentifier) {\n return getExecutionBuilderFactory(agentExecutorId).getPolicy(policyIdentifier);\n }\n\n /**\n * Sets the default UI policy for the default AgentExecutor to disable cache.\n */\n public static void disableCache() {\n disableCache(sDefaultAgentExecutorId);\n }\n\n /**\n * Sets the default UI policy for the specified AgentExecutor to disable cache.\n */\n public static void disableCache(String agentExecutorId) {\n AgentPolicy agentPolicy = new StandardAgentPolicyBuilder().buildUpon(getPolicy(agentExecutorId, AgentPolicyCache.POLICY_IDENTIFIER_UI))\n .disableCache()\n .build();\n registerPolicy(agentExecutorId, AgentPolicyCache.POLICY_IDENTIFIER_UI, agentPolicy);\n }\n\n /**\n * Create an ExecutionBuilder for the supplied agent using the default agent executor. Used only for\n * non-UI implementations.\n *\n * <p><strong>Note: In most cases you should use bgAgent or uiAgent methods.</strong></p>\n *\n * @see GroundControl#setDefaultAgentExecutorId(String)\n */\n public static <ResultType, ProgressType> ExecutionBuilder<ResultType, ProgressType> agent(Agent<ResultType, ProgressType> agent) {\n return agent(sDefaultAgentExecutorId, agent);\n }\n\n /**\n * Create an ExecutionBuilder for the supplied agent on the specified AgentExecutor. Used only for\n * non-UI implementations.\n *\n * <p><strong>Note: In most cases you should use bgAgent or uiAgent methods.</strong></p>\n */\n public static <ResultType, ProgressType> ExecutionBuilder<ResultType, ProgressType> agent(String agentExecutorId, Agent<ResultType, ProgressType> agent) {\n return getExecutionBuilderFactory(agentExecutorId).createForAgent(agent);\n }\n\n /**\n * Create an ExecutionBuilder from inside of another Agent using the supplied AgentExecutor. Used only for\n * non-UI implementations. Supply the agentExecutor provided to the calling Agent with {@link Agent#setAgentExecutor(AgentExecutor)} method.\n * If your Agent extends {@link com.bottlerocketstudios.groundcontrol.agent.AbstractAgent} this is retained\n * for you so you can use {@link AbstractAgent#getAgentExecutor()}.\n */\n public static <ResultType, ProgressType> ExecutionBuilder<ResultType, ProgressType> bgAgent(AgentExecutor agentExecutor, Agent<ResultType, ProgressType> agent) {\n return agent(agentExecutor.getId(), agent);\n }\n\n /**\n * Create an ExecutionBuilder attached the uiObject for the supplied agent using the default AgentExecutor.\n * If you use this method you must also use {@link GroundControl#onDestroy(Object)}\n *\n * @see GroundControl#setDefaultAgentExecutorId(String)\n */\n public static <ResultType, ProgressType> ExecutionBuilder<ResultType, ProgressType> uiAgent(Object uiObject, Agent<ResultType, ProgressType> agent) {\n return uiAgent(sDefaultAgentExecutorId, uiObject, agent);\n }\n\n /**\n * Create an ExecutionBuilder attached the uiObject for the supplied agent on the specified AgentExecutor.\n * If you use this method you must also use {@link GroundControl#onDestroy(String, Object)}\n */\n public static <ResultType, ProgressType> ExecutionBuilder<ResultType, ProgressType> uiAgent(String agentExecutorId, Object uiObject, Agent<ResultType, ProgressType> agent) {\n return getExecutionBuilderFactory(agentExecutorId).createForAgent(agent).ui(uiObject);\n }\n\n /**\n * This method will reattach to a one-time operation or deliver its pre-existing result that was not acknowledged\n * by the last UI object which was waiting on it. You must call {@link GroundControl#onOneTimeCompletion}\n * in your listener when the one time operation has completed. This method uses the default AgentExecutor {@link GroundControl#setDefaultAgentExecutorId(String)}\n *\n * <p><strong>Note: This is typically placed in onCreate or onActivityCreated.</strong></p>\n *\n * @param uiObject A Fragment or Activity. You must call {@link GroundControl#onDestroy} in your onDestroy.\n * @param oneTimeIdentifier A unique string that identifies the operation you are resuming.\n * This must be unique across all potentially concurrent operations on the same AgentExecutor.\n * @param listener A listener for the agent that is being reattached.\n * @param <ResultType> Type of result delivered by the agent\n * @param <ProgressType> Type of progress delivered by the agent\n * @return An ExecutionBuilder with the policy pre-populated from the\n * previous execution. In most cases, simply call .execute() on the builder.\n */\n public static <ResultType, ProgressType> AgentTether reattachToOneTime(Object uiObject, String oneTimeIdentifier, AgentListener<ResultType, ProgressType> listener) {\n return reattachToOneTime(sDefaultAgentExecutorId, uiObject, oneTimeIdentifier, listener);\n }\n\n /**\n * Reattach to one time execution using the specified AgentExecutor.\n * Full documentation {@link GroundControl#reattachToOneTime(Object, String, AgentListener)}\n */\n public static <ResultType, ProgressType> AgentTether reattachToOneTime(String agentExecutorId, Object uiObject, String oneTimeIdentifier, AgentListener<ResultType, ProgressType> listener) {\n OneTimeInformation oneTimeInformation = getUiInformationContainer(agentExecutorId).restoreOneTimeInformation(oneTimeIdentifier);\n if (oneTimeInformation != null) {\n return getExecutionBuilderFactory(agentExecutorId).createForReattach(uiObject, oneTimeIdentifier, oneTimeInformation.getAgentIdentifier(), listener, oneTimeInformation.getAgentPolicy()).execute();\n }\n return null;\n }\n\n /**\n * Must be called by {@link ExecutionBuilder#execute()} to update the UIInformationContainer with the latest tether for this agent/UI combination.\n */\n static void updateUiInformationContainer(String agentExecutorId, Object uiObject, AgentTether agentTether, AgentPolicy agentPolicy, String oneTimeId) {\n UiInformationContainer uiInformationContainer = getUiInformationContainer(agentExecutorId);\n if (!TextUtils.isEmpty(oneTimeId)) {\n uiInformationContainer.storeOneTimeInfo(oneTimeId, agentTether.getAgentIdentifier(), agentPolicy);\n }\n uiInformationContainer.storeTether(uiObject, agentTether);\n }\n\n /**\n * Always call this method when you are destroying your UI which will release all tethers to\n * avoid delivering results to listeners in dead UI components and prevent temporary listener leaks.\n * This method uses the default AgentExecutor {@link GroundControl#setDefaultAgentExecutorId(String)}\n *\n * @param uiObject The current Activity or Fragment.\n */\n public static void onDestroy(Object uiObject) {\n onDestroy(sDefaultAgentExecutorId, uiObject);\n }\n\n /**\n * Reattach to one time execution using the specified AgentExecutor.\n * Full documentation {@link GroundControl#onDestroy(Object)}\n */\n public static void onDestroy(String agentExecutorId, Object uiObject) {\n getUiInformationContainer(agentExecutorId).onDestroy(uiObject);\n }\n\n /**\n * You must call this method when completing a one-time operation. This prevents attempted re-attach\n * and redelivery of results when the result has already been consumed. This method uses the default\n * AgentExecutor {@link GroundControl#setDefaultAgentExecutorId(String)}\n */\n public static void onOneTimeCompletion(String oneTimeIdentifier) {\n onOneTimeCompletion(sDefaultAgentExecutorId, oneTimeIdentifier);\n }\n\n /**\n * Full documentation {@link GroundControl#onOneTimeCompletion(String)}\n */\n public static void onOneTimeCompletion(String agentExecutorId, String oneTimeIdentifier) {\n getUiInformationContainer(agentExecutorId).onOneTimeCompletion(oneTimeIdentifier);\n }\n\n /**\n * Determine the DefaultAgentExecutorId to be used on calls that do not specify an AgentExecutorId.\n */\n public static String getDefaultAgentExecutorId() {\n return sDefaultAgentExecutorId;\n }\n\n /**\n * Modify the DefaultAgentExecutorId so that all subsequent calls will use the corresponding AgentExecutor.\n * This must be called once and not modified later at runtime to avoid confusion in a multi-threaded\n * environment. An exception will be thrown if it is called more than once with different IDs. Calling\n * repeatedly with the same ID will not cause an exception, but may indicate a bad design. Use the\n * methods in this class which take an explicit AgentExecutorId parameter if you need to use more\n * than one AgentExecutor in the same application.\n */\n public static synchronized void setDefaultAgentExecutorId(String defaultAgentExecutorId) {\n if (sDefaultAgentExecutorSet && !TextUtils.equals(sDefaultAgentExecutorId, defaultAgentExecutorId)) {\n throw new IllegalStateException(\"The DefaultAgentExecutorId can only be set once. If you need more than one, specify that ID per method call.\");\n }\n sDefaultAgentExecutorSet = true;\n sDefaultAgentExecutorId = defaultAgentExecutorId;\n }\n}",
"public abstract class DependencyHandlingAgent<ResultType, ProgressType> extends AbstractAgent<ResultType, ProgressType> implements DependencyHandler.DependencyHandlerListener {\n\n private final DependencyHandler mDependencyHandler = new DependencyHandler(this);\n\n /**\n * Add ExecutionBuilder built without a listener and the supplied listener. This will execute the\n * callback on a thread pool. Mixing with serial dependencies is\n * possible but sticking to one or the other is easier to reason about.\n */\n protected <R, P> void addParallelDependency(ExecutionBuilder<R, P> executionBuilder, AgentListener<R, P> agentListener) {\n mDependencyHandler.addParallelDependency(executionBuilder, agentListener);\n }\n\n /**\n * Add ExecutionBuilder built without a listener and the supplied listener.\n * This will execute the callback on a background Looper. Mixing with parallel dependencies is\n * possible but sticking to one or the other is easier to reason about.\n */\n protected <R, P> void addSerialDependency(ExecutionBuilder<R, P> executionBuilder, AgentListener<R, P> agentListener) {\n mDependencyHandler.addSerialDependency(executionBuilder, agentListener);\n }\n\n /**\n * Add an ExecutionBuilder with a {@link DependencyHandler.WrappedListener}\n * already associated with it. Using something other than a WrappedListener with this instance\n * as its callback listener will never call onDependenciesCompleted()\n */\n protected <R, P> void addDependency(ExecutionBuilder<R, P> executionBuilder) {\n mDependencyHandler.addDependency(executionBuilder);\n }\n\n /**\n * Call this after adding dependencies. It will execute any pending dependencies and increment\n * the AtomicInteger used to keep count of pending callbacks.\n */\n protected List<AgentTether> executeDependencies() {\n return mDependencyHandler.executeDependencies();\n }\n\n /**\n * Cancel all of the AgentTethers collected by calls to executeDependencies().\n */\n protected void cancelDependencies() {\n mDependencyHandler.cancel();\n }\n\n @Override\n public void cancel() {\n cancelDependencies();\n }\n\n}",
"public abstract class FunctionalAgentListener<ResultType, ProgressType> implements AgentListener<ResultType, ProgressType> {\n\n @Override\n public void onProgress(String agentIdentifier, ProgressType progress) {\n //This space left intentionally blank.\n }\n}",
"public class ConfigurationController {\n private static final String TAG = ConfigurationController.class.getSimpleName();\n\n private static final String PREF_CACHE_TIME = \"ConfigurationController.cacheTime\";\n private static final String PREF_CONFIGURATION = \"ConfigurationController.configuration\";\n\n private static final long CACHE_LIFETIME_MS = TimeUnit.MINUTES.toMillis(10);\n\n private OkHttpClient mHttpClient;\n\n public ConfigurationController() {\n ServiceInjector.injectWithType(OkHttpClient.class, new Injectable<OkHttpClient>() {\n @Override\n public void receiveInjection(OkHttpClient injection) {\n mHttpClient = injection;\n }\n });\n }\n\n public Configuration downloadConfiguration(Context context) {\n Configuration configuration = null;\n Request request = ProductApi.createConfigurationRequest(context);\n try {\n JSONObject jsonObject = ProductApi.downloadJson(mHttpClient, request);\n configuration = ConfigurationSerializer.parseJsonObject(jsonObject);\n } catch (IOException e) {\n Log.e(TAG, \"Caught java.io.IOException\", e);\n } catch (JSONException e) {\n Log.e(TAG, \"Caught org.json.JSONException\", e);\n }\n return configuration;\n }\n\n public CurrentVersion downloadCurrentVersion(Configuration configuration) {\n CurrentVersion currentVersion = null;\n Request request = ProductApi.createVersionRequest(configuration);\n try {\n JSONObject jsonObject = ProductApi.downloadJson(mHttpClient, request);\n currentVersion = CurrentVersionSerializer.parseJsonObject(jsonObject);\n } catch (IOException e) {\n Log.e(TAG, \"Caught java.io.IOException\", e);\n } catch (JSONException e) {\n Log.e(TAG, \"Caught org.json.JSONException\", e);\n }\n return currentVersion;\n }\n\n public RegionConfiguration downloadRegionConfiguration(Configuration configuration, CurrentVersion currentVersion) {\n RegionConfiguration regionConfiguration = null;\n Request request = ProductApi.createRegionRequest(configuration, currentVersion);\n try {\n JSONObject jsonObject = ProductApi.downloadJson(mHttpClient, request);\n regionConfiguration = RegionConfigurationSerializer.parseJsonObject(jsonObject);\n } catch (IOException e) {\n Log.e(TAG, \"Caught java.io.IOException\", e);\n } catch (JSONException e) {\n Log.e(TAG, \"Caught org.json.JSONException\", e);\n }\n return regionConfiguration;\n }\n}",
"public class Configuration {\n private static final String TAG = Configuration.class.getSimpleName();\n \n private String mVersionPath;\n private Uri mBaseUrl;\n \n public String getVersionPath() {\n return mVersionPath;\n }\n\n public void setVersionPath(String versionPath) {\n mVersionPath = versionPath;\n }\n\n public Uri getBaseUrl() {\n return mBaseUrl;\n }\n\n public void setBaseUrl(String baseUrl) {\n mBaseUrl = Uri.parse(baseUrl);\n }\n\n \n}",
"public class CurrentVersion {\n private static final String TAG = CurrentVersion.class.getSimpleName();\n \n private String mVersion; \n \n public String getVersion() {\n return mVersion;\n }\n\n public void setVersion(String version) {\n mVersion = version;\n }\n\n \n}",
"public class RegionConfiguration {\n public static final String DEFAULT_REGION = \"DEFAULT\";\n \n private List<Region> mRegionList;\n \n public List<Region> getRegionList() {\n return mRegionList;\n }\n\n public void setRegionList(List<Region> regionList) {\n mRegionList = regionList;\n }\n\n \n}"
] | import android.content.Context;
import com.bottlerocketstudios.groundcontrol.convenience.GroundControl;
import com.bottlerocketstudios.groundcontrol.dependency.DependencyHandlingAgent;
import com.bottlerocketstudios.groundcontrol.listener.FunctionalAgentListener;
import com.bottlerocketstudios.groundcontrolsample.config.controller.ConfigurationController;
import com.bottlerocketstudios.groundcontrolsample.config.model.Configuration;
import com.bottlerocketstudios.groundcontrolsample.config.model.CurrentVersion;
import com.bottlerocketstudios.groundcontrolsample.config.model.RegionConfiguration; | /*
* Copyright (c) 2016 Bottle Rocket LLC.
* 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.bottlerocketstudios.groundcontrolsample.config.agent;
/**
* Fetch the RegionConfiguration from server or cache.
*/
public class RegionConfigurationAgent extends DependencyHandlingAgent<RegionConfiguration, Void> {
private final Context mContext;
private Configuration mConfiguration;
private CurrentVersion mCurrentVersion;
public RegionConfigurationAgent(Context context) {
mContext = context.getApplicationContext();
}
@Override
public String getUniqueIdentifier() {
return RegionConfigurationAgent.class.getCanonicalName();
}
@Override
public void cancel() {}
@Override
public void onProgressUpdateRequested() {}
@Override
public void run() { | addParallelDependency(GroundControl.bgAgent(getAgentExecutor(), new ConfigurationAgent(mContext)), | 0 |
Aleksey-Terzi/MerchantsTFC | src/com/aleksey/merchants/TileEntities/TileEntityAnvilDie.java | [
"public class CoinInfo\n{\n public String CoinName;\n public int DieColor;\n public String MetalName;\n public int Level;\n \n public CoinInfo(String coinName, int dieColor, String metalName, int level)\n {\n CoinName = coinName;\n DieColor = dieColor;\n MetalName = metalName;\n Level = level;\n }\n}",
"public class Constants\n{\n private static final int _whiteColor = 0xffffff;\n private static final int _blackColor = 0;\n \n public static final CoinInfo[] Coins = new CoinInfo[] {\n new CoinInfo(\"Bismuth\", _whiteColor, \"item.Bismuth Ingot\", 0),\n new CoinInfo(\"Tin\", _blackColor, \"item.Tin Ingot\", 0),\n new CoinInfo(\"Zinc\", _blackColor, \"item.Zinc Ingot\", 0),\n new CoinInfo(\"Copper\", _blackColor, \"item.Copper Ingot\", 1),\n new CoinInfo(\"Bronze\", _whiteColor, \"item.Bronze Ingot\", 2),\n new CoinInfo(\"BismuthBronze\", _whiteColor, \"item.Bismuth Bronze Ingot\", 2),\n new CoinInfo(\"BlackBronze\", _whiteColor, \"item.Black Bronze Ingot\", 2),\n new CoinInfo(\"Brass\", _blackColor, \"item.Brass Ingot\", 2),\n new CoinInfo(\"Lead\", _whiteColor, \"item.Lead Ingot\", 1),\n new CoinInfo(\"Gold\", _blackColor, \"item.Gold Ingot\", 2),\n new CoinInfo(\"RoseGold\", _blackColor, \"item.Rose Gold Ingot\", 2),\n new CoinInfo(\"Silver\", _blackColor, \"item.Silver Ingot\", 2),\n new CoinInfo(\"SterlingSilver\", _blackColor, \"item.Sterling Silver Ingot\", 2),\n new CoinInfo(\"Platinum\", _blackColor, \"item.Platinum Ingot\", 3),\n new CoinInfo(\"WroughtIron\", _blackColor, \"item.Wrought Iron Ingot\", 3),\n new CoinInfo(\"Nickel\", _whiteColor, \"item.Nickel Ingot\", 4),\n new CoinInfo(\"Steel\", _whiteColor, \"item.Steel Ingot\", 4),\n new CoinInfo(\"BlackSteel\", _whiteColor, \"item.Black Steel Ingot\", 5),\n };\n \n public static final DieInfo[] Dies = new DieInfo[] {\n new DieInfo(\"Copper\", \"item.Copper Ingot\", \"item.Copper Double Ingot\", 1),\n new DieInfo(\"Bronze\", \"item.Bronze Ingot\", \"item.Bronze Double Ingot\", 2),\n new DieInfo(\"BismuthBronze\", \"item.Bismuth Bronze Ingot\", \"item.Bismuth Bronze Double Ingot\", 2),\n new DieInfo(\"BlackBronze\", \"item.Black Bronze Ingot\", \"item.Black Bronze Double Ingot\", 2),\n new DieInfo(\"Brass\", \"item.Brass Ingot\", \"item.Brass Double Ingot\", 2),\n new DieInfo(\"Lead\", \"item.Lead Ingot\", \"item.Lead Double Ingot\", 1),\n new DieInfo(\"Gold\", \"item.Gold Ingot\", \"item.Gold Double Ingot\", 2),\n new DieInfo(\"RoseGold\", \"item.Rose Gold Ingot\", \"item.Rose Gold Double Ingot\", 2),\n new DieInfo(\"Silver\", \"item.Silver Ingot\", \"item.Silver Double Ingot\", 2),\n new DieInfo(\"SterlingSilver\", \"item.Sterling Silver Ingot\", \"item.Sterling Silver Double Ingot\", 2),\n new DieInfo(\"Platinum\", \"item.Platinum Ingot\", \"item.Platinum Double Ingot\", 3),\n new DieInfo(\"WroughtIron\", \"item.Wrought Iron Ingot\", \"item.Wrought Iron Double Ingot\", 3),\n new DieInfo(\"Nickel\", \"item.Nickel Ingot\", \"item.Nickel Double Ingot\", 4),\n new DieInfo(\"Steel\", \"item.Steel Ingot\", \"item.Steel Double Ingot\", 4),\n new DieInfo(\"BlackSteel\", \"item.Black Steel Ingot\", \"item.Black Steel Double Ingot\", 5),\n new DieInfo(\"BlueSteel\", \"item.Blue Steel Ingot\", \"item.Blue Steel Double Ingot\", 6),\n new DieInfo(\"RedSteel\", \"item.Red Steel Ingot\", \"item.Red Steel Double Ingot\", 6),\n };\n}",
"public class ItemList\n{\n public static Item WarehouseBook;\n public static Item Flan;\n public static Item Coin;\n public static Item Trussel;\n public static Item AnvilDie;\n \n public static void Setup()\n {\n WarehouseBook = new ItemWarehouseBook().setUnlocalizedName(\"WarehouseBook\");\n Flan = new ItemFlan().setUnlocalizedName(\"Flan\");\n Coin = new ItemCoin().setUnlocalizedName(\"Coin\");\n Trussel = new ItemTrussel().setUnlocalizedName(\"Trussel\");\n AnvilDie = new ItemAnvilDie().setUnlocalizedName(\"AnvilDie\");\n\n GameRegistry.registerItem(WarehouseBook, WarehouseBook.getUnlocalizedName());\n GameRegistry.registerItem(Flan, Flan.getUnlocalizedName());\n GameRegistry.registerItem(Coin, Coin.getUnlocalizedName());\n GameRegistry.registerItem(Trussel, Trussel.getUnlocalizedName());\n GameRegistry.registerItem(AnvilDie, AnvilDie.getUnlocalizedName());\n }\n}",
"public class CoinHelper\n{\n public static final String TagName_Key = \"Key\";\n public static final String TagName_Name = \"Name\";\n public static final String TagName_Weight = \"Weight\";\n public static final String TagName_Die = \"Die\";\n\n public static final int DieStride = 12;\n public static final int MaxFlanWeightInHundreds = 50 * 100;//100 = 1oz;\n \n public static double getWeightOz(int weightIndex)\n {\n switch(weightIndex)\n {\n case 1:\n return 50;\n case 20:\n return 2.5;\n case 50:\n return 1;\n case 100:\n return 0.5;\n case 200:\n return 0.25;\n default:\n return 0;\n }\n }\n \n public static String getWeightText(int weightIndex)\n {\n String weightInOz = String.valueOf(getWeightOz(weightIndex));\n \n return weightInOz + StatCollector.translateToLocal(\"Oz\") + \" (\" + String.valueOf(weightIndex) + \")\";\n }\n \n public static byte[] packDie(boolean[] bits)\n {\n int dataLen = bits.length / 8;\n \n if((bits.length % 8) != 0)\n dataLen++;\n \n byte[] data = new byte[dataLen];\n int mask = 1;\n \n for(int i = 0; i < bits.length; i++)\n {\n int dataIndex = i / 8;\n byte dataByte = data[dataIndex];\n int bitIndex = i % 8;\n \n if(bitIndex == 0)\n dataByte = 0;\n \n if(bits[i])\n dataByte |= (byte)(mask << bitIndex);\n \n data[dataIndex] = dataByte;\n }\n \n return data;\n }\n \n public static boolean[] unpackDie(byte[] bytes)\n {\n boolean[] bits = new boolean[bytes.length * 8];\n \n int mask = 1;\n \n for(int i = 0; i < bits.length; i++)\n {\n int dataIndex = i / 8;\n byte dataByte = bytes[dataIndex];\n int bitIndex = i % 8;\n \n bits[i] = (dataByte & ((byte)(mask << bitIndex))) != 0;\n }\n \n return bits;\n }\n \n public static String getCoinName(ItemStack itemStack)\n {\n return itemStack.getTagCompound().getString(TagName_Name);\n }\n \n public static int getCoinWeight(ItemStack itemStack)\n {\n return itemStack.getTagCompound().getInteger(TagName_Weight);\n }\n\n public static byte[] getCoinDie(ItemStack itemStack)\n {\n return itemStack.getTagCompound().getByteArray(TagName_Die);\n }\n\n public static void copyDie(ItemStack srcStack, ItemStack dstStack)\n {\n if(!dstStack.hasTagCompound())\n dstStack.setTagCompound(new NBTTagCompound());\n \n NBTTagCompound srcTag = srcStack.getTagCompound();\n NBTTagCompound dstTag = dstStack.getTagCompound();\n \n dstTag.setString(TagName_Key, srcTag.getString(TagName_Key));\n dstTag.setString(TagName_Name, srcTag.getString(TagName_Name));\n dstTag.setInteger(TagName_Weight, srcTag.getInteger(TagName_Weight));\n dstTag.setByteArray(TagName_Die, srcTag.getByteArray(TagName_Die));\n }\n}",
"public class ItemHelper\n{\n public static final boolean areItemEquals(ItemStack itemStack1, ItemStack itemStack2)\n {\n if(itemStack1 == null || itemStack2 == null)\n return false;\n \n if(itemStack1.getItem() != itemStack2.getItem() || itemStack1.getItemDamage() != itemStack2.getItemDamage())\n return false;\n\n return itemStack1.getItem() instanceof IFood\n ? Food.areEqual(itemStack1, itemStack2)\n : ItemStack.areItemStackTagsEqual(itemStack1, itemStack2); \n }\n \n public static final String getItemKey(ItemStack itemStack)\n {\n Item item = itemStack.getItem();\n String key = String.valueOf(Item.getIdFromItem(item)) + \":\" + String.valueOf(itemStack.getItemDamage());\n \n if(!(item instanceof IFood))\n return key;\n \n key += \":\"\n + (Food.isBrined(itemStack) ? \"1\": \"0\")\n + (Food.isPickled(itemStack) ? \"1\": \"0\")\n + (Food.isCooked(itemStack) ? \"1\": \"0\")\n + (Food.isDried(itemStack) ? \"1\": \"0\")\n + (Food.isSmoked(itemStack) ? \"1\": \"0\")\n + (Food.isSalted(itemStack) ? \"1\": \"0\")\n ;\n \n return key;\n }\n \n public static final int getItemStackQuantity(ItemStack itemStack)\n {\n return getItemStackQuantity(itemStack, true);\n }\n \n public static final int getItemStackQuantity(ItemStack itemStack, boolean removeDecay)\n {\n if(itemStack.getItem() instanceof IFood)\n {\n IFood food = (IFood)itemStack.getItem();\n float foodDecay = removeDecay ? Math.max(food.getFoodDecay(itemStack), 0): 0;\n int quantity = (int)(food.getFoodWeight(itemStack) - foodDecay);\n \n return quantity > 0 ? quantity: 0;\n }\n\n return itemStack.stackSize;\n }\n\n public static final int getItemStackMaxQuantity(ItemStack itemStack, IInventory inventory)\n {\n Item item = itemStack.getItem();\n \n if(item instanceof IFood)\n return (int)((IFood)itemStack.getItem()).getFoodMaxWeight(itemStack);\n \n if(inventory instanceof TEIngotPile)\n return inventory.getInventoryStackLimit();\n \n return Math.min(itemStack.getMaxStackSize(), inventory.getInventoryStackLimit());\n }\n\n public static final int getItemStackMaxQuantity_SmallVessel(ItemStack itemStack)\n {\n Item item = itemStack.getItem();\n \n if(item instanceof IFood)\n return (int)((IFood)itemStack.getItem()).getFoodMaxWeight(itemStack) / 2;\n \n return itemStack.getMaxStackSize();\n }\n \n public static final void increaseStackQuantity(ItemStack itemStack, int quantity)\n {\n if(itemStack.getItem() instanceof IFood)\n {\n IFood food = (IFood)itemStack.getItem();\n float newQuantity = food.getFoodWeight(itemStack) + quantity;\n \n Food.setWeight(itemStack, newQuantity);\n }\n else\n itemStack.stackSize += quantity;\n }\n \n public static final void setStackQuantity(ItemStack itemStack, int quantity)\n {\n if(itemStack.getItem() instanceof IFood)\n ItemFoodTFC.createTag(itemStack, quantity);\n else\n itemStack.stackSize = quantity;\n }\n}"
] | import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.util.AxisAlignedBB;
import com.aleksey.merchants.Core.CoinInfo;
import com.aleksey.merchants.Core.Constants;
import com.aleksey.merchants.Core.DieInfo;
import com.aleksey.merchants.Core.ItemList;
import com.aleksey.merchants.Helpers.CoinHelper;
import com.aleksey.merchants.Helpers.ItemHelper;
import com.bioxx.tfc.TileEntities.NetworkTileEntity;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly; | {
if (_storage[i] != null)
{
NBTTagCompound itemTag = new NBTTagCompound();
itemTag.setByte("Slot", (byte) i);
_storage[i].writeToNBT(itemTag);
itemList.appendTag(itemTag);
}
}
nbt.setTag("Items", itemList);
}
@Override
public void readFromNBT(NBTTagCompound nbt)
{
super.readFromNBT(nbt);
_metalWeightInHundreds = nbt.getInteger("MetalWeight");
_metalMeta = nbt.getInteger("MetalMeta");
NBTTagList itemList = nbt.getTagList("Items", 10);
for (int i = 0; i < itemList.tagCount(); i++)
{
NBTTagCompound itemTag = itemList.getCompoundTagAt(i);
byte byte0 = itemTag.getByte("Slot");
if (byte0 >= 0 && byte0 < _storage.length)
setInventorySlotContents(byte0, ItemStack.loadItemStackFromNBT(itemTag));
}
}
@Override
public void handleInitPacket(NBTTagCompound nbt)
{
_metalWeightInHundreds = nbt.hasKey("MetalWeight") ? nbt.getInteger("MetalWeight"): 0;
_metalMeta = nbt.hasKey("MetalMeta") ? nbt.getInteger("MetalMeta"): 0;
this.worldObj.func_147479_m(xCoord, yCoord, zCoord);
}
@Override
public void createInitNBT(NBTTagCompound nbt)
{
nbt.setInteger("MetalWeight", _metalWeightInHundreds);
nbt.setInteger("MetalMeta", _metalMeta);
}
@Override
public void handleDataPacket(NBTTagCompound nbt)
{
if (!nbt.hasKey("Action"))
return;
byte action = nbt.getByte("Action");
switch (action)
{
case _actionId_Mint:
actionHandlerMint();
break;
}
}
@Override
public void updateEntity()
{
}
//Send action to server
public void actionMint()
{
NBTTagCompound nbt = new NBTTagCompound();
nbt.setByte("Action", _actionId_Mint);
this.broadcastPacketInRange(this.createDataPacket(nbt));
this.worldObj.func_147479_m(xCoord, yCoord, zCoord);
}
private void actionHandlerMint()
{
if(!canMint())
return;
int coinWeightIndex = CoinHelper.getCoinWeight(_storage[TrusselSlot]);
int coinWeight = (int)(CoinHelper.getWeightOz(coinWeightIndex) * 100);
int metalTotalWeight = getMetalTotalWeight();
int coinQuantity = Math.min(coinWeightIndex, metalTotalWeight / coinWeight);
ItemStack coinStack = _storage[CoinSlot];
int coinStackSize = coinStack != null ? coinStack.stackSize: 0;
if(coinQuantity + coinStackSize > _maxCoinStackSize)
coinQuantity = _maxCoinStackSize - coinStackSize;
if(coinStack == null)
_storage[CoinSlot] = getResultCoin(coinQuantity);
else
coinStack.stackSize += coinQuantity;
decrMetalTotalWeight(coinQuantity * coinWeight);
damageHammer();
this.worldObj.markBlockForUpdate(xCoord, yCoord, zCoord);
}
public boolean canMint()
{
ItemStack trusselStack = _storage[TrusselSlot];
if(_storage[HammerSlot] == null || trusselStack == null)
return false;
ItemStack coinStack = _storage[CoinSlot];
ItemStack resultStack = getResultCoin(1);
| if(coinStack != null && (coinStack.stackSize >= _maxCoinStackSize || !ItemHelper.areItemEquals(coinStack, resultStack))) | 4 |
reines/game | game-client/src/main/java/com/game/client/handlers/packet/ChatHandler.java | [
"public final class Client extends ClientFrame {\n\tprivate static final Logger log = LoggerFactory.getLogger(Client.class);\n\n\tpublic static final String DEFAULT_HOST = \"localhost\";\n\tpublic static final int DEFAULT_PORT = 36954;\n\tpublic static final int[] ICON_SIZES = {128, 64, 32, 16};\n\tpublic static final int DEFAULT_WIDTH = 800;\n\tpublic static final int DEFAULT_HEIGHT = 600;\n\n\tprotected static final Options options;\n\n\tstatic {\n\t\toptions = new Options();\n\n\t\toptions.addOption(\"h\", \"help\", false, \"print this help.\");\n\t\toptions.addOption(\"v\", \"disable-vsync\", false, \"disable vsync, default false.\");\n\t\toptions.addOption(\"p\", \"port\", true, \"server port number to connect to, default \" + DEFAULT_PORT + \".\");\n\t\toptions.addOption(\"s\", \"server\", true, \"server hostname to connect to, default \" + DEFAULT_HOST + \".\");\n\t}\n\n\tpublic static final void main(String[] args) {\n\t\ttry {\n\t\t\tCommandLineParser parser = new PosixParser();\n\t\t\tCommandLine config = parser.parse(options, args);\n\n\t\t\tif (config.hasOption(\"h\")) {\n\t\t\t\tHelpFormatter help = new HelpFormatter();\n\t\t\t\thelp.printHelp(\"java \" + Client.class.getSimpleName(), options);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tClient client = new Client(config);\n\t\t\tclient.run();\n\t\t}\n\t\tcatch (ParseException e) {\n\t\t\tlog.error(\"Error parsing command line options: \" + e);\n\t\t}\n\t\tcatch (RuntimeException e) {\n\t\t\tlog.error(e.getMessage());\n\t\t}\n\t}\n\n\tprotected static BufferedImage[] loadIcons(String name, int[] sizes) {\n\t\tBufferedImage[] iconImages = new BufferedImage[sizes.length];\n\t\tfor (int i = 0;i < iconImages.length;i++) {\n\t\t\ttry {\n\t\t\t\tURL resource = Client.class.getResource(name + sizes[i] + \".png\");\n\t\t\t\tif (resource == null) {\n\t\t\t\t\t// fatal error\n\t\t\t\t\tthrow new RuntimeException(\"Resource not found: icon\" + name + sizes[i] + \".png\");\n\t\t\t\t}\n\n\t\t\t\ticonImages[i] = ImageIO.read(resource);\n\t\t\t}\n\t\t\tcatch (IOException e) {\n\t\t\t\t// fatal error\n\t\t\t\tthrow new RuntimeException(\"Error loading icon: \" + e);\n\t\t\t}\n\t\t}\n\n\t\treturn iconImages;\n\t}\n\n\tprotected LoginWindow loginWindow;\n\tprotected final CommandLine config;\n\tprotected final Connection connection;\n\tprotected final WorldManager world;\n\tprotected final Camera camera;\n\tprotected final HUD hud;\n\tprotected final PublicKey publicKey;\n\n\tpublic Client(CommandLine config) {\n\t\tsuper (\"Test Client\", DEFAULT_WIDTH, DEFAULT_HEIGHT, Client.loadIcons(\"icon\", ICON_SIZES));\n\n\t\tthis.config = config;\n\n\t\tif (config.hasOption(\"v\"))\n\t\t\tsuper.setVSync(false);\n\n\t\tloginWindow = new LoginWindow(this);\n\t\tconnection = new Connection(this);\n\t\tworld = new WorldManager(this);\n\t\tcamera = world.getCamera();\n\t\thud = new HUD(this);\n\n\t\tpublicKey = (PublicKey) PersistenceManager.load(Client.class.getResource(\"publickey.xml\"));\n\n\t\t// Pre-load the item definitions\n\t\tItem.load();\n\n\t\tlog.info(\"New client started\");\n\t}\n\n\tpublic HUD getHUD() {\n\t\treturn hud;\n\t}\n\n\tpublic Connection getConnection() {\n\t\treturn connection;\n\t}\n\n\tpublic WorldManager getWorldManager() {\n\t\treturn world;\n\t}\n\n\tpublic boolean isLoggedIn() {\n\t\treturn loginWindow == null;\n\t}\n\n\tpublic void login(final String username, final String password) {\n\t\tnew Thread(new Runnable() {\n\t\t\t@Override\n\t\t\tpublic void run() {\n\t\t\t\tRandom random = new Random();\n\n\t\t\t\tString hostname = config.getOptionValue(\"s\", DEFAULT_HOST);\n\t\t\t\tint port = DEFAULT_PORT;\n\t\t\t\tif (config.hasOption(\"p\")) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tport = Integer.parseInt(config.getOptionValue(\"p\"));\n\t\t\t\t\t}\n\t\t\t\t\tcatch (NumberFormatException e) {\n\t\t\t\t\t\tlog.error(\"Invalid port number: \" + config.getOptionValue(\"p\") + \", trying default: \" + port);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\ttry {\n\t\t\t\t\tconnection.open(hostname, port);\n\n\t\t\t\t\tHash usernameHash = new Hash(username.toLowerCase());// Clean the username and hash it to get the users ID\n\t\t\t\t\tHash passwordHash = new Hash(usernameHash + password); // Salt the password and hash it\n\n\t\t\t\t\tPacketBuilder packet = new PacketBuilder(Packet.Type.LOGIN_SEND);\n\n\t\t\t\t\tpacket.putHash(usernameHash);\n\t\t\t\t\tpacket.putHash(passwordHash);\n\n\t\t\t\t\tlong encryptionSeed = random.nextLong();\n\t\t\t\t\tpacket.putLong(encryptionSeed);\n\n\t\t\t\t\tlong decryptionSeed = random.nextLong();\n\t\t\t\t\tpacket.putLong(decryptionSeed);\n\n\t\t\t\t\t// Encrypt the login packet with our public key\n\t\t\t\t\tpacket.encrypt(publicKey);\n\n\t\t\t\t\tconnection.write(packet);\n\n\t\t\t\t\t// from now on we want to encrypt outgoing packets\n\t\t\t\t\tconnection.enableEncryption(encryptionSeed, decryptionSeed);\n\t\t\t\t}\n\t\t\t\tcatch (RuntimeIoException rioe) {\n\t\t\t\t\tconnection.close();\n\n\t\t\t\t\tlog.warn(\"Failed to connect to: \" + hostname + \":\" + port);\n\t\t\t\t\tloginWindow.failed(\"Failed to connect to the game server.\");\n\t\t\t\t}\n\t\t\t}\n\t\t}).start();\n\t}\n\n\tpublic void loginSuccess(PlayerProfile profile) {\n\t\tworld.init(profile);\n\t\tloginWindow = null;\n\n\t\tlog.info(\"Successfully logged in.\");\n\t}\n\n\tpublic void loginFailed(String message) {\n\t\tloginWindow.failed(message);\n\t\tconnection.close();\n\t}\n\n\tpublic void handleLogout() {\n\t\tif (loginWindow != null)\n\t\t\treturn;\n\n\t\tconnection.close();\n\t\tloginWindow = new LoginWindow(this);\n\t}\n\n\t@Override\n\tprotected void update(long now) {\n\t\t// Update the connection\n\t\tconnection.update(now);\n\n\t\t// If there is a login window, update it\n\t\tif (loginWindow != null) {\n\t\t\tloginWindow.update(now);\n\t\t\treturn;\n\t\t}\n\n\t\t// Update the world\n\t\tworld.update(now);\n\n\t\t// Update the HUD\n\t\thud.update(now);\n\t}\n\n\t@Override\n\tpublic void display(Graphics g) {\n\t\tGraphics2D g2d = g.get2D();\n\n\t\t// If there is a login window, display it\n\t\tif (loginWindow != null) {\n\t\t\tg2d.begin();\n\t\t\t{\n\t\t\t\tloginWindow.display(g2d);\n\t\t\t}\n\t\t\tg2d.end();\n\n\t\t\treturn;\n\t\t}\n\n\t\tGraphics3D g3d = g.get3D();\n\n\t\tg3d.begin(world.getLocation(), camera.getZoom(), camera.getRotation());\n\t\t{\n\t\t\t// Display the world\n\t\t\tworld.display(g3d);\n\t\t}\n\t\tg3d.end();\n\n\t\tg2d.begin();\n\t\t{\n\t\t\t// Draw the HUD on-top of the world\n\t\t\thud.display(g2d);\n\t\t}\n\t\tg2d.end();\n\t}\n\n\t@Override\n\tpublic void mouseClicked(int x, int y, boolean left) {\n\t\t// If there is a login window, it was clicked\n\t\tif (loginWindow != null) {\n\t\t\tloginWindow.mouseClicked(x, y, left);\n\t\t\treturn;\n\t\t}\n\n\t\t// If the HUD was clicked, don't pass the key to the world\n\t\tif (hud.mouseClicked(x, y, left))\n\t\t\treturn;\n\n\t\t// Pass the click to the world\n\t\tworld.mouseClicked(x, y, left);\n\t}\n\n\t@Override\n\tpublic void keyPressed(int keyCode, char keyChar) {\n\t\t// If there is a login window, the key goes there\n\t\tif (loginWindow != null) {\n\t\t\tloginWindow.keyPressed(keyCode, keyChar);\n\t\t\treturn;\n\t\t}\n\n\t\t// Send the key to the HUD\n\t\thud.keyPressed(keyCode, keyChar);\n\t}\n\n\t@Override\n\tprotected void close() {\n\t\tconnection.destroy();\n\t}\n}",
"public class WorldManager extends GameEngine {\n\n\tprotected final Connection connection;\n\n\tprotected PlayerProfile profile;\n\n\tpublic WorldManager(Client client) {\n\t\tsuper (client);\n\n\t\tconnection = client.getConnection();\n\t}\n\n\tpublic Hash getID() {\n\t\treturn profile.id;\n\t}\n\n\tpublic String getUsername() {\n\t\treturn profile.username;\n\t}\n\n\tpublic FriendList getFriends() {\n\t\treturn profile.friends;\n\t}\n\n\tpublic StatList getStats() {\n\t\treturn profile.stats;\n\t}\n\n\tpublic Inventory getInventory() {\n\t\treturn profile.inventory;\n\t}\n\n\tpublic void init(PlayerProfile profile) {\n\t\tthis.profile = profile;\n\n\t\tclient.setUpdateRate(ClientFrame.UPDATE_RATE_MAX);\n\n\t\tModel model = client.getGraphics().loadModel(\"test.ms3d\", MilkShapeModel.class);\n\t\tmodel.setScale(0.03f);\n\n\t\tsuper.init(new Player(profile.id, profile.username, profile.location, model));\n\t}\n\n\tpublic void sendFriendAdd(String username) {\n\t\tPacketBuilder packet = new PacketBuilder(Packet.Type.FRIEND_ADD_SEND);\n\n\t\tpacket.putString(username);\n\n\t\tconnection.write(packet);\n\t}\n\n\tpublic void sendFriendRemove(Friend friend) {\n\t\tPacketBuilder packet = new PacketBuilder(Packet.Type.FRIEND_REMOVE_SEND);\n\n\t\tpacket.putHash(friend.getID());\n\n\t\tconnection.write(packet);\n\t}\n\n\tpublic void sendFriendMessage(Friend friend, String message) {\n\t\tPacketBuilder packet = new PacketBuilder(Packet.Type.FRIEND_MESSAGE_SEND);\n\n\t\tpacket.putHash(friend.getID());\n\t\tpacket.putString(message);\n\n\t\tconnection.write(packet);\n\t}\n\n\tpublic void sendUseItem(int index) {\n\t\tPacketBuilder packet = new PacketBuilder(Packet.Type.USE_ITEM_SEND);\n\n\t\tpacket.putByte((byte) index);\n\n\t\tconnection.write(packet);\n\t}\n\n\tpublic void sendChat(String message) {\n\t\tPacketBuilder packet = new PacketBuilder(Packet.Type.CHAT_SEND);\n\n\t\tpacket.putString(message);\n\n\t\tconnection.write(packet);\n\t}\n\n\tpublic void sendWalkTo(Path path) {\n\t\tPacketBuilder packet = new PacketBuilder(Packet.Type.WALK_TO_SEND);\n\n\t\tpacket.putPath(path);\n\n\t\tconnection.write(packet);\n\t}\n}",
"public interface PacketHandler {\n\n\tpublic void handlePacket(Client client, WorldManager world, Packet packet) throws Exception;\n\n}",
"public class Player extends Entity {\n\n\tprotected final Hash id;\n\tprotected final String username;\n\tprotected final Point location;\n\tprotected final Model model;\n\n\tpublic Player(Hash id, String name, Point location, Model model) {\n\t\tthis.id = id;\n\t\tthis.username = name;\n\t\tthis.location = location;\n\t\tthis.model = model;\n\t}\n\n\t@Override\n\tpublic Hash getID() {\n\t\treturn id;\n\t}\n\n\tpublic String getUsername() {\n\t\treturn username;\n\t}\n\n\t@Override\n\tpublic Point getLocation() {\n\t\treturn location;\n\t}\n\n\tpublic Model getModel() {\n\t\treturn model;\n\t}\n\n\t@Override\n\tpublic void setLocation(Point location) {\n\t\tif (location.equals(this.location))\n\t\t\treturn;\n\n\t\t// moving right: 45�, 90�, or 135�\n\t\tif (location.x > this.location.x) {\n\t\t\t// moving up: 45�\n\t\t\tif (location.y > this.location.y)\n\t\t\t\tmodel.setRotation(45);\n\t\t\t// moving down: 135�\n\t\t\telse if (location.y < this.location.y)\n\t\t\t\tmodel.setRotation(135);\n\t\t\t// else: 90�\n\t\t\telse\n\t\t\t\tmodel.setRotation(90);\n\t\t}\n\t\t// moving left: 225�, 270�, or 315�\n\t\telse if (location.x < this.location.x){\n\t\t\t// moving up: 315�\n\t\t\tif (location.y > this.location.y)\n\t\t\t\tmodel.setRotation(315);\n\t\t\t// moving down: 225�\n\t\t\telse if (location.y < this.location.y)\n\t\t\t\tmodel.setRotation(225);\n\t\t\t// else: 270�\n\t\t\telse\n\t\t\t\tmodel.setRotation(270);\n\t\t}\n\t\t// else: 0�, or 180�\n\t\telse {\n\t\t\t// moving up: 0�\n\t\t\tif (location.y > this.location.y)\n\t\t\t\tmodel.setRotation(0);\n\t\t\t// else: 180�\n\t\t\telse\n\t\t\t\tmodel.setRotation(180);\n\t\t}\n\n\t\tthis.location.set(location);\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn id.hashCode();\n\t}\n\n\t@Override\n\tpublic boolean equals(Object o) {\n\t\tif (!(o instanceof Player))\n\t\t\treturn false;\n\n\t\tPlayer p = (Player) o;\n\t\treturn id.equals(p.id);\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"player[id = \" + id + \", username = '\" + username + \"', location = \" + location + \"]\";\n\t}\n}",
"public class ChatMessages extends Widget {\n\tprivate static final int CAPACITY = 200;\n\tprivate static final int UPDATE_DELAY = 5000;\n\n\tpublic enum Type {\n\t\tLOCAL_CHAT(Color.YELLOW),\n\t\tPRIVATE_CHAT(Color.CYAN),\n\t\tMESSAGE(Color.WHITE);\n\n\t\tpublic final Color color;\n\n\t\tprivate Type(Color color) {\n\t\t\tthis.color = color;\n\t\t}\n\t};\n\n\tprivate static class ChatMessage {\n\t\tpublic final String message;\n\t\tpublic final Type type;\n\t\tpublic final long time;\n\n\t\tpublic ChatMessage(String message, Type type, long time) {\n\t\t\tthis.message = message;\n\t\t\tthis.type = type;\n\t\t\tthis.time = time;\n\t\t}\n\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\treturn message;\n\t\t}\n\t}\n\n\tprotected long lastUpdate;\n\tprotected int maxToShow;\n\tprotected int amountToShow;\n\tprotected Type filter;\n\tprotected final Deque<ChatMessage> messages;\n\n\tpublic ChatMessages(Client client, int width, int height) {\n\t\tsuper(width, height, true);\n\n\t\tlastUpdate = 0;\n\t\tmaxToShow = super.height / client.getGraphics().get2D().getFontHeight();\n\t\tamountToShow = 0;\n\t\tfilter = null;\n\n\t\tmessages = new LinkedList<ChatMessage>();\n\t}\n\n\tpublic void setFilterType(Type filter) {\n\t\tthis.filter = filter;\n\t}\n\n\tpublic void add(String message, Type type) {\n\t\tsynchronized (messages) {\n\t\t\tif (messages.size() >= CAPACITY)\n\t\t\t\tmessages.removeLast();\n\n\t\t\tChatMessage chatMessage = new ChatMessage(message, type, System.currentTimeMillis());\n\t\t\tlastUpdate = chatMessage.time;\n\n\t\t\tmessages.addFirst(chatMessage);\n\t\t\tif (amountToShow < maxToShow)\n\t\t\t\tamountToShow++;\n\t\t}\n\t}\n\n\tpublic void update(long now) {\n\t\tsynchronized (messages) {\n\t\t\tif (now - lastUpdate > UPDATE_DELAY) {\n\t\t\t\tlastUpdate = now;\n\t\t\t\tif (amountToShow > 0)\n\t\t\t\t\tamountToShow--;\n\t\t\t}\n\t\t}\n\t}\n\n\t@Override\n\tprotected void display(Graphics2D g, int x, int y) {\n\t\tif (super.backgroundColor != null)\n\t\t\tg.fillRect(x, y, width, height, super.backgroundColor);\n\n\t\tif (super.borderColor != null)\n\t\t\tg.drawRect(x, y, width, height, super.borderColor);\n\n\t\tsynchronized (messages) {\n\t\t\tint yOff = y + super.height - 4;\n\t\t\tint limit = (filter == null) ? amountToShow : maxToShow;\n\t\t\tIterator<ChatMessage> it = messages.iterator();\n\n\t\t\tfor (int i = 0;i < limit && it.hasNext();) {\n\t\t\t\tChatMessage message = it.next();\n\n\t\t\t\tif (filter != null && filter != message.type)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tg.drawString(message.toString(), x + 4, yOff, message.type.color, true);\n\n\t\t\t\tyOff -= g.getFontHeight();\n\t\t\t\ti++;\n\t\t\t}\n\t\t}\n\t}\n}",
"public class Packet {\n\tprivate static final Logger log = LoggerFactory.getLogger(Packet.class);\n\n\tpublic static final int HEADER_SIZE = 4 + 4; // type + size\n\n\tprotected static final CharsetDecoder stringDecoder;\n\n\tstatic {\n\t\tstringDecoder = Charset.forName(\"UTF-8\").newDecoder();\n\t}\n\n\t// X_SEND are packets from the client -> server\n\t// X_RESPONSE are from the server -> client\n\tpublic enum Type {\n\t\tLOGIN_SEND,\t\t\t\tLOGIN_RESPONSE,\n\t\tPING_SEND,\n\t\tCHAT_SEND,\t\t\t\tCHAT_RESPONSE,\n\t\t\t\t\t\t\t\tMESSAGE_RESPONSE,\n\t\tUSE_ITEM_SEND,\n\t\t\t\t\t\t\t\tFRIEND_LOGIN_RESPONSE,\n\t\tFRIEND_ADD_SEND,\t\tFRIEND_ADD_RESPONSE,\n\t\tFRIEND_MESSAGE_SEND,\tFRIEND_MESSAGE_RESPONSE,\n\t\tFRIEND_REMOVE_SEND,\t\tFRIEND_REMOVE_RESPONSE,\n\t\t\t\t\t\t\t\tPLAYERS_ADD_RESPONSE,\n\t\t\t\t\t\t\t\tPLAYERS_REMOVE_RESPONSE,\n\t\t\t\t\t\t\t\tPLAYERS_UPDATE_RESPONSE,\n\t\t\t\t\t\t\t\tINVENTORY_ADD_RESPONSE,\n\t\t\t\t\t\t\t\tINVENTORY_REMOVE_RESPONSE,\n\t\t\t\t\t\t\t\tINVENTORY_UPDATE_RESPONSE,\n\t\tWALK_TO_SEND,\n\t\tSTAT_UPDATE_SEND,\n\t}\n\n\tprotected final Type type;\n\tprotected IoBuffer payload;\n\tprotected final IoSession session;\n\n\tpublic Packet(Type type, IoBuffer payload, IoSession session) {\n\t\tthis.type = type;\n\t\tthis.payload = payload;\n\t\tthis.session = session;\n\t}\n\n\tpublic IoSession getSession() {\n\t\treturn session;\n\t}\n\n\tpublic Type getType() {\n\t\treturn type;\n\t}\n\n\tprotected byte[] getBytes() {\n\t\tbyte[] bytes = new byte[this.size()];\n\n\t\tpayload.rewind();\n\t\tpayload.get(bytes, 0, bytes.length);\n\n\t\treturn bytes;\n\t}\n\n\tprotected void setBytes(byte[] bytes) {\n\t\tpayload = IoBuffer.wrap(bytes).asReadOnlyBuffer();\n\t}\n\n\tpublic void decrypt(PrivateKey key) {\n\t\ttry {\n\t\t\tCipher cipher = Cipher.getInstance(\"RSA\");\n\t\t\tcipher.init(Cipher.DECRYPT_MODE, key);\n\n\t\t\tbyte[] encrypted = this.getBytes();\n\t\t\tbyte[] decrypted = cipher.doFinal(encrypted);\n\n\t\t\tthis.setBytes(decrypted);\n\t\t}\n\t\tcatch (Exception e) {\n\t\t\tlog.error(\"Error decrpyting packet: \" + e.getMessage());\n\t\t}\n\t}\n\n\tpublic <E extends Enum<E>> E getEnum(Class<E> enumClass) {\n\t\treturn payload.getEnum(enumClass);\n\t}\n\n\tpublic String getString() {\n\t\ttry {\n\t\t\treturn payload.getString(stringDecoder);\n\t\t}\n\t\tcatch (CharacterCodingException e) {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\tpublic Hash getHash() {\n\t\tbyte[] data = new byte[Hash.LENGTH];\n\t\tpayload.get(data, 0, Hash.LENGTH);\n\n\t\treturn Hash.fromBytes(data);\n\t}\n\n\tpublic Point getPoint() {\n\t\tint x = this.getShort();\n\t\tint y = this.getShort();\n\n\t\treturn new Point(x, y);\n\t}\n\n\tpublic Stat getStat() {\n\t\tStat.Type type = this.getEnum(Stat.Type.class);\n\t\tlong exp = this.getLong();\n\t\tint current = this.getShort();\n\n\t\treturn new Stat(type, exp, current);\n\t}\n\n\tpublic Item getItem() {\n\t\tint id = this.getShort();\n\t\tlong amount = this.getLong();\n\t\tboolean equiped = this.getBoolean();\n\n\t\treturn new Item(id, amount, equiped);\n\t}\n\n\tpublic Friend getFriend() {\n\t\tHash id = this.getHash();\n\t\tString username = this.getString();\n\t\tboolean online = this.getBoolean();\n\n\t\treturn new Friend(id, username, online);\n\t}\n\n\tpublic Date getDate() {\n\t\tlong time = this.getLong();\n\n\t\treturn new Date(time);\n\t}\n\n\tpublic Path getPath() {\n\t\tPath path = new Path();\n\n\t\tint stepCount = this.getShort();\n\t\tfor (int i = 0;i < stepCount;i++)\n\t\t\tpath.append(this.getPoint());\n\n\t\treturn path;\n\t}\n\n\tpublic boolean getBoolean() {\n\t\treturn payload.get() == 1;\n\t}\n\n\tpublic byte getByte() {\n\t\treturn payload.get();\n\t}\n\n\tpublic short getShort() {\n\t\treturn payload.getShort();\n\t}\n\n\tpublic int getInt() {\n\t\treturn payload.getInt();\n\t}\n\n\tpublic long getLong() {\n\t\treturn payload.getLong();\n\t}\n\n\tpublic void rewind() {\n\t\tpayload.rewind();\n\t}\n\n\tpublic int size() {\n\t\treturn payload.limit();\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"packet[\" + type + \"].length = \" + this.size();\n\t}\n}",
"public class Hash implements Comparable<Hash>, Serializable {\n\tprivate static final Logger log = LoggerFactory.getLogger(Hash.class);\n\tprivate static final long serialVersionUID = 1L;\n\n\tpublic static final int LENGTH = 20; // in bytes\n\tpublic static final String ALGORITHM = \"SHA-1\";\n\n\tprotected static MessageDigest digest;\n\n\tstatic {\n\t\ttry {\n\t\t\tdigest = MessageDigest.getInstance(ALGORITHM);\n\t\t}\n\t\tcatch (NoSuchAlgorithmException e) {\n\t\t\tlog.error(\"No such hashing algorithm: \" + ALGORITHM);\n\t\t\tSystem.exit(1); // fatal error\n\t\t}\n\t}\n\n\tpublic static Hash fromString(String hex) {\n\t\tHash hash = new Hash();\n\t\thash.setHex(hex);\n\n\t\treturn hash;\n\t}\n\n\tpublic static Hash fromBytes(byte[] bytes) {\n\t\tHash hash = new Hash();\n\t\thash.setBytes(bytes);\n\n\t\treturn hash;\n\t}\n\n\tprotected String hex;\n\n\tpublic Hash(String str) {\n\t\ttry {\n\t\t\tdigest.update(str.getBytes(\"UTF-8\"));\n\t\t}\n\t\tcatch (UnsupportedEncodingException e) { }\n\n\t\tthis.setBytes(digest.digest());\n\t}\n\n\tprivate Hash() {\n\t\thex = null;\n\t}\n\n\tprivate void setHex(String hex) {\n\t\tthis.hex = hex;\n\t}\n\n\tprivate void setBytes(byte[] bytes) {\n\t\tFormatter foramtter = new Formatter();\n\n\t\tfor (byte b : bytes)\n\t\t\tforamtter.format(\"%02x\", b);\n\n\t\tthis.hex = foramtter.toString();\n\t}\n\n\tpublic byte[] getBytes() {\n\t\tbyte[] bytes = new byte[LENGTH];\n\n\t\tfor (int i = 0;i < LENGTH;i++)\n\t\t\tbytes[i] = (byte) Short.parseShort(hex.substring(2 * i, 2 * (i + 1)), 16);\n\n\t\treturn bytes;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn hex;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn hex.hashCode();\n\t}\n\n\t@Override\n\tpublic boolean equals(Object o) {\n\t\tif (!(o instanceof Hash))\n\t\t\treturn false;\n\n\t\tHash h = (Hash) o;\n\t\treturn hex.equals(h.hex);\n\t}\n\n\t@Override\n\tpublic int compareTo(Hash h) {\n\t\treturn hex.compareTo(h.hex);\n\t}\n}"
] | import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.game.client.Client;
import com.game.client.WorldManager;
import com.game.client.handlers.PacketHandler;
import com.game.client.model.Player;
import com.game.client.ui.ChatMessages;
import com.game.common.codec.Packet;
import com.game.common.model.Hash; | package com.game.client.handlers.packet;
public class ChatHandler implements PacketHandler {
private static final Logger log = LoggerFactory.getLogger(ChatHandler.class);
@Override | public void handlePacket(Client client, WorldManager world, Packet packet) throws Exception { | 0 |
davidmoten/rtree | src/test/java/com/github/davidmoten/rtree/BenchmarksRTree.java | [
"static List<Entry<Object, Rectangle>> entries1000(Precision precision) {\n List<Entry<Object, Rectangle>> list = new ArrayList<Entry<Object, Rectangle>>();\n BufferedReader br = new BufferedReader(\n new InputStreamReader(BenchmarksRTree.class.getResourceAsStream(\"/1000.txt\")));\n String line;\n try {\n while ((line = br.readLine()) != null) {\n String[] items = line.split(\" \");\n double x = Double.parseDouble(items[0]);\n double y = Double.parseDouble(items[1]);\n Entry<Object, Rectangle> entry;\n if (precision == Precision.DOUBLE)\n entry = Entries.entry(new Object(), Geometries.rectangle(x, y, x + 1, y + 1));\n else\n entry = Entries.entry(new Object(), Geometries.rectangle((float) x, (float) y,\n (float) x + 1, (float) y + 1));\n list.add(entry);\n }\n br.close();\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return list;\n}",
"public final class SerializerFlatBuffers<T, S extends Geometry> implements Serializer<T, S> {\n\n private final FactoryFlatBuffers<T, S> factory;\n\n private SerializerFlatBuffers(Func1<? super T, byte[]> serializer,\n Func1<byte[], ? extends T> deserializer) {\n this.factory = new FactoryFlatBuffers<T, S>(serializer, deserializer);\n }\n\n public static <T, S extends Geometry> Serializer<T, S> create(\n Func1<? super T, byte[]> serializer, Func1<byte[], ? extends T> deserializer) {\n return new SerializerFlatBuffers<T, S>(serializer, deserializer);\n }\n\n @Override\n public void write(RTree<T, S> tree, OutputStream os) throws IOException {\n FlatBufferBuilder builder = new FlatBufferBuilder();\n final Rectangle mbb;\n if (tree.root().isPresent()) {\n mbb = tree.root().get().geometry().mbr();\n } else {\n mbb = Geometries.rectangle(0, 0, 0, 0);\n }\n int b = toBounds(builder, mbb);\n Context_.startContext_(builder);\n Context_.addBounds(builder, b);\n Context_.addMinChildren(builder, tree.context().minChildren());\n Context_.addMaxChildren(builder, tree.context().maxChildren());\n int c = Context_.endContext_(builder);\n final int n;\n if (tree.root().isPresent()) {\n n = addNode(tree.root().get(), builder, factory.serializer());\n } else {\n // won't be used\n n = 0;\n }\n // int t = Tree_.createTree_(builder, c, n, tree.size());\n Tree_.startTree_(builder);\n Tree_.addContext(builder, c);\n Tree_.addSize(builder, tree.size());\n if (tree.size() > 0) {\n Tree_.addRoot(builder, n);\n }\n int t = Tree_.endTree_(builder);\n Tree_.finishTree_Buffer(builder, t);\n\n ByteBuffer bb = builder.dataBuffer();\n os.write(bb.array(), bb.position(), bb.remaining());\n }\n\n private static int toBounds(FlatBufferBuilder builder, final Rectangle r) {\n Bounds_.startBounds_(builder);\n if (r.isDoublePrecision()) {\n Bounds_.addType(builder, BoundsType_.BoundsDouble);\n int box = BoxDouble_.createBoxDouble_(builder, r.x1(), r.y1(), r.x2(), r.y2());\n Bounds_.addBoxDouble(builder, box);\n } else {\n Bounds_.addType(builder, BoundsType_.BoundsFloat);\n int box = BoxFloat_.createBoxFloat_(builder, (float) r.x1(), (float) r.y1(),\n (float) r.x2(), (float) r.y2());\n Bounds_.addBoxFloat(builder, box);\n }\n return Bounds_.endBounds_(builder);\n }\n\n private static <T, S extends Geometry> int addNode(Node<T, S> node, FlatBufferBuilder builder,\n Func1<? super T, byte[]> serializer) {\n if (node instanceof Leaf) {\n Leaf<T, S> leaf = (Leaf<T, S>) node;\n return FlatBuffersHelper.addEntries(leaf.entries(), builder, serializer);\n } else {\n NonLeaf<T, S> nonLeaf = (NonLeaf<T, S>) node;\n int[] nodes = new int[nonLeaf.count()];\n for (int i = 0; i < nonLeaf.count(); i++) {\n Node<T, S> child = nonLeaf.child(i);\n nodes[i] = addNode(child, builder, serializer);\n }\n int ch = Node_.createChildrenVector(builder, nodes);\n Rectangle mbb = nonLeaf.geometry().mbr();\n int b = toBounds(builder, mbb);\n Node_.startNode_(builder);\n Node_.addChildren(builder, ch);\n Node_.addMbb(builder, b);\n return Node_.endNode_(builder);\n }\n }\n\n @Override\n public RTree<T, S> read(InputStream is, long sizeBytes, InternalStructure structure)\n throws IOException {\n byte[] bytes = readFully(is, (int) sizeBytes);\n Tree_ t = Tree_.getRootAsTree_(ByteBuffer.wrap(bytes));\n Context<T, S> context = new Context<T, S>(t.context().minChildren(),\n t.context().maxChildren(), new SelectorRStar(), new SplitterRStar(), factory);\n Node_ node = t.root();\n if (node == null) {\n return SerializerHelper.create(Optional.empty(), 0, context);\n } else {\n final Node<T, S> root;\n if (structure == InternalStructure.SINGLE_ARRAY) {\n if (node.childrenLength() > 0) {\n root = new NonLeafFlatBuffers<T, S>(node, context, factory.deserializer());\n } else {\n root = new LeafFlatBuffers<T, S>(node, context, factory.deserializer());\n }\n } else {\n root = toNodeDefault(node, context, factory.deserializer());\n }\n return SerializerHelper.create(Optional.of(root), (int) t.size(), context);\n }\n }\n\n private static <T, S extends Geometry> Node<T, S> toNodeDefault(Node_ node,\n Context<T, S> context, Func1<byte[], ? extends T> deserializer) {\n int numChildren = node.childrenLength();\n if (numChildren > 0) {\n List<Node<T, S>> children = new ArrayList<Node<T, S>>(numChildren);\n for (int i = 0; i < numChildren; i++) {\n children.add(toNodeDefault(node.children(i), context, deserializer));\n }\n return new NonLeafDefault<T, S>(children, context);\n } else {\n List<Entry<T, S>> entries = FlatBuffersHelper.createEntries(node, deserializer);\n return new LeafDefault<T, S>(entries, context);\n }\n }\n\n @VisibleForTesting\n static byte[] readFully(InputStream is, int numBytes) throws IOException {\n byte[] b = new byte[numBytes];\n int count = 0;\n do {\n int n = is.read(b, count, numBytes - count);\n if (n > 0) {\n count += n;\n } else {\n throw new RuntimeException(\"unexpected\");\n }\n } while (count < numBytes);\n return b;\n }\n\n}",
"public final class Geometries {\n\n private Geometries() {\n // prevent instantiation\n }\n\n public static Point point(double x, double y) {\n return PointDouble.create(x, y);\n }\n\n public static Point point(float x, float y) {\n return PointFloat.create(x, y);\n }\n\n public static Point pointGeographic(double lon, double lat) {\n return point(normalizeLongitudeDouble(lon), lat);\n }\n\n public static Point pointGeographic(float lon, float lat) {\n return point(normalizeLongitude(lon), lat);\n }\n\n public static Rectangle rectangle(double x1, double y1, double x2, double y2) {\n return rectangleDouble(x1, y1, x2, y2);\n }\n\n public static Rectangle rectangle(float x1, float y1, float x2, float y2) {\n return RectangleFloat.create(x1, y1, x2, y2);\n }\n\n public static Rectangle rectangleGeographic(double lon1, double lat1, double lon2,\n double lat2) {\n return rectangleGeographic((float) lon1, (float) lat1, (float) lon2, (float) lat2);\n }\n\n public static Rectangle rectangleGeographic(float lon1, float lat1, float lon2, float lat2) {\n float x1 = normalizeLongitude(lon1);\n float x2 = normalizeLongitude(lon2);\n if (x2 < x1) {\n x2 += 360;\n }\n return rectangle(x1, lat1, x2, lat2);\n }\n\n private static Rectangle rectangleDouble(double x1, double y1, double x2, double y2) {\n return RectangleDouble.create(x1, y1, x2, y2);\n }\n\n public static Circle circle(double x, double y, double radius) {\n return CircleDouble.create(x, y, radius);\n }\n\n public static Circle circle(float x, float y, float radius) {\n return CircleFloat.create(x, y, radius);\n }\n\n public static Line line(double x1, double y1, double x2, double y2) {\n return LineDouble.create(x1, y1, x2, y2);\n }\n\n public static Line line(float x1, float y1, float x2, float y2) {\n return LineFloat.create(x1, y1, x2, y2);\n }\n\n @VisibleForTesting\n static double normalizeLongitude(double d) {\n return normalizeLongitude((float) d);\n }\n\n private static float normalizeLongitude(float d) {\n if (d == -180.0f)\n return -180.0f;\n else {\n float sign = Math.signum(d);\n float x = Math.abs(d) / 360;\n float x2 = (x - (float) Math.floor(x)) * 360;\n if (x2 >= 180)\n x2 -= 360;\n return x2 * sign;\n }\n }\n\n private static double normalizeLongitudeDouble(double d) {\n if (d == -180.0f)\n return -180.0d;\n else {\n double sign = Math.signum(d);\n double x = Math.abs(d) / 360;\n double x2 = (x - (float) Math.floor(x)) * 360;\n if (x2 >= 180)\n x2 -= 360;\n return x2 * sign;\n }\n }\n\n}",
"public interface Point extends Rectangle {\n\n double x();\n\n double y();\n\n}",
"public interface Rectangle extends Geometry, HasGeometry {\n\n double x1();\n\n double y1();\n\n double x2();\n\n double y2();\n\n double area();\n\n double intersectionArea(Rectangle r);\n\n double perimeter();\n\n Rectangle add(Rectangle r);\n\n boolean contains(double x, double y);\n \n boolean isDoublePrecision();\n\n}"
] | import static com.github.davidmoten.rtree.Utilities.entries1000;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.infra.Blackhole;
import com.github.davidmoten.rtree.fbs.SerializerFlatBuffers;
import com.github.davidmoten.rtree.geometry.Geometries;
import com.github.davidmoten.rtree.geometry.Point;
import com.github.davidmoten.rtree.geometry.Rectangle;
import rx.Subscriber;
import rx.functions.Action1;
import rx.functions.Func1; | package com.github.davidmoten.rtree;
@State(Scope.Benchmark)
public class BenchmarksRTree {
private final static Precision precision = Precision.DOUBLE;
private final List<Entry<Object, Point>> entries = GreekEarthquakes.entriesList(precision);
| private final List<Entry<Object, Rectangle>> some = entries1000(precision); | 0 |
4FunApp/4Fun | server/4FunServer/src/com/mollychin/spider/MovieSpider.java | [
"public class MovieInfo {\n\tprivate String date;\n\tprivate String movieName;\n\tprivate double mark;\n\tprivate String pic;\n\tprivate String director;\n\tprivate String playWriter;\n\tprivate String country;\n\tprivate String briefIntro;\n\tprivate String moreInfo;\n\tprivate String pageUrl;\n\tprivate String movieType;\n\tprivate List<ActorInfo> actor;\n\n\tpublic List<ActorInfo> getActor() {\n\t\treturn actor;\n\t}\n\n\tpublic void setActor(List<ActorInfo> actor) {\n\t\tthis.actor = actor;\n\t}\n\n\tpublic String getDate() {\n\t\treturn date;\n\t}\n\n\tpublic void setDate(String date) {\n\t\tthis.date = date;\n\t}\n\n\tpublic String getMovieName() {\n\t\treturn movieName;\n\t}\n\n\tpublic void setMovieName(String movieName) {\n\t\tthis.movieName = movieName;\n\t}\n\n\tpublic double getMark() {\n\t\treturn mark;\n\t}\n\n\tpublic void setMark(double mark) {\n\t\tthis.mark = mark;\n\t}\n\n\tpublic String getPic() {\n\t\treturn pic;\n\t}\n\n\tpublic void setPic(String pic) {\n\t\tthis.pic = pic;\n\t}\n\n\tpublic String getDirector() {\n\t\treturn director;\n\t}\n\n\tpublic void setDirector(String director) {\n\t\tthis.director = director;\n\t}\n\n\tpublic String getPlayWriter() {\n\t\treturn playWriter;\n\t}\n\n\tpublic void setPlayWriter(String playWriter) {\n\t\tthis.playWriter = playWriter;\n\t}\n\n\tpublic String getCountry() {\n\t\treturn country;\n\t}\n\n\tpublic void setCountry(String country) {\n\t\tthis.country = country;\n\t}\n\n\tpublic String getBriefIntro() {\n\t\treturn briefIntro;\n\t}\n\n\tpublic void setBriefIntro(String briefIntro) {\n\t\tthis.briefIntro = briefIntro;\n\t}\n\n\tpublic String getMoreInfo() {\n\t\treturn moreInfo;\n\t}\n\n\tpublic void setMoreInfo(String moreInfo) {\n\t\tthis.moreInfo = moreInfo;\n\t}\n\n\tpublic String getPageUrl() {\n\t\treturn pageUrl;\n\t}\n\n\tpublic void setPageUrl(String pageUrl) {\n\t\tthis.pageUrl = pageUrl;\n\t}\n\n\tpublic String getMovieType() {\n\t\treturn movieType;\n\t}\n\n\tpublic void setMovieType(String movieType) {\n\t\tthis.movieType = movieType;\n\t}\n\n\tpublic static class ActorInfo {\n\t\tprivate String movieName;\n\t\tprivate String actorName;\n\t\tprivate String actorRole;\n\n\t\tpublic String getMovieName() {\n\t\t\treturn movieName;\n\t\t}\n\n\t\tpublic void setMovieName(String movieName) {\n\t\t\tthis.movieName = movieName;\n\t\t}\n\n\t\tpublic String getActorName() {\n\t\t\treturn actorName;\n\t\t}\n\n\t\tpublic void setActorName(String actorName) {\n\t\t\tthis.actorName = actorName;\n\t\t}\n\n\t\tpublic String getActorRole() {\n\t\t\treturn actorRole;\n\t\t}\n\n\t\tpublic void setActorRole(String actorRole) {\n\t\t\tthis.actorRole = actorRole;\n\t\t}\n\t}\n}",
"public static class ActorInfo {\n\tprivate String movieName;\n\tprivate String actorName;\n\tprivate String actorRole;\n\n\tpublic String getMovieName() {\n\t\treturn movieName;\n\t}\n\n\tpublic void setMovieName(String movieName) {\n\t\tthis.movieName = movieName;\n\t}\n\n\tpublic String getActorName() {\n\t\treturn actorName;\n\t}\n\n\tpublic void setActorName(String actorName) {\n\t\tthis.actorName = actorName;\n\t}\n\n\tpublic String getActorRole() {\n\t\treturn actorRole;\n\t}\n\n\tpublic void setActorRole(String actorRole) {\n\t\tthis.actorRole = actorRole;\n\t}\n}",
"public class ConstantsUtil {\n\t// 注册登录状态码\n\tpublic static final int LOGIN_PASSWORD_ERROR_CODE = 1025;\n\tpublic static final int LOGIN_USER_ERROR_CODE = 1026;\n\tpublic static final int REGISTER_USER_REPEAT_ERROR_CODE = 1027;\n\n\tpublic static final int REGISTER_SUCCESS_CODE = 1050;\n\tpublic static final int LOGIN_SUCCESS_CODE = 1051;\n\n\t// 注册登录状态信息\n\tpublic static final String LOGIN_PASSWORD_ERROR_MESSAGE = \"密码错误,请重试\";\n\tpublic static final String LOGIN_USER_ERROR_MESSAGE = \"用户名不存在\";\n\tpublic static final String REGISTER_USER_REPEAT_ERROR_MESSAGE = \"用户已注册\";\n\n\tpublic static final String REGISTER_SUCCESS_MESSAGE = \"注册成功\";\n\tpublic static final String LOGIN_SUCCESS_MESSAGE = \"登录成功\";\n\n\t// 网址相关\n\tpublic static final String AR_DAILY_URL = \"http://meiriyiwen.com/random\";\n\tpublic static final String AR_ONE_ROOT_URL = \"http://www.wufafuwu.com/\";\n\tpublic static final String AR_ONE_PRE_URL = \"http://www.wufafuwu.com/a/ONE_wenzhang/list_1_\";\n\tpublic static final String AR_ONE_SUFF_URL = \".html\";\n\tpublic static final String MOVIE_URL = \"http://movie.mtime.com/classic/\";\n\tpublic static final String MUSIC_PARENT_URL = \"http://fm.baidu.com/dev/api/?tn=playlist&id=public_fengge_qingyinyue&hashcode=091575870fd397f79a49347bec1b6529&_=1481594082582\";\n\tpublic static final String MUSIC_LINK_URL = \"http://play.baidu.com/data/music/songlink?songIds=\";\n\tpublic static final String MUSIC_INFO_URL = \"http://play.baidu.com/data/music/songinfo?songIds=\";\n\tpublic static final String PIC_WUFAZHUCE_URL = \"http://wufazhuce.com/\";\n\tpublic static final String POEM_BASE_URL = \"http://www.zgshige.com\";\n\tpublic static final String PIC_ZHIHU_URL = \"http://news-at.zhihu.com/api/4/start-image/1080*1776\";\n\n\t// 数据库相关\n\tpublic final static String USER = \"root\";\n\tpublic final static String DATABASE_NAME = \"4fun_v1\";\n\tpublic final static String ROOT_URL = \"jdbc:mysql://localhost:3306/\"\n\t\t\t+ DATABASE_NAME;\n\t// 密码注意修改\n\t// ---------------------------------------------------------------------\n\tpublic final static String PASSWORD = \"123456\";\n\n\t// 计时器相关\n\tpublic final static String BEGIN_TIME = \"07:30:00\";\n\tpublic final static String END_TIME = \"07:31:00\";\n\tpublic final static int CYCLES_TIME = 120 * 1000;\n\n\t// 下载相关\n\tpublic static final String COMPUTER_IP_ADDRESS = \"http://www.icodes.vip\";\n\tpublic static final String PICTURE_ONE = \"Picture4One/\";\n\tpublic static final String PICTURE_MOVIE = \"Picture4Movie/\";\n\tpublic static final String PICTURE_ZHIHU = \"Picture4Zhihu/\";\n\tpublic static final String PICTURE_MUSIC = \"Picture4Music/\";\n\t// 服务器上是 c 盘\n\t// --------------------------------------------------------------------------------------\n\tpublic static final String LOCAL_PATH = \"f://4FunResource\";\n\tpublic static final String LOCAL_PICTURE_PATH = LOCAL_PATH\n\t\t\t+ \"/PictureFile/\";\n\tpublic static final String LOCAL_MUSIC_PATH = LOCAL_PATH + \"/musicFile/\";\n\tpublic static final String LOCAL_RECITATION_PATH = LOCAL_PATH\n\t\t\t+ \"/recitationFile/\";\n\tpublic static final String FILE_PATH = SysContextListener.PROJECT_PATH;\n\tpublic static final String PICTURE_PROJECT_PATH = FILE_PATH\n\t\t\t+ \"/PictureFile/\";\n\tpublic static final String MUSIC_PROJECT_PATH = FILE_PATH + \"/MusicFile/\";\n\tpublic static final String RECITATION_PROJECT_PATH = FILE_PATH\n\t\t\t+ \"/RecitationFile/\";\n\n}",
"public class DownloadUtil {\n\t/**\n\t * 下载一个的图片\n\t * \n\t * @param urlString\n\t * @param fileName\n\t * @return\n\t * @throws IOException\n\t */\n\tpublic static String downloadPicture(String urlString, String fileName,\n\t\t\tString picType) throws IOException {\n\t\tFile file = new File(LOCAL_PICTURE_PATH);\n\t\tString localPicturePath = \"\";\n\t\tString projectPicturePath = \"\";\n\n\t\tif (!file.exists() && !file.isDirectory()) {\n\t\t\tfile.mkdir();\n\t\t}\n\t\tif (picType.equals(PICTURE_ONE)) {\n\t\t\tlocalPicturePath = LOCAL_PICTURE_PATH + PICTURE_ONE;\n\t\t\tprojectPicturePath = PICTURE_PROJECT_PATH + PICTURE_ONE;\n\n\t\t} else if (picType.equals(PICTURE_MOVIE)) {\n\t\t\tlocalPicturePath = LOCAL_PICTURE_PATH + PICTURE_MOVIE;\n\t\t\tprojectPicturePath = PICTURE_PROJECT_PATH + PICTURE_MOVIE;\n\n\t\t} else if (picType.equals(PICTURE_ZHIHU)) {\n\t\t\tlocalPicturePath = LOCAL_PICTURE_PATH + PICTURE_ZHIHU;\n\t\t\tprojectPicturePath = PICTURE_PROJECT_PATH + PICTURE_ZHIHU;\n\t\t} else if (picType.equals(PICTURE_MUSIC)) {\n\t\t\tlocalPicturePath = LOCAL_PICTURE_PATH + PICTURE_MUSIC;\n\t\t\tprojectPicturePath = PICTURE_PROJECT_PATH + PICTURE_MUSIC;\n\t\t}\n\t\tif (!(fileName.endsWith(\".jpg\") || fileName.endsWith(\".png\"))) {\n\t\t\tfileName = changeName(fileName) + \".jpg\";\n\t\t} else {\n\t\t\tString prex = fileName.substring(0, fileName.length() - 4);\n\t\t\tfileName.replace(prex, changeName(prex));\n\t\t}\n\n\t\tdownload(urlString, fileName, localPicturePath, projectPicturePath);\n\t\tif (picType.equals(PICTURE_ONE)) {\n\t\t\treturn COMPUTER_IP_ADDRESS + \"/4Fun/PictureFile/\" + PICTURE_ONE\n\t\t\t\t\t+ fileName;\n\t\t} else if (picType.equals(PICTURE_MOVIE)) {\n\t\t\treturn COMPUTER_IP_ADDRESS + \"/4Fun/PictureFile/\" + PICTURE_MOVIE\n\t\t\t\t\t+ fileName;\n\t\t} else if (picType.equals(PICTURE_ZHIHU)) {\n\t\t\treturn COMPUTER_IP_ADDRESS + \"/4Fun/PictureFile/\" + PICTURE_ZHIHU\n\t\t\t\t\t+ fileName;\n\t\t} else if (picType.equals(PICTURE_MUSIC)) {\n\t\t\treturn COMPUTER_IP_ADDRESS + \"/4Fun/PictureFile/\" + PICTURE_MUSIC\n\t\t\t\t\t+ fileName;\n\t\t}\n\n\t\treturn projectPicturePath;\n\t}\n\n\t/**\n\t * 下载音乐\n\t * \n\t * @param urlString\n\t * @param fileName\n\t * @return\n\t * @throws IOException\n\t */\n\tpublic static String downloadMusic(String urlString, String fileName)\n\t\t\tthrows IOException {\n\t\tString localFile = LOCAL_MUSIC_PATH;\n\t\tString projectFile = MUSIC_PROJECT_PATH;\n\t\tFile file = new File(localFile);\n\t\tif (!file.exists() && !file.isDirectory()) {\n\t\t\tfile.mkdir();\n\t\t}\n\n\t\tif (!fileName.endsWith(\".mp3\")) {\n\t\t\tfileName = fileName + \".mp3\";\n\t\t}\n\t\tdownload(urlString, fileName, localFile, projectFile);\n\n\t\treturn COMPUTER_IP_ADDRESS + \"/4Fun/MusicFile/\" + fileName;\n\t}\n\n\t/**\n\t * 下载诗歌朗诵\n\t * \n\t * @param urlString\n\t * @param filename\n\t * @return\n\t * @throws IOException\n\t */\n\tpublic static String downloadRecitation(String urlString, String filename)\n\t\t\tthrows IOException {\n\t\tString localFile = LOCAL_RECITATION_PATH;\n\t\tString projectFile = RECITATION_PROJECT_PATH;\n\t\tFile file = new File(localFile);\n\t\tif (!file.exists() && !file.isDirectory()) {\n\t\t\tfile.mkdir();\n\t\t}\n\n\t\tif (!filename.endsWith(\".mp3\")) {\n\t\t\tfilename = filename + \".mp3\";\n\t\t}\n\t\tdownload(urlString, filename, localFile, projectFile);\n\n\t\treturn COMPUTER_IP_ADDRESS + \"/4Fun/RecitationFile/\" + filename;\n\t}\n\n\t/**\n\t * 修改文件名\n\t * \n\t * @param fileName\n\t * @return\n\t */\n\tprivate static String changeName(String fileName) {\n\t\tString file = new BASE64Encoder().encode(fileName.getBytes());\n\n\t\treturn file.replace(\"\\n\", \"\").replace(\"\\r\", \"\").replace(\"\\r\\n\", \"\")\n\t\t\t\t.replace(\" \", \"\").replace(\"|\", \"\").replace(\"?\", \"\")\n\t\t\t\t.replace(\"\\\\\", \"\").replace(\"\\\\\\\\\", \"\").replace(\"//\", \"\")\n\t\t\t\t.replace(\"=\", \"\");\n\t}\n\n\tprivate static void download(String urlString, String filename,\n\t\t\tString localFile, String projectFile) throws MalformedURLException,\n\t\t\tIOException, FileNotFoundException {\n\t\tURL url = new URL(urlString);\n\t\t// open connection\n\t\tURLConnection conn = url.openConnection();\n\t\t// get InputStream(向程序读进来)\n\t\tInputStream is = conn.getInputStream();\n\t\t// 1K dateBuffer\n\t\tbyte[] bs = new byte[1024];\n\t\t// 读取到的数据长度\n\t\tint len;\n\t\t// 程序向外写(输出的文件流)\n\t\tOutputStream os = new FileOutputStream(localFile + filename);\n\t\tOutputStream osPro = new FileOutputStream(projectFile + filename);\n\t\t// 开始读取\n\t\twhile ((len = is.read(bs)) != -1) {\n\t\t\tos.write(bs, 0, len);\n\t\t\tosPro.write(bs, 0, len);\n\t\t}\n\t\t// 完毕,关闭所有链接\n\t\tos.close();\n\t\tosPro.close();\n\t\tis.close();\n\t}\n}",
"public class JDBCUtil {\n\n\t// 连接\n\tpublic static Connection getConnection() throws Exception {\n\t\ttry {\n\t\t\tClass.forName(\"com.mysql.jdbc.Driver\").newInstance();\n\t\t\treturn DriverManager.getConnection(ROOT_URL, USER, PASSWORD);\n\t\t} catch (Exception e) {\n\t\t\tthrow e;\n\t\t}\n\t}\n\n\t// 关闭\n\tpublic static void closeConnection(Connection conn) {\n\t\ttry {\n\t\t\tif (!conn.isClosed()) {\n\t\t\t\tconn.close();\n\t\t\t}\n\t\t} catch (SQLException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\n\t// 查询\n\tpublic static ResultSet selectData(String sql) throws SQLException,\n\t\t\tException {\n\t\ttry {\n\t\t\tConnection conn = getConnection();\n\t\t\tPreparedStatement prepareStatement = conn.prepareStatement(sql);\n\t\t\treturn prepareStatement.executeQuery();\n\t\t} catch (SQLException e) {\n\t\t\tthrow e;\n\t\t} catch (Exception e) {\n\t\t\tthrow e;\n\t\t}\n\t}\n\n\t// 插入数据\n\tpublic static void insertData(Connection conn, String sql)\n\t\t\tthrows SQLException {\n\t\ttry {\n\t\t\tPreparedStatement prepareStatement = conn.prepareStatement(sql);\n\t\t\tint executeUpdate = prepareStatement.executeUpdate();\n\t\t\tif (executeUpdate > 0) {\n\t\t\t\tSystem.out.println(\"添加数据成功哦\");\n\t\t\t} else {\n\t\t\t\tSystem.out.println(\"添加数据失败哦\");\n\t\t\t}\n\t\t} catch (MySQLIntegrityConstraintViolationException e) {\n\t\t\tSystem.out.println(\"数据已经添加\");\n\t\t} catch (SQLException e) {\n\t\t\tthrow e;\n\t\t}\n\t}\n\n\t// 插入用户注册信息\n\tpublic static String insertUserData(Connection conn, String sql)\n\t\t\tthrows SQLException {\n\t\tString returnInfo = \"注册成功\";\n\t\ttry {\n\n\t\t\tPreparedStatement prepareStatement = conn.prepareStatement(sql);\n\t\t\tint executeUpdate = prepareStatement.executeUpdate();\n\t\t\tif (executeUpdate <= 0) {\n\t\t\t\treturnInfo = \"注册失败\";\n\t\t\t}\n\t\t\treturn returnInfo;\n\t\t} catch (SQLException e) {\n\t\t\tthrow e;\n\t\t}\n\t}\n\n\tpublic static String resultSet2Json(ResultSet rs) throws SQLException,\n\t\t\tJSONException {\n\t\t// json 对象\n\t\tJSONObject object = new JSONObject();\n\t\tboolean error = true;\n\t\t// json 数组\n\t\tJSONArray array = new JSONArray();\n\t\t// 获取列数\n\t\tResultSetMetaData metaData = rs.getMetaData();\n\t\tint columnCount = metaData.getColumnCount();\n\t\t// 遍历ResultSet中的每条数据\n\t\twhile (rs.next()) {\n\t\t\tJSONObject jsonObj = new JSONObject();\n\t\t\t// 遍历每一列\n\t\t\tfor (int i = 1; i <= columnCount; i++) {\n\t\t\t\tString columnName = metaData.getColumnLabel(i);\n\t\t\t\tString value = rs.getString(columnName);\n\t\t\t\tjsonObj.put(columnName, value);\n\t\t\t}\n\t\t\tarray.put(jsonObj);\n\t\t}\n\t\tif (array.length() > 0) {\n\t\t\terror = !error;\n\t\t}\n\t\tobject.put(\"error\", error);\n\t\tobject.put(\"result\", array);\n\n\t\treturn object.toString();\n\t}\n\n\tpublic static List<Object> resultSet2JSONArray(ResultSet rs)\n\t\t\tthrows SQLException, JSONException {\n\t\t// json 数组\n\t\tJSONArray array = new JSONArray();\n\t\t// 获取列数\n\t\tResultSetMetaData metaData = rs.getMetaData();\n\t\tint columnCount = metaData.getColumnCount();\n\t\t// 遍历ResultSet中的每条数据\n\t\twhile (rs.next()) {\n\t\t\tJSONObject jsonObj = new JSONObject();\n\t\t\t// 遍历每一列\n\t\t\tfor (int i = 1; i <= columnCount; i++) {\n\t\t\t\tString columnName = metaData.getColumnLabel(i);\n\t\t\t\tString value = rs.getString(columnName);\n\t\t\t\tjsonObj.put(columnName, value);\n\t\t\t}\n\t\t\tarray.put(jsonObj);\n\t\t}\n\n\t\treturn array.toList();\n\t}\n\n\tpublic static String resultSet2Json(ResultSet rs, List<String> sqlList)\n\t\t\tthrows Exception {\n\t\t// json 对象\n\t\tJSONObject object = new JSONObject();\n\t\tboolean error = true;\n\t\t// json 数组\n\t\tJSONArray array = new JSONArray();\n\t\t// 获取列数\n\t\tResultSetMetaData metaData = rs.getMetaData();\n\t\tint columnCount = metaData.getColumnCount();\n\t\t// 遍历ResultSet中的每条数据\n\t\twhile (rs.next()) {\n\t\t\tint row = rs.getRow() - 1;\n\t\t\tResultSet data = selectData(sqlList.get(row));\n\t\t\tJSONObject jsonObj = new JSONObject();\n\t\t\t// 遍历每一列\n\t\t\tfor (int i = 1; i <= columnCount; i++) {\n\t\t\t\tString columnName = metaData.getColumnLabel(i);\n\t\t\t\tObject value = columnName.equals(\"actor\") ? resultSet2JSONArray(data)\n\t\t\t\t\t\t: rs.getString(columnName);\n\t\t\t\tjsonObj.put(columnName, value);\n\t\t\t}\n\t\t\tarray.put(jsonObj);\n\t\t}\n\t\tif (array.length() > 0) {\n\t\t\terror = !error;\n\t\t}\n\t\tobject.put(\"error\", error);\n\t\tobject.put(\"result\", array);\n\n\t\treturn object.toString();\n\t}\n\n\tpublic static void addUser(User user) throws Exception {\n\t\tConnection connection = JDBCUtil.getConnection();\n\t\tPreparedStatement ps = null;\n\t\tString sql = \"insert into users (userName,password,sex,email) values(?,?,?,?)\";\n\n\t\ttry {\n\t\t\tps = connection.prepareStatement(sql);\n\t\t\tps.setString(1, user.getUserName());\n\t\t\tps.setString(2, user.getPassword());\n\t\t\tps.setInt(3, user.getSex());\n\t\t\tps.setString(4, user.getEmail());\n\t\t\tps.executeUpdate();\n\t\t} catch (SQLException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\n\tpublic static User userVerify(String userName, String password)\n\t\t\tthrows Exception {\n\t\tUser user = new User();\n\t\tConnection connection = JDBCUtil.getConnection();\n\t\tPreparedStatement ps = null;\n\t\tResultSet rs = null;\n\t\tString sql = \"select * from users where userName=? and password=?\";\n\t\ttry {\n\t\t\tps = connection.prepareStatement(sql);\n\t\t\tps.setString(1, userName);\n\t\t\tps.setString(2, password);\n\t\t\trs = ps.executeQuery();\n\t\t\tif (rs.next()) {\n\t\t\t\tuser.setPassword(rs.getString(\"password\"));\n\t\t\t\tuser.setUserName(rs.getString(\"userName\"));\n\t\t\t\tuser.setSex(rs.getInt(\"sex\"));\n\t\t\t\tuser.setEmail(rs.getString(\"email\"));\n\t\t\t}\n\t\t} catch (SQLException e) {\n\t\t\te.printStackTrace();\n\t\t} finally {\n\t\t\tJDBCUtil.closeConnection(connection);\n\t\t}\n\n\t\treturn user;\n\t}\n\n\t/**\n\t * 验证数据库里是否有相同的用户名\n\t * \n\t * @param userName\n\t * @return return true if has, or return false\n\t * @throws Exception\n\t */\n\tpublic static boolean sameNameVerify(String userName) throws Exception {\n\t\tString name = null;\n\t\tConnection connection = JDBCUtil.getConnection();\n\t\tPreparedStatement ps = null;\n\t\tResultSet rs = null;\n\t\tString sql = \"select * from users where userName=?\";\n\t\ttry {\n\t\t\tps = connection.prepareStatement(sql);\n\t\t\tps.setString(1, userName);\n\t\t\trs = ps.executeQuery();\n\t\t\tif (rs.next()) {\n\t\t\t\tname = rs.getString(\"userName\");\n\t\t\t\tif (name.equals(userName)) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\treturn false;\n\t\t\t} else {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t} catch (SQLException e) {\n\t\t\te.printStackTrace();\n\t\t} finally {\n\t\t\tJDBCUtil.closeConnection(connection);\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t * 验证数据库里是否有相同的邮箱\n\t * \n\t * @param email\n\t * @return return true if has, or return false\n\t * @throws Exception\n\t */\n\n\tpublic static boolean sameEmailVerify(String email) throws Exception {\n\t\tString emailVerify = null;\n\t\tConnection connection = JDBCUtil.getConnection();\n\t\tPreparedStatement ps = null;\n\t\tResultSet rs = null;\n\t\tString sql = \"select * from users where email=?\";\n\t\ttry {\n\t\t\tps = connection.prepareStatement(sql);\n\t\t\tps.setString(1, email);\n\t\t\trs = ps.executeQuery();\n\t\t\tif (rs.next()) {\n\t\t\t\temailVerify = rs.getString(\"email\");\n\t\t\t\tif (emailVerify.equals(email)) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\treturn false;\n\t\t\t} else {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t} catch (SQLException e) {\n\t\t\te.printStackTrace();\n\t\t} finally {\n\t\t\tJDBCUtil.closeConnection(connection);\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tpublic static String bean2Json(Object object) {\n\t\tGson gson = new Gson();\n\t\tString json = gson.toJson(object);\n\n\t\treturn json;\n\t}\n\n\tpublic static Object json2Bean(String json, Class<?> classOfT) {\n\t\tGson gson = new Gson();\n\t\tObject bean = gson.fromJson(json, classOfT);\n\n\t\treturn bean;\n\t}\n}",
"public class JsoupUtil {\n\tpublic static Document connect(String url) throws IOException {\n\t\t// 十秒超时连接\n\t\treturn Jsoup.connect(url).timeout(10000).get();\n\t}\n}",
"public class SystemUtil {\n\t/**\n\t * 获取当日时间的字符串\n\t * \n\t * @return\n\t */\n\tpublic static String getDate() {\n\t\tDate date = new Date();\n\t\tSimpleDateFormat dateFormat = new SimpleDateFormat(\"yyyy-MM-dd\");\n\t\treturn dateFormat.format(date);\n\t}\n\n\tpublic static String getCurrentYear() {\n\t\tDate date = new Date();\n\t\tSimpleDateFormat dateFormat = new SimpleDateFormat(\"yyyy\");\n\t\treturn dateFormat.format(date);\n\t}\n\n\tpublic static <T> T jsonParser(String urlString, Class<T> aClass)\n\t\t\tthrows MalformedURLException, IOException {\n\t\ttry {\n\t\t\tURL url = new URL(urlString);\n\t\t\tHttpURLConnection urlcon = (HttpURLConnection) url.openConnection();\n\t\t\t// 设置请求头,反爬虫,模拟browser\n\t\t\turlcon.setRequestProperty(\n\t\t\t\t\t\"User-Agent\",\n\t\t\t\t\t\"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.87 Safari/537.36\");\n\t\t\turlcon.connect(); // 获取连接\n\t\t\tInputStream is = urlcon.getInputStream();\n\t\t\tBufferedReader buffer = new BufferedReader(\n\t\t\t\t\tnew InputStreamReader(is));\n\t\t\tStringBuffer bs = new StringBuffer();\n\t\t\tString l = null;\n\t\t\twhile ((l = buffer.readLine()) != null) {\n\t\t\t\tbs.append(l);\n\t\t\t}\n\t\t\t// bs是json\n\t\t\tString json = bs.toString();\n\t\t\tT fromJson = new Gson().fromJson(json, aClass);\n\t\t\treturn fromJson;\n\t\t} catch (MalformedURLException e) {\n\t\t\te.printStackTrace();\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\n\t\treturn null;\n\t}\n}"
] | import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import com.mollychin.bean.MovieInfo;
import com.mollychin.bean.MovieInfo.ActorInfo;
import com.mollychin.utils.ConstantsUtil;
import com.mollychin.utils.DownloadUtil;
import com.mollychin.utils.JDBCUtil;
import com.mollychin.utils.JsoupUtil;
import com.mollychin.utils.SystemUtil; | package com.mollychin.spider;
/**
* Created by mollychin on 2016/11/16.
*/
public class MovieSpider {
public final static String PICTURE4MOVIE = "Picture4Movie/";
public void movieSpider() {
try {
MovieSpider movieParser = new MovieSpider();
Document document = JsoupUtil.connect(ConstantsUtil.MOVIE_URL);
Connection conn = JDBCUtil.getConnection();
MovieInfo movieInfo = new MovieInfo(); | ActorInfo actorInfo = new ActorInfo(); | 1 |
wymarc/astrolabe-generator | src/main/java/com/wymarc/astrolabe/generator/printengines/postscript/extras/horary/EqualHours.java | [
"public class Astrolabe {\n\n public static final String[] SHOWOPTIONS = { \"Climate and mater\", \"Climate only\", \"Mater only\", \"Mater and nauticum\"};\n public static final String[] SHAPEOPTIONS = { \"Classic\", \"Octagonal\"};\n public static final String[] HOUROPTIONS = { \"Roman\", \"Arabic\", \"Alphabet\"};\n public static final String[] DEGREESCALEOPTIONS = { \"None\", \"0-90\", \"0-360\"};\n public static final String[] ALTITUDEINTERVALOPTIONS = { \"1\", \"2\", \"5\", \"10\"};\n public static final String[] TOPLEFTOPTIONS = { \"Blank\", \"Unequal hours\", \"Sine scale\", \"Both\"};\n public static final String[] TOPRIGHTOPTIONS = { \"Blank\", \"Unequal hours\", \"Arcs of the signs (equal)\", \"Arcs of the signs (projected)\"};\n public static final String[] BOTTOMLEFTOPTIONS = { \"Blank\", \"7 Shadow square\", \"10 Shadow square\", \"12 Shadow square\", \"Horizontal shadow scale\"};\n public static final String[] BOTTOMRIGHTOPTIONS = { \"Blank\", \"7 shadow square\", \"10 shadow square\", \"12 shadow square\", \"Horizontal shadow scale\"};\n public static final String[] RETEOPTIONS = { \"Classic rete\", \"Classic rete with zodiac\", \"Modern rete\"};\n\n\n public static final String[] ROMANHOURS = { \"XII\", \"XI\", \"X\", \"IX\", \"VIII\", \"VII\", \"VI\", \"V\", \"IIII\", \"III\", \"II\", \"I\" };\n public static final String[] S_ROMANHOURS = { \"XII\", \"I\", \"II\", \"III\", \"IV\", \"V\", \"VI\", \"VII\", \"VIII\", \"IX\", \"X\", \"XI\" };\n\n public static final String[] ARABICHOURS = { \"12\", \"11\", \"10\", \"9\", \"8\", \"7\", \"6\", \"5\", \"4\", \"3\", \"2\", \"1\" };\n public static final String[] S_ARABICHOURS = { \"12\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"10\", \"11\" };\n\n public static final String[] ROMAN = { \"I\", \"II\", \"III\", \"IV\", \"V\", \"VI\", \"VII\", \"VIII\", \"IX\", \"X\", \"XI\", \"XII\" };\n public static final String[] S_ROMAN = { \"I\", \"XII\", \"XI\", \"X\", \"IX\", \"VIII\", \"VII\", \"VI\", \"V\", \"IV\", \"III\", \"II\" };\n\n public static final String[] SYMBOLLETTERS = { \"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"K\", \"L\", \"M\",\n \"N\", \"O\", \"P\", \"Q\", \"R\", \"S\", \"T\", \"V\", \"X\", \"Y\", \"Z\" };\n\n public static final String[] ZODIAC = { \"Aries\", \"Taurus\", \"Gemini\", \"Cancer\", \"Leo\", \"Virgo\", \"Libra\",\n \"Scorpio\", \"Sagittarius\", \"Capricorn\", \"Aquarius\", \"Pisces\" };\n\n public static final String[] MONTHS = { \"January\", \"February\", \"March\", \"April\", \"May\",\n \"June\", \"July\", \"August\", \"September\", \"October\", \"November\", \"December\" };\n\n public static final int[] MONTHSDAYS = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };\n\n public static final String[] LUNARHOUSESNAMES = {\"Alnath\",\"Allothaim\",\"Achaomazon\",\"Aldebaram\",\n \"Alchatay\",\"Alhanna\",\"Aldimiach\",\"Alnaza\",\"Archaam\",\"Algelioche\",\"Azobra\",\"Alzarpha\",\n \"Alhaire\",\"Achureth\",\"Agrapha\",\"Azubene\",\"Alchil\",\"Alchas\",\"Allatha\",\"Abnahaya\",\n \"Abeda\",\"Sadahacha\",\"Zabadola\",\"Sadabath\",\"Sadalbracha\",\"Alpharg\",\"Alcharya\",\"Albotham\" };\n\n\n private String userName; // name of user\n private Location location; // location of astrolabe\n\n private double plateDiameter; // diameter of the plate in inches\n private double limbWidth; // width of limb in inches\n private int degreeInterval; // in degrees\n private int azimuthInterval; // in degrees\n private int almucanterInterval; // in degrees\n private int degreeScaleType; // show/hide Front degree scale\n private boolean showAzimuthLines; // show/hide azimuth lines\n private boolean showTwilightLines; // show/hide twilight lines\n private boolean showAllTwilightLines; // show all three twilight lines\n private boolean showUnequalHoursLines; // show/hide unequal hour lines on plate\n private boolean showHousesofHeavenLines; // show/hide houses lines on plate\n private boolean showThrone; \t\t// print the mater throne\n private int shapeOption;\t\t\t\t\t// selects shape of mater and throne\n private boolean zodiacSymbols;\t\t\t\t// Use zodiac symbols on ecliptic instead of labels\n private int hourMarkings; \t// use roman numerals/arabic/alphabet\n\n private boolean showCosine; // show the cosine scale on the sine quadrant scale\n private boolean use100; // show the 100 scale as opposed to the 60 scale\n private boolean gridPerDegree; // show the grid lines for every degree\n private boolean showRadials; // show the 15 degree radial lines\n private boolean showArcs; // show 20 degree arcs\n private boolean showObliqityArc; // show the obliqity arc\n\n private boolean showTimeCorrection;\t\t // Print time correction on back\n private boolean showCotangentScale;\t\t // Print cotangent scale on back\n private boolean concentricCalendar; // use the concentric calendar\n private int frontPrintOption;\t\t\t\t// 0 print both, 1 print Mater only, 2 print Climate only\n private boolean showHorizonPlate; \t// show horizon plate\n private boolean showLunarMansions; \t// show lunar mansions\n private boolean showEquationOfTime; // show Equation of Time scale\n\n private boolean showRegistrationMarks; // print registation marks for assembly\n\n private int reteType; \t\t // rete type\n\n private double capricornRadius; // radius of the tropic of capricorn in points\n private double equatorRadius; // radius of the equator in points\n private double cancerRadius; // radius of the tropic of cancer in points\n private double materRadius; // radius of the tropic of cancer plus limb width in points\n private double innerLimbRadius; // radius of the inner limb edge in points\n private double universalLimbRadius; // radius of the inner limb edge in points for the universal astrolabe\n private double plateGap; \t\t// width of the space on the edge of the plates in points\n\n private int topLeft;\t\t\t\t\t\t// contents of back\n private int topRight;\n private int bottomLeft;\n private int bottomRight;\n\n private boolean printUniversalAstrolabe; // print Universal Astrolabe sheets\n private boolean printAlidadeSheet; \t // print alidadeSheet page\n private boolean printRuleSheet; \t\t// print ruleSheet page\n private boolean counterChanged; // print alidadeSheet and ruleSheet counterchanged\n\n private boolean printBasicHoraryQuadrant; //print the basic type horary quadrant as an extra\n private boolean printAdvancedHoraryQuadrant;//print the adv type horary quadrant as an extra\n private boolean printEqualHoursHoraryQuadrant;//print the equal hours type horary quadrant as an extra\n private boolean printSineQuadrant; //print the sine quadrant as an extra\n private boolean printColorSineQuadrant; //print the colored sine quadrant as an extra\n private boolean printAdvancedSineQuadrant; //print the advanced sine quadrant as an extra\n\n private List<JCheckBox> climateSetCheckboxes; // holder for the climate plate set checkboxes\n\n private String filePath = null; //holder for session save path\n\n // rete ecliptic lines\n public int LONGL = 20; // marks between signs\n public int MED = 7;\t// 5 degree marks\n public int SHORT = 5; //degree ticks\n public int TENL = 10; // 10 degree marks\n\n\n public String getUserName() {\n return userName;\n }\n\n public void setUserName(String userName) {\n this.userName = userName;\n }\n\n public double getPlateDiameter() {\n return plateDiameter;\n }\n\n public void setPlateDiameter(double plateDiameter) {\n this.plateDiameter = plateDiameter;\n }\n\n public double getLimbWidth() {\n return limbWidth;\n }\n\n public void setLimbWidth(double limbWidth) {\n this.limbWidth = limbWidth;\n }\n\n public int getDegreeInterval() {\n return degreeInterval;\n }\n\n public void setDegreeInterval(int degreeInterval){\n this.degreeInterval = degreeInterval;\n\n if (degreeInterval == 0)\n {\n this.almucanterInterval = 1;\n this.azimuthInterval = 5;\n }else if (degreeInterval == 1)\n {\n this.almucanterInterval = 2;\n this.azimuthInterval = 5;\n }else if (degreeInterval == 2)\n {\n this.almucanterInterval = 5;\n this.azimuthInterval = 5;\n }else\n {\n this.almucanterInterval = 10;\n this.azimuthInterval = 10;\n }\n }\n\n public int getAzimuthInterval() {\n return azimuthInterval;\n }\n\n public void setAzimuthInterval(int azimuthInterval) {\n this.azimuthInterval = azimuthInterval;\n }\n\n public int getAlmucanterInterval() {\n return almucanterInterval;\n }\n\n public void setAlmucanterInterval(int almucanterInterval) {\n this.almucanterInterval = almucanterInterval;\n }\n\n public int getDegreeScaleType(){\n return degreeScaleType;\n }\n\n public void setDegreeScaleType(int degreeScaleType){\n this.degreeScaleType = degreeScaleType;\n }\n\n public boolean getShowAzimuthLines() {\n return showAzimuthLines;\n }\n\n public void setShowAzimuthLines(boolean showAzimuthLines) {\n this.showAzimuthLines = showAzimuthLines;\n }\n\n public boolean getShowTwilightLines() {\n return showTwilightLines;\n }\n\n public void setShowTwilightLines(boolean showTwilightLines) {\n this.showTwilightLines = showTwilightLines;\n }\n\n public boolean getShowAllTwilightLines() {\n return showAllTwilightLines;\n }\n\n public void setShowAllTwilightLines(boolean showAllTwilightLines) {\n this.showAllTwilightLines = showAllTwilightLines;\n }\n\n public boolean getShowUnequalHoursLines() {\n return showUnequalHoursLines;\n }\n\n public void setShowUnequalHoursLines(boolean showUnequalHoursLines) {\n this.showUnequalHoursLines = showUnequalHoursLines;\n }\n\n public boolean getShowHousesofHeavenLines() {\n return showHousesofHeavenLines;\n }\n\n public void setShowHousesofHeavenLines(boolean showHousesofHeavenLines) {\n this.showHousesofHeavenLines = showHousesofHeavenLines;\n }\n\n public boolean getShowThrone() {\n return showThrone;\n }\n\n public void setShowThrone(boolean showThrone) {\n this.showThrone = showThrone;\n }\n\n public Boolean getShowZodiacSymbols(){\n return this.zodiacSymbols;\n }\n\n public void setShowZodiacSymbols(Boolean zodiacSymbols){\n this.zodiacSymbols = zodiacSymbols;\n }\n\n public int getShapeOption(){\n return this.shapeOption;\n }\n\n public void setShapeOption(int shapeOption){\n this.shapeOption = shapeOption;\n }\n\n public int getHourMarkings() {\n return hourMarkings;\n }\n\n public void setHourMarkings(int hourMarkings) {\n this.hourMarkings = hourMarkings;\n }\n\n public boolean getShowCosine() {\n return showCosine;\n }\n\n public void setShowCosine(boolean showCosine) {\n this.showCosine = showCosine;\n }\n\n public boolean getUse100() {\n return use100;\n }\n\n public void setUse100(boolean use100) {\n this.use100 = use100;\n }\n\n public boolean getGridPerDegree() {\n return gridPerDegree;\n }\n\n public void setGridPerDegree(boolean gridPerDegree) {\n this.gridPerDegree = gridPerDegree;\n }\n\n public boolean getShowRadials() {\n return showRadials;\n }\n\n public void setShowRadials(boolean showRadials) {\n this.showRadials = showRadials;\n }\n\n public boolean getShowArcs() {\n return showArcs;\n }\n\n public void setShowArcs(boolean showArcs) {\n this.showArcs = showArcs;\n }\n\n public boolean getShowObliqityArc() {\n return showObliqityArc;\n }\n\n public void setShowObliqityArc(boolean showObliqityArc) {\n this.showObliqityArc = showObliqityArc;\n }\n\n public boolean getShowTimeCorrection() {\n return showTimeCorrection;\n }\n\n public void setShowTimeCorrection(boolean showTimeCorrection) {\n this.showTimeCorrection = showTimeCorrection;\n }\n\n public boolean getShowCotangentScale() {\n return showCotangentScale;\n }\n\n public void setShowCotangentScale(boolean showCotangentScale) {\n this.showCotangentScale = showCotangentScale;\n }\n\n public boolean getShowConcentricCalendar() {\n return concentricCalendar;\n }\n\n public void setShowConcentricCalendar(boolean concentricCalendar) {\n this.concentricCalendar = concentricCalendar;\n }\n\n public int getFrontPrintOption() {\n return frontPrintOption;\n }\n\n public void setFrontPrintOption(int frontPrintOption) {\n this.frontPrintOption = frontPrintOption;\n }\n\n public boolean getShowHorizonPlate() {\n return showHorizonPlate;\n }\n\n public void setShowHorizonPlate(boolean showHorizonPlate) {\n this.showHorizonPlate = showHorizonPlate;\n }\n\n public boolean getShowLunarMansions() {\n return showLunarMansions;\n }\n\n public void setShowLunarMansions(boolean showLunarMansions) {\n this.showLunarMansions = showLunarMansions;\n }\n\n public boolean getShowEquationOfTime() {\n return showEquationOfTime;\n }\n\n public void setShowEquationOfTime(boolean showEquationOfTime) {\n this.showEquationOfTime = showEquationOfTime;\n }\n\n public boolean getShowRegistrationMarks() {\n return showRegistrationMarks;\n }\n\n public void setShowRegistrationMarks(boolean showRegistrationMarks) {\n this.showRegistrationMarks = showRegistrationMarks;\n }\n\n public int getReteType() {\n return reteType;\n }\n\n public void setReteType(int reteType) {\n this.reteType = reteType;\n }\n\n public double getCapricornRadius() {\n return capricornRadius;\n }\n\n public void setCapricornRadius(double capricornRadius) {\n this.capricornRadius = capricornRadius;\n }\n\n public double getEquatorRadius() {\n return equatorRadius;\n }\n\n public void setEquatorRadius(double equatorRadius) {\n this.equatorRadius = equatorRadius;\n }\n\n public double getCancerRadius() {\n return cancerRadius;\n }\n\n public void setCancerRadius(double cancerRadius) {\n this.cancerRadius = cancerRadius;\n }\n\n public double getMaterRadius() {\n return materRadius;\n }\n\n public void setMaterRadius(double materRadius) {\n this.materRadius = materRadius;\n }\n\n public double getUniversalLimbRadius() {\n return universalLimbRadius;\n }\n\n public double getInnerLimbRadius() {\n return innerLimbRadius;\n }\n\n public void setInnerLimbRadius(double innerLimbRadius) {\n this.innerLimbRadius = innerLimbRadius;\n }\n\n public double getPlateGap() {\n return plateGap;\n }\n\n public void setPlateGap(double plateGap) {\n this.plateGap = plateGap;\n }\n\n public int getTopLeft() {\n return topLeft;\n }\n\n public void setTopLeft(int topLeft) {\n this.topLeft = topLeft;\n }\n\n public int getTopRight() {\n return topRight;\n }\n\n public void setTopRight(int topRight) {\n this.topRight = topRight;\n }\n\n public int getBottomLeft() {\n return bottomLeft;\n }\n\n public void setBottomLeft(int bottomLeft) {\n this.bottomLeft = bottomLeft;\n }\n\n public int getBottomRight() {\n return bottomRight;\n }\n\n public void setBottomRight(int bottomRight) {\n this.bottomRight = bottomRight;\n }\n\n public boolean getPrintUniversalAstrolabe() {\n return printUniversalAstrolabe;\n }\n\n public void setPrintUniversalAstrolabe(boolean printUniversalAstrolabe) {\n this.printUniversalAstrolabe = printUniversalAstrolabe;\n }\n\n public boolean getPrintAlidadeSheet() {\n return printAlidadeSheet;\n }\n\n public void setPrintAlidadeSheet(boolean printAlidadeSheet) {\n this.printAlidadeSheet = printAlidadeSheet;\n }\n\n public boolean getPrintRuleSheet() {\n return printRuleSheet;\n }\n\n public void setPrintRuleSheet(boolean printRuleSheet) {\n this.printRuleSheet = printRuleSheet;\n }\n\n public boolean isCounterChanged() {\n return counterChanged;\n }\n\n public void setCounterChanged(boolean counterChanged) {\n this.counterChanged = counterChanged;\n }\n\n public boolean getPrintBasicHoraryQuadrant() {\n return printBasicHoraryQuadrant;\n }\n\n public void setPrintBasicHoraryQuadrant(boolean printBasicHoraryQuadrant) {\n this.printBasicHoraryQuadrant = printBasicHoraryQuadrant;\n }\n\n public boolean getPrintAdvancedHoraryQuadrant() {\n return printAdvancedHoraryQuadrant;\n }\n\n public void setPrintAdvancedHoraryQuadrant(boolean printAdvancedHoraryQuadrant) {\n this.printAdvancedHoraryQuadrant = printAdvancedHoraryQuadrant;\n }\n\n public boolean getPrintEqualHoursHoraryQuadrant() {\n return printEqualHoursHoraryQuadrant;\n }\n\n public void setPrintEqualHoursHoraryQuadrant(boolean printEqualHoursHoraryQuadrant) {\n this.printEqualHoursHoraryQuadrant = printEqualHoursHoraryQuadrant;\n }\n\n public boolean getPrintSineQuadrant() {\n return printSineQuadrant;\n }\n\n public void setPrintSineQuadrant(boolean printSineQuadrant) {\n this.printSineQuadrant = printSineQuadrant;\n }\n\n public boolean getPrintColorSineQuadrant() {\n return printColorSineQuadrant;\n }\n\n public void setPrintColorSineQuadrant(boolean printColorSineQuadrant) {\n this.printColorSineQuadrant = printColorSineQuadrant;\n }\n\n public boolean getPrintAdvancedSineQuadrant() {\n return printAdvancedSineQuadrant;\n }\n\n public void setPrintAdvancedSineQuadrant(boolean printAdvancedSineQuadrant) {\n this.printAdvancedSineQuadrant = printAdvancedSineQuadrant;\n }\n\n public List<JCheckBox> getClimateSetCheckboxes() {\n return climateSetCheckboxes;\n }\n\n public void setClimateSetCheckboxes(List<JCheckBox> climateSetCheckboxes) {\n this.climateSetCheckboxes = climateSetCheckboxes;\n }\n\n public Location getLocation(){\n return this.location;\n }\n\n public String getFilePath() {\n return filePath;\n }\n\n public void setFilePath(String filePath) {\n this.filePath = filePath;\n }\n\n\n public Astrolabe(){\n // initialize settings\n this.userName = \"Your Name\";\n this.location = new Location(\"Pennsic War\",40,58,35,\"N\",80,8,9,\"W\");\n this.plateDiameter = 6;\n this.plateGap = 14; //gap on edge of plate\n this.limbWidth = .5;\n this.degreeInterval = 2; // 5 Degrees\n this.azimuthInterval = 5;\n this.almucanterInterval = 5;\n this.degreeScaleType = 0;\n this.showAzimuthLines = true;\n this.showTwilightLines = true;\n this.showAllTwilightLines = false;\n this.showHousesofHeavenLines = true;\n this.showUnequalHoursLines = false;\n this.showThrone = true;\n this.shapeOption = 1;\n this.zodiacSymbols = false;\n this.hourMarkings = 0;\n\n this.showRegistrationMarks = true;\n this.showTimeCorrection = true;\n this.showCotangentScale = true;\n this.concentricCalendar = false;\n this.showLunarMansions = false;\n this.showEquationOfTime = false;\n this.frontPrintOption = 0; // default to printing both\n this.showHorizonPlate = false;\n\n this.reteType = 0;\n\n this.topLeft = 1; // Unequal hours\n this.topRight = 1; // Unequal hours\n this.bottomLeft = 1; // 7 Shadow Square\n this.bottomRight = 2; // 12 Shadow Square\n this.printUniversalAstrolabe = false;\n this.printAlidadeSheet = false;\n this.printRuleSheet = false;\n this.counterChanged = true;\n\n // todo this needs to have the eps code removed\n this.capricornRadius = ((72 * this.plateDiameter) / 2.0) - this.plateGap;\n this.equatorRadius = this.capricornRadius * (Math.tan(Math.toRadians((90 - 23.44) / 2.0)));\n this.cancerRadius = this.equatorRadius * (Math.tan(Math.toRadians((90 - 23.44) / 2.0)));\n this.materRadius = ((72 * this.plateDiameter) / 2.0) + (this.limbWidth * 72);\n this.innerLimbRadius = (72 * this.plateDiameter) / 2.0;\n this.universalLimbRadius = (72 * (this.plateDiameter + 0.5)) / 2.0;\n }\n\n}",
"public class EPSToolKit {\n\n /**\n * generates EPS header code for file\n *\n * @param myAstrolabe The current Astrolabe\n * @param Title The files title\n * @return String EPS output\n */\n public static String getHeader(Astrolabe myAstrolabe, String Title){\n\n Date Now = new Date();\n\n String out = \"%!PS-Adobe-3.0 EPSF-30.\";\n out += \"\\n\" + \"%%BoundingBox: 0 0 612 792\";\n out += \"\\n\" + \"%%Title: \" + Title;\n out += \"\\n\" + \"%%Creator: Richard Wymarc\";\n out += \"\\n\" + \"%%CreationDate: \" + Now.toString();\n out += \"\\n\" + \"%%EndComments\";\n out += \"\\n\" + \"%% Astrolabe Generator Postscript file\";\n out += \"\\n\" + \"%% for Latitude: \" + myAstrolabe.getLocation().getLatitude();\n out += \"\\n\" + \"%% for Longitude: \" + myAstrolabe.getLocation().getLongitude();\n out += \"\\n\" + \"\";\n out += \"\\n\" + \"mark\";\n out += \"\\n\" + \"/Astrolabe 10 dict def %local variable dictionary\";\n out += \"\\n\" + \"Astrolabe begin\";\n out += \"\\n\" + \"\";\n return out;\n }\n\n public static String setClippingBox(double x1, double y1, double x2, double y2){\n String out = \"\";\n out += \"\\n\" + \"newpath\";\n out += \"\\n\" + x1 + \" \" + y1 + \" moveto\";\n out += \"\\n\" + x1 + \" \" + y2 + \" lineto\";\n out += \"\\n\" + x2 + \" \" + y2 + \" lineto\";\n out += \"\\n\" + x2 + \" \" + y1 + \" lineto\";\n out += \"\\n\" + \"closepath clip\";\n\n return out;\n }\n\n\n\n /**\n * Fills the page (8.5\" x 11\") with white.\n *\n * @return String EPS output\n */\n public static String fillBackground(){\n // Fills the page (8.5\" x 11\") with white. \n String out = \"\";\n out += \"\\n\" + \"% Fill Background\";\n out += \"\\n\" + \"1 setgray\";\n out += \"\\n\" + \"newpath\";\n out += \"\\n\" + \"0 0 moveto\";\n out += \"\\n\" + \"0 792 lineto\";\n out += \"\\n\" + \"612 792 lineto\";\n out += \"\\n\" + \"612 0 lineto\";\n out += \"\\n\" + \"0 0 lineto\";\n out += \"\\n\" + \"fill\";\n out += \"\\n\" + \"0 setgray\";\n\n return out;\n }\n\n /**\n * Draws four registration marks to ease assembly and fills background\n *\n * @return String EPS output\n */\n public static String registrationMarks(){\n String out = \"\";\n out += \"\\n\" + \"%% ================ Draw Registration Marks =================\";\n // Fills the page (8.5\" x 11\") with white. \n out += fillBackground();\n\n // Marks the page (8.5\" x 11\") with corner Reg marks\n out += \"\\n\" + \"% Registration Marks\";\n out += \"\\n\" + \".1 setlinewidth\";\n out += \"\\n\" + \"36 36 5 0 360 arc stroke\";\n out += \"\\n\" + \"30 36 moveto\";\n out += \"\\n\" + \"50 36 lineto stroke\";\n out += \"\\n\" + \"36 30 moveto\";\n out += \"\\n\" + \"36 50 lineto stroke\";\n out += \"\\n\" + \"576 36 5 0 360 arc stroke\";\n out += \"\\n\" + \"582 36 moveto\";\n out += \"\\n\" + \"562 36 lineto stroke\";\n out += \"\\n\" + \"576 30 moveto\";\n out += \"\\n\" + \"576 50 lineto stroke\";\n out += \"\\n\" + \"576 756 5 0 360 arc stroke\";\n out += \"\\n\" + \"582 756 moveto\";\n out += \"\\n\" + \"562 756 lineto stroke\";\n out += \"\\n\" + \"576 762 moveto\";\n out += \"\\n\" + \"576 742 lineto stroke\";\n out += \"\\n\" + \"36 756 5 0 360 arc stroke\";\n out += \"\\n\" + \"30 756 moveto\";\n out += \"\\n\" + \"50 756 lineto stroke\";\n out += \"\\n\" + \"36 762 moveto\";\n out += \"\\n\" + \"36 742 lineto stroke\";\n //612 x 792\n out += \"\\n\" + \"%% ================ End Registration Marks =================\";\n return out;\n }\n\n /**\n * Centers a given text string at the current point\n *\n * @param textString String to be centered\n * @return Centered string EPS output\n */\n public static String centerText(String textString){\n return \"\\n\" + \"(\" + textString + \") dup stringwidth pop 2 div neg 0 rmoveto show\";\n }\n\n\n /**\n * Right justifies given text string at the current point\n *\n * @param textString String to be printed\n * @return Centered string EPS output\n */\n public static String rightJustifyText(String textString){\n return \"\\n\" + \"(\" + textString + \") dup stringwidth pop neg 0 rmoveto show\";\n }\n\n\n /**\n * Sets up fonts\n *\n * Run once at the beginning of the PS/EPS file, after the header code\n *\n * @return String EPS output\n *\n */\n public static String setUpFonts(){\n String out = \"\";\n out += \"\\n\" + \"%% ================ Set Up Fonts =================\";\n out += \"\\n\" + \"/NormalFont /Times-Roman findfont\";\n out += \"\\n\" + \"dup length dict begin {1 index /FID ne {def} {pop pop} ifelse} forall\";\n out += \"\\n\" + \"/Encoding ISOLatin1Encoding def currentdict end\";\n out += \"\\n\" + \"/Times-Roman-ISOLatin1 exch definefont\";\n out += \"\\n\" + \"def\";\n out += \"\\n\" + \"/NormalFont5 NormalFont 5 scalefont def\";\n out += \"\\n\" + \"/NormalFont6 NormalFont 6 scalefont def\";\n out += \"\\n\" + \"/NormalFont7 NormalFont 7 scalefont def\";\n out += \"\\n\" + \"/NormalFont8 NormalFont 8 scalefont def\";\n out += \"\\n\" + \"/NormalFont10 NormalFont 10 scalefont def\";\n out += \"\\n\" + \"/NormalFont12 NormalFont 12 scalefont def\";\n out += \"\\n\" + \"/NormalFont14 NormalFont 14 scalefont def\";\n out += \"\\n\" + \"/NormalFont16 NormalFont 16 scalefont def\";\n out += \"\\n\" + \"/NormalFont18 NormalFont 18 scalefont def\";\n out += \"\\n\" + \"/NormalFont20 NormalFont 20 scalefont def\";\n\n out += \"\\n\" + \"%% ================ End Set Up Fonts =================\";\n\n return out;\n }\n\n /**\n * Sets up PS routines to print rotated text\n *\n * Run once at the beginning of the PS/EPS file, after the header code\n *\n * @return String EPS output\n */\n public static String setUpTextRotation(){\n String out = \"\";\n out += \"\\n\" + \"%% ================ Set Up Rotated Text Routine =================\";\n out += \"\\n\" + \"% text rotation function\";\n out += \"\\n\" + \"% x y fontsize rotation (text) outputtext\";\n out += \"\\n\" + \"% ex: 20 300 12 80 (text1) outputtext\";\n out += \"\\n\" + \"/outputtext {\";\n out += \"\\n\" + \" /data exch def\";\n out += \"\\n\" + \" /rot exch def\";\n out += \"\\n\" + \" /xfont exch def\";\n out += \"\\n\" + \" /y1 exch def\";\n out += \"\\n\" + \" /x1 exch def\";\n out += \"\\n\" + \" /Times-Roman findfont\";\n out += \"\\n\" + \" xfont scalefont\";\n out += \"\\n\" + \" setfont\";\n out += \"\\n\" + \" x1 y1 moveto\";\n out += \"\\n\" + \" rot rotate\";\n out += \"\\n\" + \" data show\";\n out += \"\\n\" + \" rot neg rotate\";\n out += \"\\n\" + \"} def\";\n out += \"\\n\";\n\n return out;\n }\n\n /**\n * Sets up a set of PS routines to print circular text\n *\n * Postscript routine gleefully stolen and modified from the \"Blue Book\":\n * PostScript Language Tutorial and Cookbook, Adobe Systems Inc.\n *\n * Run once at the beginning of the PS/EPS file, after the header code\n *\n * @return String EPS output\n */\n public static String setUpCircularText(){\n String out = \"\";\n out += \"\\n\" + \"%% ================ Set Up Circular Text Routine =================\";\n out += \"\\n\" + \"/outsidecircletext\";\n out += \"\\n\" + \"{ circtextdict begin\";\n out += \"\\n\" + \"/radius exch def\";\n out += \"\\n\" + \"/centerangle exch def\";\n out += \"\\n\" + \"/ptsize exch def\";\n out += \"\\n\" + \"/str exch def\";\n out += \"\\n\" + \"/xradius radius ptsize 4 div add def\";\n out += \"\\n\" + \"\";\n out += \"\\n\" + \"gsave\";\n out += \"\\n\" + \"centerangle str findhalfangle add rotate\";\n out += \"\\n\" + \"\";\n out += \"\\n\" + \"str\";\n out += \"\\n\" + \"{ /charcode exch def\";\n out += \"\\n\" + \"( ) dup 0 charcode put outsideplacechar\";\n out += \"\\n\" + \"} forall\";\n out += \"\\n\" + \"grestore\";\n out += \"\\n\" + \"end\";\n out += \"\\n\" + \"} def\";\n out += \"\\n\" + \"\";\n out += \"\\n\" + \"/insidecircletext\";\n out += \"\\n\" + \"{ circtextdict begin\";\n out += \"\\n\" + \"/radius exch def /centerangle exch def\";\n out += \"\\n\" + \"/ptsize exch def /str exch def\";\n out += \"\\n\" + \"/xradius radius ptsize 3 div sub def\";\n out += \"\\n\" + \"gsave\";\n out += \"\\n\" + \"centerangle str findhalfangle sub rotate\";\n out += \"\\n\" + \"str\";\n out += \"\\n\" + \"{ /charcode exch def\";\n out += \"\\n\" + \"( ) dup 0 charcode put insideplacechar\";\n out += \"\\n\" + \"} forall\";\n out += \"\\n\" + \"grestore\";\n out += \"\\n\" + \"end\";\n out += \"\\n\" + \"} def\";\n out += \"\\n\" + \"\";\n out += \"\\n\" + \"/circtextdict 16 dict def\";\n out += \"\\n\" + \"circtextdict begin\";\n out += \"\\n\" + \"/findhalfangle\";\n out += \"\\n\" + \"{ stringwidth pop 2 div\";\n out += \"\\n\" + \"2 xradius mul pi mul div 360 mul\";\n out += \"\\n\" + \"} def\";\n out += \"\\n\" + \"\";\n out += \"\\n\" + \"/outsideplacechar\";\n out += \"\\n\" + \"{ /char exch def\";\n out += \"\\n\" + \"/halfangle char findhalfangle def\";\n out += \"\\n\" + \"gsave\";\n out += \"\\n\" + \"halfangle neg rotate\";\n out += \"\\n\" + \"radius 0 translate\";\n out += \"\\n\" + \"-90 rotate\";\n out += \"\\n\" + \"char stringwidth pop 2 div neg 0 moveto\";\n out += \"\\n\" + \"char show\";\n out += \"\\n\" + \"grestore\";\n out += \"\\n\" + \"halfangle 2 mul neg rotate\";\n out += \"\\n\" + \"} def\";\n out += \"\\n\" + \"\";\n out += \"\\n\" + \"/insideplacechar\";\n out += \"\\n\" + \"{ /char exch def\";\n out += \"\\n\" + \"/halfangle char findhalfangle def\";\n out += \"\\n\" + \"gsave\";\n out += \"\\n\" + \"halfangle rotate\";\n out += \"\\n\" + \"radius 0 translate\";\n out += \"\\n\" + \"90 rotate\";\n out += \"\\n\" + \"char stringwidth pop 2 div neg 0 moveto\";\n out += \"\\n\" + \"char show\";\n out += \"\\n\" + \"grestore\";\n out += \"\\n\" + \"halfangle 2 mul rotate\";\n out += \"\\n\" + \"} def\";\n out += \"\\n\" + \"/pi 3.1415923 def\";\n out += \"\\n\" + \"end\";\n out += \"\\n\" + \"\";\n out += \"\\n\" + \"%% ================ End Circular Text Routine =================\";\n\n return out;\n }\n\n /**\n * Calls PS routine to print circular text: outsidecircletext\n *\n * @param textIn \tString to be printed\n * @param pointSize Pointsize the string was set to\n * @param angle \tAngle the text is to be centered on\n * @param radius \tRadius of the circle\n *\n * @return String EPS output\n */\n public static String drawOutsideCircularText(String textIn, double pointSize, double angle, double radius){\n return \"\\n\" + \"(\" +textIn+ \") \"+ pointSize +\" \"+ angle +\" \" +radius+ \" outsidecircletext\";\n }\n\n /**\n * Calls PS routine to print circular text: Center Above\n *\n * @param textIn \tString to be printed\n * @param pointSize Pointsize the string was set to\n * @param angle \tAngle the text is to be centered on\n * @param radius \tRadius of the circle\n *\n * @return String EPS output\n */\n public static String drawInsideCircularText(String textIn, double pointSize, double angle, double radius){\n // requires that setUpCircularText above is run first\n return \"\\n\" + \"(\" +textIn+ \") \"+ pointSize +\" \"+ angle +\" \" +radius+ \" insidecircletext\";\n }\n\n /**\n * Sets up definitions for symbols\n *\n * @return String EPS output\n */\n public static String setUpSymbols(){\n // call as \"x y drawX\"\n String out = \"\";\n out += \"\\n\" + \"/drawX\";\n out += \"\\n\" + \"{gsave\";\n out += \"\\n\" + \"newpath\";\n out += \"\\n\" + \"moveto\";\n out += \"\\n\" + \"-1.5 -1.5 rmoveto\";\n out += \"\\n\" + \"3 3 rlineto\";\n out += \"\\n\" + \"-3 0 rmoveto\";\n out += \"\\n\" + \"3 -3 rlineto stroke\";\n out += \"\\n\" + \"grestore}def\";\n out += \"\\n\";\n // call as \"x y drawSmallX\"\n out += \"\\n\" + \"/drawSmallX\";\n out += \"\\n\" + \"{gsave\";\n out += \"\\n\" + \"newpath\";\n out += \"\\n\" + \"moveto\";\n out += \"\\n\" + \"-1 -1 rmoveto\";\n out += \"\\n\" + \"2 2 rlineto\";\n out += \"\\n\" + \"-2 0 rmoveto\";\n out += \"\\n\" + \"2 -2 rlineto stroke\";\n out += \"\\n\" + \"grestore}def\";\n out += \"\\n\";\n // call as \"x y cross\"\n out += \"\\n\" + \"/cross\";\n out += \"\\n\" + \"{gsave\";\n out += \"\\n\" + \"newpath\";\n out += \"\\n\" + \"moveto\";\n out += \"\\n\" + \"-4 6 rlineto\";\n out += \"\\n\" + \"8 0 rlineto\";\n out += \"\\n\" + \"-4 -6 rlineto\";\n out += \"\\n\" + \"6 4 rlineto\";\n out += \"\\n\" + \"0 -8 rlineto\";\n out += \"\\n\" + \"-6 4 rlineto\";\n out += \"\\n\" + \"4 -6 rlineto\";\n out += \"\\n\" + \"-8 0 rlineto\";\n out += \"\\n\" + \"4 6 rlineto\";\n out += \"\\n\" + \"-6 -4 rlineto\";\n out += \"\\n\" + \"0 8 rlineto\";\n out += \"\\n\" + \"+6 -4 rlineto fill\";\n out += \"\\n\" + \"grestore}def\";\n out += \"\\n\";\n // call as \"x y diamond\"\n out += \"\\n\" + \"/diamond\";\n out += \"\\n\" + \"{\";\n out += \"\\n\" + \"/y exch def\";\n out += \"\\n\" + \"/x exch def\";\n out += \"\\n\" + \"gsave\";\n out += \"\\n\" + \"newpath\";\n out += \"\\n\" + \"x y moveto\";\n out += \"\\n\" + \"0 6 rmoveto\";\n out += \"\\n\" + \"6 -6 rlineto\";\n out += \"\\n\" + \"-6 -6 rlineto\";\n out += \"\\n\" + \"-6 6 rlineto\";\n out += \"\\n\" + \"6 6 rlineto\";\n out += \"\\n\" + \"-3 -3 rmoveto\";\n out += \"\\n\" + \"6 -6 rlineto\";\n out += \"\\n\" + \"0 6 rmoveto\";\n out += \"\\n\" + \"-6 -6 rlineto stroke\";\n out += \"\\n\" + \"grestore\";\n out += \"\\n\" + \"gsave\";\n out += \"\\n\" + \"newpath\";\n out += \"\\n\" + \"1 setgray\";\n out += \"\\n\" + \"x y 2 0 360 arc fill\";\n out += \"\\n\" + \"0 setgray\";\n out += \"\\n\" + \"x y 2 0 360 arc stroke\";\n out += \"\\n\" + \"grestore}def\";\n\n return out;\n }\n\n /**\n * Draws the astrolabe throne\n *\n * since 0.1\n *\n */\n public static String buildMaterThrone(Astrolabe myAstrolabe){\n String out = \"\";\n Double innerRadius = (72 * myAstrolabe.getPlateDiameter()) / 2;\n Double limb = 72 * myAstrolabe.getLimbWidth();\n Double outerRadius = innerRadius + limb;\n\n out += \"\\n\" + \"%% ================ Draw Throne =================\";\n out += \"\\n\" + \"0 \" + (outerRadius + 28) +\" 7 0 360 arc stroke\";\n out += \"\\n\" + \"0 \" + (outerRadius + 28) +\" 38 0 180 arc stroke\";\n out += \"\\n\" + \"-38 \" + (outerRadius - 10) +\" 38 90 270 arc stroke\";\n out += \"\\n\" + \"38 \" + (outerRadius - 10) +\" 38 -90 90 arc stroke\";\n out += \"\\n\" + \".1 setlinewidth\";\n out += \"\\n\" + \"0 \" + (outerRadius + 25) +\" moveto\";\n out += \"\\n\" + \"0 \" + (outerRadius + 31) +\" lineto stroke\";\n out += \"\\n\" + \"-3 \" + (outerRadius + 28) +\" moveto\";\n out += \"\\n\" + \"3 \" + (outerRadius + 28) +\" lineto stroke\";\n out += \"\\n\" + \"%% ================ Draw Throne =================\";\n return out;\n }\n\n /**\n * Draws alternatee astrolabe throne\n *\n * since 2.0\n *\n */\n public static String buildMaterThrone2(Astrolabe myAstrolabe){\n String out = \"\";\n Double innerRadius = (72 * myAstrolabe.getPlateDiameter()) / 2;\n Double limb = 72 * myAstrolabe.getLimbWidth();\n Double outerRadius = innerRadius + limb;\n\n out += \"\\n\" + \"%% ================ Draw Throne =================\";\n out += \"\\n\" + \"0 \" + (outerRadius + 20) +\" 7 0 360 arc stroke\";\n out += \"\\n\" + \"-60 \" + outerRadius +\" moveto\";\n out += \"\\n\" + \"-30 \" + (outerRadius + 40) +\" lineto\";\n out += \"\\n\" + \"30 \" + (outerRadius + 40) +\" lineto\";\n out += \"\\n\" + \"60 \" + outerRadius +\" lineto stroke\";\n\n out += \"\\n\" + \".1 setlinewidth\";\n out += \"\\n\" + \"0 \" + (outerRadius + 17) +\" moveto\";\n out += \"\\n\" + \"0 \" + (outerRadius + 23) +\" lineto stroke\";\n out += \"\\n\" + \"-3 \" + (outerRadius + 20) +\" moveto\";\n out += \"\\n\" + \"3 \" + (outerRadius + 20) +\" lineto stroke\";\n out += \"\\n\" + \"%% ================ Draw Throne =================\";\n return out;\n }\n\n /**\n * Draws an decorative octagonal frame around the limb\n *\n * Since 2.0\n *\n */\n public static String buildOctagon(Astrolabe myAstrolabe)\n {\n /**\n * The equation for the vertexes of an octagon is\n * (r*cos(a), r*sin(a)) where r is the radius of the\n * inscribed circle and a is the angle of the vertex\n *\n */\n String fileOut = \"\";\n Double radius = myAstrolabe.getMaterRadius() + 25;\n Double degreeInterval = 45.0;\n fileOut += \"\\n\" + \"%% ==================== Create Octagon Limb ====================\";\n fileOut += \"\\n\" + \"1 setgray\";\n fileOut += \"\\n\" + -degreeInterval/2.0 + \" rotate\";\n fileOut += \"\\n\" + \"newpath\";\n fileOut += \"\\n\" + radius + \" 0 moveto\";\n for(int i = 1; i<= 8; i++){\n fileOut += \"\\n\" + radius*Math.cos(Math.toRadians(degreeInterval * i)) + \" \" + radius*Math.sin(Math.toRadians(degreeInterval * i)) + \" lineto\";\n }\n fileOut += \" fill\";\n fileOut += \"\\n\" + \"0 setgray\";\n fileOut += \"\\n\" + \"newpath\";\n fileOut += \"\\n\" + radius + \" 0 moveto\";\n\n for(int i = 1; i<= 8; i++){\n fileOut += \"\\n\" + radius*Math.cos(Math.toRadians(degreeInterval * i)) + \" \" + radius*Math.sin(Math.toRadians(degreeInterval * i)) + \" lineto\";\n }\n fileOut += \" stroke\";\n\n radius = radius -3;\n\n fileOut += \"\\n\" + \"newpath\";\n fileOut += \"\\n\" + radius + \" 0 moveto\";\n\n for(int i = 1; i<= 8; i++){\n fileOut += \"\\n\" + radius*Math.cos(Math.toRadians(degreeInterval * i)) + \" \" + radius*Math.sin(Math.toRadians(degreeInterval * i)) + \" lineto\";\n }\n fileOut += \" stroke\";\n fileOut += \"\\n\" + degreeInterval/2.0 + \" rotate\";\n\n fileOut += \"\\n\" + \"%% ==================== End Create Octagon Limb ====================\";\n fileOut += \"\\n\" + \"\";\n\n return fileOut;\n }\n}",
"public class AstroMath {\n\n /**\n * normalizes angle to 0 - 360\n * ex: 405 becomes 45\n * \n * modified from Morrison\n *\n * @param angle double decimal angle to be normalized\n * @return normalized angle\n */\n public static double normal(double angle){\n while (angle < 0){\n \tangle += 360.0;\n }\n return (((angle%360.0)/360.0) * 360.0);\n }\n\n /**\n * Returns the angle of the line of apsides\n * @param t Julian Century\n * @return angle of the line of apsides\n */\n public static double angleOfLineOfApsides(double t){\n return 180 - (102.937348 + (1.7195269*t) + (0.00045962*(t*t)) + (0.000000499*(t*t*t)));\n }\n\n /**\n * Computes Julian century (T) from current date\n *\n * modified from Morrison\n *\n * @return Julian century\n */\n public static double getT(){\n Calendar calNow = Calendar.getInstance();\n\n Calendar calMidniteJan1 = new GregorianCalendar(calNow.get(Calendar.YEAR), 0, 1); // remember January is 0\n Calendar calEpoch = new GregorianCalendar(2000, 0, 1);\n\n double julianDay = 2451544.5 + ((calMidniteJan1.getTime().getTime()-calEpoch.getTime().getTime())/(1000.0*60.0*60.0*24.0));\n return (julianDay-2451545.0)/36525.0;\n }\n\n /**\n * Computes Julian day\n *\n * modified from Morrison\n *\n * @param month int month (0-11) \n * @param day int day of month (1-31)\n * @param year int Year (4 digit)\n * @param ut double time as decimal (ex 1300.15)\n * @return Julian century\n */\n public static double julianDay(int month, int day, int year, double ut){\n int jMonth;\n int jYear;\n double jDay;\n double wv;\n double dayJ;\n\n month++; // note: in java month is 0-11 we need 1-12\n\n if (month > 2){\n jMonth = month + 1;\n jYear = year;\n }else{\n jMonth = month + 13;\n jYear = year - 1;\n }\n\n dayJ = day + ut/24.0;\n jDay = integerPart(365.25 * jYear) + integerPart(30.6001 * jMonth) + dayJ + 1720994.5;\n\n if (jDay <= 2361220){ // if date prior to 9/2/1752 return julian day\n return jDay;\n }else{\n wv = integerPart(0.01 * year);\n return jDay + 2 - wv + integerPart(wv * 0.25);\n }\n }\n\n /**\n * Computes Eccentricity of Earth's orbit from Julian century\n *\n * modified from Morrison\n *\n * @param T double Julian century \n * @return Eccentricity\n */ \n public static double ecc(double T){\n return ((-1.236E-07 * T - 4.2037E-05) * T + .016708617) ;\n }\n\n /**\n * Computes Sun's eccentric anomaly ( in radians) from Julian century\n * todo rename\n * modified from Morrison\n *\n * @param T double Julian century \n * @return Sun's eccentric anomaly angle in radians\n */ \n public static double kepler(double T){\n double m;\n double e0;\n double e;\n double ea;\n m = Math.toRadians(manom(T)) ;\n ea = m ;\n e = ecc(T) ;\n do{\n e0 = ea; ea = m + e * Math.sin(e0);\n }while (Math.abs(ea - e0) > 1.0e-09);\n return (ea);\n }\n\n /**\n * Computes Sun's True anomaly from eccentric anomaly (degrees)\n * todo change to radians\n * todo check what is input\n * modified from Morrison\n *\n * @param T double Julian century \n * @return Sun's True anomaly angle in degrees\n */\n public static double tanom(double T){\n double ea;\n double e;\n double ta;\n\n ea = kepler(T);\n e = ecc(T);\n ta = Math.atan(Math.tan(ea / 2.0) * Math.sqrt((1.0 + e) / (1.0 - e)));\n if ((ta < 0.0) || (ta > 0.0 && ea > Math.PI)){\n ta = ta + Math.PI;\n }\n ta = 2.0 * ta;\n if ((ta < Math.PI) && (ea >= 3.0 * (Math.PI/2.0)))\n {\n ta = ta + Math.PI;\n }\n return (Math.toDegrees(ta));\n }\n\n /**\n * Computes Sun's mean anomaly from T (degrees)\n * todo change to radians\n * todo check what is input\n * modified from Morrison\n *\n * @param T double Julian century \n * @return Sun's mean anomaly angle in degrees\n */\n public static double manom(double T){\n return (normal(((-4.8e-07 * T - .0001559) * T + 35999.0503) * T + 357.5291));\n }\n\n /**\n * Computes Sun's mean longitude from T (degrees)\n * todo change to radians\n * todo check what is input\n * modified from Morrison\n *\n * @param T double Julian century \n * @return Sun's mean longitude angle in degrees\n */\n public static double mlong (double T){\n return (normal(((.000000021 * T) + .00030368 * T + 36000.7698231) * T + 280.466449)) ;\n }\n\n /**\n * Computes Sun's geocentric longitude from T (degrees)\n * todo change to radians\n * todo check what is input\n * modified from Morrison\n *\n * @param T double Julian century \n * @return Sun's geocentric longitude angle in degrees\n */\n public static double geolong(double T){\n return (normal(tanom(T) + mlong(T) - manom(T))) ;\n }\n\n /**\n * Computes Sun's declination from T (degrees)\n * todo change to radians\n * todo check what is input\n * modified from Morrison\n *\n * @param T double Julian century \n * @return Sun's declination angle in radians\n */\n public static double solarDeclination(double T){\n return (Math.toDegrees(Math.asin(Math.sin(Math.toRadians(obliquity(T))) * Math.sin(Math.toRadians(geolong(T))))));\n }\n\n /**\n * Computes Sun's altitude at local noon for a given date and location\n *\n * @param month int month number (0-11)\n * @param day int day of month number (1-31)\n * @param year int 4 digit year\n * @param latitude of observer in decimal degrees\n * @return solar altitude at noon in decimal degrees\n */\n public static double solarNoonAltitude(int month, int day, int year, double latitude){\n //Calculate jday for noon of date to get Sun’s noon altitude\n double jday = julianDay( month, day, year, 12.0) ; //Julian day for date\n double T = (jday - 2451545.0) / 36525.0 ; //T for astronomy calc\n //Sun's max altitude for day (in degrees)\n return (90 - latitude + solarDeclination(T));\n }\n\n /**\n * Computes Sun's altitude at local noon for a given date and location\n *\n * @param dayOfYear int day of year number (0-365)\n * @param year int 4 digit year\n * @param latitude of observer in decimal degrees\n * @return solar altitude at noon in decimal degrees\n */\n public static double solarNoonAltitude(int dayOfYear, int year, double latitude){\n GregorianCalendar gc = new GregorianCalendar();\n gc.set(GregorianCalendar.DAY_OF_YEAR, dayOfYear);\n gc.set(GregorianCalendar.YEAR, year);\n return solarNoonAltitude(gc.get(GregorianCalendar.MONTH),gc.get(GregorianCalendar.DAY_OF_MONTH),\n year,latitude);\n }\n\n /**\n * Tests the numbers given and returns true if it is a legal date.\n * Example: 2004-02-15 is legal, 2004-02-31 is not.\n *\n * @param day day of month (1-31)\n * @param month month (1-12)\n * @param year (4 digit)\n * @return validity of date\n */\n public static boolean isLegalDate(int day, int month, int year){\n String dateString = year + \"-\" + month + \"-\" + (day + 1);\n SimpleDateFormat sdf = new SimpleDateFormat(\"yyyy-MM-dd\");\n sdf.setLenient(false);\n return sdf.parse(dateString, new ParsePosition(0)) != null;\n }\n\n\n // Polar arctangent todo\n public static double polar( double num, double den){\n double ang;\n ang = Math.atan2( num , den );\n if (ang < 0.0)\n {\n ang = ang + 2.0 * Math.PI;\n }\n return ang;\n }\n\n // todo\n public static int sgn(double num){\n if(num > 0) {\n return 1;\n } else if(num < 0) {\n return -1;\n } else {\n return 0;\n }\n }\n\n\n /**\n * Computes Obliquity of ecliptic from T\n * todo change to radians\n * todo check what is input\n * modified from Morrison\n *\n * @param T double Julian century \n * @return Obliquity of ecliptic angle in degrees\n */\n public static double obliquity(double T){\n return (((5.036111e-07 * T - 1.638889e-07) * T - .013004167) * T + 23.4392911);\n }\n\n\n /**\n * Precess star from J2000.0 coordinates to current\n *\t\n * modified from Morrison\n *\n * @param ra double right ascension \n * @param decl double declination\n * @return HashMap(String,Double):\n *\t\tprecessedRA\n *\t\tprecessedDec\n */\n public static HashMap<String,Double> precess(double ra, double decl){\n\n //compute T, the julian century\n double T = getT();\n\n // Precess star from J2000.0 coordinates\n // * Code ported and modified from C precess routine by James Morrison\n //\t published in The Astrolabe: page 347\n double raRad = Math.toRadians(ra * 15.0); //RA radians\n double decRad = Math.toRadians(decl); //Declination to radians\n double zeta = Math.toRadians((((.017998 * T + .30188) * T + 2306.2181) * T) / 3600.0);\n double z = Math.toRadians((((.018203 * T + 1.09468) * T + 2306.2181) * T) / 3600.0);\n double theta = Math.toRadians((((-.041833 * T + -.42665) * T + 2004.3109) * T) / 3600.0);\n double a = Math.cos(decRad) * Math.sin(raRad + zeta);\n double b = Math.cos(theta) * Math.cos(decRad) * Math.cos(raRad + zeta) - Math.sin(theta) * Math.sin(decRad);\n double c = Math.sin(theta) * Math.cos(decRad) * Math.cos(raRad + zeta) + Math.cos(theta) * Math.sin(decRad);\n\n double precessedRA = normal(Math.toDegrees(z + Math.atan2(a, b)))/15.0 ;\n double precessedDec = Math.toDegrees(Math.asin(c)) ;\n\n HashMap<String,Double> precessedLocation = new HashMap<>();\n precessedLocation.put(\"precessedRA\",precessedRA);\n precessedLocation.put(\"precessedDec\",precessedDec);\n\n return precessedLocation;\n }\n\n /**\n * Computes the angle of the sun at local noon for a given location and date\n * and then returns it\n *\n * @param latitude: The latitude of the observer\n * @param zodiacAngle: the location of the sum on the zodiac rel to Aries 0\n *\n * @return angle\n */\n public static Double sunsNoonAltitude(Double latitude,Double zodiacAngle){\n Double declination = Math.toDegrees(Math.asin(Math.sin(Math.toRadians(23.44)) * Math.sin(Math.toRadians(zodiacAngle))));\n return 90 - latitude + declination;\n }\n\n /**\n * Computes the great circle azimuth to Mecca(Qibla)for a given location\n *\n * @param observer: a Location defining the given location\n * @return Qibla direction\n */\n public static Double qiblaAngle(Location observer){\n //Equation taken from page 141 of Morrison's The Astrolabe:\n //\n //\t\t\t\t\t\tsin(lonQ -lon1)\n //\ttan q = ------------------------------------------------\n //\t\t\tcos lat1 * tan latQ - sin lat1 * cos(lonQ -lon1)\n //\n // where Mecca is (latQ,lonQ) and the observer is (lat1,lon1)\n // note: q is azimuth from south\n //\n\n //Compute Direction to Mecca(qibla)\n Location mecca = new Location(\"Mecca\",21,25,24,\"N\",39,49,24,\"E\"); //212524N0394924E Kaaba Location\n Double lonDiff = mecca.getLongitude() - observer.getLongitude();\n\n Double a = Math.sin(Math.toRadians(lonDiff));\n Double b = Math.cos(Math.toRadians(observer.getLatitude()))*Math.tan(Math.toRadians(mecca.getLatitude()));\n Double c = Math.sin(Math.toRadians(observer.getLatitude()))*Math.cos(Math.toRadians(lonDiff));\n\n return AstroMath.normal(Math.toDegrees(Math.atan(a / ((b) - (c)))));\n\n }\n\n /**\n * Computes time correction for location within time zone. time zones are 1 hour wide so the difference \n * between the suns positon and therefore local solar time will vary 60 minutes across a timezone\n *\t\n * @param lonDegree double longitude degrees\n * @param lonMin double longitude minutes\n * @param lonSec double longitude seconds\n * @param lonDir String longitude direction (E/W)\n * @return time correct string\n */\n public static String getTimeCorrection(double lonDegree, double lonMin, double lonSec, String lonDir){\n double longitude = lonDegree + lonMin/60.0 + lonSec/3600.0;\n if(lonDir.equals(\"W\")){\n longitude = -longitude;\n }\n int timeZone;\n double offset;\n int minutes;\n int seconds;\n String correction;\n\n timeZone = (int)Math.abs(longitude/15.0);\n if((Math.abs(longitude) - (timeZone*15)) > 7.5 ){\n timeZone++;\n }\n offset = (Math.abs(longitude) - (timeZone*15))*4;\n minutes = (int)offset;\n seconds = Math.abs((int)((offset-minutes)*60));\n correction = \"Time correction: \" + minutes + \" Minutes \" + seconds + \" Seconds\";\n\n return correction;\n }\n\n /**\n * Calculate the Equation of Time from 'day of year'\n * Originally written by Del Smith, 2016-11-29\n * Form \"Equation of Time\" Wikipedia entry\n * https://en.wikipedia.org/wiki/Equation_of_time#Calculating_the_equation_of_time\n * Downloaded 03 Oct 2017 and modified\n *\n * @param day represents the day of the year with 0 being January 1\n * @return value for the Equation of Time in decimal minutes\n */\n public static double equationOfTime(int day) {\n double meanVelocity = Math.toRadians(360.0/365.24); // Mean angular orbital velocity of Earth in radians/day\n double obliquity = Math.toRadians(obliquity(getT())); // Obliquity of the Earth in radians\n double approxAngle = meanVelocity * (day + 10);\n // Angle the Earth would move on its orbit at mean velocity from the December solstice until the day specified\n // 10 comes from the approximate number of days from December solstice to January 1\n double correctedAngle = approxAngle + Math.toRadians(1.914) * Math.sin(meanVelocity * (day - 2));\n // Angle the Earth would move from solstice to specified day, with a correction for Earth's orbital eccentricity\n // 2 is the number of days from January 1 to Earth's perihelion\n // 1.914 deg is a first-order correction for the Earth's orbital eccentricity, 0.0167 (360/pi * 0.0167)\n double angleDifference = Math.atan(Math.tan(correctedAngle) / Math.cos(obliquity));\n // Difference between the angle moved at mean velocity and at the corrected velocity, projected onto equatorial plane\n angleDifference = approxAngle - angleDifference; // Split into multiple lines for better readability\n angleDifference = angleDifference / Math.PI; // Divided by pi to get the value in half-turns\n return 720 * (angleDifference - Math.round(angleDifference)); // Return the Equation of Time in seconds\n // Corrected for any excess integer count half turns\n // 720 comes from the number of minutes it takes for Earth to complete a half turn (12h * 60m)\n }\n\n /**\n * Returns an array with the points for a circular graph representing the Equation of time\n *\n * @param innerLimit Innermost limit of the graph from the center\n * @param outerlimit Outermost limit of the graph from the center\n * @return An ArrayList of Point2D\n */\n public static ArrayList<Point2D> equationOfTimePoints(double innerLimit, double outerlimit){\n ArrayList<Point2D> points = new ArrayList<>();\n double scaling = (outerlimit - innerLimit)/34.0; //-17 to 17\n\n // First compute the angle of the first day of the year to use to align the EOT angle to the calendar ring\n double t = getT();\n double meanVelocity = 360.0/365.24; // Mean angular orbital velocity of Earth in degrees/day\n double offsetAngle = angleOfLineOfApsides(t) + meanVelocity * 2; //January 1 is two days from the perihelion\n\n for (int i = 0; i < 366; i++){\n //for each day of the current year, compute the eot adjustment in minutes\n double minutes = equationOfTime(i);\n double degrees = normal((i * (360.0/365.0))- offsetAngle);\n double r = ((outerlimit+innerLimit)/2.0) - (minutes * scaling);\n double x = r * Math.cos(Math.toRadians(degrees));\n double y = r * Math.sin(Math.toRadians(degrees));\n points.add(new Point2D.Double(x,y));\n }\n\n return points;\n }\n\n /**\n * return integer part of number\n * 25.3345 becomes 25.0\n *\t\n * modified from Morrison\n *\n * @param x double decimal number in todo: is this needed instead of Math.floor?\n * @return integer part of x\n */ \n public static double integerPart(double x) {\n return ((x >= 0) ? Math.floor(x) : Math.ceil(x)) ;\n }\n\n /**\n * Defines the Asr line for a sine quadrant.\n * plots one point for each of 90 degrees.\n *\n * Based on the Asr definition from the Maliki, Shafi'i, and Hanbali schools:\n * Asr begins when the length of any vertical gnomon's shadow equals the length\n * of the gnomon itself plus the length of that gnomon's shadow at noon.\n *\n * @param interval double\n *\n * @param multiplier 1 gives the start of Asr (+ the gnomon length), 2 gives the end (+ twice the gnomon length)\n *\n * @return Array of Point2d objects defining the Asr line\n */\n public static Point2D[] defineAsrLine (double interval, double multiplier){\n Point2D[] lineDef = new Point2D[91];\n for(int i = 0; i <= 90; i++){\n double angle = (double)i;\n lineDef[i] = asrPoint(angle, interval, multiplier);\n }\n\n return lineDef;\n }\n\n private static Point2D asrPoint(double meridianAlt, double interval, double multiplier){\n double meridianAltRadians = Math.toRadians(meridianAlt);\n double meridianX = (12.0/Math.sin(meridianAltRadians))* Math.cos(meridianAltRadians);\n double asrX = meridianX + (12.0 * multiplier);\n double asrAltRadians = Math.atan(12/asrX);\n\n double y = Math.sin(asrAltRadians) * 60.0;\n double x = y/Math.tan(meridianAltRadians);\n\n if(!(x > 0.0)){\n x = 60.0;\n }\n\n return new Point2D.Double(x*interval,y*interval);\n }\n\n /**\n * Determines the altitude of the Sun at the beginning of the Asr prayer hour\n * given the Sun's altitude at local noon.\n *\n * Based on the Asr definition from the Maliki, Shafi'i, and Hanbali schools:\n * Asr begins when the length of any vertical gnomon's shadow equals the length\n * of the gnomon itself plus the length of that gnomon's shadow at noon.\n *\n * @param meridianAlt Sun's altitude at local noon in degrees.\n *\n * @return Asr angle in degrees\n */\n private static double asrAltitude(Double meridianAlt){\n double meridianAltRadians = Math.toRadians(meridianAlt);\n\n double meridianX = (12.0/Math.sin(meridianAltRadians))* Math.cos(meridianAltRadians);\n double asrX = meridianX + 12.0;\n double asrAltRadians = Math.atan(12/asrX);\n\n return Math.toDegrees(asrAltRadians);\n }\n\n /**\n * Given the year, returns the Dominical letter for the that year\n * @param year an integer representing the year\n * @return The Dominical letter or letters for the year\n */\n public static String getDominicalLetter(int year) {\n int century = year / 100;\n int yearOfCentury = year % 100;\n int sum = 2 * century - century / 4 - yearOfCentury - yearOfCentury / 4;\n while (sum < 0)\n sum = sum + 7;\n String letter = Character.toString((char) (sum % 7 + 'A'));\n if (isLeapYear(year))\n letter = Character.toString((char) ((sum + 1) % 7 + 'A')).concat(letter);\n return letter;\n }\n\n /**\n * Determines if a given year is a leap year\n *\n * @param year an integer representing the year\n * @return true if a leap teat, false if not\n */\n public static boolean isLeapYear(int year) {\n // The year is a leap year if:\n // The year is divisible by 4 but not by 100\n // If the year is divisible by 400\n\n return year % 400 == 0 || year % 4 == 0 && year % 100 != 0;\n }\n}",
"public class InterSect {\n\n private double xi;\n private double yi;\n private double xi_prime;\n private double yi_prime;\n private double angle1;\n private double angle2;\n private Boolean intersection = false;\n\n public double getXi() {\n return xi;\n }\n\n public double getYi() {\n return yi;\n }\n\n public double getXi_prime() {\n return xi_prime;\n }\n\n public double getYi_prime() {\n return yi_prime;\n }\n\n public double getAngle1() {\n return Math.toDegrees(angle1);\n }\n\n public double getAngle2() {\n return Math.toDegrees(angle2);\n }\n\n public Boolean getIntersection() {\n return intersection;\n }\n\n private double polar ( double num, double den ){\n // Polar Arctangent\n double ang = Math.atan2( num , den );\n if (ang < 0.0)\n {\n ang = ang + 2.0 * Math.PI;\n }\n\n return ang;\n }\n\n /**\n * Computes Intersection of two circles\n *\n * @param x0 drawing circle center X\n * @param y0 drawing circle center Y\n * @param r0 drawing circle radius\n *\n * @param x1 clipping circle center X\n * @param y1 clipping circle center Y\n * @param r1 clipping circle radius\n *\n */\n public InterSect(double x0, double y0, double r0, double x1, double y1, double r1)\n {\n double a;\n double dx;\n double dy;\n double d;\n double h;\n double rx;\n double ry;\n double x2;\n double y2;\n double A1;\n double A2;\n double xi1;\n double yi1;\n double xi_prime1;\n double yi_prime1;\n\n /* dx and dy are the vertical and horizontal distances between\n * the circle centers.\n */\n dx = x1 - x0;\n dy = y1 - y0;\n\n /* Determine the straight-line distance between the centers. */\n d = Math.sqrt((dy*dy) + (dx*dx));\n //d = hypot(dx,dy); // Suggested by Keith Briggs\n\n /* Check for solvability. */\n if (d > (r0 + r1))\n {\n /* no solution. circles do not intersect. */\n this.intersection = false;\n return;\n }\n if (d < Math.abs(r0 - r1))\n {\n /* no solution. one circle is contained in the other */\n this.intersection = false;\n return;\n }\n\n /* 'point 2' is the point where the line through the circle\n * intersection points crosses the line between the circle\n * centers.\n */\n\n /* Determine the distance from point 0 to point 2. */\n a = ((r0*r0) - (r1*r1) + (d*d)) / (2.0 * d) ;\n\n /* Determine the coordinates of point 2. */\n x2 = x0 + (dx * a/d);\n y2 = y0 + (dy * a/d);\n\n /* Determine the distance from point 2 to either of the\n * intersection points.\n */\n h = Math.sqrt((r0*r0) - (a*a));\n\n /* Now determine the offsets of the intersection points from\n * point 2.\n */\n rx = -dy * (h/d);\n ry = dx * (h/d);\n\n /* Determine the absolute intersection points. */\n this.xi = x2 + rx;\n this.xi_prime = x2 - rx;\n this.yi = y2 + ry;\n this.yi_prime = y2 - ry;\n\n // Calculate intersection angles\n // first determine the intersections from the center of the circle to be drawn\n xi1 = this.xi-x0;\n xi_prime1 = this.xi_prime-x0;\n yi1 = this.yi-y0;\n yi_prime1 = this.yi_prime-y0;\n\n if ( xi1 != 0.0 )\n { //Calculate first angle\n A1 = polar( yi1 , xi1) ;\n }\n else\n {\n if ( yi1 > 0.0 )\n {\n A1 = (Math.PI/2.0); //x1 = 0 => a = 90 or 270\n }\n else\n {\n A1 = 3.0 * Math.PI / 2.0 ;\n }\n }\n\n if ( xi_prime1 != 0.0)\n {//Calculate second angle\n A2 = polar( yi_prime1 , xi_prime1 ) ;\n }\n else\n {\n if (yi_prime1 > 0.0) A2 = Math.PI / 2.0 ;\n else A2 = 3.0 * Math.PI / 2.0 ;\n }\n\n // Store returned values //TODO: WTF\n this.angle1 = A1;\n x1 = this.xi;\n y1 = this.yi;\n this.angle2 = A2;\n x2 = this.xi_prime;\n y2 = this.yi_prime;\n\n // Sort returned values\n if (this.angle1 > this.angle2)\n {\n //swap (angle1,angle2) ;\n double hold;\n hold = this.angle1;\n this.angle1=this.angle2;\n this.angle2=hold;\n //swap (x1,x2) ;\n hold = x1;\n x1=x2;\n x2=hold;\n //swap (y1,y2) ;\n hold = y1;\n y1=y2;\n y2=hold;\n }\n //System.out.println(\"Angle 1 = \" + Math.toDegrees(angle1));\n //System.out.println(\"Angle 2 = \" + Math.toDegrees(angle2));\n this.intersection = true; //Return shows there is an intersection\n }\n}",
"public class ThreePointCenter {\n\n private Point2D.Double center= new Point2D.Double(0,0);\n private double radius = 0;\n private Boolean isCircle = true;\n\n public Point2D.Double getCenter() {\n return this.center;\n }\n\n public double getRadius() {\n return this.radius;\n }\n\n public Boolean isCircle() {\n return this.isCircle;\n }\n\n public ThreePointCenter(Point2D.Double point1, Point2D.Double point2, Point2D.Double point3){\n Point2D.Double pointZ;\n\n double temp1;\n double temp2;\n\n double deltaX1;\n double deltaY1;\n double deltaX2;\n double deltaY2;\n\n // first check to see if the three points are on the same line\n // Use two points to derive the equation of a line between those points\n // then see if the third point is on that line\n if((point1.x == point2.x && point2.x == point3.x)||(point1.y == point2.y && point2.y == point3.y))\n {\n //is a straight horz or vert line\n this.isCircle = false;\n return;\n }\n\n //Check to make sure point2.x does not equal point3.x. if equal swap out for point3\n if (point2.x == point1.x)\n {\n // swap\n if (point2.x != point3.x)\n {\n // swap point2 and point3\n pointZ = point3;\n point3 = point2;\n point2 = pointZ;\n }else\n {\n // swap point1 and point3\n pointZ = point3;\n point3 = point1;\n point1 = pointZ;\n }\n }\n\n // now test to see if point3 is on the same line as point1 and point2\n double slope = (point2.y - point1.y) / (point2.x - point1.x);\n double intercept = point1.y - (slope * point1.x);\n\n if(point3.y == (slope * point3.x) + intercept) //y = mx+b\n {\n //all three points on one line\n this.isCircle = false;\n return;\n }\n\n // next check to see if point2.y is the same as point1.y or if\n // point3.y is the same as point1.y if so there is a divide-by-zero\n // problem that can be solved by swapping points around.\n // we check above to see if the points were on a horz or vert line, so if\n // point2.y is the same as point1.y then point3.y can't be etc\n\n if (point2.y == point1.y)\n {\n // swap point1 and point3\n pointZ = point3;\n point3 = point1;\n point1 = pointZ;\n } else if (point3.y == point1.y)\n {\n // swap point1 and point2\n pointZ = point2;\n point2 = point1;\n point1 = pointZ;\n }\n\n // Find point equidistant from point1, point2 and point 3\n\n deltaX1 = point2.x - point1.x;\n deltaY1 = point2.y - point1.y;\n temp1 = ((point2.x * point2.x) - (point1.x * point1.x) + (point2.y * point2.y) - (point1.y * point1.y)) / 2.0;\n deltaX2 = point3.x - point1.x;\n deltaY2 = point3.y - point1.y;\n temp2 = ((point3.x * point3.x) - (point1.x * point1.x) + (point3.y * point3.y) - (point1.y * point1.y)) / 2.0;\n\n // solve for X\n this.center.x = ((temp1 / deltaY1) - (temp2 / deltaY2)) / ((deltaX1 / deltaY1) - (deltaX2 / deltaY2));\n\n // solve for Y\n this.center.y = (temp1 - (deltaX1 * this.center.x)) / deltaY1;\n\n this.radius = Math.sqrt(((this.center.x - point1.x) * (this.center.x - point1.x)) + ((this.center.y - point1.y) * (this.center.y - point1.y))); \n }\n}"
] | import com.wymarc.astrolabe.Astrolabe;
import com.wymarc.astrolabe.generator.printengines.postscript.util.EPSToolKit;
import com.wymarc.astrolabe.math.AstroMath;
import com.wymarc.astrolabe.math.InterSect;
import com.wymarc.astrolabe.math.ThreePointCenter;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List; | /**
* $Id: AstrolabeGenerator.java,v 3.1
* <p/>
* The Astrolabe Generator 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.
* <p/>
* The Astrolabe Generator 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.
* <p/>
* 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.
* <p/>
* Copyright (c) 2017 Timothy J. Mitchell
*/
package com.wymarc.astrolabe.generator.printengines.postscript.extras.horary;
/**
* This Plugin will calculate the components of an equal hours style Horary
* Quadrant and print the results to an Encapsulated PostScript (EPS) file.
* Note that this file is static with no inputs. Software is included for reference.
* <p>
* link http://astrolabeproject.com.com
* link http://www.astrolabes.org
*/
public class EqualHours {
// Note: limit is 25N to 65N
public static double NORTH_LIMIT = 65.0;
public static double SOUTH_LIMIT = 25.0;
//todo add colors, add latitude
| private Astrolabe myAstrolabe = new Astrolabe(); | 0 |
sekwah41/Advanced-Portals | src/main/java/com/sekwah/advancedportals/bukkit/listeners/Listeners.java | [
"public class AdvancedPortalsPlugin extends JavaPlugin {\n\n private Settings settings;\n\n protected boolean isProxyPluginEnabled = false;\n\n protected boolean forceRegisterProxyChannels = false;\n protected boolean disableProxyWarning = false;\n\n private boolean worldEditActive = false;\n\n protected static final Map<String, String> PLAYER_DESTI_MAP = new HashMap<>();\n\n @Override\n public void onEnable() {\n\n saveDefaultConfig();\n\n /*Metrics metrics = */\n new Metrics(this);\n\n ConfigAccessor config = new ConfigAccessor(this, \"config.yml\");\n\n ConfigHelper configHelper = new ConfigHelper(config.getConfig());\n\n configHelper.update();\n\n config.saveConfig();\n\n FileConfiguration pluginConfig = config.getConfig();\n forceRegisterProxyChannels = pluginConfig.getBoolean(ConfigHelper.FORCE_ENABLE_PROXY_SUPPORT, false);\n disableProxyWarning = pluginConfig.getBoolean(ConfigHelper.DISABLE_PROXY_WARNING, false);\n\n ConfigAccessor portalConfig = new ConfigAccessor(this, \"portals.yml\");\n portalConfig.saveDefaultConfig();\n\n\n ConfigAccessor destinationConfig = new ConfigAccessor(this, \"destinations.yml\");\n destinationConfig.saveDefaultConfig();\n\n this.settings = new Settings(this);\n\n // Loads the portal and destination editors\n Portal.init(this);\n Destination.init(this);\n\n\n this.registerCommands();\n\n new WarpEffects(this);\n\n this.addListeners();\n this.setupDataCollector();\n\n this.setupBungee();\n\n this.getServer().getConsoleSender().sendMessage(\"\\u00A7aAdvanced portals have been successfully enabled!\");\n\n for (Player player:\n this.getServer().getOnlinePlayers()) {\n player.removeMetadata(Listeners.HAS_WARPED, this);\n player.removeMetadata(Listeners.LAVA_WARPED, this);\n }\n\n if (settings.enabledWorldEditIntegration() && Bukkit.getPluginManager().isPluginEnabled(\"WorldEdit\")) {\n worldEditActive = true;\n }\n\n // thanks to the new config accessor code the config.saveDefaultConfig(); will now\n // only copy the file if it doesnt exist!\n }\n\n private void registerCommands() {\n new PluginMessages(this);\n new AdvancedPortalsCommand(this);\n new DestinationCommand(this);\n }\n\n private void addListeners() {\n new Listeners(this);\n\n new FlowStopper(this);\n new PortalProtect(this);\n new PortalPlacer(this);\n }\n\n private void setupDataCollector() {\n Selection.loadData(this);\n }\n\n private void setupBungee() {\n // Enables very basic bungee support if not setup right\n this.getServer().getMessenger().registerOutgoingPluginChannel(this, \"BungeeCord\");\n if(forceRegisterProxyChannels || this.checkIfBungee()) {\n this.getServer().getMessenger().registerIncomingPluginChannel(this, \"BungeeCord\", new BungeeListener(this));\n\n this.getServer().getMessenger().registerOutgoingPluginChannel(this, BungeeMessages.CHANNEL_NAME);\n this.getServer().getMessenger().registerIncomingPluginChannel(this, BungeeMessages.CHANNEL_NAME, new PluginMessageReceiver(this));\n isProxyPluginEnabled = true;\n }\n else {\n isProxyPluginEnabled = false;\n }\n }\n\n public Map<String, String> getPlayerDestiMap() {\n return PLAYER_DESTI_MAP;\n }\n\n public boolean isProxyPluginEnabled() {\n return isProxyPluginEnabled;\n }\n\n private boolean checkIfBungee()\n {\n // we check if the server is Spigot/Paper (because of the spigot.yml file)\n try {\n Class.forName(\"org.spigotmc.SpigotConfig\");\n } catch (ClassNotFoundException e) {\n this.getServer().getConsoleSender().sendMessage( \"\\u00A7ePossibly unsupported version for bungee messages detected, channels won't be enabled.\" );\n getLogger().info(\"If you believe this shouldn't be the case please contact us on discord https://discord.sekwah.com/\");\n return false;\n }\n\n try {\n ConfigurationSection configSelection = getServer().spigot().getConfig().getConfigurationSection(\"settings\");\n if (configSelection != null && configSelection.getBoolean(\"bungeecord\") ) {\n getLogger().info( \"Bungee detected. Enabling proxy features.\" );\n return true;\n }\n } catch(NoSuchMethodError | NullPointerException e) {\n if(!disableProxyWarning) getLogger().info(\"BungeeCord config not detected, ignoring settings\");\n }\n\n // Will be valid if paperspigot is being used. Otherwise catch.\n try {\n ConfigurationSection configSelection = getServer().spigot().getPaperConfig().getConfigurationSection(\"settings\");\n ConfigurationSection velocity = configSelection != null ? configSelection.getConfigurationSection(\"velocity-support\") : null;\n if (velocity != null && velocity.getBoolean(\"enabled\") ) {\n getLogger().info( \"Modern forwarding detected. Enabling proxy features.\" );\n return true;\n }\n } catch(NoSuchMethodError | NullPointerException e) {\n if(!disableProxyWarning) getLogger().info(\"Paper config not detected, ignoring paper settings\");\n }\n\n if(!disableProxyWarning) getLogger().warning( \"Proxy features disabled for Advanced Portals as bungee isn't enabled on the server (spigot.yml) \" +\n \"or if you are using Paper settings.velocity-support.enabled may not be enabled (paper.yml)\" );\n return false;\n }\n\n\n @Override\n public void onDisable() {\n this.getServer().getConsoleSender().sendMessage(\"\\u00A7cAdvanced portals are being disabled!\");\n }\n\n\n public Settings getSettings() {\n return settings;\n }\n\n public boolean isWorldEditActive() {\n return worldEditActive;\n }\n}",
"public class PluginMessages {\n private static String WARP_MESSAGE;\n public boolean useCustomPrefix = false;\n public static String customPrefix = \"\\u00A7a[\\u00A7eAdvancedPortals\\u00A7a]\";\n public static String customPrefixFail = \"\\u00A7c[\\u00A77AdvancedPortals\\u00A7c]\";\n\n public PluginMessages (AdvancedPortalsPlugin plugin) {\n ConfigAccessor config = new ConfigAccessor(plugin, \"config.yml\");\n this.useCustomPrefix = config.getConfig().getBoolean(\"UseCustomPrefix\");\n if (useCustomPrefix) {\n PluginMessages.customPrefix = config.getConfig().getString(\"CustomPrefix\").replaceAll(\"&(?=[0-9a-fk-or])\", \"\\u00A7\");\n PluginMessages.customPrefixFail = config.getConfig().getString(\"CustomPrefixFail\").replaceAll(\"&(?=[0-9a-fk-or])\", \"\\u00A7\");\n }\n\n WARP_MESSAGE = ChatColor.translateAlternateColorCodes('&', config.getConfig().getString(\"WarpMessage\", \"&aYou have warped to &e<warp>&a\"));\n }\n\n // This class is so then the common messages in commands or just messages over the commands are the same and can be\n // easily changed.\n\n public static String getWarpMessage(String warp) {\n String cleanedWarp = warp.replace(\"_\", \" \");\n return WARP_MESSAGE.replace(\"<warp>\", cleanedWarp);\n }\n\n public static void UnknownCommand(CommandSender sender, String command) {\n sender.sendMessage(customPrefixFail + \" You need to type something after /\" + command + \"\\n\");\n sender.sendMessage(\"\\u00A7cIf you do not know what you can put or would like some help with the commands please type \\u00A7e\" + '\"' + \"\\u00A7e/\" + command + \" help\" + '\"' + \"\\u00A7c\\n\");\n }\n\n public static void NoPermission(CommandSender sender, String command) {\n sender.sendMessage(customPrefixFail + \" You do not have permission to perform that command!\");\n }\n}",
"public final class WarpEvent extends Event implements Cancellable {\n\n /**\n * Use listeners so you can add new triggers easier and also other plugins can listen for the event\n * and add their own triggers\n */\n private static final HandlerList handlers = new HandlerList();\n\n private boolean cancelled = false;\n\n private final Player player;\n\n @SuppressWarnings(\"unused\")\n private final AdvancedPortal portalData;\n\n private boolean hasWarped = false;\n\n public WarpEvent(Player player, AdvancedPortal portalData) {\n this.player = player;\n this.portalData = portalData;\n }\n\n public static HandlerList getHandlerList() {\n return handlers;\n }\n\n /**\n * Returns if the event has been cancelled\n *\n * @return cancelled\n */\n public boolean isCancelled() {\n return cancelled;\n }\n\n public void setCancelled(boolean cancel) {\n cancelled = cancel;\n }\n\n public AdvancedPortal getPortalData() {\n return portalData;\n }\n\n /**\n * This will return true if another plugin has warped the player(and set this to true)\n *\n * @return hasWarped\n */\n public boolean getHasWarped() {\n return hasWarped;\n }\n\n /**\n * If the\n *\n * @param warped\n */\n @SuppressWarnings(\"unused\")\n public void setHasWarped(boolean warped) {\n this.hasWarped = warped;\n }\n\n public Player getPlayer() {\n return player;\n }\n\n public HandlerList getHandlers() {\n return handlers;\n }\n}",
"public class ConfigAccessor {\n\n private final String fileName;\n private final JavaPlugin plugin;\n\n private File configFile;\n private FileConfiguration fileConfiguration;\n\n public ConfigAccessor(JavaPlugin plugin, String fileName) {\n this.plugin = plugin;\n this.fileName = fileName;\n }\n\n // gets all of the \n public void reloadConfig() {\n if (configFile == null) {\n File dataFolder = plugin.getDataFolder();\n if (dataFolder == null)\n throw new IllegalStateException();\n configFile = new File(dataFolder, fileName);\n }\n fileConfiguration = YamlConfiguration.loadConfiguration(configFile);\n\n // Look for defaults in the jar\n YamlConfiguration defConfig = YamlConfiguration.loadConfiguration(new File(this.getClass()\n .getClassLoader().getResource(fileName).getPath()));\n fileConfiguration.setDefaults(defConfig);\n }\n\n public FileConfiguration getConfig() {\n if (fileConfiguration == null) {\n this.reloadConfig();\n }\n return fileConfiguration;\n }\n\n // Saves all the data to the selected yml file\n public void saveConfig() {\n if (fileConfiguration == null || configFile == null) {\n return;\n } else {\n try {\n getConfig().save(configFile);\n } catch (IOException ex) {\n plugin.getLogger().log(Level.SEVERE, \"Could not save config to \" + configFile, ex);\n }\n }\n }\n\n // Saves \n\n /**\n * public void saveDefaultConfig() {\n * if (!configFile.exists()) {\n * this.plugin.saveResource(fileName, false);\n * }\n * }\n */\n\n // New save default config saving code, it checks if the needed config is in the jar file before\n // overriding it.\n public void saveDefaultConfig() {\n if (configFile == null) {\n configFile = new File(plugin.getDataFolder(), fileName);\n }\n if (!configFile.exists()) {\n plugin.saveResource(fileName, false);\n }\n }\n\n}",
"public class Destination {\n\n private static AdvancedPortalsPlugin plugin;\n\n private static boolean TELEPORT_RIDING = false;\n public static int PORTAL_MESSAGE_DISPLAY = 0;\n\n public static void init(AdvancedPortalsPlugin plugin) {\n Destination.plugin = plugin;\n\n ConfigAccessor config = new ConfigAccessor(plugin, \"config.yml\");\n TELEPORT_RIDING = config.getConfig().getBoolean(\"WarpRiddenEntity\");\n PORTAL_MESSAGE_DISPLAY = config.getConfig().getInt(\"WarpMessageDisplay\");\n }\n\n // TODO add permissions for destinations.\n\n // TODO try keeping the chunks loaded and add different delays to events to make\n // the horse teleport when you have more time.(its an annoying bug caused by changed)\n // in mc\n\n public static void create(Location location, String name) {\n ConfigAccessor config = new ConfigAccessor(plugin, \"destinations.yml\");\n\n config.getConfig().set(name.toLowerCase() + \".world\", location.getWorld().getName());\n\n config.getConfig().set(name.toLowerCase() + \".pos.X\", location.getX());\n config.getConfig().set(name.toLowerCase() + \".pos.Y\", location.getY());\n config.getConfig().set(name.toLowerCase() + \".pos.Z\", location.getZ());\n\n config.getConfig().set(name.toLowerCase() + \".pos.pitch\", location.getPitch());\n config.getConfig().set(name.toLowerCase() + \".pos.yaw\", location.getYaw());\n\n config.saveConfig();\n }\n\n public static void move(Location location, String name) {\n ConfigAccessor config = new ConfigAccessor(plugin, \"destinations.yml\");\n\n config.getConfig().set(name.toLowerCase() + \".world\", location.getWorld().getName());\n\n config.getConfig().set(name.toLowerCase() + \".pos.X\", location.getX());\n config.getConfig().set(name.toLowerCase() + \".pos.Y\", location.getY());\n config.getConfig().set(name.toLowerCase() + \".pos.Z\", location.getZ());\n\n config.getConfig().set(name.toLowerCase() + \".pos.pitch\", location.getPitch());\n config.getConfig().set(name.toLowerCase() + \".pos.yaw\", location.getYaw());\n\n config.saveConfig();\n }\n\n public static void rename(String oldName, String newName) {\n ConfigAccessor config = new ConfigAccessor(plugin, \"destinations.yml\");\n\n config.getConfig().set(newName.toLowerCase() + \".world\", config.getConfig().getString(oldName + \".world\"));\n\n config.getConfig().set(newName.toLowerCase() + \".pos.X\", config.getConfig().getDouble(oldName + \".pos.X\"));\n config.getConfig().set(newName.toLowerCase() + \".pos.Y\", config.getConfig().getDouble(oldName + \".pos.Y\"));\n config.getConfig().set(newName.toLowerCase() + \".pos.Z\", config.getConfig().getDouble(oldName + \".pos.Z\"));\n\n config.getConfig().set(newName.toLowerCase() + \".pos.pitch\", config.getConfig().getDouble(oldName + \".pos.pitch\"));\n config.getConfig().set(newName.toLowerCase() + \".pos.yaw\", config.getConfig().getDouble(oldName + \".pos.yaw\"));\n\n remove(oldName);\n\n config.saveConfig();\n }\n\n public static void remove(String name) {\n ConfigAccessor config = new ConfigAccessor(plugin, \"destinations.yml\");\n\n config.getConfig().set(name.toLowerCase() + \".world\", null);\n\n config.getConfig().set(name.toLowerCase() + \".pos.X\", null);\n config.getConfig().set(name.toLowerCase() + \".pos.Y\", null);\n config.getConfig().set(name.toLowerCase() + \".pos.Z\", null);\n\n config.getConfig().set(name.toLowerCase() + \".pos.pitch\", null);\n config.getConfig().set(name.toLowerCase() + \".pos.yaw\", null);\n\n config.getConfig().set(name.toLowerCase() + \".pos\", null);\n\n config.getConfig().set(name.toLowerCase(), null);\n\n config.saveConfig();\n }\n\n public static boolean warp(Player player, String name) {\n return warp(player, name, false);\n }\n\n public static boolean warp(Player player, String name, boolean hideActionBar) {\n return warp(player, name, null, hideActionBar, false);\n }\n\n public static boolean warp(Player player, String name, boolean hideActionBar, boolean noEffects) {\n return warp(player, name, null, hideActionBar, noEffects);\n }\n\n public static boolean warp(Player player, String dest, AdvancedPortal disp, boolean hideActionbar, boolean noEffects) {\n ConfigAccessor config = new ConfigAccessor(plugin, \"destinations.yml\");\n if (config.getConfig().getString(dest + \".world\") != null) {\n Location loc = player.getLocation();\n if (Bukkit.getWorld(config.getConfig().getString(dest + \".world\")) != null) {\n loc.setWorld(Bukkit.getWorld(config.getConfig().getString(dest + \".world\")));\n\n loc.setX(config.getConfig().getDouble(dest + \".pos.X\"));\n loc.setY(config.getConfig().getDouble(dest + \".pos.Y\"));\n loc.setZ(config.getConfig().getDouble(dest + \".pos.Z\"));\n\n loc.setPitch((float) config.getConfig().getDouble(dest + \".pos.pitch\"));\n loc.setYaw((float) config.getConfig().getDouble(dest + \".pos.yaw\"));\n\n if (disp != null && disp.getArg(\"particlein\") != null) {\n WarpEffects.activateParticle(player, disp.getArg(\"particlein\"));\n }\n\n if(!noEffects) {\n WarpEffects.activateEffect(player);\n WarpEffects.activateSound(player);\n }\n Chunk c = loc.getChunk();\n Entity riding = player.getVehicle();\n if (!c.isLoaded()) c.load();\n\n if (player.getVehicle() != null && TELEPORT_RIDING) {\n\n riding.eject();\n riding.teleport(loc, PlayerTeleportEvent.TeleportCause.PLUGIN);\n player.teleport(loc, PlayerTeleportEvent.TeleportCause.PLUGIN);\n riding.setPassenger(player);\n\n } else {\n player.teleport(loc, PlayerTeleportEvent.TeleportCause.PLUGIN);\n }\n\n if (disp != null && disp.getArg(\"particleout\") != null) {\n WarpEffects.activateParticle(player, disp.getArg(\"particleout\"));\n }\n if(!noEffects) {\n WarpEffects.activateEffect(player);\n WarpEffects.activateSound(player);\n }\n\n if (PORTAL_MESSAGE_DISPLAY == 1) {\n player.sendMessage(\"\");\n player.sendMessage(PluginMessages.customPrefix + PluginMessages.getWarpMessage(dest));\n player.sendMessage(\"\");\n } else if (PORTAL_MESSAGE_DISPLAY == 2 && !hideActionbar) {\n player.spigot().sendMessage(ChatMessageType.ACTION_BAR, TextComponent.fromLegacyText(PluginMessages.getWarpMessage(dest)));\n }\n\n Location newLoc = player.getLocation();\n Location newEyeLoc = player.getEyeLocation();\n UUID uuid = player.getUniqueId();\n for (AdvancedPortal portal : Portal.portals) {\n if (!portal.inPortal.contains(uuid) && !portal.isDelayed()\n && (Portal.locationInPortalTrigger(portal, newLoc) || Portal.locationInPortalTrigger(portal, newEyeLoc))) {\n portal.inPortal.add(uuid);\n }\n }\n\n return true;\n } else {\n player.sendMessage(PluginMessages.customPrefixFail + \"\\u00A7c The destination you are trying to warp to seems to be linked to a world that doesn't exist!\");\n plugin.getLogger().log(Level.SEVERE, \"The destination '\" + dest + \"' is linked to the world \"\n + config.getConfig().getString(dest + \".world\") + \" which doesnt seem to exist any more!\");\n }\n } else {\n player.sendMessage(PluginMessages.customPrefix + \"\\u00A7c The destination you are currently attempting to warp to doesnt exist!\");\n plugin.getLogger().log(Level.SEVERE, \"The destination '\" + dest + \"' has just had a warp \"\n + \"attempt and either the data is corrupt or that destination doesn't exist!\");\n }\n return false;\n }\n}",
"public class AdvancedPortal {\n\n private Set<Material> triggers = null;\n\n private String worldName = null;\n\n private Location pos1 = null;\n\n private Location pos2 = null;\n\n private String portalName = null;\n\n // TODO store destinations also as variables like portals\n private String destiation = null; // Could possibly store the destination name to stop the server having to read the config file\n\n private String bungee = null; // Could possibly store the bungee server name to stop the server having to read the config file\n\n // Bungee will be stored inside the destination.\n\n private PortalArg[] portalArgs = null;\n\n public HashSet<UUID> inPortal = new HashSet<UUID>();\n\n // TODO think of relaying out the data input to a more logical format.\n public AdvancedPortal(String portalName, Material trigger, String destination, Location pos1, Location pos2, PortalArg... portalArgs) {\n this(portalName, trigger, pos1, pos2, pos2.getWorld().getName(), portalArgs);\n this.destiation = destination;\n }\n\n public AdvancedPortal(String portalName, Material trigger, Location pos1, Location pos2, PortalArg... portalArgs) {\n this(portalName, trigger, pos1, pos2, pos2.getWorld().getName(), portalArgs);\n }\n\n public AdvancedPortal(String portalName, Material trigger, String destination, Location pos1, Location pos2, String worldName, PortalArg... portalArgs) {\n this(portalName, trigger, pos1, pos2, worldName, portalArgs);\n this.destiation = destination;\n }\n\n public AdvancedPortal(String portalName, Material trigger, Location pos1, Location pos2, String worldName, PortalArg... portalArgs) {\n this(portalName, new HashSet<>(Collections.singletonList(trigger)), pos1, pos2, worldName, portalArgs);\n }\n\n public AdvancedPortal(String portalName, Set<Material> triggers, Location pos1, Location pos2, String worldName, PortalArg... portalArgs) {\n this.portalName = portalName;\n this.triggers = triggers;\n this.pos1 = pos1;\n this.pos2 = pos2;\n this.worldName = worldName;\n this.portalArgs = portalArgs;\n }\n\n public String getArg(String arg) {\n for (PortalArg portalArg : this.portalArgs) {\n if (arg.equals(portalArg.argName)) {\n return portalArg.value;\n }\n }\n return null;\n }\n\n public PortalArg[] getArgs(){\n return this.portalArgs;\n }\n\n public boolean hasArg(String arg) {\n return this.getArg(arg) != null;\n }\n\n public Set<Material> getTriggers() {\n return this.triggers;\n }\n\n public String getWorldName() {\n return this.worldName;\n }\n\n public Location getPos1() {\n return this.pos1;\n }\n\n public Location getPos2() {\n return this.pos2;\n }\n\n public String getName() {\n return this.portalName;\n }\n\n public String getDestiation() {\n return this.destiation;\n }\n\n public void setDestiation(String destiation) {\n this.destiation = destiation;\n }\n\n public String getBungee() {\n return this.bungee;\n }\n\n public void setBungee(String bungee) {\n this.bungee = bungee;\n }\n\n public boolean isDelayed() {\n return this.hasArg(\"delayed\") && this.getArg(\"delayed\").equalsIgnoreCase(\"true\");\n }\n}",
"public class Portal {\n\n public static HashMap<String, Long> joinCooldown = new HashMap<String, Long>();\n public static HashMap<String, HashMap<String, Long>> cooldown = new HashMap<String, HashMap<String, Long>>();\n // Config values\n public static boolean portalsActive = false;\n public static AdvancedPortal[] portals = new AdvancedPortal[0];\n private static AdvancedPortalsPlugin plugin;\n public static ConfigAccessor portalData = new ConfigAccessor(plugin, \"portals.yml\");\n private static boolean showBungeeMessage;\n private static double throwback;\n private static Sound portalSound;\n private static int portalProtectionRadius;\n private static boolean blockSpectatorMode;\n private static int joinCooldownDelay;\n private static boolean commandLog;\n private static final Random random = new Random();\n\n public static void init(AdvancedPortalsPlugin plugin) {\n ConfigAccessor config = new ConfigAccessor(plugin, \"config.yml\");\n showBungeeMessage = config.getConfig().getBoolean(\"ShowBungeeWarpMessage\", false);\n\n portalProtectionRadius = config.getConfig().getBoolean(\"PortalProtection\") ?\n config.getConfig().getInt(\"PortalProtectionArea\") : 0;\n\n throwback = config.getConfig().getDouble(\"ThrowbackAmount\", 0.7);\n\n portalSound = WarpEffects.findSound(plugin, \"BLOCK_PORTAL_TRAVEL\", \"PORTAL_TRAVEL\");\n blockSpectatorMode = config.getConfig().getBoolean(\"BlockSpectatorMode\", false);\n\n joinCooldownDelay = config.getConfig().getInt(\"PortalCooldown\", 5);\n\n commandLog = config.getConfig().getBoolean(ConfigHelper.COMMAND_LOGS, true);\n\n Portal.plugin = plugin;\n Portal.loadPortals();\n }\n\n /**\n * This can be used to move the get keys to different sections\n * <p>\n * ConfigurationSection section = portalData.getSection(\"sectionname\");\n * <p>\n * section.getKeys(false);\n */\n\n public static void loadPortals() {\n portalData = new ConfigAccessor(plugin, \"portals.yml\");\n Set<String> PortalSet = portalData.getConfig().getKeys(false);\n if (PortalSet.size() > 0) {\n portals = new AdvancedPortal[PortalSet.toArray().length];\n\n /*\n * for(int i = 0; i <= PortalSet.toArray().length - 1; i++){ portals[i] = new\n * AdvancedPortal(); }\n */\n\n int portalId = 0;\n for (Object portal : PortalSet.toArray()) {\n\n ConfigurationSection portalConfigSection = portalData.getConfig()\n .getConfigurationSection(portal.toString());\n\n String blockTypesRaw = portalConfigSection.getString(\"triggerblock\");\n\n String[] blockTypesString = blockTypesRaw != null ? blockTypesRaw.split(\",\") : null;\n\n HashSet<Material> blockTypes = getMaterialSet(blockTypesString);\n\n if (blockTypes.isEmpty()) {\n blockTypes.add(Material.NETHER_PORTAL);\n }\n\n ConfigurationSection portalArgsConf = portalConfigSection.getConfigurationSection(\"portalArgs\");\n\n ArrayList<PortalArg> extraData = new ArrayList<>();\n\n if (portalArgsConf != null) {\n Set<String> argsSet = portalArgsConf.getKeys(true);\n\n for (Object argName : argsSet.toArray()) {\n if (portalArgsConf.isString(argName.toString())) {\n extraData.add(\n new PortalArg(argName.toString(), portalArgsConf.getString(argName.toString())));\n }\n }\n }\n\n String worldName = portalData.getConfig().getString(portal.toString() + \".world\");\n if (worldName != null) {\n World world = Bukkit.getWorld(worldName);\n Location pos1 = new Location(world, portalData.getConfig().getInt(portal.toString() + \".pos1.X\"),\n portalData.getConfig().getInt(portal.toString() + \".pos1.Y\"),\n portalData.getConfig().getInt(portal.toString() + \".pos1.Z\"));\n Location pos2 = new Location(world, portalData.getConfig().getInt(portal.toString() + \".pos2.X\"),\n portalData.getConfig().getInt(portal.toString() + \".pos2.Y\"),\n portalData.getConfig().getInt(portal.toString() + \".pos2.Z\"));\n\n PortalArg[] portalArgs = new PortalArg[extraData.size()];\n extraData.toArray(portalArgs);\n\n portals[portalId] = new AdvancedPortal(portal.toString(), blockTypes, pos1, pos2, worldName,\n portalArgs);\n\n portals[portalId].setBungee(portalConfigSection.getString(\"bungee\"));\n\n portals[portalId].setDestiation(portalConfigSection.getString(\"destination\"));\n\n portalId++;\n } else {\n AdvancedPortal[] tempPortals = portals;\n\n portals = new AdvancedPortal[portals.length - 1];\n\n System.arraycopy(tempPortals, 0, portals, 0, portalId);\n }\n }\n portalsActive = true;\n } else {\n portalsActive = false;\n portals = new AdvancedPortal[0];\n }\n }\n\n public static HashSet<Material> getMaterialSet(String[] blockTypesString) {\n HashSet<Material> blockTypes = new HashSet<>();\n\n if (blockTypesString != null) {\n for (String blockType : blockTypesString) {\n Material material = Material.getMaterial(blockType);\n if (material != null) {\n blockTypes.add(material);\n }\n }\n }\n\n return blockTypes;\n }\n\n public static Particle getParticle(String name) {\n try {\n return Particle.valueOf(name.toUpperCase());\n } catch (IllegalArgumentException e) {\n return null;\n }\n }\n\n public static String create(Location pos1, Location pos2, String name, String destination,\n Set<Material> triggerBlocks, PortalArg... extraData) {\n return create(pos1, pos2, name, destination, triggerBlocks, null, extraData);\n }\n\n public static String create(Location pos1, Location pos2, String name, String destination,\n Set<Material> triggerBlocks, String serverName, PortalArg... portalArgs) {\n\n if (!pos1.getWorld().equals(pos2.getWorld())) {\n plugin.getLogger().log(Level.WARNING, \"pos1 and pos2 must be in the same world!\");\n return \"\\u00A7cPortal creation error, pos1 and pos2 must be in the same world!\";\n }\n\n int LowX = 0;\n int LowY = 0;\n int LowZ = 0;\n\n int HighX = 0;\n int HighY = 0;\n int HighZ = 0;\n\n if (pos1.getX() > pos2.getX()) {\n LowX = (int) pos2.getX();\n HighX = (int) pos1.getX();\n } else {\n LowX = (int) pos1.getX();\n HighX = (int) pos2.getX();\n }\n if (pos1.getY() > pos2.getY()) {\n LowY = (int) pos2.getY();\n HighY = (int) pos1.getY();\n } else {\n LowY = (int) pos1.getY();\n HighY = (int) pos2.getY();\n }\n if (pos1.getZ() > pos2.getZ()) {\n LowZ = (int) pos2.getZ();\n HighZ = (int) pos1.getZ();\n } else {\n LowZ = (int) pos1.getZ();\n HighZ = (int) pos2.getZ();\n }\n\n Location checkpos1 = new Location(pos1.getWorld(), HighX, HighY, HighZ);\n Location checkpos2 = new Location(pos2.getWorld(), LowX, LowY, LowZ);\n\n /*\n * if (checkPortalOverlap(checkpos1, checkpos2)) {\n * plugin.getLogger().log(Level.WARNING, \"portals must not overlap!\"); return\n * \"\\u00A7cPortal creation error, portals must not overlap!\"; }\n */\n\n portalData.getConfig().set(name + \".world\", pos1.getWorld().getName());\n\n String store = triggerBlocks.stream().map(Enum::name).collect(Collectors.joining(\",\"));\n portalData.getConfig().set(name + \".triggerblock\", store);\n\n portalData.getConfig().set(name + \".destination\", destination);\n\n portalData.getConfig().set(name + \".bungee\", serverName);\n\n portalData.getConfig().set(name + \".pos1.X\", HighX);\n portalData.getConfig().set(name + \".pos1.Y\", HighY);\n portalData.getConfig().set(name + \".pos1.Z\", HighZ);\n\n portalData.getConfig().set(name + \".pos2.X\", LowX);\n portalData.getConfig().set(name + \".pos2.Y\", LowY);\n portalData.getConfig().set(name + \".pos2.Z\", LowZ);\n\n for (PortalArg arg : portalArgs) {\n portalData.getConfig().set(name + \".portalArgs.\" + arg.argName, arg.value);\n }\n\n portalData.saveConfig();\n\n loadPortals();\n\n return \"\\u00A7aPortal creation successful!\";\n }\n\n private static boolean checkPortalOverlap(Location pos1, Location pos2) {\n\n if (portalsActive) {\n int portalId = 0;\n for (@SuppressWarnings(\"unused\")\n Object portal : Portal.portals) {\n if (portals[portalId].getWorldName().equals(pos2.getWorld().getName())) { // checks that the cubes arnt\n // overlapping by seeing if\n // all 4 corners are not in\n // side another\n if (checkOverLapPortal(pos1, pos2, portals[portalId].getPos1().getBlockX(),\n portals[portalId].getPos1().getBlockY(), portals[portalId].getPos1().getBlockZ())) {\n return true;\n }\n\n if (checkOverLapPortal(pos1, pos2, portals[portalId].getPos1().getBlockX(),\n portals[portalId].getPos1().getBlockY(), portals[portalId].getPos2().getBlockZ())) {\n return true;\n }\n\n if (checkOverLapPortal(pos1, pos2, portals[portalId].getPos1().getBlockX(),\n portals[portalId].getPos2().getBlockY(), portals[portalId].getPos1().getBlockZ())) {\n return true;\n }\n\n if (checkOverLapPortal(pos1, pos2, portals[portalId].getPos2().getBlockX(),\n portals[portalId].getPos1().getBlockY(), portals[portalId].getPos1().getBlockZ())) {\n return true;\n }\n\n if (checkOverLapPortal(pos1, pos2, portals[portalId].getPos2().getBlockX(),\n portals[portalId].getPos2().getBlockY(), portals[portalId].getPos2().getBlockZ())) {\n return true;\n }\n\n if (checkOverLapPortal(pos1, pos2, portals[portalId].getPos2().getBlockX(),\n portals[portalId].getPos1().getBlockY(), portals[portalId].getPos2().getBlockZ())) {\n return true;\n }\n\n if (checkOverLapPortal(pos1, pos2, portals[portalId].getPos1().getBlockX(),\n portals[portalId].getPos2().getBlockY(), portals[portalId].getPos2().getBlockZ())) {\n return true;\n }\n\n if (checkOverLapPortal(pos1, pos2, portals[portalId].getPos2().getBlockX(),\n portals[portalId].getPos2().getBlockY(), portals[portalId].getPos1().getBlockZ())) {\n return true;\n }\n }\n portalId++;\n }\n }\n return false;\n }\n\n private static boolean checkOverLapPortal(Location pos1, Location pos2, int posX, int posY, int posZ) {\n if (pos1.getX() >= posX && pos1.getY() >= posX && pos1.getZ() >= posZ) {\n return (pos2.getX()) <= posX && pos2.getY() <= posY && pos2.getZ() <= posZ;\n }\n return false;\n }\n\n public static String create(Location pos1, Location pos2, String name, String destination, String serverName,\n PortalArg... extraData) { // add stuff for destination names or coordinates\n ConfigAccessor config = new ConfigAccessor(plugin, \"config.yml\");\n\n Material triggerBlockType;\n String BlockID = config.getConfig().getString(\"DefaultPortalTriggerBlock\");\n triggerBlockType = Material.getMaterial(BlockID);\n\n if (triggerBlockType == null) {\n triggerBlockType = Material.NETHER_PORTAL;\n }\n\n return create(pos1, pos2, name, destination, new HashSet<>(Collections.singletonList(triggerBlockType)),\n serverName, extraData);\n }\n\n public static void redefine(Location pos1, Location pos2, String name) {\n\n portalData.getConfig().set(name + \".pos1.X\", pos1.getX());\n portalData.getConfig().set(name + \".pos1.Y\", pos1.getY());\n portalData.getConfig().set(name + \".pos1.Z\", pos1.getZ());\n\n portalData.getConfig().set(name + \".pos2.X\", pos2.getX());\n portalData.getConfig().set(name + \".pos2.Y\", pos2.getY());\n portalData.getConfig().set(name + \".pos2.Z\", pos2.getZ());\n\n portalData.saveConfig();\n\n loadPortals();\n\n }\n\n public static String getDestination(String portalName) {\n return portalData.getConfig().getString(portalName + \".destination\");\n }\n\n public static void remove(String name) {\n\n Object[] keys = portalData.getConfig().getKeys(true).toArray();\n for (int i = keys.length - 1; i >= 0; i--) {\n String key = keys[i].toString();\n if (key.startsWith(name + \".\")) {\n portalData.getConfig().set(key, null);\n }\n }\n portalData.getConfig().set(name, null);\n\n // TODO add code to check if people have the portal selected and notify if\n // removed.\n\n /**\n * Set<String> keys = portalData.getConfig().getKeys(true); for(String key:\n * keys){ if(key.startsWith(name)){ portalData.getConfig().set(key, null); } }\n */\n\n /**\n * portalData.getConfig().set(name + \".world\", null);\n * portalData.getConfig().set(name + \".triggerblock\", null);\n * portalData.getConfig().set(name + \".destination\", null);\n *\n * portalData.getConfig().set(name + \".pos1.X\", null);\n * portalData.getConfig().set(name + \".pos1.Y\", null);\n * portalData.getConfig().set(name + \".pos1.Z\", null);\n *\n * portalData.getConfig().set(name + \".pos2.X\", null);\n * portalData.getConfig().set(name + \".pos2.Y\", null);\n * portalData.getConfig().set(name + \".pos2.Z\", null);\n *\n * portalData.getConfig().set(name + \".pos1\", null);\n * portalData.getConfig().set(name + \".getPos2()\", null);\n *\n * portalData.getConfig().set(name, null);\n */\n\n portalData.saveConfig();\n\n loadPortals();\n }\n\n public static AdvancedPortal getPortal(String portalName) {\n for (AdvancedPortal portalElement : Portal.portals) {\n if (portalElement.getName().equals(portalName)) {\n return portalElement;\n }\n }\n return null;\n }\n\n public static boolean portalExists(String portalName) {\n\n String posX = portalData.getConfig().getString(portalName + \".pos1.X\");\n\n return posX != null;\n }\n\n public static boolean activate(Player player, String portalName) {\n for (AdvancedPortal portal : Portal.portals) {\n if (portal.getName().equals(portalName))\n return activate(player, portal);\n }\n plugin.getLogger().log(Level.SEVERE, \"Portal not found by name of: \" + portalName);\n return false;\n }\n\n public static boolean activate(Player player, AdvancedPortal portal, boolean doKnockback) {\n\n if (blockSpectatorMode && player.getGameMode() == GameMode.SPECTATOR) {\n player.sendMessage(\n PluginMessages.customPrefixFail + \"\\u00A7c You cannot enter a portal in spectator mode!\");\n return false;\n }\n\n String permission = portal.getArg(\"permission\");\n\n boolean invertPermission = false;\n if(permission != null) {\n invertPermission = permission.startsWith(\"!\");\n if (invertPermission) {\n permission.substring(1);\n }\n }\n\n boolean noMessage = permission != null && permission.startsWith(\"nomsg.\");\n if(noMessage) {\n permission.substring(6);\n }\n\n if (!(permission == null || ((!invertPermission && player.hasPermission(permission)) || (invertPermission && !player.hasPermission(permission))) || player.isOp())) {\n if(!noMessage) {\n player.sendMessage(\n PluginMessages.customPrefixFail + \"\\u00A7c You do not have permission to use this portal!\");\n failSound(player, portal);\n if(doKnockback)\n throwPlayerBack(player);\n }\n return false;\n }\n\n Long joinCD = joinCooldown.get(player.getName());\n if (joinCD != null) {\n int diff = (int) ((System.currentTimeMillis() - joinCD) / 1000);\n if (diff < joinCooldownDelay) {\n int time = (joinCooldownDelay - diff);\n player.sendMessage(ChatColor.RED + \"There is \" + ChatColor.YELLOW + time + ChatColor.RED + (time == 1 ? \" second\" : \" seconds\") + \" join cooldown protection left.\");\n failSound(player, portal);\n if(doKnockback)\n throwPlayerBack(player);\n return false;\n }\n joinCooldown.remove(player.getName());\n }\n\n HashMap<String, Long> cds = cooldown.get(player.getName());\n if (cds != null) {\n if (cds.get(portal.getName()) != null) {\n long portalCD = cds.get(portal.getName());\n int diff = (int) ((System.currentTimeMillis() - portalCD) / 1000);\n int portalCooldown = 0; // default cooldowndelay when cooldowndelay is not specified\n try {\n portalCooldown = Integer.parseInt(portal.getArg(\"cooldowndelay\"));\n } catch (Exception ignored) {\n }\n if (diff < portalCooldown) {\n int time = (portalCooldown - diff);\n player.sendMessage(ChatColor.RED + \"Please wait \" + ChatColor.YELLOW + time + ChatColor.RED\n + (time == 1 ? \" second\" : \" seconds\") + \" until attempting to enter this portal again.\");\n failSound(player, portal);\n if(doKnockback)\n throwPlayerBack(player);\n return false;\n }\n }\n }\n if (cds == null) {\n cds = new HashMap<String, Long>();\n }\n cds.put(portal.getName(), System.currentTimeMillis());\n cooldown.put(player.getName(), cds);\n\n boolean showFailMessage = !portal.hasArg(\"command.1\");\n\n boolean hasMessage = portal.getArg(\"message\") != null;\n\n // plugin.getLogger().info(portal.getName() + \":\" + portal.getDestiation());\n boolean warped = false;\n if (portal.getBungee() != null) {\n String[] bungeeServers = portal.getBungee().split(\",\");\n String bungeeServer = bungeeServers[random.nextInt(bungeeServers.length)];\n if (showBungeeMessage) {\n player.sendMessage(PluginMessages.customPrefix + \"\\u00A7a Attempting to warp to \\u00A7e\" + bungeeServer\n + \"\\u00A7a.\");\n }\n\n if(portal.hasArg(\"leavedesti\")) {\n player.setMetadata(\"leaveDesti\", new FixedMetadataValue(plugin, portal.getArg(\"leavedesti\")));\n Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, () -> {\n player.removeMetadata(\"leaveDesti\", plugin);\n }, 20 * 10);\n }\n\n if (portal.getDestiation() != null) {\n if(plugin.isProxyPluginEnabled()) {\n ByteArrayDataOutput outForList = ByteStreams.newDataOutput();\n outForList.writeUTF(BungeeMessages.ENTER_PORTAL);\n outForList.writeUTF(bungeeServer);\n outForList.writeUTF(portal.getDestiation());\n outForList.writeUTF(player.getUniqueId().toString());\n\n player.sendPluginMessage(plugin, BungeeMessages.CHANNEL_NAME, outForList.toByteArray());\n }\n else {\n plugin.getLogger().log(Level.WARNING, \"You do not have bungee setup correctly. Cross server destinations won't work.\");\n }\n\n }\n\n ByteArrayDataOutput outForSend = ByteStreams.newDataOutput();\n outForSend.writeUTF(\"Connect\");\n outForSend.writeUTF(bungeeServer);\n\n\n\n portal.inPortal.add(player.getUniqueId());\n player.sendPluginMessage(plugin, \"BungeeCord\", outForSend.toByteArray());\n // Down to bungee to sort out the teleporting but yea theoretically they should\n // warp.\n } else if (portal.getDestiation() != null) {\n ConfigAccessor configDesti = new ConfigAccessor(plugin, \"destinations.yml\");\n if (configDesti.getConfig().getString(portal.getDestiation() + \".world\") != null) {\n warped = Destination.warp(player, portal.getDestiation(), portal, hasMessage, false);\n if (!warped) {\n if(doKnockback)\n throwPlayerBack(player);\n }\n }\n } else if (showFailMessage) {\n player.sendMessage(PluginMessages.customPrefixFail\n + \"\\u00A7c The portal you are trying to use doesn't have a destination!\");\n plugin.getLogger().log(Level.SEVERE, \"The portal '\" + portal.getName() + \"' has just had a warp \"\n + \"attempt and either the data is corrupt or portal doesn't exist!\");\n if(doKnockback)\n throwPlayerBack(player);\n failSound(player, portal);\n }\n\n if (portal.hasArg(\"command.1\")) {\n warped = true;\n int commandLine = 1;\n String command = portal.getArg(\"command.\" + commandLine);// portalData.getConfig().getString(portal.getName()+\n // \".portalArgs.command.\" + commandLine);\n do {\n // (?i) makes the search case insensitive\n command = command.replaceAll(\"@player\", player.getName());\n if(commandLog) plugin.getLogger().log(Level.INFO, \"Portal command: \" + command);\n if (command.startsWith(\"#\") && plugin.getSettings().enabledCommandLevel(\"c\")) {\n command = command.substring(1);\n try {\n plugin.getServer().dispatchCommand(Bukkit.getConsoleSender(), command);\n } catch (Exception e) {\n plugin.getLogger().warning(\"Error while executing: \" + command);\n }\n } else if (command.startsWith(\"!\") && plugin.getSettings().enabledCommandLevel(\"o\")) {\n command = command.substring(1);\n boolean wasOp = player.isOp();\n if(!wasOp) {\n try {\n player.setOp(true);\n player.chat(\"/\" + command);\n } finally {\n player.setOp(false);\n }\n } else {\n player.chat(\"/\" + command);\n }\n } else if (command.startsWith(\"^\") && plugin.getSettings().enabledCommandLevel(\"p\")) {\n command = command.substring(1);\n PermissionAttachment permissionAttachment = null;\n try {\n permissionAttachment = player.addAttachment(plugin, \"*\", true);\n player.chat(\"/\" + command);\n // player.performCommand(command);\n } finally {\n player.removeAttachment(permissionAttachment);\n }\n } else if (command.startsWith(\"%\") && plugin.getSettings().enabledCommandLevel(\"b\")) {\n if(plugin.isProxyPluginEnabled()) {\n command = command.substring(1);\n ByteArrayDataOutput outForList = ByteStreams.newDataOutput();\n outForList.writeUTF(BungeeMessages.BUNGEE_COMMAND);\n outForList.writeUTF(command);\n player.sendPluginMessage(plugin, BungeeMessages.CHANNEL_NAME, outForList.toByteArray());\n }\n else {\n plugin.getLogger().log(Level.WARNING, \"You do not have bungee setup correctly. For security advanced bungee features won't work.\");\n }\n\n } else {\n player.chat(\"/\" + command);\n // player.performCommand(command);\n }\n command = portal.getArg(\"command.\" + ++commandLine);\n } while (command != null);\n }\n\n if (warped) {\n if (hasMessage) {\n player.spigot().sendMessage(ChatMessageType.ACTION_BAR,\n TextComponent.fromLegacyText(portal.getArg(\"message\").replaceAll(\"&(?=[0-9a-fk-or])\", \"\\u00A7\")));\n }\n }\n\n return warped;\n }\n\n private static void failSound(Player player, AdvancedPortal portal) {\n if (!(portal.getTriggers().contains(Material.NETHER_PORTAL) && player.getGameMode() == GameMode.CREATIVE)) {\n player.playSound(player.getLocation(), portalSound, 0.2f, new Random().nextFloat() * 0.4F + 0.8F);\n }\n }\n\n public static void rename(String oldName, String newName) {\n\n // set it so it gets all data from one and puts it into another place\n\n ConfigAccessor config = new ConfigAccessor(plugin, \"portals.yml\");\n\n Set<String> keys = config.getConfig().getKeys(true);\n for (String key : keys) {\n if (key.startsWith(oldName + \".\")) {\n if (config.getConfig().getString(key) != null) {\n try {\n int intData = Integer.parseInt(config.getConfig().getString(key));\n config.getConfig().set(key.replace(oldName + \".\", newName + \".\"), intData);\n } catch (Exception e) {\n config.getConfig().set(key.replace(oldName + \".\", newName + \".\"),\n config.getConfig().getString(key));\n }\n\n }\n }\n }\n\n config.saveConfig();\n\n remove(oldName);\n\n }\n\n public static boolean addCommand(String portalName, String portalCommand) {\n ConfigAccessor config = new ConfigAccessor(plugin, \"portals.yml\");\n if (portalExists(portalName)) {\n int commandLine = 0;\n while (config.getConfig().getString(portalName + \".portalArgs.command.\" + ++commandLine) != null)\n ; // Loops increasing commandLine till 1 is null\n config.getConfig().set(portalName + \".portalArgs.command.\" + commandLine, portalCommand);\n config.saveConfig();\n loadPortals();\n return true;\n } else {\n return false;\n }\n }\n\n public static boolean inPortalTriggerRegion(Location loc) {\n for (AdvancedPortal portal : Portal.portals)\n if (Portal.locationInPortalTrigger(portal, loc))\n return true;\n return false;\n }\n\n public static boolean locationInPortalTrigger(AdvancedPortal portal, Location loc, int additionalArea) {\n return portal.getTriggers().contains(loc.getBlock().getType()) && locationInPortal(portal, loc, additionalArea);\n }\n\n public static boolean locationInPortalTrigger(AdvancedPortal portal, Location loc) {\n return locationInPortalTrigger(portal, loc, 0);\n }\n\n public static boolean inPortalRegion(Location loc, int additionalArea) {\n for (AdvancedPortal portal : Portal.portals)\n if (Portal.locationInPortal(portal, loc, additionalArea))\n return true;\n return false;\n }\n\n public static boolean locationInPortal(Location loc, int additionalArea) {\n for (AdvancedPortal portal : Portal.portals)\n if (Portal.locationInPortal(portal, loc, additionalArea))\n return true;\n return false;\n }\n\n public static boolean locationInPortal(AdvancedPortal portal, Location loc) {\n return locationInPortal(portal, loc);\n }\n\n public static boolean locationInPortal(AdvancedPortal portal, Location loc, int additionalArea) {\n if (!portalsActive)\n return false;\n if (loc.getWorld() != null && portal.getWorldName().equals(loc.getWorld().getName()))\n if ((portal.getPos1().getX() + 1 + additionalArea) >= loc.getX()\n && (portal.getPos1().getY() + 1 + additionalArea) > loc.getY()\n && (portal.getPos1().getZ() + 1 + additionalArea) >= loc.getZ())\n return portal.getPos2().getX() - additionalArea <= loc.getX()\n && portal.getPos2().getY() - additionalArea <= loc.getY()\n && portal.getPos2().getZ() - additionalArea <= loc.getZ();\n return false;\n }\n\n public static void throwPlayerBack(Player player) {\n // Not ensured to remove them out of the portal but it makes it feel nicer for\n // the player.\n if (throwback > 0) {\n Vector velocity = player.getLocation().getDirection();\n player.setVelocity(velocity.setY(0).normalize().multiply(-1).setY(throwback));\n }\n }\n\n public static int getPortalProtectionRadius() {\n return portalProtectionRadius;\n }\n\n public static boolean activate(Player player, AdvancedPortal portal) {\n return activate(player, portal, true);\n }\n}"
] | import com.sekwah.advancedportals.bukkit.AdvancedPortalsPlugin;
import com.sekwah.advancedportals.bukkit.PluginMessages;
import com.sekwah.advancedportals.bukkit.api.events.WarpEvent;
import com.sekwah.advancedportals.bukkit.config.ConfigAccessor;
import com.sekwah.advancedportals.bukkit.destinations.Destination;
import com.sekwah.advancedportals.bukkit.portals.AdvancedPortal;
import com.sekwah.advancedportals.bukkit.portals.Portal;
import org.bukkit.*;
import org.bukkit.block.data.BlockData;
import org.bukkit.block.data.Orientable;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.event.entity.EntityCombustEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityPortalEvent;
import org.bukkit.event.player.*;
import org.bukkit.inventory.ItemStack;
import org.bukkit.metadata.FixedMetadataValue;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID; | package com.sekwah.advancedportals.bukkit.listeners;
public class Listeners implements Listener {
private static boolean UseOnlyServerAxe = false;
private static Material WandMaterial;
private final AdvancedPortalsPlugin plugin;
public static String HAS_WARPED = "hasWarped";
public static String LAVA_WARPED = "lavaWarped";
@SuppressWarnings("deprecation")
public Listeners(AdvancedPortalsPlugin plugin) {
this.plugin = plugin;
| ConfigAccessor config = new ConfigAccessor(plugin, "config.yml"); | 3 |
spring-cloud/spring-cloud-bus | spring-cloud-bus/src/test/java/org/springframework/cloud/bus/BusAutoConfigurationTests.java | [
"@SuppressWarnings(\"serial\")\npublic class AckRemoteApplicationEvent extends RemoteApplicationEvent {\n\n\tprivate final String ackId;\n\n\tprivate final String ackDestinationService;\n\n\tprivate Class<? extends RemoteApplicationEvent> event;\n\n\t@SuppressWarnings(\"unused\")\n\tprivate AckRemoteApplicationEvent() {\n\t\tsuper();\n\t\tthis.ackDestinationService = null;\n\t\tthis.ackId = null;\n\t\tthis.event = null;\n\t}\n\n\tpublic AckRemoteApplicationEvent(Object source, String originService, Destination destination,\n\t\t\tString ackDestinationService, String ackId, Class<? extends RemoteApplicationEvent> type) {\n\t\tsuper(source, originService, destination);\n\t\tthis.ackDestinationService = ackDestinationService;\n\t\tthis.ackId = ackId;\n\t\tthis.event = type;\n\t}\n\n\tpublic String getAckId() {\n\t\treturn this.ackId;\n\t}\n\n\tpublic String getAckDestinationService() {\n\t\treturn this.ackDestinationService;\n\t}\n\n\tpublic Class<? extends RemoteApplicationEvent> getEvent() {\n\t\treturn this.event;\n\t}\n\n\t/**\n\t * Used by Jackson to set the remote class name of the event implementation. If the\n\t * implementing class is unknown to this app, set the event to\n\t * {@link UnknownRemoteApplicationEvent}.\n\t * @param eventName the fq class name of the event implementation, not null\n\t */\n\t@JsonProperty(\"event\")\n\t@SuppressWarnings(\"unchecked\")\n\tpublic void setEventName(String eventName) {\n\t\ttry {\n\t\t\tthis.event = (Class<? extends RemoteApplicationEvent>) Class.forName(eventName);\n\t\t}\n\t\tcatch (ClassNotFoundException e) {\n\t\t\tthis.event = UnknownRemoteApplicationEvent.class;\n\t\t}\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = super.hashCode();\n\t\tresult = prime * result + ((this.ackDestinationService == null) ? 0 : this.ackDestinationService.hashCode());\n\t\tresult = prime * result + ((this.ackId == null) ? 0 : this.ackId.hashCode());\n\t\tresult = prime * result + ((this.event == null) ? 0 : this.event.hashCode());\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj) {\n\t\t\treturn true;\n\t\t}\n\t\tif (!super.equals(obj)) {\n\t\t\treturn false;\n\t\t}\n\t\tif (getClass() != obj.getClass()) {\n\t\t\treturn false;\n\t\t}\n\t\tAckRemoteApplicationEvent other = (AckRemoteApplicationEvent) obj;\n\t\tif (this.ackDestinationService == null) {\n\t\t\tif (other.ackDestinationService != null) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\telse if (!this.ackDestinationService.equals(other.ackDestinationService)) {\n\t\t\treturn false;\n\t\t}\n\t\tif (this.ackId == null) {\n\t\t\tif (other.ackId != null) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\telse if (!this.ackId.equals(other.ackId)) {\n\t\t\treturn false;\n\t\t}\n\t\tif (this.event == null) {\n\t\t\tif (other.event != null) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\telse if (!this.event.equals(other.event)) {\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\n}",
"public class PathDestinationFactory implements Destination.Factory {\n\n\tpublic Destination getDestination(String originalDestination) {\n\t\tString path = originalDestination;\n\t\tif (path == null) {\n\t\t\tpath = \"**\";\n\t\t}\n\t\t// If the path is not already a wildcard, match everything that\n\t\t// follows if there at most two path elements, and last element is not a global\n\t\t// wildcard already\n\t\tif (!\"**\".equals(path)) {\n\t\t\tif (StringUtils.countOccurrencesOf(path, \":\") <= 1 && !StringUtils.endsWithIgnoreCase(path, \":**\")) {\n\t\t\t\t// All instances of the destination unless specifically requested\n\t\t\t\tpath = path + \":**\";\n\t\t\t}\n\t\t}\n\n\t\tfinal String finalPath = path;\n\t\treturn () -> finalPath;\n\t}\n\n}",
"@SuppressWarnings(\"serial\")\npublic class RefreshRemoteApplicationEvent extends RemoteApplicationEvent {\n\n\t@SuppressWarnings(\"unused\")\n\tprivate RefreshRemoteApplicationEvent() {\n\t\t// for serializers\n\t}\n\n\t@Deprecated\n\tpublic RefreshRemoteApplicationEvent(Object source, String originService, String destination) {\n\t\tthis(source, originService, new PathDestinationFactory().getDestination(destination));\n\t}\n\n\tpublic RefreshRemoteApplicationEvent(Object source, String originService, Destination destination) {\n\t\tsuper(source, originService, destination);\n\t}\n\n}",
"@SuppressWarnings(\"serial\")\n@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = \"type\")\n@JsonIgnoreProperties(\"source\")\npublic abstract class RemoteApplicationEvent extends ApplicationEvent {\n\n\tprivate static final Object TRANSIENT_SOURCE = new Object();\n\n\tprivate static final String TRANSIENT_ORIGIN = \"____transient_origin_service___\";\n\n\tprivate static final String TRANSIENT_DESTINATION = \"____transient_destination___\";\n\n\tprotected static final PathDestinationFactory DEFAULT_DESTINATION_FACTORY = new PathDestinationFactory();\n\n\tprivate final String originService;\n\n\tprivate final String destinationService;\n\n\tprivate final String id;\n\n\tprotected RemoteApplicationEvent() {\n\t\t// for serialization libs like jackson\n\t\tthis(TRANSIENT_SOURCE, TRANSIENT_ORIGIN, DEFAULT_DESTINATION_FACTORY.getDestination(TRANSIENT_DESTINATION));\n\t}\n\n\t@Deprecated\n\tprotected RemoteApplicationEvent(Object source, String originService, String destinationService) {\n\t\tthis(source, originService, DEFAULT_DESTINATION_FACTORY.getDestination(destinationService));\n\t}\n\n\tprotected RemoteApplicationEvent(Object source, String originService, Destination destination) {\n\t\tsuper(source);\n\t\tif (!originService.equals(TRANSIENT_ORIGIN)) {\n\t\t\tAssert.notNull(originService, \"originService may not be null\");\n\t\t\tthis.originService = originService;\n\t\t}\n\t\telse {\n\t\t\tthis.originService = null;\n\t\t}\n\t\tAssert.notNull(destination, \"destination may not be null\");\n\t\tthis.destinationService = destination.getDestinationAsString();\n\t\tAssert.hasText(destinationService, \"destinationService may not be empty\");\n\t\tthis.id = UUID.randomUUID().toString();\n\t}\n\n\t@Deprecated\n\tprotected RemoteApplicationEvent(Object source, String originService) {\n\t\tthis(source, originService, DEFAULT_DESTINATION_FACTORY.getDestination(null));\n\t}\n\n\tpublic String getOriginService() {\n\t\treturn this.originService;\n\t}\n\n\tpublic String getDestinationService() {\n\t\treturn this.destinationService;\n\t}\n\n\tpublic String getId() {\n\t\treturn this.id;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = 1;\n\t\tresult = prime * result + ((this.destinationService == null) ? 0 : this.destinationService.hashCode());\n\t\tresult = prime * result + ((this.id == null) ? 0 : this.id.hashCode());\n\t\tresult = prime * result + ((this.originService == null) ? 0 : this.originService.hashCode());\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj) {\n\t\t\treturn true;\n\t\t}\n\t\tif (obj == null) {\n\t\t\treturn false;\n\t\t}\n\t\tif (getClass() != obj.getClass()) {\n\t\t\treturn false;\n\t\t}\n\t\tRemoteApplicationEvent other = (RemoteApplicationEvent) obj;\n\t\tif (this.destinationService == null) {\n\t\t\tif (other.destinationService != null) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\telse if (!this.destinationService.equals(other.destinationService)) {\n\t\t\treturn false;\n\t\t}\n\t\tif (this.id == null) {\n\t\t\tif (other.id != null) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\telse if (!this.id.equals(other.id)) {\n\t\t\treturn false;\n\t\t}\n\t\tif (this.originService == null) {\n\t\t\tif (other.originService != null) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\telse if (!this.originService.equals(other.originService)) {\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn new ToStringCreator(this).append(\"id\", id).append(\"originService\", originService)\n\t\t\t\t.append(\"destinationService\", destinationService).toString();\n\n\t}\n\n}",
"@SuppressWarnings(\"serial\")\n@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = \"type\")\n@JsonIgnoreProperties(\"source\")\npublic class SentApplicationEvent extends ApplicationEvent {\n\n\tprivate static final Object TRANSIENT_SOURCE = new Object();\n\n\tprivate final String originService;\n\n\tprivate final String destinationService;\n\n\tprivate final String id;\n\n\tprivate Class<? extends RemoteApplicationEvent> type;\n\n\tprotected SentApplicationEvent() {\n\t\t// for serialization libs like jackson\n\t\tthis(TRANSIENT_SOURCE, null, null, null, RemoteApplicationEvent.class);\n\t}\n\n\tpublic SentApplicationEvent(Object source, String originService, String destinationService, String id,\n\t\t\tClass<? extends RemoteApplicationEvent> type) {\n\t\tsuper(source);\n\t\tthis.originService = originService;\n\t\tthis.type = type;\n\t\tif (destinationService == null) {\n\t\t\tdestinationService = \"*\";\n\t\t}\n\t\tif (!destinationService.contains(\":\")) {\n\t\t\t// All instances of the destination unless specifically requested\n\t\t\tdestinationService = destinationService + \":**\";\n\t\t}\n\t\tthis.destinationService = destinationService;\n\t\tthis.id = id;\n\t}\n\n\tpublic Class<? extends RemoteApplicationEvent> getType() {\n\t\treturn this.type;\n\t}\n\n\tpublic void setType(Class<? extends RemoteApplicationEvent> type) {\n\t\tthis.type = type;\n\t}\n\n\tpublic String getOriginService() {\n\t\treturn this.originService;\n\t}\n\n\tpublic String getDestinationService() {\n\t\treturn this.destinationService;\n\t}\n\n\tpublic String getId() {\n\t\treturn this.id;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = 1;\n\t\tresult = prime * result + ((this.destinationService == null) ? 0 : this.destinationService.hashCode());\n\t\tresult = prime * result + ((this.id == null) ? 0 : this.id.hashCode());\n\t\tresult = prime * result + ((this.originService == null) ? 0 : this.originService.hashCode());\n\t\tresult = prime * result + ((this.type == null) ? 0 : this.type.hashCode());\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj) {\n\t\t\treturn true;\n\t\t}\n\t\tif (obj == null) {\n\t\t\treturn false;\n\t\t}\n\t\tif (getClass() != obj.getClass()) {\n\t\t\treturn false;\n\t\t}\n\t\tSentApplicationEvent other = (SentApplicationEvent) obj;\n\t\tif (this.destinationService == null) {\n\t\t\tif (other.destinationService != null) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\telse if (!this.destinationService.equals(other.destinationService)) {\n\t\t\treturn false;\n\t\t}\n\t\tif (this.id == null) {\n\t\t\tif (other.id != null) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\telse if (!this.id.equals(other.id)) {\n\t\t\treturn false;\n\t\t}\n\t\tif (this.originService == null) {\n\t\t\tif (other.originService != null) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\telse if (!this.originService.equals(other.originService)) {\n\t\t\treturn false;\n\t\t}\n\t\tif (this.type == null) {\n\t\t\tif (other.type != null) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\telse if (!this.type.equals(other.type)) {\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\n}",
"public class UnknownRemoteApplicationEvent extends RemoteApplicationEvent {\n\n\tprotected String typeInfo;\n\n\tprotected byte[] payload;\n\n\t@SuppressWarnings(\"unused\")\n\tprivate UnknownRemoteApplicationEvent() {\n\t\tsuper();\n\t\tthis.typeInfo = null;\n\t\tthis.payload = null;\n\t}\n\n\tpublic UnknownRemoteApplicationEvent(Object source, String typeInfo, byte[] payload) {\n\t\t// Initialize originService with an empty String, to avoid NullPointer in\n\t\t// AntPathMatcher.\n\t\tsuper(source, \"\", () -> \"unknown\");\n\t\tthis.typeInfo = typeInfo;\n\t\tthis.payload = payload;\n\t}\n\n\tpublic String getTypeInfo() {\n\t\treturn this.typeInfo;\n\t}\n\n\tpublic byte[] getPayload() {\n\t\treturn this.payload;\n\t}\n\n\tpublic String getPayloadAsString() {\n\t\tif (this.payload != null) {\n\t\t\treturn new String(this.payload);\n\t\t}\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn new ToStringCreator(this).append(\"id\", getId()).append(\"originService\", getOriginService())\n\t\t\t\t.append(\"destinationService\", getDestinationService()).append(\"typeInfo\", typeInfo)\n\t\t\t\t.append(\"payload\", getPayloadAsString()).toString();\n\n\t}\n\n}"
] | import java.util.HashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.Test;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration;
import org.springframework.cloud.bus.event.AckRemoteApplicationEvent;
import org.springframework.cloud.bus.event.PathDestinationFactory;
import org.springframework.cloud.bus.event.RefreshRemoteApplicationEvent;
import org.springframework.cloud.bus.event.RemoteApplicationEvent;
import org.springframework.cloud.bus.event.SentApplicationEvent;
import org.springframework.cloud.bus.event.UnknownRemoteApplicationEvent;
import org.springframework.cloud.context.refresh.ContextRefresher;
import org.springframework.cloud.stream.config.BindingProperties;
import org.springframework.cloud.stream.config.BindingServiceProperties;
import org.springframework.cloud.stream.function.StreamBridge;
import org.springframework.cloud.stream.test.binder.TestSupportBinderAutoConfiguration;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.support.GenericMessage;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when; | /*
* Copyright 2012-2019 the original author or 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
*
* https://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 org.springframework.cloud.bus;
public class BusAutoConfigurationTests {
private ConfigurableApplicationContext context;
@After
public void close() {
if (this.context != null) {
this.context.close();
}
}
@Test
public void defaultId() {
this.context = SpringApplication.run(InboundMessageHandlerConfiguration.class, "--server.port=0");
assertThat(this.context.getBean(BusProperties.class).getId().startsWith("application:0:"))
.as("Wrong ID: " + this.context.getBean(BusProperties.class).getId()).isTrue();
}
@Test
public void inboundNotForSelf() {
this.context = SpringApplication.run(InboundMessageHandlerConfiguration.class, "--spring.cloud.bus.id=foo",
"--server.port=0");
this.context.getBean(BusConstants.INPUT, MessageChannel.class)
.send(new GenericMessage<>(new RefreshRemoteApplicationEvent(this, "bar", "bar")));
assertThat(this.context.getBean(InboundMessageHandlerConfiguration.class).refresh).isNull();
}
@Test
public void inboundFromSelf() {
this.context = SpringApplication.run(InboundMessageHandlerConfiguration.class, "--spring.cloud.bus.id=foo",
"--server.port=0");
this.context.getBean(BusConstants.INPUT, MessageChannel.class)
.send(new GenericMessage<>(new RefreshRemoteApplicationEvent(this, "foo", (String) null)));
assertThat(this.context.getBean(InboundMessageHandlerConfiguration.class).refresh).isNull();
}
@Test
public void inboundNotFromSelf() {
this.context = SpringApplication.run(InboundMessageHandlerConfiguration.class, "--spring.cloud.bus.id=bar",
"--server.port=0");
this.context.getBean(BusConstants.INPUT, MessageChannel.class)
.send(new GenericMessage<>(new RefreshRemoteApplicationEvent(this, "foo", (String) null)));
assertThat(this.context.getBean(InboundMessageHandlerConfiguration.class).refresh).isNotNull();
}
@Test
public void inboundNotFromSelfWithAck() throws Exception {
this.context = SpringApplication.run(
new Class[] { InboundMessageHandlerConfiguration.class, OutboundMessageHandlerConfiguration.class,
SentMessageConfiguration.class },
new String[] { "--spring.cloud.bus.id=bar", "--server.port=0",
"--spring.main.allow-bean-definition-overriding=true" });
this.context.getBean(BusConstants.INPUT, MessageChannel.class)
.send(new GenericMessage<>(new RefreshRemoteApplicationEvent(this, "foo", (String) null)));
RefreshRemoteApplicationEvent refresh = this.context.getBean(InboundMessageHandlerConfiguration.class).refresh;
assertThat(refresh).isNotNull();
TestStreamBusBridge busBridge = this.context.getBean(TestStreamBusBridge.class);
busBridge.latch.await(200, TimeUnit.SECONDS); | assertThat(busBridge.message).isInstanceOf(AckRemoteApplicationEvent.class); | 0 |
mzlogin/guanggoo-android | app/src/main/java/org/mazhuang/guanggoo/topiclist/TopicListPresenter.java | [
"public class NetworkTaskScheduler {\n\n private ExecutorService mExecutor;\n\n private static class InstanceHolder {\n private static NetworkTaskScheduler sInstance = new NetworkTaskScheduler();\n }\n\n public static NetworkTaskScheduler getInstance() {\n return InstanceHolder.sInstance;\n }\n\n private NetworkTaskScheduler() {\n mExecutor = new ThreadPoolExecutor(\n 1,\n 1,\n 5,\n TimeUnit.SECONDS,\n new LinkedBlockingQueue<Runnable>(),\n new NamedThreadFactory(NetworkTaskScheduler.class.getSimpleName())\n );\n }\n\n public void execute(Runnable runnable) {\n mExecutor.execute(runnable);\n }\n}",
"public interface OnResponseListener<T> {\n /**\n * 任务执行成功\n * @param data 回调的数据\n */\n void onSucceed(T data);\n\n /**\n * 任务执行失败\n * @param msg 失败提示信息\n */\n void onFailed(String msg);\n}",
"@Data\npublic class ListResult<T> {\n private List<T> data;\n private boolean hasMore;\n}",
"public class Topic {\n private String title;\n private String url;\n private String avatar;\n private Meta meta;\n private int count;\n\n public String getTitle() {\n return title;\n }\n\n public void setTitle(String title) {\n this.title = title;\n }\n\n public String getUrl() {\n return url;\n }\n\n public void setUrl(String url) {\n this.url = url;\n }\n\n public Meta getMeta() {\n return meta;\n }\n\n public void setMeta(Meta meta) {\n this.meta = meta;\n }\n\n public String getAvatar() {\n return avatar;\n }\n\n public void setAvatar(String avatar) {\n this.avatar = avatar;\n }\n\n public int getCount() {\n return count;\n }\n\n public void setCount(int count) {\n this.count = count;\n }\n\n public String getLastReplyUserName() {\n if (meta != null && meta.getLastReplyUser() != null) {\n return meta.getLastReplyUser().getUsername();\n }\n\n return null;\n }\n}",
"public abstract class BaseTask<T> implements Runnable {\n protected Handler mHandler = new Handler(Looper.getMainLooper());\n protected OnResponseListener<T> mListener;\n\n protected boolean mIsCanceled = false;\n\n BaseTask(OnResponseListener<T> listener) {\n mListener = listener;\n }\n\n public void cancel() {\n mIsCanceled = true;\n }\n\n public boolean isCanceled() {\n return mIsCanceled;\n }\n\n protected void successOnUI(final T data) {\n if (!mIsCanceled && mListener != null) {\n mHandler.post(new Runnable() {\n @Override\n public void run() {\n mListener.onSucceed(data);\n }\n });\n }\n }\n\n protected void failedOnUI(final String msg) {\n if (!mIsCanceled && mListener != null) {\n mHandler.post(new Runnable() {\n @Override\n public void run() {\n mListener.onFailed(msg);\n }\n });\n }\n }\n\n protected Connection getConnection(String url) {\n Connection connection = Jsoup.connect(url);\n\n Map<String, String> cookies = getCookies();\n if (cookies.size() > 0) {\n connection.cookies(cookies);\n }\n\n return connection;\n }\n\n protected Document get(String url) throws IOException {\n Document doc = getConnection(url).get();\n checkNotification(doc);\n return fixLink(doc);\n }\n\n protected Map<String, String> getCookies() {\n Map<String, String> cookies = new HashMap<>();\n String cookieString = PrefsUtil.getString(App.getInstance(), ConstantUtil.KEY_COOKIE, \"\");\n if (!TextUtils.isEmpty(cookieString)) {\n\n try {\n JSONObject jsonObject = new JSONObject(cookieString);\n\n Iterator it = jsonObject.keys();\n while (it.hasNext()) {\n String key = String.valueOf(it.next());\n cookies.put(key, (String) jsonObject.get(key));\n }\n } catch (JSONException e) {\n e.printStackTrace();\n }\n }\n\n return cookies;\n }\n\n protected String getCookieValue(String key) {\n Map<String, String> cookies = getCookies();\n return cookies.get(key);\n }\n\n protected String getXsrf() {\n return PrefsUtil.getString(App.getInstance(), ConstantUtil.KEY_XSRF, \"\");\n }\n\n protected <T extends Element> T fixLink(T element) {\n Elements links = element.select(\"[href]\");\n for (Element link : links) {\n String href = link.attr(\"href\");\n if (!TextUtils.isEmpty(href)) {\n if (href.toLowerCase().startsWith(\"http\")) {\n continue;\n }\n link.attr(\"href\", link.absUrl(\"href\"));\n }\n }\n links = element.select(\"[src]\");\n for (Element link : links) {\n String src = link.attr(\"src\");\n if (!TextUtils.isEmpty(src)) {\n if (src.toLowerCase().startsWith(\"http\")) {\n continue;\n }\n link.attr(\"src\", link.absUrl(\"src\"));\n }\n }\n return element;\n }\n\n protected void checkNotification(Document doc) {\n Elements elements = doc.select(\"a.contextually-unread\");\n final boolean hasNotifications = !elements.isEmpty();\n mHandler.post(() -> App.getInstance().mGlobal.hasNotifications.setValue(hasNotifications));\n }\n\n protected boolean checkAuth(Document doc) {\n Elements elements = doc.select(\"div.usercard\");\n if (!elements.isEmpty()) {\n Element usercardElement = elements.first();\n\n AuthInfoManager.getInstance().setUsername(usercardElement.select(\"div.username\").first().text());\n AuthInfoManager.getInstance().setAvatar(usercardElement.select(\"img.avatar\").first().attr(\"src\"));\n return true;\n }\n return false;\n }\n\n /**\n * 尝试补偿登录状态\n * @param doc -\n */\n protected void tryFixAuthStatus(Document doc) {\n if (doc == null) {\n return;\n }\n\n if (TextUtils.isEmpty(AuthInfoManager.getInstance().getUsername())) {\n checkAuth(doc);\n }\n }\n}",
"public class GetTopicListTask extends BaseTask<ListResult<Topic>> implements Runnable {\n\n private String mUrl;\n\n public GetTopicListTask(String url, OnResponseListener<ListResult<Topic>> listener) {\n super(listener);\n mUrl = url;\n }\n\n @Override\n public void run() {\n List<Topic> topics = new ArrayList<>();\n\n boolean succeed = false;\n boolean hasMore = false;\n try {\n Document doc = get(mUrl);\n\n tryFixAuthStatus(doc);\n\n Elements elements = doc.select(\"div.topic-item\");\n\n for (Element element : elements) {\n Topic topic = createTopicFromElement(element);\n topics.add(topic);\n }\n\n succeed = true;\n\n Elements paginationElements = doc.select(\"ul.pagination\");\n if (!paginationElements.isEmpty()) {\n Elements disabledElements = paginationElements.select(\"li.disabled\");\n if (disabledElements.isEmpty()) {\n hasMore = true;\n } else if (disabledElements.last() != null) {\n Elements disableLinkElements = disabledElements.last().select(\"a\");\n if (!ConstantUtil.NEXT_PAGE.equals(disableLinkElements.text())) {\n hasMore = true;\n }\n }\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n\n if (succeed) {\n ListResult<Topic> topicList = new ListResult<>();\n topicList.setData(topics);\n topicList.setHasMore(hasMore);\n successOnUI(topicList);\n } else {\n failedOnUI(\"获取主题列表失败\");\n }\n }\n\n public static Topic createTopicFromElement(Element element) {\n Topic topic = new Topic();\n\n Element titleElement = element.select(\"h3.title\").select(\"a\").first();\n if (titleElement != null) {\n // 主题列表页\n topic.setTitle(titleElement.text());\n } else {\n // 主题详情页\n titleElement = element.select(\"h3.title\").first();\n if (titleElement != null) {\n topic.setTitle(titleElement.text());\n }\n }\n topic.setUrl(titleElement.absUrl(\"href\"));\n\n topic.setAvatar(element.select(\"img.avatar\").attr(\"src\"));\n\n Element metaElement = element.select(\"div.meta\").first();\n Meta meta = createMetaFromElement(metaElement);\n\n topic.setMeta(meta);\n\n Elements countElements = element.select(\"div.count\");\n if (!countElements.isEmpty()) {\n topic.setCount(Integer.valueOf(countElements.first().select(\"a\").first().text()));\n }\n\n return topic;\n }\n\n private static Meta createMetaFromElement(Element element) {\n Meta meta = new Meta();\n\n Element nodeElement = element.select(\"span.node\").select(\"a\").first();\n Node node = new Node();\n node.setTitle(nodeElement.text());\n node.setUrl(nodeElement.absUrl(\"href\"));\n\n meta.setNode(node);\n\n Element userElement = element.select(\"span.username\").select(\"a\").first();\n User user = new User();\n user.setUsername(userElement.text());\n user.setUrl(userElement.absUrl(\"href\"));\n\n meta.setAuthor(user);\n\n // 主题列表页\n Elements lastTouchedElement = element.select(\"span.last-touched\");\n if (lastTouchedElement.isEmpty()) {\n // 主题详情页\n lastTouchedElement = element.select(\"span.last-reply-time\");\n }\n meta.setLastTouched(lastTouchedElement.text());\n\n Elements createdTimeElement = element.select(\"span.created-time\");\n meta.setCreatedTime(createdTimeElement.text());\n\n Element lastReplyUserElement = element.select(\"span.last-reply-username\").select(\"a\").first();\n if (lastReplyUserElement != null) {\n User lastReplyUser = new User();\n lastReplyUser.setUsername(lastReplyUserElement.select(\"strong\").text());\n lastReplyUser.setUrl(lastReplyUserElement.absUrl(\"href\"));\n\n meta.setLastReplyUser(lastReplyUser);\n }\n\n return meta;\n }\n}",
"public class ConstantUtil {\n\n private ConstantUtil() {}\n\n\n public static final String HOME_URL = \"HOME_PAGE\";\n public static final String BASE_URL = \"https://www.guozaoke.com\";\n public static final String FAVORITE_URL = BASE_URL + \"/favorite\";\n public static final String UN_FAVORITE_URL = BASE_URL + \"/unfavorite\";\n public static final String LOGIN_URL = BASE_URL + \"/login\";\n public static final String REGISTER_URL = BASE_URL + \"/register\";\n public static final String BEGINNER_GUIDE_URL = BASE_URL + \"/t/2657\";\n public static final String NODES_CLOUD_URL = BASE_URL + \"/nodes\";\n public static final String SELECT_NODE_URL = NODES_CLOUD_URL + \" \";\n public static final String BLOCKED_USER_URL = BASE_URL + \"/setting/blockedUser\";\n public static final String LATEST_URL = BASE_URL + \"/?tab=latest\";\n public static final String ELITE_URL = BASE_URL + \"/?tab=elite\";\n public static final String FOLLOWS_URL = BASE_URL + \"/?tab=follows\";\n public static final String USER_PROFILE_BASE_URL = BASE_URL + \"/u/%s\";\n public static final String USER_PROFILE_SELF_FAKE_URL = BASE_URL + \"/u/0\";\n public static final String USER_FAVORS_BASE_URL = BASE_URL + \"/u/%s/favorites\";\n public static final String USER_TOPICS_BASE_URL = BASE_URL + \"/u/%s/topics\";\n public static final String USER_REPLIES_BASE_URL = BASE_URL + \"/u/%s/replies\";\n public static final String FOLLOW_USER_BASE_URL = BASE_URL + \"/f/user/%s\";\n public static final String BLOCK_USER_BASE_URL = BASE_URL + \"/u/%s/block\";\n public static final String UNBLOCK_USER_BASE_URL = BASE_URL + \"/u/%s/unblock\";\n public static final String NEW_TOPIC_BASE_URL = BASE_URL + \"/t/create/%s\";\n public static final String NOTIFICATIONS_URL = BASE_URL + \"/notifications\";\n\n public static final String VERIFY_TELEPHONE_URL = BASE_URL + \"/setting/phoneNum\";\n\n public static final String ABOUT_URL = \"INNER_PAGE_ABOUT\";\n public static final String SEARCH_URL = \"SEARCH_URL\";\n public static final String SETTINGS_URL = \"SETTINGS_URL\";\n public static final String SETTINGS_EDIT_URL = \"SETTINGS_EDIT_URL\";\n public static final String FEEDBACK_URL = \"FEEDBACK_URL\";\n\n public static final int TOPICS_PER_PAGE = 36;\n\n public static final int FAVORITE_PER_PAGE = 16;\n\n public static final int COMMENTS_PER_PAGE = 106;\n\n public static final int REPLIES_PER_PAGE = 16;\n\n public static final int NOTIFICATIONS_PER_PAGE = 16;\n\n public static final String KEY_COOKIE = \"cookie\";\n public static final String KEY_XSRF = \"_xsrf\";\n public static final String KEY_COMMENTS_ORDER_DESC = \"comments_order_desc\";\n public static final String KEY_PRIVACY_POLICY_AGREED_VERSION = \"privacy_policy_agreed_version\";\n public static final String KEY_IMG_BED_API_KEY = \"img_bed_api_key\";\n\n public static final String NEXT_PAGE = \"下一页\";\n\n public static final int HTTP_STATUS_200 = 200;\n public static final int HTTP_STATUS_302 = 302;\n public static final int HTTP_STATUS_304 = 304;\n\n public static final int MAX_TOPICS = 1024;\n\n public static final String DOWNLOAD_URL_COOLAPK = \"https://www.coolapk.com/apk/164523\";\n public static final String PRIVACY_URL = \"https://mazhuang.org/guanggoo-android/policy\";\n public static final String IMAGE_BED_HELP_URL = \"https://mazhuang.org/guanggoo-android/image-bed-help\";\n}",
"public class UrlUtil {\n\n private UrlUtil() {}\n\n private static Pattern sTidPattern = Pattern.compile(\"/t/(\\\\d+)\");\n private static Pattern sNodeCodePattern = Pattern.compile(\"/node/(\\\\w+)\");\n private static Pattern sUserNamePattern = Pattern.compile(\"/(u|user)/(\\\\w+)\");\n\n public static String appendPage(String baseUrl, int page) {\n return String.format(Locale.US, baseUrl.contains(\"?\") ? \"%s&p=%d\" : \"%s?p=%d\",\n baseUrl, page);\n }\n\n public static String getTid(String url) {\n Matcher m = sTidPattern.matcher(url);\n if (m.find()) {\n return m.group(1);\n } else {\n return null;\n }\n }\n\n public static String getNodeCode(String url) {\n Matcher m = sNodeCodePattern.matcher(url);\n if (m.find()) {\n return m.group(1);\n } else {\n return null;\n }\n }\n\n public static String getUserName(String url) {\n Matcher m = sUserNamePattern.matcher(url);\n if (m.find()) {\n return m.group(2);\n } else {\n return null;\n }\n }\n\n public static String removeQuery(String url) {\n if (!TextUtils.isEmpty(url)) {\n url = url.split(\"\\\\?\")[0];\n url = url.split(\"#\")[0];\n }\n return url;\n }\n\n public static String urlEncode(String content) {\n try {\n return URLEncoder.encode(content, \"utf-8\");\n } catch (UnsupportedEncodingException e) {\n e.printStackTrace();\n return content;\n }\n }\n}"
] | import org.mazhuang.guanggoo.data.NetworkTaskScheduler;
import org.mazhuang.guanggoo.data.OnResponseListener;
import org.mazhuang.guanggoo.data.entity.ListResult;
import org.mazhuang.guanggoo.data.entity.Topic;
import org.mazhuang.guanggoo.data.task.BaseTask;
import org.mazhuang.guanggoo.data.task.GetTopicListTask;
import org.mazhuang.guanggoo.util.ConstantUtil;
import org.mazhuang.guanggoo.util.UrlUtil;
import lombok.Setter; | package org.mazhuang.guanggoo.topiclist;
/**
*
* @author mazhuang
* @date 2017/9/16
*/
public class TopicListPresenter implements TopicListContract.Presenter {
private TopicListContract.View mView;
private BaseTask mCurrentTask;
private int mPagination;
public TopicListPresenter(TopicListContract.View view) {
mView = view;
view.setPresenter(this);
}
@Override
public void getTopicList() {
if (mCurrentTask != null) {
mCurrentTask.cancel();
}
mCurrentTask = new GetTopicListTask(mView.getUrl(), | new OnResponseListener<ListResult<Topic>>() { | 2 |
CROW-NDOV/displaydirect | distribution/src/main/java/nl/crowndov/displaydirect/distribution/kv78/RealtimeMessageMapper.java | [
"public class DeleteMessage extends RealtimeMessage implements Serializable {\n\n private static final long serialVersionUID = -4335030844531563517L;\n\n private final int messageCode;\n\n public DeleteMessage(String dataOwnerCode, LocalDate date, int messageCode, String stopCode) {\n super(Type.MESSAGE_DELETE, date, dataOwnerCode, stopCode);\n this.messageCode = messageCode;\n }\n\n public int getMessageCode() {\n return messageCode;\n }\n\n public Integer getMessageHash() {\n return String.format(\"%s|%s|%s\", getDataOwnerCode(), getDate().toString(), getMessageCode()).hashCode();\n }\n}",
"public class PassTime extends RealtimeMessage implements Serializable {\n\n private static final long serialVersionUID = 8458255587785977161L;\n\n private String linePlanningNumber;\n private Line line;\n private int journeyNumber;\n\n private int targetArrivalTime;\n private int targetDepartureTime;\n private int expectedArrivalTime;\n private int expectedDepartureTime;\n\n private int numberOfCoaches;\n private Status tripStopStatus = Status.PLANNED;\n private Boolean wheelchairAccessible;\n\n private String destinationCode;\n private Destination destination;\n private String sideCode;\n\n private int generatedTimestamp;\n private Boolean isTimingStop;\n private int lineDirection;\n\n public PassTime(String dataOwnerCode, LocalDate date, String linePlanningNumber, int journeyNumber, String stopCode) {\n super(Type.PASSTIME, date, dataOwnerCode, stopCode);\n this.linePlanningNumber = linePlanningNumber;\n this.journeyNumber = journeyNumber;\n }\n\n public String getLinePlanningNumber() {\n return linePlanningNumber;\n }\n\n public int getJourneyNumber() {\n return journeyNumber;\n }\n\n public void setTargetArrivalTime(int targetArrivalTime) {\n this.targetArrivalTime = targetArrivalTime;\n }\n\n public void setTargetDepartureTime(int targetDepartureTime) {\n this.targetDepartureTime = targetDepartureTime;\n }\n\n public void setExpectedArrivalTime(int expectedArrivalTime) {\n this.expectedArrivalTime = expectedArrivalTime;\n }\n\n public void setExpectedDepartureTime(int expectedDepartureTime) {\n this.expectedDepartureTime = expectedDepartureTime;\n }\n\n public void setNumberOfCoaches(int numberOfCoaches) {\n this.numberOfCoaches = numberOfCoaches;\n }\n\n public void setTripStopStatus(Status tripStopStatus) {\n this.tripStopStatus = tripStopStatus;\n }\n\n public void setWheelchairAccessible(Boolean wheelchairAccessible) {\n this.wheelchairAccessible = wheelchairAccessible;\n }\n\n public void setDestinationCode(String destinationCode) {\n this.destinationCode = destinationCode;\n }\n\n public void setSideCode(String sideCode) {\n this.sideCode = sideCode;\n }\n\n public int getTargetArrivalTime() {\n return targetArrivalTime;\n }\n\n public int getTargetDepartureTime() {\n return targetDepartureTime;\n }\n\n public int getExpectedArrivalTime() {\n return expectedArrivalTime;\n }\n\n public int getExpectedDepartureTime() {\n return expectedDepartureTime;\n }\n\n public int getNumberOfCoaches() {\n return numberOfCoaches;\n }\n\n public Status getTripStopStatus() {\n return tripStopStatus;\n }\n\n public Boolean getWheelchairAccessible() {\n return wheelchairAccessible;\n }\n\n public String getDestinationCode() {\n return destinationCode;\n }\n\n public String getSideCode() {\n return sideCode;\n }\n\n public Destination getDestination() {\n return destination;\n }\n\n public void setDestination(Destination destination) {\n this.destination = destination;\n }\n\n public Line getLine() {\n return line;\n }\n\n public void setLine(Line line) {\n this.line = line;\n }\n\n public String getPassTimeKey() {\n return String.format(\"%s|%s|%s|%s|%s\", getDataOwnerCode(), getDate(), linePlanningNumber, journeyNumber, getStopCode());\n }\n\n public int getPassTimeHash() {\n return getPassTimeKey().hashCode();\n }\n\n public void setGeneratedTimestamp(int generatedTimestamp) {\n this.generatedTimestamp = generatedTimestamp;\n }\n\n public int getGeneratedTimestamp() {\n return generatedTimestamp;\n }\n\n public Boolean getIsTimingStop() {\n return isTimingStop;\n }\n\n public int getLineDirection() {\n return lineDirection;\n }\n\n public void setTimingStop(Boolean timingStop) {\n isTimingStop = timingStop;\n }\n\n public void setLineDirection(int lineDirection) {\n this.lineDirection = lineDirection;\n }\n\n public enum Status {\n PLANNED,\n UNKNOWN,\n DRIVING,\n ARRIVED,\n PASSED,\n CANCEL\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n\n PassTime passTime = (PassTime) o;\n\n if (journeyNumber != passTime.journeyNumber) return false;\n if (targetArrivalTime != passTime.targetArrivalTime) return false;\n if (targetDepartureTime != passTime.targetDepartureTime) return false;\n if (expectedArrivalTime != passTime.expectedArrivalTime) return false;\n if (expectedDepartureTime != passTime.expectedDepartureTime) return false;\n if (numberOfCoaches != passTime.numberOfCoaches) return false;\n if (linePlanningNumber != null ? !linePlanningNumber.equals(passTime.linePlanningNumber) : passTime.linePlanningNumber != null)\n return false;\n if (tripStopStatus != passTime.tripStopStatus) return false;\n if (wheelchairAccessible != null ? !wheelchairAccessible.equals(passTime.wheelchairAccessible) : passTime.wheelchairAccessible != null)\n return false;\n if (destinationCode != null ? !destinationCode.equals(passTime.destinationCode) : passTime.destinationCode != null)\n return false;\n return sideCode != null ? sideCode.equals(passTime.sideCode) : passTime.sideCode == null;\n }\n\n @Override\n public int hashCode() {\n int result = linePlanningNumber != null ? linePlanningNumber.hashCode() : 0;\n result = 31 * result + journeyNumber;\n result = 31 * result + targetArrivalTime;\n result = 31 * result + targetDepartureTime;\n result = 31 * result + expectedArrivalTime;\n result = 31 * result + expectedDepartureTime;\n result = 31 * result + numberOfCoaches;\n result = 31 * result + (tripStopStatus != null ? tripStopStatus.hashCode() : 0);\n result = 31 * result + (wheelchairAccessible != null ? wheelchairAccessible.hashCode() : 0);\n result = 31 * result + (destinationCode != null ? destinationCode.hashCode() : 0);\n result = 31 * result + (sideCode != null ? sideCode.hashCode() : 0);\n return result;\n }\n}",
"public class RealtimeMessage implements Serializable {\n\n private static final long serialVersionUID = -8692508260190453615L;\n\n private Type type;\n private LocalDate date;\n private String dataOwnerCode;\n private String stopCode;\n\n private String quayCode;\n\n public RealtimeMessage() {\n }\n\n public RealtimeMessage(Type type, LocalDate date, String dataOwnerCode, String stopCode) {\n this.type = type;\n this.date = date;\n this.dataOwnerCode = dataOwnerCode;\n this.stopCode = stopCode;\n }\n\n public String getDataOwnerCode() {\n return dataOwnerCode;\n }\n\n public LocalDate getDate() {\n return date;\n }\n\n public Type getType() {\n return type;\n }\n\n public String getStopCode() {\n return stopCode;\n }\n\n public String getQuayCode() {\n return quayCode;\n }\n\n public void setQuayCode(String quayCode) {\n this.quayCode = quayCode;\n }\n\n public enum Type {\n PASSTIME,\n MESSAGE_UPDATE,\n MESSAGE_DELETE,\n }\n}",
"public class UpdateMessage extends RealtimeMessage implements Serializable {\n\n private static final long serialVersionUID = -3939110132456463688L;\n\n private final int messageCode;\n\n private String messageContent;\n private ZonedDateTime messageStart;\n private ZonedDateTime messageEnd;\n\n public UpdateMessage(String dataOwnerCode, LocalDate date, int messageCode, String stopCode) {\n super(Type.MESSAGE_UPDATE, date, dataOwnerCode, stopCode);\n this.messageCode = messageCode;\n }\n\n public Integer getMessageHash() {\n return String.format(\"%s|%s|%s\", getDataOwnerCode(), getDate().toString(), getMessageCode()).hashCode();\n }\n\n public int getMessageCode() {\n return messageCode;\n }\n\n public String getMessageContent() {\n return messageContent;\n }\n\n public ZonedDateTime getMessageStart() {\n return messageStart;\n }\n\n public ZonedDateTime getMessageEnd() {\n return messageEnd;\n }\n\n public void setMessageContent(String messageContent) {\n this.messageContent = messageContent;\n }\n\n public void setMessageStart(ZonedDateTime messageStart) {\n this.messageStart = messageStart;\n }\n\n public void setMessageEnd(ZonedDateTime messageEnd) {\n this.messageEnd = messageEnd;\n }\n}",
"public class TimingPointProvider extends AbstractService {\n\n private static final Store.TimingPointStore points = new Store.TimingPointStore();\n\n public static void start() {\n readFile(\"timing_points\", Store.TimingPointStore.class).ifPresent(points::putAll);\n }\n\n public static void stop() {\n backup();\n }\n\n public static void backup() {\n writeFile(\"timing_points\", points);\n }\n\n public static void updateTimingPoints(Map<String, String> input) {\n points.putAll(input);\n }\n\n public static Optional<String> getStopFromTimingPoint(String dataOwnerCode, String timingPointCode) {\n return Optional.ofNullable(points.getOrDefault(dataOwnerCode+\"|\"+timingPointCode, null));\n }\n\n public static Store.TimingPointStore getAll() {\n return points;\n }\n}",
"public class Kv78Packet {\n\n private String type;\n private String comment;\n private String encoding;\n private String version;\n private ZonedDateTime generated;\n\n private String sourceFile;\n\n private List<Kv78Table> tables = new ArrayList<>();\n\n public void setType(String type) {\n this.type = type;\n }\n\n public void setComment(String comment) {\n this.comment = comment;\n }\n\n public void setEncoding(String encoding) {\n this.encoding = encoding;\n }\n\n public void setVersion(String version) {\n this.version = version;\n }\n\n public void setGenerated(ZonedDateTime generated) {\n this.generated = generated;\n }\n\n public void addTable(Kv78Table table) {\n tables.add(table);\n }\n\n public List<Kv78Table> getTables() {\n return tables;\n }\n\n public String getType() {\n return type;\n }\n\n public String getComment() {\n return comment;\n }\n\n public String getEncoding() {\n return encoding;\n }\n\n public String getVersion() {\n return version;\n }\n\n public ZonedDateTime getGenerated() {\n return generated;\n }\n\n public String getSourceFile() {\n return sourceFile;\n }\n\n public void setSourceFile(String sourceFile) {\n this.sourceFile = sourceFile;\n }\n}",
"public class Kv78Table {\n\n private String tableName;\n private String tableComment;\n\n private List<Map<String, String>> records = new ArrayList<>();\n\n\n public void setTableName(String tableName) {\n this.tableName = tableName;\n }\n\n public void setTableComment(String tableComment) {\n this.tableComment = tableComment;\n }\n\n public void setRecords(List<Map<String, String>> records) {\n this.records = records;\n }\n\n public String getTableName() {\n return tableName;\n }\n\n public String getTableComment() {\n return tableComment;\n }\n\n public List<Map<String, String>> getRecords() {\n return records;\n }\n}",
"public class DateTimeUtil {\n\n public static ZonedDateTime getTime(LocalDate date, String time) {\n String[] split = time.split(\":\");\n int hour = Integer.valueOf(split[0]);\n boolean addDay = false;\n if (hour > 23) {\n hour = hour - 24;\n addDay = true;\n }\n ZonedDateTime dateTime = ZonedDateTime.of(date, LocalTime.of(hour, Integer.valueOf(split[1]), Integer.valueOf(split[2])), Configuration.getZoneId());\n if (addDay) {\n dateTime = dateTime.plusDays(1);\n }\n return dateTime;\n }\n\n public static long getMinutesTill(String time) {\n String[] split = time.split(\":\");\n return getMinutesTill(Integer.valueOf(split[0]), Integer.valueOf(split[1]));\n }\n\n public static long getMinutesTill(int hour) {\n return getMinutesTill(hour, 0);\n }\n\n public static long getMinutesTill(int hour, int min) {\n ZonedDateTime tomorrow = ZonedDateTime.now(Configuration.getZoneId()).plusDays(1).withHour(hour).withMinute(min);\n return ChronoUnit.MINUTES.between(ZonedDateTime.now(Configuration.getZoneId()), tomorrow);\n }\n}"
] | import nl.crowndov.displaydirect.distribution.domain.travelinfo.DeleteMessage;
import nl.crowndov.displaydirect.distribution.domain.travelinfo.PassTime;
import nl.crowndov.displaydirect.distribution.domain.travelinfo.RealtimeMessage;
import nl.crowndov.displaydirect.distribution.domain.travelinfo.UpdateMessage;
import nl.crowndov.displaydirect.distribution.input.TimingPointProvider;
import nl.crowndov.displaydirect.distribution.kv78.domain.Kv78Packet;
import nl.crowndov.displaydirect.distribution.kv78.domain.Kv78Table;
import nl.crowndov.displaydirect.distribution.util.DateTimeUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.time.LocalDate;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.BiFunction;
import java.util.stream.Collectors; | package nl.crowndov.displaydirect.distribution.kv78;
/**
* Copyright 2017 CROW-NDOV
*
* This file is subject to the terms and conditions defined in file 'LICENSE.txt', which is part of this source code package.
*/
public class RealtimeMessageMapper {
private static final Logger LOGGER = LoggerFactory.getLogger(RealtimeMessageMapper.class);
public static List<RealtimeMessage> toRealtimeMessage(Kv78Packet packet) {
if (packet.getTables().size() != 1) {
return new ArrayList<>();
}
Kv78Table t = packet.getTables().get(0);
if (t != null && t.getTableName() != null) {
switch (t.getTableName()) {
case "DATEDPASSTIME":
return handle(packet, t.getRecords(), RealtimeMessageMapper::passTime);
case "GENERALMESSAGEUPDATE":
LOGGER.info("Got general message update");
return handle(packet, t.getRecords(), RealtimeMessageMapper::updateMessage);
case "GENERALMESSAGEDELETE":
LOGGER.info("Got general message delete");
return handle(packet, t.getRecords(), RealtimeMessageMapper::deleteMessage);
default:
break;
}
}
return new ArrayList<>();
}
private static List<RealtimeMessage> handle(Kv78Packet packet, List<Map<String, String>> records, BiFunction<Kv78Packet, Map<String, String>, RealtimeMessage> f) {
return records.stream().map(r -> f.apply(packet, r)).collect(Collectors.toList());
}
public static RealtimeMessage passTime(Kv78Packet packet, Map<String, String> r) {
LocalDate date = LocalDate.parse(r.get("OperationDate"));
PassTime pt = new PassTime(r.get("DataOwnerCode"), date,
r.get("LinePlanningNumber"), Integer.valueOf(r.get("JourneyNumber")), r.get("UserStopCode")); | pt.setExpectedArrivalTime((int) DateTimeUtil.getTime(date, r.get("ExpectedArrivalTime")).toEpochSecond()); | 7 |
Aurilux/Cybernetica | src/main/java/com/vivalux/cyb/item/module/ModuleLexica.java | [
"@Mod(modid = CYBModInfo.MOD_ID,\n name = CYBModInfo.MOD_NAME,\n guiFactory = CYBModInfo.GUI_FACTORY,\n version = CYBModInfo.MOD_VERSION)\npublic class Cybernetica {\n\t@Instance(CYBModInfo.MOD_ID)\n\tpublic static Cybernetica instance;\n\n\t@SidedProxy(clientSide = CYBModInfo.CLIENT_PROXY, serverSide = CYBModInfo.SERVER_PROXY)\n\tpublic static CYBClientProxy proxy;\n\n /**\n * Run before anything else. Read your config, create blocks, items, etc\n */\n\t@EventHandler\n\tpublic void preInit(FMLPreInitializationEvent e) {\n //Config should be one of the first things you do\n FMLCommonHandler.instance().bus().register(new ConfigHandler(e.getSuggestedConfigurationFile()));\n\n //proxy.preInit();\n\n //Initialize mod-independent objects\n\t\tCYBBlocks.init();\n\t\tCYBItems.init();\n CYBAchievements.init();\n\n //PacketHandler.init();\n ChestGenHandler.init();\n\t}\n\n /**\n * Build whatever data structures you care about and register handlers, tile entities, renderers, and recipes\n */\n\t@EventHandler\n\tpublic void init(FMLInitializationEvent e) {\n //Register recipes here to ensure that all mod items and blocks, including those from other mods, are added\n CYBRecipes.init();\n\n proxy.init();\n\n //Minecraft Forge event handlers\n MinecraftForge.EVENT_BUS.register(new PlayerEventHandler());\n\n //FML event handlers\n FMLCommonHandler.instance().bus().register(new UpdateHandler());\n\n //Network handlers\n NetworkRegistry.INSTANCE.registerGuiHandler(Cybernetica.instance, new GuiHandler());\n\t}\n\n /**\n * Handle interaction with other mods, complete your setup based on this\n */\n\t@EventHandler\n\tpublic void postInit(FMLPostInitializationEvent e) {\n\n //proxy.postInit();\n\n //Inter-mod communications\n //Register the Waila data provider\n /*\n\t\tif (Loader.isModLoaded(\"Waila\")) {\n FMLInterModComms.sendMessage(\"Waila\", \"register\", \"\");\n }\n */\n\t}\n}",
"public enum ImplantType {\n HEAD, TORSO, LEG, FOOT\n}",
"public abstract class Module extends Item {\n /**\n * Which implants this module can be installed on. Will be a combination of the bits listed in ImplantType in the Implant class\n */\n private EnumSet<ImplantType> compatibles = EnumSet.noneOf(ImplantType.class);\n\n /**\n * The implant this module is installed on\n */\n //TODO do I even need this?\n public Implant chassis;\n\n @Override\n public int getItemStackLimit(ItemStack stack) {\n return 1;\n }\n\n @Override\n @SideOnly(Side.CLIENT)\n public void registerIcons(IIconRegister reg) {\n this.itemIcon = reg.registerIcon(MiscUtils.getTexturePath(this.iconString));\n }\n\n @Override\n public String getUnlocalizedName() {\n return \"module.\" + this.getCoreUnlocalizedName(super.getUnlocalizedName());\n }\n\n @Override\n public String getUnlocalizedName(ItemStack stack) {\n return \"module.\" + this.getCoreUnlocalizedName(super.getUnlocalizedName());\n }\n\n /**\n * Trims the prefix identifier from the default getUnlocalizedName() (\"item.\") so we can add our own\n * @param unlocalizedName the unlocalized name\n * @return the trimmed string\n */\n protected String getCoreUnlocalizedName(String unlocalizedName) {\n return unlocalizedName.substring(unlocalizedName.indexOf(\".\") + 1);\n }\n\n public void setCompatibles(EnumSet<ImplantType> types) {\n this.compatibles = types;\n }\n\n public EnumSet<ImplantType> getCompatibles() {\n return this.compatibles;\n }\n\n /**\n * Adds text to the ItemStack's tooltip\n * @param stack the ItemStack of this item\n * @param player the player looking at the stack\n * @param list a list of strings to display in the tooltips. Each entry is it's own line\n * @param advancedTooltips if true, display advanced information in the tooltip. Probably for debugging.\n */\n @Override\n public void addInformation(ItemStack stack, EntityPlayer player, List list, boolean advancedTooltips) {\n String applicableImplants = \"\";\n if (this.compatibles == EnumSet.allOf(ImplantType.class)) {\n applicableImplants = StatCollector.translateToLocal(\"tooltip.module.all\");\n }\n else {\n for (ImplantType type : ImplantType.values()) {\n if (this.isCompatible(type)) {\n if (applicableImplants != \"\") {\n applicableImplants += \", \";\n }\n applicableImplants += StatCollector.translateToLocal(\"tooltip.module.\" + type.name().toLowerCase());\n }\n }\n }\n String info = EnumChatFormatting.GREEN + \"Compatible with: \" + applicableImplants;\n list.add(info);\n }\n\n /**\n * Determines if the module is compatible with the armorType of the given implant\n * @param type the implantType (armorType) to test against\n * @return true if this module is compatible with the implant\n */\n public boolean isCompatible(ImplantType type) {\n return this.compatibles.contains(type);\n }\n}",
"public class GuiHandler implements IGuiHandler {\n public static final int GUI_ID_INTEG = 0;\n public static final int GUI_ID_LEXICON = 1;\n\n @Override\n\tpublic Object getServerGuiElement(int id, EntityPlayer player, World world, int x, int y, int z) {\n switch (id) {\n case GUI_ID_INTEG:\n TileEntityIntegrationTable tileEntityIntegTable = (TileEntityIntegrationTable) world.getTileEntity(x, y, z);\n if (tileEntityIntegTable != null) {\n return new ContainerIntegrationTable(world, player.inventory, tileEntityIntegTable);\n }\n break;\n }\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic Object getClientGuiElement(int id, EntityPlayer player, World world, int x, int y, int z) {\n switch (id) {\n case GUI_ID_INTEG:\n TileEntityIntegrationTable tileEntityIntegTable = (TileEntityIntegrationTable) world.getTileEntity(x, y, z);\n if (tileEntityIntegTable != null) {\n return new GuiIntegrationTable(world, player.inventory, tileEntityIntegTable);\n }\n break;\n case GUI_ID_LEXICON: return new GuiLexica();\n }\n\t\treturn null;\n\t}\n}",
"public class CYBItems {\n public static Item circuit, component, relay;\n public static Item implantEye, implantArm, implantLeg;\n public static Item moduleLexica, moduleActuator;\n public static Item moduleNightvision;\n public static Item moduleBlastResist, moduleProjectileResist, moduleFireResist, moduleArmorPlate;\n\n public static void init() {\n //Materials\n circuit = new Circuit(\"circuit\", \"Circuit\");\n //component = new Component(\"component\", \"Component\");\n //relay = new Relay(\"relay\", \"Relay\");\n\n //Implants\n implantEye = new ImplantCyberneticEye(\"eyeImplant\", \"CyberneticEye\", 1);\n implantArm = new ImplantCyberneticArm(\"armImplant\", \"CyberneticArm\", 1);\n //legImplant = new ImplantCyberneticLeg(\"legImplant\", \"Cybernetic Leg\", 0, 2);\n\n //Modules\n //moduleActuator = new ModuleActuator(\"moduleActuator\", \"Actuator Module\");\n moduleLexica = new ModuleLexica(\"moduleLexica\", \"LexicaCybernetica\");\n\n moduleNightvision = new ModuleNightvision(\"moduleNightvision\", \"NightVisionModule\");\n\n moduleBlastResist = new ModuleBlastResist(\"moduleBlastResist\", \"BlastResistanceModule\");\n moduleFireResist = new ModuleFireResist(\"moduleFireResist\", \"FireResistanceModule\");\n moduleProjectileResist = new ModuleProjectileResist(\"moduleProjectileResist\", \"ProjectileResistanceModule\");\n moduleArmorPlate = new ModuleArmorPlate(\"moduleArmorPlate\", \"ArmorPlateModule\");\n\n }\n\n\t//A helper method called by each item's constructor\n\tpublic static void setItem(Item item, String str, String str2) {\n\t\titem.setUnlocalizedName(str);\n\t\titem.setTextureName(str);\n\t\titem.setCreativeTab(CYBMisc.tab);\n\t\tGameRegistry.registerItem(item, str2, CYBModInfo.MOD_ID);\n\t}\n}"
] | import com.vivalux.cyb.Cybernetica;
import com.vivalux.cyb.api.Implant.ImplantType;
import com.vivalux.cyb.api.Module;
import com.vivalux.cyb.handler.GuiHandler;
import com.vivalux.cyb.init.CYBItems;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import java.util.EnumSet; | package com.vivalux.cyb.item.module;
public class ModuleLexica extends Module {
public ModuleLexica(String str, String str2) {
CYBItems.setItem(this, str, str2); | this.setCompatibles(EnumSet.of(ImplantType.TORSO)); | 1 |
AstartesGuardian/WebDAV-Server | WebDAV-Server/src/webdav/server/virtual/contentmutation/CryptedContentMutation.java | [
"public class HTTPEnvRequest\r\n{\r\n public static Builder create()\r\n {\r\n return new Builder();\r\n }\r\n public static class Builder\r\n {\r\n public Builder()\r\n { }\r\n \r\n private HTTPRequest request;\r\n private HTTPCommand command;\r\n private HTTPServerSettings settings;\r\n private Collection<IResourceMutation> mutations = null;\r\n private byte[] bytesReceived = null;\r\n \r\n public Builder setRequest(HTTPRequest request)\r\n {\r\n this.request = request;\r\n return this;\r\n }\r\n \r\n public Builder setCommand(HTTPCommand command)\r\n {\r\n this.command = command;\r\n return this;\r\n }\r\n \r\n public Builder setBytesReceived(byte[] bytesReceived)\r\n {\r\n this.bytesReceived = bytesReceived;\r\n return this;\r\n }\r\n \r\n public Builder setSettings(HTTPServerSettings settings)\r\n {\r\n this.settings = settings;\r\n return this;\r\n }\r\n \r\n public Builder setMutations(Collection<IResourceMutation> mutations)\r\n {\r\n this.mutations = mutations;\r\n return this;\r\n }\r\n public Builder addMutations(IResourceMutation[] mutations)\r\n {\r\n this.mutations.addAll(Arrays.asList(mutations));\r\n return this;\r\n }\r\n public Builder addMutations(Collection<IResourceMutation> mutations)\r\n {\r\n this.mutations.addAll(mutations);\r\n return this;\r\n }\r\n public Builder addMutation(IResourceMutation mutation)\r\n {\r\n this.mutations.add(mutation);\r\n return this;\r\n }\r\n \r\n public HTTPEnvRequest build()\r\n {\r\n if(mutations == null)\r\n mutations = Collections.EMPTY_LIST;\r\n \r\n return new HTTPEnvRequest(\r\n bytesReceived,\r\n request,\r\n command,\r\n settings.getAuthenticationManager().checkAuth(request),\r\n settings,\r\n settings.getFileManager().getResourceMutations());\r\n }\r\n }\r\n \r\n public HTTPEnvRequest(\r\n byte[] bytesReceived,\r\n HTTPRequest request,\r\n HTTPCommand command,\r\n HTTPUser user,\r\n HTTPServerSettings settings,\r\n Collection<IResourceMutation> mutations)\r\n {\r\n this.bytesReceived = bytesReceived;\r\n this.request = request;\r\n this.command = command;\r\n this.user = user;\r\n this.settings = settings;\r\n this.mutations = mutations;\r\n }\r\n \r\n private byte[] bytesReceived;\r\n private FileSystemPath path = null;\r\n \r\n private final HTTPRequest request;\r\n private final HTTPCommand command;\r\n private final HTTPUser user;\r\n private final HTTPServerSettings settings;\r\n private final Collection<IResourceMutation> mutations;\r\n \r\n public FileSystemPath getPath()\r\n {\r\n if(path == null)\r\n path = settings.getFileSystemPathManager()\r\n .createFromString(request.getDecodedPath());\r\n \r\n return path;\r\n }\r\n \r\n public Collection<IResourceMutation> getMutations()\r\n {\r\n return mutations;\r\n }\r\n \r\n public byte[] getBytesReceived()\r\n {\r\n if(bytesReceived == null)\r\n bytesReceived = request.toBytes();\r\n return bytesReceived;\r\n }\r\n \r\n public HTTPRequest getRequest()\r\n {\r\n return request;\r\n }\r\n \r\n public HTTPCommand getCommand()\r\n {\r\n return command;\r\n }\r\n \r\n public HTTPUser getUser()\r\n {\r\n return user;\r\n }\r\n \r\n public HTTPServerSettings getSettings()\r\n {\r\n return settings;\r\n }\r\n}\r",
"public class Helper \r\n{\r\n private Helper()\r\n { }\r\n \r\n public static String toString(Date date)\r\n {\r\n return new SimpleDateFormat(\"EEE, dd MMM YYYY HH:mm:ss\", Locale.ENGLISH).format(date).replace(\".\", \"\") + \" GMT\";\r\n }\r\n \r\n public static String toUTF8(String str)\r\n {\r\n try\r\n {\r\n return URLEncoder.encode(str, \"UTF-8\").replace(\"%2F\", \"/\").replace(\"+\", \" \");\r\n }\r\n catch (UnsupportedEncodingException ex)\r\n {\r\n return str;\r\n }\r\n }\r\n \r\n public static String toBase10(String base64)\r\n {\r\n return new String(DatatypeConverter.parseBase64Binary(base64.trim().substring(\"Basic \".length()).trim()));\r\n }\r\n \r\n public static String toHex(byte[] data)\r\n {\r\n BigInteger bigInt = new BigInteger(1, data);\r\n String value = bigInt.toString(16);\r\n \r\n while(value.length() < 32)\r\n value = \"0\" + value;\r\n \r\n return value;\r\n }\r\n}\r",
"public class CipherCrypter extends AbstractCrypter\r\n{\r\n public CipherCrypter(Algorithm algo) throws NoSuchAlgorithmException, NoSuchPaddingException\r\n {\r\n this(algo.getAlgoName(), algo.getTransformationName(), algo.getKeySize());\r\n }\r\n public CipherCrypter(String algoName, String transformationName, int keySize) throws NoSuchAlgorithmException, NoSuchPaddingException\r\n {\r\n this.cipher = Cipher.getInstance(algoName);\r\n this.keySize = keySize;\r\n this.algoName = algoName;\r\n }\r\n \r\n private SecretKey key;\r\n private final Cipher cipher;\r\n private final int keySize;\r\n private final String algoName;\r\n \r\n private byte[] formatSecret(String secret)\r\n {\r\n byte[] hash;\r\n try\r\n {\r\n hash = sha256(secret);\r\n }\r\n catch (NoSuchAlgorithmException ex)\r\n { // use another hashing method\r\n hash = null;\r\n }\r\n \r\n return Arrays.copyOf(hash, keySize);\r\n }\r\n \r\n @Override\r\n public void setKey(String secret)\r\n {\r\n key = new SecretKeySpec(formatSecret(secret), algoName);\r\n }\r\n\r\n protected SecretKey getTemporaryKey(byte[] keyAddition)\r\n {\r\n if(keyAddition.length == 0)\r\n return key;\r\n \r\n byte[] encodedKey = key.getEncoded();\r\n for(int i = 0; i < keyAddition.length; i++)\r\n {\r\n encodedKey[i] += keyAddition[(i - encodedKey[i] + Byte.MAX_VALUE) % keyAddition.length];\r\n }\r\n return new SecretKeySpec(encodedKey, algoName);\r\n }\r\n\r\n @Override\r\n public synchronized byte[] encrypt(byte[] data, byte[] keyAddition) throws Exception\r\n {\r\n cipher.init(Cipher.ENCRYPT_MODE, getTemporaryKey(keyAddition));\r\n byte[] cryptedData = cipher.doFinal(data);\r\n return Base64.getEncoder().encode(cryptedData);\r\n }\r\n\r\n @Override\r\n public synchronized byte[] decrypt(byte[] cryptedData, byte[] keyAddition) throws Exception\r\n {\r\n byte[] data64 = Base64.getDecoder().decode(cryptedData);\r\n cipher.init(Cipher.DECRYPT_MODE, getTemporaryKey(keyAddition));\r\n return cipher.doFinal(data64);\r\n }\r\n}\r",
"public abstract class AbstractCrypter implements ICrypter\r\n{\r\n public enum Algorithm\r\n {\r\n AES_CBC_NoPadding(\"AES\", \"AES/CBC/NoPadding\", 128/8),\r\n AES_CBC_PKCS5Padding(\"AES\", \"AES/CBC/PKCS5Padding\", 128/8),\r\n AES_ECB_NoPadding(\"AES\", \"AES/ECB/NoPadding\", 128/8),\r\n AES_ECB_PKCS5Padding(\"AES\", \"AES/ECB/PKCS5Padding\", 128/8),\r\n DES_CBC_NoPadding(\"DES\", \"DES/CBC/NoPadding\", 56/8),\r\n DES_CBC_PKCS5Padding(\"DES\", \"DES/CBC/PKCS5Padding\", 56/8),\r\n DES_ECB_NoPadding(\"DES\", \"DES/ECB/NoPadding\", 56/8),\r\n DES_ECB_PKCS5Padding(\"DES\", \"DES/ECB/PKCS5Padding\", 56/8),\r\n DESede_CBC_NoPadding(\"DESede\", \"DESede/CBC/NoPadding\", 168/8),\r\n DESede_CBC_PKCS5Padding(\"DESede\", \"DESede/CBC/PKCS5Padding\", 168/8),\r\n DESede_ECB_NoPadding(\"DESede\", \"DESede/ECB/NoPadding\", 168/8),\r\n DESede_ECB_PKCS5Padding(\"DESede\", \"DESede/ECB/PKCS5Padding\", 168/8);\r\n \r\n private final String algoName;\r\n private final String transformationName;\r\n private final int keySize;\r\n Algorithm(String algoName, String transformationName, int keySize)\r\n {\r\n this.algoName = algoName;\r\n this.transformationName = transformationName;\r\n this.keySize = keySize;\r\n }\r\n \r\n public String getAlgoName()\r\n {\r\n return this.algoName;\r\n }\r\n public String getTransformationName()\r\n {\r\n return this.transformationName;\r\n }\r\n public int getKeySize()\r\n {\r\n return this.keySize;\r\n }\r\n }\r\n \r\n public static byte[] md5(String str) throws NoSuchAlgorithmException\r\n {\r\n try\r\n {\r\n return md5(str.getBytes(\"UTF-8\"));\r\n }\r\n catch (UnsupportedEncodingException ex)\r\n {\r\n return null;\r\n }\r\n }\r\n public static byte[] md5(byte[] data) throws NoSuchAlgorithmException\r\n {\r\n MessageDigest md = MessageDigest.getInstance(\"MD5\");\r\n //md.update(data);\r\n return md.digest(data);\r\n }\r\n public static byte[] sha256(String str) throws NoSuchAlgorithmException\r\n {\r\n try\r\n {\r\n return sha256(str.getBytes(\"UTF-8\"));\r\n }\r\n catch (UnsupportedEncodingException ex)\r\n {\r\n return null;\r\n }\r\n }\r\n public static byte[] sha256(byte[] data) throws NoSuchAlgorithmException\r\n {\r\n MessageDigest md = MessageDigest.getInstance(\"SHA-256\");\r\n md.update(data);\r\n return md.digest();\r\n }\r\n}\r",
"public interface IResource\r\n{\r\n /**\r\n * Get if the resource is visible.\r\n * \r\n * @param env\r\n * @return boolean\r\n * @throws http.server.exceptions.UserRequiredException\r\n */\r\n public boolean isVisible(HTTPEnvRequest env) throws UserRequiredException;\r\n \r\n /**\r\n * Get the type of the resource.\r\n * \r\n * @param env\r\n * @return ResourceType\r\n * @throws http.server.exceptions.UserRequiredException\r\n */\r\n public ResourceType getResourceType(HTTPEnvRequest env) throws UserRequiredException;\r\n \r\n /**\r\n * Get the web name of the resource.\r\n * \r\n * @param env\r\n * @return String\r\n * @throws http.server.exceptions.UserRequiredException\r\n */\r\n public String getWebName(HTTPEnvRequest env) throws UserRequiredException;\r\n /**\r\n * Get the resource name.\r\n * \r\n * @param env\r\n * @return String\r\n * @throws http.server.exceptions.UserRequiredException\r\n */\r\n //public FileSystemPath getPath(HTTPEnvRequest env) throws UserRequiredException;\r\n \r\n /**\r\n * Get the mime type of the resource.\r\n * \r\n * @param env\r\n * @return String\r\n * @throws http.server.exceptions.UserRequiredException\r\n */\r\n public String getMimeType(HTTPEnvRequest env) throws UserRequiredException;\r\n /**\r\n * Get the size of the resource (byte).\r\n * \r\n * @param env\r\n * @return long\r\n * @throws http.server.exceptions.UserRequiredException\r\n */\r\n public long getSize(HTTPEnvRequest env) throws UserRequiredException;\r\n /**\r\n * Get the creation time.\r\n * \r\n * @param env\r\n * @return Instant\r\n * @throws http.server.exceptions.UserRequiredException\r\n */\r\n public Instant getCreationTime(HTTPEnvRequest env) throws UserRequiredException;\r\n /**\r\n * Get the last modified date.\r\n * \r\n * @param env\r\n * @return Instant\r\n * @throws http.server.exceptions.UserRequiredException\r\n */\r\n public Instant getLastModified(HTTPEnvRequest env) throws UserRequiredException;\r\n /**\r\n * Get the list of the resources contained in this resource.\r\n * \r\n * @param env\r\n * @return Collection of IResource\r\n * @throws http.server.exceptions.UserRequiredException\r\n */\r\n public Collection<IResource> listResources(HTTPEnvRequest env) throws UserRequiredException;\r\n \r\n /**\r\n * Get the content of the resource.\r\n * \r\n * @param env\r\n * @return byte[]\r\n * @throws http.server.exceptions.UserRequiredException\r\n */\r\n public byte[] getContent(HTTPEnvRequest env) throws UserRequiredException;\r\n /**\r\n * Set the content of the resource.\r\n * \r\n * @param content Content to put in the resource\r\n * @param env\r\n * @throws http.server.exceptions.UserRequiredException\r\n */\r\n public void setContent(byte[] content, HTTPEnvRequest env) throws UserRequiredException;\r\n /**\r\n * Append a content to the resource.\r\n * \r\n * @param content Content to append in the resource\r\n * @param env\r\n * @throws http.server.exceptions.UserRequiredException\r\n */\r\n public void appendContent(byte[] content, HTTPEnvRequest env) throws UserRequiredException;\r\n \r\n /**\r\n * Delete the resource.\r\n * \r\n * @param env\r\n * @return boolean\r\n * @throws http.server.exceptions.UserRequiredException\r\n */\r\n public boolean delete(HTTPEnvRequest env) throws UserRequiredException;\r\n /**\r\n * Rename or move a resource from the current path to 'resource' path.\r\n * \r\n * @param newPath\r\n * @param env\r\n * @return boolean\r\n * @throws http.server.exceptions.UserRequiredException\r\n */\r\n public boolean moveTo(FileSystemPath oldPath, FileSystemPath newPath, HTTPEnvRequest env) throws UserRequiredException;\r\n \r\n public boolean rename(String newName, HTTPEnvRequest env) throws UserRequiredException;\r\n \r\n /**\r\n * Define if the resource exists or not.\r\n * \r\n * @param env\r\n * @return boolean\r\n * @throws UserRequiredException \r\n */\r\n public boolean exists(HTTPEnvRequest env) throws UserRequiredException;\r\n \r\n public IResource creates(ResourceType resourceType, HTTPEnvRequest env) throws UserRequiredException;\r\n public IResource creates(IResource resource, HTTPEnvRequest env) throws UserRequiredException;\r\n \r\n public boolean isOnTheSameFileSystemWith(IResource resource);\r\n \r\n public IResource getResource(LinkedList<FileSystemPath> reversedPath, HTTPEnvRequest env) throws UserRequiredException;\r\n \r\n \r\n public boolean equals(FileSystemPath path, HTTPEnvRequest env);\r\n \r\n \r\n public boolean addChild(IResource resource, HTTPEnvRequest env);\r\n public boolean removeChild(IResource resource, HTTPEnvRequest env);\r\n \r\n public boolean isInstanceOf(Class<?> c);\r\n \r\n \r\n \r\n // <editor-fold defaultstate=\"collapsed\" desc=\"Properties\">\r\n public void setProperty(String namespace, String name, String value, HTTPEnvRequest env) throws UserRequiredException;\r\n public void removeProperty(String name, HTTPEnvRequest env) throws UserRequiredException;\r\n public void removeProperty(String namespace, String name, HTTPEnvRequest env) throws UserRequiredException;\r\n public String getProperty(String name, HTTPEnvRequest env) throws UserRequiredException;\r\n public String getProperty(String namespace, String name, HTTPEnvRequest env) throws UserRequiredException;\r\n public Map<Pair<String, String>, String> getProperties(HTTPEnvRequest env) throws UserRequiredException;\r\n // </editor-fold>\r\n \r\n // <editor-fold defaultstate=\"collapsed\" desc=\"Locks\">\r\n public Collection<LockKind> getAvailableLocks() throws UserRequiredException;\r\n public List<Lock> getLocks(HTTPEnvRequest env) throws UserRequiredException;\r\n public List<Lock> getLocks(LockKind lockKind, HTTPEnvRequest env) throws UserRequiredException;\r\n public boolean setLock(Lock lock, HTTPEnvRequest env) throws UserRequiredException;\r\n public boolean setLock(LockKind lockKind, HTTPEnvRequest env) throws UserRequiredException;\r\n public void removeLock(Lock lock, HTTPEnvRequest env) throws UserRequiredException;\r\n public void removeLock(String uuid, HTTPEnvRequest env) throws UserRequiredException;\r\n public boolean canLock(LockKind lockKind, HTTPEnvRequest env) throws UserRequiredException;\r\n // </editor-fold>\r\n}\r"
] | import http.server.message.HTTPEnvRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.function.BiFunction;
import webdav.server.tools.Helper;
import webdav.server.crypter.CipherCrypter;
import webdav.server.crypter.AbstractCrypter;
import webdav.server.resource.IResource;
| package webdav.server.virtual.contentmutation;
public class CryptedContentMutation implements IContentMutation
{
public CryptedContentMutation(
AbstractCrypter.Algorithm algo,
String username,
String password,
| BiFunction<IResource, HTTPEnvRequest, byte[]> keyAdditionSupplier) throws Exception
| 0 |
IceReaper/DesktopAdventuresToolkit | src/net/eiveo/original/sections/todo/not_converted_yet/ZONE.java | [
"public class IZON {\r\n\tpublic short width;\r\n\tpublic short height;\r\n\tpublic short type;\r\n\tpublic short[] tiles;\r\n\tpublic Short world;\r\n\t\r\n\tpublic static IZON read(SmartByteBuffer data, boolean isYoda, short world) throws Exception {\r\n\t\tIZON instance = new IZON();\r\n\r\n\t\t// Somehow IZON includes identifier and the length int into the length.\r\n\t\tint length = data.getInt() - 8;\r\n\t\tint lengthStart = data.position();\r\n\r\n\t\tinstance.width = data.getShort();\r\n\t\tinstance.height = data.getShort();\r\n\t\tinstance.type = data.getShort();\r\n\t\tdata.getShort(); // 0\r\n\t\t\r\n\t\tif (isYoda) {\r\n\t\t\tdata.getShort(); // -1\r\n\t\t\tinstance.world = data.getShort();\r\n\t\t\t\r\n\t\t\tif (instance.world != world) {\r\n\t\t\t\tthrow new Exception(\"mapGroup mismatch.\");\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tinstance.tiles = new short[instance.width * instance.height * 3];\r\n\t\t\r\n\t\tfor (int i = 0; i < instance.tiles.length; i++) {\r\n\t\t\tinstance.tiles[i] = data.getShort();\r\n\t\t}\r\n\r\n\t\tif (lengthStart + length != data.position()) {\r\n\t\t\tthrow new Exception(\"Length mismatch.\");\r\n\t\t}\r\n\t\t\r\n\t\treturn instance;\r\n\t}\r\n\r\n\tpublic void write(SmartByteArrayOutputStream outputStream, boolean isYoda) {\r\n\t\toutputStream.write(\"IZON\");\r\n\t\toutputStream.sectionStart();\r\n\r\n\t\toutputStream.write(this.width);\r\n\t\toutputStream.write(this.height);\r\n\t\toutputStream.write(this.type);\r\n\t\toutputStream.write((short) 0);\r\n\t\t\r\n\t\tif (isYoda) {\r\n\t\t\toutputStream.write((short) -1);\r\n\t\t\toutputStream.write(this.world);\r\n\t\t}\r\n\t\t\r\n\t\tfor (short tile : this.tiles) {\r\n\t\t\toutputStream.write(tile);\r\n\t\t}\r\n\t\t\r\n\t\tbyte[] section = outputStream.sectionEnd();\r\n\t\t// Somehow IZON includes identifier and the length int into the length.\r\n\t\toutputStream.write(section.length + 8);\r\n\t\toutputStream.write(section);\r\n\t}\r\n}\r",
"public class IACT {\r\n\tprivate List<Condition> conditions = new ArrayList<>();\r\n\tprivate List<Action> actions = new ArrayList<>();\r\n\r\n\tpublic static IACT read(SmartByteBuffer data, boolean isYoda) throws Exception {\r\n\t\tIACT instance = new IACT();\r\n\t\t// TODO: https://github.com/cyco/DeskFun/blob/master/dfengine/include/Action.hpp\r\n\t\t// https://github.com/a-kr/jsyoda/blob/master/yodesk_decompiler/GenView/Script.cs\r\n\r\n\t\tint length = data.getInt();\r\n\t\tint lengthStart = data.position();\r\n\r\n\t\tshort amount = data.getShort();\r\n\t\t\r\n\t\tfor (int i = 0; i < amount; i++) {\r\n\t\t\tinstance.conditions.add(Condition.read(data));\r\n\t\t}\r\n\r\n\t\tamount = data.getShort();\r\n\t\t\r\n\t\tfor (int i = 0; i < amount; i++) {\r\n\t\t\tinstance.actions.add(Action.read(data));\r\n\t\t}\r\n\r\n\t\tif (isYoda && lengthStart + length != data.position()) {\r\n\t\t\tthrow new Exception(\"Length mismatch.\");\r\n\t\t}\r\n\t\t\r\n\t\treturn instance;\r\n\t}\r\n\r\n\tpublic void write(SmartByteArrayOutputStream outputStream, boolean isYoda) {\r\n\t\toutputStream.write(\"IACT\");\r\n\t\toutputStream.sectionStart();\r\n\r\n\t\toutputStream.write((short) this.conditions.size());\r\n\t\t\r\n\t\tfor (Condition condition : this.conditions) {\r\n\t\t\tcondition.write(outputStream);\r\n\t\t}\r\n\r\n\t\toutputStream.write((short) this.actions.size());\r\n\t\t\r\n\t\tfor (Action action : this.actions) {\r\n\t\t\taction.write(outputStream);\r\n\t\t}\r\n\r\n\t\tbyte[] section = outputStream.sectionEnd();\r\n\t\toutputStream.write(isYoda ? section.length : 0);\r\n\t\toutputStream.write(section);\r\n\t}\r\n\t\r\n\tpublic static class Condition {\r\n\t\tprivate short unk1;\r\n\t\tprivate short unk2;\r\n\t\tprivate short unk3;\r\n\t\tprivate short unk4;\r\n\t\tprivate short unk5;\r\n\t\tprivate short unk6;\r\n\t\tprivate String string;\r\n\t\t\r\n\t\tpublic static Condition read(SmartByteBuffer data) {\r\n\t\t\tCondition instance = new Condition();\r\n\r\n\t\t\tinstance.unk1 = data.getShort(); // TODO type\r\n\t\t\tinstance.unk2 = data.getShort(); // TODO x\r\n\t\t\tinstance.unk3 = data.getShort(); // TODO y\r\n\t\t\tinstance.unk4 = data.getShort(); // TODO data\r\n\t\t\tinstance.unk5 = data.getShort(); // TODO data\r\n\t\t\tinstance.unk6 = data.getShort(); // TODO data\r\n\t\t\t\r\n\t\t\tshort stringLength = data.getShort();\r\n\t\t\tinstance.string = data.getString(-1, stringLength);\r\n\r\n\t\t\treturn instance;\r\n\t\t}\r\n\r\n\t\tpublic void write(SmartByteArrayOutputStream outputStream) {\r\n\t\t\toutputStream.write(this.unk1);\r\n\t\t\toutputStream.write(this.unk2);\r\n\t\t\toutputStream.write(this.unk3);\r\n\t\t\toutputStream.write(this.unk4);\r\n\t\t\toutputStream.write(this.unk5);\r\n\t\t\toutputStream.write(this.unk6);\r\n\t\t\toutputStream.write((short) this.string.length());\r\n\t\t\toutputStream.write(this.string);\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic static class Action {\r\n\t\tprivate short unk1;\r\n\t\tprivate short unk2;\r\n\t\tprivate short unk3;\r\n\t\tprivate short unk4;\r\n\t\tprivate short unk5;\r\n\t\tprivate short unk6;\r\n\t\tprivate String string;\r\n\t\t\r\n\t\tpublic static Action read(SmartByteBuffer data) {\r\n\t\t\tAction instance = new Action();\r\n\t\t\t\r\n\t\t\tinstance.unk1 = data.getShort(); // TODO type\r\n\t\t\tinstance.unk2 = data.getShort(); // TODO x\r\n\t\t\tinstance.unk3 = data.getShort(); // TODO y\r\n\t\t\tinstance.unk4 = data.getShort(); // TODO data\r\n\t\t\tinstance.unk5 = data.getShort(); // TODO data\r\n\t\t\tinstance.unk6 = data.getShort(); // TODO data\r\n\t\t\t\r\n\t\t\tshort stringLength = data.getShort();\r\n\t\t\tinstance.string = data.getString(-1, stringLength);\r\n\r\n\t\t\treturn instance;\r\n\t\t}\r\n\r\n\t\tpublic void write(SmartByteArrayOutputStream outputStream) {\r\n\t\t\toutputStream.write(this.unk1);\r\n\t\t\toutputStream.write(this.unk2);\r\n\t\t\toutputStream.write(this.unk3);\r\n\t\t\toutputStream.write(this.unk4);\r\n\t\t\toutputStream.write(this.unk5);\r\n\t\t\toutputStream.write(this.unk6);\r\n\t\t\toutputStream.write((short) this.string.length());\r\n\t\t\toutputStream.write(this.string);\r\n\t\t}\r\n\t}\r\n}\r",
"public class IZAX {\r\n\tprivate short unk1;\r\n\tprivate List<Character> characters = new ArrayList<>();\r\n\tprivate List<Short> tileId1 = new ArrayList<>();\r\n\tprivate List<Short> tileId2 = new ArrayList<>();\r\n\r\n\tpublic static IZAX read(SmartByteBuffer data, boolean isYoda) throws Exception {\r\n\t\tIZAX instance = new IZAX();\r\n\t\t\r\n\t\t// Somehow IZAX includes identifier and the length int into the length.\r\n\t\tint length = data.getInt() - 8;\r\n\t\tint lengthStart = data.position();\r\n\t\t\r\n\t\tinstance.unk1 = data.getShort(); // TODO 0 or 1\r\n\t\t\r\n\t\tshort amount = data.getShort();\r\n\t\t\r\n\t\tfor (int j = 0; j < amount; j++) {\r\n\t\t\tinstance.characters.add(Character.read(data, isYoda));\r\n\t\t}\r\n\t\t\r\n\t\tamount = data.getShort();\r\n\t\t\r\n\t\tfor (int j = 0; j < amount; j++) {\r\n\t\t\tinstance.tileId1.add(data.getShort());\r\n\t\t}\r\n\t\t\r\n\t\tif (isYoda) {\r\n\t\t\tamount = data.getShort();\r\n\t\t\t\r\n\t\t\tfor (int j = 0; j < amount; j++) {\r\n\t\t\t\tinstance.tileId2.add(data.getShort());\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif (lengthStart + length != data.position()) {\r\n\t\t\tthrow new Exception(\"Length mismatch.\");\r\n\t\t}\r\n\t\t\r\n\t\treturn instance;\r\n\t}\r\n\r\n\tpublic void write(SmartByteArrayOutputStream outputStream, boolean isYoda) {\r\n\t\toutputStream.write(\"IZAX\");\r\n\t\toutputStream.sectionStart();\r\n\r\n\t\toutputStream.write(this.unk1);\r\n\t\toutputStream.write((short) this.characters.size());\r\n\t\t\r\n\t\tfor (Character character : this.characters) {\r\n\t\t\tcharacter.write(outputStream, isYoda);\r\n\t\t}\r\n\r\n\t\toutputStream.write((short) this.tileId1.size());\r\n\t\t\r\n\t\tfor (short tileId1 : this.tileId1) {\r\n\t\t\toutputStream.write(tileId1);\r\n\t\t}\r\n\t\t\r\n\t\tif (isYoda) {\r\n\r\n\t\t\toutputStream.write((short) this.tileId2.size());\r\n\t\t\t\r\n\t\t\tfor (short tileId2 : this.tileId2) {\r\n\t\t\t\toutputStream.write(tileId2);\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tbyte[] section = outputStream.sectionEnd();\r\n\t\t// Somehow IZAX includes identifier and the length int into the length.\r\n\t\toutputStream.write(section.length + 8);\r\n\t\toutputStream.write(section);\r\n\t}\r\n\t\r\n\tpublic static class Character {\r\n\t\tprivate short id;\r\n\t\tprivate short x;\r\n\t\tprivate short y;\r\n\t\tprivate short unk3;\r\n\t\tprivate short unk4;\r\n\t\tprivate short[] unk5 = new short[16];\r\n\r\n\t\tpublic static Character read(SmartByteBuffer data, boolean isYoda) {\r\n\t\t\tCharacter instance = new Character();\r\n\r\n\t\t\tinstance.id = data.getShort();\r\n\t\t\tinstance.x = data.getShort();\r\n\t\t\tinstance.y = data.getShort();\r\n\t\t\t\r\n\t\t\tif (isYoda) {\r\n\t\t\t\tinstance.unk3 = data.getShort(); // TODO itemId only?\r\n\t\t\t\tinstance.unk4 = data.getShort(); // TODO 0 or 1 - num items?\r\n\t\t\t\tdata.getShort(); // 0\r\n\t\t\t\r\n\t\t\t\tfor (int i = 0; i < 16; i++) {\r\n\t\t\t\t\tinstance.unk5[i] = data.getShort();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\treturn instance;\r\n\t\t}\r\n\r\n\t\tpublic void write(SmartByteArrayOutputStream outputStream, boolean isYoda) {\r\n\t\t\toutputStream.write(this.id);\r\n\t\t\toutputStream.write(this.x);\r\n\t\t\toutputStream.write(this.y);\r\n\t\t\t\r\n\t\t\tif (isYoda) {\r\n\t\t\t\toutputStream.write(this.unk3);\r\n\t\t\t\toutputStream.write(this.unk4);\r\n\t\t\t\toutputStream.write((short) 0);\r\n\t\t\t\t\r\n\t\t\t\tfor (short unk5 : this.unk5) {\r\n\t\t\t\t\toutputStream.write(unk5);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r",
"public class IZX4 {\r\n\tprivate short unk;\r\n\t\r\n\tpublic static IZX4 read(SmartByteBuffer data) throws Exception {\r\n\t\tIZX4 instance = new IZX4();\r\n\r\n\t\tint length = data.getInt();\r\n\t\tint lengthStart = data.position();\r\n\t\t\r\n\t\tinstance.unk = data.getShort(); // TODO mostly 1, sometimes 0\r\n\r\n\t\tif (lengthStart + length != data.position()) {\r\n\t\t\tthrow new Exception(\"Length mismatch.\");\r\n\t\t}\r\n\t\t\r\n\t\treturn instance;\r\n\t}\r\n\r\n\tpublic void write(SmartByteArrayOutputStream outputStream) {\r\n\t\toutputStream.write(\"IZX4\");\r\n\t\toutputStream.sectionStart();\r\n\r\n\t\toutputStream.write(this.unk);\r\n\t\t\r\n\t\tbyte[] section = outputStream.sectionEnd();\r\n\t\toutputStream.write(section.length);\r\n\t\toutputStream.write(section);\r\n\t}\r\n}\r",
"public static class Hotspot {\r\n\tprivate short type;\r\n\tprivate short x;\r\n\tprivate short y;\r\n\tprivate short param;\r\n\r\n\tpublic static Hotspot read(SmartByteBuffer data) {\r\n\t\tHotspot instance = new Hotspot();\r\n\t\t\t\r\n\t\tinstance.type = data.getShort();\r\n\t\tdata.getShort(); // 0\r\n\t\tinstance.x = data.getShort();\r\n\t\tinstance.y = data.getShort();\r\n\t\tdata.getShort(); // 1\r\n\t\tinstance.param = data.getShort();\r\n\t\t\t\r\n\t\treturn instance;\r\n\t}\r\n\r\n\tpublic void write(SmartByteArrayOutputStream outputStream) {\r\n\t\toutputStream.write(this.type);\r\n\t\toutputStream.write((short) 0);\r\n\t\toutputStream.write(this.x);\r\n\t\toutputStream.write(this.y);\r\n\t\toutputStream.write((short) 1);\r\n\t\toutputStream.write(this.param);\r\n\t}\r\n}\r",
"public class SmartByteArrayOutputStream {\r\n\tprivate List<ByteArrayOutputStream> sections = new ArrayList<>();\r\n\tprivate ByteArrayOutputStream section;\r\n\t\r\n\tpublic SmartByteArrayOutputStream() {\r\n\t\tthis.section = new ByteArrayOutputStream();\r\n\t\tthis.sections.add(this.section);\r\n\t}\r\n\r\n\tpublic void sectionStart() {\r\n\t\tthis.section = new ByteArrayOutputStream();\r\n\t\tthis.sections.add(this.section);\r\n\t}\r\n\t\r\n\tpublic byte[] sectionEnd() {\r\n\t\tbyte[] result = this.section.toByteArray();\r\n\t\tsections.remove(sections.size() - 1);\r\n\t\tthis.section = sections.get(sections.size() - 1);\r\n\t\treturn result;\r\n\t}\r\n\r\n\tpublic byte[] toByteArray() {\r\n\t\treturn this.section.toByteArray();\r\n\t}\r\n\r\n\tpublic void write(String string) {\r\n\t\tfor (byte byteData : string.getBytes()) {\r\n\t\t\tthis.section.write(byteData);\r\n\t\t}\r\n\t}\r\n\r\n\tpublic void write(byte value) {\r\n\t\tthis.section.write(value);\r\n\t}\r\n\r\n\tpublic void write(byte[] value) {\r\n\t\tfor (byte byteData : value) {\r\n\t\t\tthis.section.write(byteData);\r\n\t\t}\r\n\t}\r\n\r\n\tpublic void write(short value) {\r\n\t\tfor (byte byteData : new byte[] {\r\n\t (byte) value,\r\n\t (byte)(value >> 8)\r\n }) {\r\n\t\t\tthis.section.write(byteData);\r\n\t\t}\r\n\t}\r\n\r\n\tpublic void write(int value) {\r\n\t\tfor (byte byteData : new byte[] {\r\n\t (byte) value,\r\n\t (byte)(value >> 8),\r\n\t (byte)(value >> 16),\r\n\t (byte)(value >> 24)\r\n }) {\r\n\t\t\tthis.section.write(byteData);\r\n\t\t}\r\n\t}\r\n}\r",
"public class SmartByteBuffer {\r\n\tprivate ByteBuffer byteBuffer;\r\n\r\n\tpublic int capacity() {\r\n\t\treturn this.byteBuffer.capacity();\r\n\t}\r\n\r\n\tpublic byte get() {\r\n\t\treturn this.byteBuffer.get();\r\n\t}\r\n\r\n\tpublic void get(byte[] dst) {\r\n\t\tthis.byteBuffer.get(dst);\r\n\t}\r\n\r\n\tpublic int getInt() {\r\n\t\treturn this.byteBuffer.getInt();\r\n\t}\r\n\r\n\tpublic short getShort() {\r\n\t\treturn this.byteBuffer.getShort();\r\n\t}\r\n\r\n\tpublic String getString() {\r\n\t\tString string = \"\";\r\n\t\t\r\n\t\twhile (true) {\r\n\t\t\tbyte character = this.get();\r\n\t\t\tif ((character & 0xff) == 0) {\r\n\t\t\t\tbreak;\r\n\t\t\t} else {\r\n\t\t\t\tstring += new String(new byte[] { character });\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\treturn string;\r\n\t}\r\n\r\n\tpublic String getString(int index, int length) {\r\n\t\tbyte[] output = new byte[length];\r\n\t\tif (index > -1) {\r\n\t\t\tthis.position(index);\r\n\t\t}\r\n\t\tthis.byteBuffer.get(output);\r\n\t\treturn new String(output);\r\n\t}\r\n\r\n\tpublic void order(ByteOrder bo) {\r\n\t\tthis.byteBuffer.order(bo);\r\n\t}\r\n\r\n\tpublic int position() {\r\n\t\treturn this.byteBuffer.position();\r\n\t}\r\n\t\r\n\tpublic void position(int newPosition) {\r\n\t\tthis.byteBuffer.position(newPosition);\r\n\t}\r\n\r\n\tpublic static SmartByteBuffer wrap(byte[] array) {\r\n\t\tSmartByteBuffer instance = new SmartByteBuffer();\r\n\t\tinstance.byteBuffer = ByteBuffer.wrap(array);\r\n\t\treturn instance;\r\n\t}\r\n}\r"
] | import java.util.ArrayList;
import java.util.List;
import net.eiveo.original.sections.IZON;
import net.eiveo.original.sections.todo.determine_values.IACT;
import net.eiveo.original.sections.todo.determine_values.IZAX;
import net.eiveo.original.sections.todo.determine_values.IZX4;
import net.eiveo.original.sections.todo.determine_values.HTSP.Hotspot;
import net.eiveo.utils.SmartByteArrayOutputStream;
import net.eiveo.utils.SmartByteBuffer;
| package net.eiveo.original.sections.todo.not_converted_yet;
public class ZONE {
public List<Zone> zones = new ArrayList<>();
public static ZONE read(SmartByteBuffer data, boolean isYoda) throws Exception {
ZONE instance = new ZONE();
int length = 0;
int lengthStart = 0;
if (!isYoda) {
length = data.getInt();
lengthStart = data.position();
}
short zoneCount = data.getShort();
for (short i = 0; i < zoneCount; i++) {
instance.zones.add(Zone.read(data, isYoda, i));
}
if (!isYoda && lengthStart + length != data.position()) {
throw new Exception("Length mismatch.");
}
return instance;
}
| public void write(SmartByteArrayOutputStream outputStream, boolean isYoda) {
| 5 |
cqjjjzr/BiliLiveLib | BiliLiveLib/src/main/java/charlie/bililivelib/capsuletoy/CapsuleToyProtocol.java | [
"public class Globals {\n private static final String BILI_PASSPORT_HOST_ROOT = \"passport.bilibili.com\";\n private static final String BILI_LIVE_HOST_ROOT = \"live.bilibili.com\";\n @Getter\n private static int CONNECTION_ALIVE_TIME_SECOND = 10;\n private static Globals instance;\n @Getter\n private HttpHost biliLiveRoot;\n @Getter\n private HttpHost biliPassportHttpsRoot;\n private ThreadLocal<Gson> gson;\n\n private HttpClientConnectionManager connectionPool;\n @Getter\n private SSLContext bilibiliSSLContext;\n\n public static Globals get() {\n if (instance == null) {\n instance = new Globals();\n instance.init();\n }\n return instance;\n }\n\n private void init() {\n biliLiveRoot = new HttpHost(BILI_LIVE_HOST_ROOT);\n //Visit bilibili passport via https. 443 is the https port.\n biliPassportHttpsRoot = new HttpHost(BILI_PASSPORT_HOST_ROOT, 443, \"https\");\n gson = ThreadLocal.withInitial(() -> new GsonBuilder()\n .setLenient()\n .create());\n\n try {\n bilibiliSSLContext = SSLContextBuilder.create()\n .loadTrustMaterial(new BilibiliTrustStrategy())\n .build();\n } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {\n throw new AssertionError(\"failed initializing bilibili ssl context!\");\n }\n }\n\n public Gson gson() {\n return gson.get();\n }\n\n public HttpClientConnectionManager getConnectionPool() {\n if (connectionPool == null) {\n reInitializeConnectionPool();\n }\n return connectionPool;\n }\n\n public void reInitializeConnectionPool() {\n connectionPool = new PoolingHttpClientConnectionManager(CONNECTION_ALIVE_TIME_SECOND, TimeUnit.SECONDS);\n }\n\n public void setConnectionAliveTimeSecond(int connectionAliveTimeSecond) {\n CONNECTION_ALIVE_TIME_SECOND = connectionAliveTimeSecond;\n reInitializeConnectionPool();\n }\n\n\n}",
"public class BiliLiveException extends Exception {\n public BiliLiveException() {\n super();\n }\n\n public BiliLiveException(String message) {\n super(message);\n }\n\n public BiliLiveException(String message, Throwable cause) {\n super(message, cause);\n }\n}",
"public class NetworkException extends BiliLiveException {\n public NetworkException() {\n }\n\n public NetworkException(String message) {\n super(message);\n }\n\n public NetworkException(String message, Throwable cause) {\n super(message, cause);\n }\n\n /**\n * 对于给定信息和Http错误,创建一个NetworkException。\n *\n * @param message 信息\n * @param status Http状态码\n * @return NetworkException\n */\n @Contract(\"_, _ -> !null\")\n public static NetworkException createHttpError(\n @Nls String message,\n int status) {\n return new NetworkException(message + I18n.format(\"exception.http_error\", status));\n }\n}",
"public class NotLoggedInException extends BiliLiveException {\n public NotLoggedInException() {\n super();\n }\n\n public NotLoggedInException(String message) {\n super(message);\n }\n\n public NotLoggedInException(String message, Throwable cause) {\n super(message, cause);\n }\n}",
"public class PostArguments {\n private List<NameValuePair> nameValuePairs = new LinkedList<>();\n\n /**\n * 添加一个Post参数键/值对。\n *\n * @param name 键\n * @param value 值\n * @return 本类对象以便串联调用。\n */\n public PostArguments add(String name, String value) {\n nameValuePairs.add(new BasicNameValuePair(name, value));\n return this;\n }\n\n /**\n * 将本类转换为Http Client可使用的Http Entity。\n *\n * @return 转换后的Entity对象。\n * @throws UnsupportedEncodingException 当默认编码不被支持时抛出\n * @see HttpHelper\n */\n public UrlEncodedFormEntity toEntity() throws UnsupportedEncodingException {\n return new UrlEncodedFormEntity(nameValuePairs);\n }\n}",
"@Getter\npublic class Session {\n private static final String EXIT_URL_G = \"/login?act=exit\";\n private static final String ACTIVATE_URL = \"http://live.bilibili.com/2\";\n\n private static final SSLContext BILIBILI_SSL_CONTEXT = Globals.get().getBilibiliSSLContext();\n private HttpHelper httpHelper;\n @Getter\n private CookieStore cookieStore;\n\n public Session() {\n this(Globals.get().getConnectionPool());\n }\n\n public Session(String userAgent) {\n this(Globals.get().getConnectionPool(), userAgent);\n }\n\n public Session(HttpClient httpClient, CookieStore cookieStore) {\n httpHelper = new HttpHelper();\n httpHelper.init(httpClient);\n this.cookieStore = cookieStore;\n }\n\n public Session(HttpClientConnectionManager clientConnectionManager) {\n this(clientConnectionManager, BiliLiveLib.DEFAULT_USER_AGENT);\n }\n\n public Session(HttpClientConnectionManager clientConnectionManager, String userAgent) {\n httpHelper = new HttpHelper();\n initHttpHelper(clientConnectionManager, userAgent);\n }\n\n private void initHttpHelper(HttpClientConnectionManager clientConnectionManager, String userAgent) {\n cookieStore = new BasicCookieStore();\n HttpClientBuilder builder = HttpClientBuilder.create()\n .setUserAgent(userAgent)\n .setConnectionManager(clientConnectionManager)\n .setSSLContext(BILIBILI_SSL_CONTEXT)\n //.setProxy(new HttpHost(\"127.0.0.1\", 8888)) // For Fiddler Debugging\n .setDefaultCookieStore(cookieStore);\n httpHelper.init(builder.build());\n }\n\n /**\n * 登出会话。\n * @throws IOException 出现网络问题时抛出\n */\n public void logout() throws IOException {\n httpHelper.executeGet(Globals.get().getBiliPassportHttpsRoot(), EXIT_URL_G);\n cookieStore.clear();\n }\n\n protected void activate() throws IOException {\n httpHelper.executeBiliLiveGet(ACTIVATE_URL);\n }\n\n /**\n * 从Base64字符串恢复到会话。\n * @param base64 Base64流\n */\n public void fromBase64(String base64) {\n SessionPersistenceHelper.fromBase64(this, base64);\n }\n\n /**\n * 将会话序列化到Base64字符串。\n * @return 该会话的Base64字符串\n */\n public String toBase64() {\n return SessionPersistenceHelper.toBase64(this);\n }\n}"
] | import charlie.bililivelib.Globals;
import charlie.bililivelib.exceptions.BiliLiveException;
import charlie.bililivelib.exceptions.NetworkException;
import charlie.bililivelib.exceptions.NotLoggedInException;
import charlie.bililivelib.internalutil.net.PostArguments;
import charlie.bililivelib.user.Session;
import com.google.gson.JsonObject;
import com.google.gson.annotations.SerializedName;
import lombok.Getter;
import lombok.ToString;
import org.apache.http.cookie.Cookie;
import org.intellij.lang.annotations.MagicConstant;
import org.jetbrains.annotations.NotNull;
import java.util.List; | package charlie.bililivelib.capsuletoy;
/**
* 用于处理扭蛋机的协议类。
*
* @author Charlie Jiang
* @since rv1
*/
public class CapsuleToyProtocol {
private static final String CAPSULE_OPEN_POST = "/api/ajaxCapsuleOpen";
private static final String CAPSULE_INFO_GET = "/api/ajaxCapsule";
private static final String EXCEPTION_KEY = "exception.capsule_toy";
private static final int STATUS_NOT_LOGGED_IN = -101;
private static final int STATUS_SUCCESS = 0;
private static final int STATUS_NOT_ENOUGH = -500;
private static final String TOKEN_COOKIE_KEY = "LIVE_LOGIN_DATA";
private Session session;
public CapsuleToyProtocol(@NotNull Session session) {
this.session = session;
}
/**
* 打开指定数量的普通扭蛋币。
*
* @param count 数量,仅能为1,10或100
* @return 扭蛋结果
* @throws NetworkException 在发生网络错误时抛出
* @throws IllegalArgumentException 在数量不为1,10或100时抛出
*/
public OpenCapsuleToyInfo openNormal(@MagicConstant(intValues = {1, 10, 100}) int count)
throws BiliLiveException {
return openCapsule("normal", count, getToken());
}
/**
* 打开指定数量的梦幻扭蛋币。
*
* @param count 数量,仅能为1,10或100
* @return 扭蛋结果
* @throws NetworkException 在发生网络错误时抛出
* @throws IllegalArgumentException 在数量不为1,10或100时抛出
*/
public OpenCapsuleToyInfo openColorful(@MagicConstant(intValues = {1, 10, 100}) int count)
throws BiliLiveException {
return openCapsule("colorful", count, getToken());
}
private OpenCapsuleToyInfo openCapsule(String type, int count, String token) throws BiliLiveException {
if (count != 1 && count != 10 && count != 100)
throw new IllegalArgumentException("count must be 1, 10 or 100.");
JsonObject rootObject = session.getHttpHelper().postBiliLiveJSON(CAPSULE_OPEN_POST,
new PostArguments()
.add("type", type)
.add("count", String.valueOf(count))
.add("token", token),
JsonObject.class, EXCEPTION_KEY);
int code = rootObject.get("code").getAsInt();
if (rootObject.get("code").getAsInt() == STATUS_NOT_LOGGED_IN) throw new NotLoggedInException();
if (rootObject.get("code").getAsInt() != STATUS_SUCCESS) return new OpenCapsuleToyInfo(code,
rootObject.get("msg").getAsString()); | return Globals.get().gson().fromJson(rootObject, OpenCapsuleToyInfo.class); | 0 |
WolfgangFahl/Mediawiki-Japi | src/test/java/com/bitplan/mediawiki/japi/TestAPI_Allpages.java | [
"@XmlAccessorType(XmlAccessType.FIELD)\n@XmlType(name = \"\")\npublic class Bl {\n\n @XmlAttribute(name = \"pageid\")\n protected Integer pageid;\n @XmlAttribute(name = \"ns\")\n protected Integer ns;\n @XmlAttribute(name = \"title\")\n protected String title;\n\n /**\n * Ruft den Wert der pageid-Eigenschaft ab.\n * \n * @return\n * possible object is\n * {@link Integer }\n * \n */\n public Integer getPageid() {\n return pageid;\n }\n\n /**\n * Legt den Wert der pageid-Eigenschaft fest.\n * \n * @param value\n * allowed object is\n * {@link Integer }\n * \n */\n public void setPageid(Integer value) {\n this.pageid = value;\n }\n\n /**\n * Ruft den Wert der ns-Eigenschaft ab.\n * \n * @return\n * possible object is\n * {@link Integer }\n * \n */\n public Integer getNs() {\n return ns;\n }\n\n /**\n * Legt den Wert der ns-Eigenschaft fest.\n * \n * @param value\n * allowed object is\n * {@link Integer }\n * \n */\n public void setNs(Integer value) {\n this.ns = value;\n }\n\n /**\n * Ruft den Wert der title-Eigenschaft ab.\n * \n * @return\n * possible object is\n * {@link String }\n * \n */\n public String getTitle() {\n return title;\n }\n\n /**\n * Legt den Wert der title-Eigenschaft fest.\n * \n * @param value\n * allowed object is\n * {@link String }\n * \n */\n public void setTitle(String value) {\n this.title = value;\n }\n\n}",
"@XmlAccessorType(XmlAccessType.FIELD)\n@XmlType(name = \"\")\npublic class Ii {\n\n @XmlAttribute(name = \"timestamp\")\n @XmlSchemaType(name = \"dateTime\")\n protected XMLGregorianCalendar timestamp;\n @XmlAttribute(name = \"user\")\n protected String user;\n @XmlAttribute(name = \"userid\")\n protected Integer userid;\n @XmlAttribute(name = \"size\")\n protected Integer size;\n @XmlAttribute(name = \"width\")\n protected Short width;\n @XmlAttribute(name = \"height\")\n protected Short height;\n @XmlAttribute(name = \"parsedcomment\")\n protected String parsedcomment;\n @XmlAttribute(name = \"comment\")\n protected String comment;\n @XmlAttribute(name = \"html\")\n protected String html;\n @XmlAttribute(name = \"canonicaltitle\")\n protected String canonicaltitle;\n @XmlAttribute(name = \"url\")\n protected String url;\n @XmlAttribute(name = \"descriptionurl\")\n protected String descriptionurl;\n @XmlAttribute(name = \"sha1\")\n protected String sha1;\n @XmlAttribute(name = \"mime\")\n protected String mime;\n @XmlAttribute(name = \"mediatype\")\n protected String mediatype;\n @XmlAttribute(name = \"bitdepth\")\n protected BigInteger bitdepth;\n\n /**\n * Ruft den Wert der timestamp-Eigenschaft ab.\n * \n * @return\n * possible object is\n * {@link XMLGregorianCalendar }\n * \n */\n public XMLGregorianCalendar getTimestamp() {\n return timestamp;\n }\n\n /**\n * Legt den Wert der timestamp-Eigenschaft fest.\n * \n * @param value\n * allowed object is\n * {@link XMLGregorianCalendar }\n * \n */\n public void setTimestamp(XMLGregorianCalendar value) {\n this.timestamp = value;\n }\n\n /**\n * Ruft den Wert der user-Eigenschaft ab.\n * \n * @return\n * possible object is\n * {@link String }\n * \n */\n public String getUser() {\n return user;\n }\n\n /**\n * Legt den Wert der user-Eigenschaft fest.\n * \n * @param value\n * allowed object is\n * {@link String }\n * \n */\n public void setUser(String value) {\n this.user = value;\n }\n\n /**\n * Ruft den Wert der userid-Eigenschaft ab.\n * \n * @return\n * possible object is\n * {@link Integer }\n * \n */\n public Integer getUserid() {\n return userid;\n }\n\n /**\n * Legt den Wert der userid-Eigenschaft fest.\n * \n * @param value\n * allowed object is\n * {@link Integer }\n * \n */\n public void setUserid(Integer value) {\n this.userid = value;\n }\n\n /**\n * Ruft den Wert der size-Eigenschaft ab.\n * \n * @return\n * possible object is\n * {@link Integer }\n * \n */\n public Integer getSize() {\n return size;\n }\n\n /**\n * Legt den Wert der size-Eigenschaft fest.\n * \n * @param value\n * allowed object is\n * {@link Integer }\n * \n */\n public void setSize(Integer value) {\n this.size = value;\n }\n\n /**\n * Ruft den Wert der width-Eigenschaft ab.\n * \n * @return\n * possible object is\n * {@link Short }\n * \n */\n public Short getWidth() {\n return width;\n }\n\n /**\n * Legt den Wert der width-Eigenschaft fest.\n * \n * @param value\n * allowed object is\n * {@link Short }\n * \n */\n public void setWidth(Short value) {\n this.width = value;\n }\n\n /**\n * Ruft den Wert der height-Eigenschaft ab.\n * \n * @return\n * possible object is\n * {@link Short }\n * \n */\n public Short getHeight() {\n return height;\n }\n\n /**\n * Legt den Wert der height-Eigenschaft fest.\n * \n * @param value\n * allowed object is\n * {@link Short }\n * \n */\n public void setHeight(Short value) {\n this.height = value;\n }\n\n /**\n * Ruft den Wert der parsedcomment-Eigenschaft ab.\n * \n * @return\n * possible object is\n * {@link String }\n * \n */\n public String getParsedcomment() {\n return parsedcomment;\n }\n\n /**\n * Legt den Wert der parsedcomment-Eigenschaft fest.\n * \n * @param value\n * allowed object is\n * {@link String }\n * \n */\n public void setParsedcomment(String value) {\n this.parsedcomment = value;\n }\n\n /**\n * Ruft den Wert der comment-Eigenschaft ab.\n * \n * @return\n * possible object is\n * {@link String }\n * \n */\n public String getComment() {\n return comment;\n }\n\n /**\n * Legt den Wert der comment-Eigenschaft fest.\n * \n * @param value\n * allowed object is\n * {@link String }\n * \n */\n public void setComment(String value) {\n this.comment = value;\n }\n\n /**\n * Ruft den Wert der html-Eigenschaft ab.\n * \n * @return\n * possible object is\n * {@link String }\n * \n */\n public String getHtml() {\n return html;\n }\n\n /**\n * Legt den Wert der html-Eigenschaft fest.\n * \n * @param value\n * allowed object is\n * {@link String }\n * \n */\n public void setHtml(String value) {\n this.html = value;\n }\n\n /**\n * Ruft den Wert der canonicaltitle-Eigenschaft ab.\n * \n * @return\n * possible object is\n * {@link String }\n * \n */\n public String getCanonicaltitle() {\n return canonicaltitle;\n }\n\n /**\n * Legt den Wert der canonicaltitle-Eigenschaft fest.\n * \n * @param value\n * allowed object is\n * {@link String }\n * \n */\n public void setCanonicaltitle(String value) {\n this.canonicaltitle = value;\n }\n\n /**\n * Ruft den Wert der url-Eigenschaft ab.\n * \n * @return\n * possible object is\n * {@link String }\n * \n */\n public String getUrl() {\n return url;\n }\n\n /**\n * Legt den Wert der url-Eigenschaft fest.\n * \n * @param value\n * allowed object is\n * {@link String }\n * \n */\n public void setUrl(String value) {\n this.url = value;\n }\n\n /**\n * Ruft den Wert der descriptionurl-Eigenschaft ab.\n * \n * @return\n * possible object is\n * {@link String }\n * \n */\n public String getDescriptionurl() {\n return descriptionurl;\n }\n\n /**\n * Legt den Wert der descriptionurl-Eigenschaft fest.\n * \n * @param value\n * allowed object is\n * {@link String }\n * \n */\n public void setDescriptionurl(String value) {\n this.descriptionurl = value;\n }\n\n /**\n * Ruft den Wert der sha1-Eigenschaft ab.\n * \n * @return\n * possible object is\n * {@link String }\n * \n */\n public String getSha1() {\n return sha1;\n }\n\n /**\n * Legt den Wert der sha1-Eigenschaft fest.\n * \n * @param value\n * allowed object is\n * {@link String }\n * \n */\n public void setSha1(String value) {\n this.sha1 = value;\n }\n\n /**\n * Ruft den Wert der mime-Eigenschaft ab.\n * \n * @return\n * possible object is\n * {@link String }\n * \n */\n public String getMime() {\n return mime;\n }\n\n /**\n * Legt den Wert der mime-Eigenschaft fest.\n * \n * @param value\n * allowed object is\n * {@link String }\n * \n */\n public void setMime(String value) {\n this.mime = value;\n }\n\n /**\n * Ruft den Wert der mediatype-Eigenschaft ab.\n * \n * @return\n * possible object is\n * {@link String }\n * \n */\n public String getMediatype() {\n return mediatype;\n }\n\n /**\n * Legt den Wert der mediatype-Eigenschaft fest.\n * \n * @param value\n * allowed object is\n * {@link String }\n * \n */\n public void setMediatype(String value) {\n this.mediatype = value;\n }\n\n /**\n * Ruft den Wert der bitdepth-Eigenschaft ab.\n * \n * @return\n * possible object is\n * {@link BigInteger }\n * \n */\n public BigInteger getBitdepth() {\n return bitdepth;\n }\n\n /**\n * Legt den Wert der bitdepth-Eigenschaft fest.\n * \n * @param value\n * allowed object is\n * {@link BigInteger }\n * \n */\n public void setBitdepth(BigInteger value) {\n this.bitdepth = value;\n }\n\n}",
"@XmlAccessorType(XmlAccessType.FIELD)\n@XmlType(name = \"\")\npublic class Im {\n\n @XmlAttribute(name = \"ns\")\n protected Integer ns;\n @XmlAttribute(name = \"title\")\n protected String title;\n\n /**\n * Gets the value of the ns property.\n * \n * @return\n * possible object is\n * {@link Integer }\n * \n */\n public Integer getNs() {\n return ns;\n }\n\n /**\n * Sets the value of the ns property.\n * \n * @param value\n * allowed object is\n * {@link Integer }\n * \n */\n public void setNs(Integer value) {\n this.ns = value;\n }\n\n /**\n * Gets the value of the title property.\n * \n * @return\n * possible object is\n * {@link String }\n * \n */\n public String getTitle() {\n return title;\n }\n\n /**\n * Sets the value of the title property.\n * \n * @param value\n * allowed object is\n * {@link String }\n * \n */\n public void setTitle(String value) {\n this.title = value;\n }\n\n}",
"@XmlAccessorType(XmlAccessType.FIELD)\n@XmlType(name = \"\")\npublic class Img {\n\n @XmlAttribute(name = \"name\")\n protected String name;\n @XmlAttribute(name = \"timestamp\")\n @XmlSchemaType(name = \"dateTime\")\n protected XMLGregorianCalendar timestamp;\n @XmlAttribute(name = \"url\")\n protected String url;\n @XmlAttribute(name = \"descriptionurl\")\n protected String descriptionurl;\n @XmlAttribute(name = \"ns\")\n protected Integer ns;\n @XmlAttribute(name = \"title\")\n protected String title;\n\n /**\n * Ruft den Wert der name-Eigenschaft ab.\n * \n * @return\n * possible object is\n * {@link String }\n * \n */\n public String getName() {\n return name;\n }\n\n /**\n * Legt den Wert der name-Eigenschaft fest.\n * \n * @param value\n * allowed object is\n * {@link String }\n * \n */\n public void setName(String value) {\n this.name = value;\n }\n\n /**\n * Ruft den Wert der timestamp-Eigenschaft ab.\n * \n * @return\n * possible object is\n * {@link XMLGregorianCalendar }\n * \n */\n public XMLGregorianCalendar getTimestamp() {\n return timestamp;\n }\n\n /**\n * Legt den Wert der timestamp-Eigenschaft fest.\n * \n * @param value\n * allowed object is\n * {@link XMLGregorianCalendar }\n * \n */\n public void setTimestamp(XMLGregorianCalendar value) {\n this.timestamp = value;\n }\n\n /**\n * Ruft den Wert der url-Eigenschaft ab.\n * \n * @return\n * possible object is\n * {@link String }\n * \n */\n public String getUrl() {\n return url;\n }\n\n /**\n * Legt den Wert der url-Eigenschaft fest.\n * \n * @param value\n * allowed object is\n * {@link String }\n * \n */\n public void setUrl(String value) {\n this.url = value;\n }\n\n /**\n * Ruft den Wert der descriptionurl-Eigenschaft ab.\n * \n * @return\n * possible object is\n * {@link String }\n * \n */\n public String getDescriptionurl() {\n return descriptionurl;\n }\n\n /**\n * Legt den Wert der descriptionurl-Eigenschaft fest.\n * \n * @param value\n * allowed object is\n * {@link String }\n * \n */\n public void setDescriptionurl(String value) {\n this.descriptionurl = value;\n }\n\n /**\n * Ruft den Wert der ns-Eigenschaft ab.\n * \n * @return\n * possible object is\n * {@link Integer }\n * \n */\n public Integer getNs() {\n return ns;\n }\n\n /**\n * Legt den Wert der ns-Eigenschaft fest.\n * \n * @param value\n * allowed object is\n * {@link Integer }\n * \n */\n public void setNs(Integer value) {\n this.ns = value;\n }\n\n /**\n * Ruft den Wert der title-Eigenschaft ab.\n * \n * @return\n * possible object is\n * {@link String }\n * \n */\n public String getTitle() {\n return title;\n }\n\n /**\n * Legt den Wert der title-Eigenschaft fest.\n * \n * @param value\n * allowed object is\n * {@link String }\n * \n */\n public void setTitle(String value) {\n this.title = value;\n }\n\n}",
"@XmlAccessorType(XmlAccessType.FIELD)\n@XmlType(name = \"\")\npublic class Iu {\n\n @XmlAttribute(name = \"pageid\")\n protected Integer pageid;\n @XmlAttribute(name = \"ns\")\n protected Integer ns;\n @XmlAttribute(name = \"title\")\n protected String title;\n\n /**\n * Ruft den Wert der pageid-Eigenschaft ab.\n * \n * @return\n * possible object is\n * {@link Integer }\n * \n */\n public Integer getPageid() {\n return pageid;\n }\n\n /**\n * Legt den Wert der pageid-Eigenschaft fest.\n * \n * @param value\n * allowed object is\n * {@link Integer }\n * \n */\n public void setPageid(Integer value) {\n this.pageid = value;\n }\n\n /**\n * Ruft den Wert der ns-Eigenschaft ab.\n * \n * @return\n * possible object is\n * {@link Integer }\n * \n */\n public Integer getNs() {\n return ns;\n }\n\n /**\n * Legt den Wert der ns-Eigenschaft fest.\n * \n * @param value\n * allowed object is\n * {@link Integer }\n * \n */\n public void setNs(Integer value) {\n this.ns = value;\n }\n\n /**\n * Ruft den Wert der title-Eigenschaft ab.\n * \n * @return\n * possible object is\n * {@link String }\n * \n */\n public String getTitle() {\n return title;\n }\n\n /**\n * Legt den Wert der title-Eigenschaft fest.\n * \n * @param value\n * allowed object is\n * {@link String }\n * \n */\n public void setTitle(String value) {\n this.title = value;\n }\n\n}",
"@XmlAccessorType(XmlAccessType.FIELD)\n@XmlType(name = \"\", propOrder = {\n \"value\"\n})\npublic class P {\n\n @XmlValue\n protected String value;\n @XmlAttribute(name = \"pageid\")\n protected Integer pageid;\n @XmlAttribute(name = \"ns\")\n protected Byte ns;\n @XmlAttribute(name = \"title\")\n protected String title;\n\n /**\n * Gets the value of the value property.\n * \n * @return\n * possible object is\n * {@link String }\n * \n */\n public String getValue() {\n return value;\n }\n\n /**\n * Sets the value of the value property.\n * \n * @param value\n * allowed object is\n * {@link String }\n * \n */\n public void setValue(String value) {\n this.value = value;\n }\n\n /**\n * Gets the value of the pageid property.\n * \n * @return\n * possible object is\n * {@link Integer }\n * \n */\n public Integer getPageid() {\n return pageid;\n }\n\n /**\n * Sets the value of the pageid property.\n * \n * @param value\n * allowed object is\n * {@link Integer }\n * \n */\n public void setPageid(Integer value) {\n this.pageid = value;\n }\n\n /**\n * Gets the value of the ns property.\n * \n * @return\n * possible object is\n * {@link Byte }\n * \n */\n public Byte getNs() {\n return ns;\n }\n\n /**\n * Sets the value of the ns property.\n * \n * @param value\n * allowed object is\n * {@link Byte }\n * \n */\n public void setNs(Byte value) {\n this.ns = value;\n }\n\n /**\n * Gets the value of the title property.\n * \n * @return\n * possible object is\n * {@link String }\n * \n */\n public String getTitle() {\n return title;\n }\n\n /**\n * Sets the value of the title property.\n * \n * @param value\n * allowed object is\n * {@link String }\n * \n */\n public void setTitle(String value) {\n this.title = value;\n }\n\n}"
] | import com.bitplan.mediawiki.japi.api.Ii;
import com.bitplan.mediawiki.japi.api.Im;
import com.bitplan.mediawiki.japi.api.Img;
import com.bitplan.mediawiki.japi.api.Iu;
import com.bitplan.mediawiki.japi.api.P;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.List;
import java.util.logging.Level;
import org.junit.Test;
import com.bitplan.mediawiki.japi.api.Bl; | /**
*
* This file is part of the https://github.com/WolfgangFahl/Mediawiki-Japi open source project
*
* Copyright 2015-2021 BITPlan GmbH https://github.com/BITPlan
*
* 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.bitplan.mediawiki.japi;
/**
* test https://www.mediawiki.org/wiki/API:Allpages
*
* @author wf
*
*/
public class TestAPI_Allpages extends APITestbase {
@Test
public void testAllpages() throws Exception {
ExampleWiki lWiki = ewm.get(ExampleWiki.DEFAULT_WIKI_ID);
debug = true;
if (hasWikiUser(lWiki)) {
lWiki.login();
String apfrom = null;
int aplimit = 25000;
List<P> pages = lWiki.wiki.getAllPages(apfrom, aplimit);
if (debug) {
LOGGER.log(Level.INFO, "page #=" + pages.size());
}
assertTrue(pages.size() >= 6);
}
}
@Test
public void testGetAllImagesByTimeStamp() throws Exception {
ExampleWiki lWiki = ewm.get("bitplanwiki");
String[] expectedUsage = { "PDF Example", "Picture Example" };
String[] expected = { "Wuthering_Heights_NT.pdf",
"Radcliffe_Chastenay_-_Les_Mysteres_d_Udolphe_frontispice_T6.jpg" };
String aistart = "20210703131900";
String aiend = "20210703132500";
int ailimit = 500;
// lWiki.wiki.setDebug(true);
List<Img> images = lWiki.wiki.getAllImagesByTimeStamp(aistart, aiend, ailimit);
// debug = true;
if (debug) {
LOGGER.log(Level.INFO, "found images:" + images.size());
int i=0;
for (Img image:images) {
i++;
LOGGER.log(Level.INFO,String.format("%d: %s %s",i, image.getTimestamp(),image.getName()));
}
}
assertEquals(expected.length, images.size());
for (int i = 0; i < expected.length; i++) {
assertEquals(expected[i], images.get(i).getName());
}
// lWiki.wiki.setDebug(true);
int i = 0;
for (Img img : images) {
if (!"Index.png".equals(img.getName())) { | List<Iu> ius = lWiki.wiki.getImageUsage("File:" + img.getName(), "", 50); | 4 |
arquillian/arquillian-recorder | arquillian-recorder-screenshooter-base/arquillian-recorder-screenshooter-impl-base/src/main/java/org/arquillian/extension/recorder/screenshooter/impl/ScreenshooterLifecycleObserver.java | [
"public class DefaultFileNameBuilder extends AbstractFileNameBuilder {\n\n protected ResourceMetaData metaData;\n\n protected When when;\n\n protected ResourceIdentifier<ResourceType> resourceIdentifier;\n\n public DefaultFileNameBuilder() {\n setDefaultFileIdentifier();\n }\n\n public DefaultFileNameBuilder withMetaData(ResourceMetaData metaData) {\n this.metaData = metaData;\n return this;\n }\n\n public DefaultFileNameBuilder withStage(When when) {\n this.when = when;\n return this;\n }\n\n public DefaultFileNameBuilder withResourceIdentifier(ResourceIdentifier<ResourceType> resourceIdentifier) {\n if (resourceIdentifier != null) {\n this.resourceIdentifier = resourceIdentifier;\n }\n return this;\n }\n\n /**\n * When generation of file name is not overridden by {@link #withResourceIdentifier(ResourceIdentifier)}, by default, every\n * file name will be of format: <br>\n * <br>\n * testMethodName_stage.screenshotType <br>\n * <br>\n * where stage is {@link When}.\n *\n * When you do not set meta data or name of test method is null or empty string, random {@link UUID} is generated instead of\n * that. If {@link When} is not set, it is not included into file name generation. When you do not specify resource type,\n * file name will be generated without file format suffix, excluding a dot as well.\n *\n * <br>\n * After you get identifier, builder is cleared so every subsequent call of this method will return just UUID when there are\n * not used 'when' methods.\n */\n @Override\n public String build() {\n ResourceType resourceType = null;\n if (metaData != null) {\n resourceType = metaData.getResourceType();\n }\n String id = resourceIdentifier.getIdentifier(resourceType);\n clear();\n return id;\n }\n\n @Override\n public DefaultFileNameBuilder clear() {\n metaData = null;\n when = null;\n return this;\n }\n\n private void setDefaultFileIdentifier() {\n resourceIdentifier = new ResourceIdentifier<ResourceType>() {\n\n @Override\n public String getIdentifier(ResourceType resourceType) {\n StringBuilder sb = new StringBuilder();\n if (metaData == null || metaData.getTestMethodName() == null || metaData.getTestMethodName().isEmpty()) {\n sb.append(UUID.randomUUID().toString());\n } else {\n sb.append(metaData.getTestMethodName());\n }\n if (when != null) {\n sb.append(\"_\");\n sb.append(when.toString());\n }\n if (resourceType != null) {\n sb.append(\".\");\n sb.append(resourceType.toString());\n }\n return sb.toString();\n }\n };\n }\n}",
"public class RecorderStrategyRegister {\n\n private final Set<RecorderStrategy<?>> recorderStrategies = new TreeSet<RecorderStrategy<?>>(new RecorderStrategyComparator());\n\n public void add(RecorderStrategy<?> recorderStrategy) {\n this.recorderStrategies.add(recorderStrategy);\n }\n\n public void addAll(Set<RecorderStrategy<?>> recorderStrategies) {\n this.recorderStrategies.addAll(recorderStrategies);\n }\n\n public void clear() {\n recorderStrategies.clear();\n }\n\n public int size() {\n return recorderStrategies.size();\n }\n\n public RecorderStrategy<?> get(int precedence) {\n for (final RecorderStrategy<?> strategy : recorderStrategies) {\n if (strategy.precedence() == precedence) {\n return strategy;\n }\n }\n\n return null;\n }\n\n public Set<RecorderStrategy<?>> getAll() {\n return Collections.unmodifiableSet(recorderStrategies);\n }\n}",
"public enum When {\n\n AFTER(\"after\"),\n BEFORE(\"before\"),\n FAILED(\"failed\"),\n ON_EVERY_ACTION(\"onEveryAction\"),\n IN_TEST(\"in_test\");\n\n private final String name;\n\n When(String name) {\n this.name = name;\n }\n\n @Override\n public String toString() {\n return name;\n }\n\n}",
"public class ScreenshooterConfiguration extends Configuration<ScreenshooterConfiguration> {\n\n private static final String ROOT_DIR = \"target/screenshots\";\n\n private static final String SCREENSHOT_TYPE = ScreenshotType.PNG.toString();\n\n private static final String TAKE_BEFORE_TEST = \"false\";\n\n private static final String TAKE_AFTER_TEST = \"false\";\n\n private static final String TAKE_WHEN_TEST_FAILED = \"true\";\n\n private final ReporterConfiguration reporterConfiguration;\n\n public ScreenshooterConfiguration(ReporterConfiguration reporterConfiguration) {\n this.reporterConfiguration = reporterConfiguration;\n }\n\n /**\n * By default set to \"target/screenshots\"\n *\n * @return root folder where all screenshots will be placed. Directory structure is left on the extension itself\n */\n public File getRootDir() {\n return new File(getProperty(\"rootDir\", ROOT_DIR));\n }\n\n /**\n * By default set to PNG.\n *\n * @return type of image we want to have our screenshots of, consult {@link ScreenshotType}\n */\n public String getScreenshotType() {\n return getProperty(\"screenshotType\", SCREENSHOT_TYPE).toUpperCase();\n }\n\n /**\n * By default set to false.\n *\n * @return true if screenshot should be taken before test, false otherwise\n */\n public boolean getTakeBeforeTest() {\n return Boolean.parseBoolean(getProperty(\"takeBeforeTest\", TAKE_BEFORE_TEST));\n }\n\n /**\n * By default set to false.\n *\n * @return true if screenshot should be taken after test, false otherwise\n */\n public boolean getTakeAfterTest() {\n return Boolean.parseBoolean(getProperty(\"takeAfterTest\", TAKE_AFTER_TEST));\n }\n\n /**\n * By default set to true.\n *\n * @return true if screenshot should be taken when test failed, false otherwise\n */\n public boolean getTakeWhenTestFailed() {\n return Boolean.parseBoolean(getProperty(\"takeWhenTestFailed\", TAKE_WHEN_TEST_FAILED));\n }\n\n @Override\n public void validate() throws ScreenshooterConfigurationException {\n validate(reporterConfiguration);\n }\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(String.format(\"%-40s %s%n\", \"rootDir\", getRootDir()));\n sb.append(String.format(\"%-40s %s%n\", \"screenshotType\", getScreenshotType()));\n sb.append(String.format(\"%-40s %s%n\", \"takeBeforeTest\", getTakeBeforeTest()));\n sb.append(String.format(\"%-40s %s%n\", \"takeAfterTest\", getTakeAfterTest()));\n sb.append(String.format(\"%-40s %s%n\", \"takeWhenTestFailed\", getTakeWhenTestFailed()));\n return sb.toString();\n }\n\n private void validate(ReporterConfiguration reporterConfiguration) {\n\n try {\n ScreenshotType.valueOf(ScreenshotType.class, getScreenshotType());\n } catch (IllegalArgumentException ex) {\n throw new ScreenshooterConfigurationException(\n \"Screenshot type you specified in arquillian.xml is not valid screenshot type. \"\n + \"The configured screenshot type is: \" + getScreenshotType() + \". \"\n + \"The supported screenshot types are: \" + ScreenshotType.getAll(), ex);\n }\n\n final String report = reporterConfiguration.getReport().toLowerCase();\n\n if (report.contains(\"htm\") || report.contains(\"ad\") || report.equals(\"asciidoc\")) {\n final File screenshooterRootDir = new File(reporterConfiguration.getRootDir(), \"screenshots\");\n if (!getRootDir().equals(screenshooterRootDir)) {\n setProperty(\"rootDir\", screenshooterRootDir.getAbsolutePath());\n }\n }\n\n try {\n if (!getRootDir().exists()) {\n boolean created = getRootDir().mkdirs();\n if (!created) {\n throw new ScreenshooterConfigurationException(\"Unable to create root directory \"\n + getRootDir().getAbsolutePath());\n }\n } else {\n if (!getRootDir().isDirectory()) {\n throw new ScreenshooterConfigurationException(\"Root directory you specified is not a directory - \" +\n getRootDir().getAbsolutePath());\n }\n if (!getRootDir().canWrite()) {\n throw new ScreenshooterConfigurationException(\n \"You can not write to '\" + getRootDir().getAbsolutePath() + \"'.\");\n }\n }\n } catch (SecurityException ex) {\n throw new ScreenshooterConfigurationException(\n \"You are not permitted to operate on specified resource: \" + getRootDir().getAbsolutePath() + \"'.\", ex);\n }\n\n }\n}",
"public enum ScreenshotType implements ResourceType {\n\n JPEG(\"jpeg\"),\n PNG(\"png\"),\n BMP(\"bmp\"),\n WBMP(\"wbmp\"),\n GIF(\"gif\");\n\n private String name;\n\n ScreenshotType(String name) {\n this.name = name;\n }\n\n @Override\n public String toString() {\n return name;\n }\n\n /**\n *\n * @return all screenshot types concatenated to one string separated only by one space from each other\n */\n public static String getAll() {\n StringBuilder sb = new StringBuilder();\n\n for (ScreenshotType screenshotType : ScreenshotType.values()) {\n sb.append(screenshotType.toString());\n sb.append(\" \");\n }\n\n return sb.toString().trim();\n }\n\n}",
"public enum BlurLevel {\n NONE {\n @Override\n public BufferedImage blur(BufferedImage image) {\n return image;\n }\n },\n LOW {\n @Override\n public BufferedImage blur(BufferedImage image) {\n return blur(image, 10);\n }\n },\n MEDIUM {\n @Override\n public BufferedImage blur(BufferedImage image) {\n return blur(image, 15);\n }\n },\n HIGH {\n @Override\n public BufferedImage blur(BufferedImage image) {\n return blur(image, 25);\n }\n };\n\n protected BufferedImage blur(BufferedImage srcImage, int radius) {\n BufferedImage destImage = deepCopy(srcImage);\n BoxBlurFilter boxBlurFilter = new BoxBlurFilter();\n boxBlurFilter.setRadius(radius);\n boxBlurFilter.setIterations(3);\n destImage = boxBlurFilter.filter(srcImage, destImage);\n\n return destImage;\n\n }\n\n private static BufferedImage deepCopy(BufferedImage srcImage) {\n ColorModel cm = srcImage.getColorModel();\n boolean isAlphaPremultiplied = cm.isAlphaPremultiplied();\n WritableRaster raster = srcImage.copyData(null);\n return new BufferedImage(cm, raster, isAlphaPremultiplied, null);\n }\n\n public abstract BufferedImage blur(BufferedImage image);\n}",
"public class AfterScreenshotTaken {\n\n private ScreenshotMetaData metaData;\n\n public AfterScreenshotTaken(ScreenshotMetaData metaData) {\n Validate.notNull(metaData, \"Meta data is a null object\");\n\n this.metaData = metaData;\n }\n\n public ScreenshotMetaData getMetaData() {\n return metaData;\n }\n\n public void setMetaData(ScreenshotMetaData metaData) {\n Validate.notNull(metaData, \"Meta data is a null object.\");\n this.metaData = metaData;\n }\n\n}",
"public class BeforeScreenshotTaken {\n\n private ScreenshotMetaData metaData;\n\n public BeforeScreenshotTaken(ScreenshotMetaData metaData) {\n Validate.notNull(metaData, \"Meta data is a null object!\");\n\n this.metaData = metaData;\n }\n\n public ScreenshotMetaData getMetaData() {\n return metaData;\n }\n\n public void setMetaData(ScreenshotMetaData metaData) {\n Validate.notNull(metaData, \"Meta data is a null object!\");\n this.metaData = metaData;\n }\n\n}",
"public class TakeScreenshot {\n\n private When when;\n\n private Screenshot screenshot;\n\n private ScreenshotMetaData metaData;\n\n private String fileName;\n\n private final org.arquillian.extension.recorder.screenshooter.api.Screenshot annotation;\n\n public TakeScreenshot(String fileName, ScreenshotMetaData metaData, When when, org.arquillian.extension.recorder.screenshooter.api.Screenshot annotation) {\n Validate.notNull(fileName, \"File name is a null object!\");\n Validate.notNull(metaData, \"Meta data is a null object!\");\n Validate.notNull(when, \"When is a null object!\");\n this.metaData = metaData;\n this.when = when;\n this.fileName = fileName;\n this.annotation = annotation;\n }\n\n public Screenshot getScreenshot() {\n return screenshot;\n }\n\n public void setScreenshot(Screenshot screenshot) {\n this.screenshot = screenshot;\n }\n\n public ScreenshotMetaData getMetaData() {\n return metaData;\n }\n\n public void setMetaData(ScreenshotMetaData metaData) {\n Validate.notNull(metaData, \"Meta data is a null object!\");\n this.metaData = metaData;\n }\n\n public When getWhen() {\n return when;\n }\n\n public void setWhen(When when) {\n this.when = when;\n }\n\n public String getFileName() {\n return fileName;\n }\n\n public org.arquillian.extension.recorder.screenshooter.api.Screenshot getAnnotation() {\n return annotation;\n }\n\n public void setFileName(String fileName) {\n Validate.notNull(fileName, \"File name is a null object!\");\n this.fileName = fileName;\n }\n}"
] | import org.arquillian.extension.recorder.DefaultFileNameBuilder;
import org.arquillian.extension.recorder.RecorderStrategy;
import org.arquillian.extension.recorder.RecorderStrategyRegister;
import org.arquillian.extension.recorder.When;
import org.arquillian.extension.recorder.screenshooter.AnnotationScreenshootingStrategy;
import org.arquillian.extension.recorder.screenshooter.Screenshooter;
import org.arquillian.extension.recorder.screenshooter.ScreenshooterConfiguration;
import org.arquillian.extension.recorder.screenshooter.ScreenshotMetaData;
import org.arquillian.extension.recorder.screenshooter.ScreenshotType;
import org.arquillian.extension.recorder.screenshooter.api.Blur;
import org.arquillian.extension.recorder.screenshooter.api.BlurLevel;
import org.arquillian.extension.recorder.screenshooter.api.Screenshot;
import org.arquillian.extension.recorder.screenshooter.event.AfterScreenshotTaken;
import org.arquillian.extension.recorder.screenshooter.event.BeforeScreenshotTaken;
import org.arquillian.extension.recorder.screenshooter.event.TakeScreenshot;
import org.jboss.arquillian.core.api.Event;
import org.jboss.arquillian.core.api.Instance;
import org.jboss.arquillian.core.api.annotation.Inject;
import org.jboss.arquillian.core.api.annotation.Observes;
import org.jboss.arquillian.test.spi.TestClass;
import org.jboss.arquillian.test.spi.TestResult;
import org.jboss.arquillian.test.spi.event.suite.AfterTestLifecycleEvent;
import org.jboss.arquillian.test.spi.event.suite.Before;
import org.jboss.arquillian.test.spi.event.suite.TestEvent;
import org.jboss.arquillian.test.spi.event.suite.TestLifecycleEvent; | /*
* JBoss, Home of Professional Open Source
* Copyright 2013, Red Hat, Inc. and/or its affiliates, and individual
* contributors by the @authors tag. See the copyright.txt in the
* distribution for a full listing of individual contributors.
*
* 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 org.arquillian.extension.recorder.screenshooter.impl;
/**
* @author <a href="mailto:[email protected]">Stefan Miklosovic</a>
* @author <a href="mailto:[email protected]">Juraj Huska</a>
*/
public class ScreenshooterLifecycleObserver {
@Inject | private Instance<RecorderStrategyRegister> recorderStrategyRegister; | 1 |
ZhangFly/WTFSocket_Server_JAVA | src/wtf/socket/WTFSocketServer.java | [
"public interface WTFSocketController {\n\n /**\n * 控制器优先级\n * 数值越低优先级越高,默认的优先级为 WTFSocketPriority.MEDIUM\n *\n * @return 优先级数值\n */\n default int priority() {\n return WTFSocketPriority.MEDIUM;\n }\n\n /**\n * 是否响应该消息\n *\n * @param msg 消息对象\n *\n * @return 是否响应\n */\n boolean isResponse(WTFSocketMsg msg);\n\n /**\n * 控制器工作函数\n * 当控制器的isResponse()方法为true时调用\n * 当控制器工作完成后如果返回true表示该请求被消费,请求传递终止\n * 否则请求继续向下传递\n *\n * @param source 消息发送源\n * @param request 请求消息\n * @param responses 回复消息列表\n *\n * @return 请求是否被消费\n *\n * @throws WTFSocketException 异常消息\n */\n boolean work(WTFSocketRoutingItem source, WTFSocketMsg request, List<WTFSocketMsg> responses) throws WTFSocketException;\n\n}",
"@Component(\"wtf.socket.controllersGroup\")\n@Scope(\"prototype\")\npublic class WTFSocketControllersGroup implements WTFSocketHandler {\n\n private static final Log logger = LogFactory.getLog(WTFSocketControllersGroup.class);\n\n private Queue<WTFSocketController> controllers = new PriorityQueue<>(Comparator.comparingInt(WTFSocketController::priority));\n private WTFSocketControllersGroup dependence = null;\n\n /**\n * 在dependence的基础上创建一个新的升级版控制器组\n * 新的控制器组继承所有dependence中已添加的控制器\n * 当升级版控制器中的控制器不响应请求时\n * 会继续在dependence中继续询问\n *\n * @param dependence 老控制器组\n *\n * @return 升级版控制器组\n */\n public static WTFSocketControllersGroup depends(WTFSocketControllersGroup dependence) {\n return dependence.upgrade();\n }\n\n\n /**\n * 从Spring已注册的Bean中添加控制器\n */\n public void addControllerFromSpringBeans(WTFSocketServer context) {\n final ApplicationContext applicationContext = new ClassPathXmlApplicationContext(context.getConfig().getSpringPath());\n applicationContext.getBeansOfType(WTFSocketController.class)\n .forEach((key, value) -> addController(value));\n }\n\n /**\n * 添加一个控制器\n *\n * @param controller 控制器\n *\n * @return 控制器组自身\n */\n public WTFSocketControllersGroup addController(WTFSocketController controller) {\n controllers.add(controller);\n logger.info(\"WTFSocketServer mapped controller [\" + controller.getClass().getName() + \"]\");\n return this;\n }\n\n /**\n * 创建一个新的升级版控制器组\n * 新的控制器组继承所有现控制器组中已添加的控制器\n * 当升级版控制器中的控制器不响应请求时\n * 会继续在现控制器中继续询问\n *\n * @return 升级版控制器组\n */\n public WTFSocketControllersGroup upgrade() {\n final WTFSocketControllersGroup upgradeGroup = new WTFSocketControllersGroup();\n upgradeGroup.dependence = this;\n return upgradeGroup;\n }\n\n @Override\n public void handle(WTFSocketRoutingItem item, WTFSocketMsg request, List<WTFSocketMsg> responses) throws WTFSocketException {\n for (WTFSocketController controller : controllers) {\n if (controller.isResponse(request)) {\n if (controller.work(item, request, responses))\n break;\n }\n }\n if (dependence != null) dependence.handle(item, request, responses);\n }\n}",
"@Component\n@Scope(\"prototype\")\npublic class WTFSocketEventListenersGroup {\n\n private final Map<WTFSocketEventsType, Set<WTFSocketEventListener>> group = new HashMap<WTFSocketEventsType, Set<WTFSocketEventListener>>(WTFSocketEventsType.values().length) {{\n for (WTFSocketEventsType eventsType : WTFSocketEventsType.values()) {\n put(eventsType, new HashSet<>(1));\n }\n }};\n\n /**\n * 添加事件监听者\n *\n * @param eventListener 监听者\n * @param eventsType 事件类型\n */\n public void addEventListener(WTFSocketEventListener eventListener, WTFSocketEventsType eventsType) {\n group.get(eventsType).add(eventListener);\n }\n\n /**\n * 移除事件监听者\n *\n * @param eventListener 监听者\n * @param eventsType 事件类型\n */\n public void removeEventListener(WTFSocketEventListener eventListener, WTFSocketEventsType eventsType) {\n group.get(eventsType).remove(eventListener);\n }\n\n /**\n * 发生某类型事件\n *\n * @param item 发送源客户端\n * @param info 附加消息\n * @param eventsType 事件类型\n *\n * @throws WTFSocketException 异常信息\n */\n public void publishEvent(WTFSocketRoutingItem item, Object info, WTFSocketEventsType eventsType) throws WTFSocketException {\n for (WTFSocketEventListener eventListener : group.get(eventsType)) {\n eventListener.eventOccurred(item, info);\n }\n }\n\n}",
"@Component\n@Scope(\"prototype\")\npublic class WTFSocketProtocolFamily {\n\n /**\n * 解析器列表\n */\n private Queue<WTFSocketProtocolParser> parsers = new PriorityQueue<WTFSocketProtocolParser>(Comparator.comparingInt(WTFSocketProtocolParser::getPriority)) {{\n add(new WTFSocketDefaultProtocolParser());\n }};\n\n /**\n * 选择解析器从字符串数据中解析出消息对象\n *\n * @param data 字符串数据\n *\n * @return 消息对象\n *\n * @throws WTFSocketProtocolBrokenException 消息格式错误\n * @throws WTFSocketProtocolUnsupportedException 没有适合的解析器\n */\n public WTFSocketMsg parse(String data) throws WTFSocketProtocolBrokenException, WTFSocketProtocolUnsupportedException {\n for (WTFSocketProtocolParser parser : parsers) {\n if (parser.isResponse(data)) {\n return parser.parse(data);\n }\n }\n throw new WTFSocketProtocolUnsupportedException(\"There was no protocol parser to convert string to message\");\n }\n\n /**\n * 选择解析器将消息对象打包为字符串数据\n *\n * @param msg 消息对象\n *\n * @return 字符串数据\n */\n public String parse(WTFSocketMsg msg) throws WTFSocketProtocolUnsupportedException {\n for (WTFSocketProtocolParser parser : parsers) {\n if (parser.isResponse(msg)) {\n return parser.parse(msg);\n }\n }\n throw new WTFSocketProtocolUnsupportedException(\"There was no protocol parser to convert message to string\");\n }\n\n /**\n * 注册解析器\n *\n * @param parser 要解析器对象\n */\n public void registerParser(WTFSocketProtocolParser parser) {\n parsers.add(parser);\n }\n\n /**\n * 注销解析器\n *\n * @param parser 要解析器对象\n */\n public void unRegisterParser(WTFSocketProtocolParser parser) {\n parsers.remove(parser);\n }\n\n /**\n * 清空所以解析器\n */\n public void clear() {\n parsers.clear();\n }\n\n}",
"@Component\n@Scope(\"prototype\")\npublic class WTFSocketRouting {\n\n private WTFSocketServer context;\n\n private final WTFSocketRoutingItemMap<WTFSocketRoutingTmpItem> tmpMap = new WTFSocketRoutingItemMap<>();\n\n private final WTFSocketRoutingItemMap<WTFSocketRoutingFormalItem> formalMap = new WTFSocketRoutingItemMap<>();\n\n private final WTFSocketRoutingItemMap<WTFSocketRoutingDebugItem> debugMap = new WTFSocketRoutingItemMap<WTFSocketRoutingDebugItem>();\n\n public WTFSocketRouting() {\n try {\n final WTFSocketRoutingFormalItem serverItem = new WTFSocketRoutingFormalItem();\n serverItem.setTerm(new WTFSocketDefaultIOTerm());\n serverItem.setContext(context);\n serverItem.setAddress(\"server\");\n serverItem.setCover(false);\n serverItem.addAuthTarget(\"*\");\n formalMap.add(serverItem);\n } catch (WTFSocketException e) {\n e.printStackTrace();\n }\n }\n\n /**\n * 新注册的终端只能被加入临时表\n *\n * @param term 连接终端\n */\n public void register(WTFSocketIOTerm term) throws WTFSocketException {\n final WTFSocketRoutingTmpItem item = new WTFSocketRoutingTmpItem();\n item.setTerm(term);\n item.setContext(context);\n item.open();\n }\n\n public void unRegister(WTFSocketIOTerm term) throws WTFSocketException {\n for (WTFSocketRoutingItemMap map : values()) {\n if (map.contains(term.getIoTag())) {\n map.getItem(term.getIoTag()).close();\n }\n }\n }\n\n public WTFSocketRoutingItemMap<WTFSocketRoutingTmpItem> getTmpMap() {\n return tmpMap;\n }\n\n public WTFSocketRoutingItemMap<WTFSocketRoutingFormalItem> getFormalMap() {\n return formalMap;\n }\n\n public WTFSocketRoutingItemMap<WTFSocketRoutingDebugItem> getDebugMap() {\n return debugMap;\n }\n\n public WTFSocketRoutingTmpItem newTmpItem() {\n return context.getSpring().getBean(WTFSocketRoutingTmpItem.class);\n }\n\n public WTFSocketRoutingItem getItem(String key) {\n if (formalMap.contains(key))\n return formalMap.getItem(key);\n if (debugMap.contains(key))\n return debugMap.getItem(key);\n return tmpMap.getItem(key);\n }\n\n public boolean contains(String key) {\n return formalMap.contains(key) || debugMap.contains(key) || tmpMap.contains(key);\n }\n\n\n public WTFSocketRoutingItemMap[] values() {\n return new WTFSocketRoutingItemMap[]{tmpMap, formalMap, debugMap};\n }\n\n public void setContext(WTFSocketServer context) {\n this.context = context;\n }\n}",
"@Component\n@Scope(\"prototype\")\npublic class WTFSocketScheduler {\n\n private WTFSocketServer context;\n\n /**\n * 消息处理接口\n * 默认使用WTFSocketControllersGroup\n */\n @Resource(name = \"wtf.socket.controllersGroup\")\n private WTFSocketHandler handler;\n\n /**\n * 接收到消息时进行的安全检查\n */\n @Resource(name = \"wtf.socket.secure.onReceive\")\n private WTFSocketSecureStrategy onReceiveSecureStrategy;\n\n /**\n * 发送消息前进行的安全检查\n */\n @Resource(name = \"wtf.socket.secure.beforeSend\")\n private WTFSocketSecureStrategy beforeSendSecureStrategy;\n\n /**\n * io层启动器\n * 默认使用NettyBooter\n */\n @Resource(name = \"wtf.socket.nettyBooter\")\n private WTFSocketIOBooter ioBooter;\n\n /**\n * 向服务器提交一个数据包\n * 一般是有io层发起\n *\n * @param packet 数据包\n * @param ioTag 提交数据包的io的标记\n * @param connectType 提交数据的io的连接类型\n * @throws WTFSocketFatalException 致命异常\n */\n public void submit(String packet, String ioTag, String connectType) throws WTFSocketException {\n try {\n final WTFSocketMsg msg = context.getProtocolFamily().parse(packet);\n msg.setConnectType(connectType);\n msg.setIoTag(ioTag);\n\n final WTFSocketRoutingItem item = context.getRouting().getItem(ioTag);\n context.getEventsGroup().publishEvent(item, msg, WTFSocketEventsType.OnReceiveData);\n\n if (null != onReceiveSecureStrategy)\n onReceiveSecureStrategy.check(context, msg);\n\n if (context.getConfig().isUseDebug())\n WTFSocketLogUtils.received(context, packet, msg);\n\n final List<WTFSocketMsg> responses = new LinkedList<>();\n if (handler != null)\n handler.handle(item, msg, responses);\n\n sendMsg(responses);\n } catch (WTFSocketNormalException e) {\n if (e.getOriginalMsg() != null) {\n final WTFSocketMsg errResponse = e.getOriginalMsg().makeResponse();\n errResponse.setFrom(\"server\");\n errResponse.setState(e.getErrCode());\n errResponse.setBody(new JSONObject() {{\n put(\"cause\", e.getMessage());\n }});\n\n final String data = context.getProtocolFamily().parse(errResponse);\n if (context.getRouting().getFormalMap().contains(errResponse.getTo())) {\n context.getRouting().getFormalMap().getItem(errResponse.getTo()).getTerm().write(data + context.getConfig().getFirstEOT());\n }\n\n if (context.getConfig().isUseDebug())\n WTFSocketLogUtils.exception(context, data, errResponse);\n } else {\n context.getRouting().getItem(ioTag).getTerm().write(e.getMessage() + context.getConfig().getFirstEOT());\n }\n }\n }\n\n /**\n * 发送消息\n *\n * @param msg 消息对象\n * @throws WTFSocketInvalidSourceException 无效的消息源\n * @throws WTFSocketInvalidTargetException 无效的消息目标\n * @throws WTFSocketProtocolUnsupportedException 不被支持的协议\n * @throws WTFSocketPermissionDeniedException 无发送权限\n */\n public void sendMsg(WTFSocketMsg msg) throws WTFSocketException {\n\n if (null != beforeSendSecureStrategy)\n beforeSendSecureStrategy.check(context, msg);\n\n final WTFSocketRoutingItem target = context.getRouting().getItem(msg.getTo());\n msg.setVersion(target.getAccept());\n\n final String data = context.getProtocolFamily().parse(msg);\n\n context.getEventsGroup().publishEvent(target, msg, WTFSocketEventsType.BeforeSendData);\n\n if (context.getConfig().isUseDebug())\n WTFSocketLogUtils.forwarded(context, data, msg);\n\n target.getTerm().write(data + context.getConfig().getFirstEOT());\n }\n\n /**\n * 发送一组消息\n *\n * @param msgs 消息对象数组\n * @throws WTFSocketInvalidSourceException 无效的消息源\n * @throws WTFSocketInvalidTargetException 无效的消息目标\n * @throws WTFSocketProtocolUnsupportedException 不被支持的协议\n * @throws WTFSocketPermissionDeniedException 无发送权限\n */\n public void sendMsg(List<WTFSocketMsg> msgs) throws WTFSocketException {\n for (WTFSocketMsg protocol : msgs) {\n sendMsg(protocol);\n }\n }\n\n /**\n * 添加处理器\n *\n * @param handler 处理器\n */\n public void setHandler(WTFSocketHandler handler) {\n this.handler = handler;\n }\n\n /**\n * 获取处理器\n *\n * @return 处理器\n */\n public WTFSocketHandler getHandler() {\n return handler;\n }\n\n /**\n * 启动框架调度器\n */\n public void run() {\n assert context.getConfig() != null;\n\n // 如果可能,使用spring扫描加载控制器\n if (context.getSpring().getResource(context.getConfig().getSpringPath()).exists() && handler instanceof WTFSocketControllersGroup)\n ((WTFSocketControllersGroup) handler).addControllerFromSpringBeans(context);\n\n // 如果需要,加载消息转发控制器\n if (context.getConfig().isUseMsgForward() && handler instanceof WTFSocketControllersGroup)\n ((WTFSocketControllersGroup) handler).addController(WTFSocketControllers.msgForwardingController());\n\n // 启动io层\n ioBooter.work(new HashMap<String, Object>() {{\n put(\"tcpPort\", context.getConfig().getTcpPort());\n put(\"webSocketPort\", context.getConfig().getWebSocketPort());\n put(\"keepAlive\", context.getConfig().isKeepAlive());\n put(\"context\", context);\n }});\n\n // 如果需要开启临时用户清理任务\n if (context.getConfig().isCleanEmptyConnect()) {\n Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(\n () -> context.getRouting().getTmpMap().values().stream()\n .filter(WTFSocketRoutingTmpItem::isExpires)\n .forEach(item -> {\n item.getTerm().close();\n context.getRouting().getTmpMap().remove(item);\n }),\n 1, 1, TimeUnit.MINUTES);\n }\n }\n\n public void setContext(WTFSocketServer context) {\n this.context = context;\n }\n\n public void setOnReceiveSecureStrategy(WTFSocketSecureStrategy onReceiveSecureStrategy) {\n this.onReceiveSecureStrategy = onReceiveSecureStrategy;\n }\n\n public WTFSocketSecureStrategy getOnReceiveSecureStrategy() {\n return onReceiveSecureStrategy;\n }\n\n public void setBeforeSendSecureStrategy(WTFSocketSecureStrategy beforeSendSecureStrategy) {\n this.beforeSendSecureStrategy = beforeSendSecureStrategy;\n }\n\n public WTFSocketSecureStrategy getBeforeSendSecureStrategy() {\n return beforeSendSecureStrategy;\n }\n\n public void setIoBooter(WTFSocketIOBooter ioBooter) {\n if (ioBooter != null)\n this.ioBooter = ioBooter;\n }\n}",
"@Component\n@Scope(\"prototype\")\npublic class WTFSocketSecureDelegatesGroup {\n\n private final Map<WTFSocketSecureDelegateType, WTFSocketSecureDelegate> group = new HashMap<>(WTFSocketEventsType.values().length);\n\n /**\n * 安全代理\n *\n * @param delegate 代理\n * @param type 代理类型\n */\n public void addDelegate(WTFSocketSecureDelegate delegate, WTFSocketSecureDelegateType type) {\n group.put(type, delegate);\n }\n\n /**\n * 移除安全代理\n *\n * @param type 代理类型\n */\n public void removeDelegate(WTFSocketSecureDelegateType type) {\n group.remove(type);\n }\n\n /**\n * 获取安全代理\n *\n * @param type 代理类型\n *\n * @return 代理\n */\n public WTFSocketSecureDelegate getDelegate(WTFSocketSecureDelegateType type) {\n return group.get(type);\n }\n}"
] | import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import wtf.socket.controller.WTFSocketController;
import wtf.socket.controller.WTFSocketControllersGroup;
import wtf.socket.event.WTFSocketEventListenersGroup;
import wtf.socket.protocol.WTFSocketProtocolFamily;
import wtf.socket.routing.WTFSocketRouting;
import wtf.socket.schedule.WTFSocketScheduler;
import wtf.socket.secure.delegate.WTFSocketSecureDelegatesGroup;
import javax.annotation.Resource; | package wtf.socket;
/**
* WTFSocket服务器
* <p>
* Created by ZFly on 2017/4/25.
*/
public final class WTFSocketServer {
/**
* Spring 上下文
*/
private ApplicationContext spring = new ClassPathXmlApplicationContext("spring.wtf.socket.xml");
/**
* 消息调度组件
* 根据消息的头信息将消息投递到指定的目的地
*/
@Resource()
private WTFSocketScheduler scheduler;
/**
* 路由组件
* 查询和记录连接的地址
*/
@Resource
private WTFSocketRouting routing;
/**
* 协议族组件
* IO层收到数据后选择合适的解析器将数据解析为标准消息格式
*/
@Resource | private WTFSocketProtocolFamily protocolFamily; | 3 |