repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
consulo/consulo | modules/base/platform-impl/src/main/java/consulo/ide/plugins/PluginsConfigurable.java | 3255 | /*
* Copyright 2013-2020 consulo.io
*
* 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 consulo.ide.plugins;
import com.intellij.ide.IdeBundle;
import com.intellij.openapi.options.Configurable;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.options.SearchableConfigurable;
import consulo.container.plugin.PluginId;
import consulo.disposer.Disposable;
import consulo.disposer.Disposer;
import consulo.ui.annotation.RequiredUIAccess;
import jakarta.inject.Inject;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.swing.*;
/**
* @author VISTALL
* @since 2020-06-26
*/
public class PluginsConfigurable implements SearchableConfigurable, Configurable.NoScroll, Configurable.HoldPreferredFocusedComponent, Configurable.NoMargin {
public static final String ID = "platformAndPlugins";
private PluginsPanel myPanel;
@Inject
public PluginsConfigurable() {
}
@RequiredUIAccess
@Nullable
@Override
public JComponent createComponent(@Nonnull Disposable parentDisposable) {
if (myPanel == null) {
myPanel = new PluginsPanel();
Disposer.register(parentDisposable, myPanel);
}
return myPanel.getComponent();
}
@Override
public String getDisplayName() {
return IdeBundle.message("title.plugins");
}
@Nullable
@Override
public String getHelpTopic() {
String suffix = "";
if (myPanel != null) {
int selectedIndex = myPanel.getSelectedIndex();
switch (selectedIndex) {
case PluginsPanel.INSTALLED:
suffix = "/#installed";
break;
case PluginsPanel.FROM_REPOSITORY:
suffix = "/#from-repository";
break;
}
}
return getId() + suffix;
}
@Nonnull
@Override
public String getId() {
return ID;
}
@RequiredUIAccess
@Override
public boolean isModified() {
return myPanel != null && myPanel.isModified();
}
@RequiredUIAccess
@Override
public void apply() throws ConfigurationException {
if (myPanel != null) {
myPanel.apply();
}
}
@RequiredUIAccess
@Override
public void reset() {
if (myPanel != null) {
myPanel.reset();
}
}
@RequiredUIAccess
@Override
public void disposeUIResources() {
myPanel = null;
}
@Override
@Nullable
public Runnable enableSearch(final String option) {
return () -> {
if (myPanel != null) myPanel.filter(option);
};
}
public void selectInstalled(PluginId pluginId) {
myPanel.selectInstalled(pluginId);
}
public void selectAvailable(PluginId pluginId) {
myPanel.selectAvailable(pluginId);
}
public void select(PluginId pluginId) {
myPanel.getSelected().select(pluginId);
}
}
| apache-2.0 |
JohannesKlug/hbird | src/transport/protocols/src/main/java/org/hbird/transport/protocols/kiss/KissConstants.java | 2101 | package org.hbird.transport.protocols.kiss;
public final class KissConstants {
/** Frame end */
public static final byte FEND = (byte) 0xC0;
/** Frame escape */
public static final byte FESC = (byte) 0xDB;
/** Transposed frame end */
public static final byte TFEND = (byte) 0xDC;
/** Transposed frame escape */
public static final byte TFESC = (byte) 0xDD;
/**
* The id of the data frame TNC type. The rest of the frame is data to be sent on the HDLC channel. Default port 0.
* You must edit at the nibble level to send data to a different port.
*/
public static final byte DATA_FRAME = (byte) 0x00;
/**
* The next byte is the transmitter keyup delay in 10 ms units. The default start-up value is 50 (i.e., 500 ms).
*/
public static final byte TX_DELAY = (byte) 1;
/**
* The next byte is the persistence parameter, p, scaled to the range 0 - 255 with the following formula: P = p *
* 256 - 1
*
* The default value is P = 63 (i.e., p = 0.25).
*/
public static final byte P = (byte) 2;
/**
* The next byte is the slot interval in 10 ms units. The default is 10 (i.e., 100ms).
*/
public static final byte SLOT_TIME = (byte) 3;
/**
* The next byte is the time to hold up the TX after the FCS has been sent, in 10 ms units. This command is
* obsolete, and is included here only for compatibility with some existing implementations.
*/
public static final byte TX_TAIL = (byte) 4;
/**
* The next byte is 0 for half duplex, nonzero for full duplex. The default is 0 (i.e., half duplex).
*/
public static final byte FULL_DUPLEX = (byte) 5;
/**
* Specific for each TNC. In the TNC-1, this command sets the modem speed. Other implementations may use this
* function for other hardware-specific functions.
*/
public static final byte SET_HARDWARE = (byte) 6;
/**
* Exit KISS and return control to a higher-level program. This is useful only when KISS is incorporated into the
* TNC along with other applications.
*/
public static final byte RETURN = (byte) 0x0F;
private KissConstants() {
// Constants class, utility.
}
}
| apache-2.0 |
omindra/schema_org_java_api | core_with_extensions/src/main/java/org/schema/api/model/thing/place/civicStructure/Bridge.java | 290 | package org.schema.api.model.thing.place.civicStructure;
public class Bridge extends CivicStructure
{
private String openingHours;
public String getOpeningHours()
{
return openingHours;
}
public void setOpeningHours(String openingHours)
{
this.openingHours = openingHours;
}
} | apache-2.0 |
dlbunker/ps-guitar-rest | src/main/java/com/guitar/config/JpaConfiguration.java | 280 | package com.guitar.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
@Configuration
@EnableJpaRepositories(basePackages={"com.guitar.repository"})
public class JpaConfiguration {
}
| apache-2.0 |
ReactiveX/RxJava | src/test/java/io/reactivex/rxjava3/internal/operators/observable/ObservableFromMaybeTest.java | 2547 | /*
* Copyright (c) 2016-present, RxJava 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 io.reactivex.rxjava3.internal.operators.observable;
import static org.junit.Assert.*;
import org.junit.Test;
import io.reactivex.rxjava3.core.*;
import io.reactivex.rxjava3.exceptions.TestException;
import io.reactivex.rxjava3.observers.TestObserver;
import io.reactivex.rxjava3.operators.QueueFuseable;
import io.reactivex.rxjava3.subjects.MaybeSubject;
import io.reactivex.rxjava3.testsupport.TestObserverEx;
public class ObservableFromMaybeTest extends RxJavaTest {
@Test
public void success() {
Observable.fromMaybe(Maybe.just(1).hide())
.test()
.assertResult(1);
}
@Test
public void empty() {
Observable.fromMaybe(Maybe.empty().hide())
.test()
.assertResult();
}
@Test
public void error() {
Observable.fromMaybe(Maybe.error(new TestException()).hide())
.test()
.assertFailure(TestException.class);
}
@Test
public void cancelComposes() {
MaybeSubject<Integer> ms = MaybeSubject.create();
TestObserver<Integer> to = Observable.fromMaybe(ms)
.test();
to.assertEmpty();
assertTrue(ms.hasObservers());
to.dispose();
assertFalse(ms.hasObservers());
}
@Test
public void asyncFusion() {
TestObserverEx<Integer> to = new TestObserverEx<>();
to.setInitialFusionMode(QueueFuseable.ASYNC);
Observable.fromMaybe(Maybe.just(1))
.subscribe(to);
to
.assertFuseable()
.assertFusionMode(QueueFuseable.ASYNC)
.assertResult(1);
}
@Test
public void syncFusionRejected() {
TestObserverEx<Integer> to = new TestObserverEx<>();
to.setInitialFusionMode(QueueFuseable.SYNC);
Observable.fromMaybe(Maybe.just(1))
.subscribe(to);
to
.assertFuseable()
.assertFusionMode(QueueFuseable.NONE)
.assertResult(1);
}
}
| apache-2.0 |
trialmanager/voxce | src/com/Voxce/model/LabelTexts.java | 2089 | package com.Voxce.model;
import java.sql.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="label_texts")
public class LabelTexts {
private int label_text_id;
private int language_id;
private String code;
private String name;
private String text;
private int created_by;
private Date date_created;
private int modified_by;
private Date date_modified;
@Id
@GeneratedValue
@Column(name="label_text_id")
public int getLabel_text_id() {
return label_text_id;
}
public void setLabel_text_id(int label_text_id) {
this.label_text_id = label_text_id;
}
@Column(name="language_id")
public int getLanguage_id() {
return language_id;
}
public void setLanguage_id(int language_id) {
this.language_id = language_id;
}
@Column(name="code")
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
@Column(name="name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Column(name="text")
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
@Column(name="created_by")
public int getCreated_by() {
return created_by;
}
public void setCreated_by(int created_by) {
this.created_by = created_by;
}
@Column(name="date_created")
public Date getDate_created() {
return date_created;
}
public void setDate_created(Date date_created) {
this.date_created = date_created;
}
@Column(name="modified_by")
public int getModified_by() {
return modified_by;
}
public void setModified_by(int modified_by) {
this.modified_by = modified_by;
}
@Column(name="date_modified")
public Date getDate_modified() {
return date_modified;
}
public void setDate_modified(Date date_modified) {
this.date_modified = date_modified;
}
}
| apache-2.0 |
vocefiscal/vocefiscal-android | Code/src/org/vocefiscal/asynctasks/AsyncTask.java | 27929 | /*
* Copyright (C) 2008 The Android Open Source Project
*
* 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.vocefiscal.asynctasks;
import java.util.ArrayDeque;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import org.vocefiscal.bitmaps.Utils;
import android.annotation.TargetApi;
import android.os.Handler;
import android.os.Message;
import android.os.Process;
/**
* *************************************
* Copied from JB release framework:
* https://android.googlesource.com/platform/frameworks/base/+/jb-release/core/java/android/os/AsyncTask.java
*
* so that threading behavior on all OS versions is the same and we can tweak behavior by using
* executeOnExecutor() if needed.
*
* There are 3 changes in this copy of AsyncTask:
* -pre-HC a single thread executor is used for serial operation
* (Executors.newSingleThreadExecutor) and is the default
* -the default THREAD_POOL_EXECUTOR was changed to use DiscardOldestPolicy
* -a new fixed thread pool called DUAL_THREAD_EXECUTOR was added
* *************************************
*
* <p>AsyncTask enables proper and easy use of the UI thread. This class allows to
* perform background operations and publish results on the UI thread without
* having to manipulate threads and/or handlers.</p>
*
* <p>AsyncTask is designed to be a helper class around {@link Thread} and {@link android.os.Handler}
* and does not constitute a generic threading framework. AsyncTasks should ideally be
* used for short operations (a few seconds at the most.) If you need to keep threads
* running for long periods of time, it is highly recommended you use the various APIs
* provided by the <code>java.util.concurrent</code> pacakge such as {@link java.util.concurrent.Executor},
* {@link java.util.concurrent.ThreadPoolExecutor} and {@link java.util.concurrent.FutureTask}.</p>
*
* <p>An asynchronous task is defined by a computation that runs on a background thread and
* whose result is published on the UI thread. An asynchronous task is defined by 3 generic
* types, called <code>Params</code>, <code>Progress</code> and <code>Result</code>,
* and 4 steps, called <code>onPreExecute</code>, <code>doInBackground</code>,
* <code>onProgressUpdate</code> and <code>onPostExecute</code>.</p>
*
* <div class="special reference">
* <h3>Developer Guides</h3>
* <p>For more information about using tasks and threads, read the
* <a href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html">Processes and
* Threads</a> developer guide.</p>
* </div>
*
* <h2>Usage</h2>
* <p>AsyncTask must be subclassed to be used. The subclass will override at least
* one method ({@link #doInBackground}), and most often will override a
* second one ({@link #onPostExecute}.)</p>
*
* <p>Here is an example of subclassing:</p>
* <pre class="prettyprint">
* private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
* protected Long doInBackground(URL... urls) {
* int count = urls.length;
* long totalSize = 0;
* for (int i = 0; i < count; i++) {
* totalSize += Downloader.downloadFile(urls[i]);
* publishProgress((int) ((i / (float) count) * 100));
* // Escape early if cancel() is called
* if (isCancelled()) break;
* }
* return totalSize;
* }
*
* protected void onProgressUpdate(Integer... progress) {
* setProgressPercent(progress[0]);
* }
*
* protected void onPostExecute(Long result) {
* showDialog("Downloaded " + result + " bytes");
* }
* }
* </pre>
*
* <p>Once created, a task is executed very simply:</p>
* <pre class="prettyprint">
* new DownloadFilesTask().execute(url1, url2, url3);
* </pre>
*
* <h2>AsyncTask's generic types</h2>
* <p>The three types used by an asynchronous task are the following:</p>
* <ol>
* <li><code>Params</code>, the type of the parameters sent to the task upon
* execution.</li>
* <li><code>Progress</code>, the type of the progress units published during
* the background computation.</li>
* <li><code>Result</code>, the type of the result of the background
* computation.</li>
* </ol>
* <p>Not all types are always used by an asynchronous task. To mark a type as unused,
* simply use the type {@link Void}:</p>
* <pre>
* private class MyTask extends AsyncTask<Void, Void, Void> { ... }
* </pre>
*
* <h2>The 4 steps</h2>
* <p>When an asynchronous task is executed, the task goes through 4 steps:</p>
* <ol>
* <li>{@link #onPreExecute()}, invoked on the UI thread immediately after the task
* is executed. This step is normally used to setup the task, for instance by
* showing a progress bar in the user interface.</li>
* <li>{@link #doInBackground}, invoked on the background thread
* immediately after {@link #onPreExecute()} finishes executing. This step is used
* to perform background computation that can take a long time. The parameters
* of the asynchronous task are passed to this step. The result of the computation must
* be returned by this step and will be passed back to the last step. This step
* can also use {@link #publishProgress} to publish one or more units
* of progress. These values are published on the UI thread, in the
* {@link #onProgressUpdate} step.</li>
* <li>{@link #onProgressUpdate}, invoked on the UI thread after a
* call to {@link #publishProgress}. The timing of the execution is
* undefined. This method is used to display any form of progress in the user
* interface while the background computation is still executing. For instance,
* it can be used to animate a progress bar or show logs in a text field.</li>
* <li>{@link #onPostExecute}, invoked on the UI thread after the background
* computation finishes. The result of the background computation is passed to
* this step as a parameter.</li>
* </ol>
*
* <h2>Cancelling a task</h2>
* <p>A task can be cancelled at any time by invoking {@link #cancel(boolean)}. Invoking
* this method will cause subsequent calls to {@link #isCancelled()} to return true.
* After invoking this method, {@link #onCancelled(Object)}, instead of
* {@link #onPostExecute(Object)} will be invoked after {@link #doInBackground(Object[])}
* returns. To ensure that a task is cancelled as quickly as possible, you should always
* check the return value of {@link #isCancelled()} periodically from
* {@link #doInBackground(Object[])}, if possible (inside a loop for instance.)</p>
*
* <h2>Threading rules</h2>
* <p>There are a few threading rules that must be followed for this class to
* work properly:</p>
* <ul>
* <li>The AsyncTask class must be loaded on the UI thread. This is done
* automatically as of {@link android.os.Build.VERSION_CODES#JELLY_BEAN}.</li>
* <li>The task instance must be created on the UI thread.</li>
* <li>{@link #execute} must be invoked on the UI thread.</li>
* <li>Do not call {@link #onPreExecute()}, {@link #onPostExecute},
* {@link #doInBackground}, {@link #onProgressUpdate} manually.</li>
* <li>The task can be executed only once (an exception will be thrown if
* a second execution is attempted.)</li>
* </ul>
*
* <h2>Memory observability</h2>
* <p>AsyncTask guarantees that all callback calls are synchronized in such a way that the following
* operations are safe without explicit synchronizations.</p>
* <ul>
* <li>Set member fields in the constructor or {@link #onPreExecute}, and refer to them
* in {@link #doInBackground}.
* <li>Set member fields in {@link #doInBackground}, and refer to them in
* {@link #onProgressUpdate} and {@link #onPostExecute}.
* </ul>
*
* <h2>Order of execution</h2>
* <p>When first introduced, AsyncTasks were executed serially on a single background
* thread. Starting with {@link android.os.Build.VERSION_CODES#DONUT}, this was changed
* to a pool of threads allowing multiple tasks to operate in parallel. Starting with
* {@link android.os.Build.VERSION_CODES#HONEYCOMB}, tasks are executed on a single
* thread to avoid common application errors caused by parallel execution.</p>
* <p>If you truly want parallel execution, you can invoke
* {@link #executeOnExecutor(java.util.concurrent.Executor, Object[])} with
* {@link #THREAD_POOL_EXECUTOR}.</p>
*/
public abstract class AsyncTask<Params, Progress, Result> {
private static final String LOG_TAG = "AsyncTask";
private static final int CORE_POOL_SIZE = 5;
private static final int MAXIMUM_POOL_SIZE = 128;
private static final int KEEP_ALIVE = 1;
private static final ThreadFactory sThreadFactory = new ThreadFactory() {
private final AtomicInteger mCount = new AtomicInteger(1);
@Override
public Thread newThread(Runnable r) {
return new Thread(r, "AsyncTask #" + mCount.getAndIncrement());
}
};
private static final BlockingQueue<Runnable> sPoolWorkQueue =
new LinkedBlockingQueue<Runnable>(10);
/**
* An {@link java.util.concurrent.Executor} that can be used to execute tasks in parallel.
*/
public static final Executor THREAD_POOL_EXECUTOR
= new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE,
TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory,
new ThreadPoolExecutor.DiscardOldestPolicy());
/**
* An {@link java.util.concurrent.Executor} that executes tasks one at a time in serial
* order. This serialization is global to a particular process.
*/
public static final Executor SERIAL_EXECUTOR = Utils.hasHoneycomb() ? new SerialExecutor() :
Executors.newSingleThreadExecutor(sThreadFactory);
public static final Executor DUAL_THREAD_EXECUTOR =
Executors.newFixedThreadPool(2, sThreadFactory);
private static final int MESSAGE_POST_RESULT = 0x1;
private static final int MESSAGE_POST_PROGRESS = 0x2;
private static final InternalHandler sHandler = new InternalHandler();
private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
private final WorkerRunnable<Params, Result> mWorker;
private final FutureTask<Result> mFuture;
private volatile Status mStatus = Status.PENDING;
private final AtomicBoolean mCancelled = new AtomicBoolean();
private final AtomicBoolean mTaskInvoked = new AtomicBoolean();
@TargetApi(11)
private static class SerialExecutor implements Executor {
final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();
Runnable mActive;
@Override
public synchronized void execute(final Runnable r) {
mTasks.offer(new Runnable() {
@Override
public void run() {
try {
r.run();
} finally {
scheduleNext();
}
}
});
if (mActive == null) {
scheduleNext();
}
}
protected synchronized void scheduleNext() {
if ((mActive = mTasks.poll()) != null) {
THREAD_POOL_EXECUTOR.execute(mActive);
}
}
}
/**
* Indicates the current status of the task. Each status will be set only once
* during the lifetime of a task.
*/
public enum Status {
/**
* Indicates that the task has not been executed yet.
*/
PENDING,
/**
* Indicates that the task is running.
*/
RUNNING,
/**
* Indicates that {@link AsyncTask#onPostExecute} has finished.
*/
FINISHED,
}
/** @hide Used to force static handler to be created. */
public static void init() {
sHandler.getLooper();
}
/** @hide */
public static void setDefaultExecutor(Executor exec) {
sDefaultExecutor = exec;
}
/**
* Creates a new asynchronous task. This constructor must be invoked on the UI thread.
*/
public AsyncTask() {
mWorker = new WorkerRunnable<Params, Result>() {
@Override
public Result call() throws Exception {
mTaskInvoked.set(true);
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
//noinspection unchecked
return postResult(doInBackground(mParams));
}
};
mFuture = new FutureTask<Result>(mWorker) {
@Override
protected void done() {
try {
postResultIfNotInvoked(get());
} catch (InterruptedException e) {
//android.util.Log.w(LOG_TAG, e);
} catch (ExecutionException e) {
throw new RuntimeException("An error occured while executing doInBackground()",
e.getCause());
} catch (CancellationException e) {
postResultIfNotInvoked(null);
}
}
};
}
private void postResultIfNotInvoked(Result result) {
final boolean wasTaskInvoked = mTaskInvoked.get();
if (!wasTaskInvoked) {
postResult(result);
}
}
private Result postResult(Result result) {
@SuppressWarnings("unchecked")
Message message = sHandler.obtainMessage(MESSAGE_POST_RESULT,
new AsyncTaskResult<Result>(this, result));
message.sendToTarget();
return result;
}
/**
* Returns the current status of this task.
*
* @return The current status.
*/
public final Status getStatus() {
return mStatus;
}
/**
* Override this method to perform a computation on a background thread. The
* specified parameters are the parameters passed to {@link #execute}
* by the caller of this task.
*
* This method can call {@link #publishProgress} to publish updates
* on the UI thread.
*
* @param params The parameters of the task.
*
* @return A result, defined by the subclass of this task.
*
* @see #onPreExecute()
* @see #onPostExecute
* @see #publishProgress
*/
protected abstract Result doInBackground(Params... params);
/**
* Runs on the UI thread before {@link #doInBackground}.
*
* @see #onPostExecute
* @see #doInBackground
*/
protected void onPreExecute() {
}
/**
* <p>Runs on the UI thread after {@link #doInBackground}. The
* specified result is the value returned by {@link #doInBackground}.</p>
*
* <p>This method won't be invoked if the task was cancelled.</p>
*
* @param result The result of the operation computed by {@link #doInBackground}.
*
* @see #onPreExecute
* @see #doInBackground
* @see #onCancelled(Object)
*/
@SuppressWarnings({"UnusedDeclaration"})
protected void onPostExecute(Result result) {
}
/**
* Runs on the UI thread after {@link #publishProgress} is invoked.
* The specified values are the values passed to {@link #publishProgress}.
*
* @param values The values indicating progress.
*
* @see #publishProgress
* @see #doInBackground
*/
@SuppressWarnings({"UnusedDeclaration"})
protected void onProgressUpdate(Progress... values) {
}
/**
* <p>Runs on the UI thread after {@link #cancel(boolean)} is invoked and
* {@link #doInBackground(Object[])} has finished.</p>
*
* <p>The default implementation simply invokes {@link #onCancelled()} and
* ignores the result. If you write your own implementation, do not call
* <code>super.onCancelled(result)</code>.</p>
*
* @param result The result, if any, computed in
* {@link #doInBackground(Object[])}, can be null
*
* @see #cancel(boolean)
* @see #isCancelled()
*/
@SuppressWarnings({"UnusedParameters"})
protected void onCancelled(Result result) {
onCancelled();
}
/**
* <p>Applications should preferably override {@link #onCancelled(Object)}.
* This method is invoked by the default implementation of
* {@link #onCancelled(Object)}.</p>
*
* <p>Runs on the UI thread after {@link #cancel(boolean)} is invoked and
* {@link #doInBackground(Object[])} has finished.</p>
*
* @see #onCancelled(Object)
* @see #cancel(boolean)
* @see #isCancelled()
*/
protected void onCancelled() {
}
/**
* Returns <tt>true</tt> if this task was cancelled before it completed
* normally. If you are calling {@link #cancel(boolean)} on the task,
* the value returned by this method should be checked periodically from
* {@link #doInBackground(Object[])} to end the task as soon as possible.
*
* @return <tt>true</tt> if task was cancelled before it completed
*
* @see #cancel(boolean)
*/
public final boolean isCancelled() {
return mCancelled.get();
}
/**
* <p>Attempts to cancel execution of this task. This attempt will
* fail if the task has already completed, already been cancelled,
* or could not be cancelled for some other reason. If successful,
* and this task has not started when <tt>cancel</tt> is called,
* this task should never run. If the task has already started,
* then the <tt>mayInterruptIfRunning</tt> parameter determines
* whether the thread executing this task should be interrupted in
* an attempt to stop the task.</p>
*
* <p>Calling this method will result in {@link #onCancelled(Object)} being
* invoked on the UI thread after {@link #doInBackground(Object[])}
* returns. Calling this method guarantees that {@link #onPostExecute(Object)}
* is never invoked. After invoking this method, you should check the
* value returned by {@link #isCancelled()} periodically from
* {@link #doInBackground(Object[])} to finish the task as early as
* possible.</p>
*
* @param mayInterruptIfRunning <tt>true</tt> if the thread executing this
* task should be interrupted; otherwise, in-progress tasks are allowed
* to complete.
*
* @return <tt>false</tt> if the task could not be cancelled,
* typically because it has already completed normally;
* <tt>true</tt> otherwise
*
* @see #isCancelled()
* @see #onCancelled(Object)
*/
public final boolean cancel(boolean mayInterruptIfRunning) {
mCancelled.set(true);
return mFuture.cancel(mayInterruptIfRunning);
}
/**
* Waits if necessary for the computation to complete, and then
* retrieves its result.
*
* @return The computed result.
*
* @throws java.util.concurrent.CancellationException If the computation was cancelled.
* @throws java.util.concurrent.ExecutionException If the computation threw an exception.
* @throws InterruptedException If the current thread was interrupted
* while waiting.
*/
public final Result get() throws InterruptedException, ExecutionException {
return mFuture.get();
}
/**
* Waits if necessary for at most the given time for the computation
* to complete, and then retrieves its result.
*
* @param timeout Time to wait before cancelling the operation.
* @param unit The time unit for the timeout.
*
* @return The computed result.
*
* @throws java.util.concurrent.CancellationException If the computation was cancelled.
* @throws java.util.concurrent.ExecutionException If the computation threw an exception.
* @throws InterruptedException If the current thread was interrupted
* while waiting.
* @throws java.util.concurrent.TimeoutException If the wait timed out.
*/
public final Result get(long timeout, TimeUnit unit) throws InterruptedException,
ExecutionException, TimeoutException {
return mFuture.get(timeout, unit);
}
/**
* Executes the task with the specified parameters. The task returns
* itself (this) so that the caller can keep a reference to it.
*
* <p>Note: this function schedules the task on a queue for a single background
* thread or pool of threads depending on the platform version. When first
* introduced, AsyncTasks were executed serially on a single background thread.
* Starting with {@link android.os.Build.VERSION_CODES#DONUT}, this was changed
* to a pool of threads allowing multiple tasks to operate in parallel. Starting
* {@link android.os.Build.VERSION_CODES#HONEYCOMB}, tasks are back to being
* executed on a single thread to avoid common application errors caused
* by parallel execution. If you truly want parallel execution, you can use
* the {@link #executeOnExecutor} version of this method
* with {@link #THREAD_POOL_EXECUTOR}; however, see commentary there for warnings
* on its use.
*
* <p>This method must be invoked on the UI thread.
*
* @param params The parameters of the task.
*
* @return This instance of AsyncTask.
*
* @throws IllegalStateException If {@link #getStatus()} returns either
* {@link AsyncTask.Status#RUNNING} or {@link AsyncTask.Status#FINISHED}.
*
* @see #executeOnExecutor(java.util.concurrent.Executor, Object[])
* @see #execute(Runnable)
*/
public final AsyncTask<Params, Progress, Result> execute(Params... params) {
return executeOnExecutor(sDefaultExecutor, params);
}
/**
* Executes the task with the specified parameters. The task returns
* itself (this) so that the caller can keep a reference to it.
*
* <p>This method is typically used with {@link #THREAD_POOL_EXECUTOR} to
* allow multiple tasks to run in parallel on a pool of threads managed by
* AsyncTask, however you can also use your own {@link java.util.concurrent.Executor} for custom
* behavior.
*
* <p><em>Warning:</em> Allowing multiple tasks to run in parallel from
* a thread pool is generally <em>not</em> what one wants, because the order
* of their operation is not defined. For example, if these tasks are used
* to modify any state in common (such as writing a file due to a button click),
* there are no guarantees on the order of the modifications.
* Without careful work it is possible in rare cases for the newer version
* of the data to be over-written by an older one, leading to obscure data
* loss and stability issues. Such changes are best
* executed in serial; to guarantee such work is serialized regardless of
* platform version you can use this function with {@link #SERIAL_EXECUTOR}.
*
* <p>This method must be invoked on the UI thread.
*
* @param exec The executor to use. {@link #THREAD_POOL_EXECUTOR} is available as a
* convenient process-wide thread pool for tasks that are loosely coupled.
* @param params The parameters of the task.
*
* @return This instance of AsyncTask.
*
* @throws IllegalStateException If {@link #getStatus()} returns either
* {@link AsyncTask.Status#RUNNING} or {@link AsyncTask.Status#FINISHED}.
*
* @see #execute(Object[])
*/
public final AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec,
Params... params) {
if (mStatus != Status.PENDING) {
switch (mStatus) {
case RUNNING:
throw new IllegalStateException("Cannot execute task:"
+ " the task is already running.");
case FINISHED:
throw new IllegalStateException("Cannot execute task:"
+ " the task has already been executed "
+ "(a task can be executed only once)");
}
}
mStatus = Status.RUNNING;
onPreExecute();
mWorker.mParams = params;
exec.execute(mFuture);
return this;
}
/**
* Convenience version of {@link #execute(Object...)} for use with
* a simple Runnable object. See {@link #execute(Object[])} for more
* information on the order of execution.
*
* @see #execute(Object[])
* @see #executeOnExecutor(java.util.concurrent.Executor, Object[])
*/
public static void execute(Runnable runnable) {
sDefaultExecutor.execute(runnable);
}
/**
* This method can be invoked from {@link #doInBackground} to
* publish updates on the UI thread while the background computation is
* still running. Each call to this method will trigger the execution of
* {@link #onProgressUpdate} on the UI thread.
*
* {@link #onProgressUpdate} will note be called if the task has been
* canceled.
*
* @param values The progress values to update the UI with.
*
* @see #onProgressUpdate
* @see #doInBackground
*/
protected final void publishProgress(Progress... values) {
if (!isCancelled()) {
sHandler.obtainMessage(MESSAGE_POST_PROGRESS,
new AsyncTaskResult<Progress>(this, values)).sendToTarget();
}
}
private void finish(Result result) {
if (isCancelled()) {
onCancelled(result);
} else {
onPostExecute(result);
}
mStatus = Status.FINISHED;
}
private static class InternalHandler extends Handler {
@SuppressWarnings({"unchecked", "RawUseOfParameterizedType"})
@Override
public void handleMessage(Message msg) {
AsyncTaskResult result = (AsyncTaskResult) msg.obj;
switch (msg.what) {
case MESSAGE_POST_RESULT:
// There is only one result
result.mTask.finish(result.mData[0]);
break;
case MESSAGE_POST_PROGRESS:
result.mTask.onProgressUpdate(result.mData);
break;
}
}
}
private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> {
Params[] mParams;
}
@SuppressWarnings({"RawUseOfParameterizedType"})
private static class AsyncTaskResult<Data> {
final AsyncTask mTask;
final Data[] mData;
AsyncTaskResult(AsyncTask task, Data... data) {
mTask = task;
mData = data;
}
}
}
| apache-2.0 |
pjenvey/modjy-pjenvey | test/com/xhaus/modjy/ModjyTestHeaders.java | 5938 | package com.xhaus.modjy;
import com.mockrunner.base.NestedApplicationException;
import org.python.core.PyException;
public class ModjyTestHeaders extends ModjyTestBase
{
// From: http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.5.1
final static String[] hop_by_hop_headers = new String[] {
"connection",
"keep-alive",
"proxy-authenticate",
"proxy-authorization",
"te",
"trailers",
"transfer-encoding",
"upgrade",
};
protected void headerTestSetUp()
throws Exception
{
baseSetUp();
setAppFile("header_tests.py");
}
public void doHeaderTest(String appName, String queryString)
throws Exception
{
headerTestSetUp();
setAppName(appName);
createServlet();
if (queryString != null)
setQueryString(queryString);
doGet();
}
public void doHeaderTest(String appName)
throws Exception
{
doHeaderTest(appName, null);
}
public void testInvalidStatusCode()
throws Exception
{
doHeaderTest("test_invalid_status_code");
assertEquals("Status code != 500: ServerError, =='"+getStatus()+"'", 500, getStatus());
assertTrue("Could not find exception 'BadArgument' in output: " + getOutput(),
getOutput().indexOf("BadArgument")!=-1);
}
public void testNonLatin1StatusString()
throws Exception
{
// We'll let this one pass:
// 1. The integer status code can't be anything but an ASCII-encoded integer
// 2. The reason phrase is discarded on J2EE anyway
// Modjy takes no action if a non latin-1 status string is passed
doHeaderTest("test_non_latin1_status_string");
assertEquals("Status code != 500: ServerError, =='"+getStatus()+"'", 500, getStatus());
assertTrue("Could not find exception 'BadArgument' in output: " + getOutput(),
getOutput().indexOf("BadArgument")!=-1);
}
public void testLatin1StatusStringWithControlChars()
throws Exception
{
// We'll let this one pass:
// 1. The integer status code can't be anything but an ASCII-encoded integer
// 2. The reason phrase is discarded on J2EE anyway
// Modjy takes no action if a status string with control chars is passed
doHeaderTest("test_control_chars_in_status_string");
assertEquals("Status code != 500: ServerError, =='"+getStatus()+"'", 500, getStatus());
assertTrue("Could not find exception 'BadArgument' in output: " + getOutput(),
getOutput().indexOf("BadArgument")!=-1);
}
public void doBadHeadersListTest(String appName)
throws Exception
{
for (int i = 1 ; i < 5 ; i++)
{
doHeaderTest(appName, String.valueOf(i));
assertEquals("Status code != 500: ServerError, =='"+getStatus()+"'", 500, getStatus());
String firstLine = getOutput().split("\n")[0];
assertTrue("Could not find exception 'BadArgument' in output: " + firstLine,
firstLine.indexOf("BadArgument")!=-1);
}
}
public void testHeadersNotList ( )
throws Exception
{
// Ensure that setting headers to anything other than a list raises an error
doBadHeadersListTest("test_headers_not_list");
}
public void testHeadersListContainsNonTuples ( )
throws Exception
{
// Ensure that setting headers to anything other than a list raises an error
doBadHeadersListTest("test_headers_list_non_tuples");
}
public void testHeadersListContainsWrongLengthTuples ( )
throws Exception
{
// Ensure that setting headers to anything other than a list of 2-tuples raises an error
doBadHeadersListTest("test_headers_list_wrong_length_tuples");
}
public void testHeadersListContainsWrongTypeTuples ( )
throws Exception
{
// Ensure that setting headers to anything other than a list of 2-tuples of strings raises an error
doBadHeadersListTest("test_headers_list_wrong_types_in_tuples");
}
public void testHeadersListContainsNonLatin1Values ( )
throws Exception
{
// Ensure that setting header values to non-latin1 strings raises an error
doBadHeadersListTest("test_headers_list_contains_non_latin1_values");
}
public void testHeadersListContainsValuesWithControlChars ( )
throws Exception
{
// Ensure that setting header values to strings raises an error
// Disable this test: Modjy doesn't test for control characters.
// doBadHeadersListTest("test_headers_list_contains_values_with_control_chars");
}
public void testHeadersListContainsAccentedLatin1Values ( )
throws Exception
{
// Ensure that setting header values to 8-bit latin1 strings works properly
String headerName = "x-latin1-header";
String headerValue = "\u00e1\u00e9\u00ed\u00f3\u00fa";
String headerQString = headerName + "=" + headerValue;
doHeaderTest("test_headers_list_contains_accented_latin1_values", headerQString);
assertEquals("Status code != 200: ServerError, =='"+getStatus()+"'", 200, getStatus());
assertTrue("Header '"+headerName+"' not returned: ", getResponse().containsHeader(headerName));
assertEquals("Header '"+headerName+"' != '"+headerValue+"', == '"+getResponse().getHeader(headerName)+"' ",
headerValue, getResponse().getHeader(headerName));
}
public void testHopByHopHeaders ( )
throws Exception
{
// Test that attempts to set hop-by-hop headers raise exception.
for (int i = 0 ; i < hop_by_hop_headers.length ; i++)
{
doHeaderTest("test_hop_by_hop", hop_by_hop_headers[i]);
assertEquals("Status code != 500: ServerError, =='"+getStatus()+"'", 500, getStatus());
assertTrue("Could not find exception 'HopByHopHeaderSet' in output",
getOutput().indexOf("HopByHopHeaderSet")!=-1);
}
}
public void testSetHeader ( )
throws Exception
{
// test that we can set headers
}
public void testMultilineHeaders ()
{
// Need to do some research on this
}
public void testRFC2047EncodedHeaders ( )
{
// Need to do some research on this
}
}
| apache-2.0 |
Gigaspaces/xap-openspaces | src/main/java/org/openspaces/grid/gsm/machines/backup/MachinesStateBackupToSpace.java | 8314 | /*******************************************************************************
* Copyright (c) 2013 GigaSpaces Technologies Ltd. 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.
*******************************************************************************/
package org.openspaces.grid.gsm.machines.backup;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import net.jini.core.lease.Lease;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openspaces.admin.Admin;
import org.openspaces.admin.internal.admin.InternalAdmin;
import org.openspaces.admin.pu.ProcessingUnit;
import org.openspaces.core.GigaSpace;
import org.openspaces.grid.esm.EsmSystemProperties;
import org.openspaces.grid.gsm.SingleThreadedPollingLog;
import org.openspaces.grid.gsm.machines.MachinesSlaEnforcementState;
import com.gigaspaces.async.AsyncFuture;
import com.gigaspaces.internal.utils.concurrent.GSThreadFactory;
import com.gigaspaces.query.IdQuery;
public class MachinesStateBackupToSpace implements MachinesStateBackup {
private final Log logger = new SingleThreadedPollingLog(LogFactory.getLog(this.getClass()));
public static final Integer SINGLETON_ID = 0;
private final MachinesSlaEnforcementState machinesSlaEnforcementState;
private final GigaSpace space;
private final AtomicLong writeCompletedVersion;
private final AtomicReference<Throwable> lastError;
private final ThreadFactory threadFactory = new GSThreadFactory(this.getClass().getName(), /*daemonThreads=*/ true);
private final ExecutorService service = Executors.newSingleThreadExecutor(threadFactory);
private final InternalAdmin admin;
private static final long BACKUP_INTERVAL_MILLISECONDS = Long.getLong(EsmSystemProperties.ESM_BACKUP_INTERVAL_MILLISECONDS, EsmSystemProperties.ESM_BACKUP_INTERVAL_MILLISECONDS_DEFAULT);
private ScheduledFuture<?> scheduledFuture;
private boolean started = false;
private boolean recovered = false;
private AsyncFuture<MachinesState> asyncRead;
public MachinesStateBackupToSpace(Admin admin, GigaSpace space, MachinesSlaEnforcementState machinesSlaEnforcementState) {
this.admin = (InternalAdmin) admin;
this.space = space;
this.machinesSlaEnforcementState = machinesSlaEnforcementState;
writeCompletedVersion = new AtomicLong(machinesSlaEnforcementState.getVersion() - 1);
lastError = new AtomicReference<Throwable>();
}
private void startBackup() {
if (started) {
return;
}
scheduledFuture = this.admin.scheduleWithFixedDelayNonBlockingStateChange(new Runnable() {
private Future<?> future = null;
@Override
public void run() {
final long currentVersion = machinesSlaEnforcementState.getVersion();
if (writeCompletedVersion.get() == currentVersion) {
logger.trace("Already wrote machines state to space. version=" + currentVersion);
return;
}
else if (future != null && !future.isDone()) {
logger.trace("Machine state write is in progress");
}
else {
write(currentVersion);
}
}
private void write(final long currentVersion) {
try {
final MachinesState machinesState = machinesSlaEnforcementState.toMachinesState();
machinesState.setId(SINGLETON_ID);
if (machinesState.getVersion() != currentVersion) {
throw new IllegalStateException("Expected version " + currentVersion + ", instead got " + machinesState.getVersion());
}
future = service.submit(new Runnable() {
@Override
public void run() {
try {
logger.trace("Before writing machines state to space. version=" + currentVersion);
space.write(machinesState, Lease.FOREVER);
writeCompletedVersion.set(currentVersion);
lastError.set(null);
logger.trace("Successfully written machines state to space. version=" + currentVersion);
} catch (final Throwable t) {
logger.debug("Failed writing machines state to space. version=" + currentVersion, t);
lastError.set(t);
}
}
});
}
catch (final Throwable t) {
logger.debug("Failed writing machines state to space. version=" + currentVersion, t);
lastError.set(t);
}
}
},0L,
BACKUP_INTERVAL_MILLISECONDS,
TimeUnit.MILLISECONDS);
started = true;
}
@Override
public void close() {
scheduledFuture.cancel(false);
service.shutdownNow();
}
@Override
public void validateBackupCompleted(ProcessingUnit pu) throws MachinesStateBackupFailureException, MachinesStateBackupInProgressException {
final Throwable lastError = (Throwable) this.lastError.get();
if (lastError != null) {
throw new MachinesStateBackupFailureException(pu, lastError);
}
else if (writeCompletedVersion.get() != machinesSlaEnforcementState.getVersion()) {
throw new MachinesStateBackupInProgressException(pu);
}
}
@Override
public void recoverAndStartBackup(ProcessingUnit pu) throws MachinesStateRecoveryFailureException, MachinesStateRecoveryInProgressException {
recover(pu);
startBackup();
}
private void recover(ProcessingUnit pu)
throws MachinesStateRecoveryFailureException, MachinesStateRecoveryInProgressException {
if (!recovered) {
final MachinesState machinesState = readMachineStateFromSpace(pu);
if (machinesState != null) {
logger.info("Recovering machines state from " + space.getName());
machinesSlaEnforcementState.fromMachinesState(machinesState);
}
else {
logger.debug("Not recovering machines state from " + space.getName() + " since it's empty.");
}
recovered = true;
}
}
private MachinesState readMachineStateFromSpace(ProcessingUnit pu) throws MachinesStateRecoveryFailureException, MachinesStateRecoveryInProgressException {
if (this.asyncRead == null) {
this.asyncRead = space.asyncRead(new IdQuery<MachinesState>(MachinesState.class, SINGLETON_ID));
}
if (this.asyncRead != null && this.asyncRead.isDone()){
try {
return asyncRead.get();
}
catch (ExecutionException e) {
throw new MachinesStateRecoveryFailureException(pu, e);
}
catch (InterruptedException e) {
throw new MachinesStateRecoveryFailureException(pu, e);
}
}
throw new MachinesStateRecoveryInProgressException(pu);
}
} | apache-2.0 |
jayware/entity-essentials | entity-essentials-api/src/main/java/org/jayware/e2/storage/api/Storage.java | 820 | /**
* Entity Essentials -- A Component-based Entity System
*
* Copyright (C) 2017 Elmar Schug <elmar.schug@jayware.org>,
* Markus Neubauer <markus.neubauer@jayware.org>
*
* 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.jayware.e2.storage.api;
public interface Storage
{
}
| apache-2.0 |
jtgeiger/grison | lib/src/main/java/com/sibilantsolutions/grison/evt/AlarmEvt.java | 348 | package com.sibilantsolutions.grison.evt;
import com.sibilantsolutions.grison.driver.foscam.domain.AlarmTypeE;
public class AlarmEvt
{
private final AlarmTypeE alarmType;
public AlarmEvt(AlarmTypeE alarmType)
{
this.alarmType = alarmType;
}
public AlarmTypeE getAlarmType()
{
return alarmType;
}
}
| apache-2.0 |
oriontribunal/CoffeeMud | com/planet_ink/coffee_mud/Abilities/Songs/Play_Flutes.java | 2309 | package com.planet_ink.coffee_mud.Abilities.Songs;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.MusicalInstrument.InstrumentType;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.*;
/*
Copyright 2003-2016 Bo Zimmerman
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 Play_Flutes extends Play_Instrument
{
@Override
public String ID()
{
return "Play_Flutes";
}
private final static String localizedName = CMLib.lang().L("Flutes");
@Override
public String name()
{
return localizedName;
}
@Override
protected InstrumentType requiredInstrumentType()
{
return InstrumentType.FLUTES;
}
@Override
public String mimicSpell()
{
return "Chant_CharmAnimal";
}
private static Ability theSpell = null;
@Override
protected Ability getSpell()
{
if (theSpell != null)
return theSpell;
if (mimicSpell().length() == 0)
return null;
theSpell = CMClass.getAbility(mimicSpell());
return theSpell;
}
}
| apache-2.0 |
EvanMark/Spring-REST-API | src/main/java/mdx/gsd/data/service/SurveyPaeiService.java | 464 | package mdx.gsd.data.service;
import mdx.gsd.data.model.SurveyPaei;
import java.util.List;
/**
* Created by universe (E.) on 12/06/17.
*/
public interface SurveyPaeiService {
void addSurveyPaei(SurveyPaei surveyPaei);
void updateSurveyPaei(SurveyPaei surveyPaei);
SurveyPaei getSurveyPaeiById(Integer id);
List<SurveyPaei> getAllSurveyPaei();
List<SurveyPaei> getUserSurveyPaei(String id);
void removeSurveyPaei(Integer id);
}
| apache-2.0 |
Cerfoglg/cattle | code/iaas/allocator/src/main/java/io/cattle/platform/allocator/service/impl/PortBindingResourceRequest.java | 1312 | package io.cattle.platform.allocator.service.impl;
import io.cattle.platform.core.util.PortSpec;
import java.util.List;
public class PortBindingResourceRequest implements ResourceRequest {
private String instanceId;
private String resourceUuid;
private String resource;
private List<PortSpec> portRequests;
private String type;
public List<PortSpec> getPortRequests() {
return portRequests;
}
public void setPortRequests(List<PortSpec> portRequests) {
this.portRequests = portRequests;
}
@Override
public String getResource() {
return resource;
}
public void setResource(String resource) {
this.resource = resource;
}
public String getInstanceId() {
return instanceId;
}
public void setInstanceId(String instanceId) {
this.instanceId = instanceId;
}
public String getResourceUuid() {
return resourceUuid;
}
public void setResourceUuid(String resourceUuid) {
this.resourceUuid = resourceUuid;
}
@Override
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
@Override
public String toString() {
return String.format("ports: %s", portRequests);
}
}
| apache-2.0 |
trustedanalytics/hdfs-broker | src/main/java/org/trustedanalytics/servicebroker/hdfs/plans/binding/HdfsBindingClient.java | 2311 | /**
* Copyright (c) 2015 Intel Corporation
*
* 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.trustedanalytics.servicebroker.hdfs.plans.binding;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.trustedanalytics.cfbroker.store.hdfs.helper.DirHelper;
import org.trustedanalytics.cfbroker.store.hdfs.helper.HdfsPathTemplateUtils;
import org.trustedanalytics.servicebroker.framework.Credentials;
import org.trustedanalytics.servicebroker.hdfs.config.HdfsConstants;
@Component
class HdfsBindingClient
implements HdfsBareBindingOperations, HdfsSimpleBindingOperations, HdfsSpecificOrgBindingOperations {
private final Credentials credentials;
private final String userspacePathTemplate;
@Autowired
public HdfsBindingClient(Credentials credentials, String userspacePathTemplate) {
this.credentials = credentials;
this.userspacePathTemplate = userspacePathTemplate;
}
@Override
public Map<String, Object> createCredentialsMap() {
return credentials.getCredentialsMap();
}
@Override
public Map<String, Object> createCredentialsMap(UUID instanceId) {
return createCredentialsMap(instanceId, null);
}
@Override
public Map<String, Object> createCredentialsMap(UUID instanceId, UUID orgId) {
Map<String, Object> credentialsCopy = new HashMap<>(credentials.getCredentialsMap());
String dir = HdfsPathTemplateUtils.fill(userspacePathTemplate, instanceId, orgId);
String uri = DirHelper.concat(credentialsCopy.get(HdfsConstants.HADOOP_DEFAULT_FS).toString(), dir);
uri = DirHelper.removeTrailingSlashes(uri) + "/";
credentialsCopy.put("uri", uri);
return credentialsCopy;
}
}
| apache-2.0 |
XClouded/t4f-core | java/security/crypto/src/main/java/io/aos/crypto/spl02/KeyGeneratorExample.java | 3479 | /****************************************************************
* Licensed to the AOS Community (AOS) under one or more *
* contributor license agreements. See the NOTICE file *
* distributed with this work for additional information *
* regarding copyright ownership. The AOS 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 io.aos.crypto.spl02;
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
/**
* Basic example using the KeyGenerator class and
* showing how to create a SecretKeySpec from an encoded key.
*/
public class KeyGeneratorExample
{
public static void main(
String[] args)
throws Exception
{
byte[] input = new byte[] {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 };
byte[] ivBytes = new byte[] {
0x00, 0x00, 0x00, 0x01, 0x04, 0x05, 0x06, 0x07,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 };
Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding", "BC");
KeyGenerator generator = KeyGenerator.getInstance("AES", "BC");
generator.init(192);
Key encryptionKey = generator.generateKey();
System.out.println("key : " + Utils.toHex(encryptionKey.getEncoded()));
System.out.println("input : " + Utils.toHex(input));
// encryption pass
cipher.init(Cipher.ENCRYPT_MODE, encryptionKey, new IvParameterSpec(ivBytes));
byte[] cipherText = new byte[cipher.getOutputSize(input.length)];
int ctLength = cipher.update(input, 0, input.length, cipherText, 0);
ctLength += cipher.doFinal(cipherText, ctLength);
// decryption pass
Key decryptionKey = new SecretKeySpec(encryptionKey.getEncoded(), encryptionKey.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, decryptionKey, new IvParameterSpec(ivBytes));
byte[] plainText = new byte[cipher.getOutputSize(ctLength)];
int ptLength = cipher.update(cipherText, 0, ctLength, plainText, 0);
ptLength += cipher.doFinal(plainText, ptLength);
System.out.println("plain : " + Utils.toHex(plainText, ptLength) + " bytes: " + ptLength);
}
}
| apache-2.0 |
programingjd/okserver | src/main/java/info/jdavid/ok/server/header/ETag.java | 314 | package info.jdavid.ok.server.header;
/**
* ETag header.
*/
@SuppressWarnings({ "WeakerAccess" })
public final class ETag {
private ETag() {}
public static final String HEADER = "ETag";
public static final String IF_MATCH = "If-Match";
public static final String IF_NONE_MATCH = "If-None-Match";
}
| apache-2.0 |
sequenceiq/cloudbreak | core/src/main/java/com/sequenceiq/cloudbreak/core/flow2/config/Flow2Initializer.java | 1149 | package com.sequenceiq.cloudbreak.core.flow2.config;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.inject.Inject;
import org.springframework.stereotype.Component;
import com.sequenceiq.cloudbreak.core.flow2.Flow2Handler;
import com.sequenceiq.cloudbreak.core.flow2.FlowEvent;
import reactor.bus.EventBus;
import reactor.bus.selector.Selectors;
@Component
public class Flow2Initializer {
@Inject
private EventBus reactor;
@Inject
private Flow2Handler flow2Handler;
@Resource
private List<FlowConfiguration<?>> flowConfigs;
@PostConstruct
public void init() {
String eventSelector = Stream.concat(Stream.of(Flow2Handler.FLOW_FINAL, Flow2Handler.FLOW_CANCEL),
flowConfigs.stream().flatMap(c -> Arrays.stream(c.getEvents())).map(FlowEvent::event)
).distinct().collect(Collectors.joining("|"));
reactor.on(Selectors.regex(eventSelector), flow2Handler);
}
}
| apache-2.0 |
HangarGeek/SaltKlient | eu/hangar/sk/module/modules/tableflip.java | 557 | package eu.hangar.sk.module.modules;
import org.lwjgl.input.Keyboard;
import eu.hangar.sk.event.EventTarget;
import eu.hangar.sk.module.Module;
import net.minecraft.client.Minecraft;
@Module.ModInfo(name = " Tableflip", description = "tableflip", category = Module.Catergoy.SALT, bind = Keyboard.KEY_P)
public class tableflip extends Module {
@EventTarget
public void onEnable(){
Minecraft.getMinecraft().player.sendChatMessage("(╯°□°)╯︵ ┻━┻");
}
@Override
public void onDisable() {
}
}
| apache-2.0 |
vivantech/kc_fixes | src/main/java/org/kuali/kra/subaward/document/authorizer/SubAwardAuthorizer.java | 2286 | /*
* Copyright 2005-2014 The Kuali Foundation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ecl1.php
*
* 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.kuali.kra.subaward.document.authorizer;
import org.kuali.kra.authorization.Task;
import org.kuali.kra.authorization.TaskAuthorizerImpl;
import org.kuali.kra.service.KraAuthorizationService;
import org.kuali.kra.subaward.bo.SubAward;
import org.kuali.kra.subaward.document.authorization.SubAwardTask;
/**
* This class is using for SubAwardAuthorizer...
*/
public abstract class SubAwardAuthorizer extends TaskAuthorizerImpl {
private KraAuthorizationService kraAuthorizationService;
@Override
public boolean isAuthorized(String userId, Task task) {
return isAuthorized(userId, (SubAwardTask) task);
}
/**
* Is the user authorized to execute the given Subaward task?
* @param task the SubAwardTask
* @return true if the user is authorized; otherwise false
*/
public abstract boolean isAuthorized(String userId, SubAwardTask task);
/**
* Set the Kra Authorization Service.
* Usually injected by the Spring Framework.
* @param kraAuthorizationService
*/
public void setKraAuthorizationService(KraAuthorizationService kraAuthorizationService) {
this.kraAuthorizationService = kraAuthorizationService;
}
/**
* Does the given user has the permission for this Subaward?
* @param subAward the SubAward
* @param permissionName the name of the permission
* @return true if the person has the permission; otherwise false
*/
protected final boolean hasPermission(String userId,
SubAward subAward, String permissionName) {
return kraAuthorizationService.hasPermission(userId,
subAward, permissionName);
}
}
| apache-2.0 |
pbailly/daikon | daikon/src/test/java/org/talend/daikon/i18n/package1/TestClass1.java | 795 | // ============================================================================
//
// Copyright (C) 2006-2015 Talend Inc. - www.talend.com
//
// This source code is available under agreement available at
// %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt
//
// You should have received a copy of the agreement
// along with this program; if not, write to Talend SA
// 9 rue Pages 92150 Suresnes, France
//
// ============================================================================
package org.talend.daikon.i18n.package1;
/**
* test class used to test the inherited class base i18n resolver and find the location of the messages.properties see
* org.talend.daikon.i18n.ClassBasedI18nMessagesTest
*/
public class TestClass1 {
// only for tests
}
| apache-2.0 |
Smalinuxer/Vafrinn | app/src/main/java/org/chromium/chrome/browser/toolbar/ToolbarManager.java | 42616 | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.toolbar;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.SystemClock;
import android.support.v7.app.ActionBar;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnAttachStateChangeListener;
import android.view.View.OnClickListener;
import android.widget.FrameLayout;
import org.chromium.base.ThreadUtils;
import org.chromium.base.metrics.RecordHistogram;
import org.chromium.base.metrics.RecordUserAction;
import org.chromium.chrome.R;
import org.chromium.chrome.browser.BookmarksBridge;
import org.chromium.chrome.browser.ChromeActivity;
import org.chromium.chrome.browser.ChromeBrowserProviderClient;
import org.chromium.chrome.browser.TabLoadStatus;
import org.chromium.chrome.browser.UrlConstants;
import org.chromium.chrome.browser.WindowDelegate;
import org.chromium.chrome.browser.appmenu.AppMenuButtonHelper;
import org.chromium.chrome.browser.appmenu.AppMenuHandler;
import org.chromium.chrome.browser.appmenu.AppMenuObserver;
import org.chromium.chrome.browser.appmenu.ChromeAppMenuPropertiesDelegate;
import org.chromium.chrome.browser.compositor.Invalidator;
import org.chromium.chrome.browser.compositor.layouts.EmptyOverviewModeObserver;
import org.chromium.chrome.browser.compositor.layouts.Layout;
import org.chromium.chrome.browser.compositor.layouts.LayoutManager;
import org.chromium.chrome.browser.compositor.layouts.OverviewModeBehavior;
import org.chromium.chrome.browser.compositor.layouts.OverviewModeBehavior.OverviewModeObserver;
import org.chromium.chrome.browser.compositor.layouts.SceneChangeObserver;
import org.chromium.chrome.browser.fullscreen.ChromeFullscreenManager;
import org.chromium.chrome.browser.fullscreen.FullscreenManager;
import org.chromium.chrome.browser.ntp.NativePageFactory;
import org.chromium.chrome.browser.ntp.NewTabPage;
import org.chromium.chrome.browser.omnibox.LocationBar;
import org.chromium.chrome.browser.omnibox.UrlFocusChangeListener;
import org.chromium.chrome.browser.partnercustomizations.HomepageManager;
import org.chromium.chrome.browser.partnercustomizations.HomepageManager.HomepageStateListener;
import org.chromium.chrome.browser.profiles.Profile;
import org.chromium.chrome.browser.search_engines.TemplateUrlService;
import org.chromium.chrome.browser.search_engines.TemplateUrlService.TemplateUrl;
import org.chromium.chrome.browser.search_engines.TemplateUrlService.TemplateUrlServiceObserver;
import org.chromium.chrome.browser.tab.ChromeTab;
import org.chromium.chrome.browser.tab.EmptyTabObserver;
import org.chromium.chrome.browser.tab.Tab;
import org.chromium.chrome.browser.tab.TabObserver;
import org.chromium.chrome.browser.tabmodel.EmptyTabModelObserver;
import org.chromium.chrome.browser.tabmodel.EmptyTabModelSelectorObserver;
import org.chromium.chrome.browser.tabmodel.TabModel;
import org.chromium.chrome.browser.tabmodel.TabModel.TabLaunchType;
import org.chromium.chrome.browser.tabmodel.TabModel.TabSelectionType;
import org.chromium.chrome.browser.tabmodel.TabModelObserver;
import org.chromium.chrome.browser.tabmodel.TabModelSelector;
import org.chromium.chrome.browser.tabmodel.TabModelSelectorObserver;
import org.chromium.chrome.browser.toolbar.ActionModeController.ActionBarDelegate;
import org.chromium.chrome.browser.widget.findinpage.FindToolbarManager;
import org.chromium.chrome.browser.widget.findinpage.FindToolbarObserver;
import org.chromium.content_public.browser.LoadUrlParams;
import org.chromium.content_public.browser.NavigationController;
import org.chromium.content_public.browser.WebContents;
import org.chromium.ui.base.DeviceFormFactor;
import org.chromium.ui.base.PageTransition;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* Contains logic for managing the toolbar visual component. This class manages the interactions
* with the rest of the application to ensure the toolbar is always visually up to date.
*/
public class ToolbarManager implements ToolbarTabController, UrlFocusChangeListener {
/**
* Handle UI updates of menu icons. Only applicable for phones.
*/
public interface MenuDelegatePhone {
/**
* Called when current tab's loading status changes.
*
* @param isLoading Whether the current tab is loading.
*/
public void updateReloadButtonState(boolean isLoading);
}
/**
* The number of ms to wait before reporting to UMA omnibox interaction metrics.
*/
private static final int RECORD_UMA_PERFORMANCE_METRICS_DELAY_MS = 30000;
private static final int MIN_FOCUS_TIME_FOR_UMA_HISTOGRAM_MS = 1000;
private static final int MAX_FOCUS_TIME_FOR_UMA_HISTOGRAM_MS = 30000;
/**
* The minimum load progress that can be shown when a page is loading. This is not 0 so that
* it's obvious to the user that something is attempting to load.
*/
public static final float MINIMUM_LOAD_PROGRESS = 0.05f;
private final ToolbarLayout mToolbar;
private final ToolbarControlContainer mControlContainer;
private TabModelSelector mTabModelSelector;
private TabModelSelectorObserver mTabModelSelectorObserver;
private TabModelObserver mTabModelObserver;
private MenuDelegatePhone mMenuDelegatePhone;
private final ToolbarModelImpl mToolbarModel;
private Profile mCurrentProfile;
private BookmarksBridge mBookmarksBridge;
private TemplateUrlServiceObserver mTemplateUrlObserver;
private final LocationBar mLocationBar;
private FindToolbarManager mFindToolbarManager;
private final ChromeAppMenuPropertiesDelegate mAppMenuPropertiesDelegate;
private final TabObserver mTabObserver;
private final BookmarksBridge.BookmarkModelObserver mBookmarksObserver;
private final FindToolbarObserver mFindToolbarObserver;
private final OverviewModeObserver mOverviewModeObserver;
private final SceneChangeObserver mSceneChangeObserver;
private final ActionBarDelegate mActionBarDelegate;
private final ActionModeController mActionModeController;
private final LoadProgressSimulator mLoadProgressSimulator;
private ChromeFullscreenManager mFullscreenManager;
private int mFullscreenFocusToken = FullscreenManager.INVALID_TOKEN;
private int mFullscreenFindInPageToken = FullscreenManager.INVALID_TOKEN;
private int mFullscreenMenuToken = FullscreenManager.INVALID_TOKEN;
private int mPreselectedTabId = Tab.INVALID_TAB_ID;
private boolean mNativeLibraryReady;
private boolean mTabRestoreCompleted;
private AppMenuButtonHelper mAppMenuButtonHelper;
private HomepageStateListener mHomepageStateListener;
private boolean mInitializedWithNative;
/**
* Creates a ToolbarManager object.
* @param controlContainer The container of the toolbar.
* @param menuHandler The handler for interacting with the menu.
*/
public ToolbarManager(final ChromeActivity activity,
ToolbarControlContainer controlContainer, final AppMenuHandler menuHandler,
ChromeAppMenuPropertiesDelegate appMenuPropertiesDelegate,
Invalidator invalidator) {
mActionBarDelegate = new ActionModeController.ActionBarDelegate() {
@Override
public void setControlTopMargin(int margin) {
FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams)
mControlContainer.getLayoutParams();
lp.topMargin = margin;
mControlContainer.setLayoutParams(lp);
}
@Override
public int getControlTopMargin() {
FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams)
mControlContainer.getLayoutParams();
return lp.topMargin;
}
@Override
public ActionBar getSupportActionBar() {
return activity.getSupportActionBar();
}
@Override
public void setActionBarBackgroundVisibility(boolean visible) {
int visibility = visible ? View.VISIBLE : View.GONE;
activity.findViewById(R.id.action_bar_black_background).setVisibility(visibility);
// TODO(tedchoc): Add support for changing the color based on the brand color.
}
};
mToolbarModel = new ToolbarModelImpl();
mControlContainer = controlContainer;
assert mControlContainer != null;
mToolbar = (ToolbarLayout) controlContainer.findViewById(R.id.toolbar);
mToolbar.setPaintInvalidator(invalidator);
mActionModeController = new ActionModeController(activity, mActionBarDelegate);
mActionModeController.setCustomSelectionActionModeCallback(
new ToolbarActionModeCallback());
mActionModeController.setTabStripHeight(mToolbar.getTabStripHeight());
MenuDelegatePhone menuDelegate = new MenuDelegatePhone() {
@Override
public void updateReloadButtonState(boolean isLoading) {
if (mAppMenuPropertiesDelegate != null) {
mAppMenuPropertiesDelegate.loadingStateChanged(isLoading);
menuHandler.menuItemContentChanged(R.id.icon_row_menu_id);
}
}
};
setMenuDelegatePhone(menuDelegate);
mLocationBar = mToolbar.getLocationBar();
mLocationBar.setToolbarDataProvider(mToolbarModel);
mLocationBar.setUrlFocusChangeListener(this);
mLocationBar.setDefaultTextEditActionModeCallback(
mActionModeController.getActionModeCallback());
mLocationBar.initializeControls(
new WindowDelegate(activity.getWindow()),
mActionModeController.getActionBarDelegate(),
activity.getWindowAndroid());
mLocationBar.setIgnoreURLBarModification(false);
setMenuHandler(menuHandler);
mToolbar.initialize(mToolbarModel, this, mAppMenuButtonHelper);
mAppMenuPropertiesDelegate = appMenuPropertiesDelegate;
mHomepageStateListener = new HomepageStateListener() {
@Override
public void onHomepageStateUpdated() {
mToolbar.onHomeButtonUpdate(
HomepageManager.isHomepageEnabled(mToolbar.getContext()));
}
};
HomepageManager.getInstance(mToolbar.getContext()).addListener(mHomepageStateListener);
mTabModelSelectorObserver = new EmptyTabModelSelectorObserver() {
@Override
public void onTabModelSelected(TabModel newModel, TabModel oldModel) {
refreshSelectedTab();
updateTabCount();
mControlContainer.invalidateBitmap();
}
@Override
public void onTabStateInitialized() {
mTabRestoreCompleted = true;
handleTabRestoreCompleted();
}
};
mTabModelObserver = new EmptyTabModelObserver() {
@Override
public void didAddTab(Tab tab, TabLaunchType type) {
updateTabCount();
}
@Override
public void didSelectTab(Tab tab, TabSelectionType type, int lastId) {
mPreselectedTabId = Tab.INVALID_TAB_ID;
refreshSelectedTab();
}
@Override
public void tabClosureUndone(Tab tab) {
updateTabCount();
refreshSelectedTab();
}
@Override
public void didCloseTab(Tab tab) {
updateTabCount();
refreshSelectedTab();
}
@Override
public void tabPendingClosure(Tab tab) {
updateTabCount();
refreshSelectedTab();
}
@Override
public void allTabsPendingClosure(List<Integer> tabIds) {
updateTabCount();
refreshSelectedTab();
}
};
mTabObserver = new EmptyTabObserver() {
@Override
public void onSSLStateUpdated(Tab tab) {
super.onSSLStateUpdated(tab);
assert tab == mToolbarModel.getTab();
mLocationBar.updateSecurityIcon(tab.getSecurityLevel());
}
@Override
public void onWebContentsInstantSupportDisabled() {
mLocationBar.setUrlToPageUrl();
}
@Override
public void onDidNavigateMainFrame(Tab tab, String url, String baseUrl,
boolean isNavigationToDifferentPage, boolean isFragmentNavigation,
int statusCode) {
if (isNavigationToDifferentPage) {
mToolbar.onNavigatedToDifferentPage();
}
}
@Override
public void onPageLoadStarted(Tab tab, String url) {
updateButtonStatus();
updateTabLoadingState(true);
mLoadProgressSimulator.cancel();
if (NativePageFactory.isNativePageUrl(url, tab.isIncognito())) {
finishLoadProgress(false);
} else {
mToolbar.startLoadProgress();
setLoadProgress(0.0f);
}
}
@Override
public void onPageLoadFinished(Tab tab) {
Tab currentTab = mToolbarModel.getTab();
updateTabLoadingState(true);
// If we made some progress, fast-forward to complete, otherwise just dismiss any
// MINIMUM_LOAD_PROGRESS that had been set.
if (currentTab.getProgress() > MINIMUM_LOAD_PROGRESS) setLoadProgress(1.0f);
finishLoadProgress(true);
}
@Override
public void onPageLoadFailed(Tab tab, int errorCode) {
updateTabLoadingState(true);
finishLoadProgress(false);
}
@Override
public void onTitleUpdated(Tab tab) {
mLocationBar.setTitleToPageTitle();
}
@Override
public void onUrlUpdated(Tab tab) {
// Update the SSL security state as a result of this notification as it will
// sometimes be the only update we receive.
updateTabLoadingState(true);
// A URL update is a decent enough indicator that the toolbar widget is in
// a stable state to capture its bitmap for use in fullscreen.
mControlContainer.setReadyForBitmapCapture(true);
}
@Override
public void onCrash(Tab tab, boolean sadTabShown) {
updateTabLoadingState(false);
updateButtonStatus();
finishLoadProgress(false);
}
@Override
public void onLoadProgressChanged(Tab tab, int progress) {
// TODO(kkimlabs): Investigate using float progress all the way up to Blink.
setLoadProgress(progress / 100.0f);
}
@Override
public void onContentChanged(Tab tab) {
mToolbar.onTabContentViewChanged();
}
@Override
public void onWebContentsSwapped(Tab tab, boolean didStartLoad, boolean didFinishLoad) {
if (!didStartLoad) return;
if (didFinishLoad) {
mLoadProgressSimulator.start();
}
}
@Override
public void onDidStartNavigationToPendingEntry(Tab tab, String url) {
// Update URL as soon as it becomes available when it's a new tab.
// But we want to update only when it's a new tab. So we check whether the current
// navigation entry is initial, meaning whether it has the same target URL as the
// initial URL of the tab.
WebContents webContents = tab.getWebContents();
if (webContents == null) return;
NavigationController navigationController = webContents.getNavigationController();
if (navigationController == null) return;
if (navigationController.isInitialNavigation()) {
mLocationBar.setUrlToPageUrl();
}
}
@Override
public void onLoadUrl(Tab tab, LoadUrlParams params, int loadType) {
NewTabPage ntp = mToolbarModel.getNewTabPageForCurrentTab();
if (ntp == null) return;
if (!NewTabPage.isNTPUrl(params.getUrl())
&& loadType != TabLoadStatus.PAGE_LOAD_FAILED) {
ntp.setUrlFocusAnimationsDisabled(true);
mToolbar.onTabOrModelChanged();
}
}
@Override
public void onDidFailLoad(Tab tab, boolean isProvisionalLoad, boolean isMainFrame,
int errorCode, String description, String failingUrl) {
NewTabPage ntp = mToolbarModel.getNewTabPageForCurrentTab();
if (ntp == null) return;
if (isProvisionalLoad && isMainFrame) {
ntp.setUrlFocusAnimationsDisabled(false);
mToolbar.onTabOrModelChanged();
}
}
@Override
public void onContextualActionBarVisibilityChanged(Tab tab, boolean visible) {
if (visible) RecordUserAction.record("MobileActionBarShown");
ActionBar actionBar = mActionBarDelegate.getSupportActionBar();
if (!visible && actionBar != null) actionBar.hide();
if (DeviceFormFactor.isTablet(activity)) {
if (visible) {
mActionModeController.startShowAnimation();
} else {
mActionModeController.startHideAnimation();
}
}
}
};
mBookmarksObserver = new BookmarksBridge.BookmarkModelObserver() {
@Override
public void bookmarkModelChanged() {
updateBookmarkButtonStatus();
}
};
mFindToolbarObserver = new FindToolbarObserver() {
@Override
public void onFindToolbarShown() {
mToolbar.handleFindToolbarStateChange(true);
if (mFullscreenManager != null) {
mFullscreenFindInPageToken =
mFullscreenManager.showControlsPersistentAndClearOldToken(
mFullscreenFindInPageToken);
}
}
@Override
public void onFindToolbarHidden() {
mToolbar.handleFindToolbarStateChange(false);
if (mFullscreenManager != null) {
mFullscreenManager.hideControlsPersistent(mFullscreenFindInPageToken);
mFullscreenFindInPageToken = FullscreenManager.INVALID_TOKEN;
}
}
};
mOverviewModeObserver = new EmptyOverviewModeObserver() {
@Override
public void onOverviewModeStartedShowing(boolean showToolbar) {
mToolbar.setTabSwitcherMode(true, showToolbar, false);
updateButtonStatus();
}
@Override
public void onOverviewModeStartedHiding(boolean showToolbar, boolean delayAnimation) {
mToolbar.setTabSwitcherMode(false, showToolbar, delayAnimation);
updateButtonStatus();
}
@Override
public void onOverviewModeFinishedHiding() {
mToolbar.onTabSwitcherTransitionFinished();
}
};
mSceneChangeObserver = new SceneChangeObserver() {
@Override
public void onTabSelectionHinted(int tabId) {
mPreselectedTabId = tabId;
refreshSelectedTab();
}
@Override
public void onSceneChange(Layout layout) {
mToolbar.setContentAttached(layout.shouldDisplayContentOverlay());
}
};
mLoadProgressSimulator = new LoadProgressSimulator(mToolbar);
}
/**
* Initialize the manager with the components that had native initialization dependencies.
* <p>
* Calling this must occur after the native library have completely loaded.
*
* @param tabModelSelector The selector that handles tab management.
* @param fullscreenManager The manager in charge of interacting with the fullscreen feature.
* @param findToolbarManager The manager for find in page.
* @param overviewModeBehavior The overview mode manager.
* @param layoutDriver A {@link LayoutManager} instance used to watch for scene changes.
*/
public void initializeWithNative(TabModelSelector tabModelSelector,
ChromeFullscreenManager fullscreenManager,
final FindToolbarManager findToolbarManager,
final OverviewModeBehavior overviewModeBehavior,
final LayoutManager layoutDriver,
OnClickListener tabSwitcherClickHandler,
OnClickListener newTabClickHandler,
OnClickListener bookmarkClickHandler,
OnClickListener customTabsBackClickHandler) {
assert !mInitializedWithNative;
mTabModelSelector = tabModelSelector;
mToolbar.getLocationBar().updateVisualsForState();
mToolbar.getLocationBar().setUrlToPageUrl();
mToolbar.setOnTabSwitcherClickHandler(tabSwitcherClickHandler);
mToolbar.setOnNewTabClickHandler(newTabClickHandler);
mToolbar.setBookmarkClickHandler(bookmarkClickHandler);
mToolbar.setCustomTabCloseClickHandler(customTabsBackClickHandler);
mToolbarModel.initializeWithNative();
mToolbar.addOnAttachStateChangeListener(new OnAttachStateChangeListener() {
@Override
public void onViewDetachedFromWindow(View v) {
Context context = mToolbar.getContext();
HomepageManager.getInstance(context).removeListener(mHomepageStateListener);
mTabModelSelector.removeObserver(mTabModelSelectorObserver);
for (TabModel model : mTabModelSelector.getModels()) {
model.removeObserver(mTabModelObserver);
}
if (mBookmarksBridge != null) {
mBookmarksBridge.destroy();
mBookmarksBridge = null;
}
if (mTemplateUrlObserver != null) {
TemplateUrlService.getInstance().removeObserver(mTemplateUrlObserver);
mTemplateUrlObserver = null;
}
findToolbarManager.removeObserver(mFindToolbarObserver);
if (overviewModeBehavior != null) {
overviewModeBehavior.removeOverviewModeObserver(mOverviewModeObserver);
}
if (layoutDriver != null) {
layoutDriver.removeSceneChangeObserver(mSceneChangeObserver);
}
}
@Override
public void onViewAttachedToWindow(View v) {
// As we have only just registered for notifications, any that were sent prior to
// this may have been missed.
// Calling refreshSelectedTab in case we missed the initial selection notification.
refreshSelectedTab();
}
});
mFindToolbarManager = findToolbarManager;
assert fullscreenManager != null;
mFullscreenManager = fullscreenManager;
mNativeLibraryReady = false;
findToolbarManager.addObserver(mFindToolbarObserver);
if (overviewModeBehavior != null) {
overviewModeBehavior.addOverviewModeObserver(mOverviewModeObserver);
}
if (layoutDriver != null) layoutDriver.addSceneChangeObserver(mSceneChangeObserver);
onNativeLibraryReady();
mInitializedWithNative = true;
}
/**
* @return The bookmarks bridge.
*/
public BookmarksBridge getBookmarksBridge() {
return mBookmarksBridge;
}
/**
* @return The toolbar interface that this manager handles.
*/
public Toolbar getToolbar() {
return mToolbar;
}
/**
* @return The controller for toolbar action mode.
*/
public ActionModeController getActionModeController() {
return mActionModeController;
}
/**
* @return Whether the UI has been initialized.
*/
public boolean isInitialized() {
return mInitializedWithNative;
}
/**
* Adds a custom action button to the {@link Toolbar} if it is supported.
* @param drawable The {@link Drawable} to use as the background for the button.
* @param description The content description for the custom action button.
* @param listener The {@link OnClickListener} to use for clicks to the button.
*/
public void addCustomActionButton(Drawable drawable, String description,
OnClickListener listener) {
mToolbar.addCustomActionButton(drawable, description, listener);
}
/**
* Call to tear down all of the toolbar dependencies.
*/
public void destroy() {
Tab currentTab = mToolbarModel.getTab();
if (currentTab != null) currentTab.removeObserver(mTabObserver);
}
/**
* Called when the orientation of the activity has changed.
*/
public void onOrientationChange() {
mActionModeController.showControlsOnOrientationChange();
}
/**
* Called when the accessibility enabled state changes.
* @param enabled Whether accessibility is enabled.
*/
public void onAccessibilityStatusChanged(boolean enabled) {
mToolbar.onAccessibilityStatusChanged(enabled);
}
private void registerTemplateUrlObserver() {
final TemplateUrlService templateUrlService = TemplateUrlService.getInstance();
assert mTemplateUrlObserver == null;
mTemplateUrlObserver = new TemplateUrlServiceObserver() {
private TemplateUrl mSearchEngine =
templateUrlService.getDefaultSearchEngineTemplateUrl();
@Override
public void onTemplateURLServiceChanged() {
TemplateUrl searchEngine = templateUrlService.getDefaultSearchEngineTemplateUrl();
if ((mSearchEngine == null && searchEngine == null)
|| (mSearchEngine != null && mSearchEngine.equals(searchEngine))) {
return;
}
mSearchEngine = searchEngine;
mToolbar.onDefaultSearchEngineChanged();
}
};
templateUrlService.addObserver(mTemplateUrlObserver);
}
private void onNativeLibraryReady() {
mNativeLibraryReady = true;
mToolbar.onNativeLibraryReady();
final TemplateUrlService templateUrlService = TemplateUrlService.getInstance();
TemplateUrlService.LoadListener mTemplateServiceLoadListener =
new TemplateUrlService.LoadListener() {
@Override
public void onTemplateUrlServiceLoaded() {
registerTemplateUrlObserver();
templateUrlService.unregisterLoadListener(this);
}
};
templateUrlService.registerLoadListener(mTemplateServiceLoadListener);
if (templateUrlService.isLoaded()) {
mTemplateServiceLoadListener.onTemplateUrlServiceLoaded();
} else {
templateUrlService.load();
}
mTabModelSelector.addObserver(mTabModelSelectorObserver);
for (TabModel model : mTabModelSelector.getModels()) model.addObserver(mTabModelObserver);
refreshSelectedTab();
if (mTabModelSelector.isTabStateInitialized()) mTabRestoreCompleted = true;
handleTabRestoreCompleted();
}
private void handleTabRestoreCompleted() {
if (!mTabRestoreCompleted || !mNativeLibraryReady) return;
mToolbar.onStateRestored();
updateTabCount();
}
/**
* Sets the handler for any special case handling related with the menu button.
* @param menuHandler The handler to be used.
*/
private void setMenuHandler(AppMenuHandler menuHandler) {
menuHandler.addObserver(new AppMenuObserver() {
@Override
public void onMenuVisibilityChanged(boolean isVisible) {
if (mFullscreenManager == null) return;
if (isVisible) {
mFullscreenMenuToken =
mFullscreenManager.showControlsPersistentAndClearOldToken(
mFullscreenMenuToken);
} else {
mFullscreenManager.hideControlsPersistent(mFullscreenMenuToken);
mFullscreenMenuToken = FullscreenManager.INVALID_TOKEN;
}
}
});
mAppMenuButtonHelper = new AppMenuButtonHelper(menuHandler);
mAppMenuButtonHelper.setOnAppMenuShownListener(new Runnable() {
@Override
public void run() {
RecordUserAction.record("MobileToolbarShowMenu");
}
});
mLocationBar.setMenuButtonHelper(mAppMenuButtonHelper);
}
/**
* Set the delegate that will handle updates from toolbar driven state changes.
* @param menuDelegatePhone The menu delegate to be updated (only applicable to phones).
*/
public void setMenuDelegatePhone(MenuDelegatePhone menuDelegatePhone) {
mMenuDelegatePhone = menuDelegatePhone;
}
@Override
public boolean back() {
Tab tab = mToolbarModel.getTab();
if (tab != null && tab.canGoBack()) {
tab.goBack();
updateButtonStatus();
return true;
}
return false;
}
@Override
public boolean forward() {
Tab tab = mToolbarModel.getTab();
if (tab != null && tab.canGoForward()) {
tab.goForward();
updateButtonStatus();
return true;
}
return false;
}
@Override
public void stopOrReloadCurrentTab() {
Tab currentTab = mToolbarModel.getTab();
if (currentTab != null) {
if (currentTab.isLoading()) {
currentTab.stopLoading();
} else {
currentTab.reload();
RecordUserAction.record("MobileToolbarReload");
}
}
updateButtonStatus();
}
@Override
public void openHomepage() {
Tab currentTab = mToolbarModel.getTab();
assert currentTab != null;
Context context = mToolbar.getContext();
String homePageUrl = HomepageManager.getHomepageUri(context);
if (TextUtils.isEmpty(homePageUrl)) {
homePageUrl = UrlConstants.NTP_URL;
}
currentTab.loadUrl(new LoadUrlParams(homePageUrl, PageTransition.HOME_PAGE));
}
/**
* Triggered when the URL input field has gained or lost focus.
* @param hasFocus Whether the URL field has gained focus.
*/
@Override
public void onUrlFocusChange(boolean hasFocus) {
mToolbar.onUrlFocusChange(hasFocus);
if (mFindToolbarManager != null && hasFocus) mFindToolbarManager.hideToolbar();
if (mFullscreenManager == null) return;
if (hasFocus) {
mFullscreenFocusToken = mFullscreenManager.showControlsPersistentAndClearOldToken(
mFullscreenFocusToken);
} else {
mFullscreenManager.hideControlsPersistent(mFullscreenFocusToken);
mFullscreenFocusToken = FullscreenManager.INVALID_TOKEN;
}
}
/**
* Update the primary color used by the model to the given color.
* @param color The primary color for the current tab.
*/
public void updatePrimaryColor(int color) {
boolean colorChanged = mToolbarModel.getPrimaryColor() != color;
if (!colorChanged) return;
mToolbarModel.setPrimaryColor(color);
mToolbar.onPrimaryColorChanged();
}
/**
* Sets the drawable that the close button shows.
*/
public void setCloseButtonDrawable(Drawable drawable) {
mToolbar.setCloseButtonImageResource(drawable);
}
/**
* Sets whether a title should be shown within the Toolbar.
* @param showTitle Whether a title should be shown.
*/
public void setShowTitle(boolean showTitle) {
mLocationBar.setShowTitle(showTitle);
}
/**
* Focuses or unfocuses the URL bar.
* @param focused Whether URL bar should be focused.
*/
public void setUrlBarFocus(boolean focused) {
if (!isInitialized()) return;
mToolbar.getLocationBar().setUrlBarFocus(focused);
}
/**
* @return Whether {@link Toolbar} has drawn at least once.
*/
public boolean hasDoneFirstDraw() {
return mToolbar.getFirstDrawTime() != 0;
}
/**
* Handle all necessary tasks that can be delayed until initialization completes.
* @param activityCreationTimeMs The time of creation for the activity this toolbar belongs to.
* @param activityName Simple class name for the activity this toolbar belongs to.
*/
public void onDeferredStartup(final long activityCreationTimeMs,
final String activityName) {
// Record startup performance statistics
long elapsedTime = SystemClock.elapsedRealtime() - activityCreationTimeMs;
if (elapsedTime < RECORD_UMA_PERFORMANCE_METRICS_DELAY_MS) {
ThreadUtils.postOnUiThreadDelayed(new Runnable() {
@Override
public void run() {
onDeferredStartup(activityCreationTimeMs, activityName);
}
}, RECORD_UMA_PERFORMANCE_METRICS_DELAY_MS - elapsedTime);
}
RecordHistogram.recordTimesHistogram("MobileStartup.ToolbarFirstDrawTime." + activityName,
mToolbar.getFirstDrawTime() - activityCreationTimeMs, TimeUnit.MILLISECONDS);
long firstFocusTime = mToolbar.getLocationBar().getFirstUrlBarFocusTime();
if (firstFocusTime != 0) {
RecordHistogram.recordCustomTimesHistogram(
"MobileStartup.ToolbarFirstFocusTime." + activityName,
firstFocusTime - activityCreationTimeMs, MIN_FOCUS_TIME_FOR_UMA_HISTOGRAM_MS,
MAX_FOCUS_TIME_FOR_UMA_HISTOGRAM_MS, TimeUnit.MILLISECONDS, 50);
}
}
/**
* Finish any toolbar animations.
*/
public void finishAnimations() {
if (isInitialized()) mToolbar.finishAnimations();
}
/**
* Updates the current number of Tabs based on the TabModel this Toolbar contains.
*/
private void updateTabCount() {
if (!mTabRestoreCompleted) return;
mToolbar.updateTabCountVisuals(mTabModelSelector.getCurrentModel().getCount());
}
/**
* Updates the current button states and calls appropriate abstract visibility methods, giving
* inheriting classes the chance to update the button visuals as well.
*/
private void updateButtonStatus() {
Tab currentTab = mToolbarModel.getTab();
boolean tabCrashed = currentTab != null && currentTab.isShowingSadTab();
mToolbar.updateBackButtonVisibility(currentTab != null && currentTab.canGoBack());
mToolbar.updateForwardButtonVisibility(currentTab != null && currentTab.canGoForward());
updateReloadState(tabCrashed);
updateBookmarkButtonStatus();
mToolbar.getMenuButton().setVisibility(
mToolbar.shouldShowMenuButton() ? View.VISIBLE : View.GONE);
}
private void updateBookmarkButtonStatus() {
Tab currentTab = mToolbarModel.getTab();
boolean isBookmarked = currentTab != null
&& currentTab.getBookmarkId() != ChromeBrowserProviderClient.INVALID_BOOKMARK_ID;
boolean editingAllowed = currentTab == null || mBookmarksBridge == null
|| mBookmarksBridge.isEditBookmarksEnabled();
mToolbar.updateBookmarkButton(isBookmarked, editingAllowed);
}
private void updateReloadState(boolean tabCrashed) {
Tab currentTab = mToolbarModel.getTab();
boolean isLoading = false;
if (!tabCrashed) {
isLoading = (currentTab != null && currentTab.isLoading()) || !mNativeLibraryReady;
}
mToolbar.updateReloadButtonVisibility(isLoading);
if (mMenuDelegatePhone != null) mMenuDelegatePhone.updateReloadButtonState(isLoading);
}
/**
* Triggered when the selected tab has changed.
*/
private void refreshSelectedTab() {
ChromeTab tab = null;
if (mPreselectedTabId != Tab.INVALID_TAB_ID) {
tab = ChromeTab.fromTab(mTabModelSelector.getTabById(mPreselectedTabId));
}
if (tab == null) tab = ChromeTab.fromTab(mTabModelSelector.getCurrentTab());
boolean wasIncognito = mToolbarModel.isIncognito();
ChromeTab previousTab = ChromeTab.fromTab(mToolbarModel.getTab());
boolean isIncognito =
tab != null ? tab.isIncognito() : mTabModelSelector.isIncognitoSelected();
mToolbarModel.setTab(tab, isIncognito);
updateCurrentTabDisplayStatus();
if (previousTab != tab || wasIncognito != isIncognito) {
if (previousTab != tab) {
if (previousTab != null) previousTab.removeObserver(mTabObserver);
if (tab != null) tab.addObserver(mTabObserver);
}
int defaultPrimaryColor = isIncognito
? mToolbar.getResources().getColor(R.color.incognito_primary_color)
: mToolbar.getResources().getColor(R.color.default_primary_color);
int primaryColor = tab != null ? tab.getThemeColor() : defaultPrimaryColor;
updatePrimaryColor(primaryColor);
mToolbar.onTabOrModelChanged();
if (tab != null && tab.getWebContents() != null
&& tab.getWebContents().isLoadingToDifferentDocument()) {
mToolbar.onNavigatedToDifferentPage();
}
}
Profile profile = mTabModelSelector.getModel(isIncognito).getProfile();
if (mCurrentProfile != profile) {
if (mBookmarksBridge != null) mBookmarksBridge.destroy();
mBookmarksBridge = new BookmarksBridge(profile);
mBookmarksBridge.addObserver(mBookmarksObserver);
mAppMenuPropertiesDelegate.setBookmarksBridge(mBookmarksBridge);
mLocationBar.setAutocompleteProfile(profile);
mCurrentProfile = profile;
}
}
private void updateCurrentTabDisplayStatus() {
Tab tab = mToolbarModel.getTab();
mLocationBar.setUrlToPageUrl();
updateTabLoadingState(true);
if (tab == null) {
finishLoadProgress(false);
return;
}
mLoadProgressSimulator.cancel();
if (tab.isLoading()) {
if (NativePageFactory.isNativePageUrl(tab.getUrl(), tab.isIncognito())) {
finishLoadProgress(false);
} else {
mToolbar.startLoadProgress();
setLoadProgress(tab.getProgress() / 100.0f);
}
} else {
finishLoadProgress(false);
}
}
private void updateTabLoadingState(boolean updateUrl) {
mLocationBar.updateLoadingState(updateUrl);
if (updateUrl) updateButtonStatus();
}
private void setLoadProgress(float progress) {
// If it's a native page, progress bar is already hidden or being hidden, so don't update
// the value.
// TODO(kkimlabs): Investigate back/forward navigation with native page & web content and
// figure out the correct progress bar presentation.
Tab tab = mToolbarModel.getTab();
if (NativePageFactory.isNativePageUrl(tab.getUrl(), tab.isIncognito())) return;
mToolbar.setLoadProgress(Math.max(progress, MINIMUM_LOAD_PROGRESS));
}
private void finishLoadProgress(boolean delayed) {
mLoadProgressSimulator.cancel();
mToolbar.finishLoadProgress(delayed);
}
private static class LoadProgressSimulator {
private static final int MSG_ID_UPDATE_PROGRESS = 1;
private static final float PROGRESS_INCREMENT = 0.1f;
private static final int PROGRESS_INCREMENT_DELAY_MS = 10;
private final ToolbarLayout mToolbar;
private final Handler mHandler;
private float mProgress;
public LoadProgressSimulator(ToolbarLayout toolbar) {
mToolbar = toolbar;
mHandler = new Handler(Looper.getMainLooper()) {
@Override
public void handleMessage(Message msg) {
assert msg.what == MSG_ID_UPDATE_PROGRESS;
mProgress = Math.min(1.0f, mProgress += PROGRESS_INCREMENT);
mToolbar.setLoadProgress(mProgress);
if (mProgress == 1.0f) {
mToolbar.finishLoadProgress(true);
return;
}
sendEmptyMessageDelayed(MSG_ID_UPDATE_PROGRESS, PROGRESS_INCREMENT_DELAY_MS);
}
};
}
/**
* Start simulating load progress from a baseline of 0.
*/
public void start() {
mProgress = 0.0f;
mToolbar.startLoadProgress();
mToolbar.setLoadProgress(mProgress);
mHandler.sendEmptyMessage(MSG_ID_UPDATE_PROGRESS);
}
/**
* Cancels simulating load progress.
*/
public void cancel() {
mHandler.removeMessages(MSG_ID_UPDATE_PROGRESS);
}
}
}
| apache-2.0 |
lqbweb/logging-log4j2 | log4j-core/src/main/java/org/apache/logging/log4j/core/appender/rolling/RollingFileManager.java | 16439 | /*
* 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 org.apache.logging.log4j.core.appender.rolling;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Serializable;
import java.nio.ByteBuffer;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
import org.apache.logging.log4j.core.Layout;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.appender.FileManager;
import org.apache.logging.log4j.core.appender.ManagerFactory;
import org.apache.logging.log4j.core.appender.rolling.action.AbstractAction;
import org.apache.logging.log4j.core.appender.rolling.action.Action;
import org.apache.logging.log4j.core.util.Constants;
import org.apache.logging.log4j.core.util.Log4jThread;
/**
* The Rolling File Manager.
*/
public class RollingFileManager extends FileManager {
private static RollingFileManagerFactory factory = new RollingFileManagerFactory();
protected long size;
private long initialTime;
private final PatternProcessor patternProcessor;
private final Semaphore semaphore = new Semaphore(1);
private volatile TriggeringPolicy triggeringPolicy;
private volatile RolloverStrategy rolloverStrategy;
private static final AtomicReferenceFieldUpdater<RollingFileManager, TriggeringPolicy> triggeringPolicyUpdater =
AtomicReferenceFieldUpdater.newUpdater(RollingFileManager.class, TriggeringPolicy.class, "triggeringPolicy");
private static final AtomicReferenceFieldUpdater<RollingFileManager, RolloverStrategy> rolloverStrategyUpdater =
AtomicReferenceFieldUpdater.newUpdater(RollingFileManager.class, RolloverStrategy.class, "rolloverStrategy");
@Deprecated
protected RollingFileManager(final String fileName, final String pattern, final OutputStream os,
final boolean append, final long size, final long time, final TriggeringPolicy triggeringPolicy,
final RolloverStrategy rolloverStrategy, final String advertiseURI,
final Layout<? extends Serializable> layout, final int bufferSize, final boolean writeHeader) {
this(fileName, pattern, os, append, size, time, triggeringPolicy, rolloverStrategy, advertiseURI, layout,
writeHeader, ByteBuffer.wrap(new byte[Constants.ENCODER_BYTE_BUFFER_SIZE]));
}
protected RollingFileManager(final String fileName, final String pattern, final OutputStream os,
final boolean append, final long size, final long time, final TriggeringPolicy triggeringPolicy,
final RolloverStrategy rolloverStrategy, final String advertiseURI,
final Layout<? extends Serializable> layout, final boolean writeHeader, final ByteBuffer buffer) {
super(fileName, os, append, false, advertiseURI, layout, writeHeader, buffer);
this.size = size;
this.initialTime = time;
this.triggeringPolicy = triggeringPolicy;
this.rolloverStrategy = rolloverStrategy;
this.patternProcessor = new PatternProcessor(pattern);
triggeringPolicy.initialize(this);
}
/**
* Returns a RollingFileManager.
* @param fileName The file name.
* @param pattern The pattern for rolling file.
* @param append true if the file should be appended to.
* @param bufferedIO true if data should be buffered.
* @param policy The TriggeringPolicy.
* @param strategy The RolloverStrategy.
* @param advertiseURI the URI to use when advertising the file
* @param layout The Layout.
* @param bufferSize buffer size to use if bufferedIO is true
* @return A RollingFileManager.
*/
public static RollingFileManager getFileManager(final String fileName, final String pattern, final boolean append,
final boolean bufferedIO, final TriggeringPolicy policy, final RolloverStrategy strategy,
final String advertiseURI, final Layout<? extends Serializable> layout, final int bufferSize,
final boolean immediateFlush) {
return (RollingFileManager) getManager(fileName, new FactoryData(pattern, append,
bufferedIO, policy, strategy, advertiseURI, layout, bufferSize, immediateFlush), factory);
}
// override to make visible for unit tests
@Override
protected synchronized void write(final byte[] bytes, final int offset, final int length,
final boolean immediateFlush) {
super.write(bytes, offset, length, immediateFlush);
}
@Override
protected synchronized void writeToDestination(final byte[] bytes, final int offset, final int length) {
size += length;
super.writeToDestination(bytes, offset, length);
}
/**
* Returns the current size of the file.
* @return The size of the file in bytes.
*/
public long getFileSize() {
return size + byteBuffer.position();
}
/**
* Returns the time the file was created.
* @return The time the file was created.
*/
public long getFileTime() {
return initialTime;
}
/**
* Determine if a rollover should occur.
* @param event The LogEvent.
*/
public synchronized void checkRollover(final LogEvent event) {
if (triggeringPolicy.isTriggeringEvent(event)) {
rollover();
}
}
public synchronized void rollover() {
if (rollover(rolloverStrategy)) {
try {
size = 0;
initialTime = System.currentTimeMillis();
createFileAfterRollover();
} catch (final IOException e) {
logError("failed to create file after rollover", e);
}
}
}
protected void createFileAfterRollover() throws IOException {
final OutputStream os = new FileOutputStream(getFileName(), isAppend());
setOutputStream(os);
}
/**
* Returns the pattern processor.
* @return The PatternProcessor.
*/
public PatternProcessor getPatternProcessor() {
return patternProcessor;
}
public void setTriggeringPolicy(final TriggeringPolicy triggeringPolicy) {
triggeringPolicy.initialize(this);
triggeringPolicyUpdater.compareAndSet(this, this.triggeringPolicy, triggeringPolicy);
}
public void setRolloverStrategy(final RolloverStrategy rolloverStrategy) {
rolloverStrategyUpdater.compareAndSet(this, this.rolloverStrategy, rolloverStrategy);
}
/**
* Returns the triggering policy.
* @param <T> TriggeringPolicy type
* @return The TriggeringPolicy
*/
@SuppressWarnings("unchecked")
public <T extends TriggeringPolicy> T getTriggeringPolicy() {
// TODO We could parameterize this class with a TriggeringPolicy instead of type casting here.
return (T) this.triggeringPolicy;
}
/**
* Returns the rollover strategy.
* @return The RolloverStrategy
*/
public RolloverStrategy getRolloverStrategy() {
return this.rolloverStrategy;
}
private boolean rollover(final RolloverStrategy strategy) {
try {
// Block until the asynchronous operation is completed.
semaphore.acquire();
} catch (final InterruptedException e) {
logError("Thread interrupted while attempting to check rollover", e);
return false;
}
boolean success = false;
Thread thread = null;
try {
final RolloverDescription descriptor = strategy.rollover(this);
if (descriptor != null) {
writeFooter();
close();
if (descriptor.getSynchronous() != null) {
LOGGER.debug("RollingFileManager executing synchronous {}", descriptor.getSynchronous());
try {
success = descriptor.getSynchronous().execute();
} catch (final Exception ex) {
logError("caught error in synchronous task", ex);
}
}
if (success && descriptor.getAsynchronous() != null) {
LOGGER.debug("RollingFileManager executing async {}", descriptor.getAsynchronous());
thread = new Log4jThread(new AsyncAction(descriptor.getAsynchronous(), this));
thread.start();
}
return true;
}
return false;
} finally {
if (thread == null || !thread.isAlive()) {
semaphore.release();
}
}
}
/**
* Performs actions asynchronously.
*/
private static class AsyncAction extends AbstractAction {
private final Action action;
private final RollingFileManager manager;
/**
* Constructor.
* @param act The action to perform.
* @param manager The manager.
*/
public AsyncAction(final Action act, final RollingFileManager manager) {
this.action = act;
this.manager = manager;
}
/**
* Perform an action.
*
* @return true if action was successful. A return value of false will cause
* the rollover to be aborted if possible.
* @throws java.io.IOException if IO error, a thrown exception will cause the rollover
* to be aborted if possible.
*/
@Override
public boolean execute() throws IOException {
try {
return action.execute();
} finally {
manager.semaphore.release();
}
}
/**
* Cancels the action if not already initialized or waits till completion.
*/
@Override
public void close() {
action.close();
}
/**
* Determines if action has been completed.
*
* @return true if action is complete.
*/
@Override
public boolean isComplete() {
return action.isComplete();
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append(super.toString());
builder.append("[action=");
builder.append(action);
builder.append(", manager=");
builder.append(manager);
builder.append(", isComplete()=");
builder.append(isComplete());
builder.append(", isInterrupted()=");
builder.append(isInterrupted());
builder.append("]");
return builder.toString();
}
}
/**
* Factory data.
*/
private static class FactoryData {
private final String pattern;
private final boolean append;
private final boolean bufferedIO;
private final int bufferSize;
private final boolean immediateFlush;
private final TriggeringPolicy policy;
private final RolloverStrategy strategy;
private final String advertiseURI;
private final Layout<? extends Serializable> layout;
/**
* Create the data for the factory.
* @param pattern The pattern.
* @param append The append flag.
* @param bufferedIO The bufferedIO flag.
* @param advertiseURI
* @param layout The Layout.
* @param bufferSize the buffer size
* @param immediateFlush flush on every write or not
*/
public FactoryData(final String pattern, final boolean append, final boolean bufferedIO,
final TriggeringPolicy policy, final RolloverStrategy strategy, final String advertiseURI,
final Layout<? extends Serializable> layout, final int bufferSize, final boolean immediateFlush) {
this.pattern = pattern;
this.append = append;
this.bufferedIO = bufferedIO;
this.bufferSize = bufferSize;
this.policy = policy;
this.strategy = strategy;
this.advertiseURI = advertiseURI;
this.layout = layout;
this.immediateFlush = immediateFlush;
}
public TriggeringPolicy getTriggeringPolicy()
{
return this.policy;
}
public RolloverStrategy getRolloverStrategy()
{
return this.strategy;
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append(super.toString());
builder.append("[pattern=");
builder.append(pattern);
builder.append(", append=");
builder.append(append);
builder.append(", bufferedIO=");
builder.append(bufferedIO);
builder.append(", bufferSize=");
builder.append(bufferSize);
builder.append(", policy=");
builder.append(policy);
builder.append(", strategy=");
builder.append(strategy);
builder.append(", advertiseURI=");
builder.append(advertiseURI);
builder.append(", layout=");
builder.append(layout);
builder.append("]");
return builder.toString();
}
}
@Override
public void updateData(final Object data)
{
final FactoryData factoryData = (FactoryData) data;
setRolloverStrategy(factoryData.getRolloverStrategy());
setTriggeringPolicy(factoryData.getTriggeringPolicy());
}
/**
* Factory to create a RollingFileManager.
*/
private static class RollingFileManagerFactory implements ManagerFactory<RollingFileManager, FactoryData> {
/**
* Creates a RollingFileManager.
* @param name The name of the entity to manage.
* @param data The data required to create the entity.
* @return a RollingFileManager.
*/
@Override
public RollingFileManager createManager(final String name, final FactoryData data) {
final File file = new File(name);
final File parent = file.getParentFile();
if (null != parent && !parent.exists()) {
parent.mkdirs();
}
// LOG4J2-1140: check writeHeader before creating the file
final boolean writeHeader = !data.append || !file.exists();
try {
file.createNewFile();
} catch (final IOException ioe) {
LOGGER.error("Unable to create file " + name, ioe);
return null;
}
final long size = data.append ? file.length() : 0;
OutputStream os;
try {
os = new FileOutputStream(name, data.append);
final int actualSize = data.bufferedIO ? data.bufferSize : Constants.ENCODER_BYTE_BUFFER_SIZE;
final ByteBuffer buffer = ByteBuffer.wrap(new byte[actualSize]);
final long time = file.lastModified(); // LOG4J2-531 create file first so time has valid value
return new RollingFileManager(name, data.pattern, os, data.append, size, time, data.policy,
data.strategy, data.advertiseURI, data.layout, writeHeader, buffer);
} catch (final FileNotFoundException ex) {
LOGGER.error("FileManager (" + name + ") " + ex, ex);
}
return null;
}
}
}
| apache-2.0 |
ultradns/java_rest_api_client | src/main/java/biz/neustar/ultra/rest/client/RestApiClient.java | 50261 | package biz.neustar.ultra.rest.client;
import biz.neustar.ultra.rest.client.util.JsonUtils;
import biz.neustar.ultra.rest.constants.UltraRestSharedConstant;
import biz.neustar.ultra.rest.constants.ZoneType;
import biz.neustar.ultra.rest.dto.AccountList;
import biz.neustar.ultra.rest.dto.AlertDataList;
import biz.neustar.ultra.rest.dto.BatchRequest;
import biz.neustar.ultra.rest.dto.BatchResponse;
import biz.neustar.ultra.rest.dto.CreateType;
import biz.neustar.ultra.rest.dto.DnsSecInfo;
import biz.neustar.ultra.rest.dto.NameServerIpList;
import biz.neustar.ultra.rest.dto.PrimaryNameServers;
import biz.neustar.ultra.rest.dto.PrimaryZoneInfo;
import biz.neustar.ultra.rest.dto.ProbeInfo;
import biz.neustar.ultra.rest.dto.ProbeInfoList;
import biz.neustar.ultra.rest.dto.RRSet;
import biz.neustar.ultra.rest.dto.RRSetList;
import biz.neustar.ultra.rest.dto.SBTCNotification;
import biz.neustar.ultra.rest.dto.SBTCNotificationList;
import biz.neustar.ultra.rest.dto.SecondaryZoneInfo;
import biz.neustar.ultra.rest.dto.Status;
import biz.neustar.ultra.rest.dto.TaskStatusInfo;
import biz.neustar.ultra.rest.dto.TokenResponse;
import biz.neustar.ultra.rest.dto.Version;
import biz.neustar.ultra.rest.dto.WebForward;
import biz.neustar.ultra.rest.dto.WebForwardList;
import biz.neustar.ultra.rest.dto.Zone;
import biz.neustar.ultra.rest.dto.ZoneInfoList;
import biz.neustar.ultra.rest.dto.ZoneOutInfo;
import biz.neustar.ultra.rest.dto.ZoneProperties;
import biz.neustar.ultra.rest.main.ClientData;
import biz.neustar.ultra.rest.main.UltraRestClient;
import biz.neustar.ultra.rest.main.UltraRestClientFactory;
import biz.neustar.ultra.rest.main.auth.OAuth;
import biz.neustar.ultra.rest.main.auth.PasswordAuth;
import com.google.common.base.Strings;
import com.sun.jersey.core.util.MultivaluedMapImpl;
import javax.validation.constraints.NotNull;
import javax.ws.rs.core.MultivaluedMap;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Optional;
import static biz.neustar.ultra.rest.client.exception.UltraClientErrors.checkClientData;
/**
* Copyright 2012-2013 NeuStar, Inc. All rights reserved. NeuStar, the Neustar logo and related names and logos are
* registered trademarks, service marks or tradenames of NeuStar, Inc. All other product names, company names, marks,
* logos and symbols may be trademarks of their respective owners.
*/
@SuppressWarnings({
"PMD.TooManyMethods",
"PMD.ExcessivePublicCount"
})
public class RestApiClient {
public static final String ACCOUNTS = "accounts";
public static final String VERSION = "version";
public static final String STATUS = "status";
public static final String ACCOUNTS1 = "accounts/";
private static final String ZONES = "zones/";
private static final String RRSETS = "/rrsets/";
private static final String TYPEA = "A";
private static final String PROBES = "/probes";
private static final String ALERTS = "/alerts";
private static final String NOTIFICATIONS = "/notifications/";
private static final String AUTHORIZATION_TOKEN = "/authorization/token";
private static final String TASK = "/tasks/";
private static final String WEB_FORWARDS = "/webforwards";
private static final String UNSUSPEND = "/unsuspend";
private static final String BATCH = "batch";
private static final String SUB_ACCOUNTS = "subaccounts/";
private static final String TOKEN = "/token";
private static final String DNSSEC = "/dnssec";
private static final String V3 = "/v3/";
private static final int BASE_10_RADIX = 10;
private final UltraRestClient ultraRestClient;
private RestApiClient(UltraRestClient ultraRestClient) {
this.ultraRestClient = ultraRestClient;
}
public RestApiClient(String userName, String password, String url) {
ultraRestClient = UltraRestClientFactory.createRestClientOAuthUserPwd(url, userName, password,
AUTHORIZATION_TOKEN);
}
public RestApiClient(String userName, String password, String url, OAuth.Callback callback) {
ultraRestClient = UltraRestClientFactory.createRestClientOAuthUserPwdCallback(url, userName, password,
AUTHORIZATION_TOKEN, callback);
}
public static RestApiClient buildRestApiClientWithTokens(String accessToken, String refreshToken, String url,
OAuth.Callback callback) {
return new RestApiClient(
UltraRestClientFactory.createRestClientOAuthTokensCallback(url, accessToken, refreshToken,
AUTHORIZATION_TOKEN, callback));
}
public static RestApiClient buildRestApiClientWithUidPwd(String username, String password, String url,
OAuth.Callback callback) {
return new RestApiClient(UltraRestClientFactory.createRestClientOAuthUserPwdCallback(url, username, password,
AUTHORIZATION_TOKEN, callback));
}
public static RestApiClient buildRestApiClientWithUidPwd(String username, String url,
PasswordAuth.Callback callback) {
return new RestApiClient(
UltraRestClientFactory.createRestClientPasswordAuthUserPwd(url, username, AUTHORIZATION_TOKEN,
callback));
}
/**
* Create a primary zone.
*
* @param accountName - The account that the zone will be created under. The user must have write access for zones
* in that account
* @param zoneName - The name of the zone. The trailing . is optional. The zone name must not be in use by
* anyone
* @return - Status message
* @throws IOException - {@link IOException}
*/
public String createPrimaryZone(String accountName, String zoneName) throws IOException {
ZoneProperties zoneProperties = new ZoneProperties(zoneName, accountName, ZoneType.PRIMARY, null, null, null);
PrimaryZoneInfo primaryZoneInfo = new PrimaryZoneInfo(null, CreateType.NEW, null, null, null, null, null, null);
Zone zone = new Zone(zoneProperties, primaryZoneInfo, null, null);
String url = ZONES;
ClientData clientData = ultraRestClient.post(url, JsonUtils.objectToJson(zone));
checkClientData(clientData);
return clientData.getBody();
}
/**
* Create a secondary zone.
*
* @param accountName - The account that the zone will be created under. The user must have write
* access for zones in that account
* @param zoneName - The name of the zone. The trailing . is optional. The zone name must not be in
* use by anyone
* @param nameServerIpList - The primary name servers of the source zone for the secondary zone.
* @param notificationEmailAddress - The Notification Email for a secondary zone.
* @return - The task id of the secondary zone creation request
* @throws IOException - {@link IOException}
*/
public String createSecondaryZone(String accountName, String zoneName, NameServerIpList nameServerIpList,
String notificationEmailAddress) throws IOException {
ZoneProperties zoneProperties = new ZoneProperties(zoneName, accountName, ZoneType.SECONDARY, null, null, null);
SecondaryZoneInfo secondaryZoneInfo = new SecondaryZoneInfo(new PrimaryNameServers(nameServerIpList));
secondaryZoneInfo.setNotificationEmailAddress(notificationEmailAddress);
return createSecondaryZone(zoneProperties, secondaryZoneInfo);
}
/**
* Create a secondary zone.
*
* @param zoneProperties - {@link ZoneProperties}
* @param secondaryZoneInfo - {@link SecondaryZoneInfo}
* @return - The task id of the secondary zone creation request
* @throws IOException - {@link IOException}
*/
public String createSecondaryZone(ZoneProperties zoneProperties, SecondaryZoneInfo secondaryZoneInfo)
throws IOException {
Zone zone = new Zone(zoneProperties, null, secondaryZoneInfo, null);
String url = ZONES;
ClientData clientData = ultraRestClient.post(url, JsonUtils.objectToJson(zone));
checkClientData(clientData);
return clientData.getHeaders().getFirst(UltraRestSharedConstant.X_NEUSTAR_TASK_ID.getValue());
}
/**
* Update a secondary zone.
*
* @param zoneName - The name of the zone. The trailing . is optional. The zone name must not be in
* use by anyone
* @param nameServerIpList - The primary name servers of the source zone for the secondary zone.
* @param notificationEmailAddress - The Notification Email for a secondary zone.
* @return - Status message
* @throws IOException - {@link IOException}
*/
public String updateSecondaryZone(String zoneName, NameServerIpList nameServerIpList,
String notificationEmailAddress) throws IOException {
SecondaryZoneInfo secondaryZoneInfo = new SecondaryZoneInfo(new PrimaryNameServers(nameServerIpList));
secondaryZoneInfo.setNotificationEmailAddress(notificationEmailAddress);
Zone zone = new Zone(null, null, secondaryZoneInfo, null);
String url = ZONES + URLEncoder.encode(zoneName, UltraRestSharedConstant.UTF_8_CHAR_SET.getValue());
ClientData clientData = ultraRestClient.put(url, JsonUtils.objectToJson(zone));
checkClientData(clientData);
return clientData.getBody();
}
/**
* Get the task status.
*
* @param taskId - The task id.
* @return - The task status of the provided task id.
* @throws IOException - {@link IOException}
*/
public TaskStatusInfo getTaskStatus(String taskId) throws IOException {
String url = TASK + taskId;
ClientData clientData = ultraRestClient.get(url);
checkClientData(clientData);
return JsonUtils.jsonToObject(clientData.getBody(), TaskStatusInfo.class);
}
/**
* List zones for account.
*
* @param accountName - One of the user's accounts. The user must have read access for zone in that account
* @param q - The search parameters, in a hash. Valid keys are: name - substring match of the zone name
* zone_type - one of : PRIMARY/SECONDARY/ALIAS
* @param offset - The position in the list for the first returned element(0 based)
* @param limit - The maximum number of zones to be returned
* @param sort - The sort column used to order the list. Valid values for the sort field are:
* NAME/ACCOUNT_NAME/RECORD_COUNT/ZONE_TYPE
* @param reverse - Whether the list is ascending(false) or descending(true). Defaults to true
* @return - {@link ZoneInfoList}
* @throws IOException - {@link IOException}
*/
public ZoneInfoList getZonesOfAccount(String accountName, String q, int offset, int limit,
UltraRestSharedConstant.ZoneListSortType sort, boolean reverse) throws IOException {
MultivaluedMap<String, String> queryParams = buildQueryParams(q, offset, limit, sort, reverse);
String url = ACCOUNTS1 + URLEncoder.encode(accountName, UltraRestSharedConstant.UTF_8_CHAR_SET.getValue())
.replaceAll("\\+", "%20") + "/zones";
ClientData clientData = ultraRestClient.get(url, queryParams);
checkClientData(clientData);
return JsonUtils.jsonToObject(clientData.getBody(), ZoneInfoList.class);
}
/**
* List zones using cursor.
*
* @param q - name – The name of the zone to return (allows for partial string matches)
* @param cursor - Returned after the initial List Zones request. Use with the cursorInfo details for fetching the
* next or previous page(s).
* @param limit - The maximum number of rows requested. If not provided, the default value is 100.
* @return - {@link ZoneInfoList}
* @throws IOException - {@link IOException}
*/
public ZoneInfoList getZoneListByCursor(String q, String cursor, int limit) throws IOException {
MultivaluedMap<String, String> queryParams = buildQueryParams(q, null, limit, null, null, cursor);
String url = V3 + ZONES;
ClientData clientData = ultraRestClient.get(url, queryParams);
checkClientData(clientData);
return JsonUtils.jsonToObject(clientData.getBody(), ZoneInfoList.class);
}
/**
* Get zone metadata.
*
* @param zoneName - The name of the zone. The user must have read access to the zone.
* @return - {@link ZoneOutInfo}
* @throws IOException - {@link IOException}
*/
public ZoneOutInfo getZoneMetadata(String zoneName) throws IOException {
String url = ZONES + URLEncoder.encode(zoneName, UltraRestSharedConstant.UTF_8_CHAR_SET.getValue());
ClientData clientData = ultraRestClient.get(url);
checkClientData(clientData);
return JsonUtils.jsonToObject(clientData.getBody(), ZoneOutInfo.class);
}
/**
* Unsuspend a zone.
*
* @param zoneName - The name of the zone
*/
public Status unsuspendZone(String zoneName) throws IOException {
String url = ZONES + URLEncoder.encode(zoneName, UltraRestSharedConstant.UTF_8_CHAR_SET.getValue()) + UNSUSPEND;
ClientData clientData = ultraRestClient.post(url);
checkClientData(clientData);
return JsonUtils.jsonToObject(clientData.getBody(), Status.class);
}
/**
* Delete a zone.
*
* @param zoneName - The name of the zone
*/
public void deleteZone(String zoneName) throws IOException {
String url = ZONES + URLEncoder.encode(zoneName, UltraRestSharedConstant.UTF_8_CHAR_SET.getValue());
ClientData clientData = ultraRestClient.delete(url);
checkClientData(clientData);
System.out.println(clientData.getStatus());
}
/**
* Returns the list of RRSets in the specified zone.
*
* @param zoneName - The name of the zone. The user must have read access to the zone.
* @param q - The search parameters, in a hash. Valid keys are: ttl - must match the TTL for the rrset owner
* - substring match of the owner name value - substring match of the first BIND field value
* @param offset - The position in the list for the first returned element(0 based)
* @param limit - The maximum number of zones to be returned.
* @param sort - The sort column used to order the list. Valid values for the sort field are: OWNER/TTL/TYPE
* @param reverse - Whether the list is ascending(false) or descending(true). Defaults to true
* @return - {@link RRSetList}
* @throws IOException - {@link IOException}
*/
public RRSetList getRRSets(String zoneName, String q, int offset, int limit,
UltraRestSharedConstant.RRListSortType sort, boolean reverse) throws IOException {
MultivaluedMap<String, String> queryParams = buildQueryParams(q, offset, limit, sort, reverse);
String url = ZONES + URLEncoder.encode(zoneName, UltraRestSharedConstant.UTF_8_CHAR_SET.getValue()) + "/rrsets";
ClientData clientData = ultraRestClient.get(url, queryParams);
checkClientData(clientData);
return JsonUtils.jsonToObject(clientData.getBody(), RRSetList.class);
}
/**
* Returns the list of RRSets in the specified zone of the specified type.
*
* @param zoneName - The name of the zone.
* @param recordType - The type of the RRSets. This can be numeric (1) or if a well-known name is defined for the
* type (A), you can use it instead.
* @param q - The search parameters, in a hash. Valid keys are: ttl - must match the TTL for the rrset
* owner - substring match of the owner name value - substring match of the first BIND field
* value
* @param offset - The position in the list for the first returned element(0 based)
* @param limit - The maximum number of zones to be returned.
* @param sort - The sort column used to order the list. Valid values for the sort field are: OWNER/TTL/TYPE
* @param reverse - Whether the list is ascending(false) or descending(true). Defaults to true
* @return - {@link RRSetList}
* @throws IOException - {@link IOException}
*/
public RRSetList getRRSetsByType(String zoneName, String recordType, String q, int offset, int limit,
UltraRestSharedConstant.RRListSortType sort, boolean reverse) throws IOException {
MultivaluedMap<String, String> queryParams = buildQueryParams(q, offset, limit, sort, reverse);
String url = ZONES + URLEncoder.encode(zoneName, UltraRestSharedConstant.UTF_8_CHAR_SET.getValue()) + RRSETS
+ recordType;
ClientData clientData = ultraRestClient.get(url, queryParams);
checkClientData(clientData);
return JsonUtils.jsonToObject(clientData.getBody(), RRSetList.class);
}
/**
* Creates a new RRSet in the specified zone.
*
* @param zoneName - The zone that contains the RRSet.The trailing dot is optional.
* @param recordType - The type of the RRSet.This can be numeric (1) or if a well-known name is defined for the type
* (A), you can use it instead.
* @param ownerName - The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be
* relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute
* (foo.zonename.com.)
* @param ttl - The updated TTL value for the RRSet.
* @param rdata - The updated BIND data for the RRSet as a string. If there is a single resource record in the
* RRSet, you can pass in the single string or an array with a single element. If there are
* multiple resource records in this RRSet, pass in a list of strings.
* @return - Status message
* @throws IOException - {@link IOException}
*/
public String createRRSet(String zoneName, String recordType, String ownerName, Integer ttl, List<String> rdata)
throws IOException {
RRSet rrSet = new RRSet(zoneName, ownerName, recordType, ttl, rdata, null);
return createRRSet(zoneName, rrSet);
}
/**
* Creates a new RRSet in the specified zone.
*
*
* @param zoneName
* @param zoneName - The zone that contains the RRSet.The trailing dot is optional.
* @param rrSet - rrSet to be created.
* @return - Status message
* @throws IOException - {@link IOException}
*/
public String createRRSet(String zoneName, RRSet rrSet)
throws IOException {
String type = rrSet.getRrtype().replaceFirst(" *\\(\\d+\\)", "");
String url = ZONES + URLEncoder.encode(zoneName, UltraRestSharedConstant.UTF_8_CHAR_SET.getValue())
+ RRSETS
+ type + "/" + rrSet.getOwnerName();
ClientData clientData = ultraRestClient.post(url, JsonUtils.objectToJson(rrSet));
checkClientData(clientData);
return clientData.getBody();
}
/**
* Updates an existing RRSet in the specified zone.
*
* @param zoneName - The zone that contains the RRSet.The trailing dot is optional.
* @param recordType - The type of the RRSet.This can be numeric (1) or if a well-known name is defined for the type
* (A), you can use it instead.
* @param ownerName - The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be
* relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute
* (foo.zonename.com.)
* @param ttl - The updated TTL value for the RRSet.
* @param rdata - The updated BIND data for the RRSet as a string. If there is a single resource record in the
* RRSet, you can pass in the single string or an array with a single element. If there are
* multiple resource records in this RRSet, pass in a list of strings.
* @return - Status message
* @throws IOException - {@link IOException}
*/
public String updateRRSet(String zoneName, String recordType, String ownerName, Integer ttl, List<String> rdata)
throws IOException {
RRSet rrSet = new RRSet(zoneName, ownerName, recordType, ttl, rdata, null);
return updateRRSet(zoneName, rrSet);
}
/**
* Updates an existing RRSet in the specified zone.
*
*
* @param zoneName
* @param zoneName - The zone that contains the RRSet.The trailing dot is optional.
* @param rrSet - rrSet to be created.
* @return - Status message
* @throws IOException - {@link IOException}
*/
public String updateRRSet(String zoneName, RRSet rrSet)
throws IOException {
String type = rrSet.getRrtype().replaceFirst(" *\\(\\d+\\)", "");
String url = ZONES + URLEncoder.encode(zoneName, UltraRestSharedConstant.UTF_8_CHAR_SET.getValue())
+ RRSETS
+ type + "/" + rrSet.getOwnerName();
ClientData clientData = ultraRestClient.put(url, JsonUtils.objectToJson(rrSet));
checkClientData(clientData);
return clientData.getBody();
}
/**
* Delete an RRSet.
*
* @param zoneName - The zone containing the RRSet to be deleted. The trailing dot is optional.
* @param recordType - The type of the RRSet.This can be numeric (1) or if a well-known name is defined for the type
* (A), you can use it instead.
* @param ownerName - The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be
* relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute
* (foo.zonename.com.)
*/
public void deleteRRSet(String zoneName, String recordType, String ownerName) throws IOException {
String url = ZONES + URLEncoder.encode(zoneName, UltraRestSharedConstant.UTF_8_CHAR_SET.getValue()) + RRSETS
+ recordType + "/" + ownerName;
ClientData clientData = ultraRestClient.delete(url);
checkClientData(clientData);
}
/**
* Returns the list of ProbeInfo for the specified zone and owner.
*
* @param zoneName - The name of the zone. The user must have read access to the zone.
* @param ownerName - The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be
* relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute
* (foo.zonename.com.)
* @param q - may contain (space separated if both) type:TYPE and poolRecord:POOL_RECORD,
* where TYPE is one of RECORD, POOL, or ALL (default, unless poolRecord is specified),
* and POOL_RECORD is the IPv4 or CNAME as a FQDN for the pool record.
* If poolRecord is specified, type of RECORD is assumed
* @return - {@link ProbeInfoList}
* @throws IOException - {@link IOException}
*/
public ProbeInfoList getProbes(String zoneName, String ownerName, String q) throws IOException {
MultivaluedMap<String, String> queryParams = buildQueryParams(q, null, null, null, null);
String url = ZONES + URLEncoder.encode(zoneName, UltraRestSharedConstant.UTF_8_CHAR_SET.getValue()) + RRSETS
+ TYPEA + "/" + ownerName + PROBES;
ClientData clientData = ultraRestClient.get(url, queryParams);
checkClientData(clientData);
return JsonUtils.jsonToObject(clientData.getBody(), ProbeInfoList.class);
}
/**
* Creates a new probe in the specified zone and owner.
*
* @param zoneName - The zone that contains the RRSet. The trailing dot is optional.
* @param ownerName - The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be
* relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute
* (foo.zonename.com.)
* @param probeInfo - The probe info object.
* probeInfo/poolRecord - The pool record associated with this probe. Pass null/empty for a pool-level probe.
* probeInfo/type - PING, FTP, TCP, SMTP, SMTP_SEND, or DNS.
* probeInfo/interval - HALF_MINUTE, ONE_MINUTE, TWO_MINUTES, FIVE_MINUTES (default), TEN_MINUTES, or
* FIFTEEN_MINUTES.
* probeInfo/agents - See UltraDNS REST API User Guide for valid names.
* probeInfo/threshold - Number of agents that must agree for a probe state to be changed. From 1 to the number of
* agents specified
* probeInfo/details - Map of the type-specific fields for a probe. See UltraDNS REST API User Guide for fields.
* @return - The id for this probe.
* @throws IOException - {@link IOException}
*/
public String createProbe(String zoneName, String ownerName, ProbeInfo probeInfo)
throws IOException {
String url = ZONES + URLEncoder.encode(zoneName, UltraRestSharedConstant.UTF_8_CHAR_SET.getValue()) + RRSETS
+ TYPEA + "/" + ownerName + PROBES;
ClientData clientData = ultraRestClient.post(url, JsonUtils.objectToJson(probeInfo));
checkClientData(clientData);
return clientData.getBody();
}
/**
* Updates a probe with provided ID in the specified zone and owner.
*
* @param zoneName - The zone that contains the RRSet. The trailing dot is optional.
* @param ownerName - The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be
* relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute
* (foo.zonename.com.)
* @param probeInfo - The probe. ID must be equal to target probe GUID
* probeInfo/guid - GUID of the probe.
* probeInfo/type - PING, FTP, TCP, SMTP, SMTP_SEND, or DNS.
* probeInfo/interval - HALF_MINUTE, ONE_MINUTE, TWO_MINUTES, FIVE_MINUTES (default), TEN_MINUTES, or
* FIFTEEN_MINUTES.
* probeInfo/agents - See UltraDNS REST API User Guide for valid names.
* probeInfo/threshold - Number of agents that must agree for a probe state to be changed. From 1 to the number of
* agents specified
* probeInfo/details - Map of the type-specific fields for a probe. See UltraDNS REST API User Guide for fields.
* @return - Status message
* @throws IOException - {@link IOException}
*/
public String updateProbe(String zoneName, String ownerName, ProbeInfo probeInfo)
throws IOException {
String url = ZONES + URLEncoder.encode(zoneName, UltraRestSharedConstant.UTF_8_CHAR_SET.getValue()) + RRSETS
+ TYPEA + "/" + ownerName + PROBES + "/"
+ URLEncoder.encode(probeInfo.getId(), UltraRestSharedConstant.UTF_8_CHAR_SET.getValue());
ClientData clientData = ultraRestClient.put(url, JsonUtils.objectToJson(probeInfo));
checkClientData(clientData);
return clientData.getBody();
}
/**
* Deletes a probe with provided ID in the specified zone and owner.
*
* @param zoneName - The zone that contains the RRSet. The trailing dot is optional.
* @param ownerName - The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be
* relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute
* (foo.zonename.com.)
* @param guid - GUID of the probe.
* @throws IOException - {@link IOException}
*/
public void deleteProbe(String zoneName, String ownerName, String guid)
throws IOException {
String url = ZONES + URLEncoder.encode(zoneName, UltraRestSharedConstant.UTF_8_CHAR_SET.getValue()) + RRSETS
+ TYPEA + "/" + ownerName + PROBES + "/"
+ URLEncoder.encode(guid, UltraRestSharedConstant.UTF_8_CHAR_SET.getValue());
ClientData clientData = ultraRestClient.delete(url);
checkClientData(clientData);
System.out.println(clientData.getStatus());
}
/**
* Returns the list of AlertData for the specified zone and owner.
*
* @param zoneName - The name of the zone. The user must have read access to the zone.
* @param ownerName - The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be
* relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute
* (foo.zonename.com.)
* @param q - may contain status:STATUS,
* where STATUS is one of WARNING, CRITICAL, or FAIL
* @return - {@link AlertDataList}
* @throws IOException - {@link IOException}
*/
public AlertDataList getProbeAlerts(String zoneName, String ownerName, String q, int offset, int limit,
UltraRestSharedConstant.ProbeAlertSort sort, boolean reverse)
throws IOException {
MultivaluedMap<String, String> queryParams = buildQueryParams(q, offset, limit, sort, reverse);
String url = ZONES + URLEncoder.encode(zoneName, UltraRestSharedConstant.UTF_8_CHAR_SET.getValue()) + RRSETS
+ TYPEA + "/" + ownerName + ALERTS;
ClientData clientData = ultraRestClient.get(url, queryParams);
checkClientData(clientData);
return JsonUtils.jsonToObject(clientData.getBody(), AlertDataList.class);
}
/**
* Returns the list of SBTCNotification for the specified zone and owner.
*
* @param zoneName - The name of the zone. The user must have read access to the zone.
* @param ownerName - The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be
* relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute
* (foo.zonename.com.)
* @param poolRecord - If not null, will only provide notifications associated with the given pool record.
* @param email - If not null, will only provide notifications associated with the given email.
* @return - {@link SBTCNotificationList}
* @throws IOException - {@link IOException}
*/
public SBTCNotificationList getNotifications(String zoneName, String ownerName, String poolRecord, String email)
throws IOException {
String url = ZONES + URLEncoder.encode(zoneName, UltraRestSharedConstant.UTF_8_CHAR_SET.getValue()) + RRSETS
+ TYPEA + "/" + ownerName + NOTIFICATIONS;
if (email != null) {
url += URLEncoder.encode(email, UltraRestSharedConstant.UTF_8_CHAR_SET.getValue());
}
MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();
if (poolRecord != null) {
queryParams.add("poolRecord", poolRecord);
}
ClientData clientData = ultraRestClient.get(url, queryParams);
checkClientData(clientData);
return JsonUtils.jsonToObject(clientData.getBody(), SBTCNotificationList.class);
}
/**
* Creates new SBTCNotification in the specified zone and owner.
*
* @param zoneName - The zone that contains the RRSet. The trailing dot is optional.
* @param ownerName - The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be
* relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute
* (foo.zonename.com.)
* @param email - The notification email.
* @param notification - The notification object.
* @return - Status message
* @throws IOException - {@link IOException}
*/
public String createNotification(String zoneName, String ownerName, String email, SBTCNotification notification)
throws IOException {
String url = ZONES + URLEncoder.encode(zoneName, UltraRestSharedConstant.UTF_8_CHAR_SET.getValue()) + RRSETS
+ TYPEA + "/" + ownerName + NOTIFICATIONS
+ URLEncoder.encode(email, UltraRestSharedConstant.UTF_8_CHAR_SET.getValue());
ClientData clientData = ultraRestClient.post(url, JsonUtils.objectToJson(notification));
checkClientData(clientData);
return clientData.getBody();
}
/**
* Updates a probe with provided ID in the specified zone and owner.
*
* @param zoneName - The zone that contains the RRSet. The trailing dot is optional.
* @param ownerName - The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be
* relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute
* (foo.zonename.com.)
* @param email - The notification email.
* @param notification - The notification object.
* @return - Status message
* @throws IOException - {@link IOException}
*/
public String updateNotification(String zoneName, String ownerName, String email, SBTCNotification notification)
throws IOException {
String url = ZONES + URLEncoder.encode(zoneName, UltraRestSharedConstant.UTF_8_CHAR_SET.getValue()) + RRSETS
+ TYPEA + "/" + ownerName + NOTIFICATIONS
+ URLEncoder.encode(email, UltraRestSharedConstant.UTF_8_CHAR_SET.getValue());
ClientData clientData = ultraRestClient.put(url, JsonUtils.objectToJson(notification));
checkClientData(clientData);
return clientData.getBody();
}
/**
* Deletes a notification with provided email in the specified zone and owner.
*
* @param zoneName - The zone that contains the RRSet. The trailing dot is optional.
* @param ownerName - The owner name for the RRSet. If no trailing dot is supplied, the owner_name is assumed to be
* relative (foo). If a trailing dot is supplied, the owner name is assumed to be absolute
* (foo.zonename.com.)
* @param email - The notification email.
* @throws IOException - {@link IOException}
*/
public void deleteNotification(String zoneName, String ownerName, String email)
throws IOException {
String url = ZONES + URLEncoder.encode(zoneName, UltraRestSharedConstant.UTF_8_CHAR_SET.getValue()) + RRSETS
+ TYPEA + "/" + ownerName + NOTIFICATIONS
+ URLEncoder.encode(email, UltraRestSharedConstant.UTF_8_CHAR_SET.getValue());
ClientData clientData = ultraRestClient.delete(url);
checkClientData(clientData);
System.out.println(clientData.getStatus());
}
/**
* Get account details for user.
*
* @return - {@link AccountList}
* @throws IOException - {@link IOException}
*/
public AccountList getAccountDetails() throws IOException {
String url = ACCOUNTS;
ClientData clientData = ultraRestClient.get(url);
checkClientData(clientData);
return JsonUtils.jsonToObject(clientData.getBody(), AccountList.class);
}
/**
* Get version of REST API server.
*
* @return - The version of REST API server
*/
public Version getVersion() throws IOException {
ClientData clientData = ultraRestClient.get(VERSION);
checkClientData(clientData);
return JsonUtils.jsonToObject(clientData.getBody(), Version.class);
}
/**
* Get status of REST API server.
*
* @return - The status of REST API server
*/
public Status getStatus() throws IOException {
ClientData clientData = ultraRestClient.get(STATUS);
checkClientData(clientData);
return JsonUtils.jsonToObject(clientData.getBody(), Status.class);
}
private MultivaluedMap<String, String> buildQueryParams(String q, Integer offset, Integer limit, Enum sort,
Boolean reverse) {
MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();
if (!Strings.isNullOrEmpty(q)) {
queryParams.add("q", q);
}
Optional.ofNullable(offset).ifPresent(o -> queryParams.add("offset", Integer.toString(o, BASE_10_RADIX)));
Optional.ofNullable(limit).ifPresent(l -> queryParams.add("limit", Integer.toString(l, BASE_10_RADIX)));
Optional.ofNullable(sort).ifPresent(s -> queryParams.add("sort", sort.toString()));
Optional.ofNullable(reverse).ifPresent(r -> queryParams.add("reverse", Boolean.toString(reverse)));
return queryParams;
}
private MultivaluedMap<String, String> buildQueryParams(String q, Integer offset, Integer limit, Enum sort,
Boolean reverse, String cursor) {
MultivaluedMap<String, String> queryParams = buildQueryParams(q, offset, limit, sort, reverse);
Optional.ofNullable(cursor).ifPresent(c -> queryParams.add("cursor", cursor));
return queryParams;
}
/**
* Create a web forward.
*
* @param zoneName - The name of the zone. The trailing . is optional.
* @param webForward - The {@link WebForward} details.
* @return - The created {@link WebForward}
* @throws IOException - {@link IOException}
*/
public WebForward createWebForward(@NotNull final String zoneName, @NotNull WebForward webForward)
throws IOException {
String url =
ZONES + URLEncoder.encode(zoneName, UltraRestSharedConstant.UTF_8_CHAR_SET.getValue()) + WEB_FORWARDS;
ClientData clientData = ultraRestClient.post(url, JsonUtils.objectToJson(webForward));
checkClientData(clientData);
return JsonUtils.jsonToObject(clientData.getBody(), WebForward.class);
}
/**
* Get the list of web forwards.
*
* @param zoneName - The name of the zone. The trailing . is optional.
* @param q - The search parameters. Valid keys are:
* type - Valid values include:
* o Framed
* o HTTP_301_REDIRECT
* o HTTP_302_REDIRECT
* o HTTP_303_REDIRECT
* o HTTP_307_REDIRECT
* o Advanced
* advanced - Valid values include true and false.
* name – any string, will map to anything in either the host or the target.
* @param offset - The position in the list for the first returned element(0 based)
* @param limit - The maximum number of rows to be returned.
* @param sort - The sort column used to order the list. Valid values for the sort field are:
* REQUEST_TO (this is the default)
* REDIRECT_TO
* TYPE
* DOMAIN
* ADVANCED
* @param reverse - Whether the list is ascending(false) or descending(true). Defaults to true
* @throws IOException - {@link IOException}
*/
public WebForwardList getWebForwardList(@NotNull final String zoneName, String q, int offset, int limit,
UltraRestSharedConstant.WFListSortFields sort, boolean reverse) throws IOException {
MultivaluedMap<String, String> queryParams = buildQueryParams(q, offset, limit, sort, reverse);
String url =
ZONES + URLEncoder.encode(zoneName, UltraRestSharedConstant.UTF_8_CHAR_SET.getValue()) + WEB_FORWARDS;
ClientData clientData = ultraRestClient.get(url, queryParams);
checkClientData(clientData);
return JsonUtils.jsonToObject(clientData.getBody(), WebForwardList.class);
}
/**
* Update a web forward.
*
* @param zoneName - The name of the zone. The trailing . is optional.
* @param guid - The System-generated unique identifier for this object.
* @param webForward - The {@link WebForward} details.
* @return - The created {@link WebForward}
* @throws IOException - {@link IOException}
*/
public String updateWebForward(@NotNull final String zoneName, @NotNull String guid, @NotNull WebForward webForward)
throws IOException {
String url =
ZONES + URLEncoder.encode(zoneName, UltraRestSharedConstant.UTF_8_CHAR_SET.getValue()) + WEB_FORWARDS
+ "/" + guid;
ClientData clientData = ultraRestClient.put(url, JsonUtils.objectToJson(webForward));
checkClientData(clientData);
return clientData.getBody();
}
/**
* Delete a web forward.
*
* @param zoneName - The name of the zone. The trailing . is optional.
* @param guid - The System-generated unique identifier for this object.
* @throws IOException - {@link IOException}
*/
public void deleteWebForward(@NotNull final String zoneName, @NotNull String guid) throws IOException {
String url =
ZONES + URLEncoder.encode(zoneName, UltraRestSharedConstant.UTF_8_CHAR_SET.getValue()) + WEB_FORWARDS
+ "/" + guid;
ClientData clientData = ultraRestClient.delete(url);
checkClientData(clientData);
}
/**
* Perform a Batch operation.
*
* @param batchRequests - The list of batch requests. Make sure the URIs are properly encoded as per Ultra REST API
* standards, for example the spaces are replaced with '%20' etc.
* @return - The {@link BatchResponse} list
*/
public List<BatchResponse> batchOperation(@NotNull List<BatchRequest> batchRequests) throws IOException {
String url = BATCH;
ClientData clientData = ultraRestClient.post(url, JsonUtils.objectToJson(batchRequests));
checkClientData(clientData);
return JsonUtils.jsonToList(clientData.getBody(), BatchResponse.class);
}
/**
* Perform a Batch operation asynchronously.
*
* @param batchRequests - The list of batch requests. Make sure the URIs are properly encoded as per Ultra REST API
* standards, for example the spaces are replaced with '%20' etc.
* @return - The task id of the created background task
*/
public String asyncBatchOperation(@NotNull List<BatchRequest> batchRequests) throws IOException {
String url = BATCH;
MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();
queryParams.add("async", "true");
ClientData clientData = ultraRestClient.post(url, queryParams, JsonUtils.objectToJson(batchRequests));
checkClientData(clientData);
return clientData.getHeaders().getFirst(UltraRestSharedConstant.X_NEUSTAR_TASK_ID.getValue());
}
/**
* Build the {@link RestApiClient} for a Reseller's sub-account.
*
* @param subAccountName - The sub-account name to access.
* @return - The {@link RestApiClient} to access the sub-account resources.
*/
public RestApiClient buildRestApiClientForSubAccountAccess(@NotNull String subAccountName) throws IOException {
String url = SUB_ACCOUNTS + URLEncoder.encode(subAccountName, UltraRestSharedConstant.UTF_8_CHAR_SET.getValue())
.replaceAll("\\+", "%20") + TOKEN;
ClientData clientData = ultraRestClient.retryablePost(url);
checkClientData(clientData);
TokenResponse subAccountTokenResponse = JsonUtils.jsonToObject(clientData.getBody(), TokenResponse.class);
return buildRestApiClientWithTokens(subAccountTokenResponse.getAccessToken(), null,
this.ultraRestClient.getBaseUrl(), null);
}
/**
* List zones of Reseller's sub-accounts.
*
* @param q - The search parameters, in a hash. Valid keys are:
* o account_name – will only return results that match the provided sub account accountName.
* For account names that include spaces in them, replace the space with “%20”.
* o match - Valid values for match include: o name o zone_type o zone_status
* o dnssec_status o Account_name (only sub account names)
* @param offset - The position in the list for the first returned element(0 based)
* @param limit - The maximum number of zones to be returned
* @param sort - The sort column used to order the list. Valid values for the sort field are:
* NAME/ACCOUNT_NAME/ZONE_TYPE
* @param reverse - Whether the list is ascending(false) or descending(true). Defaults to true
* @return - {@link ZoneInfoList}
* @throws IOException - {@link IOException}
*/
public ZoneInfoList listSubAccountsZones(String q, int offset, int limit,
UltraRestSharedConstant.ZoneListSortType sort, boolean reverse) throws IOException {
MultivaluedMap<String, String> queryParams = buildQueryParams(q, offset, limit, sort, reverse);
String url = SUB_ACCOUNTS + "/zones";
ClientData clientData = ultraRestClient.get(url, queryParams);
checkClientData(clientData);
return JsonUtils.jsonToObject(clientData.getBody(), ZoneInfoList.class);
}
/**
* List the basic information of Reseller's sub-accounts.
*
* @param q - The search parameters, in a hash. Valid keys are:
* o account_name – will only return results that match the provided accountName. For account
* names that include spaces in them, replace the space with “%20”.
* o match - Valid values for match include: o ANYWHERE o EXACT o START o END
* @param offset - The position in the list for the first returned element(0 based)
* @param limit - The maximum number of zones to be returned
* @param reverse - Whether the list is ascending(false) or descending(true). Defaults to true
* @return - {@link AccountList}
* @throws IOException - {@link IOException}
*/
public AccountList listSubAccounts(String q, int offset, int limit, boolean reverse) throws IOException {
MultivaluedMap<String, String> queryParams = buildQueryParams(q, offset, limit, null, reverse);
String url = SUB_ACCOUNTS;
ClientData clientData = ultraRestClient.get(url, queryParams);
checkClientData(clientData);
return JsonUtils.jsonToObject(clientData.getBody(), AccountList.class);
}
/**
* Sign a zone.
*
* @param zoneName - The name of the zone. The trailing . is optional.
* @return - Either the task id of the created background task or the status message.
* @throws IOException - {@link IOException}
*/
public String signZone(@NotNull final String zoneName) throws IOException {
String url = ZONES + URLEncoder.encode(zoneName, UltraRestSharedConstant.UTF_8_CHAR_SET.getValue()) + DNSSEC;
ClientData clientData = ultraRestClient.post(url);
checkClientData(clientData);
return Optional.ofNullable(
clientData.getHeaders().getFirst(UltraRestSharedConstant.X_NEUSTAR_TASK_ID.getValue()))
.orElse(clientData.getBody());
}
/**
* Unsign a zone.
*
* @param zoneName - The name of the zone. The trailing . is optional.
* @return - Either the task id of the created background task or the status message.
* @throws IOException - {@link IOException}
*/
public String unsignZone(@NotNull final String zoneName) throws IOException {
String url = ZONES + URLEncoder.encode(zoneName, UltraRestSharedConstant.UTF_8_CHAR_SET.getValue()) + DNSSEC;
ClientData clientData = ultraRestClient.delete(url);
return Optional.ofNullable(
clientData.getHeaders().getFirst(UltraRestSharedConstant.X_NEUSTAR_TASK_ID.getValue()))
.orElse(clientData.getBody());
}
/**
* Re-sign a zone.
*
* @param zoneName - The name of the zone. The trailing . is optional.
* @return - Either the task id of the created background task or the status message.
* @throws IOException - {@link IOException}
*/
public String reSignZone(@NotNull final String zoneName) throws IOException {
String url = ZONES + URLEncoder.encode(zoneName, UltraRestSharedConstant.UTF_8_CHAR_SET.getValue()) + DNSSEC;
ClientData clientData = ultraRestClient.put(url, null);
checkClientData(clientData);
return Optional.ofNullable(
clientData.getHeaders().getFirst(UltraRestSharedConstant.X_NEUSTAR_TASK_ID.getValue()))
.orElse(clientData.getBody());
}
/**
* Get DnsSec info of a signed zone.
*
* @param zoneName - The name of the zone. The trailing . is optional.
* @return - {@link DnsSecInfo}
* @throws IOException - {@link IOException}
*/
public DnsSecInfo getDnsSecInfo(@NotNull final String zoneName) throws IOException {
String url = ZONES + URLEncoder.encode(zoneName, UltraRestSharedConstant.UTF_8_CHAR_SET.getValue()) + DNSSEC;
ClientData clientData = ultraRestClient.get(url);
checkClientData(clientData);
return JsonUtils.jsonToObject(clientData.getBody(), DnsSecInfo.class);
}
}
| apache-2.0 |
vanilla-ci/worker | src/test/java/com/vanillaci/worker/testplugins/TerminateStep.java | 329 | package com.vanillaci.worker.testplugins;
import com.vanillaci.plugins.*;
import com.vanillaci.worker.model.*;
/**
* Simply terminates
* Created by joeljohnson on 11/27/14.
*/
public class TerminateStep implements WorkStep {
@Override
public void execute(WorkContext workContext) {
workContext.setTerminated(true);
}
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-qldb/src/main/java/com/amazonaws/services/qldb/model/transform/DescribeJournalKinesisStreamResultJsonUnmarshaller.java | 3008 | /*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.qldb.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.qldb.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* DescribeJournalKinesisStreamResult JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DescribeJournalKinesisStreamResultJsonUnmarshaller implements Unmarshaller<DescribeJournalKinesisStreamResult, JsonUnmarshallerContext> {
public DescribeJournalKinesisStreamResult unmarshall(JsonUnmarshallerContext context) throws Exception {
DescribeJournalKinesisStreamResult describeJournalKinesisStreamResult = new DescribeJournalKinesisStreamResult();
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL) {
return describeJournalKinesisStreamResult;
}
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("Stream", targetDepth)) {
context.nextToken();
describeJournalKinesisStreamResult.setStream(JournalKinesisStreamDescriptionJsonUnmarshaller.getInstance().unmarshall(context));
}
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return describeJournalKinesisStreamResult;
}
private static DescribeJournalKinesisStreamResultJsonUnmarshaller instance;
public static DescribeJournalKinesisStreamResultJsonUnmarshaller getInstance() {
if (instance == null)
instance = new DescribeJournalKinesisStreamResultJsonUnmarshaller();
return instance;
}
}
| apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-neptune/src/main/java/com/amazonaws/services/neptune/model/transform/DeleteDBInstanceRequestMarshaller.java | 2434 | /*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.neptune.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.neptune.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.StringUtils;
/**
* DeleteDBInstanceRequest Marshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DeleteDBInstanceRequestMarshaller implements Marshaller<Request<DeleteDBInstanceRequest>, DeleteDBInstanceRequest> {
public Request<DeleteDBInstanceRequest> marshall(DeleteDBInstanceRequest deleteDBInstanceRequest) {
if (deleteDBInstanceRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
Request<DeleteDBInstanceRequest> request = new DefaultRequest<DeleteDBInstanceRequest>(deleteDBInstanceRequest, "AmazonNeptune");
request.addParameter("Action", "DeleteDBInstance");
request.addParameter("Version", "2014-10-31");
request.setHttpMethod(HttpMethodName.POST);
if (deleteDBInstanceRequest.getDBInstanceIdentifier() != null) {
request.addParameter("DBInstanceIdentifier", StringUtils.fromString(deleteDBInstanceRequest.getDBInstanceIdentifier()));
}
if (deleteDBInstanceRequest.getSkipFinalSnapshot() != null) {
request.addParameter("SkipFinalSnapshot", StringUtils.fromBoolean(deleteDBInstanceRequest.getSkipFinalSnapshot()));
}
if (deleteDBInstanceRequest.getFinalDBSnapshotIdentifier() != null) {
request.addParameter("FinalDBSnapshotIdentifier", StringUtils.fromString(deleteDBInstanceRequest.getFinalDBSnapshotIdentifier()));
}
return request;
}
}
| apache-2.0 |
likyateknoloji/TlosSWGroup | TlosSW_V1.0_Model/src/com/likya/tlossw/model/client/resource/CpuInfoTypeClient.java | 1160 | /*
* TlosSW_V1.0_Model
* com.likya.tlossw.model.client.resource : CpuInfoTypeClient.java
* @author Merve Ozbey
* Tarih : 29.Sub.2012 09:55:35
*/
package com.likya.tlossw.model.client.resource;
import java.io.Serializable;
public class CpuInfoTypeClient implements Serializable {
private static final long serialVersionUID = -5515964343669496851L;
private String cpuUnit;
private String usedCpuOneMin;
private String usedCpuFiveMin;
private String usedCpuFifteenMin;
public String getCpuUnit() {
return cpuUnit;
}
public void setCpuUnit(String cpuUnit) {
this.cpuUnit = cpuUnit;
}
public String getUsedCpuOneMin() {
return usedCpuOneMin;
}
public void setUsedCpuOneMin(String usedCpuOneMin) {
this.usedCpuOneMin = usedCpuOneMin;
}
public String getUsedCpuFiveMin() {
return usedCpuFiveMin;
}
public void setUsedCpuFiveMin(String usedCpuFiveMin) {
this.usedCpuFiveMin = usedCpuFiveMin;
}
public String getUsedCpuFifteenMin() {
return usedCpuFifteenMin;
}
public void setUsedCpuFifteenMin(String usedCpuFifteenMin) {
this.usedCpuFifteenMin = usedCpuFifteenMin;
}
} | apache-2.0 |
paetti1988/qmate | PCCS/org.tud.inf.st.pceditor/src-parsec/org/codehaus/jparsec/ToTokenParser.java | 657 | package org.codehaus.jparsec;
/**
* Converts the current return value as a {@link Token} with starting index and length.
*
* @author Ben Yu
*/
final class ToTokenParser extends Parser<Token> {
private final Parser<?> parser;
ToTokenParser(Parser<?> parser) {
this.parser = parser;
}
@Override boolean apply(ParseContext ctxt) {
int begin = ctxt.getIndex();
if (!parser.apply(ctxt)) {
return false;
}
int len = ctxt.getIndex() - begin;
Token token = new Token(begin, len, ctxt.result);
ctxt.result = token;
return true;
}
@Override public String toString() {
return parser.toString();
}
}
| apache-2.0 |
smrjan/seldon-server | server/src/io/seldon/api/service/async/JdoAsyncActionFactory.java | 4727 | /*
* Seldon -- open source prediction engine
* =======================================
*
* Copyright 2011-2015 Seldon Technologies Ltd and Rummble Ltd (http://www.seldon.io/)
*
* ********************************************************************************************
*
* 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.seldon.api.service.async;
import io.seldon.api.state.NewClientListener;
import io.seldon.api.state.options.DefaultOptions;
import io.seldon.api.state.zk.ZkClientConfigHandler;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import javax.annotation.PostConstruct;
import io.seldon.db.jdo.DbConfigHandler;
import io.seldon.db.jdo.DbConfigListener;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class JdoAsyncActionFactory implements DbConfigListener{
private static final String DEF_HOSTNAME = "TEST";
private static Logger logger = Logger.getLogger(JdoAsyncActionFactory.class.getName());
private static boolean active = false;
private ConcurrentHashMap<String,AsyncActionQueue> queues = new ConcurrentHashMap<>();
private static int DEF_QTIMEOUT_SECS = 5;
private static int DEF_MAXQSIZE = 100000;
private static int DEF_BATCH_SIZE = 2000;
private static int DEF_DB_RETRIES = 3;
private static boolean DEF_RUN_USERITEM_UPDATES = true;
private static boolean DEF_UPDATE_IDS_ACTION_TABLE = true;
private static boolean DEF_INSERT_ACTIONS = true;
public static final String ASYNC_PROP_PREFIX = "io.seldon.asyncactions";
private static Properties props;
private static boolean asyncUserWrites = true;
private static boolean asyncItemWrites = true;
public static boolean isActive() {
return active;
}
DefaultOptions options;
@Autowired
public JdoAsyncActionFactory(DefaultOptions options,DbConfigHandler dbConfigHandler)
{
this.options = options;
dbConfigHandler.addDbConfigListener(this);
}
public void clientDeleted(String client) {
logger.info("Removing client:"+client);
AsyncActionQueue q = queues.get(client);
if (q != null)
{
q.setKeepRunning(false);
queues.remove(client);
}
else
logger.warn("Unknown client - can't remove "+client);
}
private AsyncActionQueue create(String client)
{
int qTimeout = DEF_QTIMEOUT_SECS;
int maxqSize = DEF_MAXQSIZE;
int batchSize = DEF_BATCH_SIZE;
int dbRetries = DEF_DB_RETRIES;
boolean runUserItemUpdates = DEF_RUN_USERITEM_UPDATES;
boolean runUpdateIdsActionTable = DEF_UPDATE_IDS_ACTION_TABLE;
boolean insertActions = DEF_INSERT_ACTIONS;
return create(client,qTimeout,batchSize,maxqSize,dbRetries,runUserItemUpdates,runUpdateIdsActionTable,insertActions);
}
private static AsyncActionQueue create(String client,int qtimeoutSecs,int batchSize,int qSize,int dbRetries,boolean runUserItemUpdates,boolean runUpdateIdsActionTable,boolean insertActions)
{
JdoAsyncActionQueue q = new JdoAsyncActionQueue(client,qtimeoutSecs,batchSize,qSize,dbRetries,runUserItemUpdates,runUpdateIdsActionTable,insertActions);
Thread t = new Thread(q);
t.start();
return q;
}
public AsyncActionQueue get(String client)
{
AsyncActionQueue queue = queues.get(client);
if (queue == null)
{
queues.putIfAbsent(client, create(client));
queue = get(client);
}
return queue;
}
public static boolean isAsyncUserWrites() {
return asyncUserWrites;
}
public static void setAsyncUserWrites(boolean asyncUserWrites) {
JdoAsyncActionFactory.asyncUserWrites = asyncUserWrites;
}
public static boolean isAsyncItemWrites() {
return asyncItemWrites;
}
public static void setAsyncItemWrites(boolean asyncItemWrites) {
JdoAsyncActionFactory.asyncItemWrites = asyncItemWrites;
}
private void shutdownQueues()
{
for(Map.Entry<String,AsyncActionQueue> e : queues.entrySet())
{
e.getValue().setKeepRunning(false);
}
}
@Override
public void dbConfigInitialised(String client) {
logger.info("Adding client: "+client);
get(client);
}
}
| apache-2.0 |
bubichain/blockchain | test/testcase/testng/APITest-1.0/src/cases/ApiTestModifyEvidence.java | 13788 | package cases;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Random;
import org.testng.annotations.Test;
import base.TestBase;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import utils.APIUtil;
import utils.HttpUtil;
@Test
public class ApiTestModifyEvidence extends ApiGeneralCases {
//definition of conditions
final static int noTradeNo = 1<<1;
final static int invalidTradeNo = 1<<2;
final static int validTradeNo = 1<<3;
final static int noSigners = 1<<4;
final static int invalidSigners = 1<<5;
final static int validSigners = 1<<6;
final static int noEvidenceId = 1<<7;
final static int invalidEvidenceId = 1<<8;
final static int validEvidenceId = 1<<9;
final static int invalidAccessToken = 1<<22;
final static int noAccessToken = 1<<23;
final static int validAccessToken = 1<<24;
final static int noMetaData = 1<<25;
final static int invalidMetaData = 1<<26;
final static int validMetaData = 1<<27;
//definition of sub conditions
final static int overlimit = 1<<0;
final static int specialchar = 1<<1;
final static int floatnumber = 1<<2;
final static int isnull = 1<<3;
final static int isminus = 1<<4;
final static int illegal =1<<5;
final static int notexist =1<<6;
final static int iszero =1<<7;
final static int isChinese =1<<8;
final static int underlimit = 1<<9;
//when modify with the same users with create
final static int normalsign = 1<<16;
final static int oneaddress = 1<<10;
final static int threeaddress = 1<<11;
//when modify with the different users with create
final static int sameaddress = 1<<14;
final static int nosigners = 1<<15;
final static int wrongaddress = 1<<12;
final static int wrongpassword = 1<<13;
final static int signernumber_diff = 1<<17;
//when modify with metadata conditions
final static int nullmeta = 1<<24;
final static int longmeta = 1<<25;
final static int specialmeta = 1<<26;
static Random rand = new Random();
static int tradeNoBase = rand.nextInt(255);
static String trade_no = new String();
public static StringBuffer user_name1 = new StringBuffer("");
public static StringBuffer address1 = new StringBuffer("");
public static StringBuffer user_name2 = new StringBuffer("");
public static StringBuffer address2 = new StringBuffer("");
public static StringBuffer user_name3 = new StringBuffer("");
public static StringBuffer address3 = new StringBuffer("");
public static StringBuffer evidence_id = new StringBuffer("");
public static StringBuffer bchash = new StringBuffer("");
private int current_condition = 0;
private int current_condition_sub = 0;
public static String bc_hash = null;
public static String metadata = null;
public static String source_address = null;
//public static String evidence = null;
private void TestModifyEvidence(Object param, JSONArray sign,int signernum)
{
JSONArray signers = new JSONArray();
JSONObject singlesigner = new JSONObject();
if(signernum >0)
{
singlesigner.put("bubi_address", address1.toString());
singlesigner.put("password" ,user_name1.toString());
signers.add(singlesigner);
if(signernum>1)
{
singlesigner.put("bubi_address", address2.toString());
singlesigner.put("password" ,user_name2.toString());
signers.add(singlesigner);
if(signernum>2)
{
singlesigner.put("bubi_address", address3.toString());
singlesigner.put("password" ,user_name3.toString());
signers.add(singlesigner);
}
}
}
CreateEvidence(access_token,signers,"create an evidence",evidence_id,bchash);
String api_path = "/evidence/v1/modify" ;
if(!APIUtil.getbool(current_condition&noAccessToken))
{
if(APIUtil.getbool(current_condition&invalidAccessToken))
parameter.put("access_token",(String)param);
else
parameter.put("access_token",access_token);
}
if(!APIUtil.getbool(current_condition&noMetaData))
{
if(APIUtil.getbool(current_condition&invalidMetaData))
{
metadata = (String)param;
thrMap.put("metadata",metadata);
}
else
{
metadata = "this is a metadata";
thrMap.put("metadata",metadata);
}
}
if(!APIUtil.getbool(current_condition&noEvidenceId))
{
if(APIUtil.getbool(current_condition&invalidEvidenceId))
thrMap.put("evidence_id",(String)param);
else
thrMap.put("evidence_id",evidence_id.toString());
}
if(!APIUtil.getbool(current_condition&noTradeNo))
{
//need test limits
if(APIUtil.getbool(current_condition&(invalidTradeNo|validTradeNo)))
{
thrMap.put("trade_no", (String)param);
trade_no = (String)param;
}
else//put a standard one
{
trade_no = Long.toString((tradeNoBase++)+(System.currentTimeMillis()<<8));
thrMap.put("trade_no", trade_no);
}
}
if(sign!=null)
{
thrMap.put("signers", sign);
}
JSONObject jsonBody = JSONObject.fromObject(thrMap);
System.out.println("=========Modify Evidence========");
String result = HttpUtil.dopostApi(api_url, api_path, parameter, jsonBody);
JSONObject jsonObject =JSONObject.fromObject(result);
Verification(jsonObject);
user_name1.delete(0, user_name1.length());
user_name2.delete(0, user_name2.length());
user_name3.delete(0, user_name3.length());
address1.delete(0, address1.length());
address2.delete(0, address2.length());
address3.delete(0, address3.length());
evidence_id.delete(0, evidence_id.length());
}
private void Verification(JSONObject jsonObject)
{
switch (current_condition)
{
case validAccessToken :
case validMetaData :
case validTradeNo :
case invalidMetaData :
case noMetaData :
case validEvidenceId :
check.equals(jsonObject.getString("err_code"), "0", "errorcode is not as expected");
check.equals(jsonObject.getString("msg"), "²Ù×÷³É¹¦", "msg is not as expected");
bc_hash =(String) jsonObject.getJSONObject("data").get("bc_hash");
check.equals(bc_hash.length(),64,"hash is not as expected");
case 0:
if(APIUtil.getbool(current_condition_sub &(normalsign|oneaddress|threeaddress)))
{
check.equals(jsonObject.getString("err_code"), "0", "errorcode is not as expected");
check.equals(jsonObject.getString("msg"), "²Ù×÷³É¹¦", "msg is not as expected");
bc_hash =(String) jsonObject.getJSONObject("data").get("bc_hash");
check.equals(bc_hash.length(),64,"hash is not as expected");
//Confirmation(true);
}
else if(APIUtil.getbool(current_condition_sub &(wrongaddress|wrongpassword)))
{
check.equals(jsonObject.getString("err_code"), "21103", "errorcode is not as expected");
check.equals(jsonObject.getString("msg"), "Óû§ÃûÓëÃÜÂ벻ƥÅä", "msg is not as expected");
}
else if(current_condition_sub == sameaddress)
{
check.equals(jsonObject.getString("err_code"), "ÎĵµÎ´¶¨Òå", "errorcode is not as expected");
check.equals(jsonObject.getString("msg"), "Á½¸öµØÖ·Ò»ÑùµÄ´æÖ¤´íÎó£¬ÎĵµÎ´¶¨Òå", "msg is not as expected");
}
else if(current_condition_sub == nosigners)
{
check.equals(jsonObject.getString("err_code"), "ÎĵµÎ´¶¨Òå", "errorcode is not as expected");
check.equals(jsonObject.getString("msg"), "ûÓÐsignerµÄÇé¿ö£¬ÎĵµÎ´¶¨Òå", "msg is not as expected");
}
else if(current_condition_sub == signernumber_diff)
{
check.equals(jsonObject.getString("err_code"), "ÎĵµÎ´¶¨Òå", "errorcode is not as expected");
check.equals(jsonObject.getString("msg"), "ºÍcreateʱsignerµÄÊýÁ¿²»Í¬µÄÇé¿ö", "msg is not as expected");
}
break;
case noTradeNo :
check.equals(jsonObject.getString("err_code"), "21200", "errorcode is not as expected");
check.equals(jsonObject.getString("msg"), "×ʲú·¢ÐÐÆ¾¾ÝºÅ²»ÄÜΪ¿Õ", "msg is not as expected");
break;
case invalidTradeNo :
if(current_condition_sub == isnull)
{
check.equals(jsonObject.getString("err_code"), "ÎĵµÎ´¶¨Òå", "errorcode is not as expected");
check.equals(jsonObject.getString("msg"), "ÎĵµÎ´¶¨Òå", "msg is not as expected");
}
if(current_condition_sub == illegal)
{
check.equals(jsonObject.getString("err_code"), "ÎĵµÎ´¶¨Òå", "errorcode is not as expected");
check.equals(jsonObject.getString("msg"), "ÎĵµÎ´¶¨Òå", "msg is not as expected");
}
if(current_condition_sub == overlimit)
{
check.equals(jsonObject.getString("err_code"), "20021", "errorcode is not as expected");
check.equals(jsonObject.getString("msg"), "ƾ¾ÝºÅ³¤¶È²»ÄÜ´óÓÚ%d", "msg is not as expected");
}
break;
case invalidAccessToken :
case noAccessToken :
check.equals(jsonObject.getString("err_code"), "20015", "errorcode is not as expected");
check.equals(jsonObject.getString("msg"), "ÊÚȨÂë²»´æÔÚ»òÒѹýÆÚ", "msg is not as expected");
break;
case invalidEvidenceId:
check.equals(jsonObject.getString("err_code"), "20015", "errorcode is not as expected");
check.equals(jsonObject.getString("msg"), "ÊÚȨÂë²»´æÔÚ»òÒѹýÆÚ", "msg is not as expected");
break;
default:
break;
}
}
private JSONArray SignerLayout()
{
access_token = getToken();
//user 1 issue a kind of asset
createUser(access_token, user_name1,address1);
//create user 2
createUser(access_token, user_name2,address2);
//create user 3
createUser(access_token, user_name3,address3);
//sign
JSONArray signers = new JSONArray();
JSONObject singlesigner = new JSONObject();
switch(current_condition_sub)
{
case normalsign:
singlesigner.put("bubi_address", address1.toString());
singlesigner.put("password" ,user_name1.toString());
signers.add(singlesigner);
singlesigner.put("bubi_address", address2.toString());
singlesigner.put("password" ,user_name2.toString());
signers.add(singlesigner);
break;
case oneaddress:
singlesigner.put("bubi_address", address1.toString());
singlesigner.put("password" ,user_name1.toString());
signers.add(singlesigner);
break;
case threeaddress:
singlesigner.put("bubi_address", address1.toString());
singlesigner.put("password" ,user_name1.toString());
signers.add(singlesigner);
singlesigner.put("bubi_address", address2.toString());
singlesigner.put("password" ,user_name2.toString());
signers.add(singlesigner);
singlesigner.put("bubi_address", address3.toString());
singlesigner.put("password" ,user_name3.toString());
signers.add(singlesigner);
break;
case wrongaddress :
singlesigner.put("bubi_address", "abcdefg");
singlesigner.put("password" ,user_name1.toString());
signers.add(singlesigner);
singlesigner.put("bubi_address", address2.toString());
singlesigner.put("password" ,user_name2.toString());
signers.add(singlesigner);
break;
case wrongpassword:
singlesigner.put("bubi_address", address1.toString());
singlesigner.put("password" ,"abcde");
signers.add(singlesigner);
singlesigner.put("bubi_address", address2.toString());
singlesigner.put("password" ,user_name2.toString());
signers.add(singlesigner);
break;
case sameaddress:
singlesigner.put("bubi_address", address1.toString());
singlesigner.put("password" ,user_name1.toString());
signers.add(singlesigner);
signers.add(singlesigner);
break;
case nosigners:
break;
case signernumber_diff:
singlesigner.put("bubi_address", address1.toString());
singlesigner.put("password" ,user_name1.toString());
signers.add(singlesigner);
singlesigner.put("bubi_address", address2.toString());
singlesigner.put("password" ,user_name2.toString());
signers.add(singlesigner);
break;
}
return signers;
}
public void a_normaltest()
{
current_condition = 0;
current_condition_sub = normalsign;
TestModifyEvidence(null,SignerLayout(),2);
}
public void b_invalidsigner()
{
current_condition = 0;
current_condition_sub = oneaddress;
TestModifyEvidence(null,SignerLayout(),1);
current_condition_sub = threeaddress;
TestModifyEvidence(null,SignerLayout(),3);
current_condition_sub = wrongaddress;
TestModifyEvidence(null,SignerLayout(),2);
current_condition_sub = wrongpassword;
TestModifyEvidence(null,SignerLayout(),2);
current_condition_sub = sameaddress;
TestModifyEvidence(null,SignerLayout(),2);
current_condition_sub = nosigners;
TestModifyEvidence(null,SignerLayout(),2);
current_condition_sub = signernumber_diff;
TestModifyEvidence(null,SignerLayout(),1);
TestModifyEvidence(null,SignerLayout(),3);
}
}
| apache-2.0 |
xasx/camunda-bpm-platform | engine/src/main/java/org/camunda/bpm/engine/impl/db/sql/ProcessDefinitionTableMapping.java | 1000 | /*
* Copyright © 2013-2018 camunda services GmbH and various authors (info@camunda.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 org.camunda.bpm.engine.impl.db.sql;
/**
* @author Thorben Lindhauer
*
*/
public class ProcessDefinitionTableMapping implements MyBatisTableMapping {
public String getTableName() {
return "ACT_RE_PROCDEF";
}
public String getTableAlias() {
return "P";
}
public boolean isOneToOneRelation() {
return true;
}
}
| apache-2.0 |
xushjie1987/java-demos | demo8/src/main/java/com/testin/MyConfiger.java | 2374 | /**
* Project Name:demo8
* File Name:MyConfiger.java
* Package Name:com.testin
* Date:2016年12月16日上午12:45:03
* Copyright (c) 2016, All Rights Reserved.
*
*/
package com.testin;
import java.lang.reflect.Method;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy;
import java.util.concurrent.TimeUnit;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
/**
* ClassName:MyConfiger <br/>
* Function: <br/>
* Date: 2016年12月16日 上午12:45:03 <br/>
*
* @author xushjie
* @version
* @since JDK 1.8
* @see
*/
@EnableAsync
@Configuration
public class MyConfiger implements AsyncConfigurer {
@Override
public Executor getAsyncExecutor() {
// ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(3);
ThreadPoolExecutor executor = new ThreadPoolExecutor(2,
2,
0L,
TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<Runnable>(1));
executor.setRejectedExecutionHandler(new CallerRunsPolicy());
// ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
// executor.setCorePoolSize(2);
// executor.setMaxPoolSize(2);
// executor.setQueueCapacity(1);
// executor.setThreadNamePrefix("MyExecutor-");
// executor.initialize();
return executor;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return new AsyncUncaughtExceptionHandler() {
@Override
public void handleUncaughtException(Throwable arg0,
Method arg1,
Object... arg2) {
System.out.println("Uncaught: " + arg1.getName());
}
};
}
}
| apache-2.0 |
sdw2330976/Research-jetty-9.2.5 | jetty-util/src/main/java/org/eclipse/jetty/util/QuotedStringTokenizer.java | 17643 | //
// ========================================================================
// Copyright (c) 1995-2014 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.util;
import java.io.IOException;
import java.util.Arrays;
import java.util.NoSuchElementException;
import java.util.StringTokenizer;
/* ------------------------------------------------------------ */
/** StringTokenizer with Quoting support.
*
* This class is a copy of the java.util.StringTokenizer API and
* the behaviour is the same, except that single and double quoted
* string values are recognised.
* Delimiters within quotes are not considered delimiters.
* Quotes can be escaped with '\'.
*
* @see java.util.StringTokenizer
*
*/
public class QuotedStringTokenizer
extends StringTokenizer
{
private final static String __delim="\t\n\r";
private String _string;
private String _delim = __delim;
private boolean _returnQuotes=false;
private boolean _returnDelimiters=false;
private StringBuffer _token;
private boolean _hasToken=false;
private int _i=0;
private int _lastStart=0;
private boolean _double=true;
private boolean _single=true;
/* ------------------------------------------------------------ */
public QuotedStringTokenizer(String str,
String delim,
boolean returnDelimiters,
boolean returnQuotes)
{
super("");
_string=str;
if (delim!=null)
_delim=delim;
_returnDelimiters=returnDelimiters;
_returnQuotes=returnQuotes;
if (_delim.indexOf('\'')>=0 ||
_delim.indexOf('"')>=0)
throw new Error("Can't use quotes as delimiters: "+_delim);
_token=new StringBuffer(_string.length()>1024?512:_string.length()/2);
}
/* ------------------------------------------------------------ */
public QuotedStringTokenizer(String str,
String delim,
boolean returnDelimiters)
{
this(str,delim,returnDelimiters,false);
}
/* ------------------------------------------------------------ */
public QuotedStringTokenizer(String str,
String delim)
{
this(str,delim,false,false);
}
/* ------------------------------------------------------------ */
public QuotedStringTokenizer(String str)
{
this(str,null,false,false);
}
/* ------------------------------------------------------------ */
@Override
public boolean hasMoreTokens()
{
// Already found a token
if (_hasToken)
return true;
_lastStart=_i;
int state=0;
boolean escape=false;
while (_i<_string.length())
{
char c=_string.charAt(_i++);
switch (state)
{
case 0: // Start
if(_delim.indexOf(c)>=0)
{
if (_returnDelimiters)
{
_token.append(c);
return _hasToken=true;
}
}
else if (c=='\'' && _single)
{
if (_returnQuotes)
_token.append(c);
state=2;
}
else if (c=='\"' && _double)
{
if (_returnQuotes)
_token.append(c);
state=3;
}
else
{
_token.append(c);
_hasToken=true;
state=1;
}
break;
case 1: // Token
_hasToken=true;
if(_delim.indexOf(c)>=0)
{
if (_returnDelimiters)
_i--;
return _hasToken;
}
else if (c=='\'' && _single)
{
if (_returnQuotes)
_token.append(c);
state=2;
}
else if (c=='\"' && _double)
{
if (_returnQuotes)
_token.append(c);
state=3;
}
else
{
_token.append(c);
}
break;
case 2: // Single Quote
_hasToken=true;
if (escape)
{
escape=false;
_token.append(c);
}
else if (c=='\'')
{
if (_returnQuotes)
_token.append(c);
state=1;
}
else if (c=='\\')
{
if (_returnQuotes)
_token.append(c);
escape=true;
}
else
{
_token.append(c);
}
break;
case 3: // Double Quote
_hasToken=true;
if (escape)
{
escape=false;
_token.append(c);
}
else if (c=='\"')
{
if (_returnQuotes)
_token.append(c);
state=1;
}
else if (c=='\\')
{
if (_returnQuotes)
_token.append(c);
escape=true;
}
else
{
_token.append(c);
}
break;
}
}
return _hasToken;
}
/* ------------------------------------------------------------ */
@Override
public String nextToken()
throws NoSuchElementException
{
if (!hasMoreTokens() || _token==null)
throw new NoSuchElementException();
String t=_token.toString();
_token.setLength(0);
_hasToken=false;
return t;
}
/* ------------------------------------------------------------ */
@Override
public String nextToken(String delim)
throws NoSuchElementException
{
_delim=delim;
_i=_lastStart;
_token.setLength(0);
_hasToken=false;
return nextToken();
}
/* ------------------------------------------------------------ */
@Override
public boolean hasMoreElements()
{
return hasMoreTokens();
}
/* ------------------------------------------------------------ */
@Override
public Object nextElement()
throws NoSuchElementException
{
return nextToken();
}
/* ------------------------------------------------------------ */
/** Not implemented.
*/
@Override
public int countTokens()
{
return -1;
}
/* ------------------------------------------------------------ */
/** Quote a string.
* The string is quoted only if quoting is required due to
* embedded delimiters, quote characters or the
* empty string.
* @param s The string to quote.
* @param delim the delimiter to use to quote the string
* @return quoted string
*/
public static String quoteIfNeeded(String s, String delim)
{
if (s==null)
return null;
if (s.length()==0)
return "\"\"";
for (int i=0;i<s.length();i++)
{
char c = s.charAt(i);
if (c=='\\' || c=='"' || c=='\'' || Character.isWhitespace(c) || delim.indexOf(c)>=0)
{
StringBuffer b=new StringBuffer(s.length()+8);
quote(b,s);
return b.toString();
}
}
return s;
}
/* ------------------------------------------------------------ */
/** Quote a string.
* The string is quoted only if quoting is required due to
* embeded delimiters, quote characters or the
* empty string.
* @param s The string to quote.
* @return quoted string
*/
public static String quote(String s)
{
if (s==null)
return null;
if (s.length()==0)
return "\"\"";
StringBuffer b=new StringBuffer(s.length()+8);
quote(b,s);
return b.toString();
}
private static final char[] escapes = new char[32];
static
{
Arrays.fill(escapes, (char)0xFFFF);
escapes['\b'] = 'b';
escapes['\t'] = 't';
escapes['\n'] = 'n';
escapes['\f'] = 'f';
escapes['\r'] = 'r';
}
/* ------------------------------------------------------------ */
/** Quote a string into an Appendable.
* Only quotes and backslash are escaped.
* @param buffer The Appendable
* @param input The String to quote.
*/
public static void quoteOnly(Appendable buffer, String input)
{
if(input==null)
return;
try
{
buffer.append('"');
for (int i = 0; i < input.length(); ++i)
{
char c = input.charAt(i);
if (c == '"' || c == '\\')
buffer.append('\\');
buffer.append(c);
}
buffer.append('"');
}
catch (IOException x)
{
throw new RuntimeException(x);
}
}
/* ------------------------------------------------------------ */
/** Quote a string into an Appendable.
* The characters ", \, \n, \r, \t, \f and \b are escaped
* @param buffer The Appendable
* @param input The String to quote.
*/
public static void quote(Appendable buffer, String input)
{
if(input==null)
return;
try
{
buffer.append('"');
for (int i = 0; i < input.length(); ++i)
{
char c = input.charAt(i);
if (c >= 32)
{
if (c == '"' || c == '\\')
buffer.append('\\');
buffer.append(c);
}
else
{
char escape = escapes[c];
if (escape == 0xFFFF)
{
// Unicode escape
buffer.append('\\').append('u').append('0').append('0');
if (c < 0x10)
buffer.append('0');
buffer.append(Integer.toString(c, 16));
}
else
{
buffer.append('\\').append(escape);
}
}
}
buffer.append('"');
}
catch (IOException x)
{
throw new RuntimeException(x);
}
}
/* ------------------------------------------------------------ */
public static String unquoteOnly(String s)
{
return unquoteOnly(s, false);
}
/* ------------------------------------------------------------ */
/** Unquote a string, NOT converting unicode sequences
* @param s The string to unquote.
* @param lenient if true, will leave in backslashes that aren't valid escapes
* @return quoted string
*/
public static String unquoteOnly(String s, boolean lenient)
{
if (s==null)
return null;
if (s.length()<2)
return s;
char first=s.charAt(0);
char last=s.charAt(s.length()-1);
if (first!=last || (first!='"' && first!='\''))
return s;
StringBuilder b = new StringBuilder(s.length() - 2);
boolean escape=false;
for (int i=1;i<s.length()-1;i++)
{
char c = s.charAt(i);
if (escape)
{
escape=false;
if (lenient && !isValidEscaping(c))
{
b.append('\\');
}
b.append(c);
}
else if (c=='\\')
{
escape=true;
}
else
{
b.append(c);
}
}
return b.toString();
}
/* ------------------------------------------------------------ */
public static String unquote(String s)
{
return unquote(s,false);
}
/* ------------------------------------------------------------ */
/** Unquote a string.
* @param s The string to unquote.
* @return quoted string
*/
public static String unquote(String s, boolean lenient)
{
if (s==null)
return null;
if (s.length()<2)
return s;
char first=s.charAt(0);
char last=s.charAt(s.length()-1);
if (first!=last || (first!='"' && first!='\''))
return s;
StringBuilder b = new StringBuilder(s.length() - 2);
boolean escape=false;
for (int i=1;i<s.length()-1;i++)
{
char c = s.charAt(i);
if (escape)
{
escape=false;
switch (c)
{
case 'n':
b.append('\n');
break;
case 'r':
b.append('\r');
break;
case 't':
b.append('\t');
break;
case 'f':
b.append('\f');
break;
case 'b':
b.append('\b');
break;
case '\\':
b.append('\\');
break;
case '/':
b.append('/');
break;
case '"':
b.append('"');
break;
case 'u':
b.append((char)(
(TypeUtil.convertHexDigit((byte)s.charAt(i++))<<24)+
(TypeUtil.convertHexDigit((byte)s.charAt(i++))<<16)+
(TypeUtil.convertHexDigit((byte)s.charAt(i++))<<8)+
(TypeUtil.convertHexDigit((byte)s.charAt(i++)))
)
);
break;
default:
if (lenient && !isValidEscaping(c))
{
b.append('\\');
}
b.append(c);
}
}
else if (c=='\\')
{
escape=true;
}
else
{
b.append(c);
}
}
return b.toString();
}
/* ------------------------------------------------------------ */
/** Check that char c (which is preceded by a backslash) is a valid
* escape sequence.
* @param c
* @return
*/
private static boolean isValidEscaping(char c)
{
return ((c == 'n') || (c == 'r') || (c == 't') ||
(c == 'f') || (c == 'b') || (c == '\\') ||
(c == '/') || (c == '"') || (c == 'u'));
}
/* ------------------------------------------------------------ */
public static boolean isQuoted(String s)
{
return s!=null && s.length()>0 && s.charAt(0)=='"' && s.charAt(s.length()-1)=='"';
}
/* ------------------------------------------------------------ */
/**
* @return handle double quotes if true
*/
public boolean getDouble()
{
return _double;
}
/* ------------------------------------------------------------ */
/**
* @param d handle double quotes if true
*/
public void setDouble(boolean d)
{
_double=d;
}
/* ------------------------------------------------------------ */
/**
* @return handle single quotes if true
*/
public boolean getSingle()
{
return _single;
}
/* ------------------------------------------------------------ */
/**
* @param single handle single quotes if true
*/
public void setSingle(boolean single)
{
_single=single;
}
}
| apache-2.0 |
bwolf/je-misc-samples | spring/spring-jdbc-first/src/main/java/org/antbear/jee/spring/jdbc/App.java | 1747 | package org.antbear.jee.spring.jdbc;
import org.antbear.jee.spring.jdbc.dataaccess.CustomerDao;
import org.antbear.jee.spring.jdbc.dataaccess.OrderDao;
import org.antbear.jee.spring.jdbc.dataaccess.OrderPositionDao;
import org.antbear.jee.spring.jdbc.dataaccess.ProductDao;
import org.antbear.jee.spring.jdbc.domain.Customer;
import org.antbear.jee.spring.jdbc.domain.Order;
import org.antbear.jee.spring.jdbc.domain.OrderPosition;
import org.antbear.jee.spring.jdbc.domain.Product;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
public class App {
private final static Logger log = LoggerFactory.getLogger(App.class);
@Autowired
private CustomerDao customerDao;
@Autowired
private OrderDao orderDao;
@Autowired
private OrderPositionDao orderPositionDao;
@Autowired
private ProductDao productDao;
public void businessMethod() {
for (final Customer customer : customerDao.findAll()) {
log.debug(customer.toString());
final List<Order> orders = orderDao.findByCustomer(customer.getId());
for (final Order order : orders) {
log.debug(order.toString());
final List<OrderPosition> orderPositions = orderPositionDao.findByOrder(order.getId());
for (final OrderPosition orderPosition : orderPositions) {
log.debug(orderPosition.toString());
final Product product = productDao.findById(orderPosition.getProductId());
log.debug(product.toString());
}
}
}
}
}
| apache-2.0 |
chmyga/component-runtime | component-runtime-design-extension/src/test/java/org/talend/test/MetadataMigrationProcessor.java | 3409 | /**
* Copyright (C) 2006-2020 Talend Inc. - www.talend.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 org.talend.test;
import java.io.Serializable;
import java.util.Map;
import org.talend.sdk.component.api.component.MigrationHandler;
import org.talend.sdk.component.api.component.Version;
import org.talend.sdk.component.api.configuration.Option;
import org.talend.sdk.component.api.configuration.type.DataSet;
import org.talend.sdk.component.api.configuration.type.DataStore;
import org.talend.sdk.component.api.configuration.ui.layout.GridLayout;
import org.talend.sdk.component.api.meta.Documentation;
import org.talend.sdk.component.api.processor.ElementListener;
import org.talend.sdk.component.api.processor.Input;
import org.talend.sdk.component.api.processor.Processor;
import org.talend.sdk.component.api.record.Record;
import lombok.Data;
@Processor(family = "metadata", name = "MetadataMigrationProcessor")
public class MetadataMigrationProcessor implements Serializable {
public MetadataMigrationProcessor(@Option("configuration") final Config config) {
// no-op
}
@ElementListener
public void onElement(@Input final Record in) {
// no-op
}
public static class Config {
@Option
private MyDataSet dataset;
}
@Data
@DataSet
@Version(value = 2, migrationHandler = MyDataSet.InputMapperDataSetHandler.class)
@GridLayout({ @GridLayout.Row({ "dataStore" }), @GridLayout.Row({ "config" }) })
@Documentation("")
public static class MyDataSet implements Serializable {
@Option
private MyDataStore dataStore;
@Option
private String config;
public static class InputMapperDataSetHandler implements MigrationHandler {
@Override
public Map<String, String> migrate(final int incomingVersion, final Map<String, String> incomingData) {
final String value = incomingData.remove("option");
if (value != null) {
incomingData.put("config", value);
}
return incomingData;
}
}
}
@Data
@DataStore
@Version(value = 2, migrationHandler = MyDataStore.InputMapperDataStoretHandler.class)
@GridLayout({ @GridLayout.Row({ "url" }) })
@Documentation("")
public static class MyDataStore {
@Option
private String url;
public static class InputMapperDataStoretHandler implements MigrationHandler {
@Override
public Map<String, String> migrate(final int incomingVersion, final Map<String, String> incomingData) {
final String value = incomingData.remove("connection");
if (value != null) {
incomingData.put("url", value);
}
return incomingData;
}
}
}
} | apache-2.0 |
stanleychg/Quizzy | src/wordgames/game/QuizFront.java | 26604 | /*
* QuizFront - Main Menu
*
* User can do the following on this screen:
* -Create a new quiz
* -Modify/Delete a quiz
* -Play with a quiz
* -Import/Export quizzes
*/
package wordgames.game;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.List;
import wordgames.game.util.CommonFunctions;
import wordgames.game.util.QuizDatabaseManager;
import wordgames.game.util.Quiz;
import wordgames.game.util.QuizListAdapter;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Environment;
import android.text.InputType;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AnimationSet;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class QuizFront extends Activity{
//Dialog Sizes
final float HEADER_SIZE = 30.0f;
final float NAME_SIZE = 30.0f;
final float TITLE_SIZE = 25.0f;
//Dialog Titles/Descriptions
final String EDIT_TITLE = "Edit Quiz";
final String PLAY_TITLE = "Use Quiz";
final String DELETE_TITLE = "Delete Quiz";
final String EXPORT_TITLE = "Export Quiz";
final String IMPORT_TITLE = "Import Quiz";
final String TOGGLE_TEXT = "Toggle All";
final String IMPORT_LIST_TEXT = "Select Quizzes to Import";
final String ADD_QUIZ_TITLE = "Add New Quiz";
final String ADD_QUIZ_HINT = "Gen Psych 101";
final String QUIZ_OPTIONS_TITLE = "What would you like to do?";
//UI
GridView quizList;
QuizListAdapter qlva;
ArrayList<Quiz> qm;
QuizDatabaseManager data;
Intent i;
//Initialization
public void onCreate(Bundle saved){
super.onCreate(saved);
setContentView(R.layout.quiz_front);
//Set Click Listener to GridView of Quizzes
quizList = (GridView)findViewById(R.id.frontQuizList);
quizList.setOnItemClickListener(new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> arg0, View view,
int position, long arg3) {
// TODO Auto-generated method stub
System.out.println("POSITION: " + position);
dialogOptions(view.getContext(),position);
}
});
//Set Hold Listener to GridView of Quizzes
quizList.setOnItemLongClickListener(new OnItemLongClickListener(){
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
return false;
}
});
//List of quizzes updated in onResume
}
//Updates list of quizzes and animates the views
//Called when:
//a) Device sleeps and resumes
//b) User exits QuizMaker
protected void onResume() {
super.onResume();
updateList();
//Animate Views
AnimationSet as = (AnimationSet)AnimationUtils.loadAnimation(this, R.animator.fade_in);
quizList.startAnimation(as);
}
//Inflate ActionBar
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.quiz_front_action, menu);
return super.onCreateOptionsMenu(menu);
}
//ActionBar Event Listener
public boolean onOptionsItemSelected(MenuItem item){
FileChannel src;
FileChannel dst;
switch(item.getItemId()){
case R.id.menu_add:
dialogCreate(QuizFront.this);
return true;
case R.id.menu_import:
//Import Quizzes
try {
//Store a temporary copy of the databases in the SD card
String phoneDbPath = getResources().getString(R.string.internal_directory_folder)
+ "//"
+ getResources().getString(R.string.database_file)
+ "TEMP";
String sdDBPath = getResources().getString(R.string.sd_directory_folder)
+ "//"
+ getResources().getString(R.string.database_file)
+ ".db";
File sdDB = new File(Environment.getExternalStorageDirectory(), sdDBPath);
File phoneDb = new File(Environment.getDataDirectory(),phoneDbPath);
//Check state of sd
if (sdDB.canRead()) {
//sd card can write. Set this settings through Android Manifest
//<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
System.out.println("Can Read from SD...");
//Open file streams
src = new FileInputStream(sdDB).getChannel();
dst = new FileOutputStream(phoneDb).getChannel();
dst.transferFrom(src, 0, src.size());
QuizDatabaseManager temp = new QuizDatabaseManager(
QuizFront.this,
getResources().getString(R.string.database_file) + "TEMP");
temp.open(false);
//Tracks quizzes in sd card
List<QuizImport> tempList = new ArrayList<QuizImport>();
for(String s: temp.getQuizCount()){
tempList.add(new QuizImport(s));
}
temp.close();
showImportList(QuizFront.this,tempList);
//Ensure that all opened streams are closed
src.close(); src = null;
dst.close(); dst = null;
}
} catch (Exception e) {
//Exception hit. Print error message
System.out.println("Error:" + e.getMessage());
Toast.makeText(QuizFront.this, "ERROR 0: Quizzes failed to import", Toast.LENGTH_LONG).show();
}
return true;
case R.id.menu_export:
//Export Quizzes to SD Card
try {
//Sets the directories.
//sd = sd card directory
//data = data directory
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
//Set folder path
String folder = getResources().getString(R.string.sd_directory_folder);
//Set up folder directory
File dir = new File(sd, folder);
if(!dir.exists()){
//If it doesn't exist, make it.
if(dir.mkdirs()) System.out.println("Folder does not exist. Folder made");
else System.out.println("Folder does not exist. Folder failed to materialize");
}
else System.out.println("Folder exists...");
System.out.println("Attempting Backup...");
//Check state of sd
//System.out.println(sd.toString());
if (sd.canWrite()) {
//sd card can write. Set this settings through Android Manifest
//<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
System.out.println("Can write into SD...");
//Set database path
String phoneDBPath;
//Set backup database path
String sdDBPath;
//Set up directories
File phoneDB;
File sdDB;
//Transfer SQLite databases
//Time t = new Time();
//t.setToNow();
phoneDBPath = getResources().getString(R.string.internal_directory_folder)
+ "//"
+ getResources().getString(R.string.database_file);
sdDBPath = getResources().getString(R.string.sd_directory_folder)
+ "//"
+ getResources().getString(R.string.database_file)
// + t.month/10 + t.month%10 + t.monthDay/10 + t.monthDay%10 + t.year
+ ".db";
phoneDB = new File(data, phoneDBPath);
sdDB = new File(sd, sdDBPath);
if (phoneDB.exists()) {
System.out.println("Database Exists...");
src = new FileInputStream(phoneDB).getChannel();
dst = new FileOutputStream(sdDB).getChannel();
dst.transferFrom(src, 0, src.size());
src.close();
dst.close();
System.out.println("Quizzes backed up!");
}
Toast.makeText(QuizFront.this, "Quizzes successfully exported!", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
// exception
System.out.println("Crash");
Toast.makeText(QuizFront.this, "ERROR 0: Quizzes failed to export", Toast.LENGTH_LONG).show();
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
//Add Quiz Dialog
private void dialogCreate(final Context mContext) {
final Dialog dialog = new Dialog(mContext);
dialog.setTitle(ADD_QUIZ_TITLE);
//Initialize Dialog
LinearLayout ll = new LinearLayout(mContext);
ll.setOrientation(LinearLayout.VERTICAL);
ll.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
LinearLayout llBot = new LinearLayout(mContext);
llBot.setOrientation(LinearLayout.HORIZONTAL);
llBot.setWeightSum(1.0f);
final EditText name = new EditText(mContext);
name.setTextSize(NAME_SIZE);
name.setInputType(InputType.TYPE_TEXT_FLAG_CAP_WORDS);
name.setLayoutParams(new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT,
0.25f));
name.setHint(ADD_QUIZ_HINT);
llBot.addView(name);
ImageButton set = new ImageButton(mContext);
set.setImageResource(R.drawable.green_check);
set.setScaleType(ScaleType.CENTER_INSIDE);
set.setAdjustViewBounds(true);
set.setLayoutParams(new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT,
0.75f));
//Set event listener to create new quiz
set.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String s = name.getText().toString();
if(CommonFunctions.checkChar(s) == true && !s.isEmpty()){
Intent i = new Intent(mContext, QuizMaker.class);
i.putExtra("name", s);
mContext.startActivity(i);
dialog.dismiss();
hideIntro();
} else if(!s.isEmpty()){
//Invalid characters
Toast.makeText(v.getContext(), "Invalid name! Please take out all spaces!", Toast.LENGTH_SHORT).show();
} else {
//Name is empty
Toast.makeText(v.getContext(), "Invalid name! Please insert a name!", Toast.LENGTH_SHORT).show();
}
}
});
set.setPadding(5, 5, 5, 5);
llBot.addView(set);
ll.addView(llBot);
dialog.setContentView(ll);
dialog.show();
}
//Quiz Options Dialog
private void dialogOptions(final Context mContext, final int pos) {
final Dialog dialog = new Dialog(mContext);
dialog.setTitle(QUIZ_OPTIONS_TITLE);
final Quiz q = qm.get(pos);
//Initialize Dialog
LinearLayout ll = new LinearLayout(mContext);
LinearLayout ll2 = new LinearLayout(mContext);
ll.setOrientation(LinearLayout.VERTICAL);
ll2.setOrientation(LinearLayout.HORIZONTAL);
LinearLayout llEdit = new LinearLayout(mContext);
llEdit.setOrientation(LinearLayout.VERTICAL);
llEdit.setLayoutParams(new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT,
1.0f));
ImageButton edit = new ImageButton(mContext);
edit.setImageResource(R.drawable.hammer_small);
edit.setAdjustViewBounds(true);
edit.setScaleType(ScaleType.CENTER_INSIDE);
edit.setLayoutParams(new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT,
1.0f));
//Set event listener to edit existing quiz
edit.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(mContext, QuizMaker.class);
i.putExtra("name", q.getName());
mContext.startActivity(i);
dialog.dismiss();
}
});
edit.setPadding(5, 5, 5, 5);
llEdit.addView(edit);
TextView editTitle = new TextView(mContext);
editTitle.setText(EDIT_TITLE);
editTitle.setGravity(Gravity.CENTER_HORIZONTAL);
editTitle.setTextSize(TITLE_SIZE);
llEdit.addView(editTitle);
ll2.addView(llEdit);
LinearLayout llPlay = new LinearLayout(mContext);
llPlay.setOrientation(LinearLayout.VERTICAL);
llPlay.setLayoutParams(new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT,
1.0f));
ImageButton play = new ImageButton(mContext);
play.setImageResource(R.drawable.puzzle_small);
play.setScaleType(ScaleType.CENTER_INSIDE);
play.setAdjustViewBounds(true);
play.setLayoutParams(new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT,
1.0f));
//Set event listener to use quiz
play.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(mContext, QuizGame.class);
i.putExtra("name", q.getName());
mContext.startActivity(i);
dialog.dismiss();
}
});
play.setPadding(5, 5, 5, 5);
llPlay.addView(play);
TextView playTitle = new TextView(mContext);
playTitle.setText(PLAY_TITLE);
playTitle.setGravity(Gravity.CENTER_HORIZONTAL);
playTitle.setTextSize(TITLE_SIZE);
llPlay.addView(playTitle);
ll2.addView(llPlay);
LinearLayout llDelete = new LinearLayout(mContext);
llDelete.setOrientation(LinearLayout.VERTICAL);
llDelete.setLayoutParams(new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT,
1.0f));
ImageButton delete = new ImageButton(mContext);
delete.setImageResource(R.drawable.trash_can_small);
delete.setScaleType(ScaleType.CENTER_INSIDE);
delete.setAdjustViewBounds(true);
delete.setLayoutParams(new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT,
1.0f));
//Set event listener to delete quiz
delete.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//Remove from list
String tableName = qm.get(pos).getName();
qm.remove(pos);
qlva.notifyDataSetChanged();
//Delete quiz/table
data = new QuizDatabaseManager(
mContext,
getResources().getString(R.string.database_file));
data.open(true);
data.setTable(tableName);
data.dropTable();
data.close();
Toast.makeText(mContext, q.getName() + " removed from list", Toast.LENGTH_LONG).show();
dialog.dismiss();
}
});
delete.setPadding(5, 5, 5, 5);
llDelete.addView(delete);
TextView deleteTitle = new TextView(mContext);
deleteTitle.setText(DELETE_TITLE);
deleteTitle.setGravity(Gravity.CENTER_HORIZONTAL);
deleteTitle.setTextSize(TITLE_SIZE);
llDelete.addView(deleteTitle);
ll2.addView(llDelete);
ll.addView(ll2);
dialog.setContentView(ll);
dialog.show();
}
// //Create dialog to delete quiz
// private void dialogDelete(final Context mContext, final String quizName){
// final Dialog dialog = new Dialog(mContext);
// dialog.setTitle("Delete " + quizName + "?");
//
// //Initialize Dialog
// LinearLayout ll = new LinearLayout(mContext);
// ll.setLayoutParams(new LinearLayout.LayoutParams(
// LayoutParams.MATCH_PARENT,
// LayoutParams.MATCH_PARENT));
// ll.setOrientation(LinearLayout.HORIZONTAL);
//
// ImageButton set = new ImageButton(mContext);
// set.setLayoutParams(new LinearLayout.LayoutParams(
// LayoutParams.MATCH_PARENT,
// LayoutParams.MATCH_PARENT,
// 1.0f));
// set.setAdjustViewBounds(true);
// set.setImageResource(R.drawable.green_check);
// set.setOnClickListener(new OnClickListener(){
//
// @Override
// public void onClick(View v) {
// // TODO Auto-generated method stub
// dialog.dismiss();
// }
//
// });
// ll.addView(set);
//
// ImageButton undo = new ImageButton(mContext);
// undo.setLayoutParams(new LinearLayout.LayoutParams(
// LayoutParams.MATCH_PARENT,
// LayoutParams.MATCH_PARENT,
// 1.0f));
// undo.setAdjustViewBounds(true);
// undo.setImageResource(R.drawable.red_x);
// undo.setOnClickListener(new OnClickListener(){
//
// @Override
// public void onClick(View v) {
// // TODO Auto-generated method stub
// dialog.dismiss();
// }
//
// });
// ll.addView(undo);
//
// dialog.setContentView(ll);
// dialog.show();
// }
//
//Import Function - Select Quizzes to import
private void showImportList(final Context mContext, final List<QuizImport> quizzes){
final Dialog dialog = new Dialog(mContext);
dialog.setTitle(IMPORT_LIST_TEXT);
LinearLayout ll = new LinearLayout(mContext);
LinearLayout llRight = new LinearLayout(mContext);
llRight.setLayoutParams(new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT,
0.65f));
ll.setOrientation(LinearLayout.HORIZONTAL);
llRight.setOrientation(LinearLayout.VERTICAL);
ListView list = new ListView(mContext);
list.setLayoutParams(new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT,
0.35f));
final ImportAdapter ia = new ImportAdapter(mContext,R.layout.quiz_listview_import, quizzes);
list.setAdapter(ia);
list.setOnItemClickListener(new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
long arg3) {
// TODO Auto-generated method stub
quizzes.get(pos).toggleImportStatus();
ia.notifyDataSetChanged();
}
});
ll.addView(list);
ImageButton set = new ImageButton(mContext);
set.setImageResource(R.drawable.green_check);
set.setAdjustViewBounds(true);
set.setScaleType(ScaleType.CENTER_INSIDE);
set.setLayoutParams(new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT,
0.3f));
set.setOnClickListener(new OnClickListener() {
boolean hasImported = false;
//Sets the directories.
//data = data directory
File data = Environment.getDataDirectory();
public void onClick(View v) {
//Make sure internal directory exists
File f = new File(data,getResources().getString(R.string.internal_directory_folder));
if(f.mkdirs()){
System.out.println("Internal Directories Created...");
}
for(QuizImport q : quizzes){
if(q.getImportStatus() == true){
QuizDatabaseManager src = new QuizDatabaseManager(
mContext,
getResources().getString(R.string.database_file) + "TEMP");
QuizDatabaseManager dst = new QuizDatabaseManager(
mContext,
getResources().getString(R.string.database_file));
Cursor c = null;
try {
src.open(false);
dst.open(true);
src.setTable(q.getQuizName());
if(dst.setTable(q.getQuizName())){
dst.deleteAllWords();
} else{
dst.addTable(q.getQuizName());
dst.setTable(q.getQuizName());
}
c = src.getAllWords();
c.moveToFirst();
startManagingCursor(c);
if(c.getCount() != 0){
do{
dst.addWord(c.getString(c.getColumnIndex("word")),c.getString(c.getColumnIndex("definition")));
} while (c.moveToNext());
}
hasImported = true;
} catch (Exception e) {
System.out.println("Crash: " + e.getMessage());
Toast.makeText(mContext, "ERROR 1: Quizzes failed to import", Toast.LENGTH_LONG).show();
} finally{
if(c != null)
c.close();
dst.close();
src.close();
}
}
}
if(hasImported){
Toast.makeText(mContext, "Quizzes successfully imported!", Toast.LENGTH_SHORT).show();
updateList();
}
dialog.dismiss();
hideIntro();
}
});
set.setPadding(5, 5, 5, 5);
llRight.addView(set);
//Set
Button toggleAll = new Button(mContext);
toggleAll.setLayoutParams(new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT,
0.7f));
toggleAll.setText(TOGGLE_TEXT);
toggleAll.setTextSize(TITLE_SIZE);
toggleAll.setOnClickListener(new OnClickListener() {
boolean toggleStatus = true;
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
for(QuizImport q: quizzes){
q.setImportStatus(toggleStatus);
}
toggleStatus = !toggleStatus;
ia.notifyDataSetChanged();
}
});
llRight.addView(toggleAll);
ll.addView(llRight);
dialog.setContentView(ll);
dialog.show();
}
//Updates list of quizzes available
private void updateList(){
qm = new ArrayList<Quiz>();
data = new QuizDatabaseManager(this, getResources().getString(R.string.database_file));
data.open(true);
//Grab list of all quizzes
ArrayList<String> quizDb = data.getQuizCount();
data.close();
//If # of quizzes > 0:
if(quizDb != null && quizDb.size() > 0){
//# of quizzes > 0. Grab quizzes and display them onto screen
//Hide Tutorial
hideIntro();
//Take quiz names, remove brackets, and add them to QuizManager
for(int x = 0; x < quizDb.size(); x++){
qm.add(new Quiz(quizDb.get(x)));
}
//Set adapter
qlva = new QuizListAdapter(this,R.layout.quiz_listview,qm);
quizList.setAdapter(qlva);
}
}
//When device switches from portrait to landscape and vice versa
@Override
public void onConfigurationChanged(Configuration newConfig) {
// TODO Auto-generated method stub
super.onConfigurationChanged(newConfig);
setContentView(R.layout.quiz_front);
//Set Click Listener to GridView of Quizzes
quizList = (GridView)findViewById(R.id.frontQuizList);
quizList.setOnItemClickListener(new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> arg0, View view,
int position, long arg3) {
// TODO Auto-generated method stub
System.out.println("POSITION: " + position);
dialogOptions(view.getContext(),position);
}
});
//Set Hold Listener to GridView of Quizzes
quizList.setOnItemLongClickListener(new OnItemLongClickListener(){
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
return false;
}
});
updateList();
}
//Hide Introduction
private void hideIntro(){
View v = findViewById(R.id.frontIntro);
v.setVisibility(View.GONE);
}
//Internal helper class to import Quizzes
class QuizImport {
//Name of Quiz
private String name;
//Whether to import a quiz or not
private boolean shouldImport;
public QuizImport(String name){
this.name = name;
shouldImport = false;
}
public void toggleImportStatus(){
shouldImport = !shouldImport;
}
public void setImportStatus(boolean shouldImport){
this.shouldImport = shouldImport;
}
public String getQuizName(){
return name;
}
public boolean getImportStatus(){
return shouldImport;
}
}
//Internal helper class to populate Listview with Quizzes
class ImportAdapter extends ArrayAdapter<QuizImport>{
private int layout;
public ImportAdapter(Context context, int layout, List<QuizImport> objects) {
super(context, layout, objects);
this.layout = layout;
// TODO Auto-generated constructor stub
}
/* (non-Javadoc)
* @see android.widget.ArrayAdapter#getView(int, android.view.View, android.view.ViewGroup)
*/
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v = convertView;
if(v == null){
LayoutInflater li = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = li.inflate(layout, null);
}
TextView quizName = (TextView)v.findViewById(R.id.importQuizName);
CheckBox check = (CheckBox)v.findViewById(R.id.importCheck);
QuizImport q = getItem(position);
quizName.setText(q.getQuizName());
check.setChecked(q.getImportStatus());
return v;
}
}
}
| apache-2.0 |
rogerkeays/novdl | src/jamaica/faces/component/html/HOutputFormat.java | 365 | package jamaica.faces.component.html;
import jamaica.faces.component.html.FluentHtmlOutputFormat;
import javax.faces.component.html.HtmlOutputFormat;
public class HOutputFormat extends HtmlOutputFormat
implements FluentHtmlOutputFormat<HOutputFormat> {
public static HOutputFormat h_outputFormat() {
return new HOutputFormat();
}
}
| apache-2.0 |
remondis-it/remap | src/test/java/com/remondis/remap/basic/MapperTest.java | 14645 | package com.remondis.remap.basic;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.junit.Test;
import com.remondis.remap.Mapper;
import com.remondis.remap.Mapping;
import com.remondis.remap.MappingException;
import com.remondis.remap.test.MapperTests.PersonWithAddress;
import com.remondis.remap.test.MapperTests.PersonWithFoo;
public class MapperTest {
public static final String MORE_IN_A = "moreInA";
public static final Long ZAHL_IN_A = -88L;
public static final Integer B_INTEGER = -999;
public static final int B_NUMBER = 222;
public static final String B_STRING = "b string";
public static final Integer INTEGER = 310;
public static final int NUMBER = 210;
public static final String STRING = "a string";
@Test(expected = MappingException.class)
public void shouldDenyMapNull() {
Mapper<A, AResource> mapper = Mapping.from(A.class)
.to(AResource.class)
.reassign(A::getMoreInA)
.to(AResource::getMoreInAResource)
.reassign(A::getZahlInA)
.to(AResource::getZahlInAResource)
.useMapper(Mapping.from(B.class)
.to(BResource.class)
.mapper())
.mapper();
mapper.map((A) null);
}
@Test
public void shouldFailDueToNoRegisteredMapper() {
assertThatThrownBy(() -> Mapping.from(A.class)
.to(AResource.class)
.reassign(A::getMoreInA)
.to(AResource::getMoreInAResource)
.reassign(A::getZahlInA)
.to(AResource::getZahlInAResource)
.mapper()).isInstanceOf(MappingException.class)
.hasMessageStartingWith("No mapper found for type mapping");
}
/**
* This is the happy-path test for mapping {@link A} to {@link AResource} with a nested mapping. This test does not
* check the inherited fields.
*/
@Test
public void shouldMapCorrectly() {
Mapper<A, AResource> mapper = Mapping.from(A.class)
.to(AResource.class)
.omitInSource(A::getMoreInA)
.omitInDestination(AResource::getMoreInAResource)
.reassign(A::getZahlInA)
.to(AResource::getZahlInAResource)
.useMapper(Mapping.from(B.class)
.to(BResource.class)
.mapper())
.mapper();
B b = new B(B_STRING, B_NUMBER, B_INTEGER);
A a = new A(MORE_IN_A, STRING, NUMBER, INTEGER, ZAHL_IN_A, b);
a.setZahlInA(ZAHL_IN_A);
AResource ar = mapper.map(a);
assertNull(ar.getMoreInAResource());
assertEquals(STRING, a.getString());
assertEquals(STRING, ar.getString());
assertEquals(NUMBER, a.getNumber());
assertEquals(NUMBER, ar.getNumber());
assertEquals(INTEGER, a.getInteger());
assertEquals(INTEGER, ar.getInteger());
assertEquals(ZAHL_IN_A, a.getZahlInA());
assertEquals(ZAHL_IN_A, ar.getZahlInAResource());
BResource br = ar.getB();
assertEquals(B_STRING, b.getString());
assertEquals(B_STRING, br.getString());
assertEquals(B_NUMBER, b.getNumber());
assertEquals(B_NUMBER, br.getNumber());
assertEquals(B_INTEGER, b.getInteger());
assertEquals(B_INTEGER, br.getInteger());
}
/**
* Ensures that the {@link Mapper} detects one more property in the source object that is not omitted by the mapping
* configuration. The {@link Mapper} is expected to throw a {@link MappingException}.
*/
@Test
public void oneMoreSourceFieldInA() {
assertThatThrownBy(() -> Mapping.from(AWithOneMoreSourceField.class)
.to(AResourceWithOneMoreSourceField.class)
.mapper()).isInstanceOf(MappingException.class)
.hasMessageContaining("- Property 'onlyInA' in AWithOneMoreSourceField");
}
/**
* Ensures that an unmatched source field is omitted.
*/
@Test
public void oneMoreSourceFieldInAButItIsOmitted() {
Mapper<AWithOneMoreSourceField, AResourceWithOneMoreSourceField> mapper = Mapping
.from(AWithOneMoreSourceField.class)
.to(AResourceWithOneMoreSourceField.class)
.omitInSource(a -> a.getOnlyInA())
.mapper();
AWithOneMoreSourceField aWithOneMoreSourceField = new AWithOneMoreSourceField(1, 10, "text");
AResourceWithOneMoreSourceField map = mapper.map(aWithOneMoreSourceField);
assertEquals(aWithOneMoreSourceField.getText(), map.getText());
assertEquals(aWithOneMoreSourceField.getZahl(), map.getZahl());
}
/**
* Ensures that the {@link Mapper} detects one more property in the destination object that is not omitted by the
* mapping
* configuration. The {@link Mapper} is expected to throw a {@link MappingException}.
*/
@Test
public void oneMoreDestinationFieldInAResource() {
assertThatThrownBy(() -> Mapping.from(AWithOneMoreDestinationField.class)
.to(AResourceWithOneMoreDestinationField.class)
.mapper()).isInstanceOf(MappingException.class)
.hasMessageContaining("- Property 'onlyInAResource' in AResourceWithOneMoreDestinationField");
}
/**
* Ensures that an unmatched destination field is omitted.
*/
@Test
public void oneMoreDestinationFieldInAResourceButItsOmmited() {
Mapper<AWithOneMoreDestinationField, AResourceWithOneMoreDestinationField> mapper = Mapping
.from(AWithOneMoreDestinationField.class)
.to(AResourceWithOneMoreDestinationField.class)
.omitInDestination(ar -> ar.getOnlyInAResource())
.mapper();
AWithOneMoreDestinationField aWithOneMoreDestinationField = new AWithOneMoreDestinationField(10, "text");
AResourceWithOneMoreDestinationField map = mapper.map(aWithOneMoreDestinationField);
assertEquals(aWithOneMoreDestinationField.getText(), map.getText());
assertEquals(aWithOneMoreDestinationField.getZahl(), map.getZahl());
}
/**
* Ensures that the mapper performs a correct reassigment of fields.
*/
@Test
public void reassign() {
Mapper<AReassign, AResourceReassign> mapper = Mapping.from(AReassign.class)
.to(AResourceReassign.class)
.reassign(AReassign::getFirstNumberInA)
.to(AResourceReassign::getFirstNumberInAResource)
.reassign(AReassign::getSecondNumberInA)
.to(AResourceReassign::getSecondNumberInAResource)
.mapper();
AReassign aReassgin = new AReassign(1, 2, 3);
AResourceReassign map = mapper.map(aReassgin);
assertEquals(aReassgin.getZahl(), map.getZahl());
assertEquals(aReassgin.getFirstNumberInA(), map.getFirstNumberInAResource());
assertEquals(aReassgin.getSecondNumberInA(), map.getSecondNumberInAResource());
}
/**
* Ensures that the mapper does not allow an omitted field in the source to be reassigned.
*/
@Test(expected = MappingException.class)
public void reassignAnOmmitedFieldInSource() {
Mapping.from(AReassign.class)
.to(AResourceReassign.class)
.omitInSource(AReassign::getFirstNumberInA)
.reassign(AReassign::getFirstNumberInA)
.to(AResourceReassign::getFirstNumberInAResource)
.reassign(AReassign::getSecondNumberInA)
.to(AResourceReassign::getSecondNumberInAResource)
.mapper();
}
/**
* Ensures that the mapper does not allow an omitted field in the destination to be reassigned.
*/
@Test(expected = MappingException.class)
public void reassignToAnOmmitedFieldInDestination() {
Mapping.from(AReassign.class)
.to(AResourceReassign.class)
.omitInDestination(ar -> ar.getFirstNumberInAResource())
.reassign(AReassign::getFirstNumberInA)
.to(AResourceReassign::getFirstNumberInAResource)
.reassign(AReassign::getSecondNumberInA)
.to(AResourceReassign::getSecondNumberInAResource)
.mapper();
}
/**
* Ensures that the mapper detects an unmapped field in the destination while the all source fields are mapped.
*/
@Test(expected = MappingException.class)
public void reassignAndOneDestinationFieldIsUnmapped() {
Mapping.from(AReassign.class)
.to(AResourceReassign.class)
.reassign(AReassign::getFirstNumberInA)
.to(AResourceReassign::getSecondNumberInAResource)
.omitInSource(AReassign::getSecondNumberInA)
.mapper();
}
@SuppressWarnings("rawtypes")
@Test
public void shouldMapToNewList() {
Mapper<A, AResource> mapper = Mapping.from(A.class)
.to(AResource.class)
.omitInSource(A::getMoreInA)
.omitInDestination(AResource::getMoreInAResource)
.reassign(A::getZahlInA)
.to(AResource::getZahlInAResource)
.useMapper(Mapping.from(B.class)
.to(BResource.class)
.mapper())
.mapper();
B b = new B(B_STRING, B_NUMBER, B_INTEGER);
A a = new A(MORE_IN_A, STRING, NUMBER, INTEGER, ZAHL_IN_A, b);
a.setZahlInA(ZAHL_IN_A);
A[] aarr = new A[] {
a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a, a
};
List<A> aList = Arrays.asList(aarr);
List<AResource> arCollection = mapper.map(aList);
// Make sure this is a new collection
assertFalse((List) aList == (List) arCollection);
assertEquals(aarr.length, aList.size());
assertEquals(aarr.length, arCollection.size());
for (AResource ar : arCollection) {
assertNull(ar.getMoreInAResource());
assertEquals(STRING, a.getString());
assertEquals(STRING, ar.getString());
assertEquals(NUMBER, a.getNumber());
assertEquals(NUMBER, ar.getNumber());
assertEquals(INTEGER, a.getInteger());
assertEquals(INTEGER, ar.getInteger());
assertEquals(ZAHL_IN_A, a.getZahlInA());
assertEquals(ZAHL_IN_A, ar.getZahlInAResource());
BResource br = ar.getB();
assertEquals(B_STRING, b.getString());
assertEquals(B_STRING, br.getString());
assertEquals(B_NUMBER, b.getNumber());
assertEquals(B_NUMBER, br.getNumber());
assertEquals(B_INTEGER, b.getInteger());
assertEquals(B_INTEGER, br.getInteger());
}
}
@SuppressWarnings("rawtypes")
@Test
public void shouldMapToNewSet() {
Mapper<A, AResource> mapper = Mapping.from(A.class)
.to(AResource.class)
.omitInSource(A::getMoreInA)
.omitInDestination(AResource::getMoreInAResource)
.reassign(A::getZahlInA)
.to(AResource::getZahlInAResource)
.useMapper(Mapping.from(B.class)
.to(BResource.class)
.mapper())
.mapper();
int max = 10;
A[] aarr = new A[max];
for (int i = 0; i < max; i++) {
B b = new B(B_STRING, B_NUMBER, B_INTEGER);
A a = new A(MORE_IN_A, STRING, NUMBER, INTEGER, ZAHL_IN_A, b);
a.setZahlInA(ZAHL_IN_A);
aarr[i] = a;
}
Set<A> aList = new HashSet<>(Arrays.asList(aarr));
Set<AResource> arCollection = mapper.map(aList);
// Make sure this is a new collection
assertFalse((Set) aList == (Set) arCollection);
assertEquals(max, aList.size());
assertEquals(max, arCollection.size());
Iterator<A> as = aList.iterator();
Iterator<AResource> ars = arCollection.iterator();
while (as.hasNext()) {
A a = as.next();
AResource ar = ars.next();
assertNull(ar.getMoreInAResource());
assertEquals(STRING, a.getString());
assertEquals(STRING, ar.getString());
assertEquals(NUMBER, a.getNumber());
assertEquals(NUMBER, ar.getNumber());
assertEquals(INTEGER, a.getInteger());
assertEquals(INTEGER, ar.getInteger());
assertEquals(ZAHL_IN_A, a.getZahlInA());
assertEquals(ZAHL_IN_A, ar.getZahlInAResource());
B b = a.getB();
BResource br = ar.getB();
assertEquals(B_STRING, b.getString());
assertEquals(B_STRING, br.getString());
assertEquals(B_NUMBER, b.getNumber());
assertEquals(B_NUMBER, br.getNumber());
assertEquals(B_INTEGER, b.getInteger());
assertEquals(B_INTEGER, br.getInteger());
}
}
@Test
public void shouldDenyIllegalArguments() {
assertThatThrownBy(() -> {
Mapping.from(null);
}).isInstanceOf(IllegalArgumentException.class)
.hasNoCause();
assertThatThrownBy(() -> {
Mapping.from(A.class)
.to(null);
}).isInstanceOf(IllegalArgumentException.class)
.hasNoCause();
assertThatThrownBy(() -> {
Mapping.from(A.class)
.to(AResource.class)
.omitInSource(null);
}).isInstanceOf(IllegalArgumentException.class)
.hasNoCause();
assertThatThrownBy(() -> {
Mapping.from(A.class)
.to(AResource.class)
.omitInSource(A::getMoreInA)
.omitInDestination(null);
}).isInstanceOf(IllegalArgumentException.class)
.hasNoCause();
assertThatThrownBy(() -> {
Mapping.from(A.class)
.to(AResource.class)
.omitInSource(A::getMoreInA)
.omitInDestination(AResource::getMoreInAResource)
.reassign(null);
}).isInstanceOf(IllegalArgumentException.class)
.hasNoCause();
assertThatThrownBy(() -> {
Mapping.from(A.class)
.to(AResource.class)
.omitInSource(A::getMoreInA)
.omitInDestination(AResource::getMoreInAResource)
.reassign(A::getZahlInA)
.to(null);
}).isInstanceOf(IllegalArgumentException.class)
.hasNoCause();
assertThatThrownBy(() -> {
Mapping.from(A.class)
.to(AResource.class)
.omitInSource(A::getMoreInA)
.omitInDestination(AResource::getMoreInAResource)
.reassign(A::getZahlInA)
.to(AResource::getZahlInAResource)
.useMapper((Mapper<?, ?>) null);
}).isInstanceOf(IllegalArgumentException.class)
.hasNoCause();
// Perform the API test on replace
assertThatThrownBy(() -> {
Mapping.from(PersonWithAddress.class)
.to(PersonWithFoo.class)
.replace(null, PersonWithFoo::getFoo);
}).isInstanceOf(IllegalArgumentException.class)
.hasNoCause();
assertThatThrownBy(() -> {
Mapping.from(PersonWithAddress.class)
.to(PersonWithFoo.class)
.replace(PersonWithAddress::getAddress, null);
}).isInstanceOf(IllegalArgumentException.class)
.hasNoCause();
assertThatThrownBy(() -> {
Mapping.from(PersonWithAddress.class)
.to(PersonWithFoo.class)
.replace(PersonWithAddress::getAddress, PersonWithFoo::getFoo)
.with(null);
}).isInstanceOf(IllegalArgumentException.class)
.hasNoCause();
}
}
| apache-2.0 |
ofpteam/ofp | src/main/java/com/webside/ofp/bean/OfpTreeBean.java | 509 | package com.webside.ofp.bean;
import java.util.List;
public class OfpTreeBean {
private String text;
private int id;
private List<OfpTreeBean> nodes;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public List<OfpTreeBean> getNodes() {
return nodes;
}
public void setNodes(List<OfpTreeBean> nodes) {
this.nodes = nodes;
}
}
| apache-2.0 |
ads-tec/JSONRpcDevice | src/jsonrpcdevice/JSONRpcException.java | 1027 | /**
* Copyright 2015 ads-tec GmbH
*
* 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 jsonrpcdevice;
public class JSONRpcException extends Exception {
/**
*
*/
private static final long serialVersionUID = 1252532100215144699L;
public JSONRpcException() {
super();
}
public JSONRpcException(String message, Throwable cause) {
super(message, cause);
}
public JSONRpcException(Throwable cause) {
super(cause);
}
public JSONRpcException(String s) {
super(s);
}
}
| apache-2.0 |
dbeaver/dbeaver | plugins/org.jkiss.dbeaver.ext.exasol.ui/src/org/jkiss/dbeaver/ext/exasol/ui/config/ExasolCreateForeignKeyDialog.java | 1353 | /*
* DBeaver - Universal Database Manager
* Copyright (C) 2017-2017 Karl Griesser (fullref@gmail.com)
* Copyright (C) 2010-2022 DBeaver Corp and others
*
* 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.jkiss.dbeaver.ext.exasol.ui.config;
import org.jkiss.dbeaver.ext.exasol.model.ExasolTableForeignKey;
import org.jkiss.dbeaver.model.struct.rdb.DBSForeignKeyModifyRule;
import org.jkiss.dbeaver.ui.editors.object.struct.EditForeignKeyPage;
import java.util.Map;
public class ExasolCreateForeignKeyDialog extends EditForeignKeyPage {
public ExasolCreateForeignKeyDialog(String title, ExasolTableForeignKey foreignKey, Map<String, Object> options) {
super(title, foreignKey, new DBSForeignKeyModifyRule[0], options);
}
@Override
protected boolean supportsCustomName() {
return true;
}
}
| apache-2.0 |
gravitee-io/gravitee-gateway | gravitee-gateway-http/src/main/java/io/gravitee/gateway/http/vertx/VertxHttp2ServerRequest.java | 1884 | /**
* Copyright (C) 2015 The Gravitee team (http://gravitee.io)
*
* 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.gravitee.gateway.http.vertx;
import io.gravitee.common.http.HttpVersion;
import io.gravitee.common.http.IdGenerator;
import io.gravitee.gateway.api.Request;
import io.gravitee.gateway.api.Response;
import io.gravitee.gateway.api.buffer.Buffer;
import io.gravitee.gateway.api.handler.Handler;
import io.gravitee.gateway.api.http2.HttpFrame;
import io.vertx.core.http.HttpServerRequest;
/**
* @author David BRASSELY (david.brassely at graviteesource.com)
* @author GraviteeSource Team
*/
public class VertxHttp2ServerRequest extends VertxHttpServerRequest {
public VertxHttp2ServerRequest(HttpServerRequest httpServerRequest, IdGenerator idGenerator) {
super(httpServerRequest, idGenerator);
}
@Override
public HttpVersion version() {
return HttpVersion.HTTP_2;
}
@Override
public Request customFrameHandler(Handler<HttpFrame> frameHandler) {
getNativeServerRequest()
.customFrameHandler(
frame -> frameHandler.handle(HttpFrame.create(frame.type(), frame.flags(), Buffer.buffer(frame.payload().getBytes())))
);
return this;
}
@Override
public Response create() {
return new VertxHttp2ServerResponse(this);
}
}
| apache-2.0 |
kisskys/incubator-asterixdb | asterixdb/asterix-om/src/main/java/org/apache/asterix/om/typecomputer/impl/ClosedRecordConstructorResultType.java | 3561 | /*
* 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 org.apache.asterix.om.typecomputer.impl;
import java.util.Iterator;
import org.apache.asterix.om.base.AString;
import org.apache.asterix.om.constants.AsterixConstantValue;
import org.apache.asterix.om.typecomputer.base.IResultTypeComputer;
import org.apache.asterix.om.typecomputer.base.TypeComputerUtilities;
import org.apache.asterix.om.types.ARecordType;
import org.apache.asterix.om.types.IAType;
import org.apache.commons.lang3.mutable.Mutable;
import org.apache.hyracks.algebricks.common.exceptions.AlgebricksException;
import org.apache.hyracks.algebricks.core.algebra.base.ILogicalExpression;
import org.apache.hyracks.algebricks.core.algebra.base.LogicalExpressionTag;
import org.apache.hyracks.algebricks.core.algebra.expressions.AbstractFunctionCallExpression;
import org.apache.hyracks.algebricks.core.algebra.expressions.ConstantExpression;
import org.apache.hyracks.algebricks.core.algebra.expressions.IVariableTypeEnvironment;
import org.apache.hyracks.algebricks.core.algebra.metadata.IMetadataProvider;
public class ClosedRecordConstructorResultType implements IResultTypeComputer {
public static final ClosedRecordConstructorResultType INSTANCE = new ClosedRecordConstructorResultType();
@Override
public IAType computeType(ILogicalExpression expression, IVariableTypeEnvironment env,
IMetadataProvider<?, ?> metadataProvider) throws AlgebricksException {
AbstractFunctionCallExpression f = (AbstractFunctionCallExpression) expression;
/**
* if type has been top-down propagated, use the enforced type
*/
ARecordType type = (ARecordType) TypeComputerUtilities.getRequiredType(f);
if (type != null)
return type;
int n = f.getArguments().size() / 2;
String[] fieldNames = new String[n];
IAType[] fieldTypes = new IAType[n];
int i = 0;
Iterator<Mutable<ILogicalExpression>> argIter = f.getArguments().iterator();
while (argIter.hasNext()) {
ILogicalExpression e1 = argIter.next().getValue();
if (e1.getExpressionTag() == LogicalExpressionTag.CONSTANT) {
ConstantExpression nameExpr = (ConstantExpression) e1;
fieldNames[i] = ((AString) ((AsterixConstantValue) nameExpr.getValue()).getObject()).getStringValue();
} else {
throw new AlgebricksException(
"Field name " + i + "(" + e1 + ") in call to closed-record-constructor is not a constant.");
}
ILogicalExpression e2 = argIter.next().getValue();
fieldTypes[i] = (IAType) env.getType(e2);
i++;
}
return new ARecordType(null, fieldNames, fieldTypes, false);
}
}
| apache-2.0 |
manuelmagix/android_packages_apps_Settings | src/com/android/settings/sim/SimSettings.java | 25435 | /*
* Copyright (C) 2014 The Android Open Source Project
*
* 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.android.settings.sim;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemProperties;
import android.preference.Preference;
import android.preference.PreferenceCategory;
import android.preference.PreferenceScreen;
import android.preference.SwitchPreference;
import android.provider.SearchIndexableResource;
import android.provider.Settings.SettingNotFoundException;
import android.telephony.SubscriptionInfo;
import android.telephony.SubscriptionManager;
import android.telephony.TelephonyManager;
import android.telephony.PhoneStateListener;
import android.util.Log;
import android.widget.Toast;
import com.android.internal.telephony.Phone;
import com.android.internal.telephony.PhoneConstants;
import com.android.internal.telephony.TelephonyIntents;
import com.android.settings.R;
import com.android.settings.RestrictedSettingsFragment;
import com.android.settings.Utils;
import com.android.settings.notification.DropDownPreference;
import com.android.settings.search.BaseSearchIndexProvider;
import com.android.settings.search.Indexable;
import java.util.ArrayList;
import java.util.List;
public class SimSettings extends RestrictedSettingsFragment implements Indexable {
private static final String TAG = "SimSettings";
private static final boolean DBG = true;
public static final String CONFIG_LTE_SUB_SELECT_MODE = "config_lte_sub_select_mode";
private static final String CONFIG_PRIMARY_SUB_SETABLE = "config_primary_sub_setable";
private static final String DISALLOW_CONFIG_SIM = "no_config_sim";
private static final String SIM_ENABLER_CATEGORY = "sim_enablers";
private static final String SIM_ACTIVITIES_CATEGORY = "sim_activities";
private static final String MOBILE_NETWORK_CATEGORY = "mobile_network";
private static final String KEY_CELLULAR_DATA = "sim_cellular_data";
private static final String KEY_CALLS = "sim_calls";
private static final String KEY_SMS = "sim_sms";
private static final String KEY_ACTIVITIES = "activities";
private static final String KEY_PRIMARY_SUB_SELECT = "select_primary_sub";
private static final String SIM_DATA_CATEGORY = "sim_data_category";
private static final String SIM_DATA_KEY = "sim_data";
private static final int EVT_UPDATE = 1;
private long mPreferredDataSubscription;
private int mNumSlots = 0;
/**
* By UX design we have use only one Subscription Information(SubInfo) record per SIM slot.
* mAvalableSubInfos is the list of SubInfos we present to the user.
* mSubInfoList is the list of all SubInfos.
*/
private List<SubscriptionInfo> mAvailableSubInfos = null;
private List<SubscriptionInfo> mSubInfoList = null;
private Preference mPrimarySubSelect = null;
private List<MultiSimEnablerPreference> mSimEnablers = null;
private List<Preference> mMobileNetworkSettings = null;
private SubscriptionInfo mCellularData = null;
private SubscriptionInfo mCalls = null;
private SubscriptionInfo mSMS = null;
private int mNumSims;
private int mPhoneCount;
private int[] mCallState;
private PhoneStateListener[] mPhoneStateListener;
private boolean mDataDisableToastDisplayed = false;
private SubscriptionManager mSubscriptionManager;
private boolean mHardcodeDefaultMobileNetworks = false;
private TelephonyManager mTelephonyManager;
public SimSettings() {
super(DISALLOW_CONFIG_SIM);
}
@Override
public void onCreate(final Bundle bundle) {
super.onCreate(bundle);
Log.d(TAG,"on onCreate");
mSubscriptionManager = SubscriptionManager.from(getActivity());
mTelephonyManager = (TelephonyManager) getActivity()
.getSystemService(Context.TELEPHONY_SERVICE);
if (mSubInfoList == null) {
mSubInfoList = mSubscriptionManager.getActiveSubscriptionInfoList();
}
mHardcodeDefaultMobileNetworks = getResources()
.getBoolean(R.bool.config_hardcodeDefaultMobileNetworks);
mNumSlots = mTelephonyManager.getSimCount();
mPhoneCount = TelephonyManager.getDefault().getPhoneCount();
mCallState = new int[mPhoneCount];
mPhoneStateListener = new PhoneStateListener[mPhoneCount];
listen();
mPreferredDataSubscription = mSubscriptionManager.getDefaultDataSubId();
createPreferences();
updateAllOptions();
IntentFilter intentFilter =
new IntentFilter(TelephonyIntents.ACTION_DEFAULT_DATA_SUBSCRIPTION_CHANGED);
intentFilter.addAction(TelephonyIntents.ACTION_SUBINFO_CONTENT_CHANGE);
intentFilter.addAction(TelephonyIntents.ACTION_SUBINFO_RECORD_UPDATED);
getActivity().registerReceiver(mDdsSwitchReceiver, intentFilter);
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG,"on onDestroy");
getActivity().unregisterReceiver(mDdsSwitchReceiver);
unRegisterPhoneStateListener();
}
private void unRegisterPhoneStateListener() {
for (int i = 0; i < mPhoneCount; i++) {
if (mPhoneStateListener[i] != null) {
mTelephonyManager.listen(mPhoneStateListener[i], PhoneStateListener.LISTEN_NONE);
mPhoneStateListener[i] = null;
}
}
}
private BroadcastReceiver mDdsSwitchReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.d(TAG, "Intent received: " + action);
if (TelephonyIntents.ACTION_DEFAULT_DATA_SUBSCRIPTION_CHANGED.equals(action)) {
updateCellularDataValues();
int preferredDataSubscription = mSubscriptionManager.getDefaultDataSubId();
if (preferredDataSubscription != mPreferredDataSubscription) {
mPreferredDataSubscription = preferredDataSubscription;
String status = getResources().getString(R.string.switch_data_subscription,
mSubscriptionManager.getSlotId(preferredDataSubscription) + 1);
Toast.makeText(getActivity(), status, Toast.LENGTH_SHORT).show();
}
} else if (TelephonyIntents.ACTION_SUBINFO_CONTENT_CHANGE.equals(action)
|| TelephonyIntents.ACTION_SUBINFO_RECORD_UPDATED.equals(action)) {
mAvailableSubInfos.clear();
mNumSims = 0;
mSubInfoList = mSubscriptionManager.getActiveSubscriptionInfoList();
if (mSubInfoList != null) {
for (int i = 0; i < mNumSlots; ++i) {
final SubscriptionInfo sir = findRecordBySlotId(i);
// Do not display deactivated subInfo in preference list
if ((sir != null) && (sir.mStatus == mSubscriptionManager.ACTIVE)) {
mNumSims++;
mAvailableSubInfos.add(sir);
}
}
}
// Refresh UI whenever subinfo record gets changed
updateAllOptions();
}
final SwitchPreference dataToggle = (SwitchPreference) findPreference(SIM_DATA_KEY);
dataToggle.setChecked(mTelephonyManager.getDataEnabled());
}
};
private void createPreferences() {
addPreferencesFromResource(R.xml.sim_settings);
final SwitchPreference dataToggle = (SwitchPreference) findPreference(SIM_DATA_KEY);
dataToggle.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
final boolean dataEnabled = (Boolean) newValue;
mTelephonyManager.setDataEnabled(dataEnabled);
return true;
}
});
mPrimarySubSelect = (Preference) findPreference(KEY_PRIMARY_SUB_SELECT);
final PreferenceCategory simEnablers =
(PreferenceCategory)findPreference(SIM_ENABLER_CATEGORY);
final PreferenceCategory mobileNetwork =
(PreferenceCategory) findPreference(MOBILE_NETWORK_CATEGORY);
mAvailableSubInfos = new ArrayList<SubscriptionInfo>(mNumSlots);
mSimEnablers = new ArrayList<MultiSimEnablerPreference>(mNumSlots);
mMobileNetworkSettings = new ArrayList<Preference>(mNumSlots);
for (int i = 0; i < mNumSlots; ++i) {
final SubscriptionInfo sir = findRecordBySlotId(i);
if (mNumSlots > 1) {
MultiSimEnablerPreference multiSimEnablerPreference =
new MultiSimEnablerPreference(getActivity(), sir, mHandler, i);
mSimEnablers.add(multiSimEnablerPreference);
simEnablers.addPreference(multiSimEnablerPreference);
if (mHardcodeDefaultMobileNetworks && i == 0) {
multiSimEnablerPreference.setExplicitlyDisabled(true);
}
} else {
removePreference(SIM_ENABLER_CATEGORY);
}
// Do not display deactivated subInfo in preference list
if ((sir != null) && (sir.mStatus == mSubscriptionManager.ACTIVE)) {
mNumSims++;
mAvailableSubInfos.add(sir);
}
Intent mobileNetworkIntent = new Intent();
mobileNetworkIntent.setComponent(new ComponentName(
"com.android.phone", "com.android.phone.MobileNetworkSettings"));
SubscriptionManager.putPhoneIdAndSubIdExtra(mobileNetworkIntent,
i, sir != null ? sir.getSubscriptionId() : -1);
Preference mobileNetworkPref = new Preference(getActivity());
mobileNetworkPref.setTitle(
getString(R.string.sim_mobile_network_settings_title, (i + 1)));
mobileNetworkPref.setIntent(mobileNetworkIntent);
mobileNetwork.addPreference(mobileNetworkPref);
mMobileNetworkSettings.add(mobileNetworkPref);
}
}
private void updateAllOptions() {
Log.d(TAG,"updateAllOptions");
mSubInfoList = mSubscriptionManager.getActiveSubscriptionInfoList();
updateActivitesCategory();
updateSimEnablers();
updateMobileNetworkSettings();
}
private void listen() {
for (int i = 0; i < mPhoneCount; i++) {
int[] subId = mSubscriptionManager.getSubId(i);
if (subId != null) {
if (subId[0] > 0) {
mCallState[i] = mTelephonyManager.getCallState(subId[0]);
mTelephonyManager.listen(getPhoneStateListener(i, subId[0]),
PhoneStateListener.LISTEN_CALL_STATE);
}
}
}
}
private PhoneStateListener getPhoneStateListener(int phoneId, int subId) {
final int i = phoneId;
mPhoneStateListener[phoneId] = new PhoneStateListener(subId) {
@Override
public void onCallStateChanged(int state, String ignored) {
Log.d(TAG, "onCallStateChanged: " + state);
mCallState[i] = state;
updateCellularDataPreference();
}
};
return mPhoneStateListener[phoneId];
}
private void updateActivitesCategory() {
createDropDown((DropDownPreference) findPreference(KEY_CELLULAR_DATA));
createDropDown((DropDownPreference) findPreference(KEY_CALLS));
createDropDown((DropDownPreference) findPreference(KEY_SMS));
updateCellularDataValues();
updateCallValues();
updateSmsValues();
}
/**
* finds a record with subId.
* Since the number of SIMs are few, an array is fine.
*/
private SubscriptionInfo findRecordBySubId(final long subId) {
final int availableSubInfoLength = mAvailableSubInfos.size();
for (int i = 0; i < availableSubInfoLength; ++i) {
final SubscriptionInfo sir = mAvailableSubInfos.get(i);
if (sir != null && sir.getSubscriptionId() == subId) {
return sir;
}
}
return null;
}
/**
* finds a record with slotId.
* Since the number of SIMs are few, an array is fine.
*/
private SubscriptionInfo findRecordBySlotId(final int slotId) {
if (mSubInfoList != null) {
final int availableSubInfoLength = mSubInfoList.size();
for (int i = 0; i < availableSubInfoLength; ++i) {
final SubscriptionInfo sir = mSubInfoList.get(i);
if (sir.getSimSlotIndex() == slotId) {
//Right now we take the first subscription on a SIM.
return sir;
}
}
}
return null;
}
private void updateSmsValues() {
final DropDownPreference simPref = (DropDownPreference) findPreference(KEY_SMS);
long subId = mSubscriptionManager.isSMSPromptEnabled() ?
0 : mSubscriptionManager.getDefaultSmsSubId();
final SubscriptionInfo sir = findRecordBySubId(subId);
if (sir != null) {
simPref.setSelectedValue(sir, false);
}
simPref.setEnabled(mNumSims > 1);
}
private void updateCellularDataValues() {
final DropDownPreference simPref = (DropDownPreference) findPreference(KEY_CELLULAR_DATA);
final SubscriptionInfo sir = findRecordBySubId(mSubscriptionManager.getDefaultDataSubId());
if (sir != null) {
simPref.setSelectedValue(sir, false);
}
updateCellularDataPreference();
}
private void updateCellularDataPreference() {
final DropDownPreference simPref = (DropDownPreference) findPreference(KEY_CELLULAR_DATA);
boolean callStateIdle = isCallStateIdle();
// Enable data preference in msim mode and call state idle
simPref.setEnabled((mNumSims > 1) && callStateIdle);
// Display toast only once when the user enters the activity even though the call moves
// through multiple call states (eg - ringing to offhook for incoming calls)
if (callStateIdle == false && isResumed() && !mDataDisableToastDisplayed) {
Toast.makeText(getActivity(), R.string.data_disabled_in_active_call,
Toast.LENGTH_SHORT).show();
mDataDisableToastDisplayed = true;
}
// Reset dataDisableToastDisplayed
if (callStateIdle) {
mDataDisableToastDisplayed = false;
}
}
private boolean isCallStateIdle() {
boolean callStateIdle = true;
for (int i = 0; i < mCallState.length; i++) {
if (TelephonyManager.CALL_STATE_IDLE != mCallState[i]) {
callStateIdle = false;
}
}
Log.d(TAG, "isCallStateIdle " + callStateIdle);
return callStateIdle;
}
private void updateCallValues() {
final DropDownPreference simPref = (DropDownPreference) findPreference(KEY_CALLS);
long subId = mSubscriptionManager.isVoicePromptEnabled() ?
0 : mSubscriptionManager.getDefaultVoiceSubId();
final SubscriptionInfo sir = findRecordBySubId(subId);
if (sir != null) {
simPref.setSelectedValue(sir, false);
}
simPref.setEnabled(mNumSims > 1);
}
@Override
public void onPause() {
super.onPause();
Log.d(TAG,"on Pause");
mDataDisableToastDisplayed = false;
for (int i = 0; i < mSimEnablers.size(); ++i) {
MultiSimEnablerPreference simEnabler = mSimEnablers.get(i);
if (simEnabler != null) simEnabler.cleanUp();
}
}
@Override
public void onResume() {
super.onResume();
Log.d(TAG,"on Resume, number of slots = " + mNumSlots);
initLTEPreference();
updateAllOptions();
}
private void initLTEPreference() {
boolean isPrimarySubFeatureEnable = SystemProperties
.getBoolean("persist.radio.primarycard", false);
boolean primarySetable = android.provider.Settings.Global.getInt(
this.getContentResolver(), CONFIG_PRIMARY_SUB_SETABLE, 0) == 1;
logd("isPrimarySubFeatureEnable :" + isPrimarySubFeatureEnable +
" primarySetable :" + primarySetable);
if (!isPrimarySubFeatureEnable || !primarySetable) {
final PreferenceCategory simActivities =
(PreferenceCategory) findPreference(SIM_ACTIVITIES_CATEGORY);
simActivities.removePreference(mPrimarySubSelect);
return;
}
int primarySlot = getCurrentPrimarySlot();
boolean isManualMode = android.provider.Settings.Global.getInt(
this.getContentResolver(), CONFIG_LTE_SUB_SELECT_MODE, 1) == 0;
logd("init LTE primary slot : " + primarySlot + " isManualMode :" + isManualMode);
if (-1 != primarySlot) {
SubscriptionInfo subInfo = findRecordBySlotId(primarySlot);
CharSequence lteSummary = (subInfo == null ) ? null : subInfo.getDisplayName();
mPrimarySubSelect.setSummary(lteSummary);
} else {
mPrimarySubSelect.setSummary("");
}
mPrimarySubSelect.setEnabled(isManualMode);
}
public int getCurrentPrimarySlot() {
for (int index = 0; index < mNumSlots; index++) {
int current = getPreferredNetwork(index);
if (current == Phone.NT_MODE_TD_SCDMA_GSM_WCDMA_LTE
|| current == Phone.NT_MODE_TD_SCDMA_GSM_WCDMA) {
return index;
}
}
return -1;
}
private int getPreferredNetwork(int sub) {
int nwMode = -1;
try {
nwMode = TelephonyManager.getIntAtIndex(this.getContentResolver(),
android.provider.Settings.Global.PREFERRED_NETWORK_MODE, sub);
} catch (SettingNotFoundException snfe) {
}
return nwMode;
}
@Override
public boolean onPreferenceTreeClick(final PreferenceScreen preferenceScreen,
final Preference preference) {
if (preference instanceof MultiSimEnablerPreference) {
((MultiSimEnablerPreference) preference).createEditDialog();
return true;
} else if (preference == mPrimarySubSelect) {
startActivity(mPrimarySubSelect.getIntent());
return true;
}
return false;
}
public void createDropDown(DropDownPreference preference) {
final DropDownPreference simPref = preference;
final String keyPref = simPref.getKey();
int mActCount = 0;
final boolean askFirst = keyPref.equals(KEY_CALLS) || keyPref.equals(KEY_SMS);
//If Fragment not yet attached to Activity, return
if (!isAdded()) {
Log.d(TAG,"Fragment not yet attached to Activity, EXIT!!" );
return;
}
simPref.clearItems();
// Get num of activated Subs if mSubInfoList is not null
if (mSubInfoList != null) {
for (SubscriptionInfo subInfo : mSubInfoList) {
if (subInfo != null && subInfo.mStatus == mSubscriptionManager.ACTIVE) mActCount++;
}
}
if (askFirst && mActCount > 1) {
simPref.addItem(getResources().getString(
R.string.sim_calls_ask_first_prefs_title), null);
}
final int subAvailableSize = mAvailableSubInfos.size();
for (int i = 0; i < subAvailableSize; ++i) {
final SubscriptionInfo sir = mAvailableSubInfos.get(i);
if(sir != null){
if (i > 0 && (keyPref.equals(KEY_CALLS) || keyPref.equals(KEY_SMS)) &&
mHardcodeDefaultMobileNetworks) {
continue;
}
simPref.addItem(sir.getDisplayName().toString(), sir);
}
}
simPref.setCallback(new DropDownPreference.Callback() {
@Override
public boolean onItemSelected(int pos, Object value) {
final int subId = value == null ? 0 :
((SubscriptionInfo)value).getSubscriptionId();
Log.d(TAG,"calling setCallback: " + simPref.getKey() + "subId: " + subId);
if (simPref.getKey().equals(KEY_CELLULAR_DATA)) {
if (mSubscriptionManager.getDefaultDataSubId() != subId) {
mSubscriptionManager.setDefaultDataSubId(subId);
}
} else if (simPref.getKey().equals(KEY_CALLS)) {
//subId 0 is meant for "Ask First"/"Prompt" option as per AOSP
if (subId == 0) {
mSubscriptionManager.setVoicePromptEnabled(true);
} else {
mSubscriptionManager.setVoicePromptEnabled(false);
if (mSubscriptionManager.getDefaultVoiceSubId() != subId) {
mSubscriptionManager.setDefaultVoiceSubId(subId);
}
}
} else if (simPref.getKey().equals(KEY_SMS)) {
if (subId == 0) {
mSubscriptionManager.setSMSPromptEnabled(true);
} else {
mSubscriptionManager.setSMSPromptEnabled(false);
if (mSubscriptionManager.getDefaultSmsSubId() != subId) {
mSubscriptionManager.setDefaultSmsSubId(subId);
}
}
}
return true;
}
});
}
private void setActivity(Preference preference, SubscriptionInfo sir) {
final String key = preference.getKey();
if (key.equals(KEY_CELLULAR_DATA)) {
mCellularData = sir;
} else if (key.equals(KEY_CALLS)) {
mCalls = sir;
} else if (key.equals(KEY_SMS)) {
mSMS = sir;
}
updateActivitesCategory();
}
/**
* For search
*/
public static final SearchIndexProvider SEARCH_INDEX_DATA_PROVIDER =
new BaseSearchIndexProvider() {
@Override
public List<SearchIndexableResource> getXmlResourcesToIndex(Context context,
boolean enabled) {
ArrayList<SearchIndexableResource> result =
new ArrayList<SearchIndexableResource>();
if (Utils.showSimCardTile(context)) {
SearchIndexableResource sir = new SearchIndexableResource(context);
sir.xmlResId = R.xml.sim_settings;
result.add(sir);
}
return result;
}
};
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
logd("msg.what = " + msg.what);
switch(msg.what) {
case EVT_UPDATE:
updateAllOptions();
break;
default:
break;
}
}
};
private void updateSimEnablers() {
for (int i = 0; i < mSimEnablers.size(); ++i) {
MultiSimEnablerPreference simEnabler = mSimEnablers.get(i);
if (simEnabler != null) simEnabler.update();
}
}
private void updateMobileNetworkSettings() {
for (int i = 0; i < mMobileNetworkSettings.size(); i++) {
Preference preference = mMobileNetworkSettings.get(i);
if (preference != null) {
Intent intent = preference.getIntent();
int subId = intent.getIntExtra(PhoneConstants.SUBSCRIPTION_KEY,
SubscriptionManager.INVALID_SUBSCRIPTION_ID);;
if (!SubscriptionManager.isValidSubscriptionId(subId)
|| !SubscriptionManager.isUsableSubIdValue(subId)) {
preference.setEnabled(false);
} else {
preference.setEnabled(true);
}
}
}
}
private void logd(String msg) {
if (DBG) Log.d(TAG, msg);
}
private void loge(String s) {
Log.e(TAG, s);
}
}
| apache-2.0 |
mdogan/hazelcast | hazelcast/src/main/java/com/hazelcast/sql/impl/expression/ColumnExpression.java | 3330 | /*
* Copyright (c) 2008-2020, Hazelcast, Inc. 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.
*/
package com.hazelcast.sql.impl.expression;
import com.hazelcast.nio.ObjectDataInput;
import com.hazelcast.nio.ObjectDataOutput;
import com.hazelcast.nio.serialization.IdentifiedDataSerializable;
import com.hazelcast.sql.impl.SqlDataSerializerHook;
import com.hazelcast.sql.impl.row.Row;
import com.hazelcast.sql.impl.type.QueryDataType;
import com.hazelcast.sql.impl.type.QueryDataTypeUtils;
import java.io.IOException;
/**
* Column access expression.
*/
public final class ColumnExpression<T> implements Expression<T>, IdentifiedDataSerializable {
/** Index in the row. */
private int index;
/** Type of the returned value. */
private QueryDataType type;
public ColumnExpression() {
// No-op.
}
private ColumnExpression(int index, QueryDataType type) {
this.index = index;
this.type = type;
}
public static ColumnExpression<?> create(int index, QueryDataType type) {
// Canonicalize the column type: currently values of non-canonical types,
// like QueryDataType.VARCHAR_CHARACTER, are canonicalized to values of
// some other canonical type, like QueryDataType.VARCHAR. That kind of
// changes the observed type of a column to a canonical one.
Class<?> canonicalClass = type.getConverter().getNormalizedValueClass();
QueryDataType canonicalType = QueryDataTypeUtils.resolveTypeForClass(canonicalClass);
return new ColumnExpression<>(index, canonicalType);
}
@SuppressWarnings("unchecked")
@Override public T eval(Row row, ExpressionEvalContext context) {
return (T) row.get(index);
}
@Override
public QueryDataType getType() {
return type;
}
@Override
public int getFactoryId() {
return SqlDataSerializerHook.F_ID;
}
@Override
public int getClassId() {
return SqlDataSerializerHook.EXPRESSION_COLUMN;
}
@Override
public void writeData(ObjectDataOutput out) throws IOException {
out.writeInt(index);
out.writeObject(type);
}
@Override
public void readData(ObjectDataInput in) throws IOException {
index = in.readInt();
type = in.readObject();
}
@Override
public int hashCode() {
int result = index;
result = 31 * result + type.hashCode();
return result;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ColumnExpression<?> that = (ColumnExpression<?>) o;
return index == that.index && type.equals(that.type);
}
}
| apache-2.0 |
lvweiwolf/poi-3.16 | src/ooxml/testcases/org/apache/poi/ss/formula/TestFormulaParser.java | 9998 | /*
* ====================================================================
* 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 org.apache.poi.ss.formula;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFEvaluationWorkbook;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.formula.ptg.AbstractFunctionPtg;
import org.apache.poi.ss.formula.ptg.NameXPxg;
import org.apache.poi.ss.formula.ptg.Ptg;
import org.apache.poi.ss.formula.ptg.Ref3DPxg;
import org.apache.poi.ss.formula.ptg.StringPtg;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xssf.XSSFTestDataSamples;
import org.apache.poi.xssf.usermodel.XSSFEvaluationWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.Test;
/**
* Test {@link FormulaParser}'s handling of row numbers at the edge of the
* HSSF/XSSF ranges.
*
* @author David North
*/
public class TestFormulaParser {
@Test
public void testHSSFFailsForOver65536() {
FormulaParsingWorkbook workbook = HSSFEvaluationWorkbook.create(new HSSFWorkbook());
try {
FormulaParser.parse("Sheet1!1:65537", workbook, FormulaType.CELL, 0);
fail("Expected exception");
}
catch (FormulaParseException expected) {
// expected here
}
}
private static void checkHSSFFormula(String formula) {
HSSFWorkbook wb = new HSSFWorkbook();
FormulaParsingWorkbook workbook = HSSFEvaluationWorkbook.create(wb);
FormulaParser.parse(formula, workbook, FormulaType.CELL, 0);
IOUtils.closeQuietly(wb);
}
private static void checkXSSFFormula(String formula) {
XSSFWorkbook wb = new XSSFWorkbook();
FormulaParsingWorkbook workbook = XSSFEvaluationWorkbook.create(wb);
FormulaParser.parse(formula, workbook, FormulaType.CELL, 0);
IOUtils.closeQuietly(wb);
}
private static void checkFormula(String formula) {
checkHSSFFormula(formula);
checkXSSFFormula(formula);
}
@Test
public void testHSSFPassCase() {
checkHSSFFormula("Sheet1!1:65536");
}
@Test
public void testXSSFWorksForOver65536() {
checkXSSFFormula("Sheet1!1:65537");
}
@Test
public void testXSSFFailCase() {
FormulaParsingWorkbook workbook = XSSFEvaluationWorkbook.create(new XSSFWorkbook());
try {
FormulaParser.parse("Sheet1!1:1048577", workbook, FormulaType.CELL, 0); // one more than max rows.
fail("Expected exception");
}
catch (FormulaParseException expected) {
// expected here
}
}
// copied from org.apache.poi.hssf.model.TestFormulaParser
@Test
public void testMacroFunction() throws Exception {
// testNames.xlsm contains a VB function called 'myFunc'
final String testFile = "testNames.xlsm";
XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook(testFile);
try {
XSSFEvaluationWorkbook workbook = XSSFEvaluationWorkbook.create(wb);
//Expected ptg stack: [NamePtg(myFunc), StringPtg(arg), (additional operands would go here...), FunctionPtg(myFunc)]
Ptg[] ptg = FormulaParser.parse("myFunc(\"arg\")", workbook, FormulaType.CELL, -1);
assertEquals(3, ptg.length);
// the name gets encoded as the first operand on the stack
NameXPxg tname = (NameXPxg) ptg[0];
assertEquals("myFunc", tname.toFormulaString());
// the function's arguments are pushed onto the stack from left-to-right as OperandPtgs
StringPtg arg = (StringPtg) ptg[1];
assertEquals("arg", arg.getValue());
// The external FunctionPtg is the last Ptg added to the stack
// During formula evaluation, this Ptg pops off the the appropriate number of
// arguments (getNumberOfOperands()) and pushes the result on the stack
AbstractFunctionPtg tfunc = (AbstractFunctionPtg) ptg[2];
assertTrue(tfunc.isExternalFunction());
// confirm formula parsing is case-insensitive
FormulaParser.parse("mYfUnC(\"arg\")", workbook, FormulaType.CELL, -1);
// confirm formula parsing doesn't care about argument count or type
// this should only throw an error when evaluating the formula.
FormulaParser.parse("myFunc()", workbook, FormulaType.CELL, -1);
FormulaParser.parse("myFunc(\"arg\", 0, TRUE)", workbook, FormulaType.CELL, -1);
// A completely unknown formula name (not saved in workbook) should still be parseable and renderable
// but will throw an NotImplementedFunctionException or return a #NAME? error value if evaluated.
FormulaParser.parse("yourFunc(\"arg\")", workbook, FormulaType.CELL, -1);
// Make sure workbook can be written and read
XSSFTestDataSamples.writeOutAndReadBack(wb).close();
// Manually check to make sure file isn't corrupted
// TODO: develop a process for occasionally manually reviewing workbooks
// to verify workbooks are not corrupted
/*
final File fileIn = XSSFTestDataSamples.getSampleFile(testFile);
final File reSavedFile = new File(fileIn.getParentFile(), fileIn.getName().replace(".xlsm", "-saved.xlsm"));
final FileOutputStream fos = new FileOutputStream(reSavedFile);
wb.write(fos);
fos.close();
*/
} finally {
wb.close();
}
}
@Test
public void testParserErrors() throws Exception {
XSSFWorkbook wb = XSSFTestDataSamples.openSampleWorkbook("testNames.xlsm");
try {
XSSFEvaluationWorkbook workbook = XSSFEvaluationWorkbook.create(wb);
parseExpectedException("(");
parseExpectedException(")");
parseExpectedException("+");
parseExpectedException("42+");
parseExpectedException("IF()");
parseExpectedException("IF("); //no closing paren
parseExpectedException("myFunc(", workbook); //no closing paren
} finally {
wb.close();
}
}
private static void parseExpectedException(String formula) {
parseExpectedException(formula, null);
}
/** confirm formula has invalid syntax and parsing the formula results in FormulaParseException
*/
private static void parseExpectedException(String formula, FormulaParsingWorkbook wb) {
try {
FormulaParser.parse(formula, wb, FormulaType.CELL, -1);
fail("Expected FormulaParseException: " + formula);
} catch (final FormulaParseException e) {
// expected during successful test
assertNotNull(e.getMessage());
}
}
// trivial case for bug 60219: FormulaParser can't parse external references when sheet name is quoted
@Test
public void testParseExternalReferencesWithUnquotedSheetName() throws Exception {
XSSFWorkbook wb = new XSSFWorkbook();
XSSFEvaluationWorkbook fpwb = XSSFEvaluationWorkbook.create(wb);
Ptg[] ptgs = FormulaParser.parse("[1]Sheet1!A1", fpwb, FormulaType.CELL, -1);
// org.apache.poi.ss.formula.ptg.Ref3DPxg [ [workbook=1] sheet=Sheet 1 ! A1]
assertEquals("Ptgs length", 1, ptgs.length);
assertTrue("Ptg class", ptgs[0] instanceof Ref3DPxg);
Ref3DPxg pxg = (Ref3DPxg) ptgs[0];
assertEquals("External workbook number", 1, pxg.getExternalWorkbookNumber());
assertEquals("Sheet name", "Sheet1", pxg.getSheetName());
assertEquals("Row", 0, pxg.getRow());
assertEquals("Column", 0, pxg.getColumn());
wb.close();
}
// bug 60219: FormulaParser can't parse external references when sheet name is quoted
@Test
public void testParseExternalReferencesWithQuotedSheetName() throws Exception {
XSSFWorkbook wb = new XSSFWorkbook();
XSSFEvaluationWorkbook fpwb = XSSFEvaluationWorkbook.create(wb);
Ptg[] ptgs = FormulaParser.parse("'[1]Sheet 1'!A1", fpwb, FormulaType.CELL, -1);
// org.apache.poi.ss.formula.ptg.Ref3DPxg [ [workbook=1] sheet=Sheet 1 ! A1]
assertEquals("Ptgs length", 1, ptgs.length);
assertTrue("Ptg class", ptgs[0] instanceof Ref3DPxg);
Ref3DPxg pxg = (Ref3DPxg) ptgs[0];
assertEquals("External workbook number", 1, pxg.getExternalWorkbookNumber());
assertEquals("Sheet name", "Sheet 1", pxg.getSheetName());
assertEquals("Row", 0, pxg.getRow());
assertEquals("Column", 0, pxg.getColumn());
wb.close();
}
// bug 60260
@Test
public void testUnicodeSheetName() {
checkFormula("'Sheet\u30FB1'!A1:A6");
}
}
| apache-2.0 |
mufaddalq/cloudstack-datera-driver | core/src/com/cloud/agent/api/UpgradeSnapshotCommand.java | 2448 | // 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 com.cloud.agent.api;
import com.cloud.storage.StoragePool;
public class UpgradeSnapshotCommand extends SnapshotCommand {
private String version;
private Long templateId;
private Long tmpltAccountId;
protected UpgradeSnapshotCommand() {
}
/**
* @param primaryStoragePoolNameLabel The UUID of the primary storage Pool
* @param secondaryStoragePoolURL This is what shows up in the UI when you click on Secondary storage.
* @param snapshotUuid The UUID of the snapshot which is going to be upgraded
* @param _version version for this snapshot
*/
public UpgradeSnapshotCommand(StoragePool pool,
String secondaryStoragePoolURL,
Long dcId,
Long accountId,
Long volumeId,
Long templateId,
Long tmpltAccountId,
String volumePath,
String snapshotUuid,
String snapshotName,
String version)
{
super(pool, secondaryStoragePoolURL, snapshotUuid, snapshotName, dcId, accountId, volumeId);
this.version = version;
this.templateId = templateId;
this.tmpltAccountId = tmpltAccountId;
}
public String getVersion() {
return version;
}
public Long getTemplateId() {
return templateId;
}
public Long getTmpltAccountId() {
return tmpltAccountId;
}
}
| apache-2.0 |
dvamedveda/b.savelev | chapter_001/src/main/java/ru/job4j/condition/Point.java | 1395 | package ru.job4j.condition;
/**
* Класс Point, содержащий класс, конструктор и метод для работы с точнами.
*
* @author - b.savelev (mailto: justmustdie@yandex.ru)
* @version - 1.0
* @since 0.1
*/
public class Point {
/**
* Поля класса, обозначающие его координаты.
*/
private int x, y;
/**
* Конструктор класса Point.
* @param x координата x.
* @param y координата y.
*/
public Point(int x, int y) {
this.x = x;
this.y = y;
}
/**
* Возращает координату X точки.
*
* @return int x
*/
public int getX() {
return this.x;
}
/**
* Возвращает координату Y точки.
*
* @return int y
*/
public int getY() {
return this.y;
}
/**
* Метод, определящий, находится ли точка на заданной функции.
*
* @param a int один из параметров функции.
* @param b int второй из параметров функции.
* @return boolean нахождение точки на функции
*/
public boolean is(int a, int b) {
return (this.y == a * this.x + b);
}
} | apache-2.0 |
mengdd/LeetCode | algorithms/src/main/java/SymmetricTree/TreeNode.java | 148 | package SymmetricTree;
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
| apache-2.0 |
noties/Storm2.0 | stormparser/parser-test/src/test/java/storm/parser/converter/StormConverterTest.java | 9834 | package storm.parser.converter;
import android.content.ContentValues;
import android.database.Cursor;
import junit.framework.TestCase;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import storm.annotations.Column;
import storm.annotations.PrimaryKey;
import storm.annotations.Serialize;
import storm.annotations.Table;
import storm.cursormock.StormCursorMock;
import storm.parser.ParserAssert;
import storm.parser.StormParserException;
import storm.parser.StormParserFactory;
import storm.parser.converter.serializer.BooleanIntSerializer;
import storm.parser.converter.serializer.BooleanStringSerializer;
import storm.parser.converter.serializer.StormSerializer;
/**
* Created by Dimitry Ivanov on 13.12.2015.
*/
@RunWith(RobolectricTestRunner.class)
@Config(manifest = Config.NONE)
public class StormConverterTest extends TestCase {
private <T> StormConverter<T> getConverter(Class<T> cl) {
ParserAssert.assertApt(cl, StormConverterAptClassNameBuilder.getInstance());
try {
return new StormParserFactory().provide(cl).converter();
} catch (StormParserException e) {
throw new RuntimeException(e);
}
}
@Table
static class Test1 {
@Override
public boolean equals(Object o) {
if (this == o) return true;
// we skip checking for Class<?> equality because we are using
// anonymous class for fast creation of this object
Test1 test1 = (Test1) o;
if (id != test1.id) return false;
if (Float.compare(test1.someFloat, someFloat) != 0) return false;
if (Double.compare(test1.someDouble, someDouble) != 0) return false;
if (someInt != test1.someInt) return false;
if (someString != null ? !someString.equals(test1.someString) : test1.someString != null)
return false;
return Arrays.equals(byteArray, test1.byteArray);
}
@Override
public String toString() {
return "Test1{" +
"id=" + id +
", someString='" + someString + '\'' +
", someFloat=" + someFloat +
", someDouble=" + someDouble +
", someInt=" + someInt +
", byteArray=" + Arrays.toString(byteArray) +
'}';
}
@Column
@PrimaryKey
long id;
@Column
String someString;
@Column
float someFloat;
@Column("some_double")
double someDouble;
@Column
int someInt;
@Column
byte[] byteArray;
}
@Test
public void test1_1() {
final StormConverter<Test1> converter = getConverter(Test1.class);
final Cursor cursor = StormCursorMock.newInstance(
Test1.class,
new StormCursorMock.Row(2L, "someString", 3.F, -.05D, -88, new byte[]{(byte) 1})
);
final Test1 initial = new Test1() {{
id = 2L; someString = "someString"; someFloat = 3.F; someDouble = -.05D; someInt = -88; byteArray = new byte[] {(byte) 1};
}};
cursor.moveToFirst();
final Test1 parsed = converter.fromCursor(cursor);
assertTrue(parsed != null);
assertTrue(parsed.equals(initial));
final ContentValues cvWith = converter.toContentValues(initial, true);
final ContentValues cvWithout = converter.toContentValues(initial, false);
assertTrue(cvWith.size() == 6);
assertTrue(cvWithout.size() == 5);
assertContentValuesNotNull(cvWith, "id", "someString", "someFloat", "some_double", "someInt", "byteArray");
assertContentValuesNotNull(cvWithout, "someString", "someFloat", "some_double", "someInt", "byteArray");
}
@Test
public void test1_2() {
final StormConverter<Test1> converter = getConverter(Test1.class);
final Cursor cursor = StormCursorMock.newInstance(
Test1.class,
new StormCursorMock.Row(11L, null, null, null, 15, null)
);
final Test1 initial = new Test1() {{
id = 11L; someInt = 15;
}};
cursor.moveToFirst();
final Test1 parsed = converter.fromCursor(cursor);
assertTrue(parsed != null);
assertTrue(parsed.equals(initial));
final ContentValues cvWith = converter.toContentValues(initial, true);
final ContentValues cvWithout = converter.toContentValues(initial, false);
assertTrue(cvWith.size() == 6);
assertTrue(cvWithout.size() == 5);
assertContentValuesNotNull(cvWith, "id", "someInt");
assertContentValuesNotNull(cvWithout, "someInt");
assertContentValuesNull(cvWith, "someString", "someFloat", "some_double", "byteArray");
assertContentValuesNull(cvWithout, "someString", "someFloat", "some_double", "byteArray");
}
static class DateLongSerializer implements StormSerializer<Date, Long> {
@Override
public Long serialize(Date date) {
return date == null ? -1L : date.getTime();
}
@Override
public Date deserialize(Type type, Long aLong) {
return aLong == null || aLong == -1L ? null : new Date(aLong);
}
}
@Table
static class Test2 {
@Override
public boolean equals(Object o) {
if (this == o) return true;
Test2 test2 = (Test2) o;
if (someBooleanInt != test2.someBooleanInt) return false;
if (someBooleanString != test2.someBooleanString) return false;
if (id != null ? !id.equals(test2.id) : test2.id != null) return false;
return !(someDate != null ? !someDate.equals(test2.someDate) : test2.someDate != null);
}
@Override
public String toString() {
return "Test2{" +
"id='" + id + '\'' +
", someBooleanInt=" + someBooleanInt +
", someBooleanString=" + someBooleanString +
", someDate=" + someDate +
'}';
}
@Column
@PrimaryKey
String id;
@Column
@Serialize(BooleanIntSerializer.class)
boolean someBooleanInt;
@Column
@Serialize(BooleanStringSerializer.class)
boolean someBooleanString;
@Column
@Serialize(DateLongSerializer.class)
Date someDate;
}
@Test
public void test2() {
final StormConverter<Test2> converter = getConverter(Test2.class);
final long time = System.currentTimeMillis();
final Cursor cursor = StormCursorMock.newInstance(
Test2.class,
new StormCursorMock.Row("123", 1, "false", time)
);
final Test2 initial = new Test2() {{
id = "123"; someBooleanInt = true; someBooleanString = false; someDate = new Date(time);
}};
cursor.moveToFirst();
final Test2 parsed = converter.fromCursor(cursor);
assertTrue(parsed != null);
assertTrue(parsed.equals(initial));
final ContentValues cvWith = converter.toContentValues(initial, true);
final ContentValues cvWithout = converter.toContentValues(initial, false);
assertContentValuesNotNull(cvWith, "id", "someBooleanInt", "someBooleanString", "someDate");
assertContentValuesNotNull(cvWithout, "someBooleanInt", "someBooleanString", "someDate");
}
@Table
static class Test3 {
@Override
public boolean equals(Object o) {
if (this == o) return true;
Test3 test3 = (Test3) o;
if (id != test3.id) return false;
return !(someString != null ? !someString.equals(test3.someString) : test3.someString != null);
}
@PrimaryKey(autoincrement = true)
@Column
long id;
@Column
String someString;
}
@Test
public void test3_1() {
final StormConverter<Test3> converter = getConverter(Test3.class);
final Cursor cursor = StormCursorMock.newInstance(
Test3.class,
new StormCursorMock.Row(0L, "0"),
new StormCursorMock.Row(1L, "1"),
new StormCursorMock.Row(2L, "2")
);
final List<Test3> initial = new ArrayList<>(3);
for (int i = 0; i < 3; i++) {
final long val = i;
initial.add(new Test3() {{id = val; someString = String.valueOf(val);}});
}
cursor.moveToFirst();
final List<Test3> parsed = converter.fromCursorList(cursor);
assertTrue(initial.equals(parsed));
}
private void assertContentValuesNull(ContentValues cv, String... nullKeys) {
Object object;
for (String key: nullKeys) {
object = cv.get(key);
if (object == null) {
assertTrue(true);
continue;
}
if (object instanceof Number) {
assertTrue(String.format("Asserting null key `%s` in `%s`", key, cv), ((Number) object).intValue() == 0);
continue;
}
assertTrue(String.format("Asserting null key `%s` in `%s`", key, cv), false);
}
}
private void assertContentValuesNotNull(ContentValues cv, String... notNullKeys) {
for (String key: notNullKeys) {
assertTrue(String.format("Asserting not null key `%s` in `%s`", key, cv), cv.get(key) != null);
}
}
}
| apache-2.0 |
tokee/lucene | contrib/swing/src/java/org/apache/lucene/swing/models/TableSearcher.java | 12319 | package org.apache.lucene.swing.models;
/**
* Copyright 2005 The Apache Software Foundation
*
* 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.
*/
import java.util.ArrayList;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableModel;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.WhitespaceAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.Fieldable;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.queryParser.MultiFieldQueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.swing.models.ListSearcher.CountingCollector;
import org.apache.lucene.util.Version;
/**
* This is a TableModel that encapsulates Lucene
* search logic within a TableModel implementation.
* It is implemented as a TableModel decorator,
* similar to the TableSorter demo from Sun that decorates
* a TableModel and provides sorting functionality. The benefit
* of this architecture is that you can decorate any TableModel
* implementation with this searching table model -- making it
* easy to add searching functionality to existing JTables -- or
* making new search capable table lucene.
*
* <p>This decorator works by holding a reference to a decorated ot inner
* TableModel. All data is stored within that table model, not this
* table model. Rather, this table model simply manages links to
* data in the inner table model according to the search. All methods on
* TableSearcher forward to the inner table model with subtle filtering
* or alteration according to the search criteria.
*
* <p>Using the table model:
*
* Pass the TableModel you want to decorate in at the constructor. When
* the TableModel initializes, it displays all search results. Call
* the search method with any valid Lucene search String and the data
* will be filtered by the search string. Users can always clear the search
* at any time by searching with an empty string. Additionally, you can
* add a button calling the clearSearch() method.
*
*/
public class TableSearcher extends AbstractTableModel {
/**
* The inner table model we are decorating
*/
protected TableModel tableModel;
/**
* This listener is used to register this class as a listener to
* the decorated table model for update events
*/
private TableModelListener tableModelListener;
/**
* these keeps reference to the decorated table model for data
* only rows that match the search criteria are linked
*/
private ArrayList<Integer> rowToModelIndex = new ArrayList<Integer>();
//Lucene stuff.
/**
* In memory lucene index
*/
private RAMDirectory directory;
/**
* Cached lucene analyzer
*/
private Analyzer analyzer;
/**
* Links between this table model and the decorated table model
* are maintained through links based on row number. This is a
* key constant to denote "row number" for indexing
*/
private static final String ROW_NUMBER = "ROW_NUMBER";
/**
* Cache the current search String. Also used internally to
* key whether there is an active search running or not. i.e. if
* searchString is null, there is no active search.
*/
private String searchString = null;
/**
* @param tableModel The table model to decorate
*/
public TableSearcher(TableModel tableModel) {
analyzer = new WhitespaceAnalyzer(Version.LUCENE_CURRENT);
tableModelListener = new TableModelHandler();
setTableModel(tableModel);
tableModel.addTableModelListener(tableModelListener);
clearSearchingState();
}
/**
*
* @return The inner table model this table model is decorating
*/
public TableModel getTableModel() {
return tableModel;
}
/**
* Set the table model used by this table model
* @param tableModel The new table model to decorate
*/
public void setTableModel(TableModel tableModel) {
//remove listeners if there...
if (this.tableModel != null) {
this.tableModel.removeTableModelListener(tableModelListener);
}
this.tableModel = tableModel;
if (this.tableModel != null) {
this.tableModel.addTableModelListener(tableModelListener);
}
//recalculate the links between this table model and
//the inner table model since the decorated model just changed
reindex();
// let all listeners know the table has changed
fireTableStructureChanged();
}
/**
* Reset the search results and links to the decorated (inner) table
* model from this table model.
*/
private void reindex() {
try {
// recreate the RAMDirectory
directory = new RAMDirectory();
IndexWriter writer = new IndexWriter(directory, new IndexWriterConfig(
Version.LUCENE_CURRENT, analyzer));
// iterate through all rows
for (int row=0; row < tableModel.getRowCount(); row++){
//for each row make a new document
Document document = new Document();
//add the row number of this row in the decorated table model
//this will allow us to retrieve the results later
//and map this table model's row to a row in the decorated
//table model
document.add(new Field(ROW_NUMBER, "" + row, Field.Store.YES, Field.Index.ANALYZED));
//iterate through all columns
//index the value keyed by the column name
//NOTE: there could be a problem with using column names with spaces
for (int column=0; column < tableModel.getColumnCount(); column++){
String columnName = tableModel.getColumnName(column);
String columnValue = String.valueOf(tableModel.getValueAt(row, column)).toLowerCase();
document.add(new Field(columnName, columnValue, Field.Store.YES, Field.Index.ANALYZED));
}
writer.addDocument(document);
}
writer.optimize();
writer.close();
} catch (Exception e){
e.printStackTrace();
}
}
/**
* @return The current lucene analyzer
*/
public Analyzer getAnalyzer() {
return analyzer;
}
/**
* @param analyzer The new analyzer to use
*/
public void setAnalyzer(Analyzer analyzer) {
this.analyzer = analyzer;
//reindex from the model with the new analyzer
reindex();
//rerun the search if there is an active search
if (isSearching()){
search(searchString);
}
}
/**
* Run a new search.
*
* @param searchString Any valid lucene search string
*/
public void search(String searchString){
//if search string is null or empty, clear the search == search all
if (searchString == null || searchString.equals("")){
clearSearchingState();
fireTableDataChanged();
return;
}
try {
//cache search String
this.searchString = searchString;
//make a new index searcher with the in memory (RAM) index.
IndexSearcher is = new IndexSearcher(directory, true);
//make an array of fields - one for each column
String[] fields = new String[tableModel.getColumnCount()];
for (int t=0; t<tableModel.getColumnCount(); t++){
fields[t]=tableModel.getColumnName(t);
}
//build a query based on the fields, searchString and cached analyzer
//NOTE: This is an area for improvement since the MultiFieldQueryParser
// has some weirdness.
MultiFieldQueryParser parser = new MultiFieldQueryParser(Version.LUCENE_CURRENT, fields, analyzer);
Query query = parser.parse(searchString);
//reset this table model with the new results
resetSearchResults(is, query);
} catch (Exception e){
e.printStackTrace();
}
//notify all listeners that the table has been changed
fireTableStructureChanged();
}
/**
*
* @param hits The new result set to set this table to.
*/
private void resetSearchResults(IndexSearcher searcher, Query query) {
try {
//clear our index mapping this table model rows to
//the decorated inner table model
rowToModelIndex.clear();
CountingCollector countingCollector = new CountingCollector();
searcher.search(query, countingCollector);
ScoreDoc[] hits = searcher.search(query, countingCollector.numHits).scoreDocs;
//iterate through the hits
//get the row number stored at the index
//that number is the row number of the decorated
//table model row that we are mapping to
for (int t=0; t<hits.length; t++){
Document document = searcher.doc(hits[t].doc);
Fieldable field = document.getField(ROW_NUMBER);
rowToModelIndex.add(Integer.valueOf(field.stringValue()));
}
} catch (Exception e){
e.printStackTrace();
}
}
private int getModelRow(int row){
return rowToModelIndex.get(row);
}
/**
* Clear the currently active search
* Resets the complete dataset of the decorated
* table model.
*/
private void clearSearchingState(){
searchString = null;
rowToModelIndex.clear();
for (int t=0; t<tableModel.getRowCount(); t++){
rowToModelIndex.add(t);
}
}
// TableModel interface methods
public int getRowCount() {
return (tableModel == null) ? 0 : rowToModelIndex.size();
}
public int getColumnCount() {
return (tableModel == null) ? 0 : tableModel.getColumnCount();
}
@Override
public String getColumnName(int column) {
return tableModel.getColumnName(column);
}
@Override
public Class<?> getColumnClass(int column) {
return tableModel.getColumnClass(column);
}
@Override
public boolean isCellEditable(int row, int column) {
return tableModel.isCellEditable(getModelRow(row), column);
}
public Object getValueAt(int row, int column) {
return tableModel.getValueAt(getModelRow(row), column);
}
@Override
public void setValueAt(Object aValue, int row, int column) {
tableModel.setValueAt(aValue, getModelRow(row), column);
}
private boolean isSearching() {
return searchString != null;
}
private class TableModelHandler implements TableModelListener {
public void tableChanged(TableModelEvent e) {
// If we're not searching, just pass the event along.
if (!isSearching()) {
clearSearchingState();
reindex();
fireTableChanged(e);
return;
}
// Something has happened to the data that may have invalidated the search.
reindex();
search(searchString);
fireTableDataChanged();
return;
}
}
}
| apache-2.0 |
aminmf/crawljax | examples/src/test/java/com/crawljax/plugins/testilizer/generated/claroline_INIT/GeneratedTestCase45.java | 24939 | package com.crawljax.plugins.testilizer.generated.claroline_INIT;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.NodeList;
import com.crawljax.forms.RandomInputValueGenerator;
import com.crawljax.util.DomUtils;
/*
* Generated @ Tue Apr 08 22:59:20 PDT 2014
*/
public class GeneratedTestCase45 {
private WebDriver driver;
private String url;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
private DOMElement element;
private DOMElement parentElement;
private ArrayList<DOMElement> childrenElements = new ArrayList<DOMElement>();
private String DOM = null;
boolean getCoverageReport = false;
@Before
public void setUp() throws Exception {
// Setting the JavaScript code coverage switch
getCoverageReport = com.crawljax.plugins.testilizer.Testilizer.getCoverageReport();
if (getCoverageReport)
driver = new FirefoxDriver(getProfile());
else
driver = new FirefoxDriver();
url = "http://localhost:8888/claroline-1.11.7/index.php?logout=true";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
public static FirefoxProfile getProfile() {
FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("network.proxy.http", "localhost");
profile.setPreference("network.proxy.http_port", 3128);
profile.setPreference("network.proxy.type", 1);
/* use proxy for everything, including localhost */
profile.setPreference("network.proxy.no_proxies_on", "");
return profile;
}
@After
public void tearDown() throws Exception {
if (getCoverageReport)
((JavascriptExecutor) driver).executeScript(" if (window.jscoverage_report) {return jscoverage_report('CodeCoverageReport');}");
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
/*
* Test Cases
*/
@Test
public void method45(){
driver.get(url);
//From state 0 to state 147
//Eventable{eventType=click, identification=cssSelector button[type="submit"], element=Element{node=[BUTTON: null], tag=BUTTON, text=Enter, attributes={tabindex=3, type=submit}}, source=StateVertexImpl{id=0, name=index}, target=StateVertexImpl{id=147, name=state147}}
mutateDOMTree(0);
checkState0_OriginalAssertions();
checkState0_ReusedAssertions();
checkState0_GeneratedAssertions();
checkState0_LearnedAssertions();
checkState0_AllAssertions();
checkState0_RandAssertions1();
checkState0_RandAssertions2();
checkState0_RandAssertions3();
checkState0_RandAssertions4();
checkState0_RandAssertions5();
driver.findElement(By.id("login")).clear();
driver.findElement(By.id("login")).sendKeys("nainy");
driver.findElement(By.id("password")).clear();
driver.findElement(By.id("password")).sendKeys("nainy");
driver.findElement(By.cssSelector("button[type=\"submit\"]")).click();
//From state 147 to state 2
//Eventable{eventType=click, identification=text Platform administration, element=Element{node=[A: null], tag=A, text=Platform administration, attributes={href=/claroline-1.11.7/claroline/admin/, target=_top}}, source=StateVertexImpl{id=147, name=state147}, target=StateVertexImpl{id=2, name=state2}}
mutateDOMTree(147);
checkState147_OriginalAssertions();
checkState147_ReusedAssertions();
checkState147_GeneratedAssertions();
checkState147_LearnedAssertions();
checkState147_AllAssertions();
checkState147_RandAssertions1();
checkState147_RandAssertions2();
checkState147_RandAssertions3();
checkState147_RandAssertions4();
checkState147_RandAssertions5();
driver.findElement(By.linkText("Platform administration")).click();
//From state 2 to state 43
//Eventable{eventType=click, identification=text Configuration, element=Element{node=[A: null], tag=A, text=Configuration, attributes={href=tool/config_list.php}}, source=StateVertexImpl{id=2, name=state2}, target=StateVertexImpl{id=43, name=state43}}
mutateDOMTree(2);
checkState2_OriginalAssertions();
checkState2_ReusedAssertions();
checkState2_GeneratedAssertions();
checkState2_LearnedAssertions();
checkState2_AllAssertions();
checkState2_RandAssertions1();
checkState2_RandAssertions2();
checkState2_RandAssertions3();
checkState2_RandAssertions4();
checkState2_RandAssertions5();
driver.findElement(By.linkText("Configuration")).click();
//From state 43 to state 53
//Eventable{eventType=click, identification=text Assignments, element=Element{node=[A: null], tag=A, text=Assignments, attributes={href=config_edit.php?config_code=CLWRK}}, source=StateVertexImpl{id=43, name=state43}, target=StateVertexImpl{id=53, name=state53}}
mutateDOMTree(43);
checkState43_OriginalAssertions();
checkState43_ReusedAssertions();
checkState43_GeneratedAssertions();
checkState43_LearnedAssertions();
checkState43_AllAssertions();
checkState43_RandAssertions1();
checkState43_RandAssertions2();
checkState43_RandAssertions3();
checkState43_RandAssertions4();
checkState43_RandAssertions5();
driver.findElement(By.linkText("Assignments")).click();
//From state 53 to state 56
//Eventable{eventType=click, identification=text Quota, element=Element{node=[A: null], tag=A, text=Quota, attributes={href=/claroline-1.11.7/claroline/admin/tool/config_edit.php?config_code=CLWRK§ion=quota}}, source=StateVertexImpl{id=53, name=state53}, target=StateVertexImpl{id=56, name=state56}}
mutateDOMTree(53);
checkState53_OriginalAssertions();
checkState53_ReusedAssertions();
checkState53_GeneratedAssertions();
checkState53_LearnedAssertions();
checkState53_AllAssertions();
checkState53_RandAssertions1();
checkState53_RandAssertions2();
checkState53_RandAssertions3();
checkState53_RandAssertions4();
checkState53_RandAssertions5();
driver.findElement(By.linkText("Quota")).click();
//From state 56 to state 57
//Eventable{eventType=click, identification=cssSelector input[type="submit"], element=Element{node=[INPUT: null], tag=INPUT, text=, attributes={type=submit, value=Ok}}, source=StateVertexImpl{id=56, name=state56}, target=StateVertexImpl{id=57, name=state57}}
mutateDOMTree(56);
checkState56_OriginalAssertions();
checkState56_ReusedAssertions();
checkState56_GeneratedAssertions();
checkState56_LearnedAssertions();
checkState56_AllAssertions();
checkState56_RandAssertions1();
checkState56_RandAssertions2();
checkState56_RandAssertions3();
checkState56_RandAssertions4();
checkState56_RandAssertions5();
driver.findElement(By.cssSelector("input[type=\"submit\"]")).click();
//From state 57 to state 60
//Eventable{eventType=click, identification=text Submissions, element=Element{node=[A: null], tag=A, text=Submissions, attributes={href=/claroline-1.11.7/claroline/admin/tool/config_edit.php?config_code=CLWRK§ion=submissions}}, source=StateVertexImpl{id=57, name=state57}, target=StateVertexImpl{id=60, name=state60}}
mutateDOMTree(57);
checkState57_OriginalAssertions();
checkState57_ReusedAssertions();
checkState57_GeneratedAssertions();
checkState57_LearnedAssertions();
checkState57_AllAssertions();
checkState57_RandAssertions1();
checkState57_RandAssertions2();
checkState57_RandAssertions3();
checkState57_RandAssertions4();
checkState57_RandAssertions5();
driver.findElement(By.linkText("Submissions")).click();
//From state 60 to state 61
//Eventable{eventType=click, identification=cssSelector input[type="submit"], element=Element{node=[INPUT: null], tag=INPUT, text=, attributes={type=submit, value=Ok}}, source=StateVertexImpl{id=60, name=state60}, target=StateVertexImpl{id=61, name=state61}}
mutateDOMTree(60);
checkState60_OriginalAssertions();
checkState60_ReusedAssertions();
checkState60_GeneratedAssertions();
checkState60_LearnedAssertions();
checkState60_AllAssertions();
checkState60_RandAssertions1();
checkState60_RandAssertions2();
checkState60_RandAssertions3();
checkState60_RandAssertions4();
checkState60_RandAssertions5();
driver.findElement(By.id("label_clwrk_endDateDelay")).clear();
driver.findElement(By.id("label_clwrk_endDateDelay")).sendKeys("365");
driver.findElement(By.cssSelector("input[type=\"submit\"]")).click();
//From state 61 to state 67
//Eventable{eventType=click, identification=text View all, element=Element{node=[A: null], tag=A, text=View all, attributes={href=/claroline-1.11.7/claroline/admin/tool/config_edit.php?config_code=CLWRK§ion=viewall}}, source=StateVertexImpl{id=61, name=state61}, target=StateVertexImpl{id=67, name=state67}}
mutateDOMTree(61);
checkState61_OriginalAssertions();
checkState61_ReusedAssertions();
checkState61_GeneratedAssertions();
checkState61_LearnedAssertions();
checkState61_AllAssertions();
checkState61_RandAssertions1();
checkState61_RandAssertions2();
checkState61_RandAssertions3();
checkState61_RandAssertions4();
checkState61_RandAssertions5();
driver.findElement(By.linkText("View all")).click();
//From state 67 to state 14
//Eventable{eventType=click, identification=text Logout, element=Element{node=[A: null], tag=A, text=Logout, attributes={href=/claroline-1.11.7/index.php?logout=true, target=_top}}, source=StateVertexImpl{id=67, name=state67}, target=StateVertexImpl{id=14, name=state14}}
mutateDOMTree(67);
checkState67_OriginalAssertions();
checkState67_ReusedAssertions();
checkState67_GeneratedAssertions();
checkState67_LearnedAssertions();
checkState67_AllAssertions();
checkState67_RandAssertions1();
checkState67_RandAssertions2();
checkState67_RandAssertions3();
checkState67_RandAssertions4();
checkState67_RandAssertions5();
driver.findElement(By.linkText("Logout")).click();
//Sink node at state 14
mutateDOMTree(14);
checkState14_OriginalAssertions();
checkState14_ReusedAssertions();
checkState14_GeneratedAssertions();
checkState14_LearnedAssertions();
checkState14_AllAssertions();
checkState14_RandAssertions1();
checkState14_RandAssertions2();
checkState14_RandAssertions3();
checkState14_RandAssertions4();
checkState14_RandAssertions5();
}
public void checkState0_OriginalAssertions(){
}
public void checkState0_ReusedAssertions(){
}
public void checkState0_GeneratedAssertions(){
}
public void checkState0_LearnedAssertions(){
}
public void checkState0_AllAssertions(){
}
public void checkState0_RandAssertions1(){
}
public void checkState0_RandAssertions2(){
}
public void checkState0_RandAssertions3(){
}
public void checkState0_RandAssertions4(){
}
public void checkState0_RandAssertions5(){
}
public void checkState147_OriginalAssertions(){
}
public void checkState147_ReusedAssertions(){
}
public void checkState147_GeneratedAssertions(){
}
public void checkState147_LearnedAssertions(){
}
public void checkState147_AllAssertions(){
}
public void checkState147_RandAssertions1(){
}
public void checkState147_RandAssertions2(){
}
public void checkState147_RandAssertions3(){
}
public void checkState147_RandAssertions4(){
}
public void checkState147_RandAssertions5(){
}
public void checkState2_OriginalAssertions(){
}
public void checkState2_ReusedAssertions(){
}
public void checkState2_GeneratedAssertions(){
}
public void checkState2_LearnedAssertions(){
}
public void checkState2_AllAssertions(){
}
public void checkState2_RandAssertions1(){
}
public void checkState2_RandAssertions2(){
}
public void checkState2_RandAssertions3(){
}
public void checkState2_RandAssertions4(){
}
public void checkState2_RandAssertions5(){
}
public void checkState43_OriginalAssertions(){
}
public void checkState43_ReusedAssertions(){
}
public void checkState43_GeneratedAssertions(){
}
public void checkState43_LearnedAssertions(){
}
public void checkState43_AllAssertions(){
}
public void checkState43_RandAssertions1(){
}
public void checkState43_RandAssertions2(){
}
public void checkState43_RandAssertions3(){
}
public void checkState43_RandAssertions4(){
}
public void checkState43_RandAssertions5(){
}
public void checkState53_OriginalAssertions(){
if(!(driver.findElement(By.name("editConfClass")).getText().matches("^[\\s\\S]*ets how the assignment property \"default works visibility\" acts\\. It will change the visibility of all the new submissions or it will change the visibility of all submissions already done in the assignment and the new one\\.[\\s\\S]*$"))){System.out.println(Thread.currentThread().getStackTrace()[1].getMethodName()); return;} // original assertion
if(!(driver.findElement(By.name("editConfClass")).getText().matches("^[\\s\\S]*For assignments list[\\s\\S]*$"))){System.out.println(Thread.currentThread().getStackTrace()[1].getMethodName()); return;} // original assertion
if(!(driver.findElement(By.name("editConfClass")).getText().matches("^[\\s\\S]*/<COURSEID>/work/[\\s\\S]*$"))){System.out.println(Thread.currentThread().getStackTrace()[1].getMethodName()); return;} // original assertion
}
public void checkState53_ReusedAssertions(){
}
public void checkState53_GeneratedAssertions(){
}
public void checkState53_LearnedAssertions(){
}
public void checkState53_AllAssertions(){
if(!(driver.findElement(By.name("editConfClass")).getText().matches("^[\\s\\S]*ets how the assignment property \"default works visibility\" acts\\. It will change the visibility of all the new submissions or it will change the visibility of all submissions already done in the assignment and the new one\\.[\\s\\S]*$"))){System.out.println(Thread.currentThread().getStackTrace()[1].getMethodName()); return;} // original assertion
if(!(driver.findElement(By.name("editConfClass")).getText().matches("^[\\s\\S]*For assignments list[\\s\\S]*$"))){System.out.println(Thread.currentThread().getStackTrace()[1].getMethodName()); return;} // original assertion
if(!(driver.findElement(By.name("editConfClass")).getText().matches("^[\\s\\S]*/<COURSEID>/work/[\\s\\S]*$"))){System.out.println(Thread.currentThread().getStackTrace()[1].getMethodName()); return;} // original assertion
}
public void checkState53_RandAssertions1(){
}
public void checkState53_RandAssertions2(){
}
public void checkState53_RandAssertions3(){
}
public void checkState53_RandAssertions4(){
}
public void checkState53_RandAssertions5(){
}
public void checkState56_OriginalAssertions(){
if(!(driver.findElement(By.name("editConfClass")).getText().matches("^[\\s\\S]*Maximum size of a document that a user can uploa[\\s\\S]*$"))){System.out.println(Thread.currentThread().getStackTrace()[1].getMethodName()); return;} // original assertion
}
public void checkState56_ReusedAssertions(){
}
public void checkState56_GeneratedAssertions(){
}
public void checkState56_LearnedAssertions(){
}
public void checkState56_AllAssertions(){
if(!(driver.findElement(By.name("editConfClass")).getText().matches("^[\\s\\S]*Maximum size of a document that a user can uploa[\\s\\S]*$"))){System.out.println(Thread.currentThread().getStackTrace()[1].getMethodName()); return;} // original assertion
}
public void checkState56_RandAssertions1(){
}
public void checkState56_RandAssertions2(){
}
public void checkState56_RandAssertions3(){
}
public void checkState56_RandAssertions4(){
}
public void checkState56_RandAssertions5(){
}
public void checkState57_OriginalAssertions(){
if(!(driver.findElement(By.cssSelector("div.claroDialogBox.boxSuccess")).getText().matches("^[\\s\\S]*Properties for Assignments, \\(CLWRK\\) are now effective on server\\.[\\s\\S]*$"))){System.out.println(Thread.currentThread().getStackTrace()[1].getMethodName()); return;} // original assertion
}
public void checkState57_ReusedAssertions(){
}
public void checkState57_GeneratedAssertions(){
}
public void checkState57_LearnedAssertions(){
}
public void checkState57_AllAssertions(){
if(!(driver.findElement(By.cssSelector("div.claroDialogBox.boxSuccess")).getText().matches("^[\\s\\S]*Properties for Assignments, \\(CLWRK\\) are now effective on server\\.[\\s\\S]*$"))){System.out.println(Thread.currentThread().getStackTrace()[1].getMethodName()); return;} // original assertion
}
public void checkState57_RandAssertions1(){
}
public void checkState57_RandAssertions2(){
}
public void checkState57_RandAssertions3(){
}
public void checkState57_RandAssertions4(){
}
public void checkState57_RandAssertions5(){
}
public void checkState60_OriginalAssertions(){
}
public void checkState60_ReusedAssertions(){
}
public void checkState60_GeneratedAssertions(){
}
public void checkState60_LearnedAssertions(){
}
public void checkState60_AllAssertions(){
}
public void checkState60_RandAssertions1(){
}
public void checkState60_RandAssertions2(){
}
public void checkState60_RandAssertions3(){
}
public void checkState60_RandAssertions4(){
}
public void checkState60_RandAssertions5(){
}
public void checkState61_OriginalAssertions(){
}
public void checkState61_ReusedAssertions(){
}
public void checkState61_GeneratedAssertions(){
}
public void checkState61_LearnedAssertions(){
}
public void checkState61_AllAssertions(){
}
public void checkState61_RandAssertions1(){
}
public void checkState61_RandAssertions2(){
}
public void checkState61_RandAssertions3(){
}
public void checkState61_RandAssertions4(){
}
public void checkState61_RandAssertions5(){
}
public void checkState67_OriginalAssertions(){
}
public void checkState67_ReusedAssertions(){
}
public void checkState67_GeneratedAssertions(){
}
public void checkState67_LearnedAssertions(){
}
public void checkState67_AllAssertions(){
}
public void checkState67_RandAssertions1(){
}
public void checkState67_RandAssertions2(){
}
public void checkState67_RandAssertions3(){
}
public void checkState67_RandAssertions4(){
}
public void checkState67_RandAssertions5(){
}
public void checkState14_OriginalAssertions(){
}
public void checkState14_ReusedAssertions(){
}
public void checkState14_GeneratedAssertions(){
}
public void checkState14_LearnedAssertions(){
}
public void checkState14_AllAssertions(){
}
public void checkState14_RandAssertions1(){
}
public void checkState14_RandAssertions2(){
}
public void checkState14_RandAssertions3(){
}
public void checkState14_RandAssertions4(){
}
public void checkState14_RandAssertions5(){
}
/*
* Auxiliary methods
*/
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private boolean isElementPatternTagPresent(DOMElement parent, DOMElement element, ArrayList<DOMElement> children) {
try {
String source = driver.getPageSource();
Document dom = DomUtils.asDocument(source);
NodeList nodeList = dom.getElementsByTagName(element.getTagName());
org.w3c.dom.Element sourceElement = null;
for (int i = 0; i < nodeList.getLength(); i++){
sourceElement = (org.w3c.dom.Element) nodeList.item(i);
// check parent node's tag and attributes
String parentTagName = sourceElement.getParentNode().getNodeName();
if (!parentTagName.equals(parent.getTagName()))
continue;
// check children nodes' tags
HashSet<String> childrenTagNameFromDOM = new HashSet<String>();
for (int j=0; j<sourceElement.getChildNodes().getLength();j++)
childrenTagNameFromDOM.add(sourceElement.getChildNodes().item(j).getNodeName());
HashSet<String> childrenTagNameToTest = new HashSet<String>();
for (int k=0; k<children.size();k++)
childrenTagNameToTest.add(children.get(k).getTagName());
if (!childrenTagNameToTest.equals(childrenTagNameFromDOM))
continue;
return true;
}
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
private boolean isElementPatternFullPresent(DOMElement parent, DOMElement element, ArrayList<DOMElement> children) {
try {
String source = driver.getPageSource();
Document dom = DomUtils.asDocument(source);
NodeList nodeList = dom.getElementsByTagName(element.getTagName());
org.w3c.dom.Element sourceElement = null;
for (int i = 0; i < nodeList.getLength(); i++){
// check node's attributes
sourceElement = (org.w3c.dom.Element) nodeList.item(i);
NamedNodeMap elementAttList = sourceElement.getAttributes();
HashSet<String> elemetAtts = new HashSet<String>();
for (int j = 0; j < elementAttList.getLength(); j++)
elemetAtts.add(elementAttList.item(j).getNodeName() + "=\"" + elementAttList.item(j).getNodeValue() + "\"");
if (!element.getAttributes().equals(elemetAtts))
continue;
// check parent node's tag and attributes
String parentTagName = sourceElement.getParentNode().getNodeName();
if (!parentTagName.equals(parent.getTagName()))
continue;
NamedNodeMap parentAttList = sourceElement.getParentNode().getAttributes();
HashSet<String> parentAtts = new HashSet<String>();
for (int j = 0; j < parentAttList.getLength(); j++)
parentAtts.add(parentAttList.item(j).getNodeName() + "=\"" + parentAttList.item(j).getNodeValue() + "\"");
if (!parent.getAttributes().equals(parentAtts))
continue;
// check children nodes' tags
HashSet<String> childrenTagNameFromDOM = new HashSet<String>();
for (int j=0; j<sourceElement.getChildNodes().getLength();j++)
childrenTagNameFromDOM.add(sourceElement.getChildNodes().item(j).getNodeName());
HashSet<String> childrenTagNameToTest = new HashSet<String>();
for (int k=0; k<children.size();k++)
childrenTagNameToTest.add(children.get(k).getTagName());
if (!childrenTagNameToTest.equals(childrenTagNameFromDOM))
continue;
// check children nodes' attributes
HashSet<HashSet<String>> childrenAttsFromDOM = new HashSet<HashSet<String>>();
for (int j=0; j<sourceElement.getChildNodes().getLength();j++){
NamedNodeMap childAttListFromDOM = sourceElement.getChildNodes().item(j).getAttributes();
HashSet<String> childAtts = new HashSet<String>();
if (childAttListFromDOM!=null)
for (int k = 0; k < childAttListFromDOM.getLength(); k++)
childAtts.add(childAttListFromDOM.item(k).getNodeName() + "=\"" + childAttListFromDOM.item(k).getNodeValue() + "\"");
childrenAttsFromDOM.add(childAtts);
}
HashSet<HashSet<String>> childrenAttsToTest = new HashSet<HashSet<String>>();
for (int k=0; k<children.size();k++)
childrenAttsToTest.add(children.get(k).getAttributes());
if (!childrenAttsToTest.equals(childrenAttsFromDOM))
continue;
return true;
}
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
private boolean isAlertPresent() {
try {
driver.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alertText;
} finally {
acceptNextAlert = true;
}
}
public class DOMElement {
private String tagName;
private String textContent;
private HashSet<String> attributes = new HashSet<String>();
public DOMElement(String tagName, String textContent, ArrayList<String> attributes){
this.tagName = tagName;
this.textContent = textContent;
if (attributes.get(0)!="")
for (int i=0; i<attributes.size();i++)
this.attributes.add(attributes.get(i));
}
public String getTagName() {
return tagName;
}
public String getTextContent() {
return textContent;
}
public HashSet<String> getAttributes() {
return attributes;
}
}
private void mutateDOMTree(int stateID){
// execute JavaScript code to mutate DOM
String code = com.crawljax.plugins.testilizer.Testilizer.mutateDOMTreeCode(stateID);
if (code!= null){
long RandomlySelectedDOMElementID = (long) ((JavascriptExecutor)driver).executeScript(code);
int MutationOperatorCode = com.crawljax.plugins.testilizer.Testilizer.MutationOperatorCode;
int StateToBeMutated = com.crawljax.plugins.testilizer.Testilizer.StateToBeMutated;
com.crawljax.plugins.testilizer.Testilizer.SelectedRandomElementInDOM[MutationOperatorCode][StateToBeMutated]
= (int) RandomlySelectedDOMElementID;
}
}
}
| apache-2.0 |
AntonGavr92/agavrikov | chapter_006/src/main/java/ru/job4j/FileCacheManager.java | 2120 | package ru.job4j;
import java.io.*;
import java.lang.ref.SoftReference;
import java.util.HashMap;
/**
* FileCacheManager class.
* @author agavrikov
* @since 28.08.2017
* @version 1
*/
public class FileCacheManager extends CacheManger<String, String> {
/**
* Cache map.
*/
private final HashMap<String, SoftReference<String>> CacheMap = new HashMap<String, SoftReference<String>>();
/**
* Method for adding key/value in map.
* @param key key
* @param value value
*/
@Override
public void add(String key, String value) {
SoftReference<String> valMap = new SoftReference<>(value);
this.CacheMap.put(key, valMap);
}
/**
* Method for get value by key from map.
* @param key key
* @return file content
*/
@Override
public String get(String key) {
String result = "";
if (this.CacheMap.containsKey(key)) {
result = this.CacheMap.get(key).get();
} else {
result = createCache(key);
}
return result;
}
/**
* Method for create cache file.
* @param key key in map
* @return file content
*/
private String createCache(String key) {
StringBuilder sb = new StringBuilder();
try (BufferedReader bf = new BufferedReader(new FileReader(new File(key)))) {
String line = bf.readLine();
while (line != null) {
sb.append(line);
line = bf.readLine();
}
} catch (IOException e) {
e.getStackTrace();
}
this.add(key, sb.toString());
return sb.toString();
}
/**
* Point of start program.
* @param args params
*/
public static void main(String[] args) {
FileCacheManager fcm = new FileCacheManager();
fcm.get(fcm.getClass().getClassLoader().getResource("logjmap.txt").getPath());
fcm.get(fcm.getClass().getClassLoader().getResource("logjstack.txt").getPath());
fcm.get(fcm.getClass().getClassLoader().getResource("logjmap.txt").getPath());
}
}
| apache-2.0 |
wapalxj/Java | javaworkplace/ZJXL_java/src/CC15_5_Works/Co2_PreColorClass_2.java | 1181 | package CC15_5_Works;
import java.awt.Color;
import java.util.HashMap;
import java.util.Map;
public class Co2_PreColorClass_2 {
public static void main(String[] args) {
Drawer2 d=new Drawer2();
d.drawLine();
d.drawLine("RED");
}
}
class Drawer2{
public Drawer2() {
super();
}
public void drawLine() {
System.out.println("»Ò»Ìõ"+MyColor2.black.toString()+"ÑÕÉ«µÄÏß");
}
public void drawLine(String color) {
System.out.println("»Ò»Ìõ"+ MyColor2.color(color).toString()+"ÑÕÉ«µÄÏß");
}
}
class MyColor2{
private static Map<String, Color> colors =new HashMap<String, Color>();
static{
colors.put("RED",Color.RED);
colors.put("BLACK",Color.BLACK);
colors.put("blue",Color.blue);
colors.put("cyan",Color.cyan);
colors.put("GRAY",Color.GRAY);
colors.put("GREEN",Color.GREEN);
colors.put("PINK",Color.pink);
colors.put("yellow",Color.yellow);
}
public final static Color black=colors.get("BLACK");
public final static Color red=colors.get("RED");
public final static Color YELLOW=colors.get("YELLOW");
public final static Color GRAY=colors.get("GRAY");
public static Color color(String color) {
return colors.get(color);
}
} | apache-2.0 |
xBlackCat/sjpu-dbah | src/java/org/xblackcat/sjpu/storage/converter/IToObjectConverter.java | 587 | package org.xblackcat.sjpu.storage.converter;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* Implementation of the interface should have a default constructor.
*
* @author xBlackCat
*/
public interface IToObjectConverter<T> {
/**
* Converts a current row in ResultSet object to correspond object.
*
* @param rs result of query.
* @return a new object from ResultSet row fields
* @throws java.sql.SQLException if any database related storage is affected.
*/
T convert(ResultSet rs) throws SQLException;
}
| apache-2.0 |
ymhadjou/JSFGestionContact | src/beans/ModifyAddressBean.java | 2200 | package beans;
import java.util.ArrayList;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import domain.Adresse;
import services.AdresseService;
@ManagedBean(name="modifyAddress")
public class ModifyAddressBean {
private String street;
private String city;
private String zip;
private String country;
private int id;
private AdresseService as = new AdresseService();
private ArrayList<Adresse> addresses = as.listAddresses();
public ArrayList<Adresse> getAddresses() {
return addresses;
}
public void setAddresses(ArrayList<Adresse> addresses) {
this.addresses = addresses;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getZip() {
return zip;
}
public void setZip(String zip) {
this.zip = zip;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String checkInfosAddresses(){
FacesContext context = FacesContext.getCurrentInstance();
AdresseService as = new AdresseService();
//Contrôle que les champs sont non-vides
if (isMissing(this.city)||isMissing(this.country) || isMissing(this.street) || isMissing(this.zip) || (id==0)) {
context.addMessage(null, new FacesMessage("Form fields can't be empty."));
// return("missing-login-pass");
}
if(context.getMessageList().size()>0)
return null;
else{
context.addMessage(null, new FacesMessage("Address has been successfully updated."));
Adresse a = new Adresse(this.id,this.city,this.zip,this.country, this.street);
as.modifyAddress(a);
return ("addresses");
}
}
//controle champs non vides
private boolean isMissing(String value) {
return((value == null) || (value.trim().isEmpty()));
}
}
| apache-2.0 |
suhothayan/siddhi-3 | modules/siddhi-api/src/main/java/org/wso2/siddhi/query/api/condition/ConditionValidator.java | 1297 | /*
* Copyright (c) 2005 - 2014, WSO2 Inc. (http://www.wso2.org) 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.
*/
package org.wso2.siddhi.query.api.condition;
import java.util.Map;
import java.util.Set;
public class ConditionValidator {
// public static void validate(Condition condition, List<QueryEventSource> queryEventSources,
// ConcurrentMap<String, AbstractDefinition> streamTableDefinitionMap, String streamReferenceId, boolean processInStreamDefinition) {
// condition.validate(queryEventSources,streamTableDefinitionMap, streamReferenceId, processInStreamDefinition);
// }
public static Map<String, Set<String>> getDependency(Condition condition) {
return condition.getDependency();
}
}
| apache-2.0 |
rtsgordon/chcp-toolmaker | framework-user/src/main/java/org/chcp/framework/user/user/UserServiceImpl.java | 2923 | /**
* Copyright(C) 2014-2015 CHCP
* Licensed to CHCP under Apache License Version 2.0
* Author: Gordon Wang
*/
package org.chcp.framework.user.user;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.chcp.framework.user.domain.dao.UserDao;
import org.chcp.framework.user.domain.entity.Role;
import org.chcp.framework.user.domain.entity.User;
import org.chcp.framework.user.domain.service.UserService;
//Service定义Transaction,DAO层是否还要定义
@Service
@Transactional(propagation=Propagation.REQUIRED, isolation=Isolation.DEFAULT, readOnly=false, rollbackFor=Exception.class)
public class UserServiceImpl implements UserService
{
private static Logger logger =LoggerFactory.getLogger(UserServiceImpl.class);
@Autowired
private UserDao userDao;
public User createUser(User user) throws Exception
{
/*
User admin = new User();
admin.setUserName("admin");
admin.setPassword("admin");
admin.setIntro("Administrator user.");
List<String> list = new ArrayList<String>();
list.add(Role.ROLE_ADMIN);
admin.setAddRoles(list);
userService.createUser(admin);
*/
//查询userId是否存在,存在的话抛出异常。
if(null != userDao.findById(user.getUserId()))
{
throw new Exception("UserId " + user.getUserId() + "already exist, can't create the same Id user.");
}
userDao.save(user);
return user;
}
public User updateUser(User user) throws Exception
{
User result = userDao.findByUserName(user.getUserName());
if(null == result)
{
throw new Exception("Can't find user:" + user.getUserName());
}
//对每一项进行比较,如果变化则赋值
if(!result.getFirstName().equals(user.getFirstName()))
{
result.setFirstName(user.getFirstName());
}
userDao.update(result);
return result;
}
public int deleteUser(List<String> userNames) throws Exception
{
return userDao.deleteByUserName(userNames);
}
public User getUserByName(String userName) throws Exception
{
User result = userDao.findByUserName(userName);
if(null == result)
{
throw new Exception("Can't find user, name is:" + userName);
}
return result;
}
@SuppressWarnings("unchecked")
public List<User> getUserList(int start, int limit, String sortBy, String direction, StringBuffer totalSize) throws Exception
{
//totalSize作为出参返回符合条件记录条数
totalSize.append(userDao.getCount());
return (List<User>) userDao.findList(start, limit, sortBy, direction);
}
} | apache-2.0 |
patrickfav/density-converter | src/main/java/at/favre/tools/dconvert/arg/EScaleMode.java | 763 | /*
* Copyright 2016 Patrick Favre-Bulle
*
* 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 at.favre.tools.dconvert.arg;
/**
* How the scale attribute should be interpreted
*/
public enum EScaleMode {
FACTOR, DP_WIDTH, DP_HEIGHT
}
| apache-2.0 |
MichaelSun/corelib | src/main/java/com/michael/corelib/coreutils/StringUtils.java | 13348 | /*
* Copyright (C) 2014 Markus Junginger, greenrobot (http://greenrobot.de)
*
* 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.michael.corelib.coreutils;
import com.michael.corelib.internet.NetworkLog;
import java.io.*;
import java.math.BigInteger;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.zip.GZIPInputStream;
public class StringUtils {
/** Splits a String based on a single character, which is usually faster than regex-based String.split(). */
public static String[] fastSplit(String string, char delimiter) {
List<String> list = new ArrayList<String>();
int size = string.length();
int start = 0;
for (int i = 0; i < size; i++) {
if (string.charAt(i) == delimiter) {
if (start < i) {
list.add(string.substring(start, i));
} else {
list.add("");
}
start = i + 1;
} else if (i == size - 1) {
list.add(string.substring(start, size));
}
}
String[] elements = new String[list.size()];
list.toArray(elements);
return elements;
}
/**
* URL-Encodes a given string using UTF-8 (some web pages have problems with UTF-8 and umlauts, consider
* {@link #encodeUrlIso(String)} also). No UnsupportedEncodingException to handle as it is dealt with in this
* method.
*/
public static String encodeUrl(String stringToEncode) {
try {
return URLEncoder.encode(stringToEncode, "UTF-8");
} catch (UnsupportedEncodingException e1) {
throw new RuntimeException(e1);
}
}
/**
* URL-encodes a given string using ISO-8859-1, which may work better with web pages and umlauts compared to UTF-8.
* No UnsupportedEncodingException to handle as it is dealt with in this method.
*/
public static String encodeUrlIso(String stringToEncode) {
try {
return URLEncoder.encode(stringToEncode, "ISO-8859-1");
} catch (UnsupportedEncodingException e1) {
throw new RuntimeException(e1);
}
}
/**
* URL-Decodes a given string using UTF-8. No UnsupportedEncodingException to handle as it is dealt with in this
* method.
*/
public static String decodeUrl(String stringToDecode) {
try {
return URLDecoder.decode(stringToDecode, "UTF-8");
} catch (UnsupportedEncodingException e1) {
throw new RuntimeException(e1);
}
}
/**
* URL-Decodes a given string using ISO-8859-1. No UnsupportedEncodingException to handle as it is dealt with in
* this method.
*/
public static String decodeUrlIso(String stringToDecode) {
try {
return URLDecoder.decode(stringToDecode, "ISO-8859-1");
} catch (UnsupportedEncodingException e1) {
throw new RuntimeException(e1);
}
}
/**
* Generates the MD5 digest for a given String based on UTF-8. The digest is padded with zeroes in the front if
* necessary.
*
* @return MD5 digest (32 characters).
*/
public static String generateMD5String(String stringToEncode) {
return generateDigestString(stringToEncode, "MD5", "UTF-8", 32);
}
/**
* Generates the SHA-1 digest for a given String based on UTF-8. The digest is padded with zeroes in the front if
* necessary. The SHA-1 algorithm is considers to produce less collisions than MD5.
*
* @return SHA-1 digest (40 characters).
*/
public static String generateSHA1String(String stringToEncode) {
return generateDigestString(stringToEncode, "SHA-1", "UTF-8", 40);
}
public static String
generateDigestString(String stringToEncode, String digestAlgo, String encoding, int lengthToPad) {
// Loosely inspired by http://workbench.cadenhead.org/news/1428/creating-md5-hashed-passwords-java
MessageDigest digester;
try {
digester = MessageDigest.getInstance(digestAlgo);
} catch (NoSuchAlgorithmException nsae) {
throw new RuntimeException(nsae);
}
try {
digester.update(stringToEncode.getBytes(encoding));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
return toHexString(digester.digest(), lengthToPad);
}
public static String toHexString(byte[] bytes, int lengthToPad) {
BigInteger hash = new BigInteger(1, bytes);
String digest = hash.toString(16);
while (digest.length() < lengthToPad) {
digest = "0" + digest;
}
return digest;
}
/**
* Simple HTML/XML entity resolving: Only supports unicode enitities and a very limited number text represented
* entities (apos, quot, gt, lt, and amp). There are many more: http://www.w3.org/TR/REC-html40/sgml/dtd.html
*
* @param entity The entity name without & and ; (null throws NPE)
* @return Resolved entity or the entity itself if it could not be resolved.
*/
public static String resolveEntity(String entity) {
if (entity.length() > 1 && entity.charAt(0) == '#') {
if (entity.charAt(1) == 'x') {
return String.valueOf((char) Integer.parseInt(entity.substring(2), 16));
} else {
return String.valueOf((char) Integer.parseInt(entity.substring(1)));
}
} else if (entity.equals("apos")) {
return "'";
} else if (entity.equals("quot")) {
return "\"";
} else if (entity.equals("gt")) {
return ">";
} else if (entity.equals("lt")) {
return "<";
} else if (entity.equals("amp")) {
return "&";
} else {
return entity;
}
}
/**
* Cuts the string at the end if it's longer than maxLength and appends "..." to it. The length of the resulting
* string including "..." is always less or equal to the given maxLength. It's valid to pass a null text; in this
* case null is returned.
*/
public static String ellipsize(String text, int maxLength) {
if (text != null && text.length() > maxLength) {
return text.substring(0, maxLength - 3) + "...";
}
return text;
}
public static String[] splitLines(String text, boolean skipEmptyLines) {
if (skipEmptyLines) {
return text.split("[\n\r]+");
} else {
return text.split("\\r?\\n");
}
}
public static List<String> findLinesContaining(String text, String searchText) {
String[] splitLinesSkipEmpty = splitLines(text, true);
List<String> matching = new ArrayList<String>();
for (String line : splitLinesSkipEmpty) {
if (line.contains(searchText)) {
matching.add(line);
}
}
return matching;
}
/**
* Returns a concatenated string consisting of the given lines seperated by a new line character \n. The last line
* does not have a \n at the end.
*/
public static String concatLines(List<String> lines) {
StringBuilder builder = new StringBuilder();
int countMinus1 = lines.size() - 1;
for (int i = 0; i < countMinus1; i++) {
builder.append(lines.get(i)).append('\n');
}
if (!lines.isEmpty()) {
builder.append(lines.get(countMinus1));
}
return builder.toString();
}
public static String joinIterableOnComma(Iterable<?> iterable) {
if (iterable != null) {
StringBuilder buf = new StringBuilder();
Iterator<?> it = iterable.iterator();
while (it.hasNext()) {
buf.append(it.next());
if (it.hasNext()) {
buf.append(',');
}
}
return buf.toString();
} else {
return "";
}
}
public static String joinArrayOnComma(int[] array) {
if (array != null) {
StringBuilder buf = new StringBuilder();
for (int i = 0; i < array.length; i++) {
if (i != 0) {
buf.append(',');
}
buf.append(array[i]);
}
return buf.toString();
} else {
return "";
}
}
public static String joinArrayOnComma(String[] array) {
if (array != null) {
StringBuilder buf = new StringBuilder();
for (int i = 0; i < array.length; i++) {
if (i != 0) {
buf.append(',');
}
buf.append(array[i]);
}
return buf.toString();
} else {
return "";
}
}
private final static String[] hexDigits = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};
public static String byteArrayToHexString(byte[] b) {
StringBuilder resultSb = new StringBuilder(512);
for (int i = 0; i < b.length; i++) {
resultSb.append(byteToHexString(b[i]));
}
return resultSb.toString();
}
public static String byteToHexString(byte b) {
int n = b;
if (n < 0)
n = 256 + n;
int d1 = n >>> 4 & 0xf;
int d2 = n & 0xf;
return hexDigits[d1] + hexDigits[d2];
}
public static String unGzipBytesToString(InputStream in) {
try {
PushbackInputStream pis = new PushbackInputStream(in, 2);
byte[] signature = new byte[2];
int readLength = pis.read(signature);
pis.unread(signature);
if (readLength == -1) {
return null;
}
int head = ((signature[0] & 0x00FF) | ((signature[1] << 8) & 0xFF00));
if (head != GZIPInputStream.GZIP_MAGIC) {
return new String(toByteArray(pis), "UTF-8").trim();
}
GZIPInputStream gzip = new GZIPInputStream(pis);
byte[] readBuf = new byte[8 * 1024];
ByteArrayOutputStream outputByte = new ByteArrayOutputStream();
int readCount = 0;
do {
readCount = gzip.read(readBuf);
if (readCount > 0) {
outputByte.write(readBuf, 0, readCount);
}
} while (readCount > 0);
if (outputByte.size() > 0) {
return new String(outputByte.toByteArray(), "UTF-8");
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 将input流转为byte数组,自动关闭
*
* @param input
* @return
*/
public static byte[] toByteArray(InputStream input) throws Exception {
if (input == null) {
return null;
}
ByteArrayOutputStream output = null;
byte[] result = null;
try {
output = new ByteArrayOutputStream();
byte[] buffer = new byte[1024 * 100];
int n = 0;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
}
result = output.toByteArray();
} finally {
closeQuietly(input);
closeQuietly(output);
}
return result;
}
/**
* 关闭InputStream
*/
private static void closeQuietly(InputStream is) {
try {
if (is != null) {
is.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 关闭InputStream
*/
private static void closeQuietly(OutputStream os) {
try {
if (os != null) {
os.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void dumpLongStringToLogcat(String longString) {
int step = 2048;
int index = 0;
do {
if (index >= longString.length()) {
break;
} else {
if ((index + step) < longString.length()) {
NetworkLog.LOGD(longString.substring(index, index + step));
} else {
NetworkLog.LOGD(longString.substring(index, longString.length()));
}
}
index = index + step;
} while (index < longString.length());
}
}
| apache-2.0 |
gosu-lang/old-gosu-repo | gosu-core-api/src/main/java/gw/lang/parser/ExternalSymbolMapForMap.java | 1227 | /*
* Copyright 2013 Guidewire Software, Inc.
*/
package gw.lang.parser;
import java.util.HashMap;
public class ExternalSymbolMapForMap extends ExternalSymbolMapBase {
private HashMap<String, ISymbol> _externalSymbols;
public ExternalSymbolMapForMap( HashMap<String, ISymbol> externalSymbols) {
this(externalSymbols, false);
}
public ExternalSymbolMapForMap( HashMap<String, ISymbol> externalSymbols, boolean assumeSymbolsRequireExternalSymbolMapArgument) {
super(assumeSymbolsRequireExternalSymbolMapArgument);
_externalSymbols = externalSymbols;
}
public ISymbol getSymbol(String name) {
ISymbol symbol = _externalSymbols.get( name );
if( symbol == null ) {
symbol = getAltSymbol( name );
}
return symbol;
}
private ISymbol getAltSymbol( String name ) {
String altName = handleCrappyPcfCapitalization( name );
if( altName != null ) {
return _externalSymbols.get( altName );
}
return null;
}
public boolean isExternalSymbol(String name) {
if( !_externalSymbols.containsKey( name ) ) {
return getAltSymbol( name ) != null;
}
return true;
}
public HashMap<String, ISymbol> getMap() {
return _externalSymbols;
}
}
| apache-2.0 |
ScriptonBasestar-Lib/sb-tool-jvm | collection/src/test/java/org/scriptonbasestar/tool/collection/joiner/JoinerTest.java | 644 | package org.scriptonbasestar.tool.collection.joiner;
import org.junit.Assert;
import org.junit.Test;
import org.scriptonbasestar.tool.collection.builder.ListBuilder;
import java.util.List;
/**
* @author archmagece
* @since 2017-09-06
*/
public class JoinerTest {
@Test
public void test_Joiner_run() {
//given
List<String> list = ListBuilder.create("33", "fefe", "fww", "jiojio", "sdfjjksfkjfld").build();
//when
String result = Joiner.<String>on(",").append(list).join();
//then
System.out.println(result);
String expectedString = "33,fefe,fww,jiojio,sdfjjksfkjfld";
Assert.assertEquals(result, expectedString);
}
}
| apache-2.0 |
wapache/wason | api/src/main/java/javax/json/spi/package-info.java | 2707 | /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 2012-2013 Oracle and/or its affiliates. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can
* obtain a copy of the License at
* https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html
* or packager/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at packager/legal/LICENSE.txt.
*
* GPL Classpath Exception:
* Oracle designates this particular file as subject to the "Classpath"
* exception as provided by Oracle in the GPL Version 2 section of the License
* file that accompanied this code.
*
* Modifications:
* If applicable, add the following below the License Header, with the fields
* enclosed by brackets [] replaced by your own identifying information:
* "Portions Copyright [year] [name of copyright owner]"
*
* Contributor(s):
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
/**
* Service Provider Interface (SPI) to plug in implementations for
* JSON processing objects.
*
* <p> {@link javax.json.spi.JsonProvider JsonProvider} is an abstract class
* that provides a service for creating JSON processing instances.
* A <i>service provider</i> for {@code JsonProvider} provides an
* specific implementation by subclassing and implementing the methods in
* {@code JsonProvider}. This enables using custom, efficient JSON processing
* implementations (for e.g. parser and generator) other than the default ones.
*
* <p>The API locates and loads providers using {@link java.util.ServiceLoader}.
*
* @since JSON Processing 1.0
* @author Jitendra Kotamraju
*/
package javax.json.spi;
| apache-2.0 |
yext/closure-templates | java/src/com/google/template/soy/sharedpasses/render/Environment.java | 6182 | /*
* Copyright 2014 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.template.soy.sharedpasses.render;
import com.google.template.soy.data.SoyRecord;
import com.google.template.soy.data.SoyValue;
import com.google.template.soy.data.SoyValueProvider;
import com.google.template.soy.data.restricted.NullData;
import com.google.template.soy.data.restricted.UndefinedData;
import com.google.template.soy.exprtree.VarDefn;
import com.google.template.soy.exprtree.VarDefn.Kind;
import com.google.template.soy.soytree.TemplateNode;
import com.google.template.soy.soytree.defn.TemplateParam;
import java.util.IdentityHashMap;
import java.util.Map;
/**
* The local variable table.
*
* <p>All declared {@code @param}s and {@code {let ...}} statements define variables that are stored
* in a table. The mapping between local variable and
*
* <p>New empty environments can be created with the {@link #create} factory method and seeded with
* the {@link #bind} method.
*
* <p>For the most part this class is only used by this package, but it is publicly exposed to aid
* in testing usecases.
*/
public abstract class Environment {
Environment() {} // package private constructor to limit subclasses to this package.
/**
* The main way to create an environment.
*
* <p>Allocates the local variable table for the template and prepopulates it with data from the
* given SoyRecords.
*/
static Environment create(TemplateNode template, SoyRecord data, SoyRecord ijData) {
return new Impl(template, data, ijData);
}
/**
* For Prerendering we create an {@link Environment} for the given template where all entries are
* initialized to UndefinedData.
*/
public static Environment prerenderingEnvironment() {
return new EmptyImpl();
}
/** Associates a value with the given variable. */
abstract void bind(VarDefn var, SoyValueProvider value);
/**
* Binds the data about the current loop position to support the isLast and index builtin
* functions.
*/
abstract void bindLoopPosition(
VarDefn loopVar, SoyValueProvider value, int index, boolean isLast);
/** Returns the resolved SoyValue for the given VarDefn. Guaranteed to not return null. */
abstract SoyValue getVar(VarDefn var);
/** Returns the resolved SoyValue for the given VarDefn. Guaranteed to not return null. */
abstract SoyValueProvider getVarProvider(VarDefn var);
/** Returns {@code true} if we are the last iteration for the given loop variable. */
abstract boolean isLast(VarDefn loopVar);
/** Returns the current iterator inject for the given loop variable. */
abstract int getIndex(VarDefn loopVar);
private static final class Impl extends Environment {
private static final class LoopPosition {
boolean isLast;
int index;
SoyValueProvider item;
}
final Map<VarDefn, Object> localVariables = new IdentityHashMap<>();
final SoyRecord data;
Impl(TemplateNode template, SoyRecord data, SoyRecord ijData) {
this.data = data;
for (TemplateParam param : template.getAllParams()) {
SoyValueProvider provider =
(param.isInjected() ? ijData : data).getFieldProvider(param.name());
if (provider == null) {
provider =
param.isRequired() || param.hasDefault() ? UndefinedData.INSTANCE : NullData.INSTANCE;
}
bind(param, provider);
}
}
@Override
void bind(VarDefn var, SoyValueProvider value) {
localVariables.put(var, value);
}
@Override
void bindLoopPosition(VarDefn loopVar, SoyValueProvider value, int index, boolean isLast) {
LoopPosition position =
(LoopPosition) localVariables.computeIfAbsent(loopVar, ignored -> new LoopPosition());
position.item = value;
position.index = index;
position.isLast = isLast;
}
@Override
SoyValueProvider getVarProvider(VarDefn var) {
if (var.kind() == Kind.UNDECLARED) {
// Special case for legacy templates with undeclared params. Undeclared params aren't
// assigned indices in the local variable table.
SoyValueProvider provider = data.getFieldProvider(var.name());
return provider != null ? provider : UndefinedData.INSTANCE;
}
Object o = localVariables.get(var);
if (o instanceof LoopPosition) {
return ((LoopPosition) o).item;
}
return (SoyValueProvider) o;
}
@Override
SoyValue getVar(VarDefn var) {
return getVarProvider(var).resolve();
}
@Override
boolean isLast(VarDefn var) {
return ((LoopPosition) localVariables.get(var)).isLast;
}
@Override
int getIndex(VarDefn var) {
return ((LoopPosition) localVariables.get(var)).index;
}
}
/** An environment that is empty and returns {@link UndefinedData} for everything. */
private static final class EmptyImpl extends Environment {
@Override
void bind(VarDefn var, SoyValueProvider value) {
throw new UnsupportedOperationException();
}
@Override
void bindLoopPosition(VarDefn loopVar, SoyValueProvider value, int index, boolean isLast) {
throw new UnsupportedOperationException();
}
@Override
SoyValueProvider getVarProvider(VarDefn var) {
return UndefinedData.INSTANCE;
}
@Override
SoyValue getVar(VarDefn var) {
return UndefinedData.INSTANCE;
}
@Override
boolean isLast(VarDefn loopVar) {
return UndefinedData.INSTANCE.booleanValue();
}
@Override
int getIndex(VarDefn loopVar) {
return UndefinedData.INSTANCE.integerValue();
}
}
}
| apache-2.0 |
wenzhucjy/tomcat_source | tomcat-8.0.9-sourcecode/java/org/apache/tomcat/util/bcel/classfile/ConstantString.java | 2115 | /*
* 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 org.apache.tomcat.util.bcel.classfile;
import java.io.DataInput;
import java.io.IOException;
import org.apache.tomcat.util.bcel.Constants;
/**
* This class is derived from the abstract
* <A HREF="org.apache.tomcat.util.bcel.classfile.Constant.html">Constant</A> class
* and represents a reference to a String object.
*
* @author <A HREF="mailto:m.dahm@gmx.de">M. Dahm</A>
* @see Constant
*/
public final class ConstantString extends Constant {
private static final long serialVersionUID = 2809338612858801341L;
private int string_index; // Identical to ConstantClass except for this name
/**
* Initialize instance from file data.
*
* @param file Input stream
* @throws IOException
*/
ConstantString(DataInput file) throws IOException {
this(file.readUnsignedShort());
}
/**
* @param string_index Index of Constant_Utf8 in constant pool
*/
public ConstantString(int string_index) {
super(Constants.CONSTANT_String);
this.string_index = string_index;
}
/**
* @return Index in constant pool of the string (ConstantUtf8).
*/
public final int getStringIndex() {
return string_index;
}
}
| apache-2.0 |
consulo/consulo | modules/base/compiler-impl/src/main/java/consulo/compiler/make/DependencyCache.java | 2159 | /*
* Copyright 2013-2016 consulo.io
*
* 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 consulo.compiler.make;
import com.intellij.compiler.impl.ExitException;
import com.intellij.compiler.make.CacheCorruptedException;
import com.intellij.openapi.compiler.ex.CompileContextEx;
import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.Trinity;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.Function;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.io.File;
import java.util.Set;
/**
* @author VISTALL
* @since 23:35/25.05.13
*/
public interface DependencyCache {
ExtensionPointName<DependencyCacheEP> EP_NAME = ExtensionPointName.create("com.intellij.compiler.dependencyCache");
void findDependentFiles(CompileContextEx context,
Ref<CacheCorruptedException> exceptionRef,
Function<Pair<int[], Set<VirtualFile>>, Pair<int[], Set<VirtualFile>>> filter,
Set<VirtualFile> dependentFiles, Set<VirtualFile> compiledWithErrors) throws CacheCorruptedException,
ExitException;
boolean hasUnprocessedTraverseRoots();
void resetState();
void clearTraverseRoots();
void update() throws CacheCorruptedException;
@Nullable
String relativePathToQName(@Nonnull String path, char separator);
void syncOutDir(Trinity<File, String, Boolean> trinity) throws CacheCorruptedException;
}
| apache-2.0 |
ultradns/java_rest_api_client | src/main/java/biz/neustar/ultra/rest/dto/SecurityQuestion.java | 2160 | package biz.neustar.ultra.rest.dto;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
/**
* Security Question.
*/
@JsonInclude(Include.NON_NULL)
public class SecurityQuestion {
/**
* The id for the security question.
*/
private String id;
/**
* The text of the security question.
*/
private String question;
public SecurityQuestion() {
super();
}
/**
* Parameterized constructor.
*/
public SecurityQuestion(String id, String question) {
super();
this.id = id;
this.question = question;
}
/**
* return question id.
*
* @return BigDecimal
*/
public String getId() {
return this.id;
}
/**
* set question id.
*
* @param id - BigDecimal
*/
public void setId(String id) {
this.id = id;
}
/**
* return question description.
*
* @return String
*/
public String getQuestion() {
return this.question;
}
/**
* Set question description.
*
* @param question - String
*/
public void setQuestion(String question) {
this.question = question;
}
/*
* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public final String toString() {
return MoreObjects.toStringHelper(this).add("id", getId()).add("question", getQuestion()).toString();
}
/*
* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return Objects.hashCode(id, question);
}
/*
* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object object) {
if (!(object instanceof SecurityQuestion)) {
return false;
}
SecurityQuestion that = (SecurityQuestion) object;
return Objects.equal(this.id, that.id) && Objects.equal(this.question, that.question);
}
}
| apache-2.0 |
wellwu50/coolweather | app/src/main/java/org/well/coolwearher/gson/Basic.java | 388 | package org.well.coolwearher.gson;
import com.google.gson.annotations.SerializedName;
/**
* Created by zz on 2017/7/11.
*/
public class Basic {
@SerializedName("city")
public String cityName;
@SerializedName("id")
public String weatherId;
public Update update;
public class Update {
@SerializedName("loc")
public String updateTime;
}
}
| apache-2.0 |
marcinkwiatkowski/buck | test/com/facebook/buck/python/PythonTestBuilder.java | 5060 | /*
* Copyright 2015-present Facebook, 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.facebook.buck.python;
import com.facebook.buck.cli.FakeBuckConfig;
import com.facebook.buck.cxx.CxxPlatform;
import com.facebook.buck.cxx.CxxPlatformUtils;
import com.facebook.buck.io.ExecutableFinder;
import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.model.Flavor;
import com.facebook.buck.model.FlavorDomain;
import com.facebook.buck.rules.AbstractNodeBuilder;
import com.facebook.buck.rules.coercer.PatternMatchedCollection;
import com.facebook.buck.rules.coercer.SourceList;
import com.facebook.buck.rules.coercer.VersionMatchedCollection;
import com.facebook.buck.versions.Version;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSortedSet;
import java.util.Optional;
public class PythonTestBuilder
extends AbstractNodeBuilder<
PythonTestDescriptionArg.Builder, PythonTestDescriptionArg, PythonTestDescription,
PythonTest> {
protected PythonTestBuilder(
BuildTarget target,
PythonBuckConfig pythonBuckConfig,
FlavorDomain<PythonPlatform> pythonPlatforms,
CxxPlatform defaultCxxPlatform,
FlavorDomain<CxxPlatform> cxxPlatforms) {
super(
new PythonTestDescription(
new PythonBinaryDescription(
pythonBuckConfig,
pythonPlatforms,
CxxPlatformUtils.DEFAULT_CONFIG,
defaultCxxPlatform,
cxxPlatforms),
pythonBuckConfig,
pythonPlatforms,
CxxPlatformUtils.DEFAULT_CONFIG,
defaultCxxPlatform,
Optional.empty(),
cxxPlatforms),
target);
}
public static PythonTestBuilder create(
BuildTarget target, FlavorDomain<PythonPlatform> pythonPlatforms) {
PythonBuckConfig pythonBuckConfig =
new PythonBuckConfig(FakeBuckConfig.builder().build(), new ExecutableFinder());
return new PythonTestBuilder(
target,
pythonBuckConfig,
pythonPlatforms,
CxxPlatformUtils.DEFAULT_PLATFORM,
CxxPlatformUtils.DEFAULT_PLATFORMS);
}
public static PythonTestBuilder create(BuildTarget target) {
return create(target, PythonTestUtils.PYTHON_PLATFORMS);
}
public PythonTestBuilder setSrcs(SourceList srcs) {
getArgForPopulating().setSrcs(srcs);
return this;
}
public PythonTestBuilder setPlatformSrcs(PatternMatchedCollection<SourceList> platformSrcs) {
getArgForPopulating().setPlatformSrcs(platformSrcs);
return this;
}
public PythonTestBuilder setPlatformResources(
PatternMatchedCollection<SourceList> platformResources) {
getArgForPopulating().setPlatformResources(platformResources);
return this;
}
public PythonTestBuilder setBaseModule(String baseModule) {
getArgForPopulating().setBaseModule(Optional.of(baseModule));
return this;
}
public PythonTestBuilder setBuildArgs(ImmutableList<String> buildArgs) {
getArgForPopulating().setBuildArgs(buildArgs);
return this;
}
public PythonTestBuilder setDeps(ImmutableSortedSet<BuildTarget> deps) {
getArgForPopulating().setDeps(deps);
return this;
}
public PythonTestBuilder setPlatformDeps(
PatternMatchedCollection<ImmutableSortedSet<BuildTarget>> deps) {
getArgForPopulating().setPlatformDeps(deps);
return this;
}
public PythonTestBuilder setPlatform(String platform) {
getArgForPopulating().setPlatform(Optional.of(platform));
return this;
}
public PythonTestBuilder setCxxPlatform(Flavor platform) {
getArgForPopulating().setCxxPlatform(Optional.of(platform));
return this;
}
public PythonTestBuilder setPackageStyle(PythonBuckConfig.PackageStyle packageStyle) {
getArgForPopulating().setPackageStyle(Optional.of(packageStyle));
return this;
}
public PythonTestBuilder setVersionedSrcs(VersionMatchedCollection<SourceList> versionedSrcs) {
getArgForPopulating().setVersionedSrcs(Optional.of(versionedSrcs));
return this;
}
public PythonTestBuilder setVersionedResources(
VersionMatchedCollection<SourceList> versionedResources) {
getArgForPopulating().setVersionedResources(Optional.of(versionedResources));
return this;
}
@Override
public PythonTestBuilder setSelectedVersions(
ImmutableMap<BuildTarget, Version> selectedVersions) {
super.setSelectedVersions(selectedVersions);
return this;
}
}
| apache-2.0 |
jaamsim/jaamsim | src/main/java/com/jaamsim/input/ExpResult.java | 5378 | /*
* JaamSim Discrete Event Simulation
* Copyright (C) 2014 Ausenco Engineering Canada Inc.
* Copyright (C) 2016-2021 JaamSim Software 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.jaamsim.input;
import com.jaamsim.basicsim.Entity;
import com.jaamsim.basicsim.JaamSimModel;
import com.jaamsim.units.Unit;
public class ExpResult {
public interface Iterator {
public boolean hasNext();
public ExpResult nextKey() throws ExpError;
}
public interface Collection {
public ExpResult index(ExpResult index) throws ExpError;
// Collections have a copy-on-write feature, where the old reference may be invalidated
// after assigning, always use the value returned as the new collection
public Collection assign(ExpResult key, ExpResult value) throws ExpError;
public Iterator getIter();
public int getSize();
public String getOutputString(JaamSimModel simModel);
public Collection getCopy();
}
public final ExpResType type;
public final double value;
public final Class<? extends Unit> unitType;
public final String stringVal;
public final Entity entVal;
public final Collection colVal;
public final ExpParser.LambdaClosure lcVal;
public static ExpResult makeNumResult(double val, Class<? extends Unit> ut) {
return new ExpResult(ExpResType.NUMBER, val, ut, null, null, null, null);
}
public static ExpResult makeStringResult(String str) {
return new ExpResult(ExpResType.STRING, 0, null, str, null, null, null);
}
public static ExpResult makeEntityResult(Entity ent) {
return new ExpResult(ExpResType.ENTITY, 0, null, null, ent, null, null);
}
public static ExpResult makeCollectionResult(Collection col) {
return new ExpResult(ExpResType.COLLECTION, 0, null, null, null, col, null);
}
public static ExpResult makeLambdaResult(ExpParser.LambdaClosure lc) {
return new ExpResult(ExpResType.LAMBDA, 0, null, null, null, null, lc);
}
private ExpResult(ExpResType type, double val, Class<? extends Unit> ut, String str, Entity ent, Collection col, ExpParser.LambdaClosure lc) {
this.type = type;
value = val;
unitType = ut;
stringVal = str;
entVal = ent;
colVal = col;
lcVal = lc;
}
public <T> T getValue(double simTime, Class<T> klass) {
// Make a best effort to return the type
if (klass.isAssignableFrom(ExpResult.class))
return klass.cast(this);
if (type == ExpResType.STRING && klass.isAssignableFrom(String.class)) {
return klass.cast(stringVal);
}
if (type == ExpResType.ENTITY && klass.isAssignableFrom(Entity.class)) {
return klass.cast(entVal);
}
if (klass.equals(double.class) || klass.equals(Double.class)) {
if (type == ExpResType.NUMBER)
return klass.cast(value);
}
return null;
}
public ExpResult getCopy() {
if (type == ExpResType.COLLECTION) {
return makeCollectionResult(colVal.getCopy());
}
return this;
}
public String getOutputString(JaamSimModel simModel) {
switch (type) {
case NUMBER:
double factor = 1.0d;
String unitString = Unit.getSIUnit(unitType);
if (simModel != null) {
factor = simModel.getDisplayedUnitFactor(unitType);
unitString = simModel.getDisplayedUnit(unitType);
}
if (unitString.isEmpty())
return String.format("%s", value);
return String.format("%s[%s]", value/factor, unitString);
case STRING:
return String.format("\"%s\"", stringVal);
case ENTITY:
if (entVal == null)
return "null";
return String.format("[%s]", entVal.getName());
case COLLECTION:
return colVal.getOutputString(simModel);
case LAMBDA:
return "function|" + lcVal.getNumParams()+"|";
default:
assert(false);
return "???";
}
}
// Like 'getOutputString' but does not quote string types, making it more useful in string formaters
public String getFormatString() {
switch (type) {
case NUMBER:
String unitString = Unit.getSIUnit(unitType);
if (unitString.isEmpty())
return String.format("%s", value);
return String.format("%s[%s]", value, unitString);
case STRING:
return stringVal;
case ENTITY:
if (entVal == null)
return "null";
return String.format("[%s]", entVal.getName());
case COLLECTION:
return colVal.getOutputString(null);
case LAMBDA:
return "function|" + lcVal.getNumParams()+"|";
default:
assert(false);
return "???";
}
}
@Override
public String toString() {
return getOutputString(null);
}
@Override
public boolean equals(Object o) {
if (ExpResult.class != o.getClass()) {
return false;
}
ExpResult other = (ExpResult)o;
switch (type) {
case NUMBER:
return this.value == other.value && this.unitType == other.unitType;
case STRING:
return this.stringVal.equals(other.stringVal);
case ENTITY:
return this.entVal == other.entVal;
case COLLECTION:
return this.colVal == other.colVal;
default:
return false;
}
}
}
| apache-2.0 |
KidEinstein/giraph | goffish-giraph/src/main/java/in/dream_lab/goffish/giraph/factories/DefaultSubgraphVertexValueFactory.java | 994 | package in.dream_lab.goffish.giraph.factories;
import in.dream_lab.goffish.giraph.conf.GiraphSubgraphConstants;
import org.apache.giraph.conf.GiraphConfigurationSettable;
import org.apache.giraph.conf.ImmutableClassesGiraphConfiguration;
import org.apache.giraph.utils.WritableUtils;
import org.apache.hadoop.io.Writable;
/**
* Created by anirudh on 23/10/16.
*/
public class DefaultSubgraphVertexValueFactory<SVV extends Writable> implements SubgraphVertexValueFactory<SVV>, GiraphConfigurationSettable {
private ImmutableClassesGiraphConfiguration conf;
private Class<SVV> subgraphVertexValueClass;
@Override
public SVV newInstance() {
return WritableUtils.createWritable(subgraphVertexValueClass, conf);
}
@Override
public void setConf(ImmutableClassesGiraphConfiguration configuration) {
this.conf = configuration;
this.subgraphVertexValueClass = (Class<SVV>) GiraphSubgraphConstants.SUBGRAPH_VERTEX_VALUE_CLASS.get(conf);
}
}
| apache-2.0 |
baart92/jgrades | jg-backend/implementation/base/jg-lic/interface/src/main/java/org/jgrades/lic/api/model/package-info.java | 298 | @XmlJavaTypeAdapters({@XmlJavaTypeAdapter(type = DateTime.class, value = LicenceDateTimeAdapter.class)}) package org.jgrades.lic.api.model;
import org.joda.time.DateTime;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapters;
| apache-2.0 |
oriontribunal/CoffeeMud | com/planet_ink/coffee_mud/Abilities/Druid/Chant_MetalMold.java | 5151 | package com.planet_ink.coffee_mud.Abilities.Druid;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.*;
/*
Copyright 2003-2016 Bo Zimmerman
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 Chant_MetalMold extends Chant
{
@Override public String ID() { return "Chant_MetalMold"; }
private final static String localizedName = CMLib.lang().L("Metal Mold");
@Override public String name() { return localizedName; }
@Override protected int canTargetCode(){return CAN_MOBS|CAN_ITEMS;}
@Override public int classificationCode(){return Ability.ACODE_CHANT|Ability.DOMAIN_PLANTGROWTH;}
@Override public int abstractQuality(){return Ability.QUALITY_MALICIOUS;}
private Item findMobTargetItem(MOB mobTarget)
{
final Vector<Item> goodPossibilities=new Vector<Item>();
final Vector<Item> possibilities=new Vector<Item>();
for(int i=0;i<mobTarget.numItems();i++)
{
final Item item=mobTarget.getItem(i);
if((item!=null) && (item.subjectToWearAndTear()) && (CMLib.flags().isMetal(item)))
{
if(item.amWearingAt(Wearable.IN_INVENTORY))
possibilities.addElement(item);
else
goodPossibilities.addElement(item);
}
}
if(goodPossibilities.size()>0)
return goodPossibilities.elementAt(CMLib.dice().roll(1,goodPossibilities.size(),-1));
else
if(possibilities.size()>0)
return possibilities.elementAt(CMLib.dice().roll(1,possibilities.size(),-1));
return null;
}
@Override
public int castingQuality(MOB mob, Physical target)
{
if(mob!=null)
{
if((target instanceof MOB)&&(target!=mob))
{
if(findMobTargetItem((MOB)target)==null)
return Ability.QUALITY_INDIFFERENT;
}
}
return super.castingQuality(mob,target);
}
@Override
public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel)
{
final MOB mobTarget=getTarget(mob,commands,givenTarget,true,false);
Item target=null;
if(mobTarget!=null)
target=findMobTargetItem(mobTarget);
if(target==null)
target=getTarget(mob,mob.location(),givenTarget,commands,Wearable.FILTER_ANY);
if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
return false;
final boolean success=proficiencyCheck(mob,0,auto);
if(success && (target!=null) && CMLib.flags().isMetal(target) && target.subjectToWearAndTear())
{
final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?L("<T-NAME> grow(s) moldy!"):L("^S<S-NAME> chant(s), causing <T-NAMESELF> to get eaten by mold.^?"));
final CMMsg msg2=CMClass.getMsg(mob,mobTarget,this,verbalCastCode(mob,mobTarget,auto),null);
if((mob.location().okMessage(mob,msg))&&((mobTarget==null)||(mob.location().okMessage(mob,msg2))))
{
mob.location().send(mob,msg);
if(mobTarget!=null)
mob.location().send(mob,msg2);
if(msg.value()<=0)
{
int damage=2;
final int num=(mob.phyStats().level()+super.getX1Level(mob)+(2*getXLEVELLevel(mob)))/2;
for(int i=0;i<num;i++)
damage+=CMLib.dice().roll(1,2,2);
if(CMLib.flags().isABonusItems(target))
damage=(int)Math.round(CMath.div(damage,2.0));
if(target.phyStats().ability()>0)
damage=(int)Math.round(CMath.div(damage,1+target.phyStats().ability()));
CMLib.combat().postItemDamage(mob, target, null, damage, CMMsg.TYP_ACID, null);
}
}
}
else
if(mobTarget!=null)
return maliciousFizzle(mob,mobTarget,L("<S-NAME> chant(s) at <T-NAME> for mold, but nothing happens."));
else
if(target!=null)
return maliciousFizzle(mob,target,L("<S-NAME> chant(s) at <T-NAME> for mold, but nothing happens."));
else
return maliciousFizzle(mob,null,L("<S-NAME> chant(s) for mold, but nothing happens."));
// return whether it worked
return success;
}
}
| apache-2.0 |
jhwing/SKShare | SKShare_wechat/src/test/java/stark/skshare/wechat/ExampleUnitTest.java | 398 | package stark.skshare.wechat;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | apache-2.0 |
rodm/TeamCity.SonarQubePlugin | sonar-plugin-agent/src/main/java/jetbrains/buildserver/sonarplugin/SQRBuildService.java | 8810 | package jetbrains.buildserver.sonarplugin;
import jetbrains.buildServer.RunBuildException;
import jetbrains.buildServer.agent.plugins.beans.PluginDescriptor;
import jetbrains.buildServer.agent.runner.CommandLineBuildService;
import jetbrains.buildServer.agent.runner.JavaCommandLineBuilder;
import jetbrains.buildServer.agent.runner.JavaRunnerUtil;
import jetbrains.buildServer.agent.runner.ProgramCommandLine;
import jetbrains.buildServer.runner.JavaRunnerConstants;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.io.FilenameFilter;
import java.util.*;
/**
* Created by Andrey Titov on 4/3/14.
*
* SonarQube Runner wrapper process.
*/
public class SQRBuildService extends CommandLineBuildService {
private static final String BUNDLED_SQR_RUNNER_PATH = "sonar-qube-runner";
private static final String SQR_RUNNER_PATH_PROPERTY = "teamcity.tool.sonarquberunner";
@NotNull
private final PluginDescriptor myPluginDescriptor;
@NotNull
private final SonarProcessListener mySonarProcessListener;
public SQRBuildService(@NotNull final PluginDescriptor pluginDescriptor,
@NotNull final SonarProcessListener sonarProcessListener) {
myPluginDescriptor = pluginDescriptor;
mySonarProcessListener = sonarProcessListener;
}
@NotNull
@Override
public ProgramCommandLine makeProgramCommandLine() throws RunBuildException {
JavaCommandLineBuilder builder = new JavaCommandLineBuilder();
builder.setJavaHome(getRunnerContext().getRunnerParameters().get(JavaRunnerConstants.TARGET_JDK_HOME));
builder.setEnvVariables(getRunnerContext().getBuildParameters().getEnvironmentVariables());
builder.setSystemProperties(getRunnerContext().getBuildParameters().getSystemProperties());
builder.setJvmArgs(JavaRunnerUtil.extractJvmArgs(getRunnerContext().getRunnerParameters()));
builder.setClassPath(getClasspath());
builder.setMainClass("org.sonar.runner.Main");
builder.setProgramArgs(
composeSQRArgs(
getRunnerContext().getRunnerParameters(),
getBuild().getSharedConfigParameters()
));
builder.setWorkingDir(getRunnerContext().getWorkingDirectory().getAbsolutePath());
final ProgramCommandLine cmd = builder.build();
getLogger().message("Starting SQR");
for (String str : cmd.getArguments()) {
getLogger().message(str);
}
return cmd;
}
/**
* Composes SonarQube Runner arguments.
* @param runnerParameters Parameters to compose arguments from
* @param sharedConfigParameters Shared config parameters to compose arguments from
* @return List of arguments to be passed to the SQR
*/
private List<String> composeSQRArgs(@NotNull final Map<String, String> runnerParameters,
@NotNull final Map<String, String> sharedConfigParameters) {
final List<String> res = new LinkedList<String>();
final Map<String, String> allParameters = new HashMap<String, String>(runnerParameters);
allParameters.putAll(sharedConfigParameters);
final SQRParametersAccessor accessor = new SQRParametersAccessor(allParameters);
addSQRArg(res, "-Dproject.home", ".");
addSQRArg(res, "-Dsonar.host.url", accessor.getHostUrl());
addSQRArg(res, "-Dsonar.jdbc.url", accessor.getJDBCUrl());
addSQRArg(res, "-Dsonar.jdbc.username", accessor.getJDBCUsername());
addSQRArg(res, "-Dsonar.jdbc.password", accessor.getJDBCPassword());
addSQRArg(res, "-Dsonar.projectKey", accessor.getProjectKey());
addSQRArg(res, "-Dsonar.projectName", accessor.getProjectName());
addSQRArg(res, "-Dsonar.projectVersion", accessor.getProjectVersion());
addSQRArg(res, "-Dsonar.sources", accessor.getProjectSources());
addSQRArg(res, "-Dsonar.tests", accessor.getProjectTests());
addSQRArg(res, "-Dsonar.binaries", accessor.getProjectBinaries());
addSQRArg(res, "-Dsonar.modules", accessor.getProjectModules());
addSQRArg(res, "-Dsonar.password", accessor.getPassword());
addSQRArg(res, "-Dsonar.login", accessor.getLogin());
final String additionalParameters = accessor.getAdditionalParameters();
if (additionalParameters != null) {
res.addAll(Arrays.asList(additionalParameters.split("\\n")));
}
final Set<String> collectedReports = mySonarProcessListener.getCollectedReports();
if (!collectedReports.isEmpty() && (accessor.getAdditionalParameters() == null || !accessor.getAdditionalParameters().contains("-Dsonar.junit.reportsPath"))) {
addSQRArg(res, "-Dsonar.dynamicAnalysis", "reuseReports");
addSQRArg(res, "-Dsonar.junit.reportsPath", collectReportsPath(collectedReports, accessor.getProjectModules()));
}
final String jacocoExecFilePath = sharedConfigParameters.get("teamcity.jacoco.coverage.datafile");
if (jacocoExecFilePath != null) {
final File file = new File(jacocoExecFilePath);
if (file.exists() && file.isFile() && file.canRead()) {
addSQRArg(res, "-Dsonar.java.coveragePlugin", "jacoco");
addSQRArg(res, "-Dsonar.jacoco.reportPath", jacocoExecFilePath);
}
}
return res;
}
@Nullable
private String collectReportsPath(Set<String> collectedReports, String projectModules) {
StringBuilder sb = new StringBuilder();
final String[] modules = projectModules != null ? projectModules.split(",") : new String[0];
Set<String> filteredReports = new HashSet<String>();
for (String report : collectedReports) {
if (!new File(report).exists()) continue;
for (String module : modules) {
final int indexOf = report.indexOf(module);
if (indexOf > 0) {
report = report.substring(indexOf + module.length() + 1);
}
}
filteredReports.add(report);
}
for (String report : filteredReports) {
sb.append(report).append(',');
break; // At the moment sonar.junit.reportsPath doesn't accept several paths
}
return sb.length() > 0 ? sb.substring(0, sb.length() - 1) : null;
}
/**
* Adds argument only if it's value is not null
* @param argList Result list of arguments
* @param key Argument key
* @param value Argument value
*/
protected static void addSQRArg(@NotNull final List<String> argList, @NotNull final String key, @Nullable final String value) {
if (!Util.isEmpty(value)) {
argList.add(key + "=" + value);
}
}
/**
* @return Classpath for SonarQube Runner
* @throws SQRJarException
*/
@NotNull
private String getClasspath() throws SQRJarException {
final File pluginJar[] = getSQRJar(myPluginDescriptor.getPluginRoot());
final StringBuilder builder = new StringBuilder();
for (final File file : pluginJar) {
builder.append(file.getAbsolutePath()).append(File.pathSeparatorChar);
}
return builder.substring(0, builder.length() - 1);
}
/**
* @param sqrRoot SQR root directory
* @return SonarQube Runner jar location
* @throws SQRJarException
*/
@NotNull
private File[] getSQRJar(@NotNull final File sqrRoot) throws SQRJarException {
final String path = getRunnerContext().getConfigParameters().get(SQR_RUNNER_PATH_PROPERTY);
File baseDir;
if (path != null) {
baseDir = new File(path);
} else {
baseDir = new File(sqrRoot, BUNDLED_SQR_RUNNER_PATH);
}
final File libPath = new File(baseDir, "lib");
if (!libPath.exists()) {
throw new SQRJarException("SonarQube Runner lib path doesn't exist: " + libPath.getAbsolutePath());
} else if (!libPath.isDirectory()) {
throw new SQRJarException("SonarQube Runner lib path is not a directory: " + libPath.getAbsolutePath());
} else if (!libPath.canRead()) {
throw new SQRJarException("Cannot read SonarQube Runner lib path: " + libPath.getAbsolutePath());
}
final File[] jars = libPath.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith("jar");
}
});
if (jars.length == 0) {
throw new SQRJarException("No JAR files found in lib path: " + libPath);
}
return jars;
}
}
| apache-2.0 |
anandsubbu/incubator-metron | metron-platform/metron-enrichment/metron-enrichment-common/src/test/java/org/apache/metron/enrichment/cache/ObjectCacheTest.java | 3919 | /**
* 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 org.apache.metron.enrichment.cache;
import org.apache.commons.io.IOUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.metron.common.utils.SerDeUtils;
import org.apache.metron.integration.utils.TestUtils;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ObjectCacheTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
private FileSystem fs;
private List<String> data;
private ObjectCache cache;
private File tempDir;
@Before
public void setup() throws IOException {
fs = FileSystem.get(new Configuration());
data = new ArrayList<>();
{
data.add("apache");
data.add("metron");
data.add("is");
data.add("great");
}
cache = new ObjectCache();
tempDir = TestUtils.createTempDir(this.getClass().getName());
}
@Test
public void test() throws Exception {
String filename = "test.ser";
Assert.assertTrue(cache.isEmpty() || !cache.containsKey(filename));
assertDataIsReadCorrectly(filename);
}
public void assertDataIsReadCorrectly(String filename) throws IOException {
File file = new File(tempDir, filename);
try(BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file))) {
IOUtils.write(SerDeUtils.toBytes(data), bos);
}
cache.initialize(new ObjectCacheConfig(new HashMap<>()));
List<String> readData = (List<String>) cache.get(file.getAbsolutePath());
Assert.assertEquals(readData, data);
Assert.assertTrue(cache.containsKey(file.getAbsolutePath()));
}
@Test
public void testMultithreaded() throws Exception {
String filename = "testmulti.ser";
Assert.assertTrue(cache.isEmpty() || !cache.containsKey(filename));
Thread[] ts = new Thread[10];
for(int i = 0;i < ts.length;++i) {
ts[i] = new Thread(() -> {
try {
assertDataIsReadCorrectly(filename);
} catch (Exception e) {
throw new IllegalStateException(e.getMessage(), e);
}
});
ts[i].start();
}
for(Thread t : ts) {
t.join();
}
}
@Test
public void shouldThrowExceptionOnMaxFileSize() throws Exception {
String filename = "maxSizeException.ser";
File file = new File(tempDir, filename);
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage(String.format("File at path '%s' is larger than the configured max file size of 1", file.getAbsolutePath()));
try(BufferedOutputStream bos = new BufferedOutputStream(fs.create(new Path(file.getAbsolutePath()), true))) {
IOUtils.write(SerDeUtils.toBytes(data), bos);
}
ObjectCacheConfig objectCacheConfig = new ObjectCacheConfig(new HashMap<>());
objectCacheConfig.setMaxFileSize(1);
cache.initialize(objectCacheConfig);
cache.get(file.getAbsolutePath());
}
}
| apache-2.0 |
KiviMao/kivi | Java.Source/spring-data-elasticsearch/src/main/java/org/springframework/data/elasticsearch/core/facet/request/RangeFacetRequestBuilder.java | 1997 | /*
* Copyright 2014 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
*
* 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.springframework.data.elasticsearch.core.facet.request;
import org.springframework.data.elasticsearch.core.facet.FacetRequest;
/**
* Basic range facet
*
* @author Artur Konczak
*/
@Deprecated
public class RangeFacetRequestBuilder {
RangeFacetRequest result;
public RangeFacetRequestBuilder(String name) {
result = new RangeFacetRequest(name);
}
public RangeFacetRequestBuilder field(String field) {
result.setField(field);
return this;
}
public RangeFacetRequestBuilder fields(String keyField, String valueField) {
result.setFields(keyField, valueField);
return this;
}
public RangeFacetRequestBuilder range(double from, double to) {
result.range(from, to);
return this;
}
public RangeFacetRequestBuilder range(String from, String to) {
result.range(from, to);
return this;
}
public RangeFacetRequestBuilder from(double from) {
result.range(from, null);
return this;
}
public RangeFacetRequestBuilder to(double to) {
result.range(null, to);
return this;
}
public RangeFacetRequestBuilder from(String from) {
result.range(from, null);
return this;
}
public RangeFacetRequestBuilder to(String to) {
result.range(null, to);
return this;
}
public RangeFacetRequestBuilder applyQueryFilter() {
result.setApplyQueryFilter(true);
return this;
}
public FacetRequest build() {
return result;
}
} | apache-2.0 |
KiminRyu/ExoPlayer | library/core/src/test/java/com/google/android/exoplayer2/source/CompositeSequenceableLoaderTest.java | 12343 | /*
* Copyright (C) 2017 The Android Open Source Project
*
* 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.exoplayer2.source;
import static com.google.common.truth.Truth.assertThat;
import com.google.android.exoplayer2.C;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
/**
* Unit test for {@link CompositeSequenceableLoader}.
*/
@RunWith(RobolectricTestRunner.class)
@Config(sdk = Config.TARGET_SDK, manifest = Config.NONE)
public final class CompositeSequenceableLoaderTest {
/**
* Tests that {@link CompositeSequenceableLoader#getBufferedPositionUs()} returns minimum buffered
* position among all sub-loaders.
*/
@Test
public void testGetBufferedPositionUsReturnsMinimumLoaderBufferedPosition() {
FakeSequenceableLoader loader1 =
new FakeSequenceableLoader(/* bufferedPositionUs */ 1000, /* nextLoadPositionUs */ 2000);
FakeSequenceableLoader loader2 =
new FakeSequenceableLoader(/* bufferedPositionUs */ 1001, /* nextLoadPositionUs */ 2001);
CompositeSequenceableLoader compositeSequenceableLoader = new CompositeSequenceableLoader(
new SequenceableLoader[] {loader1, loader2});
assertThat(compositeSequenceableLoader.getBufferedPositionUs()).isEqualTo(1000);
}
/**
* Tests that {@link CompositeSequenceableLoader#getBufferedPositionUs()} returns minimum buffered
* position that is not {@link C#TIME_END_OF_SOURCE} among all sub-loaders.
*/
@Test
public void testGetBufferedPositionUsReturnsMinimumNonEndOfSourceLoaderBufferedPosition() {
FakeSequenceableLoader loader1 =
new FakeSequenceableLoader(/* bufferedPositionUs */ 1000, /* nextLoadPositionUs */ 2000);
FakeSequenceableLoader loader2 =
new FakeSequenceableLoader(/* bufferedPositionUs */ 1001, /* nextLoadPositionUs */ 2000);
FakeSequenceableLoader loader3 =
new FakeSequenceableLoader(
/* bufferedPositionUs */ C.TIME_END_OF_SOURCE,
/* nextLoadPositionUs */ C.TIME_END_OF_SOURCE);
CompositeSequenceableLoader compositeSequenceableLoader = new CompositeSequenceableLoader(
new SequenceableLoader[] {loader1, loader2, loader3});
assertThat(compositeSequenceableLoader.getBufferedPositionUs()).isEqualTo(1000);
}
/**
* Tests that {@link CompositeSequenceableLoader#getBufferedPositionUs()} returns
* {@link C#TIME_END_OF_SOURCE} when all sub-loaders have buffered till end-of-source.
*/
@Test
public void testGetBufferedPositionUsReturnsEndOfSourceWhenAllLoaderBufferedTillEndOfSource() {
FakeSequenceableLoader loader1 =
new FakeSequenceableLoader(
/* bufferedPositionUs */ C.TIME_END_OF_SOURCE,
/* nextLoadPositionUs */ C.TIME_END_OF_SOURCE);
FakeSequenceableLoader loader2 =
new FakeSequenceableLoader(
/* bufferedPositionUs */ C.TIME_END_OF_SOURCE,
/* nextLoadPositionUs */ C.TIME_END_OF_SOURCE);
CompositeSequenceableLoader compositeSequenceableLoader = new CompositeSequenceableLoader(
new SequenceableLoader[] {loader1, loader2});
assertThat(compositeSequenceableLoader.getBufferedPositionUs()).isEqualTo(C.TIME_END_OF_SOURCE);
}
/**
* Tests that {@link CompositeSequenceableLoader#getNextLoadPositionUs()} returns minimum next
* load position among all sub-loaders.
*/
@Test
public void testGetNextLoadPositionUsReturnMinimumLoaderNextLoadPositionUs() {
FakeSequenceableLoader loader1 =
new FakeSequenceableLoader(/* bufferedPositionUs */ 1000, /* nextLoadPositionUs */ 2001);
FakeSequenceableLoader loader2 =
new FakeSequenceableLoader(/* bufferedPositionUs */ 1001, /* nextLoadPositionUs */ 2000);
CompositeSequenceableLoader compositeSequenceableLoader = new CompositeSequenceableLoader(
new SequenceableLoader[] {loader1, loader2});
assertThat(compositeSequenceableLoader.getNextLoadPositionUs()).isEqualTo(2000);
}
/**
* Tests that {@link CompositeSequenceableLoader#getNextLoadPositionUs()} returns minimum next
* load position that is not {@link C#TIME_END_OF_SOURCE} among all sub-loaders.
*/
@Test
public void testGetNextLoadPositionUsReturnMinimumNonEndOfSourceLoaderNextLoadPositionUs() {
FakeSequenceableLoader loader1 =
new FakeSequenceableLoader(/* bufferedPositionUs */ 1000, /* nextLoadPositionUs */ 2000);
FakeSequenceableLoader loader2 =
new FakeSequenceableLoader(/* bufferedPositionUs */ 1001, /* nextLoadPositionUs */ 2001);
FakeSequenceableLoader loader3 =
new FakeSequenceableLoader(
/* bufferedPositionUs */ 1001, /* nextLoadPositionUs */ C.TIME_END_OF_SOURCE);
CompositeSequenceableLoader compositeSequenceableLoader = new CompositeSequenceableLoader(
new SequenceableLoader[] {loader1, loader2, loader3});
assertThat(compositeSequenceableLoader.getNextLoadPositionUs()).isEqualTo(2000);
}
/**
* Tests that {@link CompositeSequenceableLoader#getNextLoadPositionUs()} returns
* {@link C#TIME_END_OF_SOURCE} when all sub-loaders have next load position at end-of-source.
*/
@Test
public void testGetNextLoadPositionUsReturnsEndOfSourceWhenAllLoaderLoadingLastChunk() {
FakeSequenceableLoader loader1 =
new FakeSequenceableLoader(
/* bufferedPositionUs */ 1000, /* nextLoadPositionUs */ C.TIME_END_OF_SOURCE);
FakeSequenceableLoader loader2 =
new FakeSequenceableLoader(
/* bufferedPositionUs */ 1001, /* nextLoadPositionUs */ C.TIME_END_OF_SOURCE);
CompositeSequenceableLoader compositeSequenceableLoader = new CompositeSequenceableLoader(
new SequenceableLoader[] {loader1, loader2});
assertThat(compositeSequenceableLoader.getNextLoadPositionUs()).isEqualTo(C.TIME_END_OF_SOURCE);
}
/**
* Tests that {@link CompositeSequenceableLoader#continueLoading(long)} only allows the loader
* with minimum next load position to continue loading if next load positions are not behind
* current playback position.
*/
@Test
public void testContinueLoadingOnlyAllowFurthestBehindLoaderToLoadIfNotBehindPlaybackPosition() {
FakeSequenceableLoader loader1 =
new FakeSequenceableLoader(/* bufferedPositionUs */ 1000, /* nextLoadPositionUs */ 2000);
FakeSequenceableLoader loader2 =
new FakeSequenceableLoader(/* bufferedPositionUs */ 1001, /* nextLoadPositionUs */ 2001);
CompositeSequenceableLoader compositeSequenceableLoader = new CompositeSequenceableLoader(
new SequenceableLoader[] {loader1, loader2});
compositeSequenceableLoader.continueLoading(100);
assertThat(loader1.numInvocations).isEqualTo(1);
assertThat(loader2.numInvocations).isEqualTo(0);
}
/**
* Tests that {@link CompositeSequenceableLoader#continueLoading(long)} allows all loaders
* with next load position behind current playback position to continue loading.
*/
@Test
public void testContinueLoadingReturnAllowAllLoadersBehindPlaybackPositionToLoad() {
FakeSequenceableLoader loader1 =
new FakeSequenceableLoader(/* bufferedPositionUs */ 1000, /* nextLoadPositionUs */ 2000);
FakeSequenceableLoader loader2 =
new FakeSequenceableLoader(/* bufferedPositionUs */ 1001, /* nextLoadPositionUs */ 2001);
FakeSequenceableLoader loader3 =
new FakeSequenceableLoader(/* bufferedPositionUs */ 1002, /* nextLoadPositionUs */ 2002);
CompositeSequenceableLoader compositeSequenceableLoader = new CompositeSequenceableLoader(
new SequenceableLoader[] {loader1, loader2, loader3});
compositeSequenceableLoader.continueLoading(3000);
assertThat(loader1.numInvocations).isEqualTo(1);
assertThat(loader2.numInvocations).isEqualTo(1);
assertThat(loader3.numInvocations).isEqualTo(1);
}
/**
* Tests that {@link CompositeSequenceableLoader#continueLoading(long)} does not allow loader
* with next load position at end-of-source to continue loading.
*/
@Test
public void testContinueLoadingOnlyNotAllowEndOfSourceLoaderToLoad() {
FakeSequenceableLoader loader1 =
new FakeSequenceableLoader(
/* bufferedPositionUs */ 1000, /* nextLoadPositionUs */ C.TIME_END_OF_SOURCE);
FakeSequenceableLoader loader2 =
new FakeSequenceableLoader(
/* bufferedPositionUs */ 1001, /* nextLoadPositionUs */ C.TIME_END_OF_SOURCE);
CompositeSequenceableLoader compositeSequenceableLoader = new CompositeSequenceableLoader(
new SequenceableLoader[] {loader1, loader2});
compositeSequenceableLoader.continueLoading(3000);
assertThat(loader1.numInvocations).isEqualTo(0);
assertThat(loader2.numInvocations).isEqualTo(0);
}
/**
* Tests that {@link CompositeSequenceableLoader#continueLoading(long)} returns true if the loader
* with minimum next load position can make progress if next load positions are not behind
* current playback position.
*/
@Test
public void testContinueLoadingReturnTrueIfFurthestBehindLoaderCanMakeProgress() {
FakeSequenceableLoader loader1 =
new FakeSequenceableLoader(/* bufferedPositionUs */ 1000, /* nextLoadPositionUs */ 2000);
FakeSequenceableLoader loader2 =
new FakeSequenceableLoader(/* bufferedPositionUs */ 1001, /* nextLoadPositionUs */ 2001);
loader1.setNextChunkDurationUs(1000);
CompositeSequenceableLoader compositeSequenceableLoader = new CompositeSequenceableLoader(
new SequenceableLoader[] {loader1, loader2});
assertThat(compositeSequenceableLoader.continueLoading(100)).isTrue();
}
/**
* Tests that {@link CompositeSequenceableLoader#continueLoading(long)} returns true if any loader
* that are behind current playback position can make progress, even if it is not the one with
* minimum next load position.
*/
@Test
public void testContinueLoadingReturnTrueIfLoaderBehindPlaybackPositionCanMakeProgress() {
FakeSequenceableLoader loader1 =
new FakeSequenceableLoader(/* bufferedPositionUs */ 1000, /* nextLoadPositionUs */ 2000);
FakeSequenceableLoader loader2 =
new FakeSequenceableLoader(/* bufferedPositionUs */ 1001, /* nextLoadPositionUs */ 2001);
// loader2 is not the furthest behind, but it can make progress if allowed.
loader2.setNextChunkDurationUs(1000);
CompositeSequenceableLoader compositeSequenceableLoader = new CompositeSequenceableLoader(
new SequenceableLoader[] {loader1, loader2});
assertThat(compositeSequenceableLoader.continueLoading(3000)).isTrue();
}
private static class FakeSequenceableLoader implements SequenceableLoader {
private long bufferedPositionUs;
private long nextLoadPositionUs;
private int numInvocations;
private int nextChunkDurationUs;
private FakeSequenceableLoader(long bufferedPositionUs, long nextLoadPositionUs) {
this.bufferedPositionUs = bufferedPositionUs;
this.nextLoadPositionUs = nextLoadPositionUs;
}
@Override
public long getBufferedPositionUs() {
return bufferedPositionUs;
}
@Override
public long getNextLoadPositionUs() {
return nextLoadPositionUs;
}
@Override
public boolean continueLoading(long positionUs) {
numInvocations++;
boolean loaded = nextChunkDurationUs != 0;
// The current chunk has been loaded, advance to next chunk.
bufferedPositionUs = nextLoadPositionUs;
nextLoadPositionUs += nextChunkDurationUs;
nextChunkDurationUs = 0;
return loaded;
}
@Override
public void reevaluateBuffer(long positionUs) {
// Do nothing.
}
private void setNextChunkDurationUs(int nextChunkDurationUs) {
this.nextChunkDurationUs = nextChunkDurationUs;
}
}
}
| apache-2.0 |
iritgo/iritgo-aktera | aktera-journal/src/main/java/de/iritgo/aktera/journal/JournalManagerImpl.java | 10792 | /**
* This file is part of the Iritgo/Aktera Framework.
*
* Copyright (C) 2005-2011 Iritgo Technologies.
* Copyright (C) 2003-2005 BueroByte GbR.
*
* Iritgo 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 de.iritgo.aktera.journal;
import java.sql.*;
import java.util.*;
import com.ibm.icu.util.GregorianCalendar;
import lombok.Setter;
import de.iritgo.aktario.framework.command.CommandTools;
import de.iritgo.aktera.authentication.defaultauth.entity.UserDAO;
import de.iritgo.aktera.configuration.SystemConfigManager;
import de.iritgo.aktera.event.EventManager;
import de.iritgo.aktera.journal.entity.JournalEntry;
import de.iritgo.aktera.logger.Logger;
import de.iritgo.aktera.model.ModelRequest;
import de.iritgo.aktera.scheduler.*;
import de.iritgo.aktera.spring.SpringTools;
import de.iritgo.aktera.startup.*;
import de.iritgo.simplelife.bean.BeanTools;
import de.iritgo.simplelife.constants.SortOrder;
import de.iritgo.simplelife.string.StringTools;
public class JournalManagerImpl implements JournalManager, StartupHandler
{
@Setter
private JournalDAO journalDAO;
@Setter
private Logger logger;
@Setter
private Map<String, JournalExtender> journalExtenders;
@Setter
private List<JournalExecute> journalExecuters;
@Setter
private EventManager eventManager;
@Setter
private SystemConfigManager systemConfigManager;
@Setter
private Scheduler scheduler;
@Override
public void startup() throws StartupException
{
if (systemConfigManager.getBool("phone", "journalCleanupEnabled"))
{
Time cleanupTime = systemConfigManager.getTime("phone", "journalCleanupTime");
int cleanupInterval = systemConfigManager.getInt("phone", "journalCleanupPeriod");
logger.info("Starting Journal cleanup job (at " + cleanupTime + ", delete entries older than "
+ cleanupInterval + " seconds)");
GregorianCalendar cleanupTimeCal = new GregorianCalendar();
cleanupTimeCal.setTime(cleanupTime);
Runnable cleanupTask = new Runnable()
{
@Override
public void run()
{
journalCleanup();
}
};
scheduler.scheduleRunnable(
"de.iritgo.aktera.journal.JournalCleanup",
"JournalManager",
cleanupTask,
new ScheduleOn().hour(cleanupTimeCal.get(Calendar.HOUR_OF_DAY))
.minute(cleanupTimeCal.get(Calendar.MINUTE)).second(0));
}
}
@Override
public void shutdown() throws ShutdownException
{
}
@Override
public void addJournalEntry(JournalEntry journalEntry)
{
if (journalEntry.getExtendedInfoType() != null)
{
JournalExtender je = journalExtenders.get(journalEntry.getExtendedInfoType());
if (je != null)
{
je.newJournalEntry(journalEntry);
}
}
journalDAO.create(journalEntry);
Properties eventProps = new Properties();
eventProps.put("journalEntry", journalEntry);
eventManager.fire("iritgo.aktera.journal.new-entry", eventProps);
refreshAktarioJournalList(journalEntry);
}
@Override
public void deleteJournalEntry(JournalEntry journalEntry)
{
if (journalEntry == null)
{
logger.error("Can't delete journal entry. The journal entry object is null.");
Thread.dumpStack();
return;
}
if (journalEntry.getExtendedInfoType() != null)
{
JournalExtender je = journalExtenders.get(journalEntry.getExtendedInfoType());
if (je != null)
{
je.deletedJournalEntry(journalEntry);
}
}
journalDAO.delete(journalEntry);
Properties eventProps = new Properties();
eventProps.put("journalEntry", journalEntry);
eventManager.fire("iritgo.aktera.journal.removed-entry", eventProps);
refreshAktarioJournalList(journalEntry);
}
private void refreshAktarioJournalList(JournalEntry journalEntry)
{
UserDAO userDAO = (UserDAO) SpringTools.getBean(UserDAO.ID);
de.iritgo.aktera.authentication.defaultauth.entity.AkteraUser userAktera = userDAO.findUserById(journalEntry
.getOwnerId());
Properties props = new Properties();
props.setProperty("akteraUserName", userAktera.getName());
CommandTools.performAsync("de.iritgo.aktera.journal.RefreshJournal", props);
}
@Override
public Map<String, Object> getJournalEntryById(Integer id)
{
Map<String, Object> entry = new HashMap<String, Object>();
JournalEntry journalEntry = journalDAO.getById(id);
addJournalEntryAttributes(journalEntry, entry);
if (journalEntry.getExtendedInfoType() != null)
{
JournalExtender je = journalExtenders.get(journalEntry.getExtendedInfoType());
if (je != null)
{
je.addJournalEntryAttributes(entry);
}
}
return entry;
}
@Override
public List<Map<String, Object>> listJournalEntries(String search, Timestamp start, Timestamp end, Integer ownerId,
String ownerType, String sortColumnName, SortOrder sortOrder, int firstResult, int resultsPerPage)
{
List<Map<String, Object>> entries = new LinkedList<Map<String, Object>>();
for (JournalEntry journalEntry : journalDAO.listJournalEntries(search, start, end, ownerId, ownerType,
sortColumnName, sortOrder, firstResult, resultsPerPage))
{
Map<String, Object> entry = new HashMap<String, Object>();
addJournalEntryAttributes(journalEntry, entry);
if (journalEntry.getExtendedInfoType() != null)
{
JournalExtender je = journalExtenders.get(journalEntry.getExtendedInfoType());
if (je != null)
{
je.addJournalEntryAttributes(entry);
}
}
entries.add(entry);
}
return entries;
}
@Override
public long countJournalEntries(String search, Timestamp start, Timestamp end, Integer ownerId, String ownerType)
{
return journalDAO.countJournalEntries(search, start, end, ownerId, ownerType);
}
@Override
public List<Map<String, Object>> listJournalEntriesByPrimaryAndSecondaryType(String search, Timestamp start,
Timestamp end, Integer ownerId, String ownerType, String sortColumnName, SortOrder sortOrder,
int firstResult, int resultsPerPage, String primaryType, String secondaryType)
{
List<Map<String, Object>> entries = new LinkedList<Map<String, Object>>();
for (JournalEntry journalEntry : journalDAO.listJournalEntriesByPrimaryAndSecondaryType(search, start, end,
ownerId, ownerType, sortColumnName, sortOrder, firstResult, resultsPerPage, primaryType,
secondaryType))
{
Map<String, Object> entry = new HashMap<String, Object>();
addJournalEntryAttributes(journalEntry, entry);
if (journalEntry.getExtendedInfoType() != null)
{
JournalExtender je = journalExtenders.get(journalEntry.getExtendedInfoType());
if (je != null)
{
je.addJournalEntryAttributes(entry);
}
}
entries.add(entry);
}
return entries;
}
@Override
public long countJournalEntriesByPrimaryAndSecondaryType(String search, Timestamp start, Timestamp end,
Integer ownerId, String ownerType, String primaryType, String secondaryType)
{
return journalDAO.countJournalEntriesByPrimaryAndSecondaryType(search, start, end, ownerId, ownerType,
primaryType, secondaryType);
}
private void addJournalEntryAttributes(JournalEntry journalEntry, Map<String, Object> entry)
{
BeanTools.copyBean2Map(journalEntry, entry, true);
}
@Override
public void deleteJournalEntry(int journalEntryId)
{
JournalEntry journalEntry = journalDAO.getById(journalEntryId);
deleteJournalEntry(journalEntry);
}
@Override
public long countJournalEntriesByCondition(String condition, Map<String, Object> conditionMap)
{
return journalDAO.countJournalEntriesByCondition(condition, conditionMap);
}
@Override
public List<Map<String, Object>> listJournalEntriesByCondition(String sortColumnName, SortOrder sortOrder,
int firstResult, int resultsPerPage, String condition, Map<String, Object> conditionMap)
{
List<Map<String, Object>> entries = new LinkedList<Map<String, Object>>();
for (JournalEntry journalEntry : journalDAO.listJournalEntriesByCondition(sortColumnName, sortOrder,
firstResult, resultsPerPage, condition, conditionMap))
{
Map<String, Object> entry = new HashMap<String, Object>();
addJournalEntryAttributes(journalEntry, entry);
if (journalEntry.getExtendedInfoType() != null)
{
JournalExtender je = journalExtenders.get(journalEntry.getExtendedInfoType());
if (je != null)
{
je.addJournalEntryAttributes(entry);
}
}
entries.add(entry);
}
return entries;
}
@Override
public void executeJournalEntry(String commandId, int id, String prefix, ModelRequest req)
{
Map<String, Object> entry = getJournalEntryById(id);
String primaryType = (String) entry.get("primaryType");
String secondaryType = (String) entry.get("secondaryType");
for (JournalExecute execute : journalExecuters)
{
execute.execute(commandId, primaryType, secondaryType, prefix, entry, req);
}
}
@Override
public void deleteJournalAllEntries(Integer ownerId)
{
List<JournalEntry> journalEntries = journalDAO.listJournalEntriesByOwnerId(ownerId);
for (JournalExtender extender : journalExtenders.values())
{
extender.deleteAllJournalEntries(journalEntries);
}
Properties eventProps = new Properties();
eventProps.setProperty("ownerId", StringTools.trim(ownerId));
eventManager.fire("iritgo.aktera.journal.remove-all-entries", eventProps);
journalDAO.deleteAllJournalEntriesByOwnerId(ownerId);
UserDAO userDAO = (UserDAO) SpringTools.getBean(UserDAO.ID);
de.iritgo.aktera.authentication.defaultauth.entity.AkteraUser userAktera = userDAO.findUserById(ownerId);
Properties props = new Properties();
props.setProperty("akteraUserName", userAktera.getName());
CommandTools.performAsync("de.iritgo.aktera.journal.RefreshJournal", props);
}
@Override
public void deleteAllJournalEntriesBefore(long periodInSeconds)
{
for (JournalExtender extender : journalExtenders.values())
{
extender.deleteAllJournalEntriesBefore(periodInSeconds);
}
journalDAO.deleteAllJournalDatasBefore(periodInSeconds);
journalDAO.deleteAllJournalEntriesBefore(periodInSeconds);
}
@Override
public void journalCleanup()
{
int cleanupInterval = systemConfigManager.getInt("phone", "journalCleanupPeriod");
if (cleanupInterval > 0)
{
logger.info("Cleaning CDR data older than " + cleanupInterval + " seconds)");
deleteAllJournalEntriesBefore(cleanupInterval);
}
}
}
| apache-2.0 |
schnurlei/jdynameta | jdy/jdy.model.metadata/src/main/java/de/jdynameta/metamodel/metainfo/MetaModelPersistentObjectCreator.java | 5136 | /**
*
* Copyright 2011 (C) Rainer Schneider,Roggenburg <schnurlei@googlemail.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 de.jdynameta.metamodel.metainfo;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import de.jdynameta.base.creation.ObjectCreator;
import de.jdynameta.base.metainfo.AssociationInfo;
import de.jdynameta.base.metainfo.ClassInfo;
import de.jdynameta.base.objectlist.ObjectList;
import de.jdynameta.base.value.ObjectCreationException;
import de.jdynameta.base.value.ProxyResolver;
import de.jdynameta.base.value.TypedValueObject;
import de.jdynameta.base.value.ValueObject;
import de.jdynameta.base.value.defaultimpl.TypedReflectionObjectInterface;
import de.jdynameta.base.value.defaultimpl.TypedReflectionValueObject;
import de.jdynameta.base.value.defaultimpl.TypedWrappedValueObject;
import de.jdynameta.metamodel.generation.MetaModelClassFileGenerator;
import de.jdynameta.metamodel.metainfo.model.impl.ObjectReferenceAttributeInfoModelImpl;
import de.jdynameta.persistence.impl.proxy.ReflectionObjectCreator;
import de.jdynameta.persistence.manager.impl.AssociationInfoListModel;
/**
* Creates an GenericPersitentObjectCreator for the ClassInfo
*
* Use an external Object creator to create referenced Objects
* (maybe they are cached and have not be created)
* @author Rainer
*
*/
@SuppressWarnings("serial")
public class MetaModelPersistentObjectCreator extends ReflectionObjectCreator<ValueObject,TypedReflectionObjectInterface>
{
private final MetaModelPersistenceObjectManager objectManager;
public MetaModelPersistentObjectCreator(ObjectCreator aReferencedObjectCreator, ProxyResolver aProxyResolver
, MetaModelPersistenceObjectManager aObjectManager)
{
super( aProxyResolver, new ModelNameCreator(), aObjectManager);
this.objectManager = aObjectManager;
}
@Override
protected TypedReflectionValueObject createNoProxyObjectFor( TypedValueObject aValueModel) throws ObjectCreationException
{
TypedReflectionValueObject newObject;
try
{
final Class<? extends Object> metaClass = Class.forName(getNameCreator().getAbsolutClassNameFor(aValueModel.getClassInfo()));
Constructor<? extends Object> classConstructor = metaClass.getConstructor(new Class[] {});
newObject = (TypedReflectionValueObject) classConstructor.newInstance(new Object[]{});
setValuesInObject(metaClass, newObject, aValueModel.getClassInfo(), aValueModel);
} catch (Exception excp)
{
throw new ObjectCreationException(excp);
}
return newObject;
}
@Override
protected ObjectList<TypedReflectionObjectInterface> createNonProxyObjectList(AssociationInfo aAssocInfo, ObjectList aListToSet, Object aParent)
{
return new AssociationInfoListModel<TypedReflectionObjectInterface>(objectManager, aAssocInfo, aListToSet, aParent);
}
// protected ObjectList<ValueObject> createProxyObjectList(AssociationInfo aAssocInfo, Object aParent)
// {
// return new ProxyAssociationListModel<ValueObject>(objectManager, aAssocInfo, (ValueObject) aParent );
// }
/* (non-Javadoc)
* @see de.comafra.model.persistence.ObjectCreatorWithProxy#createProxyObjectFor(de.comafra.model.metainfo.ClassInfo, de.comafra.model.value.ValueObject)
*/
@Override
protected TypedReflectionObjectInterface createProxyObjectFor( TypedValueObject aValueModel) throws ObjectCreationException
{
try
{
Method aMethod = ObjectReferenceAttributeInfoModelImpl.class.getMethod("getInternalName", (Class[]) null );
} catch (SecurityException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
TypedReflectionObjectInterface newObject = super.createProxyObjectFor( aValueModel);
return newObject;
}
public TypedValueObject getValueObjectFor(ClassInfo aClassinfo, ValueObject aObjectToTransform)
{
return new TypedWrappedValueObject( aObjectToTransform, aClassinfo) ;
}
public static class ModelNameCreator extends MetaModelClassFileGenerator.ModelNameCreator
{
@Override
public String getReferenceClassNameFor(ClassInfo aInfo)
{
return "de.jdynameta.metamodel.metainfo.model" +"." + aInfo.getInternalName();
//.substring(0, aInfo.getInternalName().length() - "Model".length());
}
@Override
public String getPackageNameFor(ClassInfo aInfo)
{
return "de.jdynameta.metamodel.metainfo.model.impl";
}
}
}
| apache-2.0 |
seanashmore/soundAffect | app/src/main/java/com/alittlelost/soundaffectsample/MainActivity.java | 1306 | package com.alittlelost.soundaffectsample;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;
import com.alittlelost.soundaffect.SoundAffect;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
SoundAffect soundAffect;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
soundAffect = findViewById(R.id.soundAffect);
soundAffect.bindService(new SoundAffect.OnBindAttemptCompleteCallback() {
@Override
public void onSuccess() {
soundAffect.loadUrl("http://www.sample-videos.com/audio/mp3/crowd-cheering.mp3");
Toast.makeText(MainActivity.this, "Loaded audio from url", Toast.LENGTH_SHORT).show();
}
@Override
public void onFailure() {
Toast.makeText(MainActivity.this, "Service bind attempt failed", Toast.LENGTH_SHORT).show();
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.i(TAG, "Unbinding media service");
soundAffect.unbindService();
}
}
| apache-2.0 |
google-code-export/google-api-dfp-java | src/com/google/api/ads/dfp/v201302/TeamError.java | 4176 | /**
* TeamError.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter.
*/
package com.google.api.ads.dfp.v201302;
/**
* Errors related to a Team.
*/
public class TeamError extends com.google.api.ads.dfp.v201302.ApiError implements java.io.Serializable {
/* The error reason represented by an enum. */
private com.google.api.ads.dfp.v201302.TeamErrorReason reason;
public TeamError() {
}
public TeamError(
java.lang.String fieldPath,
java.lang.String trigger,
java.lang.String errorString,
java.lang.String apiErrorType,
com.google.api.ads.dfp.v201302.TeamErrorReason reason) {
super(
fieldPath,
trigger,
errorString,
apiErrorType);
this.reason = reason;
}
/**
* Gets the reason value for this TeamError.
*
* @return reason * The error reason represented by an enum.
*/
public com.google.api.ads.dfp.v201302.TeamErrorReason getReason() {
return reason;
}
/**
* Sets the reason value for this TeamError.
*
* @param reason * The error reason represented by an enum.
*/
public void setReason(com.google.api.ads.dfp.v201302.TeamErrorReason reason) {
this.reason = reason;
}
private java.lang.Object __equalsCalc = null;
public synchronized boolean equals(java.lang.Object obj) {
if (!(obj instanceof TeamError)) return false;
TeamError other = (TeamError) obj;
if (obj == null) return false;
if (this == obj) return true;
if (__equalsCalc != null) {
return (__equalsCalc == obj);
}
__equalsCalc = obj;
boolean _equals;
_equals = super.equals(obj) &&
((this.reason==null && other.getReason()==null) ||
(this.reason!=null &&
this.reason.equals(other.getReason())));
__equalsCalc = null;
return _equals;
}
private boolean __hashCodeCalc = false;
public synchronized int hashCode() {
if (__hashCodeCalc) {
return 0;
}
__hashCodeCalc = true;
int _hashCode = super.hashCode();
if (getReason() != null) {
_hashCode += getReason().hashCode();
}
__hashCodeCalc = false;
return _hashCode;
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(TeamError.class, true);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201302", "TeamError"));
org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("reason");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201302", "reason"));
elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201302", "TeamError.Reason"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
/**
* Get Custom Serializer
*/
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanSerializer(
_javaType, _xmlType, typeDesc);
}
/**
* Get Custom Deserializer
*/
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanDeserializer(
_javaType, _xmlType, typeDesc);
}
}
| apache-2.0 |
google-code-export/google-api-dfp-java | src/com/google/api/ads/dfp/v201211/Content.java | 9120 | /**
* Content.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter.
*/
package com.google.api.ads.dfp.v201211;
/**
* A {@code Content} represents video metadata from a publisher's
* Content Management System (CMS) that has been synced to
* DFP.
* <p>
* Video line items can be targeted to {@code Content}
* to indicate what ads should match when the {@code Content}
* is being played.
*/
public class Content implements java.io.Serializable {
/* Uniquely identifies the {@code Content}. This attribute is
* read-only and
* is assigned by Google when the content is created. */
private java.lang.Long id;
/* The name of the {@code Content}. This attribute is read-only. */
private java.lang.String name;
/* The status of this {@code Content}. This attribute is read-only. */
private com.google.api.ads.dfp.v201211.ContentStatus status;
/* Whether the content status was defined by the user, or by the
* source CMS
* from which the content was ingested. This attribute
* is read-only. */
private com.google.api.ads.dfp.v201211.ContentStatusDefinedBy statusDefinedBy;
public Content() {
}
public Content(
java.lang.Long id,
java.lang.String name,
com.google.api.ads.dfp.v201211.ContentStatus status,
com.google.api.ads.dfp.v201211.ContentStatusDefinedBy statusDefinedBy) {
this.id = id;
this.name = name;
this.status = status;
this.statusDefinedBy = statusDefinedBy;
}
/**
* Gets the id value for this Content.
*
* @return id * Uniquely identifies the {@code Content}. This attribute is
* read-only and
* is assigned by Google when the content is created.
*/
public java.lang.Long getId() {
return id;
}
/**
* Sets the id value for this Content.
*
* @param id * Uniquely identifies the {@code Content}. This attribute is
* read-only and
* is assigned by Google when the content is created.
*/
public void setId(java.lang.Long id) {
this.id = id;
}
/**
* Gets the name value for this Content.
*
* @return name * The name of the {@code Content}. This attribute is read-only.
*/
public java.lang.String getName() {
return name;
}
/**
* Sets the name value for this Content.
*
* @param name * The name of the {@code Content}. This attribute is read-only.
*/
public void setName(java.lang.String name) {
this.name = name;
}
/**
* Gets the status value for this Content.
*
* @return status * The status of this {@code Content}. This attribute is read-only.
*/
public com.google.api.ads.dfp.v201211.ContentStatus getStatus() {
return status;
}
/**
* Sets the status value for this Content.
*
* @param status * The status of this {@code Content}. This attribute is read-only.
*/
public void setStatus(com.google.api.ads.dfp.v201211.ContentStatus status) {
this.status = status;
}
/**
* Gets the statusDefinedBy value for this Content.
*
* @return statusDefinedBy * Whether the content status was defined by the user, or by the
* source CMS
* from which the content was ingested. This attribute
* is read-only.
*/
public com.google.api.ads.dfp.v201211.ContentStatusDefinedBy getStatusDefinedBy() {
return statusDefinedBy;
}
/**
* Sets the statusDefinedBy value for this Content.
*
* @param statusDefinedBy * Whether the content status was defined by the user, or by the
* source CMS
* from which the content was ingested. This attribute
* is read-only.
*/
public void setStatusDefinedBy(com.google.api.ads.dfp.v201211.ContentStatusDefinedBy statusDefinedBy) {
this.statusDefinedBy = statusDefinedBy;
}
private java.lang.Object __equalsCalc = null;
public synchronized boolean equals(java.lang.Object obj) {
if (!(obj instanceof Content)) return false;
Content other = (Content) obj;
if (obj == null) return false;
if (this == obj) return true;
if (__equalsCalc != null) {
return (__equalsCalc == obj);
}
__equalsCalc = obj;
boolean _equals;
_equals = true &&
((this.id==null && other.getId()==null) ||
(this.id!=null &&
this.id.equals(other.getId()))) &&
((this.name==null && other.getName()==null) ||
(this.name!=null &&
this.name.equals(other.getName()))) &&
((this.status==null && other.getStatus()==null) ||
(this.status!=null &&
this.status.equals(other.getStatus()))) &&
((this.statusDefinedBy==null && other.getStatusDefinedBy()==null) ||
(this.statusDefinedBy!=null &&
this.statusDefinedBy.equals(other.getStatusDefinedBy())));
__equalsCalc = null;
return _equals;
}
private boolean __hashCodeCalc = false;
public synchronized int hashCode() {
if (__hashCodeCalc) {
return 0;
}
__hashCodeCalc = true;
int _hashCode = 1;
if (getId() != null) {
_hashCode += getId().hashCode();
}
if (getName() != null) {
_hashCode += getName().hashCode();
}
if (getStatus() != null) {
_hashCode += getStatus().hashCode();
}
if (getStatusDefinedBy() != null) {
_hashCode += getStatusDefinedBy().hashCode();
}
__hashCodeCalc = false;
return _hashCode;
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(Content.class, true);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201211", "Content"));
org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("id");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201211", "id"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "long"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("name");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201211", "name"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("status");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201211", "status"));
elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201211", "ContentStatus"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("statusDefinedBy");
elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201211", "statusDefinedBy"));
elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201211", "ContentStatusDefinedBy"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
/**
* Get Custom Serializer
*/
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanSerializer(
_javaType, _xmlType, typeDesc);
}
/**
* Get Custom Deserializer
*/
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanDeserializer(
_javaType, _xmlType, typeDesc);
}
}
| apache-2.0 |
pablow91/TheResistance | app/src/main/java/eu/stosdev/theresistance/model/messages/VoteFinishedMessage.java | 1034 | package eu.stosdev.theresistance.model.messages;
import android.support.annotation.NonNull;
import java.util.Map;
import eu.stosdev.theresistance.model.messages.utils.AbsEvent;
import eu.stosdev.theresistance.model.messages.utils.AbsMessage;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
@AllArgsConstructor(access = AccessLevel.PUBLIC)
public class VoteFinishedMessage extends AbsMessage<VoteFinishedMessage.Event> {
private Map<String, Boolean> votes;
@NonNull @Override
public Event getEvent(String participantId) {
return new Event(participantId);
}
public class Event extends AbsEvent {
private boolean used;
private Event(String participantId) {
super(participantId);
}
public Map<String, Boolean> getVotes() {
used = true;
return votes;
}
public boolean isUsed() {
return used;
}
}
}
| apache-2.0 |
sbrossie/killbill | profiles/killbill/src/main/java/org/killbill/billing/server/filters/RequestDataFilter.java | 4158 | /*
* Copyright 2014-2016 Groupon, Inc
* Copyright 2014-2016 The Billing Project, LLC
*
* The Billing Project 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 org.killbill.billing.server.filters;
import java.io.OutputStream;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.inject.Singleton;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import org.glassfish.jersey.server.ContainerException;
import org.glassfish.jersey.server.ContainerRequest;
import org.glassfish.jersey.server.ContainerResponse;
import org.glassfish.jersey.server.spi.ContainerResponseWriter;
import org.killbill.billing.util.UUIDs;
import org.killbill.commons.request.Request;
import org.killbill.commons.request.RequestData;
@Singleton
public class RequestDataFilter implements ContainerRequestFilter, ContainerResponseFilter {
private static final String REQUEST_ID_HEADER = "X-Request-Id";
private static final String LEGACY_REQUEST_ID_HEADER = "X-Killbill-Request-Id-Req";
@Override
public void filter(final ContainerRequestContext requestContext) {
final List<String> requestIdHeaderRequests = getRequestId(requestContext);
final String requestId = (requestIdHeaderRequests == null || requestIdHeaderRequests.isEmpty()) ? UUIDs.randomUUID().toString() : requestIdHeaderRequests.get(0);
Request.setPerThreadRequestData(new RequestData(requestId));
}
@Override
public void filter(final ContainerRequestContext requestContext, final ContainerResponseContext responseContext) {
final ContainerRequest containerRequest = (ContainerRequest) requestContext;
containerRequest.setWriter(new Adapter(containerRequest.getResponseWriter()));
}
private List<String> getRequestId(final ContainerRequestContext requestContext) {
List<String> requestIds = requestContext.getHeaders().get(REQUEST_ID_HEADER);
if (requestIds == null || requestIds.isEmpty()) {
requestIds = requestContext.getHeaders().get(LEGACY_REQUEST_ID_HEADER);
}
return requestIds;
}
private static final class Adapter implements ContainerResponseWriter {
private final ContainerResponseWriter crw;
Adapter(final ContainerResponseWriter containerResponseWriter) {
this.crw = containerResponseWriter;
}
@Override
public OutputStream writeResponseStatusAndHeaders(final long contentLength, final ContainerResponse responseContext) throws ContainerException {
return crw.writeResponseStatusAndHeaders(contentLength, responseContext);
}
@Override
public boolean suspend(final long timeOut, final TimeUnit timeUnit, final TimeoutHandler timeoutHandler) {
return crw.suspend(timeOut, timeUnit, timeoutHandler);
}
@Override
public void setSuspendTimeout(final long timeOut, final TimeUnit timeUnit) throws IllegalStateException {
crw.setSuspendTimeout(timeOut, timeUnit);
}
@Override
public void commit() {
crw.commit();
// Reset the per-thread RequestData last
Request.resetPerThreadRequestData();
}
@Override
public void failure(final Throwable error) {
crw.failure(error);
}
@Override
public boolean enableResponseBuffering() {
return crw.enableResponseBuffering();
}
}
}
| apache-2.0 |
liyuzhao/enterpriseChat-android | src/com/easemob/chatuidemo/activity/VoiceCallActivity.java | 14957 | /**
* Copyright (C) 2013-2014 EaseMob Technologies. 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.
*/
package com.easemob.chatuidemo.activity;
import java.util.UUID;
import android.media.AudioManager;
import android.media.RingtoneManager;
import android.media.SoundPool;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.easemob.applib.controller.HXSDKHelper;
import com.easemob.chat.EMCallStateChangeListener;
import com.easemob.chat.EMChatManager;
import com.easemob.exceptions.EMServiceNotReadyException;
import com.easemob.qixin.R;
/**
* 语音通话页面
*
*/
public class VoiceCallActivity extends CallActivity implements OnClickListener {
private LinearLayout comingBtnContainer;
private Button hangupBtn;
private Button refuseBtn;
private Button answerBtn;
private ImageView muteImage;
private ImageView handsFreeImage;
private boolean isMuteState;
private boolean isHandsfreeState;
private TextView callStateTextView;
private int streamID;
private boolean endCallTriggerByMe = false;
private Handler handler = new Handler();
private TextView nickTextView;
private TextView durationTextView;
private Chronometer chronometer;
String st1;
private boolean isAnswered;
private LinearLayout voiceContronlLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(savedInstanceState != null){
finish();
return;
}
setContentView(R.layout.activity_voice_call);
HXSDKHelper.getInstance().isVoiceCalling = true;
comingBtnContainer = (LinearLayout) findViewById(R.id.ll_coming_call);
refuseBtn = (Button) findViewById(R.id.btn_refuse_call);
answerBtn = (Button) findViewById(R.id.btn_answer_call);
hangupBtn = (Button) findViewById(R.id.btn_hangup_call);
muteImage = (ImageView) findViewById(R.id.iv_mute);
handsFreeImage = (ImageView) findViewById(R.id.iv_handsfree);
callStateTextView = (TextView) findViewById(R.id.tv_call_state);
nickTextView = (TextView) findViewById(R.id.tv_nick);
durationTextView = (TextView) findViewById(R.id.tv_calling_duration);
chronometer = (Chronometer) findViewById(R.id.chronometer);
voiceContronlLayout = (LinearLayout) findViewById(R.id.ll_voice_control);
refuseBtn.setOnClickListener(this);
answerBtn.setOnClickListener(this);
hangupBtn.setOnClickListener(this);
muteImage.setOnClickListener(this);
handsFreeImage.setOnClickListener(this);
getWindow().addFlags(
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
| WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
// 注册语音电话的状态的监听
addCallStateListener();
msgid = UUID.randomUUID().toString();
username = getIntent().getStringExtra("username");
// 语音电话是否为接收的
isInComingCall = getIntent().getBooleanExtra("isComingCall", false);
// 设置通话人
nickTextView.setText(username);
if (!isInComingCall) {// 拨打电话
soundPool = new SoundPool(1, AudioManager.STREAM_RING, 0);
outgoing = soundPool.load(this, R.raw.outgoing, 1);
comingBtnContainer.setVisibility(View.INVISIBLE);
hangupBtn.setVisibility(View.VISIBLE);
st1 = getResources().getString(R.string.Are_connected_to_each_other);
callStateTextView.setText(st1);
handler.postDelayed(new Runnable() {
public void run() {
streamID = playMakeCallSounds();
}
}, 300);
try {
// 拨打语音电话
EMChatManager.getInstance().makeVoiceCall(username);
} catch (EMServiceNotReadyException e) {
e.printStackTrace();
final String st2 = getResources().getString(R.string.Is_not_yet_connected_to_the_server);
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(VoiceCallActivity.this, st2, 0).show();
}
});
}
} else { // 有电话进来
voiceContronlLayout.setVisibility(View.INVISIBLE);
Uri ringUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
audioManager.setMode(AudioManager.MODE_RINGTONE);
audioManager.setSpeakerphoneOn(true);
ringtone = RingtoneManager.getRingtone(this, ringUri);
ringtone.play();
}
}
/**
* 设置电话监听
*/
void addCallStateListener() {
callStateListener = new EMCallStateChangeListener() {
@Override
public void onCallStateChanged(CallState callState, CallError error) {
// Message msg = handler.obtainMessage();
switch (callState) {
case CONNECTING: // 正在连接对方
runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
callStateTextView.setText(st1);
}
});
break;
case CONNECTED: // 双方已经建立连接
runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
String st3 = getResources().getString(R.string.have_connected_with);
callStateTextView.setText(st3);
}
});
break;
case ACCEPTED: // 电话接通成功
runOnUiThread(new Runnable() {
@Override
public void run() {
try {
if (soundPool != null)
soundPool.stop(streamID);
} catch (Exception e) {
}
if(!isHandsfreeState)
closeSpeakerOn();
//显示是否为直连,方便测试
((TextView)findViewById(R.id.tv_is_p2p)).setText(EMChatManager.getInstance().isDirectCall()
? R.string.direct_call : R.string.relay_call);
chronometer.setVisibility(View.VISIBLE);
chronometer.setBase(SystemClock.elapsedRealtime());
// 开始记时
chronometer.start();
String str4 = getResources().getString(R.string.In_the_call);
callStateTextView.setText(str4);
callingState = CallingState.NORMAL;
}
});
break;
case DISCONNNECTED: // 电话断了
final CallError fError = error;
runOnUiThread(new Runnable() {
private void postDelayedCloseMsg() {
handler.postDelayed(new Runnable() {
@Override
public void run() {
saveCallRecord(0);
Animation animation = new AlphaAnimation(1.0f, 0.0f);
animation.setDuration(800);
findViewById(R.id.root_layout).startAnimation(animation);
finish();
}
}, 200);
}
@Override
public void run() {
chronometer.stop();
callDruationText = chronometer.getText().toString();
String st2 = getResources().getString(R.string.The_other_party_refused_to_accept);
String st3 = getResources().getString(R.string.Connection_failure);
String st4 = getResources().getString(R.string.The_other_party_is_not_online);
String st5 = getResources().getString(R.string.The_other_is_on_the_phone_please);
String st6 = getResources().getString(R.string.The_other_party_did_not_answer_new);
String st7 = getResources().getString(R.string.hang_up);
String st8 = getResources().getString(R.string.The_other_is_hang_up);
String st9 = getResources().getString(R.string.did_not_answer);
String st10 = getResources().getString(R.string.Has_been_cancelled);
String st11 = getResources().getString(R.string.hang_up);
if (fError == CallError.REJECTED) {
callingState = CallingState.BEREFUESD;
callStateTextView.setText(st2);
} else if (fError == CallError.ERROR_TRANSPORT) {
callStateTextView.setText(st3);
} else if (fError == CallError.ERROR_INAVAILABLE) {
callingState = CallingState.OFFLINE;
callStateTextView.setText(st4);
} else if (fError == CallError.ERROR_BUSY) {
callingState = CallingState.BUSY;
callStateTextView.setText(st5);
} else if (fError == CallError.ERROR_NORESPONSE) {
callingState = CallingState.NORESPONSE;
callStateTextView.setText(st6);
} else {
if (isAnswered) {
callingState = CallingState.NORMAL;
if (endCallTriggerByMe) {
// callStateTextView.setText(st7);
} else {
callStateTextView.setText(st8);
}
} else {
if (isInComingCall) {
callingState = CallingState.UNANSWERED;
callStateTextView.setText(st9);
} else {
if (callingState != CallingState.NORMAL) {
callingState = CallingState.CANCED;
callStateTextView.setText(st10);
}else {
callStateTextView.setText(st11);
}
}
}
}
postDelayedCloseMsg();
}
});
break;
default:
break;
}
}
};
EMChatManager.getInstance().addCallStateChangeListener(callStateListener);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_refuse_call: // 拒绝接听
refuseBtn.setEnabled(false);
if (ringtone != null)
ringtone.stop();
try {
EMChatManager.getInstance().rejectCall();
} catch (Exception e1) {
e1.printStackTrace();
saveCallRecord(0);
finish();
}
callingState = CallingState.REFUESD;
break;
case R.id.btn_answer_call: // 接听电话
answerBtn.setEnabled(false);
if (ringtone != null)
ringtone.stop();
if (isInComingCall) {
try {
callStateTextView.setText("正在接听...");
EMChatManager.getInstance().answerCall();
isAnswered = true;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
saveCallRecord(0);
finish();
return;
}
}
comingBtnContainer.setVisibility(View.INVISIBLE);
hangupBtn.setVisibility(View.VISIBLE);
voiceContronlLayout.setVisibility(View.VISIBLE);
closeSpeakerOn();
break;
case R.id.btn_hangup_call: // 挂断电话
hangupBtn.setEnabled(false);
if (soundPool != null)
soundPool.stop(streamID);
chronometer.stop();
endCallTriggerByMe = true;
callStateTextView.setText(getResources().getString(R.string.hanging_up));
try {
EMChatManager.getInstance().endCall();
} catch (Exception e) {
e.printStackTrace();
saveCallRecord(0);
finish();
}
break;
case R.id.iv_mute: // 静音开关
if (isMuteState) {
// 关闭静音
muteImage.setImageResource(R.drawable.icon_mute_normal);
audioManager.setMicrophoneMute(false);
isMuteState = false;
} else {
// 打开静音
muteImage.setImageResource(R.drawable.icon_mute_on);
audioManager.setMicrophoneMute(true);
isMuteState = true;
}
break;
case R.id.iv_handsfree: // 免提开关
if (isHandsfreeState) {
// 关闭免提
handsFreeImage.setImageResource(R.drawable.icon_speaker_normal);
closeSpeakerOn();
isHandsfreeState = false;
} else {
handsFreeImage.setImageResource(R.drawable.icon_speaker_on);
openSpeakerOn();
isHandsfreeState = true;
}
break;
default:
break;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
HXSDKHelper.getInstance().isVoiceCalling = false;
}
@Override
public void onBackPressed() {
EMChatManager.getInstance().endCall();
callDruationText = chronometer.getText().toString();
saveCallRecord(0);
finish();
}
}
| apache-2.0 |
xasx/camunda-bpm-platform | qa/test-db-instance-migration/test-migration/src/test/java/org/camunda/bpm/qa/upgrade/scenarios720/eventsubprocess/NestedParallelNonInterruptingEventSubprocessScenarioTest.java | 8570 | /*
* Copyright © 2013-2018 camunda services GmbH and various authors (info@camunda.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 org.camunda.bpm.qa.upgrade.scenarios720.eventsubprocess;
import static org.camunda.bpm.qa.upgrade.util.ActivityInstanceAssert.assertThat;
import static org.camunda.bpm.qa.upgrade.util.ActivityInstanceAssert.describeActivityInstanceTree;
import org.camunda.bpm.engine.runtime.ActivityInstance;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.camunda.bpm.engine.task.Task;
import org.camunda.bpm.qa.upgrade.Origin;
import org.camunda.bpm.qa.upgrade.ScenarioUnderTest;
import org.camunda.bpm.qa.upgrade.UpgradeTestRule;
import org.camunda.bpm.qa.upgrade.util.ThrowBpmnErrorDelegate;
import org.camunda.bpm.qa.upgrade.util.ThrowBpmnErrorDelegate.ThrowBpmnErrorDelegateException;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
@ScenarioUnderTest("NestedParallelNonInterruptingEventSubprocessScenario")
@Origin("7.2.0")
public class NestedParallelNonInterruptingEventSubprocessScenarioTest {
@Rule
public UpgradeTestRule rule = new UpgradeTestRule();
@Test
@ScenarioUnderTest("init.1")
public void testInitCompletionCase1() {
// given
Task innerTask = rule.taskQuery().taskDefinitionKey("innerTask").singleResult();
Task eventSubprocessTask1 = rule.taskQuery().taskDefinitionKey("eventSubProcessTask1").singleResult();
Task eventSubprocessTask2 = rule.taskQuery().taskDefinitionKey("eventSubProcessTask2").singleResult();
// when
rule.getTaskService().complete(innerTask.getId());
rule.getTaskService().complete(eventSubprocessTask1.getId());
rule.getTaskService().complete(eventSubprocessTask2.getId());
// then
rule.assertScenarioEnded();
}
@Test
@ScenarioUnderTest("init.2")
public void testInitCompletionCase2() {
// given
Task innerTask = rule.taskQuery().taskDefinitionKey("innerTask").singleResult();
Task eventSubprocessTask1 = rule.taskQuery().taskDefinitionKey("eventSubProcessTask1").singleResult();
Task eventSubprocessTask2 = rule.taskQuery().taskDefinitionKey("eventSubProcessTask2").singleResult();
// when
rule.getTaskService().complete(eventSubprocessTask1.getId());
rule.getTaskService().complete(eventSubprocessTask2.getId());
rule.getTaskService().complete(innerTask.getId());
// then
rule.assertScenarioEnded();
}
@Test
@ScenarioUnderTest("init.3")
public void testInitActivityInstanceTree() {
// given
ProcessInstance instance = rule.processInstance();
// when
ActivityInstance activityInstance = rule.getRuntimeService().getActivityInstance(instance.getId());
// then
Assert.assertNotNull(activityInstance);
assertThat(activityInstance).hasStructure(
describeActivityInstanceTree(instance.getProcessDefinitionId())
.beginScope("subProcess")
.activity("innerTask")
// eventSubProcess was previously no scope so it misses here
.activity("eventSubProcessTask1")
.activity("eventSubProcessTask2")
.done());
}
@Test
@ScenarioUnderTest("init.4")
public void testInitDeletion() {
// given
ProcessInstance instance = rule.processInstance();
// when
rule.getRuntimeService().deleteProcessInstance(instance.getId(), null);
// then
rule.assertScenarioEnded();
}
@Test
@ScenarioUnderTest("init.5")
public void testInitThrowError() {
// given
ProcessInstance instance = rule.processInstance();
Task eventSubprocessTask = rule.taskQuery().taskDefinitionKey("eventSubProcessTask1").singleResult();
// when
rule.getRuntimeService().setVariable(instance.getId(), ThrowBpmnErrorDelegate.ERROR_INDICATOR_VARIABLE, true);
rule.getTaskService().complete(eventSubprocessTask.getId());
// then
Task escalatedTask = rule.taskQuery().singleResult();
Assert.assertEquals("escalatedTask", escalatedTask.getTaskDefinitionKey());
Assert.assertNotNull(escalatedTask);
rule.getTaskService().complete(escalatedTask.getId());
rule.assertScenarioEnded();
}
@Test
@ScenarioUnderTest("init.6")
public void testInitThrowUnhandledException() {
// given
ProcessInstance instance = rule.processInstance();
Task eventSubprocessTask = rule.taskQuery().taskDefinitionKey("eventSubProcessTask1").singleResult();
// when
rule.getRuntimeService().setVariable(instance.getId(), ThrowBpmnErrorDelegate.EXCEPTION_INDICATOR_VARIABLE, true);
rule.getRuntimeService().setVariable(instance.getId(), ThrowBpmnErrorDelegate.EXCEPTION_MESSAGE_VARIABLE, "unhandledException");
// then
try {
rule.getTaskService().complete(eventSubprocessTask.getId());
Assert.fail("should throw a ThrowBpmnErrorDelegateException");
} catch (ThrowBpmnErrorDelegateException e) {
Assert.assertEquals("unhandledException", e.getMessage());
}
}
@Test
@ScenarioUnderTest("init.innerTask.1")
public void testInitInnerTaskCompletion() {
// given
Task eventSubprocessTask1 = rule.taskQuery().taskDefinitionKey("eventSubProcessTask1").singleResult();
Task eventSubprocessTask2 = rule.taskQuery().taskDefinitionKey("eventSubProcessTask2").singleResult();
// when
rule.getTaskService().complete(eventSubprocessTask1.getId());
rule.getTaskService().complete(eventSubprocessTask2.getId());
// then
rule.assertScenarioEnded();
}
@Test
@ScenarioUnderTest("init.innerTask.2")
public void testInitInnerTaskActivityInstanceTree() {
// given
ProcessInstance instance = rule.processInstance();
// when
ActivityInstance activityInstance = rule.getRuntimeService().getActivityInstance(instance.getId());
// then
Assert.assertNotNull(activityInstance);
assertThat(activityInstance).hasStructure(
describeActivityInstanceTree(instance.getProcessDefinitionId())
.beginScope("subProcess")
// eventSubProcess was previously no scope so it misses here
.activity("eventSubProcessTask1")
.activity("eventSubProcessTask2")
.done());
}
@Test
@ScenarioUnderTest("init.innerTask.3")
public void testInitInnerTaskDeletion() {
// given
ProcessInstance instance = rule.processInstance();
// when
rule.getRuntimeService().deleteProcessInstance(instance.getId(), null);
// then
rule.assertScenarioEnded();
}
@Test
@ScenarioUnderTest("init.innerTask.4")
public void testInitInnerTaskThrowError() {
// given
ProcessInstance instance = rule.processInstance();
Task eventSubprocessTask = rule.taskQuery().taskDefinitionKey("eventSubProcessTask1").singleResult();
// when
rule.getRuntimeService().setVariable(instance.getId(), ThrowBpmnErrorDelegate.ERROR_INDICATOR_VARIABLE, true);
rule.getTaskService().complete(eventSubprocessTask.getId());
// then
Task escalatedTask = rule.taskQuery().singleResult();
Assert.assertEquals("escalatedTask", escalatedTask.getTaskDefinitionKey());
Assert.assertNotNull(escalatedTask);
rule.getTaskService().complete(escalatedTask.getId());
rule.assertScenarioEnded();
}
@Test
@ScenarioUnderTest("init.innerTask.5")
public void testInitInnerTaskThrowUnhandledException() {
// given
ProcessInstance instance = rule.processInstance();
Task eventSubprocessTask = rule.taskQuery().taskDefinitionKey("eventSubProcessTask1").singleResult();
// when
rule.getRuntimeService().setVariable(instance.getId(), ThrowBpmnErrorDelegate.EXCEPTION_INDICATOR_VARIABLE, true);
rule.getRuntimeService().setVariable(instance.getId(), ThrowBpmnErrorDelegate.EXCEPTION_MESSAGE_VARIABLE, "unhandledException");
// then
try {
rule.getTaskService().complete(eventSubprocessTask.getId());
Assert.fail("should throw a ThrowBpmnErrorDelegateException");
} catch (ThrowBpmnErrorDelegateException e) {
Assert.assertEquals("unhandledException", e.getMessage());
}
}
}
| apache-2.0 |
ullgren/camel | components/camel-platform-http-vertx/src/main/java/org/apache/camel/component/platform/http/vertx/VertxPlatformHttpConsumer.java | 9366 | /*
* 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 org.apache.camel.component.platform.http.vertx;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import io.vertx.core.Handler;
import io.vertx.core.MultiMap;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpMethod;
import io.vertx.ext.web.FileUpload;
import io.vertx.ext.web.Route;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.Processor;
import org.apache.camel.component.platform.http.PlatformHttpEndpoint;
import org.apache.camel.component.platform.http.spi.Method;
import org.apache.camel.component.platform.http.spi.UploadAttacher;
import org.apache.camel.spi.HeaderFilterStrategy;
import org.apache.camel.support.DefaultConsumer;
import org.apache.camel.support.DefaultMessage;
import org.apache.camel.util.FileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.apache.camel.component.platform.http.vertx.VertxPlatformHttpSupport.appendHeader;
import static org.apache.camel.component.platform.http.vertx.VertxPlatformHttpSupport.populateCamelHeaders;
import static org.apache.camel.component.platform.http.vertx.VertxPlatformHttpSupport.writeResponse;
/**
* A {@link org.apache.camel.Consumer} for the {@link org.apache.camel.component.platform.http.spi.PlatformHttpEngine}
* based on Vert.x Web.
*/
public class VertxPlatformHttpConsumer extends DefaultConsumer {
private static final Logger LOGGER = LoggerFactory.getLogger(VertxPlatformHttpConsumer.class);
private static final Pattern PATH_PARAMETER_PATTERN = Pattern.compile("\\{([^/}]+)\\}");
private final Router router;
private final List<Handler<RoutingContext>> handlers;
private final String fileNameExtWhitelist;
private final UploadAttacher uploadAttacher;
private Route route;
public VertxPlatformHttpConsumer(PlatformHttpEndpoint endpoint, Processor processor, Router router,
List<Handler<RoutingContext>> handlers, UploadAttacher uploadAttacher) {
super(endpoint, processor);
this.router = router;
this.handlers = handlers;
String list = endpoint.getFileNameExtWhitelist();
this.fileNameExtWhitelist = list == null ? null : list.toLowerCase(Locale.US);
this.uploadAttacher = uploadAttacher;
}
@Override
public PlatformHttpEndpoint getEndpoint() {
return (PlatformHttpEndpoint) super.getEndpoint();
}
@Override
protected void doStart() throws Exception {
super.doStart();
final PlatformHttpEndpoint endpoint = getEndpoint();
final String path = endpoint.getPath();
// Transform from the Camel path param syntax /path/{key} to vert.x web's /path/:key
final String vertxPathParamPath = PATH_PARAMETER_PATTERN.matcher(path).replaceAll(":$1");
final Route newRoute = router.route(vertxPathParamPath);
final Set<Method> methods = Method.parseList(endpoint.getHttpMethodRestrict());
if (!methods.equals(Method.getAll())) {
methods.stream().forEach(m -> newRoute.method(HttpMethod.valueOf(m.name())));
}
if (endpoint.getConsumes() != null) {
newRoute.consumes(endpoint.getConsumes());
}
if (endpoint.getProduces() != null) {
newRoute.produces(endpoint.getProduces());
}
handlers.forEach(newRoute::handler);
newRoute.handler(
ctx -> {
Exchange exchg = null;
try {
final Exchange exchange = exchg = toExchange(ctx);
createUoW(exchange);
getAsyncProcessor().process(
exchange,
doneSync -> writeResponse(ctx, exchange, getEndpoint().getHeaderFilterStrategy()));
} catch (Exception e) {
ctx.fail(e);
getExceptionHandler().handleException("Failed handling platform-http endpoint " + path, exchg, e);
} finally {
if (exchg != null) {
doneUoW(exchg);
}
}
});
this.route = newRoute;
}
@Override
protected void doStop() throws Exception {
if (route != null) {
route.remove();
route = null;
}
super.doStop();
}
@Override
protected void doSuspend() throws Exception {
if (route != null) {
route.disable();
}
super.doSuspend();
}
@Override
protected void doResume() throws Exception {
if (route != null) {
route.enable();
}
super.doResume();
}
private Exchange toExchange(RoutingContext ctx) {
final Exchange exchange = getEndpoint().createExchange();
Message in = toCamelMessage(ctx, exchange);
final String charset = ctx.parsedHeaders().contentType().parameter("charset");
if (charset != null) {
exchange.setProperty(Exchange.CHARSET_NAME, charset);
in.setHeader(Exchange.HTTP_CHARACTER_ENCODING, charset);
}
exchange.setIn(in);
return exchange;
}
private Message toCamelMessage(RoutingContext ctx, Exchange exchange) {
final Message result = new DefaultMessage(exchange);
final HeaderFilterStrategy headerFilterStrategy = getEndpoint().getHeaderFilterStrategy();
populateCamelHeaders(ctx, result.getHeaders(), exchange, headerFilterStrategy);
final String mimeType = ctx.parsedHeaders().contentType().value();
final boolean isMultipartFormData = "multipart/form-data".equals(mimeType);
if ("application/x-www-form-urlencoded".equals(mimeType) || isMultipartFormData) {
final MultiMap formData = ctx.request().formAttributes();
final Map<String, Object> body = new HashMap<>();
for (String key : formData.names()) {
for (String value : formData.getAll(key)) {
if (headerFilterStrategy != null
&& !headerFilterStrategy.applyFilterToExternalHeaders(key, value, exchange)) {
appendHeader(result.getHeaders(), key, value);
appendHeader(body, key, value);
}
}
}
result.setBody(body);
if (isMultipartFormData) {
populateAttachments(ctx.fileUploads(), result);
}
} else {
// extract body by myself if undertow parser didn't handle and the method is allowed to have one
// body is extracted as byte[] then auto TypeConverter kicks in
Method m = Method.valueOf(ctx.request().method().name());
if (m.canHaveBody()) {
final Buffer body = ctx.getBody();
if (body != null) {
result.setBody(body.getBytes());
} else {
result.setBody(null);
}
} else {
result.setBody(null);
}
}
return result;
}
private void populateAttachments(Set<FileUpload> uploads, Message message) {
for (FileUpload upload : uploads) {
final String name = upload.name();
final String fileName = upload.fileName();
LOGGER.trace("HTTP attachment {} = {}", name, fileName);
// is the file name accepted
boolean accepted = true;
if (fileNameExtWhitelist != null) {
String ext = FileUtil.onlyExt(fileName);
if (ext != null) {
ext = ext.toLowerCase(Locale.US);
if (!fileNameExtWhitelist.equals("*") && !fileNameExtWhitelist.contains(ext)) {
accepted = false;
}
}
}
if (accepted) {
final File localFile = new File(upload.uploadedFileName());
uploadAttacher.attachUpload(localFile, fileName, message);
} else {
LOGGER.debug(
"Cannot add file as attachment: {} because the file is not accepted according to fileNameExtWhitelist: {}",
fileName, fileNameExtWhitelist);
}
}
}
}
| apache-2.0 |
avarabyeu/restendpoint | src/main/java/com/github/avarabyeu/restendpoint/http/ErrorHandler.java | 1364 | /*
* Copyright (C) 2014 Andrei Varabyeu
*
* 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.github.avarabyeu.restendpoint.http;
import com.github.avarabyeu.restendpoint.http.exception.RestEndpointIOException;
import com.google.common.io.ByteSource;
/**
* Error Handler for RestEndpoint
*
* @author Andrei Varabyeu
*/
public interface ErrorHandler {
/**
* Checks whether there is an error in response
*
* @param rs response instance
* @return TRUE if response contains error
*/
boolean hasError(Response<ByteSource> rs);
/**
* Handles response if there is an error
*
* @param rs response instance
* @throws com.github.avarabyeu.restendpoint.http.exception.RestEndpointIOException In case of error
*/
void handle(Response<ByteSource> rs) throws RestEndpointIOException;
}
| apache-2.0 |
jtgeiger/grison | demo/src/main/java/com/sibilantsolutions/grison/Grison.java | 2832 | package com.sibilantsolutions.grison;
import java.io.IOException;
import java.net.SocketException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ConfigurableApplicationContext;
import io.reactivex.rxjava3.exceptions.UndeliverableException;
import io.reactivex.rxjava3.plugins.RxJavaPlugins;
/**
* Grisons, also known as South American wolverines, are mustelids native to Central and South America.
* -- Wikipedia
*/
@SpringBootApplication
public class Grison {
final static private Logger logger = LoggerFactory.getLogger(Grison.class);
static public void main(final String[] args) {
logger.info("main started.");
rxInit();
try {
SpringApplicationBuilder builder = new SpringApplicationBuilder(Grison.class);
builder.headless(false);
ConfigurableApplicationContext ctx = builder.run(args);
logger.info("main finished: ctx={}.", ctx);
} catch (Exception e) {
logger.error("Exiting because initialization failed.");
System.exit(9);
}
}
private static void rxInit() {
RxJavaPlugins.setErrorHandler(e -> {
boolean isUndeliverableException = false;
if (e instanceof UndeliverableException) {
isUndeliverableException = true;
e = e.getCause();
}
if (e instanceof SocketException) {
// fine, irrelevant network problem or API that throws on cancellation
return;
}
if (e instanceof IOException) {
// fine, irrelevant network problem or API that throws on cancellation
return;
}
if (e instanceof InterruptedException) {
// fine, some blocking code was interrupted by a dispose call
return;
}
if ((e instanceof NullPointerException) || (e instanceof IllegalArgumentException)) {
// that's likely a bug in the application
Thread.currentThread().getUncaughtExceptionHandler()
.uncaughtException(Thread.currentThread(), e);
return;
}
if (e instanceof IllegalStateException) {
// that's a bug in RxJava or in a custom operator
Thread.currentThread().getUncaughtExceptionHandler()
.uncaughtException(Thread.currentThread(), e);
return;
}
logger.warn("Undeliverable exception received, not sure what to do (source was UE={})", isUndeliverableException, e);
});
}
}
| apache-2.0 |
flumebase/flumebase | src/main/java/com/odiago/flumebase/exec/DummyExecEnv.java | 2989 | /**
* Licensed to Odiago, Inc. under one or more contributor license
* agreements. See the NOTICE.txt file distributed with this work for
* additional information regarding copyright ownership. Odiago, Inc.
* 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 com.odiago.flumebase.exec;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.odiago.flumebase.plan.FlowSpecification;
import com.odiago.flumebase.server.SessionId;
/**
* Execution engine that logs an error for every operation. This execution engine
* is used when the client is not connected to any other execution engine.
*/
public class DummyExecEnv extends ExecEnvironment {
private static final Logger LOG = LoggerFactory.getLogger(
DummyExecEnv.class.getName());
@Override
public SessionId connect() {
// Do nothing.
return new SessionId(0);
}
@Override
public boolean isConnected() {
return false; // Never connected.
}
@Override
public String getEnvName() {
return "dummy";
}
@Override
public QuerySubmitResponse submitQuery(String query, Map<String, String> options) {
return new QuerySubmitResponse("Not connected", null);
}
@Override
public FlowId addFlow(FlowSpecification spec) {
LOG.error("Not connected");
return null;
}
@Override
public void cancelFlow(FlowId id) {
LOG.error("Not connected");
}
@Override
public Map<FlowId, FlowInfo> listFlows() {
LOG.error("Not connected");
return new HashMap<FlowId, FlowInfo>();
}
@Override
public void joinFlow(FlowId id) {
LOG.error("Not connected");
}
@Override
public boolean joinFlow(FlowId id, long timeout) {
LOG.error("Not connected");
return false;
}
@Override
public void watchFlow(SessionId sessionId, FlowId flowId) {
LOG.error("Not connected");
}
@Override
public void unwatchFlow(SessionId sessionId, FlowId flowId) {
LOG.error("Not connected");
}
@Override
public List<FlowId> listWatchedFlows(SessionId sessionId) {
return Collections.emptyList();
}
@Override
public void setFlowName(FlowId flowId, String name) {
LOG.error("Not connected");
}
@Override
public void disconnect(SessionId sessionId) {
// Do nothing.
}
@Override
public void shutdown() {
LOG.error("Cannot shut down: Not connected.");
}
}
| apache-2.0 |
talsma-ict/umldoclet | src/plantuml-asl/src/net/sourceforge/plantuml/help/CommandHelpFont.java | 2606 | /* ========================================================================
* PlantUML : a free UML diagram generator
* ========================================================================
*
* (C) Copyright 2009-2020, Arnaud Roques
*
* Project Info: https://plantuml.com
*
* If you like this project or if you find it useful, you can support us at:
*
* https://plantuml.com/patreon (only 1$ per month!)
* https://plantuml.com/paypal
*
* This file is part of PlantUML.
*
* 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.
*
*
* Original Author: Arnaud Roques
*/
package net.sourceforge.plantuml.help;
import java.awt.GraphicsEnvironment;
import net.sourceforge.plantuml.LineLocation;
import net.sourceforge.plantuml.command.CommandExecutionResult;
import net.sourceforge.plantuml.command.SingleLineCommand2;
import net.sourceforge.plantuml.command.regex.IRegex;
import net.sourceforge.plantuml.command.regex.RegexConcat;
import net.sourceforge.plantuml.command.regex.RegexLeaf;
import net.sourceforge.plantuml.command.regex.RegexResult;
public class CommandHelpFont extends SingleLineCommand2<Help> {
public CommandHelpFont() {
super(getRegexConcat());
}
static IRegex getRegexConcat() {
return RegexConcat.build(CommandHelpFont.class.getName(), RegexLeaf.start(), //
new RegexLeaf("help"), //
RegexLeaf.spaceOneOrMore(), //
new RegexLeaf("fonts?"), RegexLeaf.end());
}
@Override
protected CommandExecutionResult executeArg(Help diagram, LineLocation location, RegexResult arg) {
diagram.add("<b>Help on font");
diagram.add(" ");
diagram.add("The code of this command is located in <i>net.sourceforge.plantuml.help</i> package.");
diagram.add("You may improve it on <i>https://github.com/plantuml/plantuml/tree/master/src/net/sourceforge/plantuml/help</i>");
diagram.add(" ");
diagram.add(" The possible font on your system are :");
final String name[] = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
for (String n : name) {
diagram.add("* " + n);
}
return CommandExecutionResult.ok();
}
}
| apache-2.0 |
RobAltena/deeplearning4j | nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/api/ops/impl/shape/Reshape.java | 4835 | /*******************************************************************************
* Copyright (c) 2015-2018 Skymind, Inc.
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available 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.
*
* SPDX-License-Identifier: Apache-2.0
******************************************************************************/
package org.nd4j.linalg.api.ops.impl.shape;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import onnx.Onnx;
import org.nd4j.autodiff.samediff.SDVariable;
import org.nd4j.autodiff.samediff.SameDiff;
import org.nd4j.imports.descriptors.properties.PropertyMapping;
import org.nd4j.linalg.api.buffer.DataType;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.api.ops.DynamicCustomOp;
import org.tensorflow.framework.AttrValue;
import org.tensorflow.framework.GraphDef;
import org.tensorflow.framework.NodeDef;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Reshape function
*
* @author Adam Gibson
*/
@Slf4j
public class Reshape extends DynamicCustomOp {
private long[] shape;
private String arrName;
public Reshape(SameDiff sameDiff, SDVariable i_v, long[] shape) {
super(null, sameDiff, new SDVariable[]{i_v});
this.shape = shape;
addIArgument(shape);
}
public Reshape(SameDiff sameDiff, SDVariable i_v, SDVariable shape) {
super(null, sameDiff, new SDVariable[]{i_v, shape});
}
public Reshape(INDArray in, INDArray shape, INDArray out){
super(null, new INDArray[]{in, shape}, new INDArray[]{out}, null, (List<Integer>)null);
}
public Reshape() {
}
@Override
public void initFromTensorFlow(NodeDef nodeDef, SameDiff initWith, Map<String, AttrValue> attributesForNode, GraphDef graph) {
if (!nodeDef.containsAttr("TShape") && nodeDef.getInputCount() == 1) {
this.shape = new long[]{};
return;
} else if(nodeDef.getInputCount() == 1){
val shape = nodeDef.getAttrOrThrow("Tshape");
if (!shape.hasShape()) {
val shapeRet = new long[2];
shapeRet[0] = 1;
shapeRet[1] = shape.getValueCase().getNumber();
this.shape = shapeRet;
} else {
val shapeVals = shape.getShape().getDimList();
if (shapeVals.size() > 1) {
this.shape = new long[shapeVals.size()];
for (int i = 0; i < shapeVals.size(); i++) {
this.shape[i] = (int) shapeVals.get(i).getSize();
}
} else {
this.shape = new long[2];
this.shape[0] = 1;
this.shape[1] = (int) shapeVals.get(0).getSize();
}
}
//all TF is c
if (this.shape != null) {
addIArgument(this.shape);
}
}
}
@Override
public void initFromOnnx(Onnx.NodeProto node, SameDiff initWith, Map<String, Onnx.AttributeProto> attributesForNode, Onnx.GraphProto graph) {
}
@Override
public Map<String, Map<String, PropertyMapping>> mappingsForFunction() {
Map<String, Map<String, PropertyMapping>> ret = new HashMap<>();
Map<String, PropertyMapping> map = new HashMap<>();
val shapeMapping = PropertyMapping.builder()
.onnxAttrName("shape")
.tfInputPosition(-1)
.propertyNames(new String[]{"shape"})
.build();
map.put("shape", shapeMapping);
ret.put(tensorflowName(), map);
ret.put(onnxName(), map);
return ret;
}
@Override
public String opName() {
return "reshape";
}
@Override
public String onnxName() {
return "Reshape";
}
@Override
public String tensorflowName() {
return "Reshape";
}
@Override
public List<SDVariable> doDiff(List<SDVariable> i_v) {
SDVariable origShape = f().shape(arg());
SDVariable ret = f().reshape(i_v.get(0), origShape);
return Collections.singletonList(ret);
}
@Override
public List<DataType> calculateOutputDataTypes(List<DataType> dataTypes){
//Output type is always same as input type
return Collections.singletonList(dataTypes.get(0));
}
}
| apache-2.0 |
kiritbasu/datacollector | commonlib/src/main/java/com/streamsets/pipeline/lib/parser/sdcrecord/SdcRecordDataParserFactory.java | 2224 | /**
* 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 com.streamsets.pipeline.lib.parser.sdcrecord;
import com.streamsets.pipeline.api.impl.Utils;
import com.streamsets.pipeline.lib.io.OverrunReader;
import com.streamsets.pipeline.lib.parser.DataParserFactory;
import com.streamsets.pipeline.lib.parser.DataParser;
import com.streamsets.pipeline.lib.parser.DataParserException;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
public class SdcRecordDataParserFactory extends DataParserFactory {
public static final Map<String, Object> CONFIGS = Collections.emptyMap();
public static final Set<Class<? extends Enum>> MODES = Collections.emptySet();
public SdcRecordDataParserFactory(Settings settings) {
super(settings);
}
@Override
public DataParser getParser(String id, InputStream is, long offset) throws DataParserException {
try {
return new SdcRecordDataParser(getSettings().getContext(), is, offset,
getSettings().getMaxRecordLen());
} catch (IOException ex) {
throw new DataParserException(Errors.SDC_RECORD_PARSER_00, id, offset, ex.toString(), ex);
}
}
@Override
public DataParser getParser(String id, Reader reader, long offset) throws DataParserException {
throw new UnsupportedOperationException(Utils.format("{} does not support character based data", getClass().getName()));
}
}
| apache-2.0 |
romanoid/buck | test/com/facebook/buck/artifact_cache/ArtifactCachesIntegrationTest.java | 25258 | /*
* Copyright 2018-present Facebook, 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.facebook.buck.artifact_cache;
import com.facebook.buck.artifact_cache.config.ArtifactCacheBuckConfig;
import com.facebook.buck.artifact_cache.thrift.BuckCacheFetchResponse;
import com.facebook.buck.artifact_cache.thrift.BuckCacheResponse;
import com.facebook.buck.artifact_cache.thrift.BuckCacheStoreResponse;
import com.facebook.buck.core.cell.CellPathResolver;
import com.facebook.buck.core.cell.TestCellPathResolver;
import com.facebook.buck.core.model.BuildId;
import com.facebook.buck.core.model.BuildTargetFactory;
import com.facebook.buck.core.model.TargetConfigurationSerializerForTests;
import com.facebook.buck.core.parser.buildtargetparser.ParsingUnconfiguredBuildTargetFactory;
import com.facebook.buck.core.parser.buildtargetparser.UnconfiguredBuildTargetFactory;
import com.facebook.buck.core.rulekey.RuleKey;
import com.facebook.buck.event.BuckEventBus;
import com.facebook.buck.event.BuckEventBusForTests;
import com.facebook.buck.io.file.BorrowablePath;
import com.facebook.buck.io.file.LazyPath;
import com.facebook.buck.io.filesystem.ProjectFilesystem;
import com.facebook.buck.io.filesystem.impl.FakeProjectFilesystem;
import com.facebook.buck.slb.ThriftUtil;
import com.facebook.buck.support.bgtasks.BackgroundTaskManager;
import com.facebook.buck.support.bgtasks.TaskManagerScope;
import com.facebook.buck.support.bgtasks.TestBackgroundTaskManager;
import com.facebook.buck.testutil.TemporaryPaths;
import com.facebook.buck.testutil.integration.HttpdForTests;
import com.google.common.base.Charsets;
import com.google.common.util.concurrent.MoreExecutors;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.X509KeyManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import okhttp3.tls.HandshakeCertificates;
import okhttp3.tls.HeldCertificate;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
public class ArtifactCachesIntegrationTest {
/**
* Certs generated with: openssl genrsa -out ca.key 2048 openssl req -new -x509 -days 3650 -key
* ca.key -out ca.crt openssl genrsa -out client.key 2048 openssl req -new -key client.key -out
* client.csr openssl x509 -req -days 3650 -in client.csr -CA ca.crt -CAkey ca.key -set_serial 01
* -out client.crt openssl pkcs8 -inform PEM -outform PEM -in client.key -out client.key.pkcs8
* -nocrypt -topk8 openssl genrsa -out server.key 2048 openssl req -new -key server.key -out
* server.csr openssl x509 -req -days 3650 -in server.csr -CA ca.crt -CAkey ca.key -set_serial 02
* -out server.crt openssl pkcs8 -inform PEM -outform PEM -in server.key -out server.key.pkcs8
* -nocrypt -topk8
*/
private static final String SAMPLE_CLIENT_CERT =
"-----BEGIN CERTIFICATE-----\n"
+ "MIIDEjCCAfoCAQEwDQYJKoZIhvcNAQEFBQAwTTELMAkGA1UEBhMCVVMxEzARBgNV\n"
+ "BAgMCldhc2hpbmd0b24xEDAOBgNVBAcMB1NlYXR0bGUxFzAVBgNVBAMMDmNhLmV4\n"
+ "YW1wbGUuY29tMB4XDTE4MTAwMzE4Mjk1N1oXDTI4MDkzMDE4Mjk1N1owUTELMAkG\n"
+ "A1UEBhMCVVMxEzARBgNVBAgMCldhc2hpbmd0b24xEDAOBgNVBAcMB1NlYXR0bGUx\n"
+ "GzAZBgNVBAMMEmNsaWVudC5leGFtcGxlLmNvbTCCASIwDQYJKoZIhvcNAQEBBQAD\n"
+ "ggEPADCCAQoCggEBANyyXUD+FSzICbv2JF7Z0Xnx9HVO1sZFjJlmTDknt/nyRw1y\n"
+ "sOZMO1LE7Wit24k6amqAZhjceehmPZIdQbtLxpBzwmtYum6qymLaC34Xx2LYEG4P\n"
+ "RJHY9AtMrb8hd4X4ZQD+bhAH59u+kTnVO+0vlOnyT3xPKVQQ+FEoErfmBDpKSiaj\n"
+ "v/ireTC/VrAcB24qhONKJuWK8xxu7vuJ6uNFU83IXrqgjS0iXkDWTXAI/dxZLexZ\n"
+ "Gm6nu66VCZlUbAP2Q1L0SPf2ZGKORo8VBl6MI+cT09k31CFjU4xaW9vosQQ9dInb\n"
+ "/5FK9K65OrbRIO3QdZclMs1Y5uDpLiFSvDfrZmMCAwEAATANBgkqhkiG9w0BAQUF\n"
+ "AAOCAQEAY56F8WLWwoCDCYF1YD4LcMRq8cuCMTTNk9v8gD7VSORuC+7bsyvTpMLx\n"
+ "qZbNNCJsv+L5GbRDnH4T98OEtrOn6pAgW8y7jKZNISPo6Tqohvn2Bi40OiCBNynr\n"
+ "0bki3HpLxDqgkOjbNCO35vHLs7ZtY1EijBnphlW57e4rXMAe63qkblWSXfxKo33+\n"
+ "0l4OiL/O0gPRrdeJEAU0k/GPgMdHd3QierkKg9LhZEIuU3bTMassPiWDwVGUXDov\n"
+ "ZEWyZ0qCcFV2nj23zPr/16FFvxuZEcGd9fBDLbJHbkBH1nlikFnchjvGCzH5gEcA\n"
+ "hpHC7IcvLgJPOTV0HbyaHmCxhBU8IQ==\n"
+ "-----END CERTIFICATE-----";
private static final String SAMPLE_CLIENT_KEY =
"-----BEGIN PRIVATE KEY-----\n"
+ "MIIEugIBADANBgkqhkiG9w0BAQEFAASCBKQwggSgAgEAAoIBAQDcsl1A/hUsyAm7\n"
+ "9iRe2dF58fR1TtbGRYyZZkw5J7f58kcNcrDmTDtSxO1orduJOmpqgGYY3HnoZj2S\n"
+ "HUG7S8aQc8JrWLpuqspi2gt+F8di2BBuD0SR2PQLTK2/IXeF+GUA/m4QB+fbvpE5\n"
+ "1TvtL5Tp8k98TylUEPhRKBK35gQ6Skomo7/4q3kwv1awHAduKoTjSiblivMcbu77\n"
+ "ierjRVPNyF66oI0tIl5A1k1wCP3cWS3sWRpup7uulQmZVGwD9kNS9Ej39mRijkaP\n"
+ "FQZejCPnE9PZN9QhY1OMWlvb6LEEPXSJ2/+RSvSuuTq20SDt0HWXJTLNWObg6S4h\n"
+ "Urw362ZjAgMBAAECggEAJjDjfFS7u1Uegh1VK+jLnCunnwk2l3b/nqgaNqXN633m\n"
+ "l8gqHqBAf9E+OCgl3nhyY922TUUR/4p5yygu8MdrJCI0GblwAaiifzq2VGqvAUbc\n"
+ "iP8xYX/Gs5HgWzviYBec+vAMgc+satVucjCZPzFFtrpM0Pkt8LNDFWA25QXz41YX\n"
+ "cpqUCR4tCGz5K3hI2XTeQehNrbCjzq01AT2+jY05JSDaU2lLc7b+tCcI+M6rWjF1\n"
+ "V2XufeVvYm/sG6eLasWIxpDKHFZCOvB1m6h1t+59d7e4y4rokjg2fspgTAjYNObb\n"
+ "YhDzxWhNUVQcbeo8OTwYZnZaQprOqY6uEo4C6E75qQKBgQD1NXB8roZoExYYkTeb\n"
+ "nK+1UD23opJTcbVGiqhP9qp7HP5o+e9Gk3TSZplZnIpaPqSib+tR3TU5lKEMefWS\n"
+ "p3Ou8K8Qgd9nlqK/gBuoT5ZmgaWr6HaUP5Pt4FOjrZ3g1M2kR7r9yqqg/moVvpiP\n"
+ "SBFzB+o6eCOjfjErTFXEXDeXvwKBgQDmaMTGvSY29QeVju8on9kgjHeZC1geYmav\n"
+ "23n6MrLwS0F5O/jVzZAll/hCljeZML/0aI733MZiDPd5qsn6jx6oyZ6GyWAtxoJw\n"
+ "JO+hRZq3dG/h74rp8aN/yfA2VPTfXCzJtsGBH9sF18eTnyfW2HXb+D7QT9tTlbQR\n"
+ "s8gL9qg6XQJ/XOjitltqkgSpWqWrbErySMEeoXX3+6YaCaCAJcxQzFUwEJajExrM\n"
+ "KOy3Lj0iLw+NUf8WKu6mPCsU2qVbZzYLnz2TF64d+CIbiHQCBsQhOLXnEDwEsidk\n"
+ "5b0Z8+rU51u6j4SeVYt1G4tKpvKQ27ly4yMcnQrodgpalw1VchF+/wKBgAa3CvUX\n"
+ "0iNL5Nqw/btbXUKblWi6cekAySla5iUqkRh7uP7Fhq0Efqz5ztxx8FDgoNeIrJIA\n"
+ "ty9oXVYIajaJMUWOCra267ypymdmTC2RD79E/3XAO3Yx+qfgxMVwmGpiD1QZpW4T\n"
+ "9Zgn/8MHomuah2TPyVTc3vGCrWrOqIfgumppAoGAB4zQWSn4+le24DHwgYwCChkT\n"
+ "s7wao8DiTMBRGYmfeAgMx/U2U3m/gN9q/+7WT+X4AKseXoWKuDegQq4CHlgkDyh2\n"
+ "B7sBo4ZpLm3kOlUlznssMBUEG2i/iyZGPwHBKcUskemLL5M2wIHH1O/CYJ3jDMcK\n"
+ "9kGk/IHTW2kCBLs+mVA=\n"
+ "-----END PRIVATE KEY-----";
private static final String SAMPLE_SERVER_CERT =
"-----BEGIN CERTIFICATE-----\n"
+ "MIIDEjCCAfoCAQIwDQYJKoZIhvcNAQEFBQAwTTELMAkGA1UEBhMCVVMxEzARBgNV\n"
+ "BAgMCldhc2hpbmd0b24xEDAOBgNVBAcMB1NlYXR0bGUxFzAVBgNVBAMMDmNhLmV4\n"
+ "YW1wbGUuY29tMB4XDTE4MTAwMzE4MzAwOVoXDTI4MDkzMDE4MzAwOVowUTELMAkG\n"
+ "A1UEBhMCVVMxEzARBgNVBAgMCldhc2hpbmd0b24xEDAOBgNVBAcMB1NlYXR0bGUx\n"
+ "GzAZBgNVBAMMEnNlcnZlci5leGFtcGxlLmNvbTCCASIwDQYJKoZIhvcNAQEBBQAD\n"
+ "ggEPADCCAQoCggEBAMRkUtz2qYmvJ2xWbVNHbGOoEinDqxXY749kEVf9swGDCtbd\n"
+ "qNmuB3P81CoEWm3O1ZnIBfgD6hNzC9YC0KJ16x7B7YbR37rw/so0AVIdiDU2Ftjz\n"
+ "N76Ih+GXKV1ZXE8Noq5W9BfccMxhwEr5+eI1v11V91x9LgMLzbUzbnr0SS7+/VOb\n"
+ "0C2tG2QSvyY33NMAAGyFRc9EPIB22blaIaylTqsp11akDd8im1+x/lpvJAt7qgxX\n"
+ "8bgtlI+z7d7bmvdO6bUlFWYXxgl2SFNdbFHyz7TvbbQrxEfTMZiFYgsmrp+0mGG7\n"
+ "2putPVyvE2x9sMUCXsnsZT6gHGKaNGURFWiJwtECAwEAATANBgkqhkiG9w0BAQUF\n"
+ "AAOCAQEAOlzAIo2c36+VUtZNbrOs767daO0WY4a+5tV+z9wU5dNa09MO74yN0cYl\n"
+ "O+4Kf9646GvVFfP0d3YLSivWJ8BC2j6m/plugnyjorO5eGdTeWaZk8foRpnK/yys\n"
+ "lCU7OT8NxmUp+ch+Oer6RyOG18HP7eRV5ejC+PoaCFlAq+rrdA9dZm4sQCRgWVd9\n"
+ "xWXJVSTmF2X7U6bT4r52P7ETLpqiG7ZHkZvZo8KbPi8U5V0CAqsV9J9QDOfJvstl\n"
+ "oN2PC/nv6B6b7ZNGj3wMWhoYBDT7gWgKeM0PlXERyjgMX3Ckn4j67u4trV1/TLUz\n"
+ "MUcHV2A4aEJMpR+W74/BRmKAPMwUCw==\n"
+ "-----END CERTIFICATE-----";
private static final String SAMPLE_SERVER_KEY =
"-----BEGIN PRIVATE KEY-----\n"
+ "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDEZFLc9qmJryds\n"
+ "Vm1TR2xjqBIpw6sV2O+PZBFX/bMBgwrW3ajZrgdz/NQqBFptztWZyAX4A+oTcwvW\n"
+ "AtCidesewe2G0d+68P7KNAFSHYg1NhbY8ze+iIfhlyldWVxPDaKuVvQX3HDMYcBK\n"
+ "+fniNb9dVfdcfS4DC821M2569Eku/v1Tm9AtrRtkEr8mN9zTAABshUXPRDyAdtm5\n"
+ "WiGspU6rKddWpA3fIptfsf5abyQLe6oMV/G4LZSPs+3e25r3Tum1JRVmF8YJdkhT\n"
+ "XWxR8s+07220K8RH0zGYhWILJq6ftJhhu9qbrT1crxNsfbDFAl7J7GU+oBximjRl\n"
+ "ERVoicLRAgMBAAECggEAK5PPRzR8Xg69gq6Sx53bkSlkDlxahBiE355mss2agMVh\n"
+ "DFhW9SZGhRgew8v/fMoeX2cg2+2SbQpkH/Kz9LiRmVuSpw2+xS5geuGbQWtII/aC\n"
+ "j1U4k1CcRhRSm2IOt4PhCypEM184sEEod/qL1gPzGHTQ1Hb6VLazyHdHFoVKD+Ek\n"
+ "aATfYPYM8NEyPebkJVxjWGHv+eZXwyrF2mGiOoBOLlUWl+VkIHkTB7qe+nKsrtyw\n"
+ "JhJKt2Z2+390EL4Rxg0uqp5thvd4scKAzB58m42zd0m09X89Lw6722PmYlMCf9qX\n"
+ "5dNLxVkTQyiwn55JHN0Zlo+pyrDEijmRG+wDXqJgIQKBgQD+sT8Hs7vFaM3l7gt0\n"
+ "fsZtTOOMU4/ksEtPlQNQaTeoiSmMr6xGak4Xvr6LD/SxB1dPvaT0QSTJEQkXUx4U\n"
+ "G8zuNtJut4+dO3XV/88l+MDYSsI5KbwH5bYWwPXnsCTNf46IBMArbpoCJeVYV+W3\n"
+ "SdHDcG6QhvSsGXmzvEIWOyeOBQKBgQDFZnNTunRZEIhKAffFK0SnJL/kTKkVERW6\n"
+ "SWMqMoTW2ZckpSMnyfFbyz4LX0rl6MLOzGuk4ttVjCT7yvjhBiDUc2yY2wSFc5DK\n"
+ "gyuJqoVkcAklxGvQ1Yc07eMIB64Ipjz0J2kDaxjsn/TLYGGZlq8RO67nuUeH5Jrv\n"
+ "C++BrutvXQKBgQD8XFHw5sVSSJNjlafiCU/Bs2Lwg0fbuFcXBrae8XKF20rBLLwN\n"
+ "lX3Fh2mzzt6MnpKD34xXvUietfOFGgV+tUEsdEO0EswJZoZOwcbWgBFM/15NV64J\n"
+ "QTJYf1/o7x64RADNg6+KGXAeWsBR9d4W690dwwS6zg4XjLKLRilRb9G0pQKBgAtC\n"
+ "Tq2l4uD5mmxuNE2grCfEZtWEsdgrw0t+yBMuEnmWq5JBgQHR+Nw9eWp4ovL+Fa5p\n"
+ "5nHfJpd4iNt7tjpPeSvk8Xq+c0GRV97VIHSXr0gNQ9hNncCpjS6tqtdYaMrBgJSE\n"
+ "cu7o+uD0Nqgq9SYnfBDFkLJS1QuhNF0SFzUUXwVZAoGAfhGMXxl1uDkFIoSOySEV\n"
+ "d7DPQJLFT9crsqBbpA7nDuNB/3BXUqCjz+MaVHpNQEykfke9rAuswNjRl75cTcnE\n"
+ "m2NkREF3dEi1CllNZxb0LRFVpAmJwBFFcevpqvQnDSokZ7/5tUsaUMrR+mbq5vaV\n"
+ "9lVGHblMKOFQ22R+E4yI7G8=\n"
+ "-----END PRIVATE KEY-----";
private static final String SAMPLE_CA_CERT =
"-----BEGIN CERTIFICATE-----\n"
+ "MIIDFjCCAf4CCQCFJYJEzO/NoTANBgkqhkiG9w0BAQsFADBNMQswCQYDVQQGEwJV\n"
+ "UzETMBEGA1UECAwKV2FzaGluZ3RvbjEQMA4GA1UEBwwHU2VhdHRsZTEXMBUGA1UE\n"
+ "AwwOY2EuZXhhbXBsZS5jb20wHhcNMTgxMDAzMTgyOTM3WhcNMjgwOTMwMTgyOTM3\n"
+ "WjBNMQswCQYDVQQGEwJVUzETMBEGA1UECAwKV2FzaGluZ3RvbjEQMA4GA1UEBwwH\n"
+ "U2VhdHRsZTEXMBUGA1UEAwwOY2EuZXhhbXBsZS5jb20wggEiMA0GCSqGSIb3DQEB\n"
+ "AQUAA4IBDwAwggEKAoIBAQDO+b9sMlJPpLbS0YHRz5jNUikshqelUriLLGyPKIcH\n"
+ "4Gd2HXp1kIpkN9U+h30EKAO2kluSkzU6q1EPOg54VIdZwOI+89F3fGvTuACGBBRW\n"
+ "KXDnLLfBj/XKE4JRAHxej8rrJzbYNv3iy1jcSRdMPdXw+RMBt4fbS7JuEeY1c1iM\n"
+ "hFbCZAqBgOWRQV+JqZJ5hv0x2Y8hmTQN8O8PRl5VwpKT+aNrpunyQVYdyzfMtHrm\n"
+ "c4W3MU2W9Oa0mTLzVAa9rVrpOxpSmEfXcMY8RIIN1mOK0yuJVPW8K0TcKy/HfO14\n"
+ "4OBsbzrlvtVNLSMeiCIvsROXJCBd90ZtE3DHwZYRvltTAgMBAAEwDQYJKoZIhvcN\n"
+ "AQELBQADggEBADEhwOYsugkZ0IhTD9CGPnCqOY97iLaVXy7/P7xnOtzlXJiK/AMj\n"
+ "tapwh9mG1vgpOv9orCyTm6GZqBSObhoymyFGoxWgku3nQyiqJDQFAbB2+N46H5GC\n"
+ "r4Cu+MnPGljJtNClVn+Q9CRKuaOSiRYygGc84bUbQAeMuPnRswK2IInAahzfpWWI\n"
+ "xYFwXb3611NqPQAIwnFdgpmsm4Ko82xh5sWhchRy5BwIlGUXxrFAOUOMonvIUzSW\n"
+ "hitWCW5AMwHKOeTs0/4BmJE/6rmR84ozZ0z3X/5+LAYLeI+GbUZBr/kUB3euXaj4\n"
+ "rGN2EuvbdWav5As8evyWUnB5QGxTTeptYCg=\n"
+ "-----END CERTIFICATE-----";
private static final RuleKey ruleKey = new RuleKey("00000000000000000000000000000000");
private static final Path outputPath = Paths.get("output/file");
private static final BuildId BUILD_ID = new BuildId("test");
@Rule public TemporaryPaths tempDir = new TemporaryPaths();
private BackgroundTaskManager bgTaskManager;
private TaskManagerScope managerScope;
private Path clientCertPath;
private Path clientKeyPath;
private Path serverCertPath;
private Path serverKeyPath;
private Path caCertPath;
private ClientCertificateHandler clientCertificateHandler;
@Before
public void setUp() throws IOException {
bgTaskManager = new TestBackgroundTaskManager();
managerScope = bgTaskManager.getNewScope(BUILD_ID);
clientCertPath = tempDir.newFile("client.crt");
clientKeyPath = tempDir.newFile("client.key");
serverCertPath = tempDir.newFile("server.crt");
serverKeyPath = tempDir.newFile("server.key");
caCertPath = tempDir.newFile("ca.crt");
Files.write(clientCertPath, SAMPLE_CLIENT_CERT.getBytes(Charsets.UTF_8));
Files.write(clientKeyPath, SAMPLE_CLIENT_KEY.getBytes(Charsets.UTF_8));
Files.write(serverCertPath, SAMPLE_SERVER_CERT.getBytes(Charsets.UTF_8));
Files.write(serverKeyPath, SAMPLE_SERVER_KEY.getBytes(Charsets.UTF_8));
Files.write(caCertPath, SAMPLE_CA_CERT.getBytes(Charsets.UTF_8));
clientCertificateHandler =
createClientCertificateHandler(clientKeyPath, clientCertPath, caCertPath);
}
@After
public void tearDown() throws InterruptedException {
managerScope.close();
bgTaskManager.shutdown(1, TimeUnit.SECONDS);
}
@Test
public void testUsesClientTlsCertsForHttpsFetch() throws Exception {
NotFoundHandler handler = new NotFoundHandler(false, false);
X509KeyManager keyManager = clientCertificateHandler.getHandshakeCertificates().keyManager();
X509Certificate clientCert =
keyManager.getCertificateChain(keyManager.getClientAliases("RSA", null)[0])[0];
ProjectFilesystem projectFilesystem = new FakeProjectFilesystem();
BuckEventBus buckEventBus = BuckEventBusForTests.newInstance();
try (HttpdForTests server = new HttpdForTests(caCertPath, serverCertPath, serverKeyPath)) {
server.addHandler(handler);
server.start();
ArtifactCacheBuckConfig cacheConfig =
ArtifactCacheBuckConfigTest.createFromText(
"[cache]",
"mode = http",
"http_url = " + server.getRootUri(),
"http_client_tls_key = " + clientKeyPath.toString(),
"http_client_tls_cert = " + clientCertPath.toString());
CacheResult result;
try (ArtifactCache artifactCache =
newArtifactCache(buckEventBus, projectFilesystem, cacheConfig)
.remoteOnlyInstance(false, false)) {
result =
artifactCache
.fetchAsync(
BuildTargetFactory.newInstance("//:foo"),
ruleKey,
LazyPath.ofInstance(outputPath))
.get();
}
Assert.assertEquals(result.cacheError().orElse(""), CacheResultType.MISS, result.getType());
Assert.assertEquals(1, handler.peerCertificates.size());
Assert.assertEquals(1, handler.peerCertificates.get(0).length);
Assert.assertEquals(clientCert, handler.peerCertificates.get(0)[0]);
}
}
@Test
public void testUsesClientTlsCertsForThriftFetch() throws Exception {
NotFoundHandler handler = new NotFoundHandler(true, false);
X509KeyManager keyManager = clientCertificateHandler.getHandshakeCertificates().keyManager();
X509Certificate clientCert =
keyManager.getCertificateChain(keyManager.getClientAliases("RSA", null)[0])[0];
ProjectFilesystem projectFilesystem = new FakeProjectFilesystem();
BuckEventBus buckEventBus = BuckEventBusForTests.newInstance();
try (HttpdForTests server = new HttpdForTests(caCertPath, serverCertPath, serverKeyPath)) {
server.addHandler(handler);
server.start();
ArtifactCacheBuckConfig cacheConfig =
ArtifactCacheBuckConfigTest.createFromText(
"[cache]",
"mode = thrift_over_http",
"http_url = " + server.getRootUri(),
"hybrid_thrift_endpoint = /hybrid_thrift",
"http_client_tls_key = " + clientKeyPath.toString(),
"http_client_tls_cert = " + clientCertPath.toString());
CacheResult result;
try (ArtifactCache artifactCache =
newArtifactCache(buckEventBus, projectFilesystem, cacheConfig)
.remoteOnlyInstance(false, false)) {
result =
artifactCache
.fetchAsync(
BuildTargetFactory.newInstance("//:foo"),
ruleKey,
LazyPath.ofInstance(outputPath))
.get();
}
Assert.assertEquals(CacheResultType.MISS, result.getType());
Assert.assertEquals(1, handler.peerCertificates.size());
Assert.assertEquals(1, handler.peerCertificates.get(0).length);
Assert.assertEquals(clientCert, handler.peerCertificates.get(0)[0]);
}
}
@Test
public void testUsesClientTlsCertsForHttpsStore() throws Exception {
NotFoundHandler handler = new NotFoundHandler(false, true);
X509KeyManager keyManager = clientCertificateHandler.getHandshakeCertificates().keyManager();
X509Certificate clientCert =
keyManager.getCertificateChain(keyManager.getClientAliases("RSA", null)[0])[0];
String data = "data";
BuckEventBus buckEventBus = BuckEventBusForTests.newInstance();
FakeProjectFilesystem projectFilesystem = new FakeProjectFilesystem();
projectFilesystem.writeContentsToPath(data, outputPath);
try (HttpdForTests server = new HttpdForTests(caCertPath, serverCertPath, serverKeyPath)) {
server.addHandler(handler);
server.start();
ArtifactCacheBuckConfig cacheConfig =
ArtifactCacheBuckConfigTest.createFromText(
"[cache]",
"mode = http",
"http_url = " + server.getRootUri(),
"http_client_tls_key = " + clientKeyPath.toString(),
"http_client_tls_cert = " + clientCertPath.toString());
try (ArtifactCache artifactCache =
newArtifactCache(buckEventBus, projectFilesystem, cacheConfig)
.remoteOnlyInstance(false, false)) {
artifactCache
.store(
ArtifactInfo.builder().addRuleKeys(ruleKey).build(),
BorrowablePath.borrowablePath(outputPath))
.get();
}
Assert.assertEquals(1, handler.peerCertificates.size());
Assert.assertEquals(1, handler.peerCertificates.get(0).length);
Assert.assertEquals(clientCert, handler.peerCertificates.get(0)[0]);
}
}
@Test
public void testUsesClientTlsCertsForThriftStore() throws Exception {
NotFoundHandler handler = new NotFoundHandler(true, true);
X509KeyManager keyManager = clientCertificateHandler.getHandshakeCertificates().keyManager();
X509Certificate clientCert =
keyManager.getCertificateChain(keyManager.getClientAliases("RSA", null)[0])[0];
String data = "data";
BuckEventBus buckEventBus = BuckEventBusForTests.newInstance();
FakeProjectFilesystem projectFilesystem = new FakeProjectFilesystem();
projectFilesystem.writeContentsToPath(data, outputPath);
try (HttpdForTests server = new HttpdForTests(caCertPath, serverCertPath, serverKeyPath)) {
server.addHandler(handler);
server.start();
ArtifactCacheBuckConfig cacheConfig =
ArtifactCacheBuckConfigTest.createFromText(
"[cache]",
"mode = thrift_over_http",
"http_url = " + server.getRootUri(),
"hybrid_thrift_endpoint = /hybrid_thrift",
"http_client_tls_key = " + clientKeyPath.toString(),
"http_client_tls_cert = " + clientCertPath.toString());
try (ArtifactCache artifactCache =
newArtifactCache(buckEventBus, projectFilesystem, cacheConfig)
.remoteOnlyInstance(false, false)) {
artifactCache
.store(
ArtifactInfo.builder().addRuleKeys(ruleKey).build(),
BorrowablePath.borrowablePath(outputPath))
.get();
}
Assert.assertEquals(1, handler.peerCertificates.size());
Assert.assertEquals(1, handler.peerCertificates.get(0).length);
Assert.assertEquals(clientCert, handler.peerCertificates.get(0)[0]);
}
}
private ArtifactCaches newArtifactCache(
BuckEventBus buckEventBus,
ProjectFilesystem projectFilesystem,
ArtifactCacheBuckConfig cacheConfig) {
CellPathResolver cellPathResolver = TestCellPathResolver.get(projectFilesystem);
UnconfiguredBuildTargetFactory unconfiguredBuildTargetFactory =
new ParsingUnconfiguredBuildTargetFactory();
return new ArtifactCaches(
cacheConfig,
buckEventBus,
target -> unconfiguredBuildTargetFactory.create(cellPathResolver, target),
TargetConfigurationSerializerForTests.create(cellPathResolver),
projectFilesystem,
Optional.empty(),
MoreExecutors.newDirectExecutorService(),
MoreExecutors.newDirectExecutorService(),
MoreExecutors.newDirectExecutorService(),
MoreExecutors.newDirectExecutorService(),
managerScope,
"test://",
"myhostname",
Optional.of(clientCertificateHandler));
}
/**
* Create a ClientCertificateHandler that accepts all hostnames (so that we don't have to setup
* hostnames for tests), and that accepts certs signed by the CA
*/
private ClientCertificateHandler createClientCertificateHandler(
Path clientKeyPath, Path clientCertPath, Path caCertPath) throws IOException {
X509Certificate certificate =
ClientCertificateHandler.parseCertificate(Optional.of(clientCertPath), true).get();
X509Certificate caCertificate =
ClientCertificateHandler.parseCertificate(Optional.of(caCertPath), true).get();
PrivateKey privateKey =
ClientCertificateHandler.parsePrivateKey(Optional.of(clientKeyPath), certificate, true)
.get();
HeldCertificate cert =
new HeldCertificate(new KeyPair(certificate.getPublicKey(), privateKey), certificate);
HandshakeCertificates.Builder hsBuilder = new HandshakeCertificates.Builder();
hsBuilder.addPlatformTrustedCertificates();
hsBuilder.addTrustedCertificate(caCertificate);
hsBuilder.heldCertificate(cert);
return new ClientCertificateHandler(hsBuilder.build(), Optional.of((s, sslSession) -> true));
}
class NotFoundHandler extends AbstractHandler {
private final boolean isThrift;
private final boolean isStore;
List<X509Certificate[]> peerCertificates = new ArrayList<>();
public NotFoundHandler(boolean isThrift, boolean isStore) {
this.isThrift = isThrift;
this.isStore = isStore;
}
@Override
public void handle(
String s,
Request request,
HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse)
throws IOException {
X509Certificate[] certs =
(X509Certificate[])
httpServletRequest.getAttribute("javax.servlet.request.X509Certificate");
peerCertificates.add(certs);
if (isThrift) {
httpServletResponse.setStatus(HttpServletResponse.SC_OK);
BuckCacheResponse response = new BuckCacheResponse();
response.setWasSuccessful(true);
if (isStore) {
BuckCacheStoreResponse storeResponse = new BuckCacheStoreResponse();
response.setStoreResponse(storeResponse);
} else {
BuckCacheFetchResponse fetchResponse = new BuckCacheFetchResponse();
fetchResponse.setArtifactExists(false);
response.setFetchResponse(fetchResponse);
}
byte[] serialized = ThriftUtil.serialize(ThriftArtifactCache.PROTOCOL, response);
httpServletResponse.setContentType("application/octet-stream");
httpServletResponse
.getOutputStream()
.write(ByteBuffer.allocate(4).putInt(serialized.length).array());
httpServletResponse.getOutputStream().write(serialized);
httpServletResponse.getOutputStream().close();
} else {
if (isStore) {
httpServletResponse.setStatus(HttpServletResponse.SC_OK);
} else {
httpServletResponse.setStatus(HttpServletResponse.SC_NOT_FOUND);
}
}
request.setHandled(true);
}
}
}
| apache-2.0 |
innerfunction/semo-core-and | src/com/innerfunction/uri/LocalResource.java | 1815 | package com.innerfunction.uri;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import com.innerfunction.util.NotificationCenter;
/**
* Object for representing local preference data resources.
*/
public class LocalResource extends Resource {
private static final String LogTag = "LocalURIResource";
private String name;
private SharedPreferences preferences;
public LocalResource(Context context, SharedPreferences preferences, CompoundURI uri, Resource parent) {
super( context, uri.getName(), uri, parent );
this.name = uri.getName();
this.preferences = preferences;
}
public String getLocalName() {
return this.name;
}
public String asString() {
return this.preferences.getString( name, null );
}
public Number asNumber() {
return this.preferences.getFloat( name, 0 );
}
public Boolean asBoolean() {
return this.preferences.getBoolean( name, false );
}
public boolean updateWithValue(Object value) {
SharedPreferences.Editor editor = this.preferences.edit();
if( value instanceof Boolean ) {
editor.putBoolean( this.name, (Boolean)value );
}
else if( value instanceof Number ) {
editor.putFloat( this.name, ((Number)value).floatValue() );
}
else {
editor.putString( this.name, value.toString() );
}
if( editor.commit() ) {
NotificationCenter.getInstance().sendNotification( Constants.NotificationTypes.LocalDataUpdate.toString(), this.name );
return true;
}
Log.w( LogTag, String.format("Failed to write update to shared preferences (%s -> %s)", value, this.name ) );
return false;
}
}
| apache-2.0 |
5of9/traccar | src/org/traccar/model/GroupAttribute.java | 1103 | /*
* Copyright 2017 Anton Tananaev (anton@traccar.org)
* Copyright 2017 Andrey Kunitsyn (andrey@traccar.org)
*
* 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.traccar.model;
public class GroupAttribute {
private long groupId;
public long getGroupId() {
return groupId;
}
public void setGroupId(long groupId) {
this.groupId = groupId;
}
private long attributeId;
public long getAttributeId() {
return attributeId;
}
public void setAttributeId(long attributeId) {
this.attributeId = attributeId;
}
}
| apache-2.0 |
mhus/mhus-inka | de.mhus.hair/hair3/de.mhus.cap.core/src/de/mhus/cap/core/ConnectionDefinition.java | 2185 | package de.mhus.cap.core;
import java.util.UUID;
import org.eclipse.swt.graphics.Image;
import de.mhus.lib.MException;
import de.mhus.lib.cao.CaoException;
import de.mhus.lib.cao.util.MutableElement;
import de.mhus.lib.cao.util.NoneApplication;
import de.mhus.lib.config.IConfig;
public class ConnectionDefinition extends MutableElement {
public static final String TITLE = "title";
public static final String SERVICE = "service";
public static final String URL = "url";
public static final String ID = "id";
private Image imageOpen;
private Image imageClose;
public ConnectionDefinition(IConfig config) throws MException {
super(NoneApplication.getInstance());
setTitle(config.getExtracted("title"));
setService(config.getExtracted("service"));
setUrl(config.getExtracted("url"));
String id = config.getExtracted("id");
if (id == null)
id = UUID.randomUUID().toString();
setId(id);
imageOpen = Activator.getImageDescriptor("/icons/database_go.png").createImage();
imageClose = Activator.getImageDescriptor("/icons/database.png").createImage();
}
public void setService(String service) throws MException {
setString(SERVICE, service);
}
public String getUrl() throws CaoException {
return getString(URL);
}
public String getService() throws CaoException {
return getString(SERVICE);
}
public void setUrl(String url) throws MException {
setString(URL,url);
}
public String getTitle() throws CaoException {
return getString(TITLE);
}
@Override
public boolean equals(Object other) {
if (other == null) return false;
if (other instanceof ConnectionDefinition) {
try {
return getId().equals( ((ConnectionDefinition)other).getId() );
} catch (CaoException e) {
}
}
return super.equals(other);
}
public void setTitle(String title) throws MException {
setString(TITLE,title);
}
public void fill(IConfig config) throws MException {
config.setString("title", getTitle());
config.setString("url", getUrl());
config.setString("service", getService());
config.setString("id", getId());
}
public Image getImage(boolean connected) {
return connected ? imageOpen : imageClose;
}
}
| apache-2.0 |
ua-eas/ksd-kc5.2.1-rice2.3.6-ua | rice-framework/krad-web-framework/src/main/java/org/kuali/rice/krad/datadictionary/DataDictionaryIndexMapper.java | 14959 | /**
* Copyright 2005-2014 The Kuali Foundation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php
*
* 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.kuali.rice.krad.datadictionary;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.kuali.rice.krad.datadictionary.uif.UifDictionaryIndex;
import org.kuali.rice.krad.service.KRADServiceLocatorWeb;
import org.kuali.rice.krad.service.ModuleService;
import org.kuali.rice.krad.uif.UifConstants;
import org.kuali.rice.krad.uif.view.View;
import org.springframework.beans.PropertyValues;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* A DataDictionaryMapper that simply consults the statically initialized
* DataDictionaryIndex mappings
*
* @author Kuali Rice Team (rice.collab@kuali.org)
*/
public class DataDictionaryIndexMapper implements DataDictionaryMapper {
private static final Logger LOG = Logger.getLogger(DataDictionaryIndexMapper.class);
/**
* @see org.kuali.rice.krad.datadictionary.DataDictionaryMapper#getAllInactivationBlockingMetadatas(org.kuali.rice.krad.datadictionary.DataDictionaryIndex,
* java.lang.Class)
*/
public Set<InactivationBlockingMetadata> getAllInactivationBlockingMetadatas(DataDictionaryIndex index,
Class<?> blockedClass) {
return index.getInactivationBlockersForClass().get(blockedClass);
}
/**
* @see org.kuali.rice.krad.datadictionary.DataDictionaryMapper#getBusinessObjectClassNames(org.kuali.rice.krad.datadictionary.DataDictionaryIndex)
*/
public List<String> getBusinessObjectClassNames(DataDictionaryIndex index) {
List classNames = new ArrayList();
classNames.addAll(index.getBusinessObjectEntries().keySet());
return Collections.unmodifiableList(classNames);
}
/**
* @see org.kuali.rice.krad.datadictionary.DataDictionaryMapper#getBusinessObjectEntries(org.kuali.rice.krad.datadictionary.DataDictionaryIndex)
*/
public Map<String, BusinessObjectEntry> getBusinessObjectEntries(DataDictionaryIndex index) {
return index.getBusinessObjectEntries();
}
/**
* @see org.kuali.rice.krad.datadictionary.DataDictionaryMapper#getDataObjectEntryForConcreteClass(org.kuali.rice.krad.datadictionary.DataDictionaryIndex,
* java.lang.String)
*/
@Override
public DataObjectEntry getDataObjectEntryForConcreteClass(DataDictionaryIndex ddIndex, String className) {
if (StringUtils.isBlank(className)) {
throw new IllegalArgumentException("invalid (blank) className");
}
if (LOG.isDebugEnabled()) {
LOG.debug("calling getDataObjectEntry '" + className + "'");
}
String trimmedClassName = className;
int index = className.indexOf("$$");
if (index >= 0) {
trimmedClassName = className.substring(0, index);
}
return ddIndex.getDataObjectEntries().get(trimmedClassName);
}
/**
* @see org.kuali.rice.krad.datadictionary.DataDictionaryMapper#getBusinessObjectEntryForConcreteClass(java.lang.String)
*/
public BusinessObjectEntry getBusinessObjectEntryForConcreteClass(DataDictionaryIndex ddIndex, String className) {
if (StringUtils.isBlank(className)) {
throw new IllegalArgumentException("invalid (blank) className");
}
if (LOG.isDebugEnabled()) {
LOG.debug("calling getBusinessObjectEntry '" + className + "'");
}
int index = className.indexOf("$$");
if (index >= 0) {
className = className.substring(0, index);
}
return ddIndex.getBusinessObjectEntries().get(className);
}
/**
* @see org.kuali.rice.krad.datadictionary.DataDictionaryMapper#getDictionaryObjectEntry(org.kuali.rice.krad.datadictionary.DataDictionaryIndex,
* java.lang.String)
*/
public DataDictionaryEntry getDictionaryObjectEntry(DataDictionaryIndex ddIndex, String className) {
if (StringUtils.isBlank(className)) {
throw new IllegalArgumentException("invalid (blank) className");
}
if (LOG.isDebugEnabled()) {
LOG.debug("calling getDictionaryObjectEntry '" + className + "'");
}
int index = className.indexOf("$$");
if (index >= 0) {
className = className.substring(0, index);
}
// look in the JSTL key cache
DataDictionaryEntry entry = null;
if (ddIndex.getEntriesByJstlKey() != null) {
entry = ddIndex.getEntriesByJstlKey().get(className);
}
// check the Object list
if (entry == null) {
entry = ddIndex.getDataObjectEntries().get(className);
}
// KULRICE-8005 Breaks when override business object classes
// check the BO list
if (entry == null) {
entry = getBusinessObjectEntry(ddIndex, className);
}
// check the document list
if (entry == null) {
entry = getDocumentEntry(ddIndex, className);
}
return entry;
}
/**
* @see org.kuali.rice.krad.datadictionary.DataDictionaryMapper#getDataObjectEntry(org.kuali.rice.krad.datadictionary.DataDictionaryIndex,
* java.lang.String)
*/
@Override
public DataObjectEntry getDataObjectEntry(DataDictionaryIndex index, String className) {
DataObjectEntry entry = getDataObjectEntryForConcreteClass(index, className);
if (entry == null) {
Class<?> boClass = null;
try {
boClass = Class.forName(className);
ModuleService responsibleModuleService =
KRADServiceLocatorWeb.getKualiModuleService().getResponsibleModuleService(boClass);
if (responsibleModuleService != null && responsibleModuleService.isExternalizable(boClass)) {
entry = responsibleModuleService.getExternalizableBusinessObjectDictionaryEntry(boClass);
}
} catch (ClassNotFoundException cnfex) {
// swallow so we can return null
}
}
return entry;
}
public BusinessObjectEntry getBusinessObjectEntry(DataDictionaryIndex index, String className) {
BusinessObjectEntry entry = getBusinessObjectEntryForConcreteClass(index, className);
if (entry == null) {
Class boClass = null;
try {
boClass = Class.forName(className);
ModuleService responsibleModuleService =
KRADServiceLocatorWeb.getKualiModuleService().getResponsibleModuleService(boClass);
if (responsibleModuleService != null && responsibleModuleService.isExternalizable(boClass)) {
return responsibleModuleService.getExternalizableBusinessObjectDictionaryEntry(boClass);
}
} catch (ClassNotFoundException cnfex) {
}
return null;
} else {
return entry;
}
}
/**
* @see org.kuali.rice.krad.datadictionary.DataDictionaryMapper#getDocumentEntries(org.kuali.rice.krad.datadictionary.DataDictionaryIndex)
*/
public Map<String, DocumentEntry> getDocumentEntries(DataDictionaryIndex index) {
return Collections.unmodifiableMap(index.getDocumentEntries());
}
/**
* @see org.kuali.rice.krad.datadictionary.DataDictionaryMapper#getDocumentEntry(org.kuali.rice.krad.datadictionary.DataDictionaryIndex,
* java.lang.String)
*/
public DocumentEntry getDocumentEntry(DataDictionaryIndex index, String documentTypeDDKey) {
if (StringUtils.isBlank(documentTypeDDKey)) {
throw new IllegalArgumentException("invalid (blank) documentTypeName");
}
if (LOG.isDebugEnabled()) {
LOG.debug("calling getDocumentEntry by documentTypeName '" + documentTypeDDKey + "'");
}
DocumentEntry de = index.getDocumentEntries().get(documentTypeDDKey);
if (de == null) {
try {
Class<?> clazz = Class.forName(documentTypeDDKey);
de = index.getDocumentEntriesByBusinessObjectClass().get(clazz);
if (de == null) {
de = index.getDocumentEntriesByMaintainableClass().get(clazz);
}
} catch (ClassNotFoundException ex) {
LOG.warn("Unable to find document entry for key: " + documentTypeDDKey);
}
}
return de;
}
/**
* @see org.kuali.rice.krad.datadictionary.DataDictionaryMapper#getDocumentTypeName(org.kuali.rice.krad.datadictionary.DataDictionaryIndex,
* java.lang.String)
*/
public String getDocumentTypeName(DataDictionaryIndex index, String documentTypeName) {
// TODO arh14 - THIS METHOD NEEDS JAVADOCS
return null;
}
/**
* @see org.kuali.rice.krad.datadictionary.DataDictionaryMapper#getMaintenanceDocumentEntryForBusinessObjectClass(org.kuali.rice.krad.datadictionary.DataDictionaryIndex,
* java.lang.Class)
*/
public MaintenanceDocumentEntry getMaintenanceDocumentEntryForBusinessObjectClass(DataDictionaryIndex index,
Class<?> businessObjectClass) {
if (businessObjectClass == null) {
throw new IllegalArgumentException("invalid (null) dataObjectClass");
}
if (LOG.isDebugEnabled()) {
LOG.debug("calling getDocumentEntry by dataObjectClass '" + businessObjectClass + "'");
}
return (MaintenanceDocumentEntry) index.getDocumentEntriesByBusinessObjectClass().get(businessObjectClass);
}
/**
* @see org.kuali.rice.krad.datadictionary.DataDictionaryMapper#getViewById(org.kuali.rice.krad.datadictionary.uif.UifDictionaryIndex,
* java.lang.String)
*/
public View getViewById(UifDictionaryIndex index, String viewId) {
if (StringUtils.isBlank(viewId)) {
throw new IllegalArgumentException("invalid (blank) view id");
}
if (LOG.isDebugEnabled()) {
LOG.debug("calling getViewById by id '" + viewId + "'");
}
return index.getViewById(viewId);
}
/**
* @see org.kuali.rice.krad.datadictionary.DataDictionaryMapper#getImmutableViewById(org.kuali.rice.krad.datadictionary.uif.UifDictionaryIndex,
* java.lang.String)
*/
public View getImmutableViewById(UifDictionaryIndex index, String viewId) {
if (StringUtils.isBlank(viewId)) {
throw new IllegalArgumentException("invalid (blank) view id");
}
return index.getImmutableViewById(viewId);
}
/**
* @see org.kuali.rice.krad.datadictionary.DataDictionaryMapper#getViewByTypeIndex(UifDictionaryIndex,
* java.lang.String, java.util.Map)
*/
public View getViewByTypeIndex(UifDictionaryIndex index, UifConstants.ViewType viewTypeName,
Map<String, String> indexKey) {
if (viewTypeName == null) {
throw new IllegalArgumentException("invalid (blank) view type name");
}
if ((indexKey == null) || indexKey.isEmpty()) {
throw new IllegalArgumentException("index key must have at least one entry");
}
return index.getViewByTypeIndex(viewTypeName, indexKey);
}
/**
* @see DataDictionaryMapper#getViewByTypeIndex(org.kuali.rice.krad.datadictionary.uif.UifDictionaryIndex,
* org.kuali.rice.krad.uif.UifConstants.ViewType, java.util.Map<java.lang.String,java.lang.String>)
*/
public String getViewIdByTypeIndex(UifDictionaryIndex index, UifConstants.ViewType viewTypeName,
Map<String, String> indexKey) {
if (viewTypeName == null) {
throw new IllegalArgumentException("invalid (blank) view type name");
}
if ((indexKey == null) || indexKey.isEmpty()) {
throw new IllegalArgumentException("index key must have at least one entry");
}
return index.getViewIdByTypeIndex(viewTypeName, indexKey);
}
/**
* @see org.kuali.rice.krad.datadictionary.DataDictionaryIndexMapper#viewByTypeExist(UifDictionaryIndex,
* java.lang.String, java.util.Map)
*/
public boolean viewByTypeExist(UifDictionaryIndex index, UifConstants.ViewType viewTypeName,
Map<String, String> indexKey) {
if (viewTypeName == null) {
throw new IllegalArgumentException("invalid (blank) view type name");
}
if ((indexKey == null) || indexKey.isEmpty()) {
throw new IllegalArgumentException("index key must have at least one entry");
}
return index.viewByTypeExist(viewTypeName, indexKey);
}
/**
* @see org.kuali.rice.krad.datadictionary.DataDictionaryMapper#getViewPropertiesById(org.kuali.rice.krad.datadictionary.view.ViewDictionaryIndex,
* java.lang.String)
*/
public PropertyValues getViewPropertiesById(UifDictionaryIndex index, String viewId) {
if (StringUtils.isBlank(viewId)) {
throw new IllegalArgumentException("invalid (blank) view id");
}
return index.getViewPropertiesById(viewId);
}
/**
* @see org.kuali.rice.krad.datadictionary.DataDictionaryIndexMapper#getViewPropertiesByType(UifDictionaryIndex,
* java.lang.String, java.util.Map)
*/
public PropertyValues getViewPropertiesByType(UifDictionaryIndex index, UifConstants.ViewType viewTypeName,
Map<String, String> indexKey) {
if (viewTypeName == null) {
throw new IllegalArgumentException("invalid (blank) view type name");
}
if ((indexKey == null) || indexKey.isEmpty()) {
throw new IllegalArgumentException("index key must have at least one entry");
}
return index.getViewPropertiesByType(viewTypeName, indexKey);
}
/**
* @see org.kuali.rice.krad.datadictionary.DataDictionaryMapper#getViewsForType(UifDictionaryIndex,
* java.lang.String)
*/
public List<View> getViewsForType(UifDictionaryIndex index, UifConstants.ViewType viewTypeName) {
if (viewTypeName == null) {
throw new IllegalArgumentException("invalid (blank) view type name");
}
return index.getViewsForType(viewTypeName);
}
}
| apache-2.0 |