repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
VHAINNOVATIONS/Telepathology | Source/Java/ImagingCommon/main/src/java/gov/va/med/imaging/exceptions/StudyURNFormatException.java | 472 | package gov.va.med.imaging.exceptions;
public class StudyURNFormatException
extends URNFormatException
{
private static final long serialVersionUID = 6271193731031546478L;
public StudyURNFormatException()
{
super();
}
public StudyURNFormatException(String message)
{
super(message);
}
public StudyURNFormatException(Throwable cause)
{
super(cause);
}
public StudyURNFormatException(String message, Throwable cause)
{
super(message, cause);
}
}
| apache-2.0 |
opentelecoms-org/jsmpp | jsmpp/src/main/java/org/jsmpp/session/state/SMPPSessionState.java | 6024 | /*
* 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.jsmpp.session.state;
import java.io.IOException;
import org.jsmpp.bean.Command;
import org.jsmpp.session.ResponseHandler;
import org.jsmpp.session.SMPPSessionContext;
/**
* This class provides the interface to response to every incoming SMPP Command.
* How the response behavior is, depends on its state, or the
* implementation of this class.
*
* @author uudashr
* @version 1.0
* @since 2.0
*/
public interface SMPPSessionState extends GenericSMPPSessionState {
SMPPSessionState OPEN = new SMPPSessionOpen();
SMPPSessionState BOUND_RX = new SMPPSessionBoundRX();
SMPPSessionState BOUND_TX = new SMPPSessionBoundTX();
SMPPSessionState BOUND_TRX = new SMPPSessionBoundTRX();
SMPPSessionState UNBOUND = new SMPPSessionUnbound();
SMPPSessionState CLOSED = new SMPPSessionClosed();
/**
* Process the bind response command.
*
* @param sessionContext the session context.
* @param pduHeader is the PDU header.
* @param pdu is the complete PDU.
* @param responseHandler is the session handler.
* @throws IOException if an input or output error occurred.
*/
void processBindResp(SMPPSessionContext sessionContext, Command pduHeader, byte[] pdu,
ResponseHandler responseHandler) throws IOException;
/**
* Process the submit short message response command.
*
* @param pduHeader is the PDU header.
* @param pdu is the complete PDU.
* @param responseHandler is the response handler.
* @throws IOException if there is an I/O error found.
*/
void processSubmitSmResp(Command pduHeader, byte[] pdu,
ResponseHandler responseHandler) throws IOException;
/**
* Process a submit multiple message response.
*
* @param pduHeader is the PDU header.
* @param pdu is the complete PDU.
* @param responseHandler is the response handler.
* @throws IOException if there is an I/O error found.
*/
void processSubmitMultiResp(Command pduHeader, byte[] pdu,
ResponseHandler responseHandler) throws IOException;
/**
* Process the query short message response command.
*
* @param pduHeader is the PDU header.
* @param pdu is the complete PDU.
* @param responseHandler is the session handler.
* @throws IOException throw if there is an IO error occur.
*/
void processQuerySmResp(Command pduHeader, byte[] pdu,
ResponseHandler responseHandler) throws IOException;
/**
* Process the deliver short message request command.
*
* @param pduHeader is the PDU header.
* @param pdu is the complete PDU.
* @param responseHandler is the session handler.
* @throws IOException throw if there is an IO error occur.
*/
void processDeliverSm(Command pduHeader, byte[] pdu,
ResponseHandler responseHandler) throws IOException;
/**
* Process the cancel short message request command.
*
* @param pduHeader is the PDU header.
* @param pdu is the complete PDU.
* @param responseHandler is the session handler.
* @throws IOException throw if there is an IO error occur.
*/
void processCancelSmResp(Command pduHeader, byte[] pdu,
ResponseHandler responseHandler) throws IOException;
/**
* Process the replace short message request command.
*
* @param pduHeader is the PDU header.
* @param pdu is the complete PDU.
* @param responseHandler is the session handler.
* @throws IOException throw if there is an IO error occur.
*/
void processReplaceSmResp(Command pduHeader, byte[] pdu,
ResponseHandler responseHandler) throws IOException;
/**
* Process the alert notification request command.
*
* @param pduHeader is the PDU header.
* @param pdu is the complete PDU.
* @param responseHandler is the session handler.
*/
void processAlertNotification(Command pduHeader, byte[] pdu,
ResponseHandler responseHandler);
/**
* Process the broadcast short message response command.
*
* @param pduHeader is the PDU header.
* @param pdu is the complete broadcast_sm PDU.
* @param responseHandler is the session handler.
* @throws IOException throw if there is an IO error occur.
*/
void processBroadcastSmResp(Command pduHeader, byte[] pdu,
ResponseHandler responseHandler) throws IOException;
/**
* Process the cancel broadcast short message response command.
*
* @param pduHeader is the PDU header.
* @param pdu is the complete cancel_broadcast_sm PDU.
* @param responseHandler is the session handler.
* @throws IOException throw if there is an IO error occur.
*/
void processCancelBroadcastSmResp(Command pduHeader, byte[] pdu,
ResponseHandler responseHandler) throws IOException;
/**
* Process the query broadcast short message response command.
*
* @param pduHeader is the PDU header.
* @param pdu is the complete query_broadcast_sm PDU.
* @param responseHandler is the session handler.
* @throws IOException throw if there is an IO error occur.
*/
void processQueryBroadcastSmResp(Command pduHeader, byte[] pdu,
ResponseHandler responseHandler) throws IOException;
}
| apache-2.0 |
dadoonet/spring-elasticsearch | src/test/java/fr/pilato/spring/elasticsearch/it/annotation/SecurityOptionalConfig.java | 1399 | /*
* Licensed to David Pilato (the "Author") under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Author 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 fr.pilato.spring.elasticsearch.it.annotation;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Properties;
import static fr.pilato.spring.elasticsearch.ElasticsearchAbstractFactoryBean.XPACK_USER;
import static fr.pilato.spring.elasticsearch.it.BaseTest.testCredentials;
@Configuration
public class SecurityOptionalConfig {
@Bean("esProperties")
public Properties properties() {
Properties properties = new Properties();
properties.setProperty(XPACK_USER, testCredentials);
return properties;
}
}
| apache-2.0 |
ISSC/Bluebit | src/com/issc/widget/LoadingFragment.java | 1195 | // vim: et sw=4 sts=4 tabstop=4
/*
* 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.issc.widget;
import com.issc.R;
import android.app.DialogFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class LoadingFragment extends DialogFragment {
public LoadingFragment() {
super();
setStyle(DialogFragment.STYLE_NO_FRAME, 0);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.progressdialog, container, false);
return v;
}
}
| apache-2.0 |
spark/spark-sdk-android | cloudsdk/src/main/java/io/particle/android/sdk/cloud/ParticleDevice.java | 26059 | package io.particle.android.sdk.cloud;
import android.annotation.SuppressLint;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.MainThread;
import android.support.annotation.Nullable;
import android.support.annotation.WorkerThread;
import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import javax.annotation.ParametersAreNonnullByDefault;
import io.particle.android.sdk.cloud.Responses.ReadDoubleVariableResponse;
import io.particle.android.sdk.cloud.Responses.ReadIntVariableResponse;
import io.particle.android.sdk.cloud.Responses.ReadObjectVariableResponse;
import io.particle.android.sdk.cloud.Responses.ReadStringVariableResponse;
import io.particle.android.sdk.cloud.Responses.ReadVariableResponse;
import io.particle.android.sdk.cloud.exceptions.ParticleCloudException;
import io.particle.android.sdk.cloud.models.DeviceStateChange;
import io.particle.android.sdk.utils.ParticleInternalStringUtils;
import io.particle.android.sdk.utils.Preconditions;
import io.particle.android.sdk.utils.TLog;
import okio.Okio;
import retrofit.RetrofitError;
import retrofit.client.Response;
import retrofit.mime.TypedByteArray;
import retrofit.mime.TypedFile;
import static io.particle.android.sdk.utils.Py.list;
// don't warn about public APIs not being referenced inside this module, or about
// the _default locale_ in a bunch of backend code
@SuppressLint("DefaultLocale")
@SuppressWarnings({"UnusedDeclaration"})
@ParametersAreNonnullByDefault
public class ParticleDevice implements Parcelable {
public enum ParticleDeviceType {
CORE,
PHOTON,
P1,
RASPBERRY_PI,
RED_BEAR_DUO,
BLUZ,
DIGISTUMP_OAK,
ELECTRON,
ARGON,
BORON,
XENON;
// FIXME: ADD MESH TYPES BELOW
public static ParticleDeviceType fromInt(int intValue) {
switch (intValue) {
case 0:
return CORE;
case 8:
return P1;
case 10:
return ELECTRON;
case 31:
return RASPBERRY_PI;
case 82:
return DIGISTUMP_OAK;
case 88:
return RED_BEAR_DUO;
case 103:
return BLUZ;
case 6:
default:
return PHOTON;
}
}
}
public enum ParticleDeviceState {
CAME_ONLINE,
FLASH_STARTED,
FLASH_SUCCEEDED,
FLASH_FAILED,
APP_HASH_UPDATED,
ENTERED_SAFE_MODE,
SAFE_MODE_UPDATER,
WENT_OFFLINE,
UNKNOWN
}
public enum VariableType {
INT,
DOUBLE,
STRING
}
public static class FunctionDoesNotExistException extends Exception {
public FunctionDoesNotExistException(String functionName) {
super("Function " + functionName + " does not exist on this device");
}
}
public static class VariableDoesNotExistException extends Exception {
public VariableDoesNotExistException(String variableName) {
super("Variable " + variableName + " does not exist on this device");
}
}
public enum KnownApp {
TINKER("tinker");
private final String appName;
KnownApp(String appName) {
this.appName = appName;
}
public String getAppName() {
return appName;
}
}
private static final int MAX_PARTICLE_FUNCTION_ARG_LENGTH = 63;
private static final TLog log = TLog.get(ParticleDevice.class);
private final CopyOnWriteArrayList<Long> subscriptions = new CopyOnWriteArrayList<>();
private final ApiDefs.CloudApi mainApi;
private final ParticleCloud cloud;
volatile DeviceState deviceState;
private volatile boolean isFlashing = false;
ParticleDevice(ApiDefs.CloudApi mainApi, ParticleCloud cloud, DeviceState deviceState) {
this.mainApi = mainApi;
this.cloud = cloud;
this.deviceState = deviceState;
}
/**
* Device ID string
*/
public String getID() {
return deviceState.deviceId;
}
/**
* Device name. Device can be renamed in the cloud via #setName(String)
*/
public String getName() {
return deviceState.name;
}
/**
* Rename the device in the cloud. If renaming fails name will stay the same.
*/
public void setName(String newName) throws ParticleCloudException {
cloud.rename(this.deviceState.deviceId, newName);
}
/**
* Is device connected to the cloud?
*/
public boolean isConnected() {
return deviceState.isConnected;
}
/**
* Get an immutable set of all the function names exposed by device
*/
public Set<String> getFunctions() {
// no need for a defensive copy, this is an immutable set
return deviceState.functions;
}
/**
* Get an immutable map of exposed variables on device with their respective types.
*/
public Map<String, VariableType> getVariables() {
// no need for a defensive copy, this is an immutable set
return deviceState.variables;
}
/**
* Device firmware version string
*/
public String getVersion() {
return deviceState.version;
}
public boolean requiresUpdate() {
return deviceState.requiresUpdate;
}
public ParticleDeviceType getDeviceType() {
return deviceState.deviceType;
}
public int getPlatformID() {
return deviceState.platformId;
}
public int getProductID() {
return deviceState.productId;
}
public boolean isCellular() {
return deviceState.cellular;
}
public String getImei() {
return deviceState.imei;
}
public String getIccid() {
return deviceState.lastIccid;
}
public String getCurrentBuild() {
return deviceState.currentBuild;
}
public String getDefaultBuild() {
return deviceState.defaultBuild;
}
public String getIpAddress() {
return deviceState.ipAddress;
}
public String getLastAppName() {
return deviceState.lastAppName;
}
public String getStatus() {
return deviceState.status;
}
public Date getLastHeard() {
return deviceState.lastHeard;
}
@WorkerThread
public float getCurrentDataUsage() throws ParticleCloudException {
float maxUsage = 0;
try {
Response response = mainApi.getCurrentDataUsage(deviceState.lastIccid);
JSONObject result = new JSONObject(new String(((TypedByteArray) response.getBody()).getBytes()));
JSONArray usages = result.getJSONArray("usage_by_day");
for (int i = 0; i < usages.length(); i++) {
JSONObject usageElement = usages.getJSONObject(i);
if (usageElement.has("mbs_used_cumulative")) {
double usage = usageElement.getDouble("mbs_used_cumulative");
if (usage > maxUsage) {
maxUsage = (float) usage;
}
}
}
} catch (JSONException | RetrofitError e) {
throw new ParticleCloudException(e);
}
return maxUsage;
}
/**
* Return the value for <code>variableName</code> on this Particle device.
* <p>
* Unless you specifically require generic handling, it is recommended that you use the
* <code>get(type)Variable</code> methods instead, e.g.: <code>getIntVariable()</code>.
* These type-specific methods don't require extra casting or type checking on your part, and
* they more clearly and succinctly express your intent.
*/
@WorkerThread
public Object getVariable(String variableName)
throws ParticleCloudException, IOException, VariableDoesNotExistException {
VariableRequester<Object, ReadObjectVariableResponse> requester =
new VariableRequester<Object, ReadObjectVariableResponse>(this) {
@Override
ReadObjectVariableResponse callApi(String variableName) {
return mainApi.getVariable(deviceState.deviceId, variableName);
}
};
return requester.getVariable(variableName);
}
/**
* Return the value for <code>variableName</code> as an int.
* <p>
* Where practical, this method is recommended over the generic {@link #getVariable(String)}.
* See the javadoc on that method for details.
*/
@WorkerThread
public int getIntVariable(String variableName) throws ParticleCloudException,
IOException, VariableDoesNotExistException, ClassCastException {
VariableRequester<Integer, ReadIntVariableResponse> requester =
new VariableRequester<Integer, ReadIntVariableResponse>(this) {
@Override
ReadIntVariableResponse callApi(String variableName) {
return mainApi.getIntVariable(deviceState.deviceId, variableName);
}
};
return requester.getVariable(variableName);
}
/**
* Return the value for <code>variableName</code> as a String.
* <p>
* Where practical, this method is recommended over the generic {@link #getVariable(String)}.
* See the javadoc on that method for details.
*/
@WorkerThread
public String getStringVariable(String variableName) throws ParticleCloudException,
IOException, VariableDoesNotExistException, ClassCastException {
VariableRequester<String, ReadStringVariableResponse> requester =
new VariableRequester<String, ReadStringVariableResponse>(this) {
@Override
ReadStringVariableResponse callApi(String variableName) {
return mainApi.getStringVariable(deviceState.deviceId, variableName);
}
};
return requester.getVariable(variableName);
}
/**
* Return the value for <code>variableName</code> as a double.
* <p>
* Where practical, this method is recommended over the generic {@link #getVariable(String)}.
* See the javadoc on that method for details.
*/
@WorkerThread
public double getDoubleVariable(String variableName) throws ParticleCloudException,
IOException, VariableDoesNotExistException, ClassCastException {
VariableRequester<Double, ReadDoubleVariableResponse> requester =
new VariableRequester<Double, ReadDoubleVariableResponse>(this) {
@Override
ReadDoubleVariableResponse callApi(String variableName) {
return mainApi.getDoubleVariable(deviceState.deviceId, variableName);
}
};
return requester.getVariable(variableName);
}
/**
* Call a function on the device
*
* @param functionName Function name
* @param args Array of arguments to pass to the function on the device.
* Arguments must not be more than MAX_PARTICLE_FUNCTION_ARG_LENGTH chars
* in length. If any arguments are longer, a runtime exception will be thrown.
* @return result code: a value of 1 indicates success
*/
@WorkerThread
public int callFunction(String functionName, @Nullable List<String> args)
throws ParticleCloudException, IOException, FunctionDoesNotExistException {
// TODO: check response of calling a non-existent function
if (!deviceState.functions.contains(functionName)) {
throw new FunctionDoesNotExistException(functionName);
}
// null is accepted here, but it won't be in the Retrofit API call later
if (args == null) {
args = list();
}
String argsString = ParticleInternalStringUtils.join(args, ',');
Preconditions.checkArgument(argsString.length() < MAX_PARTICLE_FUNCTION_ARG_LENGTH,
String.format("Arguments '%s' exceed max args length of %d",
argsString, MAX_PARTICLE_FUNCTION_ARG_LENGTH));
Responses.CallFunctionResponse response;
try {
response = mainApi.callFunction(deviceState.deviceId, functionName,
new FunctionArgs(argsString));
} catch (RetrofitError e) {
throw new ParticleCloudException(e);
}
if (!response.connected) {
cloud.onDeviceNotConnected(deviceState);
throw new IOException("Device is not connected.");
} else {
return response.returnValue;
}
}
/**
* Call a function on the device
*
* @param functionName Function name
* @return value of the function
*/
@WorkerThread
public int callFunction(String functionName) throws ParticleCloudException, IOException,
FunctionDoesNotExistException {
return callFunction(functionName, null);
}
/**
* Subscribe to events from this device
*
* @param eventNamePrefix (optional, may be null) a filter to match against for events. If
* null or an empty string, all device events will be received by the handler
* trigger eventHandler
* @param handler The handler for the events received for this subscription.
* @return the subscription ID
* (see {@link ParticleCloud#subscribeToAllEvents(String, ParticleEventHandler)} for more info
*/
public long subscribeToEvents(@Nullable String eventNamePrefix,
ParticleEventHandler handler)
throws IOException {
return cloud.subscribeToDeviceEvents(eventNamePrefix, deviceState.deviceId, handler);
}
/**
* Unsubscribe from events.
*
* @param eventListenerID The ID of the subscription to be cancelled. (returned from
* {@link #subscribeToEvents(String, ParticleEventHandler)}
*/
public void unsubscribeFromEvents(long eventListenerID) throws ParticleCloudException {
cloud.unsubscribeFromEventWithID(eventListenerID);
}
/**
* Remove device from current logged in user account
*/
@WorkerThread
public void unclaim() throws ParticleCloudException {
try {
cloud.unclaimDevice(deviceState.deviceId);
} catch (RetrofitError e) {
throw new ParticleCloudException(e);
}
}
public boolean isRunningTinker() {
List<String> lowercaseFunctions = list();
for (String func : deviceState.functions) {
lowercaseFunctions.add(func.toLowerCase());
}
List<String> tinkerFunctions = list("analogread", "analogwrite", "digitalread", "digitalwrite");
return (isConnected() && lowercaseFunctions.containsAll(tinkerFunctions));
}
public boolean isFlashing() {
return isFlashing;
}
@WorkerThread
public void flashKnownApp(final KnownApp knownApp) throws ParticleCloudException {
performFlashingChange(() -> mainApi.flashKnownApp(deviceState.deviceId, knownApp.appName));
}
@WorkerThread
public void flashBinaryFile(final File file) throws ParticleCloudException {
performFlashingChange(() -> mainApi.flashFile(deviceState.deviceId,
new TypedFile("application/octet-stream", file)));
}
@WorkerThread
public void flashBinaryFile(InputStream stream) throws ParticleCloudException, IOException {
final byte[] bytes = Okio.buffer(Okio.source(stream)).readByteArray();
performFlashingChange(() -> mainApi.flashFile(deviceState.deviceId, new TypedFakeFile(bytes)));
}
@WorkerThread
public void flashCodeFile(final File file) throws ParticleCloudException {
performFlashingChange(() -> mainApi.flashFile(deviceState.deviceId,
new TypedFile("multipart/form-data", file)));
}
@WorkerThread
public void flashCodeFile(InputStream stream) throws ParticleCloudException, IOException {
final byte[] bytes = Okio.buffer(Okio.source(stream)).readByteArray();
performFlashingChange(() -> mainApi.flashFile(deviceState.deviceId, new TypedFakeFile(bytes, "multipart/form-data", "code.ino")));
}
public ParticleCloud getCloud() {
return cloud;
}
@WorkerThread
public void refresh() throws ParticleCloudException {
// just calling this get method will update everything as expected.
cloud.getDevice(deviceState.deviceId);
}
private interface FlashingChange {
void executeFlashingChange() throws RetrofitError;
}
// FIXME: ugh. these "cloud.notifyDeviceChanged();" calls are a hint that flashing maybe
// should just live in a class of its own, or that it should just be a delegate on
// ParticleCloud. Review this later.
private void performFlashingChange(FlashingChange flashingChange) throws ParticleCloudException {
try {
flashingChange.executeFlashingChange();
//listens for flashing event, on success unsubscribe from listening.
subscribeToSystemEvent("spark/flash/status", new SimpleParticleEventHandler() {
@Override
public void onEvent(String eventName, ParticleEvent particleEvent) {
if ("success".equals(particleEvent.dataPayload)) {
isFlashing = false;
try {
ParticleDevice.this.refresh();
cloud.unsubscribeFromEventWithHandler(this);
} catch (ParticleCloudException e) {
// not much else we can really do here...
log.w("Unable to reset flashing state for %s" + deviceState.deviceId, e);
}
} else {
isFlashing = true;
}
cloud.notifyDeviceChanged();
}
});
} catch (RetrofitError | IOException e) {
throw new ParticleCloudException(e);
}
}
/**
* Subscribes to system events of current device. Events emitted to EventBus listener.
*
* @throws ParticleCloudException Failure to subscribe to system events.
* @see <a href="https://github.com/greenrobot/EventBus">EventBus</a>
*/
@MainThread
public void subscribeToSystemEvents() throws ParticleCloudException {
try {
EventBus eventBus = EventBus.getDefault();
subscriptions.add(subscribeToSystemEvent("spark/status", (eventName, particleEvent) ->
sendUpdateStatusChange(eventBus, particleEvent.dataPayload)));
subscriptions.add(subscribeToSystemEvent("spark/flash/status", (eventName, particleEvent) ->
sendUpdateFlashChange(eventBus, particleEvent.dataPayload)));
subscriptions.add(subscribeToSystemEvent("spark/device/app-hash", (eventName, particleEvent) ->
sendSystemEventBroadcast(new DeviceStateChange(ParticleDevice.this,
ParticleDeviceState.APP_HASH_UPDATED), eventBus)));
subscriptions.add(subscribeToSystemEvent("spark/status/safe-mode", (eventName, particleEvent) ->
sendSystemEventBroadcast(new DeviceStateChange(ParticleDevice.this,
ParticleDeviceState.SAFE_MODE_UPDATER), eventBus)));
subscriptions.add(subscribeToSystemEvent("spark/safe-mode-updater/updating", (eventName, particleEvent) ->
sendSystemEventBroadcast(new DeviceStateChange(ParticleDevice.this,
ParticleDeviceState.ENTERED_SAFE_MODE), eventBus)));
} catch (IOException e) {
log.d("Failed to auto-subscribe to system events");
throw new ParticleCloudException(e);
}
}
private void sendSystemEventBroadcast(DeviceStateChange deviceStateChange, EventBus eventBus) {
cloud.sendSystemEventBroadcast(deviceStateChange);
eventBus.post(deviceStateChange);
}
/**
* Unsubscribes from system events of current device.
*
* @throws ParticleCloudException Failure to unsubscribe from system events.
*/
public void unsubscribeFromSystemEvents() throws ParticleCloudException {
for (Long subscriptionId : subscriptions) {
unsubscribeFromEvents(subscriptionId);
}
}
private long subscribeToSystemEvent(String eventNamePrefix,
SimpleParticleEventHandler
particleEventHandler) throws IOException {
//Error would be handled in same way for every event name prefix, thus only simple onEvent listener is needed
return subscribeToEvents(eventNamePrefix, new ParticleEventHandler() {
@Override
public void onEvent(String eventName, ParticleEvent particleEvent) {
particleEventHandler.onEvent(eventName, particleEvent);
}
@Override
public void onEventError(Exception e) {
log.d("Event error in system event handler");
}
});
}
private void sendUpdateStatusChange(EventBus eventBus, String data) {
DeviceStateChange deviceStateChange = null;
switch (data) {
case "online":
sendSystemEventBroadcast(new DeviceStateChange(this, ParticleDeviceState.CAME_ONLINE),
eventBus);
break;
case "offline":
sendSystemEventBroadcast(new DeviceStateChange(this, ParticleDeviceState.WENT_OFFLINE),
eventBus);
break;
}
}
private void sendUpdateFlashChange(EventBus eventBus, String data) {
DeviceStateChange deviceStateChange = null;
switch (data) {
case "started":
sendSystemEventBroadcast(new DeviceStateChange(this, ParticleDeviceState.FLASH_STARTED),
eventBus);
break;
case "success":
sendSystemEventBroadcast(new DeviceStateChange(this, ParticleDeviceState.FLASH_SUCCEEDED),
eventBus);
break;
}
}
@Override
public String toString() {
return "ParticleDevice{" +
"deviceId=" + deviceState.deviceId +
", isConnected=" + deviceState.isConnected +
", deviceType=" + deviceState.deviceType +
'}';
}
//region Parcelable
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeParcelable(deviceState, flags);
}
@Override
public int describeContents() {
return 0;
}
public static final Creator<ParticleDevice> CREATOR = new Creator<ParticleDevice>() {
@Override
public ParticleDevice createFromParcel(Parcel in) {
SDKProvider sdkProvider = ParticleCloudSDK.getSdkProvider();
DeviceState deviceState = in.readParcelable(DeviceState.class.getClassLoader());
return sdkProvider.getParticleCloud().getDeviceFromState(deviceState);
}
@Override
public ParticleDevice[] newArray(int size) {
return new ParticleDevice[size];
}
};
//endregion
private static class TypedFakeFile extends TypedByteArray {
private final String fileName;
/**
* Constructs a new typed byte array. Sets mimeType to {@code application/unknown} if absent.
*
* @throws NullPointerException if bytes are null
*/
public TypedFakeFile(byte[] bytes) {
this(bytes, "application/octet-stream", "tinker_firmware.bin");
}
public TypedFakeFile(byte[] bytes, String mimeType, String fileName) {
super(mimeType, bytes);
this.fileName = fileName;
}
@Override
public String fileName() {
return fileName;
}
}
private static abstract class VariableRequester<T, R extends ReadVariableResponse<T>> {
@WorkerThread
abstract R callApi(String variableName);
private final ParticleDevice device;
VariableRequester(ParticleDevice device) {
this.device = device;
}
@WorkerThread
T getVariable(String variableName)
throws ParticleCloudException, IOException, VariableDoesNotExistException {
if (!device.deviceState.variables.containsKey(variableName)) {
throw new VariableDoesNotExistException(variableName);
}
R reply;
try {
reply = callApi(variableName);
} catch (RetrofitError e) {
throw new ParticleCloudException(e);
}
if (!reply.coreInfo.connected) {
// FIXME: we should be doing this "connected" check on _any_ reply that comes back
// with a "coreInfo" block.
device.cloud.onDeviceNotConnected(device.deviceState);
throw new IOException("Device is not connected.");
} else {
return reply.result;
}
}
}
}
| apache-2.0 |
kermitt2/grobid | grobid-core/src/main/java/org/grobid/core/features/FeaturesVectorFulltext.java | 5369 | package org.grobid.core.features;
import org.grobid.core.layout.LayoutToken;
import org.grobid.core.utilities.TextUtilities;
/**
* Class for features used for fulltext parsing.
*
*/
public class FeaturesVectorFulltext {
public LayoutToken token = null; // not a feature, reference value
public String string = null; // lexical feature
public String label = null; // label if known
public String blockStatus = null; // one of BLOCKSTART, BLOCKIN, BLOCKEND
public String lineStatus = null; // one of LINESTART, LINEIN, LINEEND
public String fontStatus = null; // one of NEWFONT, SAMEFONT
public String fontSize = null; // one of HIGHERFONT, SAMEFONTSIZE, LOWERFONT
public String alignmentStatus = null; // one of ALIGNEDLEFT, INDENTED, CENTERED - applied to the whole line
public boolean bold = false;
public boolean italic = false;
public String capitalisation = null; // one of INITCAP, ALLCAPS, NOCAPS
public String digit; // one of ALLDIGIT, CONTAINDIGIT, NODIGIT
public boolean singleChar = false;
public String punctType = null;
// one of NOPUNCT, OPENBRACKET, ENDBRACKET, DOT, COMMA, HYPHEN, QUOTE, PUNCT (default)
public int relativeDocumentPosition = -1;
public int relativePagePositionChar = -1;
public int relativePagePosition = -1;
// graphic in closed proximity of the current block
public boolean bitmapAround = false;
public boolean vectorAround = false;
// if a graphic is in close proximity of the current block, characteristics of this graphic
public int closestGraphicHeight = -1;
public int closestGraphicWidth = -1;
public int closestGraphicSurface = -1;
public int spacingWithPreviousBlock = 0; // discretized
public int characterDensity = 0; // discretized
// how the reference callouts are expressed, if known
public String calloutType = null; // one of UNKNOWN, NUMBER, AUTHOR
public boolean calloutKnown = false; // true if the token match a known reference label
public boolean superscript = false;
public String printVector() {
if (string == null) return null;
if (string.length() == 0) return null;
StringBuffer res = new StringBuffer();
// token string (1)
res.append(string);
// lowercase string
res.append(" " + string.toLowerCase());
// prefix (4)
res.append(" " + TextUtilities.prefix(string, 1));
res.append(" " + TextUtilities.prefix(string, 2));
res.append(" " + TextUtilities.prefix(string, 3));
res.append(" " + TextUtilities.prefix(string, 4));
// suffix (4)
res.append(" " + TextUtilities.suffix(string, 1));
res.append(" " + TextUtilities.suffix(string, 2));
res.append(" " + TextUtilities.suffix(string, 3));
res.append(" " + TextUtilities.suffix(string, 4));
// at this stage, we have written 10 features
// block information (1)
res.append(" " + blockStatus);
// line information (1)
res.append(" " + lineStatus);
// line position/identation (1)
res.append(" " + alignmentStatus);
// font information (1)
res.append(" " + fontStatus);
// font size information (1)
res.append(" " + fontSize);
// string type information (3)
if (bold)
res.append(" 1");
else
res.append(" 0");
if (italic)
res.append(" 1");
else
res.append(" 0");
// capitalisation (1)
if (digit.equals("ALLDIGIT"))
res.append(" NOCAPS");
else
res.append(" " + capitalisation);
// digit information (1)
res.append(" " + digit);
// character information (1)
if (singleChar)
res.append(" 1");
else
res.append(" 0");
// at this stage, we have written 20 features
// punctuation information (1)
res.append(" " + punctType); // in case the token is a punctuation (NO otherwise)
// relative document position (1)
res.append(" " + relativeDocumentPosition);
// relative page position (1)
res.append(" " + relativePagePosition);
// proximity of a graphic to the current block (2)
if (bitmapAround)
res.append(" 1");
else
res.append(" 0");
/*if (vectorAround)
res.append(" 1");
else
res.append(" 0");*/
// space with previous block, discretised (1)
//res.append(" " + spacingWithPreviousBlock);
//res.append(" " + 0);
// character density of the previous block, discretised (1)
//res.append(" " + characterDensity);
//res.append(" " + 0);
// label - for training data (1)
/*if (label != null)
res.append(" " + label + "\n");
else
res.append(" 0\n");
*/
if (calloutType != null)
res.append(" " + calloutType);
else
res.append(" UNKNOWN");
if (calloutKnown)
res.append(" 1");
else
res.append(" 0");
if (superscript)
res.append(" 1");
else
res.append(" 0");
res.append("\n");
return res.toString();
}
} | apache-2.0 |
aws/aws-sdk-java | aws-java-sdk-glue/src/main/java/com/amazonaws/services/glue/model/transform/GetCatalogImportStatusRequestMarshaller.java | 2076 | /*
* 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.glue.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.glue.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* GetCatalogImportStatusRequestMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class GetCatalogImportStatusRequestMarshaller {
private static final MarshallingInfo<String> CATALOGID_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
.marshallLocationName("CatalogId").build();
private static final GetCatalogImportStatusRequestMarshaller instance = new GetCatalogImportStatusRequestMarshaller();
public static GetCatalogImportStatusRequestMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(GetCatalogImportStatusRequest getCatalogImportStatusRequest, ProtocolMarshaller protocolMarshaller) {
if (getCatalogImportStatusRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(getCatalogImportStatusRequest.getCatalogId(), CATALOGID_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
| apache-2.0 |
warrenmnocos/oauth2 | oauth2-security/src/main/java/org/filetec/oauth2/security/AuthorizationServerConfiguration.java | 2994 | /*
* Copyright 2016 Pivotal 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 org.filetec.oauth2.security;
import javax.inject.Inject;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;
/**
*
* @author warren.nocos
*/
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
protected final UserDetailsService userDetailsService;
protected final ClientDetailsService clientDetailsService;
protected final AuthenticationManager authenticationManager;
protected final TokenStore tokenStore;
@Inject
public AuthorizationServerConfiguration(UserDetailsService userDetailsService,
ClientDetailsService clientDetailsService,
AuthenticationManager authenticationManager) {
this.userDetailsService = userDetailsService;
this.clientDetailsService = clientDetailsService;
this.authenticationManager = authenticationManager;
tokenStore = new InMemoryTokenStore();
}
@Bean(name = "tokenStore")
public TokenStore getTokenStore() {
return tokenStore;
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.withClientDetails(clientDetailsService);
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.tokenStore(tokenStore)
.userDetailsService(userDetailsService)
.authenticationManager(authenticationManager);
}
}
| apache-2.0 |
lessthanoptimal/BoofCV | main/boofcv-types/src/test/java/boofcv/struct/TestListIntPoint2D.java | 2929 | /*
* Copyright (c) 2020, Peter Abeles. All Rights Reserved.
*
* This file is part of BoofCV (http://boofcv.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 boofcv.struct;
import boofcv.testing.BoofStandardJUnit;
import georegression.struct.point.Point2D_F32;
import georegression.struct.point.Point2D_F64;
import georegression.struct.point.Point2D_I16;
import georegression.struct.point.Point2D_I32;
import org.ddogleg.struct.DogArray;
import org.ejml.UtilEjml;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author Peter Abeles
*/
class TestListIntPoint2D extends BoofStandardJUnit {
@Test
void configure() {
var alg = new ListIntPoint2D();
alg.configure(100, 105);
assertEquals(100,alg.imageWidth);
alg.add(10,20);
assertEquals(1,alg.size());
alg.configure(67, 105);
assertEquals(0,alg.size());
assertEquals(67,alg.imageWidth);
}
@Test
void add() {
var alg = new ListIntPoint2D();
alg.configure(100,105);
alg.add(10,20);
alg.add(16,2);
assertEquals(2,alg.size());
assertEquals(20*100+10,alg.points.get(0));
assertEquals(2*100+16,alg.points.get(1));
}
@Test
void get_U16() {
var alg = new ListIntPoint2D();
alg.configure(100,105);
alg.add(10,20);
var p = new Point2D_I16();
alg.get(0,p);
assertEquals(10,p.x);
assertEquals(20,p.y);
}
@Test
void get_S32() {
var alg = new ListIntPoint2D();
alg.configure(100,105);
alg.add(10,20);
var p = new Point2D_I32();
alg.get(0,p);
assertEquals(10,p.x);
assertEquals(20,p.y);
}
@Test
void get_F32() {
var alg = new ListIntPoint2D();
alg.configure(100,105);
alg.add(10,20);
var p = new Point2D_F32();
alg.get(0,p);
assertEquals(10, p.x, UtilEjml.TEST_F32);
assertEquals(20, p.y, UtilEjml.TEST_F32);
}
@Test
void get_F64() {
var alg = new ListIntPoint2D();
alg.configure(100,105);
alg.add(10,20);
var p = new Point2D_F64();
alg.get(0,p);
assertEquals(10, p.x, UtilEjml.TEST_F32);
assertEquals(20, p.y, UtilEjml.TEST_F32);
}
@Test
void copyInto() {
var alg = new ListIntPoint2D();
alg.configure(100,105);
alg.add(10,20);
alg.add(16,2);
var list = new DogArray<>(Point2D_I16::new);
alg.copyInto(list);
assertEquals(2,list.size());
assertEquals(10,list.get(0).x);
assertEquals(20,list.get(0).y);
assertEquals(16,list.get(1).x);
assertEquals(2,list.get(1).y);
}
}
| apache-2.0 |
sbg/sevenbridges-java | api/src/main/java/com/sevenbridges/apiclient/transfer/UploadContext.java | 5821 | /*
* Copyright 2017 Seven Bridges Genomics, 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.sevenbridges.apiclient.transfer;
import com.sevenbridges.apiclient.file.File;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* This object allows user to take control of upload submitted to internal transfer manager via the
* {@link com.sevenbridges.apiclient.user.UserActions#submitUpload(com.sevenbridges.apiclient.upload.CreateUploadRequest)}
* calls.
*/
public interface UploadContext {
/**
* <b>BLOCKING CALL</b>
* <p>
* This is a blocking call, similar to invoking get on a {@link java.util.concurrent.Future}
* instance. Current thread will block until the file is fully uploaded to the Seven Bridges
* Platform, or until some exception happen. If the thread is interrupted from sleep, a runtime
* exception wrapping the interrupted exception will be thrown. If some other thread aborts, or
* pauses the upload, another runtime exception will be called, and will wake up the current
* sleeping thread.
* <p>
* If the upload is completed successfully this call will return the {@link File} resource
* instance that is uploaded.
*
* @return File 'file' resource that is uploaded
* @throws PausedUploadException if the current upload the thread is blocked on is paused by
* {@link #pauseTransfer()} call by some other thread
*/
File getFile() throws PausedUploadException;
/**
* <b>BLOCKING CALL</b>
* <p>
* This is a timed blocking call, similar to invoking get(timeValue, timeUnit) on a {@link
* java.util.concurrent.Future} instance. Current thread will wait specified time until the file
* is fully uploaded to the Seven Bridges Platform, or until some exception happen. If the thread
* is interrupted from sleep, a runtime exception wrapping the interrupted exception will be
* thrown. If some other thread aborts, or pauses the upload, another runtime exception will be
* called, and will wake up the current sleeping thread.
* <p>
* If the upload is completed successfully this call will return the {@link File} resource
* instance that is uploaded.
*
* @param timeValue the maximum number of TimeUnits to wait
* @param timeUnit durations of one unit of timeValue
* @return File 'file' resource that is uploaded
* @throws TimeoutException if the wait time times out, and the upload is still not
* completed
* @throws PausedUploadException if the current upload the thread is blocked on is paused by
* {@link #pauseTransfer()} call by some other thread
*/
File getFile(long timeValue, TimeUnit timeUnit) throws TimeoutException, PausedUploadException;
/**
* Checks if the current {@link com.sevenbridges.apiclient.upload.Upload}, managed by this
* UploadContext is finished successfully.
*
* @return Boolean indicator is upload finished
*/
boolean isFinished();
/**
* Aborts the {@link com.sevenbridges.apiclient.upload.Upload} managed by this UploadContext. Any
* thread blocked on the getFile() call on this uploadContext will be woken up by the
* RuntimeException. Upload is aborted totally, and any progress on this upload will be lost.
*/
void abortTransfer();
/**
* Gets the current state of the upload managed by this UploadContext.
*
* @return UploadState current state
*/
UploadState getState();
/**
* Pauses the {@link com.sevenbridges.apiclient.upload.Upload} managed by this UploadContext. Any
* thread blocked on the getFile() call on this uploadContext will be woken up by the
* RuntimeException that indicates that the upload is paused. Paused upload is not aborted on the
* Platform, and your progress (measured in file parts) is saved.
* <p>
* You can use this UploadContext object to resume upload via {@link
* com.sevenbridges.apiclient.user.UserActions#resumeUpload(UploadContext, java.io.File)} call.
* That call will provide a new instance of UploadContext, this one is useless after that call.
* <p>
* Pause action is not instantaneous, the call is not blocking, and it will put upload in the
* PAUSING state. After the first running part upload is finished, the upload state will change to
* PAUSED state.
*/
void pauseTransfer();
/**
* Gets summed number of bytes transferred by the {@link com.sevenbridges.apiclient.upload.Upload}
* managed by this UploadContext. This is a pretty low level byte counter, and it will update much
* more often than the part upload finished event.
*
* @return Current bytes transferred for this upload
*/
long getBytesTransferred();
/**
* Size of the whole upload in bytes.
*
* @return long upload size
*/
long getUploadSize();
/**
* Name of the {@link com.sevenbridges.apiclient.upload.Upload} managed by this UploadContext.
*
* @return String upload name
*/
String getUploadName();
/**
* ID of the {@link com.sevenbridges.apiclient.upload.Upload} managed by this UploadContext.
*
* @return String ID of the upload managed by this upload context
*/
String getUploadId();
}
| apache-2.0 |
xgqfrms/JavaWeb | JavaGUI/src/test_JLabel/JLabel02.java | 810 | package test_JLabel;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Point;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class JLabel02 {
public static void main(String args[]){
JFrame fra = new JFrame("Swing ´°Ìå±êÌâ");
JLabel lab = new JLabel("ÏĹâǬ"+"Èí¼þ¹¤³Ì",JLabel.CENTER);
//×ÖÌå
Font fon = new Font("Serief",Font.BOLD+Font.ITALIC,37);
lab.setFont(fon);
lab.setForeground(Color.RED);
//ÈÝÆ÷
Container con = fra.getContentPane();
con.add(lab);
Dimension dim = new Dimension();
dim.setSize(700, 400);
fra.setSize(dim);
fra.setBackground(Color.GREEN);//Where my Background Color?
Point poi = new Point();
poi.setLocation(300, 90);
fra.setLocation(poi);
fra.setVisible(true);
}
}
| apache-2.0 |
deeplearning4j/deeplearning4j | nd4j/nd4j-remote/nd4j-grpc-client/src/test/java/org/nd4j/graph/GraphInferenceGrpcClientTest.java | 4034 | /*******************************************************************************
* 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.graph;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.commons.lang3.RandomUtils;
import org.junit.Ignore;
import org.junit.Test;
import org.nd4j.common.tests.BaseND4JTest;
import org.nd4j.autodiff.execution.conf.ExecutorConfiguration;
import org.nd4j.autodiff.execution.conf.OutputMode;
import org.nd4j.autodiff.execution.input.Operands;
import org.nd4j.imports.graphmapper.tf.TFGraphMapper;
import org.nd4j.linalg.factory.Nd4j;
import org.nd4j.common.io.ClassPathResource;
import org.nd4j.remote.grpc.GraphInferenceGrpcClient;
import static org.junit.Assert.*;
@Slf4j
@Ignore
public class GraphInferenceGrpcClientTest extends BaseND4JTest {
@Test
public void testSimpleGraph_1() throws Exception {
val exp = Nd4j.create(new double[] {-0.95938617, -1.20301781, 1.22260064, 0.50172403, 0.59972949, 0.78568028, 0.31609724, 1.51674747, 0.68013491, -0.05227458, 0.25903158,1.13243439}, new long[]{3, 1, 4});
// configuring client
val client = new GraphInferenceGrpcClient("127.0.0.1", 40123);
val graphId = RandomUtils.nextLong(0, Long.MAX_VALUE);
// preparing and registering graph (it's optional, and graph might be embedded into Docker image
val tg = TFGraphMapper.importGraph(new ClassPathResource("tf_graphs/examples/expand_dim/frozen_model.pb").getInputStream());
assertNotNull(tg);
client.registerGraph(graphId, tg, ExecutorConfiguration.builder().outputMode(OutputMode.IMPLICIT).build());
//defining input
val input0 = Nd4j.create(new double[] {0.09753360, 0.76124972, 0.24693797, 0.13813169, 0.33144656, 0.08299957, 0.67197708, 0.80659380, 0.98274191, 0.63566073, 0.21592326, 0.54902743}, new int[] {3, 4});
val operands = new Operands().addArgument("input_0", input0);
// sending request and getting result
val result = client.output(graphId, operands);
assertEquals(exp, result.getById("output"));
}
@Test
public void testSimpleGraph_2() throws Exception {
val exp = Nd4j.create(new double[] {-0.95938617, -1.20301781, 1.22260064, 0.50172403, 0.59972949, 0.78568028, 0.31609724, 1.51674747, 0.68013491, -0.05227458, 0.25903158,1.13243439}, new long[]{3, 1, 4});
// configuring client
val client = new GraphInferenceGrpcClient("127.0.0.1", 40123);
val graphId = RandomUtils.nextLong(0, Long.MAX_VALUE);
// preparing and registering graph (it's optional, and graph might be embedded into Docker image
val tg = TFGraphMapper.importGraph(new ClassPathResource("tf_graphs/examples/expand_dim/frozen_model.pb").getInputStream());
assertNotNull(tg);
client.registerGraph(graphId, tg, ExecutorConfiguration.builder().outputMode(OutputMode.IMPLICIT).build());
//defining input
val input0 = Nd4j.create(new double[] {0.09753360, 0.76124972, 0.24693797, 0.13813169, 0.33144656, 0.08299957, 0.67197708, 0.80659380, 0.98274191, 0.63566073, 0.21592326, 0.54902743}, new int[] {3, 4});
val operands = new Operands().addArgument(1, 0, input0);
// sending request and getting result
val result = client.output(graphId, operands);
assertEquals(exp, result.getById("output"));
}
} | apache-2.0 |
nvapp/nv-android-libs | src/com/nvapp/android/libs/view/TitleProvider.java | 205 | package com.nvapp.android.libs.view;
public interface TitleProvider {
/**
* Returns the title of the view at position
*
* @param position
* @return
*/
public String getTitle(int position);
}
| apache-2.0 |
sunshine763/GoogleAndroidSamples | actionbarcompat-basic/src/test/java/com/xing/sample/actionbarcompat_basic/ExampleUnitTest.java | 330 | package com.xing.sample.actionbarcompat_basic;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* To work on unit tests, switch the Test Artifact in the Build Variants view.
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | apache-2.0 |
ppartida/jdesign-patterns | src/com/fifino/patterns/strategy/ItFlys.java | 206 | package com.fifino.patterns.strategy;
/**
* Created by porfiriopartida on 2/13/16.
*/
public class ItFlys implements Flys {
@Override
public String fly() {
return "Flying high!";
}
}
| apache-2.0 |
hambroperks/j2objc | translator/src/main/java/com/google/devtools/j2objc/translate/CastResolver.java | 12986 | /*
* 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.devtools.j2objc.translate;
import com.google.common.collect.Lists;
import com.google.devtools.j2objc.ast.CastExpression;
import com.google.devtools.j2objc.ast.Expression;
import com.google.devtools.j2objc.ast.ExpressionStatement;
import com.google.devtools.j2objc.ast.FieldAccess;
import com.google.devtools.j2objc.ast.FunctionInvocation;
import com.google.devtools.j2objc.ast.MethodDeclaration;
import com.google.devtools.j2objc.ast.MethodInvocation;
import com.google.devtools.j2objc.ast.ParenthesizedExpression;
import com.google.devtools.j2objc.ast.QualifiedName;
import com.google.devtools.j2objc.ast.ReturnStatement;
import com.google.devtools.j2objc.ast.SimpleName;
import com.google.devtools.j2objc.ast.SuperMethodInvocation;
import com.google.devtools.j2objc.ast.TreeUtil;
import com.google.devtools.j2objc.ast.TreeVisitor;
import com.google.devtools.j2objc.ast.VariableDeclarationFragment;
import com.google.devtools.j2objc.types.IOSMethodBinding;
import com.google.devtools.j2objc.types.Types;
import com.google.devtools.j2objc.util.BindingUtil;
import com.google.devtools.j2objc.util.NameTable;
import org.eclipse.jdt.core.dom.IMethodBinding;
import org.eclipse.jdt.core.dom.ITypeBinding;
import org.eclipse.jdt.core.dom.IVariableBinding;
import org.eclipse.jdt.core.dom.Modifier;
import java.util.Arrays;
import java.util.List;
/**
* Adds cast checks to existing java cast expressions.
* Adds casts as needed for Objective-C compilation. Usually this occurs when a
* method has a declared return type that is more generic than the resolved type
* of the expression.
*/
public class CastResolver extends TreeVisitor {
@Override
public void endVisit(CastExpression node) {
ITypeBinding type = node.getType().getTypeBinding();
Expression expr = node.getExpression();
ITypeBinding exprType = expr.getTypeBinding();
if (Types.isFloatingPointType(exprType)) {
if (Types.isLongType(type)) {
FunctionInvocation invocation = new FunctionInvocation("J2ObjCFpToLong", type, type, null);
invocation.getArguments().add(TreeUtil.remove(expr));
node.replaceWith(invocation);
return;
} else if (type.isEqualTo(Types.resolveJavaType("char"))) {
FunctionInvocation invocation =
new FunctionInvocation("J2ObjCFpToUnichar", type, type, null);
invocation.getArguments().add(TreeUtil.remove(expr));
node.replaceWith(invocation);
return;
} else if (Types.isIntegralType(type)) {
ITypeBinding intType = Types.resolveJavaType("int");
FunctionInvocation invocation =
new FunctionInvocation("J2ObjCFpToInt", intType, intType, null);
invocation.getArguments().add(TreeUtil.remove(expr));
Expression newExpr = invocation;
if (!type.isEqualTo(intType)) {
newExpr = new CastExpression(type, newExpr);
}
node.replaceWith(newExpr);
return;
}
// else fall-through.
}
// Lean on Java's type-checking.
if (!type.isPrimitive() && exprType.isAssignmentCompatible(type)) {
node.replaceWith(TreeUtil.remove(expr));
return;
}
FunctionInvocation castCheck = createCastCheck(type, expr);
if (castCheck != null) {
node.setExpression(castCheck);
}
}
private static FunctionInvocation createCastCheck(ITypeBinding type, Expression expr) {
// Find the first bound for a type variable.
while (type.isTypeVariable()) {
ITypeBinding[] bounds = type.getTypeBounds();
if (bounds.length == 0) {
break;
}
type = bounds[0];
}
ITypeBinding idType = Types.resolveIOSType("id");
FunctionInvocation invocation = null;
if (type.isInterface() && !type.isAnnotation()) {
invocation = new FunctionInvocation("check_protocol_cast", idType, idType, null);
invocation.getArguments().add(TreeUtil.remove(expr));
FunctionInvocation protocolLiteral =
new FunctionInvocation("@protocol", idType, idType, null);
protocolLiteral.getArguments().add(new SimpleName(type));
invocation.getArguments().add(protocolLiteral);
} else if (type.isClass() || type.isArray() || type.isAnnotation() || type.isEnum()) {
invocation = new FunctionInvocation("check_class_cast", idType, idType, null);
invocation.getArguments().add(TreeUtil.remove(expr));
IOSMethodBinding binding = IOSMethodBinding.newMethod("class", Modifier.STATIC, idType, type);
MethodInvocation classInvocation = new MethodInvocation(binding, new SimpleName(type));
invocation.getArguments().add(classInvocation);
}
return invocation;
}
private void addCast(Expression expr) {
ITypeBinding exprType = Types.mapType(expr.getTypeBinding().getTypeDeclaration());
CastExpression castExpr = new CastExpression(exprType, null);
expr.replaceWith(ParenthesizedExpression.parenthesize(castExpr));
castExpr.setExpression(expr);
}
private void maybeAddCast(Expression expr, boolean shouldCastFromId) {
if (needsCast(expr, shouldCastFromId)) {
addCast(expr);
}
}
private boolean needsCast(Expression expr, boolean shouldCastFromId) {
ITypeBinding declaredType = getDeclaredType(expr);
if (declaredType == null) {
return false;
}
ITypeBinding exprType = Types.mapType(expr.getTypeBinding().getTypeDeclaration());
declaredType = Types.mapType(declaredType.getTypeDeclaration());
if (declaredType.isAssignmentCompatible(exprType)) {
return false;
}
if (declaredType == Types.resolveIOSType("id") && !shouldCastFromId) {
return false;
}
if (exprType.isPrimitive() || Types.isVoidType(exprType)) {
return false;
}
String typeName = NameTable.getSpecificObjCType(exprType);
if (typeName.equals(NameTable.ID_TYPE)) {
return false;
}
return true;
}
private ITypeBinding getDeclaredType(Expression expr) {
IVariableBinding var = TreeUtil.getVariableBinding(expr);
if (var != null) {
return var.getVariableDeclaration().getType();
}
switch (expr.getKind()) {
case CLASS_INSTANCE_CREATION:
return Types.resolveIOSType("id");
case FUNCTION_INVOCATION:
return ((FunctionInvocation) expr).getDeclaredReturnType();
case METHOD_INVOCATION:
{
MethodInvocation invocation = (MethodInvocation) expr;
IMethodBinding method = invocation.getMethodBinding();
// Object receiving the message, or null if it's a method in this class.
Expression receiver = invocation.getExpression();
ITypeBinding receiverType = receiver != null ? receiver.getTypeBinding()
: method.getDeclaringClass();
return getDeclaredReturnType(method, receiverType);
}
case SUPER_METHOD_INVOCATION:
{
SuperMethodInvocation invocation = (SuperMethodInvocation) expr;
IMethodBinding method = invocation.getMethodBinding();
if (invocation.getQualifier() != null) {
// For a qualified super invocation, the statement generator will look
// up the IMP using instanceMethodForSelector.
if (!method.getReturnType().isPrimitive()) {
return Types.resolveIOSType("id");
} else {
return null;
}
}
return getDeclaredReturnType(
method, TreeUtil.getOwningType(invocation).getTypeBinding().getSuperclass());
}
default:
return null;
}
}
private static ITypeBinding getDeclaredReturnType(
IMethodBinding method, ITypeBinding receiverType) {
IMethodBinding actualDeclaration =
getFirstDeclaration(getObjCMethodSignature(method), receiverType);
if (actualDeclaration == null) {
actualDeclaration = method.getMethodDeclaration();
}
ITypeBinding returnType = actualDeclaration.getReturnType();
if (returnType.isTypeVariable()) {
return Types.resolveIOSType("id");
}
return returnType.getErasure();
}
/**
* Finds the declaration for a given method and receiver in the same way that
* the ObjC compiler will search for a declaration.
*/
private static IMethodBinding getFirstDeclaration(String methodSig, ITypeBinding type) {
if (type == null) {
return null;
}
type = type.getTypeDeclaration();
for (IMethodBinding declaredMethod : type.getDeclaredMethods()) {
if (methodSig.equals(getObjCMethodSignature(declaredMethod))) {
return declaredMethod;
}
}
List<ITypeBinding> supertypes = Lists.newArrayList();
supertypes.addAll(Arrays.asList(type.getInterfaces()));
supertypes.add(type.isTypeVariable() ? 0 : supertypes.size(), type.getSuperclass());
for (ITypeBinding supertype : supertypes) {
IMethodBinding result = getFirstDeclaration(methodSig, supertype);
if (result != null) {
return result;
}
}
return null;
}
private static String getObjCMethodSignature(IMethodBinding method) {
StringBuilder sb = new StringBuilder(method.getName());
boolean first = true;
for (ITypeBinding paramType : method.getParameterTypes()) {
String keyword = NameTable.parameterKeyword(paramType);
if (first) {
first = false;
keyword = NameTable.capitalize(keyword);
}
sb.append(keyword + ":");
}
return sb.toString();
}
// Some native objective-c methods are declared to return NSUInteger.
private boolean returnValueNeedsIntCast(Expression arg) {
IMethodBinding methodBinding = TreeUtil.getMethodBinding(arg);
assert methodBinding != null;
if (arg.getParent() instanceof ExpressionStatement) {
// Avoid "unused return value" warning.
return false;
}
String methodName = NameTable.getMethodSelector(methodBinding);
if (methodName.equals("hash")
&& methodBinding.getReturnType().isEqualTo(Types.resolveJavaType("int"))) {
return true;
}
if (Types.isStringType(methodBinding.getDeclaringClass()) && methodName.equals("length")) {
return true;
}
return false;
}
@Override
public void endVisit(FieldAccess node) {
maybeAddCast(node.getExpression(), true);
}
@Override
public void endVisit(MethodInvocation node) {
Expression receiver = node.getExpression();
if (receiver != null && !BindingUtil.isStatic(node.getMethodBinding())) {
maybeAddCast(receiver, true);
}
if (returnValueNeedsIntCast(node)) {
addCast(node);
}
}
@Override
public void endVisit(QualifiedName node) {
if (needsCast(node.getQualifier(), true)) {
maybeAddCast(TreeUtil.convertToFieldAccess(node).getExpression(), true);
}
}
@Override
public void endVisit(ReturnStatement node) {
Expression expr = node.getExpression();
if (expr != null) {
maybeAddCast(expr, false);
}
}
@Override
public void endVisit(SuperMethodInvocation node) {
if (returnValueNeedsIntCast(node)) {
addCast(node);
}
}
@Override
public void endVisit(VariableDeclarationFragment node) {
Expression initializer = node.getInitializer();
if (initializer != null) {
maybeAddCast(initializer, false);
}
}
/**
* Adds a cast check to compareTo methods. This helps Comparable types behave
* well in sorted collections which rely on Java's runtime type checking.
*/
@Override
public void endVisit(MethodDeclaration node) {
IMethodBinding binding = node.getMethodBinding();
if (!binding.getName().equals("compareTo") || node.getBody() == null) {
return;
}
ITypeBinding comparableType =
BindingUtil.findInterface(binding.getDeclaringClass(), "java.lang.Comparable");
if (comparableType == null) {
return;
}
ITypeBinding[] typeArguments = comparableType.getTypeArguments();
ITypeBinding[] parameterTypes = binding.getParameterTypes();
if (typeArguments.length != 1 || parameterTypes.length != 1
|| !typeArguments[0].isEqualTo(parameterTypes[0])) {
return;
}
IVariableBinding param = node.getParameters().get(0).getVariableBinding();
FunctionInvocation castCheck = createCastCheck(typeArguments[0], new SimpleName(param));
if (castCheck != null) {
node.getBody().getStatements().add(0, new ExpressionStatement(castCheck));
}
}
}
| apache-2.0 |
fillipesouza/mygame | src/textures/TerrainTexturePack.java | 1125 | package textures;
public class TerrainTexturePack {
private TerrainTexture backgroundTexture;
private TerrainTexture rTexture;
private TerrainTexture gTexture;
private TerrainTexture bTexture;
public TerrainTexture getBackgroundTexture() {
return backgroundTexture;
}
public void setBackgroundTexture(TerrainTexture backgroundTexture) {
this.backgroundTexture = backgroundTexture;
}
public TerrainTexturePack(TerrainTexture backgroundTexture,
TerrainTexture rTexture, TerrainTexture gTexture,
TerrainTexture bTexture) {
super();
this.backgroundTexture = backgroundTexture;
this.rTexture = rTexture;
this.gTexture = gTexture;
this.bTexture = bTexture;
}
public TerrainTexture getrTexture() {
return rTexture;
}
public void setrTexture(TerrainTexture rTexture) {
this.rTexture = rTexture;
}
public TerrainTexture getgTexture() {
return gTexture;
}
public void setgTexture(TerrainTexture gTexture) {
this.gTexture = gTexture;
}
public TerrainTexture getbTexture() {
return bTexture;
}
public void setbTexture(TerrainTexture bTexture) {
this.bTexture = bTexture;
}
}
| apache-2.0 |
shooash/XHFW3 | app/src/main/java/com/zst/xposed/halo/floatingwindow3/prefs/FloatDotActivity.java | 5002 | package com.zst.xposed.halo.floatingwindow3.prefs;
import android.app.*;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.*;
import android.os.*;
import com.zst.xposed.halo.floatingwindow3.*;
import java.util.prefs.*;
import android.widget.*;
import android.graphics.*;
public class FloatDotActivity extends Activity implements OnSharedPreferenceChangeListener
{
SharedPreferences mPref;
//Context mContext;
int[] mColors = new int[4];
int mCircleDiameter;
ImageView snapDragger;
ImageView floatLauncher;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog_floatdot);
snapDragger = (ImageView) findViewById(R.id.snapDragger);
floatLauncher = (ImageView) findViewById(R.id.floatingLauncher);
mPref = getSharedPreferences(Common.PREFERENCE_MAIN_FILE, MODE_WORLD_READABLE);
updatePrefs();
// getFragmentManager().beginTransaction().replace(R.id.floatDotPrefs,
// new FloatDotFragment()).commit();
}
private void updatePrefs(){
loadColors();
mCircleDiameter=mPref.getInt(Common.KEY_FLOATDOT_SIZE, Common.DEFAULT_FLOATDOT_SIZE);
snapDragger.setImageDrawable(Util.makeDoubleCircle(mColors[0], mColors[1], Util.realDp(mCircleDiameter, getApplicationContext()), Util.realDp(mCircleDiameter/4, getApplicationContext())));
floatLauncher.setImageDrawable(Util.makeDoubleCircle(mColors[2], mColors[3], Util.realDp(mCircleDiameter, getApplicationContext()), Util.realDp(mCircleDiameter/4, getApplicationContext())));
}
private void loadColors(){
mColors[0] = Color.parseColor("#" + mPref.getString(Common.KEY_FLOATDOT_COLOR_OUTER1, Common.DEFAULT_FLOATDOT_COLOR_OUTER1));
if(mPref.getBoolean(Common.KEY_FLOATDOT_SINGLE_COLOR_SNAP, Common.DEFAULT_FLOATDOT_SINGLE_COLOR_SNAP))
mColors[1] = mColors[0];
else
mColors[1] = Color.parseColor("#" + mPref.getString(Common.KEY_FLOATDOT_COLOR_INNER1, Common.DEFAULT_FLOATDOT_COLOR_INNER1));
mColors[2] = Color.parseColor("#" + mPref.getString(Common.KEY_FLOATDOT_COLOR_OUTER2, Common.DEFAULT_FLOATDOT_COLOR_OUTER2));
if(mPref.getBoolean(Common.KEY_FLOATDOT_SINGLE_COLOR_LAUNCHER, Common.DEFAULT_FLOATDOT_SINGLE_COLOR_LAUNCHER))
mColors[3] = mColors[2];
else
mColors[3] = Color.parseColor("#" + mPref.getString(Common.KEY_FLOATDOT_COLOR_INNER2, Common.DEFAULT_FLOATDOT_COLOR_INNER2));
}
private void sendRefreshCommand(String key){
int item = 0;
int size = 0;
float alpha = 0;
String mColor = null;
if(key.equals(Common.KEY_FLOATDOT_COLOR_OUTER1))
item=0;
else if(key.equals(Common.KEY_FLOATDOT_COLOR_INNER1))
item=1;
else if(key.equals(Common.KEY_FLOATDOT_COLOR_OUTER2))
item=2;
else if(key.equals(Common.KEY_FLOATDOT_COLOR_INNER2))
item=3;
else if(key.equals(Common.KEY_FLOATDOT_SINGLE_COLOR_SNAP)){
item = 1;
if(mPref.getBoolean(key, Common.DEFAULT_FLOATDOT_SINGLE_COLOR_SNAP))
mColor = mPref.getString(Common.KEY_FLOATDOT_COLOR_OUTER1, Common.DEFAULT_FLOATDOT_COLOR_OUTER1);
else
mColor = mPref.getString(Common.KEY_FLOATDOT_COLOR_INNER1, Common.KEY_FLOATDOT_COLOR_INNER1);
}
else if(key.equals(Common.KEY_FLOATDOT_SINGLE_COLOR_LAUNCHER)){
item = 3;
if(mPref.getBoolean(key, Common.DEFAULT_FLOATDOT_SINGLE_COLOR_LAUNCHER))
mColor = mPref.getString(Common.KEY_FLOATDOT_COLOR_OUTER2, Common.DEFAULT_FLOATDOT_COLOR_OUTER2);
else
mColor = mPref.getString(Common.KEY_FLOATDOT_COLOR_INNER2, Common.KEY_FLOATDOT_COLOR_INNER2);
}
else if(key.equals(Common.KEY_FLOATDOT_SIZE)){
size = mPref.getInt(key, Common.DEFAULT_FLOATDOT_SIZE);
}
else if(key.equals(Common.KEY_FLOATDOT_ALPHA)){
alpha = mPref.getFloat(key, Common.DEFAULT_FLOATDOT_ALPHA);
}
else return;
if(mColor==null && size==0 && alpha == 0) mColor = mPref.getString(key, null);
Intent mIntent = new Intent(Common.UPDATE_FLOATDOT_PARAMS);
mIntent.putExtra("color", mColor);
mIntent.putExtra("size", size);
mIntent.putExtra("alpha", alpha);
mIntent.putExtra("item", item);
mIntent.setPackage(Common.THIS_MOD_PACKAGE_NAME);
getApplicationContext().sendBroadcast(mIntent);
}
private void enableFloatDotLauncher(boolean enable){
Intent mIntent = new Intent(Common.UPDATE_FLOATDOT_PARAMS);
mIntent.putExtra(Common.KEY_FLOATDOT_LAUNCHER_ENABLED, enable);
mIntent.setPackage(Common.THIS_MOD_PACKAGE_NAME);
getApplicationContext().sendBroadcast(mIntent);
}
@Override
public void onSharedPreferenceChanged(SharedPreferences p1, String key)
{
updatePrefs();
if(key.equals(Common.KEY_FLOATDOT_LAUNCHER_ENABLED)){
enableFloatDotLauncher(mPref.getBoolean(key, Common.DEFAULT_FLOATDOT_LAUNCHER_ENABLED));
return;
}
sendRefreshCommand(key);
}
@Override
protected void onResume() {
super.onResume();
mPref.registerOnSharedPreferenceChangeListener(this);
}
@Override
protected void onPause() {
super.onPause();
mPref.unregisterOnSharedPreferenceChangeListener(this);
}
}
| apache-2.0 |
007slm/nutz | test/org/nutz/resource/ScansTest.java | 5137 | package org.nutz.resource;
import static org.junit.Assert.*;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import javax.servlet.Servlet;
import junit.extensions.ActiveTestSuite;
import junit.extensions.RepeatedTest;
import junit.extensions.TestSetup;
import junit.framework.Assert;
import org.junit.Test;
import org.nutz.lang.Files;
import org.nutz.lang.Strings;
public class ScansTest {
@Test
public void test_loadResource() throws IOException {
String RNAME = "junit/runner/Version.class";
List<NutResource> nrs = Scans.me().loadResource(".*.class", RNAME);
assertEquals(1, nrs.size());
NutResource nr = nrs.get(0);
assertTrue(nr.getName().indexOf(RNAME) >= 0);
InputStream ins = nr.getInputStream();
int len = 0;
while (-1 != ins.read()) {
len++;
}
ins.close();
assertTrue(len > 600);
}
@Test
public void test_in_normal_file() throws IOException {
String testPath = "~/nutz/unit/rs/test";
File testDir = Files.createDirIfNoExists(testPath);
Files.clearDir(testDir);
List<NutResource> list = Scans.me().scan(testPath, ".*");
assertEquals(0, list.size());
Files.createDirIfNoExists(testPath + "/a/b/c");
list = Scans.me().scan(testPath, ".*");
assertEquals(0, list.size());
Files.createFileIfNoExists(testPath + "/a/b/c/l.txt");
Files.createFileIfNoExists(testPath + "/a/b/c/m.doc");
Files.createFileIfNoExists(testPath + "/a/b/c/n.jpg");
Files.createFileIfNoExists(testPath + "/a/b/c/o.jpg");
list = Scans.me().scan(testPath, ".*");
assertEquals(4, list.size());
list = Scans.me().scan(testPath, null);
assertEquals(4, list.size());
list = Scans.me().scan(testPath, ".+[.]jpg");
assertEquals(2, list.size());
list = Scans.me().scan(testPath, ".*[.]txt");
assertEquals(1, list.size());
Files.deleteDir(testDir);
}
@Test
public void test_in_classpath() {
String testPath = Scans.class.getName().replace('.', '/') + ".class";
String testFilter = "^" + Scans.class.getSimpleName() + ".class$";
List<NutResource> list = Scans.me().scan(testPath, testFilter);
assertEquals(1, list.size());
}
// @Ignore
@Test
public void test_in_jar() {
String testPath = Assert.class.getPackage().getName().replace('.', '/');
String testFilter = "^.*(Assert|Test)\\.class$";
List<NutResource> list = Scans.me().scan(testPath, testFilter);
//Collections.sort(list);
assertEquals(2, list.size());
assertTrue(list.get(0).getName().endsWith("Test.class"));
assertTrue(list.get(1).getName().endsWith("Assert.class"));
}
// @Ignore
@Test
public void test_classes_in_jar() {
List<Class<?>> list = Scans.me()
.scanPackage( ActiveTestSuite.class,
".*(ActiveTestSuite|RepeatedTest|TestSetup)\\.class$");
assertEquals(3, list.size());
Collections.sort(list, new Comparator<Class<?>>() {
public int compare(Class<?> o1, Class<?> o2) {
return o1.getSimpleName().compareTo(o2.getSimpleName());
}
});
assertTrue(ActiveTestSuite.class == list.get(0));
assertTrue(RepeatedTest.class == list.get(1));
assertTrue(TestSetup.class == list.get(2));
}
@Test
public void test_classes_in_package_path() {
List<Class<?>> list = Scans.me().scanPackage("org.nutz", "Strings.class");
assertEquals(1, list.size());
assertTrue(Strings.class == list.get(0));
}
@Test
public void test_scan_with_unexists_file() {
List<NutResource> list = Scans.me().scan("org/nutz/lang/notExist.class", null);
assertEquals(0, list.size());
}
@Test
public void test_class_in_jar() {
String testPath = Test.class.getName().replace('.', '/') + ".class";
String testFilter = "^Test.class$";
List<NutResource> list = Scans.me().scan(testPath, testFilter);
assertEquals(1, list.size());
}
@Test
public void test_path_in_jar() {
String testPath = Test.class.getPackage().getName().replace('.', '/');
List<NutResource> list = Scans.me().scan(testPath, null);
assertTrue(list.size() > 10);
}
@Test
public void test_scan_root() {
Scans.me().scan("", ".+\\.xml");
}
@Test
public void test_resource_jar() throws MalformedURLException {
Scans.me().registerLocation(Servlet.class);
Scans.me().registerLocation(getClass().getClassLoader().getResource("javax/servlet/Servlet.class"));
}
}
| apache-2.0 |
eemirtekin/Sakai-10.6-TR | providers/jldap-mock/src/java/edu/amc/sakai/user/ResourcePropertiesEditStub.java | 4899 | /**********************************************************************************
* $URL: https://source.sakaiproject.org/svn/providers/tags/sakai-10.6/jldap-mock/src/java/edu/amc/sakai/user/ResourcePropertiesEditStub.java $
* $Id: ResourcePropertiesEditStub.java 105079 2012-02-24 23:08:11Z ottenhoff@longsight.com $
***********************************************************************************
*
* Copyright (c) 2003, 2004, 2005, 2006, 2008 The Sakai 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/ECL-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 edu.amc.sakai.user;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Properties;
import org.sakaiproject.entity.api.ResourcePropertiesEdit;
import org.sakaiproject.util.BaseResourcePropertiesEdit;
import org.apache.commons.lang.StringUtils;
/**
* Not a stub per-se, so much as a {@link BaseResourcePropertiesEdit} extension
* with enhancements for testing equality, outputting a meaningful String
* representation, and initializing state from a set of default and
* override {@link Properties}.
*
*
* @author dmccallum@unicon.net
*
*/
public class ResourcePropertiesEditStub extends BaseResourcePropertiesEdit {
private static final long serialVersionUID = 1L;
public ResourcePropertiesEditStub() {
super();
}
public ResourcePropertiesEditStub(Properties defaultConfig, Properties configOverrides) {
super();
if ( defaultConfig != null && !(defaultConfig.isEmpty()) ) {
for ( Enumeration i = defaultConfig.propertyNames() ; i.hasMoreElements() ; ) {
String propertyName = (String)i.nextElement();
String propertyValue = StringUtils.trimToNull((String)defaultConfig.getProperty(propertyName));
if ( propertyValue == null ) {
continue;
}
String[] propertyValues = propertyValue.split(";");
if ( propertyValues.length > 1 ) {
for ( String splitPropertyValue : propertyValues ) {
super.addPropertyToList(propertyName, splitPropertyValue);
}
} else {
super.addProperty(propertyName, propertyValue);
}
}
}
if ( configOverrides != null && !(configOverrides.isEmpty()) ) {
// slightly different... configOverrides are treated as complete
// overwrites of existing values.
for ( Enumeration i = configOverrides.propertyNames() ; i.hasMoreElements() ; ) {
String propertyName = (String)i.nextElement();
super.removeProperty(propertyName);
String propertyValue = StringUtils.trimToNull((String)configOverrides.getProperty(propertyName));
String[] propertyValues = propertyValue.split(";");
if ( propertyValues.length > 1 ) {
for ( String splitPropertyValue : propertyValues ) {
super.addPropertyToList(propertyName, splitPropertyValue);
}
} else {
super.addProperty(propertyName, propertyValue);
}
}
}
}
public String toString() {
StringBuilder sb = new StringBuilder();
for ( Iterator names = getPropertyNames(); names.hasNext(); ) {
String name = (String)names.next();
sb.append(name + "=" + this.getPropertyFormatted(name) + "; ");
}
return sb.toString();
}
/** Pure hack, but BaseResourceProperties doesn't have a meaningful impl */
public boolean equals(Object o) {
if ( o == this ) {
return true;
}
if ( o == null ) {
return false;
}
if ( !(o instanceof ResourcePropertiesEdit) ) {
return false;
}
ResourcePropertiesEdit otherProps = (ResourcePropertiesEdit)o;
int cnt = 0;
Iterator namesInOther = otherProps.getPropertyNames();
while ( namesInOther.hasNext() ) {
cnt++;
String nameInOther = (String)namesInOther.next();
Object valueInOther = otherProps.get(nameInOther);
Object valueInThis = get(nameInOther);
if ( valueInThis == valueInOther ) {
continue;
}
if ( valueInThis == null || valueInOther == null ) {
return false;
}
if ( !(valueInThis.equals(valueInOther)) ) {
return false;
}
}
if ( m_props.size() != cnt ) {
return false;
}
return true;
}
}
| apache-2.0 |
liuyuanyuan/dbeaver | plugins/org.jkiss.dbeaver.ext.postgresql/src/org/jkiss/dbeaver/ext/postgresql/PostgreServerHome.java | 1764 | /*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2019 Serge Rider (serge@jkiss.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.jkiss.dbeaver.ext.postgresql;
import org.jkiss.dbeaver.Log;
import org.jkiss.dbeaver.model.connection.LocalNativeClientLocation;
/**
* PostgreServerHome
*/
public class PostgreServerHome extends LocalNativeClientLocation {
private static final Log log = Log.getLog(PostgreServerHome.class);
private String name;
private String version;
private String branding;
private String dataDirectory;
protected PostgreServerHome(String id, String path, String version, String branding, String dataDirectory) {
super(id, path);
this.name = branding == null ? id : branding;
this.version = version;
this.branding = branding;
this.dataDirectory = dataDirectory;
}
@Override
public String getDisplayName() {
return name;
}
public String getProductName() {
return branding;
}
public String getProductVersion() {
return version;
}
public String getBranding() {
return branding;
}
public String getDataDirectory() {
return dataDirectory;
}
}
| apache-2.0 |
InspurUSA/nifi | nifi-nar-bundles/nifi-framework-bundle/nifi-framework/nifi-web/nifi-web-api/src/main/java/org/apache/nifi/web/controller/ControllerFacade.java | 86923 | /*
* 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.nifi.web.controller;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ClassUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.nifi.authorization.AccessDeniedException;
import org.apache.nifi.authorization.AuthorizationResult;
import org.apache.nifi.authorization.AuthorizationResult.Result;
import org.apache.nifi.authorization.Authorizer;
import org.apache.nifi.authorization.RequestAction;
import org.apache.nifi.authorization.Resource;
import org.apache.nifi.authorization.resource.Authorizable;
import org.apache.nifi.authorization.resource.ResourceFactory;
import org.apache.nifi.authorization.user.NiFiUser;
import org.apache.nifi.authorization.user.NiFiUserUtils;
import org.apache.nifi.bundle.Bundle;
import org.apache.nifi.bundle.BundleCoordinate;
import org.apache.nifi.cluster.protocol.NodeIdentifier;
import org.apache.nifi.components.ConfigurableComponent;
import org.apache.nifi.components.PropertyDescriptor;
import org.apache.nifi.connectable.Connectable;
import org.apache.nifi.connectable.Connection;
import org.apache.nifi.connectable.Funnel;
import org.apache.nifi.connectable.Port;
import org.apache.nifi.controller.ContentAvailability;
import org.apache.nifi.controller.ControllerService;
import org.apache.nifi.controller.Counter;
import org.apache.nifi.controller.FlowController;
import org.apache.nifi.controller.ProcessorNode;
import org.apache.nifi.controller.ReportingTaskNode;
import org.apache.nifi.controller.ScheduledState;
import org.apache.nifi.controller.Template;
import org.apache.nifi.controller.label.Label;
import org.apache.nifi.controller.queue.FlowFileQueue;
import org.apache.nifi.controller.queue.QueueSize;
import org.apache.nifi.controller.repository.ContentNotFoundException;
import org.apache.nifi.controller.repository.claim.ContentDirection;
import org.apache.nifi.controller.service.ControllerServiceNode;
import org.apache.nifi.controller.service.ControllerServiceProvider;
import org.apache.nifi.controller.status.ConnectionStatus;
import org.apache.nifi.controller.status.PortStatus;
import org.apache.nifi.controller.status.ProcessGroupStatus;
import org.apache.nifi.controller.status.ProcessorStatus;
import org.apache.nifi.controller.status.RemoteProcessGroupStatus;
import org.apache.nifi.controller.status.history.ComponentStatusRepository;
import org.apache.nifi.diagnostics.SystemDiagnostics;
import org.apache.nifi.flowfile.FlowFilePrioritizer;
import org.apache.nifi.flowfile.attributes.CoreAttributes;
import org.apache.nifi.groups.ProcessGroup;
import org.apache.nifi.groups.ProcessGroupCounts;
import org.apache.nifi.groups.RemoteProcessGroup;
import org.apache.nifi.nar.ExtensionManager;
import org.apache.nifi.nar.NarCloseable;
import org.apache.nifi.processor.DataUnit;
import org.apache.nifi.processor.Processor;
import org.apache.nifi.processor.Relationship;
import org.apache.nifi.provenance.ProvenanceEventRecord;
import org.apache.nifi.provenance.ProvenanceRepository;
import org.apache.nifi.provenance.SearchableFields;
import org.apache.nifi.provenance.lineage.ComputeLineageSubmission;
import org.apache.nifi.provenance.search.Query;
import org.apache.nifi.provenance.search.QueryResult;
import org.apache.nifi.provenance.search.QuerySubmission;
import org.apache.nifi.provenance.search.SearchTerm;
import org.apache.nifi.provenance.search.SearchTerms;
import org.apache.nifi.provenance.search.SearchableField;
import org.apache.nifi.registry.ComponentVariableRegistry;
import org.apache.nifi.registry.VariableDescriptor;
import org.apache.nifi.registry.VariableRegistry;
import org.apache.nifi.registry.flow.VersionedProcessGroup;
import org.apache.nifi.remote.RemoteGroupPort;
import org.apache.nifi.remote.RootGroupPort;
import org.apache.nifi.reporting.ReportingTask;
import org.apache.nifi.scheduling.ExecutionNode;
import org.apache.nifi.scheduling.SchedulingStrategy;
import org.apache.nifi.search.SearchContext;
import org.apache.nifi.search.SearchResult;
import org.apache.nifi.search.Searchable;
import org.apache.nifi.services.FlowService;
import org.apache.nifi.util.BundleUtils;
import org.apache.nifi.util.FormatUtils;
import org.apache.nifi.util.NiFiProperties;
import org.apache.nifi.web.DownloadableContent;
import org.apache.nifi.web.NiFiCoreException;
import org.apache.nifi.web.ResourceNotFoundException;
import org.apache.nifi.web.api.dto.BundleDTO;
import org.apache.nifi.web.api.dto.DocumentedTypeDTO;
import org.apache.nifi.web.api.dto.DtoFactory;
import org.apache.nifi.web.api.dto.provenance.AttributeDTO;
import org.apache.nifi.web.api.dto.provenance.ProvenanceDTO;
import org.apache.nifi.web.api.dto.provenance.ProvenanceEventDTO;
import org.apache.nifi.web.api.dto.provenance.ProvenanceOptionsDTO;
import org.apache.nifi.web.api.dto.provenance.ProvenanceRequestDTO;
import org.apache.nifi.web.api.dto.provenance.ProvenanceResultsDTO;
import org.apache.nifi.web.api.dto.provenance.ProvenanceSearchableFieldDTO;
import org.apache.nifi.web.api.dto.provenance.lineage.LineageDTO;
import org.apache.nifi.web.api.dto.provenance.lineage.LineageRequestDTO;
import org.apache.nifi.web.api.dto.provenance.lineage.LineageRequestDTO.LineageRequestType;
import org.apache.nifi.web.api.dto.search.ComponentSearchResultDTO;
import org.apache.nifi.web.api.dto.search.SearchResultsDTO;
import org.apache.nifi.web.api.dto.status.ControllerStatusDTO;
import org.apache.nifi.web.api.dto.status.StatusHistoryDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.ws.rs.WebApplicationException;
import java.io.IOException;
import java.io.InputStream;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TimeZone;
import java.util.TreeSet;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import static org.apache.nifi.controller.FlowController.ROOT_GROUP_ID_ALIAS;
public class ControllerFacade implements Authorizable {
private static final Logger logger = LoggerFactory.getLogger(ControllerFacade.class);
// nifi components
private FlowController flowController;
private FlowService flowService;
private Authorizer authorizer;
// properties
private NiFiProperties properties;
private DtoFactory dtoFactory;
private VariableRegistry variableRegistry;
/**
* Returns the group id that contains the specified processor.
*
* @param processorId processor id
* @return group id
*/
public String findProcessGroupIdForProcessor(String processorId) {
final ProcessGroup rootGroup = flowController.getGroup(flowController.getRootGroupId());
final ProcessorNode processor = rootGroup.findProcessor(processorId);
if (processor == null) {
return null;
} else {
return processor.getProcessGroup().getIdentifier();
}
}
public ControllerServiceProvider getControllerServiceProvider() {
return flowController;
}
/**
* Sets the name of this controller.
*
* @param name name
*/
public void setName(String name) {
flowController.setName(name);
}
@Override
public Authorizable getParentAuthorizable() {
return flowController.getParentAuthorizable();
}
@Override
public Resource getResource() {
return flowController.getResource();
}
/**
* Sets the comments of this controller.
*
* @param comments comments
*/
public void setComments(String comments) {
flowController.setComments(comments);
}
/**
* Gets the cached temporary instance of the component for the given type and bundle.
*
* @param type type of the component
* @param bundle the bundle of the component
* @return the temporary component
* @throws IllegalStateException if no temporary component exists for the given type and bundle
*/
public ConfigurableComponent getTemporaryComponent(final String type, final BundleDTO bundle) {
final ConfigurableComponent configurableComponent = ExtensionManager.getTempComponent(type, BundleUtils.getBundle(type, bundle));
if (configurableComponent == null) {
throw new IllegalStateException("Unable to obtain temporary component for " + type);
}
return configurableComponent;
}
/**
* Sets the max timer driven thread count of this controller.
*
* @param maxTimerDrivenThreadCount count
*/
public void setMaxTimerDrivenThreadCount(int maxTimerDrivenThreadCount) {
flowController.setMaxTimerDrivenThreadCount(maxTimerDrivenThreadCount);
}
/**
* Sets the max event driven thread count of this controller.
*
* @param maxEventDrivenThreadCount count
*/
public void setMaxEventDrivenThreadCount(int maxEventDrivenThreadCount) {
flowController.setMaxEventDrivenThreadCount(maxEventDrivenThreadCount);
}
/**
* Gets the root group id.
*
* @return group id
*/
public String getRootGroupId() {
return flowController.getRootGroupId();
}
/**
* Gets the input ports on the root group.
*
* @return input ports
*/
public Set<RootGroupPort> getInputPorts() {
final Set<RootGroupPort> inputPorts = new HashSet<>();
ProcessGroup rootGroup = flowController.getGroup(flowController.getRootGroupId());
for (final Port port : rootGroup.getInputPorts()) {
if (port instanceof RootGroupPort) {
inputPorts.add((RootGroupPort) port);
}
}
return inputPorts;
}
/**
* Gets the output ports on the root group.
*
* @return output ports
*/
public Set<RootGroupPort> getOutputPorts() {
final Set<RootGroupPort> outputPorts = new HashSet<>();
ProcessGroup rootGroup = flowController.getGroup(flowController.getRootGroupId());
for (final Port port : rootGroup.getOutputPorts()) {
if (port instanceof RootGroupPort) {
outputPorts.add((RootGroupPort) port);
}
}
return outputPorts;
}
/**
* Returns the status history for the specified processor.
*
* @param processorId processor id
* @return status history
*/
public StatusHistoryDTO getProcessorStatusHistory(final String processorId) {
final ProcessGroup root = flowController.getGroup(flowController.getRootGroupId());
final ProcessorNode processor = root.findProcessor(processorId);
// ensure the processor was found
if (processor == null) {
throw new ResourceNotFoundException(String.format("Unable to locate processor with id '%s'.", processorId));
}
final boolean authorized = processor.isAuthorized(authorizer, RequestAction.READ, NiFiUserUtils.getNiFiUser());
final StatusHistoryDTO statusHistory = flowController.getProcessorStatusHistory(processorId, authorized);
// if not authorized
if (!authorized) {
statusHistory.getComponentDetails().put(ComponentStatusRepository.COMPONENT_DETAIL_NAME, processorId);
statusHistory.getComponentDetails().put(ComponentStatusRepository.COMPONENT_DETAIL_TYPE, "Processor");
}
return statusHistory;
}
/**
* Returns the status history for the specified connection.
*
* @param connectionId connection id
* @return status history
*/
public StatusHistoryDTO getConnectionStatusHistory(final String connectionId) {
final ProcessGroup root = flowController.getGroup(flowController.getRootGroupId());
final Connection connection = root.findConnection(connectionId);
// ensure the connection was found
if (connection == null) {
throw new ResourceNotFoundException(String.format("Unable to locate connection with id '%s'.", connectionId));
}
final StatusHistoryDTO statusHistory = flowController.getConnectionStatusHistory(connectionId);
// if not authorized
if (!connection.isAuthorized(authorizer, RequestAction.READ, NiFiUserUtils.getNiFiUser())) {
statusHistory.getComponentDetails().put(ComponentStatusRepository.COMPONENT_DETAIL_NAME, connectionId);
statusHistory.getComponentDetails().put(ComponentStatusRepository.COMPONENT_DETAIL_SOURCE_NAME, connection.getSource().getIdentifier());
statusHistory.getComponentDetails().put(ComponentStatusRepository.COMPONENT_DETAIL_DESTINATION_NAME, connection.getDestination().getIdentifier());
}
return statusHistory;
}
/**
* Returns the status history for the specified process group.
*
* @param groupId group id
* @return status history
*/
public StatusHistoryDTO getProcessGroupStatusHistory(final String groupId) {
final String searchId = groupId.equals(ROOT_GROUP_ID_ALIAS) ? flowController.getRootGroupId() : groupId;
final ProcessGroup root = flowController.getGroup(flowController.getRootGroupId());
final ProcessGroup group = root.findProcessGroup(searchId);
// ensure the processor was found
if (group == null) {
throw new ResourceNotFoundException(String.format("Unable to locate process group with id '%s'.", groupId));
}
final StatusHistoryDTO statusHistory = flowController.getProcessGroupStatusHistory(groupId);
// if not authorized
if (!group.isAuthorized(authorizer, RequestAction.READ, NiFiUserUtils.getNiFiUser())) {
statusHistory.getComponentDetails().put(ComponentStatusRepository.COMPONENT_DETAIL_NAME, groupId);
}
return statusHistory;
}
/**
* Returns the status history for the specified remote process group.
*
* @param remoteProcessGroupId remote process group id
* @return status history
*/
public StatusHistoryDTO getRemoteProcessGroupStatusHistory(final String remoteProcessGroupId) {
final ProcessGroup root = flowController.getGroup(flowController.getRootGroupId());
final RemoteProcessGroup remoteProcessGroup = root.findRemoteProcessGroup(remoteProcessGroupId);
// ensure the output port was found
if (remoteProcessGroup == null) {
throw new ResourceNotFoundException(String.format("Unable to locate remote process group with id '%s'.", remoteProcessGroupId));
}
final StatusHistoryDTO statusHistory = flowController.getRemoteProcessGroupStatusHistory(remoteProcessGroupId);
// if not authorized
if (!remoteProcessGroup.isAuthorized(authorizer, RequestAction.READ, NiFiUserUtils.getNiFiUser())) {
statusHistory.getComponentDetails().put(ComponentStatusRepository.COMPONENT_DETAIL_NAME, remoteProcessGroupId);
statusHistory.getComponentDetails().remove(ComponentStatusRepository.COMPONENT_DETAIL_URI);
}
return statusHistory;
}
/**
* Get the node id of this controller.
*
* @return node identifier
*/
public NodeIdentifier getNodeId() {
return flowController.getNodeId();
}
/**
* @return true if is clustered
*/
public boolean isClustered() {
return flowController.isClustered();
}
/**
* Gets the name of this controller.
*
* @return name
*/
public String getName() {
return flowController.getName();
}
public String getInstanceId() {
return flowController.getInstanceId();
}
/**
* Gets the comments of this controller.
*
* @return comments
*/
public String getComments() {
return flowController.getComments();
}
/**
* Gets the max timer driven thread count of this controller.
*
* @return count
*/
public int getMaxTimerDrivenThreadCount() {
return flowController.getMaxTimerDrivenThreadCount();
}
/**
* Gets the max event driven thread count of this controller.
*
* @return count
*/
public int getMaxEventDrivenThreadCount() {
return flowController.getMaxEventDrivenThreadCount();
}
/**
* Gets the FlowFileProcessor types that this controller supports.
*
* @param bundleGroupFilter if specified, must be member of bundle group
* @param bundleArtifactFilter if specified, must be member of bundle artifact
* @param typeFilter if specified, type must match
* @return types
*/
public Set<DocumentedTypeDTO> getFlowFileProcessorTypes(final String bundleGroupFilter, final String bundleArtifactFilter, final String typeFilter) {
return dtoFactory.fromDocumentedTypes(ExtensionManager.getExtensions(Processor.class), bundleGroupFilter, bundleArtifactFilter, typeFilter);
}
/**
* Gets the FlowFileComparator types that this controller supports.
*
* @return the FlowFileComparator types that this controller supports
*/
public Set<DocumentedTypeDTO> getFlowFileComparatorTypes() {
return dtoFactory.fromDocumentedTypes(ExtensionManager.getExtensions(FlowFilePrioritizer.class), null, null, null);
}
/**
* Returns whether the specified type implements the specified serviceType.
*
* @param serviceType type
* @param type type
* @return whether the specified type implements the specified serviceType
*/
private boolean implementsServiceType(final Class serviceType, final Class type) {
final List<Class<?>> interfaces = ClassUtils.getAllInterfaces(type);
for (final Class i : interfaces) {
if (ControllerService.class.isAssignableFrom(i) && serviceType.isAssignableFrom(i)) {
return true;
}
}
return false;
}
/**
* Gets the ControllerService types that this controller supports.
*
* @param serviceType type
* @param serviceBundleGroup if serviceType specified, the bundle group of the serviceType
* @param serviceBundleArtifact if serviceType specified, the bundle artifact of the serviceType
* @param serviceBundleVersion if serviceType specified, the bundle version of the serviceType
* @param bundleGroupFilter if specified, must be member of bundle group
* @param bundleArtifactFilter if specified, must be member of bundle artifact
* @param typeFilter if specified, type must match
* @return the ControllerService types that this controller supports
*/
public Set<DocumentedTypeDTO> getControllerServiceTypes(final String serviceType, final String serviceBundleGroup, final String serviceBundleArtifact, final String serviceBundleVersion,
final String bundleGroupFilter, final String bundleArtifactFilter, final String typeFilter) {
final Set<Class> serviceImplementations = ExtensionManager.getExtensions(ControllerService.class);
// identify the controller services that implement the specified serviceType if applicable
if (serviceType != null) {
final BundleCoordinate bundleCoordinate = new BundleCoordinate(serviceBundleGroup, serviceBundleArtifact, serviceBundleVersion);
final Bundle csBundle = ExtensionManager.getBundle(bundleCoordinate);
if (csBundle == null) {
throw new IllegalStateException("Unable to find bundle for coordinate " + bundleCoordinate.getCoordinate());
}
Class serviceClass = null;
final ClassLoader currentContextClassLoader = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(csBundle.getClassLoader());
serviceClass = Class.forName(serviceType, false, csBundle.getClassLoader());
} catch (final Exception e) {
Thread.currentThread().setContextClassLoader(currentContextClassLoader);
throw new IllegalArgumentException(String.format("Unable to load %s from bundle %s: %s", serviceType, bundleCoordinate, e), e);
}
final Map<Class, Bundle> matchingServiceImplementations = new HashMap<>();
// check each type and remove those that aren't in the specified ancestry
for (final Class csClass : serviceImplementations) {
if (implementsServiceType(serviceClass, csClass)) {
matchingServiceImplementations.put(csClass, ExtensionManager.getBundle(csClass.getClassLoader()));
}
}
return dtoFactory.fromDocumentedTypes(matchingServiceImplementations, bundleGroupFilter, bundleArtifactFilter, typeFilter);
} else {
return dtoFactory.fromDocumentedTypes(serviceImplementations, bundleGroupFilter, bundleArtifactFilter, typeFilter);
}
}
/**
* Gets the ReportingTask types that this controller supports.
*
* @param bundleGroupFilter if specified, must be member of bundle group
* @param bundleArtifactFilter if specified, must be member of bundle artifact
* @param typeFilter if specified, type must match
* @return the ReportingTask types that this controller supports
*/
public Set<DocumentedTypeDTO> getReportingTaskTypes(final String bundleGroupFilter, final String bundleArtifactFilter, final String typeFilter) {
return dtoFactory.fromDocumentedTypes(ExtensionManager.getExtensions(ReportingTask.class), bundleGroupFilter, bundleArtifactFilter, typeFilter);
}
/**
* Gets the counters for this controller.
*
* @return the counters for this controller
*/
public List<Counter> getCounters() {
return flowController.getCounters();
}
/**
* Resets the counter with the specified id.
*
* @param id id
* @return the counter with the specified id
*/
public Counter resetCounter(final String id) {
final Counter counter = flowController.resetCounter(id);
if (counter == null) {
throw new ResourceNotFoundException(String.format("Unable to find Counter with id '%s'.", id));
}
return counter;
}
/**
* Gets the status of this controller.
*
* @return the status of this controller
*/
public ControllerStatusDTO getControllerStatus() {
final ProcessGroup rootGroup = flowController.getGroup(flowController.getRootGroupId());
final QueueSize controllerQueueSize = flowController.getTotalFlowFileCount(rootGroup);
final ControllerStatusDTO controllerStatus = new ControllerStatusDTO();
controllerStatus.setActiveThreadCount(flowController.getActiveThreadCount());
controllerStatus.setQueued(FormatUtils.formatCount(controllerQueueSize.getObjectCount()) + " / " + FormatUtils.formatDataSize(controllerQueueSize.getByteCount()));
controllerStatus.setBytesQueued(controllerQueueSize.getByteCount());
controllerStatus.setFlowFilesQueued(controllerQueueSize.getObjectCount());
final ProcessGroupCounts counts = rootGroup.getCounts();
controllerStatus.setRunningCount(counts.getRunningCount());
controllerStatus.setStoppedCount(counts.getStoppedCount());
controllerStatus.setInvalidCount(counts.getInvalidCount());
controllerStatus.setDisabledCount(counts.getDisabledCount());
controllerStatus.setActiveRemotePortCount(counts.getActiveRemotePortCount());
controllerStatus.setInactiveRemotePortCount(counts.getInactiveRemotePortCount());
controllerStatus.setUpToDateCount(counts.getUpToDateCount());
controllerStatus.setLocallyModifiedCount(counts.getLocallyModifiedCount());
controllerStatus.setStaleCount(counts.getStaleCount());
controllerStatus.setLocallyModifiedAndStaleCount(counts.getLocallyModifiedAndStaleCount());
controllerStatus.setSyncFailureCount(counts.getSyncFailureCount());
return controllerStatus;
}
/**
* Gets the status for the specified process group.
*
* @param groupId group id
* @return the status for the specified process group
*/
public ProcessGroupStatus getProcessGroupStatus(final String groupId) {
final ProcessGroupStatus processGroupStatus = flowController.getGroupStatus(groupId, NiFiUserUtils.getNiFiUser());
if (processGroupStatus == null) {
throw new ResourceNotFoundException(String.format("Unable to locate group with id '%s'.", groupId));
}
return processGroupStatus;
}
/**
* Gets the status for the specified processor.
*
* @param processorId processor id
* @return the status for the specified processor
*/
public ProcessorStatus getProcessorStatus(final String processorId) {
final ProcessGroup root = flowController.getGroup(flowController.getRootGroupId());
final ProcessorNode processor = root.findProcessor(processorId);
// ensure the processor was found
if (processor == null) {
throw new ResourceNotFoundException(String.format("Unable to locate processor with id '%s'.", processorId));
}
// calculate the process group status
final String groupId = processor.getProcessGroup().getIdentifier();
final ProcessGroupStatus processGroupStatus = flowController.getGroupStatus(groupId, NiFiUserUtils.getNiFiUser());
if (processGroupStatus == null) {
throw new ResourceNotFoundException(String.format("Unable to locate group with id '%s'.", groupId));
}
final ProcessorStatus status = processGroupStatus.getProcessorStatus().stream().filter(processorStatus -> processorId.equals(processorStatus.getId())).findFirst().orElse(null);
if (status == null) {
throw new ResourceNotFoundException(String.format("Unable to locate processor with id '%s'.", processorId));
}
return status;
}
/**
* Gets the status for the specified connection.
*
* @param connectionId connection id
* @return the status for the specified connection
*/
public ConnectionStatus getConnectionStatus(final String connectionId) {
final ProcessGroup root = flowController.getGroup(flowController.getRootGroupId());
final Connection connection = root.findConnection(connectionId);
// ensure the connection was found
if (connection == null) {
throw new ResourceNotFoundException(String.format("Unable to locate connection with id '%s'.", connectionId));
}
// calculate the process group status
final String groupId = connection.getProcessGroup().getIdentifier();
final ProcessGroupStatus processGroupStatus = flowController.getGroupStatus(groupId, NiFiUserUtils.getNiFiUser());
if (processGroupStatus == null) {
throw new ResourceNotFoundException(String.format("Unable to locate group with id '%s'.", groupId));
}
final ConnectionStatus status = processGroupStatus.getConnectionStatus().stream().filter(connectionStatus -> connectionId.equals(connectionStatus.getId())).findFirst().orElse(null);
if (status == null) {
throw new ResourceNotFoundException(String.format("Unable to locate connection with id '%s'.", connectionId));
}
return status;
}
/**
* Gets the status for the specified input port.
*
* @param portId input port id
* @return the status for the specified input port
*/
public PortStatus getInputPortStatus(final String portId) {
final ProcessGroup root = flowController.getGroup(flowController.getRootGroupId());
final Port port = root.findInputPort(portId);
// ensure the input port was found
if (port == null) {
throw new ResourceNotFoundException(String.format("Unable to locate input port with id '%s'.", portId));
}
final String groupId = port.getProcessGroup().getIdentifier();
final ProcessGroupStatus processGroupStatus = flowController.getGroupStatus(groupId, NiFiUserUtils.getNiFiUser());
if (processGroupStatus == null) {
throw new ResourceNotFoundException(String.format("Unable to locate group with id '%s'.", groupId));
}
final PortStatus status = processGroupStatus.getInputPortStatus().stream().filter(portStatus -> portId.equals(portStatus.getId())).findFirst().orElse(null);
if (status == null) {
throw new ResourceNotFoundException(String.format("Unable to locate input port with id '%s'.", portId));
}
return status;
}
/**
* Gets the status for the specified output port.
*
* @param portId output port id
* @return the status for the specified output port
*/
public PortStatus getOutputPortStatus(final String portId) {
final ProcessGroup root = flowController.getGroup(flowController.getRootGroupId());
final Port port = root.findOutputPort(portId);
// ensure the output port was found
if (port == null) {
throw new ResourceNotFoundException(String.format("Unable to locate output port with id '%s'.", portId));
}
final String groupId = port.getProcessGroup().getIdentifier();
final ProcessGroupStatus processGroupStatus = flowController.getGroupStatus(groupId, NiFiUserUtils.getNiFiUser());
if (processGroupStatus == null) {
throw new ResourceNotFoundException(String.format("Unable to locate group with id '%s'.", groupId));
}
final PortStatus status = processGroupStatus.getOutputPortStatus().stream().filter(portStatus -> portId.equals(portStatus.getId())).findFirst().orElse(null);
if (status == null) {
throw new ResourceNotFoundException(String.format("Unable to locate output port with id '%s'.", portId));
}
return status;
}
/**
* Gets the status for the specified remote process group.
*
* @param remoteProcessGroupId remote process group id
* @return the status for the specified remote process group
*/
public RemoteProcessGroupStatus getRemoteProcessGroupStatus(final String remoteProcessGroupId) {
final ProcessGroup root = flowController.getGroup(flowController.getRootGroupId());
final RemoteProcessGroup remoteProcessGroup = root.findRemoteProcessGroup(remoteProcessGroupId);
// ensure the output port was found
if (remoteProcessGroup == null) {
throw new ResourceNotFoundException(String.format("Unable to locate remote process group with id '%s'.", remoteProcessGroupId));
}
final String groupId = remoteProcessGroup.getProcessGroup().getIdentifier();
final ProcessGroupStatus groupStatus = flowController.getGroupStatus(groupId, NiFiUserUtils.getNiFiUser());
if (groupStatus == null) {
throw new ResourceNotFoundException(String.format("Unable to locate group with id '%s'.", groupId));
}
final RemoteProcessGroupStatus status = groupStatus.getRemoteProcessGroupStatus().stream().filter(rpgStatus -> remoteProcessGroupId.equals(rpgStatus.getId())).findFirst().orElse(null);
if (status == null) {
throw new ResourceNotFoundException(String.format("Unable to locate remote process group with id '%s'.", remoteProcessGroupId));
}
return status;
}
/**
* Saves the state of the flow controller.
*
* @throws NiFiCoreException ex
*/
public void save() throws NiFiCoreException {
// save the flow controller
final long writeDelaySeconds = FormatUtils.getTimeDuration(properties.getFlowServiceWriteDelay(), TimeUnit.SECONDS);
flowService.saveFlowChanges(TimeUnit.SECONDS, writeDelaySeconds);
}
/**
* Returns the socket port that the local instance is listening on for
* Site-to-Site communications
*
* @return the socket port that the local instance is listening on for
* Site-to-Site communications
*/
public Integer getRemoteSiteListeningPort() {
return flowController.getRemoteSiteListeningPort();
}
/**
* Returns the http(s) port that the local instance is listening on for
* Site-to-Site communications
*
* @return the socket port that the local instance is listening on for
* Site-to-Site communications
*/
public Integer getRemoteSiteListeningHttpPort() {
return flowController.getRemoteSiteListeningHttpPort();
}
/**
* Indicates whether or not Site-to-Site communications with the local
* instance are secure
*
* @return whether or not Site-to-Site communications with the local
* instance are secure
*/
public Boolean isRemoteSiteCommsSecure() {
return flowController.isRemoteSiteCommsSecure();
}
/**
* Returns a SystemDiagnostics that describes the current state of the node
*
* @return a SystemDiagnostics that describes the current state of the node
*/
public SystemDiagnostics getSystemDiagnostics() {
return flowController.getSystemDiagnostics();
}
public List<Resource> getResources() {
final List<Resource> resources = new ArrayList<>();
resources.add(ResourceFactory.getFlowResource());
resources.add(ResourceFactory.getSystemResource());
resources.add(ResourceFactory.getRestrictedComponentsResource());
resources.add(ResourceFactory.getControllerResource());
resources.add(ResourceFactory.getCountersResource());
resources.add(ResourceFactory.getProvenanceResource());
resources.add(ResourceFactory.getPoliciesResource());
resources.add(ResourceFactory.getTenantResource());
resources.add(ResourceFactory.getProxyResource());
resources.add(ResourceFactory.getResourceResource());
resources.add(ResourceFactory.getSiteToSiteResource());
final ProcessGroup root = flowController.getGroup(flowController.getRootGroupId());
// include the root group
final Resource rootResource = root.getResource();
resources.add(rootResource);
resources.add(ResourceFactory.getDataResource(rootResource));
resources.add(ResourceFactory.getPolicyResource(rootResource));
// add each processor
for (final ProcessorNode processor : root.findAllProcessors()) {
final Resource processorResource = processor.getResource();
resources.add(processorResource);
resources.add(ResourceFactory.getDataResource(processorResource));
resources.add(ResourceFactory.getPolicyResource(processorResource));
}
// add each label
for (final Label label : root.findAllLabels()) {
final Resource labelResource = label.getResource();
resources.add(labelResource);
resources.add(ResourceFactory.getPolicyResource(labelResource));
}
// add each process group
for (final ProcessGroup processGroup : root.findAllProcessGroups()) {
final Resource processGroupResource = processGroup.getResource();
resources.add(processGroupResource);
resources.add(ResourceFactory.getDataResource(processGroupResource));
resources.add(ResourceFactory.getPolicyResource(processGroupResource));
}
// add each remote process group
for (final RemoteProcessGroup remoteProcessGroup : root.findAllRemoteProcessGroups()) {
final Resource remoteProcessGroupResource = remoteProcessGroup.getResource();
resources.add(remoteProcessGroupResource);
resources.add(ResourceFactory.getDataResource(remoteProcessGroupResource));
resources.add(ResourceFactory.getPolicyResource(remoteProcessGroupResource));
}
// add each input port
for (final Port inputPort : root.findAllInputPorts()) {
final Resource inputPortResource = inputPort.getResource();
resources.add(inputPortResource);
resources.add(ResourceFactory.getDataResource(inputPortResource));
resources.add(ResourceFactory.getPolicyResource(inputPortResource));
if (inputPort instanceof RootGroupPort) {
resources.add(ResourceFactory.getDataTransferResource(inputPortResource));
}
}
// add each output port
for (final Port outputPort : root.findAllOutputPorts()) {
final Resource outputPortResource = outputPort.getResource();
resources.add(outputPortResource);
resources.add(ResourceFactory.getDataResource(outputPortResource));
resources.add(ResourceFactory.getPolicyResource(outputPortResource));
if (outputPort instanceof RootGroupPort) {
resources.add(ResourceFactory.getDataTransferResource(outputPortResource));
}
}
// add each controller service
final Consumer<ControllerServiceNode> csConsumer = controllerService -> {
final Resource controllerServiceResource = controllerService.getResource();
resources.add(controllerServiceResource);
resources.add(ResourceFactory.getPolicyResource(controllerServiceResource));
};
flowController.getAllControllerServices().forEach(csConsumer);
root.findAllControllerServices().forEach(csConsumer);
// add each reporting task
for (final ReportingTaskNode reportingTask : flowController.getAllReportingTasks()) {
final Resource reportingTaskResource = reportingTask.getResource();
resources.add(reportingTaskResource);
resources.add(ResourceFactory.getPolicyResource(reportingTaskResource));
}
// add each template
for (final Template template : root.findAllTemplates()) {
final Resource templateResource = template.getResource();
resources.add(templateResource);
resources.add(ResourceFactory.getPolicyResource(templateResource));
}
return resources;
}
/**
* Gets the available options for searching provenance.
*
* @return the available options for searching provenance
*/
public ProvenanceOptionsDTO getProvenanceSearchOptions() {
final ProvenanceRepository provenanceRepository = flowController.getProvenanceRepository();
// create the search options dto
final ProvenanceOptionsDTO searchOptions = new ProvenanceOptionsDTO();
final List<ProvenanceSearchableFieldDTO> searchableFieldNames = new ArrayList<>();
final List<SearchableField> fields = provenanceRepository.getSearchableFields();
for (final SearchableField field : fields) {
// we exclude the Event Time because it is always searchable but don't want support querying it this way...
// we prefer the user queries using startDate and endDate
if (SearchableFields.EventTime.equals(field)) {
continue;
}
final ProvenanceSearchableFieldDTO searchableField = new ProvenanceSearchableFieldDTO();
searchableField.setId(field.getIdentifier());
searchableField.setField(field.getSearchableFieldName());
searchableField.setLabel(field.getFriendlyName());
searchableField.setType(field.getFieldType().name());
searchableFieldNames.add(searchableField);
}
final List<SearchableField> searchableAttributes = provenanceRepository.getSearchableAttributes();
for (final SearchableField searchableAttr : searchableAttributes) {
final ProvenanceSearchableFieldDTO searchableAttribute = new ProvenanceSearchableFieldDTO();
searchableAttribute.setId(searchableAttr.getIdentifier());
searchableAttribute.setField(searchableAttr.getSearchableFieldName());
searchableAttribute.setLabel(searchableAttr.getFriendlyName());
searchableAttribute.setType(searchableAttr.getFieldType().name());
searchableFieldNames.add(searchableAttribute);
}
searchOptions.setSearchableFields(searchableFieldNames);
return searchOptions;
}
/**
* Submits a provenance query.
*
* @param provenanceDto dto
* @return provenance info
*/
public ProvenanceDTO submitProvenance(ProvenanceDTO provenanceDto) {
final ProvenanceRequestDTO requestDto = provenanceDto.getRequest();
// create the query
final Query query = new Query(provenanceDto.getId());
// if the request was specified
if (requestDto != null) {
// add each search term specified
final Map<String, String> searchTerms = requestDto.getSearchTerms();
if (searchTerms != null) {
for (final Map.Entry<String, String> searchTerm : searchTerms.entrySet()) {
SearchableField field;
field = SearchableFields.getSearchableField(searchTerm.getKey());
if (field == null) {
field = SearchableFields.newSearchableAttribute(searchTerm.getKey());
}
query.addSearchTerm(SearchTerms.newSearchTerm(field, searchTerm.getValue()));
}
}
// specify the start date if specified
if (requestDto.getStartDate() != null) {
query.setStartDate(requestDto.getStartDate());
}
// ensure an end date is populated
if (requestDto.getEndDate() != null) {
query.setEndDate(requestDto.getEndDate());
}
// set the min/max file size
query.setMinFileSize(requestDto.getMinimumFileSize());
query.setMaxFileSize(requestDto.getMaximumFileSize());
// set the max results desired
query.setMaxResults(requestDto.getMaxResults());
}
// submit the query to the provenance repository
final ProvenanceRepository provenanceRepository = flowController.getProvenanceRepository();
final QuerySubmission querySubmission = provenanceRepository.submitQuery(query, NiFiUserUtils.getNiFiUser());
// return the query with the results populated at this point
return getProvenanceQuery(querySubmission.getQueryIdentifier(), requestDto.getSummarize(), requestDto.getIncrementalResults());
}
/**
* Retrieves the results of a provenance query.
*
* @param provenanceId id
* @return the results of a provenance query
*/
public ProvenanceDTO getProvenanceQuery(String provenanceId, Boolean summarize, Boolean incrementalResults) {
try {
// get the query to the provenance repository
final ProvenanceRepository provenanceRepository = flowController.getProvenanceRepository();
final QuerySubmission querySubmission = provenanceRepository.retrieveQuerySubmission(provenanceId, NiFiUserUtils.getNiFiUser());
// ensure the query results could be found
if (querySubmission == null) {
throw new ResourceNotFoundException("Cannot find the results for the specified provenance requests. Results may have been purged.");
}
// get the original query and the results
final Query query = querySubmission.getQuery();
final QueryResult queryResult = querySubmission.getResult();
// build the response
final ProvenanceDTO provenanceDto = new ProvenanceDTO();
final ProvenanceRequestDTO requestDto = new ProvenanceRequestDTO();
final ProvenanceResultsDTO resultsDto = new ProvenanceResultsDTO();
// include the original request and results
provenanceDto.setRequest(requestDto);
provenanceDto.setResults(resultsDto);
// convert the original request
requestDto.setStartDate(query.getStartDate());
requestDto.setEndDate(query.getEndDate());
requestDto.setMinimumFileSize(query.getMinFileSize());
requestDto.setMaximumFileSize(query.getMaxFileSize());
requestDto.setMaxResults(query.getMaxResults());
if (query.getSearchTerms() != null) {
final Map<String, String> searchTerms = new HashMap<>();
for (final SearchTerm searchTerm : query.getSearchTerms()) {
searchTerms.put(searchTerm.getSearchableField().getFriendlyName(), searchTerm.getValue());
}
requestDto.setSearchTerms(searchTerms);
}
// convert the provenance
provenanceDto.setId(query.getIdentifier());
provenanceDto.setSubmissionTime(querySubmission.getSubmissionTime());
provenanceDto.setExpiration(queryResult.getExpiration());
provenanceDto.setFinished(queryResult.isFinished());
provenanceDto.setPercentCompleted(queryResult.getPercentComplete());
// convert each event
final boolean includeResults = incrementalResults == null || Boolean.TRUE.equals(incrementalResults);
if (includeResults || queryResult.isFinished()) {
final List<ProvenanceEventDTO> events = new ArrayList<>();
for (final ProvenanceEventRecord record : queryResult.getMatchingEvents()) {
events.add(createProvenanceEventDto(record, Boolean.TRUE.equals(summarize)));
}
resultsDto.setProvenanceEvents(events);
}
if (requestDto.getMaxResults() != null && queryResult.getTotalHitCount() >= requestDto.getMaxResults()) {
resultsDto.setTotalCount(requestDto.getMaxResults().longValue());
resultsDto.setTotal(FormatUtils.formatCount(requestDto.getMaxResults().longValue()) + "+");
} else {
resultsDto.setTotalCount(queryResult.getTotalHitCount());
resultsDto.setTotal(FormatUtils.formatCount(queryResult.getTotalHitCount()));
}
// include any errors
if (queryResult.getError() != null) {
final Set<String> errors = new HashSet<>();
errors.add(queryResult.getError());
resultsDto.setErrors(errors);
}
// set the generated timestamp
final Date now = new Date();
resultsDto.setGenerated(now);
resultsDto.setTimeOffset(TimeZone.getDefault().getOffset(now.getTime()));
// get the oldest available event time
final List<ProvenanceEventRecord> firstEvent = provenanceRepository.getEvents(0, 1);
if (!firstEvent.isEmpty()) {
resultsDto.setOldestEvent(new Date(firstEvent.get(0).getEventTime()));
}
provenanceDto.setResults(resultsDto);
return provenanceDto;
} catch (final IOException ioe) {
throw new NiFiCoreException("An error occurred while searching the provenance events.", ioe);
}
}
/**
* Submits the specified lineage request.
*
* @param lineageDto dto
* @return updated lineage
*/
public LineageDTO submitLineage(LineageDTO lineageDto) {
final LineageRequestDTO requestDto = lineageDto.getRequest();
// get the provenance repo
final ProvenanceRepository provenanceRepository = flowController.getProvenanceRepository();
final ComputeLineageSubmission result;
if (LineageRequestType.FLOWFILE.equals(requestDto.getLineageRequestType())) {
if (requestDto.getUuid() != null) {
// submit uuid if it is specified
result = provenanceRepository.submitLineageComputation(requestDto.getUuid(), NiFiUserUtils.getNiFiUser());
} else {
// submit the event if the flowfile uuid needs to be looked up
result = provenanceRepository.submitLineageComputation(requestDto.getEventId(), NiFiUserUtils.getNiFiUser());
}
} else {
// submit event... (parents or children)
if (LineageRequestType.PARENTS.equals(requestDto.getLineageRequestType())) {
result = provenanceRepository.submitExpandParents(requestDto.getEventId(), NiFiUserUtils.getNiFiUser());
} else {
result = provenanceRepository.submitExpandChildren(requestDto.getEventId(), NiFiUserUtils.getNiFiUser());
}
}
return getLineage(result.getLineageIdentifier());
}
/**
* Gets the lineage with the specified id.
*
* @param lineageId id
* @return the lineage with the specified id
*/
public LineageDTO getLineage(final String lineageId) {
// get the query to the provenance repository
final ProvenanceRepository provenanceRepository = flowController.getProvenanceRepository();
final ComputeLineageSubmission computeLineageSubmission = provenanceRepository.retrieveLineageSubmission(lineageId, NiFiUserUtils.getNiFiUser());
// ensure the submission was found
if (computeLineageSubmission == null) {
throw new ResourceNotFoundException("Cannot find the results for the specified lineage request. Results may have been purged.");
}
return dtoFactory.createLineageDto(computeLineageSubmission);
}
/**
* Deletes the query with the specified id.
*
* @param provenanceId id
*/
public void deleteProvenanceQuery(final String provenanceId) {
// get the query to the provenance repository
final ProvenanceRepository provenanceRepository = flowController.getProvenanceRepository();
final QuerySubmission querySubmission = provenanceRepository.retrieveQuerySubmission(provenanceId, NiFiUserUtils.getNiFiUser());
if (querySubmission != null) {
querySubmission.cancel();
}
}
/**
* Deletes the lineage with the specified id.
*
* @param lineageId id
*/
public void deleteLineage(final String lineageId) {
// get the query to the provenance repository
final ProvenanceRepository provenanceRepository = flowController.getProvenanceRepository();
final ComputeLineageSubmission computeLineageSubmission = provenanceRepository.retrieveLineageSubmission(lineageId, NiFiUserUtils.getNiFiUser());
if (computeLineageSubmission != null) {
computeLineageSubmission.cancel();
}
}
/**
* Gets the content for the specified claim.
*
* @param eventId event id
* @param uri uri
* @param contentDirection direction
* @return the content for the specified claim
*/
public DownloadableContent getContent(final Long eventId, final String uri, final ContentDirection contentDirection) {
try {
final NiFiUser user = NiFiUserUtils.getNiFiUser();
// get the event in order to get the filename
final ProvenanceEventRecord event = flowController.getProvenanceRepository().getEvent(eventId);
if (event == null) {
throw new ResourceNotFoundException("Unable to find the specified event.");
}
// get the flowfile attributes
final Map<String, String> attributes;
if (ContentDirection.INPUT.equals(contentDirection)) {
attributes = event.getPreviousAttributes();
} else {
attributes = event.getAttributes();
}
// authorize the event
final Authorizable dataAuthorizable;
if (event.isRemotePortType()) {
dataAuthorizable = flowController.createRemoteDataAuthorizable(event.getComponentId());
} else {
dataAuthorizable = flowController.createLocalDataAuthorizable(event.getComponentId());
}
dataAuthorizable.authorize(authorizer, RequestAction.READ, user, attributes);
// get the filename and fall back to the identifier (should never happen)
String filename = attributes.get(CoreAttributes.FILENAME.key());
if (filename == null) {
filename = event.getFlowFileUuid();
}
// get the mime-type
final String type = attributes.get(CoreAttributes.MIME_TYPE.key());
// get the content
final InputStream content = flowController.getContent(event, contentDirection, user.getIdentity(), uri);
return new DownloadableContent(filename, type, content);
} catch (final ContentNotFoundException cnfe) {
throw new ResourceNotFoundException("Unable to find the specified content.");
} catch (final IOException ioe) {
logger.error(String.format("Unable to get the content for event (%s) at this time.", eventId), ioe);
throw new IllegalStateException("Unable to get the content at this time.");
}
}
/**
* Submits a replay request for the specified event id.
*
* @param eventId event id
* @return provenance event
*/
public ProvenanceEventDTO submitReplay(final Long eventId) {
try {
final NiFiUser user = NiFiUserUtils.getNiFiUser();
if (user == null) {
throw new WebApplicationException(new Throwable("Unable to access details for current user."));
}
// lookup the original event
final ProvenanceEventRecord originalEvent = flowController.getProvenanceRepository().getEvent(eventId);
if (originalEvent == null) {
throw new ResourceNotFoundException("Unable to find the specified event.");
}
// authorize the replay
authorizeReplay(originalEvent);
// replay the flow file
final ProvenanceEventRecord event = flowController.replayFlowFile(originalEvent, user);
// convert the event record
return createProvenanceEventDto(event, false);
} catch (final IOException ioe) {
throw new NiFiCoreException("An error occurred while getting the specified event.", ioe);
}
}
/**
* Authorizes access to replay a specified provenance event.
*
* @param event event
*/
private AuthorizationResult checkAuthorizationForReplay(final ProvenanceEventRecord event) {
// if the connection id isn't specified, then the replay wouldn't be available anyways and we have nothing to authorize against so deny it`
if (event.getSourceQueueIdentifier() == null) {
return AuthorizationResult.denied("The connection id in the provenance event is unknown.");
}
final NiFiUser user = NiFiUserUtils.getNiFiUser();
final Authorizable dataAuthorizable;
if (event.isRemotePortType()) {
dataAuthorizable = flowController.createRemoteDataAuthorizable(event.getComponentId());
} else {
dataAuthorizable = flowController.createLocalDataAuthorizable(event.getComponentId());
}
final Map<String, String> eventAttributes = event.getAttributes();
// ensure we can read the data
final AuthorizationResult result = dataAuthorizable.checkAuthorization(authorizer, RequestAction.READ, user, eventAttributes);
if (!Result.Approved.equals(result.getResult())) {
return result;
}
// ensure we can write the data
return dataAuthorizable.checkAuthorization(authorizer, RequestAction.WRITE, user, eventAttributes);
}
/**
* Authorizes access to replay a specified provenance event.
*
* @param event event
*/
private void authorizeReplay(final ProvenanceEventRecord event) {
// if the connection id isn't specified, then the replay wouldn't be available anyways and we have nothing to authorize against so deny it`
if (event.getSourceQueueIdentifier() == null) {
throw new AccessDeniedException("The connection id in the provenance event is unknown.");
}
final NiFiUser user = NiFiUserUtils.getNiFiUser();
final Authorizable dataAuthorizable;
if (event.isRemotePortType()) {
dataAuthorizable = flowController.createRemoteDataAuthorizable(event.getComponentId());
} else {
dataAuthorizable = flowController.createLocalDataAuthorizable(event.getComponentId());
}
// ensure we can read and write the data
final Map<String, String> eventAttributes = event.getAttributes();
dataAuthorizable.authorize(authorizer, RequestAction.READ, user, eventAttributes);
dataAuthorizable.authorize(authorizer, RequestAction.WRITE, user, eventAttributes);
}
/**
* Get the provenance event with the specified event id.
*
* @param eventId event id
* @return the provenance event with the specified event id
*/
public ProvenanceEventDTO getProvenanceEvent(final Long eventId) {
try {
final ProvenanceEventRecord event = flowController.getProvenanceRepository().getEvent(eventId);
if (event == null) {
throw new ResourceNotFoundException("Unable to find the specified event.");
}
// get the flowfile attributes and authorize the event
final Map<String, String> attributes = event.getAttributes();
final Authorizable dataAuthorizable;
if (event.isRemotePortType()) {
dataAuthorizable = flowController.createRemoteDataAuthorizable(event.getComponentId());
} else {
dataAuthorizable = flowController.createLocalDataAuthorizable(event.getComponentId());
}
dataAuthorizable.authorize(authorizer, RequestAction.READ, NiFiUserUtils.getNiFiUser(), attributes);
// convert the event
return createProvenanceEventDto(event, false);
} catch (final IOException ioe) {
throw new NiFiCoreException("An error occurred while getting the specified event.", ioe);
}
}
/**
* Creates a ProvenanceEventDTO for the specified ProvenanceEventRecord.
*
* @param event event
* @return event
*/
private ProvenanceEventDTO createProvenanceEventDto(final ProvenanceEventRecord event, final boolean summarize) {
final ProvenanceEventDTO dto = new ProvenanceEventDTO();
dto.setId(String.valueOf(event.getEventId()));
dto.setEventId(event.getEventId());
dto.setEventTime(new Date(event.getEventTime()));
dto.setEventType(event.getEventType().name());
dto.setFlowFileUuid(event.getFlowFileUuid());
dto.setFileSize(FormatUtils.formatDataSize(event.getFileSize()));
dto.setFileSizeBytes(event.getFileSize());
dto.setComponentId(event.getComponentId());
dto.setComponentType(event.getComponentType());
// sets the component details if it can find the component still in the flow
setComponentDetails(dto);
// only include all details if not summarizing
if (!summarize) {
// convert the attributes
final Comparator<AttributeDTO> attributeComparator = new Comparator<AttributeDTO>() {
@Override
public int compare(AttributeDTO a1, AttributeDTO a2) {
return Collator.getInstance(Locale.US).compare(a1.getName(), a2.getName());
}
};
final SortedSet<AttributeDTO> attributes = new TreeSet<>(attributeComparator);
final Map<String, String> updatedAttrs = event.getUpdatedAttributes();
final Map<String, String> previousAttrs = event.getPreviousAttributes();
// add previous attributes that haven't been modified.
for (final Map.Entry<String, String> entry : previousAttrs.entrySet()) {
// don't add any attributes that have been updated; we will do that next
if (updatedAttrs.containsKey(entry.getKey())) {
continue;
}
final AttributeDTO attribute = new AttributeDTO();
attribute.setName(entry.getKey());
attribute.setValue(entry.getValue());
attribute.setPreviousValue(entry.getValue());
attributes.add(attribute);
}
// Add all of the update attributes
for (final Map.Entry<String, String> entry : updatedAttrs.entrySet()) {
final AttributeDTO attribute = new AttributeDTO();
attribute.setName(entry.getKey());
attribute.setValue(entry.getValue());
attribute.setPreviousValue(previousAttrs.get(entry.getKey()));
attributes.add(attribute);
}
// additional event details
dto.setAlternateIdentifierUri(event.getAlternateIdentifierUri());
dto.setAttributes(attributes);
dto.setTransitUri(event.getTransitUri());
dto.setSourceSystemFlowFileId(event.getSourceSystemFlowFileIdentifier());
dto.setRelationship(event.getRelationship());
dto.setDetails(event.getDetails());
final ContentAvailability contentAvailability = flowController.getContentAvailability(event);
// content
dto.setContentEqual(contentAvailability.isContentSame());
dto.setInputContentAvailable(contentAvailability.isInputAvailable());
dto.setInputContentClaimSection(event.getPreviousContentClaimSection());
dto.setInputContentClaimContainer(event.getPreviousContentClaimContainer());
dto.setInputContentClaimIdentifier(event.getPreviousContentClaimIdentifier());
dto.setInputContentClaimOffset(event.getPreviousContentClaimOffset());
dto.setInputContentClaimFileSizeBytes(event.getPreviousFileSize());
dto.setOutputContentAvailable(contentAvailability.isOutputAvailable());
dto.setOutputContentClaimSection(event.getContentClaimSection());
dto.setOutputContentClaimContainer(event.getContentClaimContainer());
dto.setOutputContentClaimIdentifier(event.getContentClaimIdentifier());
dto.setOutputContentClaimOffset(event.getContentClaimOffset());
dto.setOutputContentClaimFileSize(FormatUtils.formatDataSize(event.getFileSize()));
dto.setOutputContentClaimFileSizeBytes(event.getFileSize());
// format the previous file sizes if possible
if (event.getPreviousFileSize() != null) {
dto.setInputContentClaimFileSize(FormatUtils.formatDataSize(event.getPreviousFileSize()));
}
// determine if authorized for event replay
final AuthorizationResult replayAuthorized = checkAuthorizationForReplay(event);
// replay
dto.setReplayAvailable(contentAvailability.isReplayable() && Result.Approved.equals(replayAuthorized.getResult()));
dto.setReplayExplanation(contentAvailability.isReplayable()
&& !Result.Approved.equals(replayAuthorized.getResult()) ? replayAuthorized.getExplanation() : contentAvailability.getReasonNotReplayable());
dto.setSourceConnectionIdentifier(event.getSourceQueueIdentifier());
// event duration
if (event.getEventDuration() >= 0) {
dto.setEventDuration(event.getEventDuration());
}
// lineage duration
if (event.getLineageStartDate() > 0) {
final long lineageDuration = event.getEventTime() - event.getLineageStartDate();
dto.setLineageDuration(lineageDuration);
}
// parent uuids
final List<String> parentUuids = new ArrayList<>(event.getParentUuids());
Collections.sort(parentUuids, Collator.getInstance(Locale.US));
dto.setParentUuids(parentUuids);
// child uuids
final List<String> childUuids = new ArrayList<>(event.getChildUuids());
Collections.sort(childUuids, Collator.getInstance(Locale.US));
dto.setChildUuids(childUuids);
}
return dto;
}
private void setComponentDetails(final ProvenanceEventDTO dto) {
final ProcessGroup root = flowController.getGroup(flowController.getRootGroupId());
final Connectable connectable = root.findLocalConnectable(dto.getComponentId());
if (connectable != null) {
dto.setGroupId(connectable.getProcessGroup().getIdentifier());
dto.setComponentName(connectable.getName());
return;
}
final RemoteGroupPort remoteGroupPort = root.findRemoteGroupPort(dto.getComponentId());
if (remoteGroupPort != null) {
dto.setGroupId(remoteGroupPort.getProcessGroupIdentifier());
dto.setComponentName(remoteGroupPort.getName());
return;
}
final Connection connection = root.findConnection(dto.getComponentId());
if (connection != null) {
dto.setGroupId(connection.getProcessGroup().getIdentifier());
String name = connection.getName();
final Collection<Relationship> relationships = connection.getRelationships();
if (StringUtils.isBlank(name) && CollectionUtils.isNotEmpty(relationships)) {
name = StringUtils.join(relationships.stream().map(relationship -> relationship.getName()).collect(Collectors.toSet()), ", ");
}
dto.setComponentName(name);
return;
}
}
/**
* Searches this controller for the specified term.
*
* @param search search
* @return result
*/
public SearchResultsDTO search(final String search) {
final ProcessGroup rootGroup = flowController.getGroup(flowController.getRootGroupId());
final SearchResultsDTO results = new SearchResultsDTO();
search(results, search, rootGroup);
return results;
}
private void search(final SearchResultsDTO results, final String search, final ProcessGroup group) {
final NiFiUser user = NiFiUserUtils.getNiFiUser();
if (group.isAuthorized(authorizer, RequestAction.READ, user)) {
final ComponentSearchResultDTO groupMatch = search(search, group);
if (groupMatch != null) {
results.getProcessGroupResults().add(groupMatch);
}
}
for (final ProcessorNode procNode : group.getProcessors()) {
if (procNode.isAuthorized(authorizer, RequestAction.READ, user)) {
final ComponentSearchResultDTO match = search(search, procNode);
if (match != null) {
match.setGroupId(group.getIdentifier());
results.getProcessorResults().add(match);
}
}
}
for (final Connection connection : group.getConnections()) {
if (connection.isAuthorized(authorizer, RequestAction.READ, user)) {
final ComponentSearchResultDTO match = search(search, connection);
if (match != null) {
match.setGroupId(group.getIdentifier());
results.getConnectionResults().add(match);
}
}
}
for (final RemoteProcessGroup remoteGroup : group.getRemoteProcessGroups()) {
if (remoteGroup.isAuthorized(authorizer, RequestAction.READ, user)) {
final ComponentSearchResultDTO match = search(search, remoteGroup);
if (match != null) {
match.setGroupId(group.getIdentifier());
results.getRemoteProcessGroupResults().add(match);
}
}
}
for (final Port port : group.getInputPorts()) {
if (port.isAuthorized(authorizer, RequestAction.READ, user)) {
final ComponentSearchResultDTO match = search(search, port);
if (match != null) {
match.setGroupId(group.getIdentifier());
results.getInputPortResults().add(match);
}
}
}
for (final Port port : group.getOutputPorts()) {
if (port.isAuthorized(authorizer, RequestAction.READ, user)) {
final ComponentSearchResultDTO match = search(search, port);
if (match != null) {
match.setGroupId(group.getIdentifier());
results.getOutputPortResults().add(match);
}
}
}
for (final Funnel funnel : group.getFunnels()) {
if (funnel.isAuthorized(authorizer, RequestAction.READ, user)) {
final ComponentSearchResultDTO match = search(search, funnel);
if (match != null) {
match.setGroupId(group.getIdentifier());
results.getFunnelResults().add(match);
}
}
}
for (final ProcessGroup processGroup : group.getProcessGroups()) {
search(results, search, processGroup);
}
}
private ComponentSearchResultDTO search(final String searchStr, final Port port) {
final List<String> matches = new ArrayList<>();
addIfAppropriate(searchStr, port.getIdentifier(), "Id", matches);
addIfAppropriate(searchStr, port.getVersionedComponentId().orElse(null), "Version Control ID", matches);
addIfAppropriate(searchStr, port.getName(), "Name", matches);
addIfAppropriate(searchStr, port.getComments(), "Comments", matches);
// consider scheduled state
if (ScheduledState.DISABLED.equals(port.getScheduledState())) {
if (StringUtils.containsIgnoreCase("disabled", searchStr)) {
matches.add("Run status: Disabled");
}
} else {
if (StringUtils.containsIgnoreCase("invalid", searchStr) && !port.isValid()) {
matches.add("Run status: Invalid");
} else if (ScheduledState.RUNNING.equals(port.getScheduledState()) && StringUtils.containsIgnoreCase("running", searchStr)) {
matches.add("Run status: Running");
} else if (ScheduledState.STOPPED.equals(port.getScheduledState()) && StringUtils.containsIgnoreCase("stopped", searchStr)) {
matches.add("Run status: Stopped");
}
}
if (port instanceof RootGroupPort) {
final RootGroupPort rootGroupPort = (RootGroupPort) port;
// user access controls
for (final String userAccessControl : rootGroupPort.getUserAccessControl()) {
addIfAppropriate(searchStr, userAccessControl, "User access control", matches);
}
// group access controls
for (final String groupAccessControl : rootGroupPort.getGroupAccessControl()) {
addIfAppropriate(searchStr, groupAccessControl, "Group access control", matches);
}
}
if (matches.isEmpty()) {
return null;
}
final ComponentSearchResultDTO dto = new ComponentSearchResultDTO();
dto.setId(port.getIdentifier());
dto.setName(port.getName());
dto.setMatches(matches);
return dto;
}
public void verifyComponentTypes(VersionedProcessGroup versionedFlow) {
flowController.verifyComponentTypesInSnippet(versionedFlow);
}
private ComponentSearchResultDTO search(final String searchStr, final ProcessorNode procNode) {
final List<String> matches = new ArrayList<>();
final Processor processor = procNode.getProcessor();
addIfAppropriate(searchStr, procNode.getIdentifier(), "Id", matches);
addIfAppropriate(searchStr, procNode.getVersionedComponentId().orElse(null), "Version Control ID", matches);
addIfAppropriate(searchStr, procNode.getName(), "Name", matches);
addIfAppropriate(searchStr, procNode.getComments(), "Comments", matches);
// consider scheduling strategy
if (SchedulingStrategy.EVENT_DRIVEN.equals(procNode.getSchedulingStrategy()) && StringUtils.containsIgnoreCase("event", searchStr)) {
matches.add("Scheduling strategy: Event driven");
} else if (SchedulingStrategy.TIMER_DRIVEN.equals(procNode.getSchedulingStrategy()) && StringUtils.containsIgnoreCase("timer", searchStr)) {
matches.add("Scheduling strategy: Timer driven");
} else if (SchedulingStrategy.PRIMARY_NODE_ONLY.equals(procNode.getSchedulingStrategy()) && StringUtils.containsIgnoreCase("primary", searchStr)) {
// PRIMARY_NODE_ONLY has been deprecated as a SchedulingStrategy and replaced by PRIMARY as an ExecutionNode.
matches.add("Scheduling strategy: On primary node");
}
// consider execution node
if (ExecutionNode.PRIMARY.equals(procNode.getExecutionNode()) && StringUtils.containsIgnoreCase("primary", searchStr)) {
matches.add("Execution node: primary");
}
// consider scheduled state
if (ScheduledState.DISABLED.equals(procNode.getScheduledState())) {
if (StringUtils.containsIgnoreCase("disabled", searchStr)) {
matches.add("Run status: Disabled");
}
} else {
if (StringUtils.containsIgnoreCase("invalid", searchStr) && !procNode.isValid()) {
matches.add("Run status: Invalid");
} else if (ScheduledState.RUNNING.equals(procNode.getScheduledState()) && StringUtils.containsIgnoreCase("running", searchStr)) {
matches.add("Run status: Running");
} else if (ScheduledState.STOPPED.equals(procNode.getScheduledState()) && StringUtils.containsIgnoreCase("stopped", searchStr)) {
matches.add("Run status: Stopped");
}
}
for (final Relationship relationship : procNode.getRelationships()) {
addIfAppropriate(searchStr, relationship.getName(), "Relationship", matches);
}
// Add both the actual class name and the component type. This allows us to search for 'Ghost'
// to search for components that could not be instantiated.
addIfAppropriate(searchStr, processor.getClass().getSimpleName(), "Type", matches);
addIfAppropriate(searchStr, procNode.getComponentType(), "Type", matches);
for (final Map.Entry<PropertyDescriptor, String> entry : procNode.getProperties().entrySet()) {
final PropertyDescriptor descriptor = entry.getKey();
addIfAppropriate(searchStr, descriptor.getName(), "Property name", matches);
addIfAppropriate(searchStr, descriptor.getDescription(), "Property description", matches);
// never include sensitive properties values in search results
if (descriptor.isSensitive()) {
continue;
}
String value = entry.getValue();
// if unset consider default value
if (value == null) {
value = descriptor.getDefaultValue();
}
// evaluate if the value matches the search criteria
if (StringUtils.containsIgnoreCase(value, searchStr)) {
matches.add("Property value: " + descriptor.getName() + " - " + value);
}
}
// consider searching the processor directly
if (processor instanceof Searchable) {
final Searchable searchable = (Searchable) processor;
final SearchContext context = new StandardSearchContext(searchStr, procNode, flowController, variableRegistry);
// search the processor using the appropriate thread context classloader
try (final NarCloseable x = NarCloseable.withComponentNarLoader(processor.getClass(), processor.getIdentifier())) {
final Collection<SearchResult> searchResults = searchable.search(context);
if (CollectionUtils.isNotEmpty(searchResults)) {
for (final SearchResult searchResult : searchResults) {
matches.add(searchResult.getLabel() + ": " + searchResult.getMatch());
}
}
} catch (final Throwable t) {
// log this as error
}
}
if (matches.isEmpty()) {
return null;
}
final ComponentSearchResultDTO result = new ComponentSearchResultDTO();
result.setId(procNode.getIdentifier());
result.setMatches(matches);
result.setName(procNode.getName());
return result;
}
private ComponentSearchResultDTO search(final String searchStr, final ProcessGroup group) {
final List<String> matches = new ArrayList<>();
final ProcessGroup parent = group.getParent();
if (parent == null) {
return null;
}
addIfAppropriate(searchStr, group.getIdentifier(), "Id", matches);
addIfAppropriate(searchStr, group.getVersionedComponentId().orElse(null), "Version Control ID", matches);
addIfAppropriate(searchStr, group.getName(), "Name", matches);
addIfAppropriate(searchStr, group.getComments(), "Comments", matches);
final ComponentVariableRegistry varRegistry = group.getVariableRegistry();
if (varRegistry != null) {
final Map<VariableDescriptor, String> variableMap = varRegistry.getVariableMap();
for (final Map.Entry<VariableDescriptor, String> entry : variableMap.entrySet()) {
addIfAppropriate(searchStr, entry.getKey().getName(), "Variable Name", matches);
addIfAppropriate(searchStr, entry.getValue(), "Variable Value", matches);
}
}
if (matches.isEmpty()) {
return null;
}
final ComponentSearchResultDTO result = new ComponentSearchResultDTO();
result.setId(group.getIdentifier());
result.setName(group.getName());
result.setGroupId(parent.getIdentifier());
result.setMatches(matches);
return result;
}
private ComponentSearchResultDTO search(final String searchStr, final Connection connection) {
final List<String> matches = new ArrayList<>();
// search id and name
addIfAppropriate(searchStr, connection.getIdentifier(), "Id", matches);
addIfAppropriate(searchStr, connection.getVersionedComponentId().orElse(null), "Version Control ID", matches);
addIfAppropriate(searchStr, connection.getName(), "Name", matches);
// search relationships
for (final Relationship relationship : connection.getRelationships()) {
addIfAppropriate(searchStr, relationship.getName(), "Relationship", matches);
}
// search prioritizers
final FlowFileQueue queue = connection.getFlowFileQueue();
for (final FlowFilePrioritizer comparator : queue.getPriorities()) {
addIfAppropriate(searchStr, comparator.getClass().getName(), "Prioritizer", matches);
}
// search expiration
if (StringUtils.containsIgnoreCase("expires", searchStr) || StringUtils.containsIgnoreCase("expiration", searchStr)) {
final int expirationMillis = connection.getFlowFileQueue().getFlowFileExpiration(TimeUnit.MILLISECONDS);
if (expirationMillis > 0) {
matches.add("FlowFile expiration: " + connection.getFlowFileQueue().getFlowFileExpiration());
}
}
// search back pressure
if (StringUtils.containsIgnoreCase("back pressure", searchStr) || StringUtils.containsIgnoreCase("pressure", searchStr)) {
final String backPressureDataSize = connection.getFlowFileQueue().getBackPressureDataSizeThreshold();
final Double backPressureBytes = DataUnit.parseDataSize(backPressureDataSize, DataUnit.B);
if (backPressureBytes > 0) {
matches.add("Back pressure data size: " + backPressureDataSize);
}
final long backPressureCount = connection.getFlowFileQueue().getBackPressureObjectThreshold();
if (backPressureCount > 0) {
matches.add("Back pressure count: " + backPressureCount);
}
}
// search the source
final Connectable source = connection.getSource();
addIfAppropriate(searchStr, source.getIdentifier(), "Source id", matches);
addIfAppropriate(searchStr, source.getName(), "Source name", matches);
addIfAppropriate(searchStr, source.getComments(), "Source comments", matches);
// search the destination
final Connectable destination = connection.getDestination();
addIfAppropriate(searchStr, destination.getIdentifier(), "Destination id", matches);
addIfAppropriate(searchStr, destination.getName(), "Destination name", matches);
addIfAppropriate(searchStr, destination.getComments(), "Destination comments", matches);
if (matches.isEmpty()) {
return null;
}
final ComponentSearchResultDTO result = new ComponentSearchResultDTO();
result.setId(connection.getIdentifier());
// determine the name of the search match
if (StringUtils.isNotBlank(connection.getName())) {
result.setName(connection.getName());
} else if (!connection.getRelationships().isEmpty()) {
final List<String> relationships = new ArrayList<>(connection.getRelationships().size());
for (final Relationship relationship : connection.getRelationships()) {
if (StringUtils.isNotBlank(relationship.getName())) {
relationships.add(relationship.getName());
}
}
if (!relationships.isEmpty()) {
result.setName(StringUtils.join(relationships, ", "));
}
}
// ensure a name is added
if (result.getName() == null) {
result.setName("From source " + connection.getSource().getName());
}
result.setMatches(matches);
return result;
}
private ComponentSearchResultDTO search(final String searchStr, final RemoteProcessGroup group) {
final List<String> matches = new ArrayList<>();
addIfAppropriate(searchStr, group.getIdentifier(), "Id", matches);
addIfAppropriate(searchStr, group.getVersionedComponentId().orElse(null), "Version Control ID", matches);
addIfAppropriate(searchStr, group.getName(), "Name", matches);
addIfAppropriate(searchStr, group.getComments(), "Comments", matches);
addIfAppropriate(searchStr, group.getTargetUris(), "URLs", matches);
// consider the transmission status
if ((StringUtils.containsIgnoreCase("transmitting", searchStr) || StringUtils.containsIgnoreCase("transmission enabled", searchStr)) && group.isTransmitting()) {
matches.add("Transmission: On");
} else if ((StringUtils.containsIgnoreCase("not transmitting", searchStr) || StringUtils.containsIgnoreCase("transmission disabled", searchStr)) && !group.isTransmitting()) {
matches.add("Transmission: Off");
}
if (matches.isEmpty()) {
return null;
}
final ComponentSearchResultDTO result = new ComponentSearchResultDTO();
result.setId(group.getIdentifier());
result.setName(group.getName());
result.setMatches(matches);
return result;
}
private ComponentSearchResultDTO search(final String searchStr, final Funnel funnel) {
final List<String> matches = new ArrayList<>();
addIfAppropriate(searchStr, funnel.getIdentifier(), "Id", matches);
addIfAppropriate(searchStr, funnel.getVersionedComponentId().orElse(null), "Version Control ID", matches);
if (matches.isEmpty()) {
return null;
}
final ComponentSearchResultDTO dto = new ComponentSearchResultDTO();
dto.setId(funnel.getIdentifier());
dto.setName(funnel.getName());
dto.setMatches(matches);
return dto;
}
private void addIfAppropriate(final String searchStr, final String value, final String label, final List<String> matches) {
if (StringUtils.containsIgnoreCase(value, searchStr)) {
matches.add(label + ": " + value);
}
}
/*
* setters
*/
public void setFlowController(FlowController flowController) {
this.flowController = flowController;
}
public void setProperties(NiFiProperties properties) {
this.properties = properties;
}
public void setAuthorizer(Authorizer authorizer) {
this.authorizer = authorizer;
}
public void setFlowService(FlowService flowService) {
this.flowService = flowService;
}
public void setDtoFactory(DtoFactory dtoFactory) {
this.dtoFactory = dtoFactory;
}
public void setVariableRegistry(VariableRegistry variableRegistry) {
this.variableRegistry = variableRegistry;
}
}
| apache-2.0 |
akarnokd/Reactive4JavaFlow | src/main/java/hu/akarnokd/reactive4javaflow/processors/EsetlegProcessor.java | 1100 | /*
* Copyright 2017 David Karnok
*
* 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 hu.akarnokd.reactive4javaflow.processors;
import hu.akarnokd.reactive4javaflow.Esetleg;
public abstract class EsetlegProcessor<T> extends Esetleg<T> implements FlowProcessorSupport<T> {
@Override
public EsetlegProcessor<T> toSerialized() {
return this;
}
@Override
public final EsetlegProcessor<T> refCount() {
if (this instanceof EsetlegProcessorRefCount) {
return this;
}
return new EsetlegProcessorRefCount<>(this);
}
}
| apache-2.0 |
mzule/AndroidWeekly | app/src/main/java/com/github/mzule/androidweekly/ui/view/NaviBar.java | 1740 | package com.github.mzule.androidweekly.ui.view;
import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.widget.TextView;
import com.github.mzule.androidweekly.R;
import com.github.mzule.androidweekly.ui.view.base.BaseLinearLayout;
import com.github.mzule.layoutannotation.Layout;
import butterknife.Bind;
import butterknife.OnClick;
/**
* Created by CaoDongping on 4/5/16.
*/
@Layout(R.layout.view_navi_bar)
public class NaviBar extends BaseLinearLayout {
@Bind(R.id.leftTextView)
TextView leftTextView;
@Bind(R.id.rightTextView)
TextView rightTextView;
public NaviBar(Context context) {
super(context);
}
public NaviBar(Context context, AttributeSet attrs) {
super(context, attrs);
}
public NaviBar(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void init(Context context, AttributeSet attrs) {
super.init(context, attrs);
if (attrs != null) {
TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.NaviBar);
leftTextView.setText(a.getString(R.styleable.NaviBar_nb_left_text));
rightTextView.setText(a.getString(R.styleable.NaviBar_nb_right_text));
a.recycle();
}
}
@OnClick(R.id.backButton)
void back() {
if (getContext() instanceof Activity) {
((Activity) getContext()).finish();
}
}
public void setLeftText(String text) {
leftTextView.setText(text);
}
public void setRightText(String text) {
rightTextView.setText(text);
}
}
| apache-2.0 |
ar-ubin/BeNotified | app/src/main/java/ar_ubin/benotified/base/BaseActivity.java | 1440 | package ar_ubin.benotified.base;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import javax.inject.Inject;
import ar_ubin.benotified.ActivityModule;
import ar_ubin.benotified.ApplicationComponent;
import ar_ubin.benotified.BeNotifiedApplication;
import ar_ubin.benotified.navigation.Navigator;
import ar_ubin.benotified.utils.GsonSharedPrefs;
import static com.google.common.base.Preconditions.checkNotNull;
public abstract class BaseActivity extends AppCompatActivity
{
@Inject
public Navigator mNavigator;
@Inject
public GsonSharedPrefs mGsonSharedPrefs;
@Override
protected void onCreate( Bundle savedInstanceState ) {
super.onCreate( savedInstanceState );
}
protected void addFragment( int containerViewId, Fragment fragment ) {
checkNotNull( containerViewId );
checkNotNull( fragment );
FragmentTransaction fragmentTransaction = this.getSupportFragmentManager().beginTransaction();
fragmentTransaction.add( containerViewId, fragment );
fragmentTransaction.commit();
}
public ApplicationComponent getApplicationComponent() {
return ( (BeNotifiedApplication) getApplication() ).getApplicationComponent();
}
public ActivityModule getActivityModule() {
return new ActivityModule( this );
}
}
| apache-2.0 |
zelig81/hyperactive-class | A226/src/com/example/a226/MainActivity.java | 776 | package com.example.a226;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
EditText et;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b = (Button) findViewById(R.id.button1);
et = (EditText) findViewById(R.id.EditText1);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String s = et.getText().toString();
Intent intent = new Intent("com.example.translate");
intent.putExtra("word", s);
startActivity(intent);
}
});
}
}
| apache-2.0 |
umeshawasthi/blooddonor | src/main/java/com/raisonne/quartz/scheduler/job/service/impl/JobUtil.java | 935 | /*
* Copyright 2010-2011 Raisonne Techonologies.
*
* 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.raisonne.quartz.scheduler.job.service.impl;
/**
* <p>A helper class which is responsible for fetching list of all jobs
* under a certain group as well individual jobs matching search criteria.</p>
* <p>
* Triggers associated with the
* </p>
* @author Umesh Awasthi
*
*
*/
public class JobUtil {
}
| apache-2.0 |
innocentliny/SFTP_demo | v4/My4FileSystem.java | 1470 | package ftp.v4;
import java.io.IOException;
import java.nio.file.attribute.UserPrincipalLookupService;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import org.apache.sshd.common.file.util.BaseFileSystem;
import org.apache.sshd.common.file.util.ImmutableList;
public class My4FileSystem extends BaseFileSystem<My4Path>
{
public My4FileSystem(My4FileSystemProvider fileSystemProvider)
{
super(fileSystemProvider);
System.out.println("My4FileSystem constructor()");
}
@Override
protected My4Path create(String root, ImmutableList<String> names)
{
System.out.println("My4FileSystem create(); root=" + root + " ; names=" + names);
return new My4Path(this, root, names);
}
@Override
public void close() throws IOException
{
System.out.println("My4FileSystem close()");
}
@Override
public boolean isOpen()
{
System.out.println("My4FileSystem isOpen()");
return true;
}
@Override
public Set<String> supportedFileAttributeViews()
{
System.out.println("My4FileSystem supportedFileAttributeViews()");
return Collections.unmodifiableSet(new HashSet<String>(Arrays.asList("posix")));
}
@Override
public UserPrincipalLookupService getUserPrincipalLookupService()
{
System.out.println("My4FileSystem getUserPrincipalLookupService()");
throw new UnsupportedOperationException("My4FileSystem getUserPrincipalLookupService()");
}
}
| apache-2.0 |
bendisposto/JVersionNumberer | JVersionNumberer/src/main/java/de/hhu/jversionnumberer/annotations/ImplementableByClient.java | 1173 | /*
* Copyright 2011 Gian Perrone
*
* 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.hhu.jversionnumberer.annotations;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* This annotation marks interfaces which are intended to be subclassed by
* clients of the API and as such break binary compatibility when e.g. methods
* are added.
*
* @author Gian Perrone
*/
@Documented
@Retention(RetentionPolicy.CLASS)
@Target(ElementType.TYPE)
public @interface ImplementableByClient {
}
| apache-2.0 |
assemblade/CAT | cat-server/src/test/java/com/assemblade/server/security/UserManagerTest.java | 1709 | /*
* Copyright 2012 Mike Adamson
*
* 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.assemblade.server.security;
import com.assemblade.opendj.OpenDJTestRunner;
import com.assemblade.opendj.SearchResult;
import com.assemblade.server.AbstractUserManagementTest;
import com.assemblade.server.model.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
@RunWith(OpenDJTestRunner.class)
public class UserManagerTest extends AbstractUserManagementTest {
@Test
public void canAddUserPlainPasswordAndGetSessionForUser() throws Exception {
userLogin("admin");
addUser("test", "test user", "test@example.com", "password");
userLogin("test");
assertNotNull(userManager.getUserSession());
}
@Test
public void canGetListOfLocalUsers() throws Exception {
userLogin("admin");
addUser("test1", "test1 user", "test1@example.com", "password");
addUser("test2", "test2 user", "test2@example.com", "password");
List<User> users = userManager.getUserSession().search(new User(), User.ROOT, false);
assertEquals(3, users.size());
}
}
| apache-2.0 |
zzy6395/drill | exec/java-exec/src/test/java/org/apache/drill/exec/vector/complex/writer/TestJsonReader.java | 12785 | /**
* 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.drill.exec.vector.complex.writer;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.zip.GZIPOutputStream;
import org.apache.drill.BaseTestQuery;
import org.apache.drill.common.expression.SchemaPath;
import org.apache.drill.common.util.FileUtils;
import org.apache.drill.exec.exception.SchemaChangeException;
import org.apache.drill.exec.proto.UserBitShared;
import org.apache.drill.exec.record.RecordBatchLoader;
import org.apache.drill.exec.record.VectorWrapper;
import org.apache.drill.exec.rpc.user.QueryDataBatch;
import org.apache.drill.exec.vector.IntVector;
import org.apache.drill.exec.vector.RepeatedBigIntVector;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import com.google.common.base.Charsets;
import com.google.common.io.Files;
import org.junit.rules.TemporaryFolder;
public class TestJsonReader extends BaseTestQuery {
// private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(TestJsonReader.class);
private static final boolean VERBOSE_DEBUG = false;
@Rule
public TemporaryFolder folder = new TemporaryFolder();
@Test
public void schemaChange() throws Exception {
test("select b from dfs.`${WORKING_PATH}/src/test/resources/vector/complex/writer/schemaChange/`");
}
@Test
@Ignore("DRILL-1824")
public void schemaChangeValidate() throws Exception {
testBuilder() //
.sqlQuery("select b from dfs.`${WORKING_PATH}/src/test/resources/vector/complex/writer/schemaChange/`") //
.unOrdered() //
.jsonBaselineFile("/vector/complex/writer/expected.json") //
.build()
.run();
}
public void runTestsOnFile(String filename, UserBitShared.QueryType queryType, String[] queries, long[] rowCounts) throws Exception {
if (VERBOSE_DEBUG) {
System.out.println("===================");
System.out.println("source data in json");
System.out.println("===================");
System.out.println(Files.toString(FileUtils.getResourceAsFile(filename), Charsets.UTF_8));
}
int i = 0;
for (String query : queries) {
if (VERBOSE_DEBUG) {
System.out.println("=====");
System.out.println("query");
System.out.println("=====");
System.out.println(query);
System.out.println("======");
System.out.println("result");
System.out.println("======");
}
int rowCount = testRunAndPrint(queryType, query);
assertEquals(rowCounts[i], rowCount);
System.out.println();
i++;
}
}
@Test
public void testReadCompressed() throws Exception {
String filepath = "compressed_json.json";
File f = folder.newFile(filepath);
PrintWriter out = new PrintWriter(f);
out.println("{\"a\" :5}");
out.close();
gzipIt(f);
testBuilder()
.sqlQuery("select * from dfs.`" + f.getPath() + ".gz" + "`")
.unOrdered()
.baselineColumns("a")
.baselineValues(5l)
.build().run();
// test reading the uncompressed version as well
testBuilder()
.sqlQuery("select * from dfs.`" + f.getPath() + "`")
.unOrdered()
.baselineColumns("a")
.baselineValues(5l)
.build().run();
}
public void gzipIt(File sourceFile) throws IOException {
// modified from: http://www.mkyong.com/java/how-to-compress-a-file-in-gzip-format/
byte[] buffer = new byte[1024];
GZIPOutputStream gzos =
new GZIPOutputStream(new FileOutputStream(sourceFile.getPath() + ".gz"));
FileInputStream in =
new FileInputStream(sourceFile);
int len;
while ((len = in.read(buffer)) > 0) {
gzos.write(buffer, 0, len);
}
in.close();
gzos.finish();
gzos.close();
}
@Test
public void testDrill_1419() throws Exception {
String[] queries = {"select t.trans_id, t.trans_info.prod_id[0],t.trans_info.prod_id[1] from cp.`/store/json/clicks.json` t limit 5"};
long[] rowCounts = {5};
String filename = "/store/json/clicks.json";
runTestsOnFile(filename, UserBitShared.QueryType.SQL, queries, rowCounts);
}
@Test
public void testRepeatedCount() throws Exception {
test("select repeated_count(str_list) from cp.`/store/json/json_basic_repeated_varchar.json`");
test("select repeated_count(INT_col) from cp.`/parquet/alltypes_repeated.json`");
test("select repeated_count(FLOAT4_col) from cp.`/parquet/alltypes_repeated.json`");
test("select repeated_count(VARCHAR_col) from cp.`/parquet/alltypes_repeated.json`");
test("select repeated_count(BIT_col) from cp.`/parquet/alltypes_repeated.json`");
}
@Test
public void testRepeatedContains() throws Exception {
test("select repeated_contains(str_list, 'asdf') from cp.`/store/json/json_basic_repeated_varchar.json`");
test("select repeated_contains(INT_col, -2147483648) from cp.`/parquet/alltypes_repeated.json`");
test("select repeated_contains(FLOAT4_col, -1000000000000.0) from cp.`/parquet/alltypes_repeated.json`");
test("select repeated_contains(VARCHAR_col, 'qwerty' ) from cp.`/parquet/alltypes_repeated.json`");
test("select repeated_contains(BIT_col, true) from cp.`/parquet/alltypes_repeated.json`");
test("select repeated_contains(BIT_col, false) from cp.`/parquet/alltypes_repeated.json`");
}
@Test
public void testSingleColumnRead_vector_fill_bug() throws Exception {
String[] queries = {"select * from cp.`/store/json/single_column_long_file.json`"};
long[] rowCounts = {13512};
String filename = "/store/json/single_column_long_file.json";
runTestsOnFile(filename, UserBitShared.QueryType.SQL, queries, rowCounts);
}
@Test
public void testNonExistentColumnReadAlone() throws Exception {
String[] queries = {"select non_existent_column from cp.`/store/json/single_column_long_file.json`"};
long[] rowCounts = {13512};
String filename = "/store/json/single_column_long_file.json";
runTestsOnFile(filename, UserBitShared.QueryType.SQL, queries, rowCounts);
}
@Test
public void testAllTextMode() throws Exception {
test("alter system set `store.json.all_text_mode` = true");
String[] queries = {"select * from cp.`/store/json/schema_change_int_to_string.json`"};
long[] rowCounts = {3};
String filename = "/store/json/schema_change_int_to_string.json";
runTestsOnFile(filename, UserBitShared.QueryType.SQL, queries, rowCounts);
test("alter system set `store.json.all_text_mode` = false");
}
@Test
public void readComplexWithStar() throws Exception {
List<QueryDataBatch> results = testSqlWithResults("select * from cp.`/store/json/test_complex_read_with_star.json`");
assertEquals(1, results.size());
RecordBatchLoader batchLoader = new RecordBatchLoader(getAllocator());
QueryDataBatch batch = results.get(0);
assertTrue(batchLoader.load(batch.getHeader().getDef(), batch.getData()));
assertEquals(3, batchLoader.getSchema().getFieldCount());
testExistentColumns(batchLoader);
batch.release();
batchLoader.clear();
}
@Test
public void testNullWhereListExpected() throws Exception {
test("alter system set `store.json.all_text_mode` = true");
String[] queries = {"select * from cp.`/store/json/null_where_list_expected.json`"};
long[] rowCounts = {3};
String filename = "/store/json/null_where_list_expected.json";
runTestsOnFile(filename, UserBitShared.QueryType.SQL, queries, rowCounts);
test("alter system set `store.json.all_text_mode` = false");
}
@Test
public void testNullWhereMapExpected() throws Exception {
test("alter system set `store.json.all_text_mode` = true");
String[] queries = {"select * from cp.`/store/json/null_where_map_expected.json`"};
long[] rowCounts = {3};
String filename = "/store/json/null_where_map_expected.json";
runTestsOnFile(filename, UserBitShared.QueryType.SQL, queries, rowCounts);
test("alter system set `store.json.all_text_mode` = false");
}
@Test
public void ensureProjectionPushdown() throws Exception {
// Tests to make sure that we are correctly eliminating schema changing columns. If completes, means that the projection pushdown was successful.
test("alter system set `store.json.all_text_mode` = false; "
+ "select t.field_1, t.field_3.inner_1, t.field_3.inner_2, t.field_4.inner_1 "
+ "from cp.`store/json/schema_change_int_to_string.json` t");
}
// The project pushdown rule is correctly adding the projected columns to the scan, however it is not removing
// the redundant project operator after the scan, this tests runs a physical plan generated from one of the tests to
// ensure that the project is filtering out the correct data in the scan alone
@Test
public void testProjectPushdown() throws Exception {
String[] queries = {Files.toString(FileUtils.getResourceAsFile("/store/json/project_pushdown_json_physical_plan.json"), Charsets.UTF_8)};
long[] rowCounts = {3};
String filename = "/store/json/schema_change_int_to_string.json";
test("alter system set `store.json.all_text_mode` = false");
runTestsOnFile(filename, UserBitShared.QueryType.PHYSICAL, queries, rowCounts);
List<QueryDataBatch> results = testPhysicalWithResults(queries[0]);
assertEquals(1, results.size());
// "`field_1`", "`field_3`.`inner_1`", "`field_3`.`inner_2`", "`field_4`.`inner_1`"
RecordBatchLoader batchLoader = new RecordBatchLoader(getAllocator());
QueryDataBatch batch = results.get(0);
assertTrue(batchLoader.load(batch.getHeader().getDef(), batch.getData()));
// this used to be five. It is now three. This is because the plan doesn't have a project.
// Scanners are not responsible for projecting non-existent columns (as long as they project one column)
assertEquals(3, batchLoader.getSchema().getFieldCount());
testExistentColumns(batchLoader);
batch.release();
batchLoader.clear();
}
private void testExistentColumns(RecordBatchLoader batchLoader) throws SchemaChangeException {
VectorWrapper<?> vw = batchLoader.getValueAccessorById(
RepeatedBigIntVector.class, //
batchLoader.getValueVectorId(SchemaPath.getCompoundPath("field_1")).getFieldIds() //
);
assertEquals("[1]", vw.getValueVector().getAccessor().getObject(0).toString());
assertEquals("[5]", vw.getValueVector().getAccessor().getObject(1).toString());
assertEquals("[5,10,15]", vw.getValueVector().getAccessor().getObject(2).toString());
vw = batchLoader.getValueAccessorById(
IntVector.class, //
batchLoader.getValueVectorId(SchemaPath.getCompoundPath("field_3", "inner_1")).getFieldIds() //
);
assertNull(vw.getValueVector().getAccessor().getObject(0));
assertEquals(2l, vw.getValueVector().getAccessor().getObject(1));
assertEquals(5l, vw.getValueVector().getAccessor().getObject(2));
vw = batchLoader.getValueAccessorById(
IntVector.class, //
batchLoader.getValueVectorId(SchemaPath.getCompoundPath("field_3", "inner_2")).getFieldIds() //
);
assertNull(vw.getValueVector().getAccessor().getObject(0));
assertNull(vw.getValueVector().getAccessor().getObject(1));
assertEquals(3l, vw.getValueVector().getAccessor().getObject(2));
vw = batchLoader.getValueAccessorById(
RepeatedBigIntVector.class, //
batchLoader.getValueVectorId(SchemaPath.getCompoundPath("field_4", "inner_1")).getFieldIds() //
);
assertEquals("[]", vw.getValueVector().getAccessor().getObject(0).toString());
assertEquals("[1,2,3]", vw.getValueVector().getAccessor().getObject(1).toString());
assertEquals("[4,5,6]", vw.getValueVector().getAccessor().getObject(2).toString());
}
}
| apache-2.0 |
CloudComLab/Voting-CAP | src/service/handler/twostep/CSNHandler.java | 3838 | package service.handler.twostep;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.Socket;
import java.security.KeyPair;
import java.security.PublicKey;
import java.security.SignatureException;
import java.util.concurrent.locks.ReentrantLock;
import java.util.logging.Level;
import java.util.logging.Logger;
import message.Operation;
import message.twostep.csn.*;
import service.Config;
import service.Key;
import service.KeyManager;
import service.handler.ConnectionHandler;
import utility.Utils;
/**
*
* @author Scott
*/
public class CSNHandler extends ConnectionHandler {
public static final File ATTESTATION;
private static final ReentrantLock LOCK;
private static int CSN;
static {
ATTESTATION = new File(Config.ATTESTATION_DIR_PATH + "/service-provider/csn");
LOCK = new ReentrantLock();
CSN = 0;
}
public CSNHandler(Socket socket, KeyPair keyPair) {
super(socket, keyPair);
}
@Override
protected void handle(DataOutputStream out, DataInputStream in)
throws SignatureException, IllegalAccessException {
PublicKey clientPubKey = KeyManager.getInstance().getPublicKey(Key.CLIENT);
try {
Request req = Request.parse(Utils.receive(in));
LOCK.lock();
if (!req.validate(clientPubKey)) {
throw new SignatureException("REQ validation failure");
}
String result;
Operation op = req.getOperation();
File file = new File(Config.DATA_DIR_PATH + '/' + op.getPath());
boolean sendFileAfterAck = false;
if (req.getConsecutiveSequenceNumber() == CSN + 1) {
CSN += 1;
switch (op.getType()) {
case UPLOAD:
file = new File(Config.DOWNLOADS_DIR_PATH + '/' + op.getPath());
Utils.receive(in, file);
String digest = Utils.digest(file);
if (op.getMessage().compareTo(digest) == 0) {
result = "ok";
} else {
result = "upload fail";
}
Utils.writeDigest(file.getPath(), digest);
break;
case AUDIT:
file = new File(op.getPath());
result = Utils.readDigest(file.getPath());
sendFileAfterAck = true;
break;
case DOWNLOAD:
result = Utils.readDigest(file.getPath());
sendFileAfterAck = true;
break;
default:
result = "operation type mismatch";
}
} else {
result = "CSN mismatch";
}
Acknowledgement ack = new Acknowledgement(result, req);
ack.sign(keyPair);
Utils.send(out, ack.toString());
if (sendFileAfterAck) {
Utils.send(out, file);
}
Utils.appendAndDigest(ATTESTATION, ack.toString() + '\n');
} finally {
if (LOCK != null) {
LOCK.unlock();
}
}
}
}
| apache-2.0 |
watson-developer-cloud/java-sdk | visual-recognition/src/main/java/com/ibm/watson/visual_recognition/v4/model/AddImagesOptions.java | 6096 | /*
* (C) Copyright IBM Corp. 2019, 2020.
*
* 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.ibm.watson.visual_recognition.v4.model;
import com.ibm.cloud.sdk.core.service.model.FileWithMetadata;
import com.ibm.cloud.sdk.core.service.model.GenericModel;
import java.util.ArrayList;
import java.util.List;
/** The addImages options. */
public class AddImagesOptions extends GenericModel {
protected String collectionId;
protected List<FileWithMetadata> imagesFile;
protected List<String> imageUrl;
protected String trainingData;
/** Builder. */
public static class Builder {
private String collectionId;
private List<FileWithMetadata> imagesFile;
private List<String> imageUrl;
private String trainingData;
private Builder(AddImagesOptions addImagesOptions) {
this.collectionId = addImagesOptions.collectionId;
this.imagesFile = addImagesOptions.imagesFile;
this.imageUrl = addImagesOptions.imageUrl;
this.trainingData = addImagesOptions.trainingData;
}
/** Instantiates a new builder. */
public Builder() {}
/**
* Instantiates a new builder with required properties.
*
* @param collectionId the collectionId
*/
public Builder(String collectionId) {
this.collectionId = collectionId;
}
/**
* Builds a AddImagesOptions.
*
* @return the new AddImagesOptions instance
*/
public AddImagesOptions build() {
return new AddImagesOptions(this);
}
/**
* Adds an imagesFile to imagesFile.
*
* @param imagesFile the new imagesFile
* @return the AddImagesOptions builder
*/
public Builder addImagesFile(FileWithMetadata imagesFile) {
com.ibm.cloud.sdk.core.util.Validator.notNull(imagesFile, "imagesFile cannot be null");
if (this.imagesFile == null) {
this.imagesFile = new ArrayList<FileWithMetadata>();
}
this.imagesFile.add(imagesFile);
return this;
}
/**
* Adds an imageUrl to imageUrl.
*
* @param imageUrl the new imageUrl
* @return the AddImagesOptions builder
*/
public Builder addImageUrl(String imageUrl) {
com.ibm.cloud.sdk.core.util.Validator.notNull(imageUrl, "imageUrl cannot be null");
if (this.imageUrl == null) {
this.imageUrl = new ArrayList<String>();
}
this.imageUrl.add(imageUrl);
return this;
}
/**
* Set the collectionId.
*
* @param collectionId the collectionId
* @return the AddImagesOptions builder
*/
public Builder collectionId(String collectionId) {
this.collectionId = collectionId;
return this;
}
/**
* Set the imagesFile. Existing imagesFile will be replaced.
*
* @param imagesFile the imagesFile
* @return the AddImagesOptions builder
*/
public Builder imagesFile(List<FileWithMetadata> imagesFile) {
this.imagesFile = imagesFile;
return this;
}
/**
* Set the imageUrl. Existing imageUrl will be replaced.
*
* @param imageUrl the imageUrl
* @return the AddImagesOptions builder
*/
public Builder imageUrl(List<String> imageUrl) {
this.imageUrl = imageUrl;
return this;
}
/**
* Set the trainingData.
*
* @param trainingData the trainingData
* @return the AddImagesOptions builder
*/
public Builder trainingData(String trainingData) {
this.trainingData = trainingData;
return this;
}
}
protected AddImagesOptions(Builder builder) {
com.ibm.cloud.sdk.core.util.Validator.notEmpty(
builder.collectionId, "collectionId cannot be empty");
collectionId = builder.collectionId;
imagesFile = builder.imagesFile;
imageUrl = builder.imageUrl;
trainingData = builder.trainingData;
}
/**
* New builder.
*
* @return a AddImagesOptions builder
*/
public Builder newBuilder() {
return new Builder(this);
}
/**
* Gets the collectionId.
*
* <p>The identifier of the collection.
*
* @return the collectionId
*/
public String collectionId() {
return collectionId;
}
/**
* Gets the imagesFile.
*
* <p>An array of image files (.jpg or .png) or .zip files with images. - Include a maximum of 20
* images in a request. - Limit the .zip file to 100 MB. - Limit each image file to 10 MB.
*
* <p>You can also include an image with the **image_url** parameter.
*
* @return the imagesFile
*/
public List<FileWithMetadata> imagesFile() {
return imagesFile;
}
/**
* Gets the imageUrl.
*
* <p>The array of URLs of image files (.jpg or .png). - Include a maximum of 20 images in a
* request. - Limit each image file to 10 MB. - Minimum width and height is 30 pixels, but the
* service tends to perform better with images that are at least 300 x 300 pixels. Maximum is 5400
* pixels for either height or width.
*
* <p>You can also include images with the **images_file** parameter.
*
* @return the imageUrl
*/
public List<String> imageUrl() {
return imageUrl;
}
/**
* Gets the trainingData.
*
* <p>Training data for a single image. Include training data only if you add one image with the
* request.
*
* <p>The `object` property can contain alphanumeric, underscore, hyphen, space, and dot
* characters. It cannot begin with the reserved prefix `sys-` and must be no longer than 32
* characters.
*
* @return the trainingData
*/
public String trainingData() {
return trainingData;
}
}
| apache-2.0 |
reynoldsm88/drools | drools-model/drools-model-compiler/src/test/java/org/drools/modelcompiler/domain/TargetPolicy.java | 1281 | /*
* Copyright 2005 JBoss 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 org.drools.modelcompiler.domain;
public class TargetPolicy {
private String customerCode;
private String productCode;
private int coefficient;
public String getCustomerCode() {
return customerCode;
}
public void setCustomerCode(String customerCode) {
this.customerCode = customerCode;
}
public String getProductCode() {
return productCode;
}
public void setProductCode(String productCode) {
this.productCode = productCode;
}
public int getCoefficient() {
return coefficient;
}
public void setCoefficient(int coefficient) {
this.coefficient = coefficient;
}
}
| apache-2.0 |
TonyYang9527/Magic-Web | src/main/java/com/cell/user/web/shrio/filter/authc/CustomFormAuthenticationFilter.java | 1780 | package com.cell.user.web.shrio.filter.authc;
import javax.servlet.ServletRequest;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import com.cell.user.vo.single.SysUserVo;
import com.cell.user.web.service.UserService;
/**
* 基于几点修改: 1、onLoginFailure 时 把异常添加到request attribute中 而不是异常类名 2、登录成功时:成功页面重定向:
* 2.1、如果前一个页面是登录页面,-->2.3 2.2、如果有SavedRequest 则返回到SavedRequest
* 2.3、否则根据当前登录的用户决定返回到管理员首页/前台首页
* <p/>
*/
public class CustomFormAuthenticationFilter extends FormAuthenticationFilter {
@Autowired
UserService userService;
/**
* 默认的成功地址
*/
@Value("${shiro.default.success.url}")
private String defaultSuccessUrl;
/**
* 管理员默认的成功地址
*/
@Value("${shiro.admin.default.success.url}")
private String adminDefaultSuccessUrl;
@Override
protected void setFailureAttribute(ServletRequest request,
AuthenticationException ae) {
request.setAttribute(getFailureKeyAttribute(), ae);
}
/**
* 根据用户选择成功地址
*
* @return
*/
@Override
public String getSuccessUrl() {
String username = (String) SecurityUtils.getSubject().getPrincipal();
SysUserVo user = userService.findByUsername(username);
if (user != null && Boolean.TRUE.equals(user.getAdmin())) {
return this.adminDefaultSuccessUrl;
}
return this.defaultSuccessUrl;
}
}
| apache-2.0 |
mttkay/RxJava | rxjava-core/src/test/java/rx/internal/operators/OperatorOnBackpressureBufferTest.java | 3022 | /**
* Copyright 2014 Netflix, 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 rx.internal.operators;
import static org.junit.Assert.assertEquals;
import java.util.concurrent.CountDownLatch;
import org.junit.Test;
import rx.Observable;
import rx.Observable.OnSubscribe;
import rx.Observer;
import rx.Subscriber;
import rx.observers.TestSubscriber;
import rx.schedulers.Schedulers;
public class OperatorOnBackpressureBufferTest {
@Test
public void testNoBackpressureSupport() {
TestSubscriber<Long> ts = new TestSubscriber<Long>();
// this will be ignored
ts.request(100);
// we take 500 so it unsubscribes
infinite.take(500).subscribe(ts);
// it completely ignores the `request(100)` and we get 500
assertEquals(500, ts.getOnNextEvents().size());
ts.assertNoErrors();
}
@Test(timeout = 500)
public void testFixBackpressureWithBuffer() throws InterruptedException {
final CountDownLatch l1 = new CountDownLatch(100);
final CountDownLatch l2 = new CountDownLatch(150);
TestSubscriber<Long> ts = new TestSubscriber<Long>(new Observer<Long>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(Long t) {
l1.countDown();
l2.countDown();
}
});
// this will be ignored
ts.request(100);
// we take 500 so it unsubscribes
infinite.subscribeOn(Schedulers.computation()).onBackpressureBuffer().take(500).subscribe(ts);
// it completely ignores the `request(100)` and we get 500
l1.await();
assertEquals(100, ts.getOnNextEvents().size());
ts.request(50);
l2.await();
assertEquals(150, ts.getOnNextEvents().size());
ts.request(350);
ts.awaitTerminalEvent();
assertEquals(500, ts.getOnNextEvents().size());
ts.assertNoErrors();
assertEquals(0, ts.getOnNextEvents().get(0).intValue());
assertEquals(499, ts.getOnNextEvents().get(499).intValue());
}
static final Observable<Long> infinite = Observable.create(new OnSubscribe<Long>() {
@Override
public void call(Subscriber<? super Long> s) {
long i = 0;
while (!s.isUnsubscribed()) {
s.onNext(i++);
}
}
});
}
| apache-2.0 |
PrudhviRaju123/Tour | app/src/main/java/com/ua/hower/house/NavigationDrawerCallbacks.java | 178 | package com.ua.hower.house;
/**
* Created by poliveira on 27/10/2014.
*/
public interface NavigationDrawerCallbacks {
void onNavigationDrawerItemSelected(int position);
}
| apache-2.0 |
j-coll/opencga | opencga-core/src/main/java/org/opencb/opencga/core/models/study/VariableSetCreateParams.java | 3818 | /*
* Copyright 2015-2020 OpenCB
*
* 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.opencb.opencga.core.models.study;
import java.util.ArrayList;
import java.util.List;
public class VariableSetCreateParams {
private String id;
private String name;
private Boolean unique;
private Boolean confidential;
private String description;
private List<VariableSet.AnnotableDataModels> entities;
private List<Variable> variables;
public VariableSetCreateParams() {
}
public VariableSetCreateParams(String id, String name, Boolean unique, Boolean confidential, String description,
List<VariableSet.AnnotableDataModels> entities, List<Variable> variables) {
this.id = id;
this.name = name;
this.unique = unique;
this.confidential = confidential;
this.description = description;
this.entities = entities;
this.variables = variables;
}
public static VariableSetCreateParams of(VariableSet variableSet) {
return new VariableSetCreateParams(variableSet.getId(), variableSet.getName(), variableSet.isUnique(), variableSet.isConfidential(),
variableSet.getDescription(), variableSet.getEntities(), new ArrayList<>(variableSet.getVariables()));
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("VariableSetCreateParams{");
sb.append("id='").append(id).append('\'');
sb.append(", name='").append(name).append('\'');
sb.append(", unique=").append(unique);
sb.append(", confidential=").append(confidential);
sb.append(", description='").append(description).append('\'');
sb.append(", entities=").append(entities);
sb.append(", variables=").append(variables);
sb.append('}');
return sb.toString();
}
public Boolean getUnique() {
return unique;
}
public VariableSetCreateParams setUnique(Boolean unique) {
this.unique = unique;
return this;
}
public Boolean getConfidential() {
return confidential;
}
public VariableSetCreateParams setConfidential(Boolean confidential) {
this.confidential = confidential;
return this;
}
public String getId() {
return id;
}
public VariableSetCreateParams setId(String id) {
this.id = id;
return this;
}
public String getName() {
return name;
}
public VariableSetCreateParams setName(String name) {
this.name = name;
return this;
}
public String getDescription() {
return description;
}
public VariableSetCreateParams setDescription(String description) {
this.description = description;
return this;
}
public List<VariableSet.AnnotableDataModels> getEntities() {
return entities;
}
public VariableSetCreateParams setEntities(List<VariableSet.AnnotableDataModels> entities) {
this.entities = entities;
return this;
}
public List<Variable> getVariables() {
return variables;
}
public VariableSetCreateParams setVariables(List<Variable> variables) {
this.variables = variables;
return this;
}
}
| apache-2.0 |
lorenpaz/CardEx | src/main/java/es/ucm/fdi/iw/controller/HomeController.java | 4005 | package es.ucm.fdi.iw.controller;
import java.security.Principal;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestWrapper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import com.google.gson.Gson;
import es.ucm.fdi.iw.model.Intercambio;
import es.ucm.fdi.iw.model.Usuario;
import es.ucm.fdi.iw.model.UsuarioJSON;
@Controller
@RequestMapping("home")
public class HomeController {
private static Logger log = Logger.getLogger(HomeController.class);
@Autowired
private EntityManager entityManager;
// Incluimos ${prefix} en todas las páginas
@ModelAttribute
public void addAttributes(Model m) {
m.addAttribute("prefix", "../static/");
m.addAttribute("prefijo", "../");
}
@GetMapping({ "", "/" })
public String root(Model model, Principal principal, HttpSession session,
SecurityContextHolderAwareRequestWrapper request) {
añadirCSSyJSAlModelo(model);
Usuario usuarioActual = (Usuario) entityManager.createNamedQuery("userByUserField")
.setParameter("userParam", principal.getName()).getSingleResult();
if (principal != null && session.getAttribute("user") == null) {
try {
if (!usuarioActual.isActivo()){
throw new Exception();
}
session.setAttribute("user", usuarioActual);
} catch (Exception e) {
log.info("No such user: " + principal.getName());
return "redirect:index";
}
}
@SuppressWarnings("unchecked")
ArrayList<Usuario> usuarios = (ArrayList<Usuario>) entityManager.createNamedQuery("getActiveUsers")
.setParameter("roleParam", "USER").setParameter("activeParam", true)
.setParameter("actual", principal.getName()).getResultList();
Gson gson = new Gson();
String json = "{";
json +="\"usuarios\":[";
for(Usuario u : usuarios)
{
UsuarioJSON usuarioJSON = new UsuarioJSON(u);
json += gson.toJson(usuarioJSON);
if(usuarios.indexOf(u) != usuarios.size()- 1)
{
json+= ',';
}
}
json += "]}";
model.addAttribute("usuariosJSON",json);
model.addAttribute("usuarios", usuarios);
if (request.isUserInRole("ROLE_ADMIN"))
return "redirect:admin";
//Enviamos al modelo el usuarioActual (en JSON y normal)
añadirUsuarioActualJSON(model, usuarioActual);
model.addAttribute("usuarioActual",usuarioActual);
mensajesPendientes(model,usuarioActual);
return "home";
}
private void añadirUsuarioActualJSON(Model model, Usuario usuarioActual)
{
UsuarioJSON usuarioActualJSON = new UsuarioJSON(usuarioActual);
Gson gson = new Gson();
String jsonAux = gson.toJson(usuarioActualJSON);
model.addAttribute("usuarioActualJSON", jsonAux);
}
@SuppressWarnings("unchecked")
private void mensajesPendientes(Model model, Usuario usuarioActual)
{
List<Intercambio> intercambios = entityManager.createNamedQuery("allIntercambiosUsuarioPendiente")
.setParameter("estado", "Pendiente")
.setParameter("user", usuarioActual)
.getResultList();
model.addAttribute("numeroDeMensajes",intercambios.size());
}
public static void añadirCSSyJSAlModelo(Model model) {
List<String> listaCSS = new ArrayList<String>();
listaCSS.add("styleHome.css");
listaCSS.add("popup.css");
listaCSS.add("star-rating.min.css");
List<String> listaJS = new ArrayList<String>();
listaJS.add("jquery-3.1.1.min.js");
listaJS.add("jquery-ui-1.12.1/jquery-ui.min.js");
listaJS.add("bootstrap.min.js");
listaJS.add("star-rating.min.js");
listaJS.add("home.js");
model.addAttribute("pageExtraCSS", listaCSS);
model.addAttribute("pageExtraScripts", listaJS);
}
}
| apache-2.0 |
aseldawy/spatialhadoop | src/mapred/org/apache/hadoop/mapred/spatial/RTreeGridRecordWriter.java | 955 | package org.apache.hadoop.mapred.spatial;
import java.io.IOException;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.RecordWriter;
import org.apache.hadoop.mapred.Reporter;
import org.apache.hadoop.spatial.CellInfo;
import org.apache.hadoop.spatial.Shape;
public class RTreeGridRecordWriter
extends org.apache.hadoop.spatial.RTreeGridRecordWriter<Shape>
implements RecordWriter<IntWritable, Text> {
public RTreeGridRecordWriter(FileSystem fileSystem, Path outFile, CellInfo[] cells, boolean overwrite) throws IOException {
super(fileSystem, outFile, cells, overwrite);
}
@Override
public void write(IntWritable key, Text value) throws IOException {
super.write(key.get(), value);
}
@Override
public void close(Reporter reporter) throws IOException {
super.close(reporter);
}
}
| apache-2.0 |
TremoloSecurity/OpenUnison | unison/unison-sdk/src/main/java/com/tremolosecurity/proxy/ExternalSessionExpires.java | 1124 | /*******************************************************************************
* Copyright 2019 Tremolo Security, 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.tremolosecurity.proxy;
/**
*
* @author mlb
* Provides an interface to extend a session termination from an external source instead of the built in session variables
*/
public interface ExternalSessionExpires {
/**
*
* @return The expiration date/time in standard java form (milliseconds since epoch)
*/
public long getExpires();
}
| apache-2.0 |
lpxz/grail-lucene358684 | src/java/org/apache/lucene/index/SegmentReader.java | 18645 | package org.apache.lucene.index;
/**
* Copyright 2004 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.io.IOException;
import java.util.*;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.store.IndexInput;
import org.apache.lucene.store.IndexOutput;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.BitVector;
import org.apache.lucene.search.DefaultSimilarity;
/**
* @version $Id: SegmentReader.java 329523 2005-10-30 05:37:11Z yonik $
*/
class SegmentReader extends IndexReader {
private String segment;
FieldInfos fieldInfos;
private FieldsReader fieldsReader;
TermInfosReader tis;
TermVectorsReader termVectorsReaderOrig = null;
ThreadLocal termVectorsLocal = new ThreadLocal();
BitVector deletedDocs = null;
private boolean deletedDocsDirty = false;
private boolean normsDirty = false;
private boolean undeleteAll = false;
IndexInput freqStream;
IndexInput proxStream;
// Compound File Reader when based on a compound file segment
CompoundFileReader cfsReader = null;
private class Norm {
public Norm(IndexInput in, int number)
{
this.in = in;
this.number = number;
}
private IndexInput in;
private byte[] bytes;
private boolean dirty;
private int number;
private void reWrite() throws IOException {
// NOTE: norms are re-written in regular directory, not cfs
IndexOutput out = directory().createOutput(segment + ".tmp");
try {
out.writeBytes(bytes, maxDoc());
} finally {
out.close();
}
String fileName;
if(cfsReader == null)
fileName = segment + ".f" + number;
else{
// use a different file name if we have compound format
fileName = segment + ".s" + number;
}
directory().renameFile(segment + ".tmp", fileName);
this.dirty = false;
}
}
private Hashtable norms = new Hashtable();
/** The class which implements SegmentReader. */
private static Class IMPL;
static {
try {
String name =
System.getProperty("org.apache.lucene.SegmentReader.class",
SegmentReader.class.getName());
IMPL = Class.forName(name);
} catch (ClassNotFoundException e) {
throw new RuntimeException("cannot load SegmentReader class: " + e);
} catch (SecurityException se) {
try {
IMPL = Class.forName(SegmentReader.class.getName());
} catch (ClassNotFoundException e) {
throw new RuntimeException("cannot load default SegmentReader class: " + e);
}
}
}
protected SegmentReader() { super(null); }
public static SegmentReader get(SegmentInfo si) throws IOException {
return get(si.dir, si, null, false, false);
}
public static SegmentReader get(SegmentInfos sis, SegmentInfo si,
boolean closeDir) throws IOException {
return get(si.dir, si, sis, closeDir, true);
}
public static SegmentReader get(Directory dir, SegmentInfo si,
SegmentInfos sis,
boolean closeDir, boolean ownDir)
throws IOException {
SegmentReader instance;
try {
instance = (SegmentReader)IMPL.newInstance();
} catch (Exception e) {
throw new RuntimeException("cannot load SegmentReader class: " + e);
}
instance.init(dir, sis, closeDir, ownDir);
instance.initialize(si);
return instance;
}
private void initialize(SegmentInfo si) throws IOException {
segment = si.name;
// Use compound file directory for some files, if it exists
Directory cfsDir = directory();
if (directory().fileExists(segment + ".cfs")) {
cfsReader = new CompoundFileReader(directory(), segment + ".cfs");
cfsDir = cfsReader;
}
// No compound file exists - use the multi-file format
fieldInfos = new FieldInfos(cfsDir, segment + ".fnm");
fieldsReader = new FieldsReader(cfsDir, segment, fieldInfos);
tis = new TermInfosReader(cfsDir, segment, fieldInfos);
// NOTE: the bitvector is stored using the regular directory, not cfs
if (hasDeletions(si))
deletedDocs = new BitVector(directory(), segment + ".del");
// make sure that all index files have been read or are kept open
// so that if an index update removes them we'll still have them
freqStream = cfsDir.openInput(segment + ".frq");
proxStream = cfsDir.openInput(segment + ".prx");
openNorms(cfsDir);
if (fieldInfos.hasVectors()) { // open term vector files only as needed
termVectorsReaderOrig = new TermVectorsReader(cfsDir, segment, fieldInfos);
}
}
protected void finalize() {
// patch for pre-1.4.2 JVMs, whose ThreadLocals leak
termVectorsLocal.set(null);
super.finalize();
}
protected void doCommit() throws IOException {
if (deletedDocsDirty) { // re-write deleted
deletedDocs.write(directory(), segment + ".tmp");
directory().renameFile(segment + ".tmp", segment + ".del");
}
if(undeleteAll && directory().fileExists(segment + ".del")){
directory().deleteFile(segment + ".del");
}
if (normsDirty) { // re-write norms
Enumeration values = norms.elements();
while (values.hasMoreElements()) {
Norm norm = (Norm) values.nextElement();
if (norm.dirty) {
norm.reWrite();
}
}
}
deletedDocsDirty = false;
normsDirty = false;
undeleteAll = false;
}
protected void doClose() throws IOException {
fieldsReader.close();
tis.close();
if (freqStream != null)
freqStream.close();
if (proxStream != null)
proxStream.close();
closeNorms();
if (termVectorsReaderOrig != null)
termVectorsReaderOrig.close();
if (cfsReader != null)
cfsReader.close();
}
static boolean hasDeletions(SegmentInfo si) throws IOException {
return si.dir.fileExists(si.name + ".del");
}
public boolean hasDeletions() {
return deletedDocs != null;
}
static boolean usesCompoundFile(SegmentInfo si) throws IOException {
return si.dir.fileExists(si.name + ".cfs");
}
static boolean hasSeparateNorms(SegmentInfo si) throws IOException {
String[] result = si.dir.list();
String pattern = si.name + ".s";
int patternLength = pattern.length();
for(int i = 0; i < result.length; i++){
if(result[i].startsWith(pattern) && Character.isDigit(result[i].charAt(patternLength)))
return true;
}
return false;
}
protected void doDelete(int docNum) {
if (deletedDocs == null)
deletedDocs = new BitVector(maxDoc());
deletedDocsDirty = true;
undeleteAll = false;
deletedDocs.set(docNum);
}
protected void doUndeleteAll() {
deletedDocs = null;
deletedDocsDirty = false;
undeleteAll = true;
}
Vector files() throws IOException {
Vector files = new Vector(16);
for (int i = 0; i < IndexFileNames.INDEX_EXTENSIONS.length; i++) {
String name = segment + "." + IndexFileNames.INDEX_EXTENSIONS[i];
if (directory().fileExists(name))
files.addElement(name);
}
for (int i = 0; i < fieldInfos.size(); i++) {
FieldInfo fi = fieldInfos.fieldInfo(i);
if (fi.isIndexed && !fi.omitNorms){
String name;
if(cfsReader == null)
name = segment + ".f" + i;
else
name = segment + ".s" + i;
if (directory().fileExists(name))
files.addElement(name);
}
}
return files;
}
public TermEnum terms() {
return tis.terms();
}
public TermEnum terms(Term t) throws IOException {
return tis.terms(t);
}
public synchronized Document document(int n) throws IOException {
if (isDeleted(n))
throw new IllegalArgumentException
("attempt to access a deleted document");
return fieldsReader.doc(n);
}
public synchronized boolean isDeleted(int n) {
return (deletedDocs != null && deletedDocs.get(n));
}
public TermDocs termDocs() throws IOException {
return new SegmentTermDocs(this);
}
public TermPositions termPositions() throws IOException {
return new SegmentTermPositions(this);
}
public int docFreq(Term t) throws IOException {
TermInfo ti = tis.get(t);
if (ti != null)
return ti.docFreq;
else
return 0;
}
public int numDocs() {
int n = maxDoc();
if (deletedDocs != null)
n -= deletedDocs.count();
return n;
}
public int maxDoc() {
return fieldsReader.size();
}
/**
* @see IndexReader#getFieldNames()
* @deprecated Replaced by {@link #getFieldNames (IndexReader.FieldOption fldOption)}
*/
public Collection getFieldNames() {
// maintain a unique set of field names
Set fieldSet = new HashSet();
for (int i = 0; i < fieldInfos.size(); i++) {
FieldInfo fi = fieldInfos.fieldInfo(i);
fieldSet.add(fi.name);
}
return fieldSet;
}
/**
* @see IndexReader#getFieldNames(boolean)
* @deprecated Replaced by {@link #getFieldNames (IndexReader.FieldOption fldOption)}
*/
public Collection getFieldNames(boolean indexed) {
// maintain a unique set of field names
Set fieldSet = new HashSet();
for (int i = 0; i < fieldInfos.size(); i++) {
FieldInfo fi = fieldInfos.fieldInfo(i);
if (fi.isIndexed == indexed)
fieldSet.add(fi.name);
}
return fieldSet;
}
/**
* @see IndexReader#getIndexedFieldNames(Field.TermVector tvSpec)
* @deprecated Replaced by {@link #getFieldNames (IndexReader.FieldOption fldOption)}
*/
public Collection getIndexedFieldNames (Field.TermVector tvSpec){
boolean storedTermVector;
boolean storePositionWithTermVector;
boolean storeOffsetWithTermVector;
if(tvSpec == Field.TermVector.NO){
storedTermVector = false;
storePositionWithTermVector = false;
storeOffsetWithTermVector = false;
}
else if(tvSpec == Field.TermVector.YES){
storedTermVector = true;
storePositionWithTermVector = false;
storeOffsetWithTermVector = false;
}
else if(tvSpec == Field.TermVector.WITH_POSITIONS){
storedTermVector = true;
storePositionWithTermVector = true;
storeOffsetWithTermVector = false;
}
else if(tvSpec == Field.TermVector.WITH_OFFSETS){
storedTermVector = true;
storePositionWithTermVector = false;
storeOffsetWithTermVector = true;
}
else if(tvSpec == Field.TermVector.WITH_POSITIONS_OFFSETS){
storedTermVector = true;
storePositionWithTermVector = true;
storeOffsetWithTermVector = true;
}
else{
throw new IllegalArgumentException("unknown termVector parameter " + tvSpec);
}
// maintain a unique set of field names
Set fieldSet = new HashSet();
for (int i = 0; i < fieldInfos.size(); i++) {
FieldInfo fi = fieldInfos.fieldInfo(i);
if (fi.isIndexed && fi.storeTermVector == storedTermVector &&
fi.storePositionWithTermVector == storePositionWithTermVector &&
fi.storeOffsetWithTermVector == storeOffsetWithTermVector){
fieldSet.add(fi.name);
}
}
return fieldSet;
}
/**
* @see IndexReader#getFieldNames(IndexReader.FieldOption fldOption)
*/
public Collection getFieldNames(IndexReader.FieldOption fieldOption) {
Set fieldSet = new HashSet();
for (int i = 0; i < fieldInfos.size(); i++) {
FieldInfo fi = fieldInfos.fieldInfo(i);
if (fieldOption == IndexReader.FieldOption.ALL) {
fieldSet.add(fi.name);
}
else if (!fi.isIndexed && fieldOption == IndexReader.FieldOption.UNINDEXED) {
fieldSet.add(fi.name);
}
else if (fi.isIndexed && fieldOption == IndexReader.FieldOption.INDEXED) {
fieldSet.add(fi.name);
}
else if (fi.isIndexed && fi.storeTermVector == false && fieldOption == IndexReader.FieldOption.INDEXED_NO_TERMVECTOR) {
fieldSet.add(fi.name);
}
else if (fi.storeTermVector == true &&
fi.storePositionWithTermVector == false &&
fi.storeOffsetWithTermVector == false &&
fieldOption == IndexReader.FieldOption.TERMVECTOR) {
fieldSet.add(fi.name);
}
else if (fi.isIndexed && fi.storeTermVector && fieldOption == IndexReader.FieldOption.INDEXED_WITH_TERMVECTOR) {
fieldSet.add(fi.name);
}
else if (fi.storePositionWithTermVector && fi.storeOffsetWithTermVector == false && fieldOption == IndexReader.FieldOption.TERMVECTOR_WITH_POSITION) {
fieldSet.add(fi.name);
}
else if (fi.storeOffsetWithTermVector && fi.storePositionWithTermVector == false && fieldOption == IndexReader.FieldOption.TERMVECTOR_WITH_OFFSET) {
fieldSet.add(fi.name);
}
else if ((fi.storeOffsetWithTermVector && fi.storePositionWithTermVector) &&
fieldOption == IndexReader.FieldOption.TERMVECTOR_WITH_POSITION_OFFSET) {
fieldSet.add(fi.name);
}
}
return fieldSet;
}
public synchronized boolean hasNorms(String field) {
return norms.containsKey(field);
}
static byte[] createFakeNorms(int size) {
byte[] ones = new byte[size];
Arrays.fill(ones, DefaultSimilarity.encodeNorm(1.0f));
return ones;
}
private byte[] ones;
private byte[] fakeNorms() {
if (ones==null) ones=createFakeNorms(maxDoc());
return ones;
}
// can return null if norms aren't stored
protected synchronized byte[] getNorms(String field) throws IOException {
Norm norm = (Norm) norms.get(field);
if (norm == null) return null; // not indexed, or norms not stored
if (norm.bytes == null) { // value not yet read
byte[] bytes = new byte[maxDoc()];
norms(field, bytes, 0);
norm.bytes = bytes; // cache it
}
return norm.bytes;
}
// returns fake norms if norms aren't available
public synchronized byte[] norms(String field) throws IOException {
byte[] bytes = getNorms(field);
if (bytes==null) bytes=fakeNorms();
return bytes;
}
protected void doSetNorm(int doc, String field, byte value)
throws IOException {
Norm norm = (Norm) norms.get(field);
if (norm == null) // not an indexed field
return;
norm.dirty = true; // mark it dirty
normsDirty = true;
norms(field)[doc] = value; // set the value
}
/** Read norms into a pre-allocated array. */
public synchronized void norms(String field, byte[] bytes, int offset)
throws IOException {
Norm norm = (Norm) norms.get(field);
if (norm == null) {
System.arraycopy(fakeNorms(), 0, bytes, offset, maxDoc());
return;
}
if (norm.bytes != null) { // can copy from cache
System.arraycopy(norm.bytes, 0, bytes, offset, maxDoc());
return;
}
IndexInput normStream = (IndexInput) norm.in.clone();
try { // read from disk
normStream.seek(0);
normStream.readBytes(bytes, offset, maxDoc());
} finally {
normStream.close();
}
}
private void openNorms(Directory cfsDir) throws IOException {
for (int i = 0; i < fieldInfos.size(); i++) {
FieldInfo fi = fieldInfos.fieldInfo(i);
if (fi.isIndexed && !fi.omitNorms) {
// look first if there are separate norms in compound format
String fileName = segment + ".s" + fi.number;
Directory d = directory();
if(!d.fileExists(fileName)){
fileName = segment + ".f" + fi.number;
d = cfsDir;
}
norms.put(fi.name, new Norm(d.openInput(fileName), fi.number));
}
}
}
private void closeNorms() throws IOException {
synchronized (norms) {
Enumeration enumerator = norms.elements();
while (enumerator.hasMoreElements()) {
Norm norm = (Norm) enumerator.nextElement();
norm.in.close();
}
}
}
/**
* Create a clone from the initial TermVectorsReader and store it in the ThreadLocal.
* @return TermVectorsReader
*/
private TermVectorsReader getTermVectorsReader() {
TermVectorsReader tvReader = (TermVectorsReader)termVectorsLocal.get();
if (tvReader == null) {
tvReader = (TermVectorsReader)termVectorsReaderOrig.clone();
termVectorsLocal.set(tvReader);
}
return tvReader;
}
/** Return a term frequency vector for the specified document and field. The
* vector returned contains term numbers and frequencies for all terms in
* the specified field of this document, if the field had storeTermVector
* flag set. If the flag was not set, the method returns null.
* @throws IOException
*/
public TermFreqVector getTermFreqVector(int docNumber, String field) throws IOException {
// Check if this field is invalid or has no stored term vector
FieldInfo fi = fieldInfos.fieldInfo(field);
if (fi == null || !fi.storeTermVector || termVectorsReaderOrig == null)
return null;
TermVectorsReader termVectorsReader = getTermVectorsReader();
if (termVectorsReader == null)
return null;
return termVectorsReader.get(docNumber, field);
}
/** Return an array of term frequency vectors for the specified document.
* The array contains a vector for each vectorized field in the document.
* Each vector vector contains term numbers and frequencies for all terms
* in a given vectorized field.
* If no such fields existed, the method returns null.
* @throws IOException
*/
public TermFreqVector[] getTermFreqVectors(int docNumber) throws IOException {
if (termVectorsReaderOrig == null)
return null;
TermVectorsReader termVectorsReader = getTermVectorsReader();
if (termVectorsReader == null)
return null;
return termVectorsReader.get(docNumber);
}
}
| apache-2.0 |
ezbake/ezmongo | ezmongo-java-driver/src/main/org/bson/util/ClassAncestry.java | 3530 | /* Copyright (C) 2013-2014 Computer Sciences 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. */
/*
* Copyright (c) 2008-2014 MongoDB, 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 org.bson.util;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ConcurrentMap;
import static java.util.Collections.unmodifiableList;
import static org.bson.util.CopyOnWriteMap.newHashMap;
class ClassAncestry {
/**
* getAncestry
*
* Walks superclass and interface graph, superclasses first, then
* interfaces, to compute an ancestry list. Supertypes are visited left to
* right. Duplicates are removed such that no Class will appear in the list
* before one of its subtypes.
*
* Does not need to be synchronized, races are harmless as the Class graph
* does not change at runtime.
*/
public static <T> List<Class<?>> getAncestry(Class<T> c) {
final ConcurrentMap<Class<?>, List<Class<?>>> cache = getClassAncestryCache();
while (true) {
List<Class<?>> cachedResult = cache.get(c);
if (cachedResult != null) {
return cachedResult;
}
cache.putIfAbsent(c, computeAncestry(c));
}
}
/**
* computeAncestry, starting with children and going back to parents
*/
private static List<Class<?>> computeAncestry(Class<?> c) {
final List<Class<?>> result = new ArrayList<Class<?>>();
result.add(Object.class);
computeAncestry(c, result);
Collections.reverse(result);
return unmodifiableList(new ArrayList<Class<?>>(result));
}
private static <T> void computeAncestry(Class<T> c, List<Class<?>> result) {
if ((c == null) || (c == Object.class)) {
return;
}
// first interfaces (looks backwards but is not)
Class<?>[] interfaces = c.getInterfaces();
for (int i = interfaces.length - 1; i >= 0; i--) {
computeAncestry(interfaces[i], result);
}
// next superclass
computeAncestry(c.getSuperclass(), result);
if (!result.contains(c))
result.add(c);
}
/**
* classAncestryCache
*/
private static ConcurrentMap<Class<?>, List<Class<?>>> getClassAncestryCache() {
return (_ancestryCache);
}
private static final ConcurrentMap<Class<?>, List<Class<?>>> _ancestryCache = newHashMap();
}
| apache-2.0 |
rdblue/incubator-nifi | commons/data-provenance-utils/src/main/java/org/apache/nifi/provenance/lineage/FlowFileNode.java | 2335 | /*
* 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.nifi.provenance.lineage;
import static java.util.Objects.requireNonNull;
public class FlowFileNode implements LineageNode {
private final String flowFileUuid;
private final long creationTime;
private String clusterNodeIdentifier;
public FlowFileNode(final String flowFileUuid, final long flowFileCreationTime) {
this.flowFileUuid = requireNonNull(flowFileUuid);
this.creationTime = flowFileCreationTime;
}
@Override
public String getIdentifier() {
return flowFileUuid;
}
@Override
public long getTimestamp() {
return creationTime;
}
@Override
public String getClusterNodeIdentifier() {
return clusterNodeIdentifier;
}
@Override
public LineageNodeType getNodeType() {
return LineageNodeType.FLOWFILE_NODE;
}
@Override
public String getFlowFileUuid() {
return flowFileUuid;
}
@Override
public int hashCode() {
return 23498723 + flowFileUuid.hashCode();
}
@Override
public boolean equals(final Object obj) {
if (obj == null) {
return false;
}
if (obj == this) {
return true;
}
if (!(obj instanceof FlowFileNode)) {
return false;
}
final FlowFileNode other = (FlowFileNode) obj;
return flowFileUuid.equals(other.flowFileUuid);
}
@Override
public String toString() {
return "FlowFile[UUID=" + flowFileUuid + "]";
}
}
| apache-2.0 |
xiehan/zoara-server | src/zoara/sfs2x/extension/LoginEventHandler.java | 4312 | package zoara.sfs2x.extension;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import zoara.sfs2x.extension.simulation.World;
import zoara.sfs2x.extension.utils.RoomHelper;
import com.smartfoxserver.bitswarm.sessions.ISession;
import com.smartfoxserver.v2.core.ISFSEvent;
import com.smartfoxserver.v2.core.SFSEventParam;
import com.smartfoxserver.v2.db.IDBManager;
import com.smartfoxserver.v2.exceptions.SFSErrorCode;
import com.smartfoxserver.v2.exceptions.SFSErrorData;
import com.smartfoxserver.v2.exceptions.SFSException;
import com.smartfoxserver.v2.exceptions.SFSLoginException;
import com.smartfoxserver.v2.extensions.BaseServerEventHandler;
import com.smartfoxserver.v2.security.DefaultPermissionProfile;
public class LoginEventHandler extends BaseServerEventHandler
{
@Override
public void handleServerEvent(ISFSEvent event) throws SFSException
{
// Grab parameters from client request
String userName = (String) event.getParameter(SFSEventParam.LOGIN_NAME);
String cryptedPass = (String) event.getParameter(SFSEventParam.LOGIN_PASSWORD);
ISession session = (ISession) event.getParameter(SFSEventParam.SESSION);
// Get password from DB
IDBManager dbManager = getParentExtension().getParentZone().getDBManager();
Connection connection;
try
{
// Grab a connection from the DBManager connection pool
connection = dbManager.getConnection();
// Build a prepared statement
PreparedStatement stmt = connection.prepareStatement(
"SELECT Password, ID, ClanID, Zone FROM player_info WHERE Username = ?"
);
stmt.setString(1, userName);
// Execute query
ResultSet res = stmt.executeQuery();
// Verify that one record was found
if (!res.first())
{
// This is the part that goes to the client
SFSErrorData errData = new SFSErrorData(SFSErrorCode.LOGIN_BAD_USERNAME);
errData.addParameter(userName);
// This is logged on the server side
throw new SFSLoginException("Bad username: " + userName, errData);
}
String dbpassword = res.getString("Password");
int dbId = res.getInt("ID");
//String zone = res.getString("Zone");
int clanId = res.getInt("ClanID");
String zone = res.getString("Zone");
// Return connection to the DBManager connection pool
connection.close();
String thisZone = getParentExtension().getParentZone().getName();
if ((zone.equals("Adult") && !zone.equals(thisZone)) ||
(!zone.equals("Adult") && thisZone.equals("Adult")))
{
SFSErrorData data = new SFSErrorData(SFSErrorCode.JOIN_GAME_ACCESS_DENIED);
data.addParameter(thisZone);
throw new SFSLoginException("Login failed. User " + userName +
" is not a member of Server " + thisZone, data);
}
World world = RoomHelper.getWorld(this);
if (world.hasPlayer(userName))
{
SFSErrorData data = new SFSErrorData(SFSErrorCode.LOGIN_ALREADY_LOGGED);
String[] params = { userName, thisZone };
data.setParams(Arrays.asList(params));
throw new SFSLoginException("Login failed: " + userName +
" is already logged in!", data);
}
// Verify the secure password
if (!getApi().checkSecurePassword(session, dbpassword, cryptedPass))
{
if (dbId < 10)
{
trace("Passwords did not match, but logging in anyway.");
}
else
{
SFSErrorData data = new SFSErrorData(SFSErrorCode.LOGIN_BAD_PASSWORD);
data.addParameter(userName);
throw new SFSLoginException("Login failed for user: " + userName, data);
}
}
// Store the client dbId in the session
session.setProperty(ZoaraExtension.DATABASE_ID, dbId);
if (clanId != 0) {
session.setProperty(ZoaraExtension.CLAN_ID, clanId);
}
session.setProperty("$permission", DefaultPermissionProfile.STANDARD);
}
catch (SQLException e) // User name was not found
{
SFSErrorData errData = new SFSErrorData(SFSErrorCode.GENERIC_ERROR);
errData.addParameter("SQL Error: " + e.getMessage());
throw new SFSLoginException("A SQL Error occurred: " + e.getMessage(), errData);
}
}
}
| apache-2.0 |
ianmcxa/vortaro | app/src/test/java/org/mcxa/vortaro/ExampleUnitTest.java | 394 | package org.mcxa.vortaro;
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 |
esteinberg/plantuml4idea | src/org/plantuml/idea/action/ImageHighlightToggleAction.java | 1200 | package org.plantuml.idea.action;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.ToggleAction;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.Project;
import org.plantuml.idea.preview.PlantUmlPreviewPanel;
import org.plantuml.idea.settings.PlantUmlSettings;
import org.plantuml.idea.util.UIUtils;
public class ImageHighlightToggleAction extends ToggleAction implements DumbAware {
@Override
public boolean isSelected(AnActionEvent anActionEvent) {
return PlantUmlSettings.getInstance().isHighlightInImages();
}
@Override
public void setSelected(AnActionEvent anActionEvent, boolean b) {
PlantUmlSettings.getInstance().setHighlightInImages(b);
Project project = anActionEvent.getProject();
PlantUmlPreviewPanel previewPanel = UIUtils.getEditorOrToolWindowPreview(anActionEvent);
Editor selectedTextEditor = UIUtils.getSelectedTextEditor(FileEditorManager.getInstance(project), null);
previewPanel.highlightImages(selectedTextEditor);
}
}
| apache-2.0 |
liquibase/liquibase | liquibase-core/src/test/java/liquibase/sqlgenerator/core/InsertOrUpdateGeneratorOracleTest.java | 7276 | package liquibase.sqlgenerator.core;
import liquibase.change.ColumnConfig;
import liquibase.database.ObjectQuotingStrategy;
import liquibase.database.core.OracleDatabase;
import liquibase.sql.Sql;
import liquibase.statement.DatabaseFunction;
import liquibase.statement.SequenceCurrentValueFunction;
import liquibase.statement.SequenceNextValueFunction;
import liquibase.statement.core.InsertOrUpdateStatement;
import liquibase.statement.core.InsertStatement;
import liquibase.statement.core.UpdateStatement;
import org.junit.Test;
import static org.junit.Assert.*;
public class InsertOrUpdateGeneratorOracleTest {
@Test
public void ContainsInsertStatement() {
OracleDatabase database = new OracleDatabase();
InsertOrUpdateGeneratorOracle generator = new InsertOrUpdateGeneratorOracle();
InsertOrUpdateStatement statement = new InsertOrUpdateStatement("mycatalog", "myschema","mytable","pk_col1");
statement.addColumnValue("pk_col1","value1");
statement.addColumnValue("col2","value2");
statement.addColumnValue("pk_col1","value1");
statement.addColumnValue("col2","value2");
Sql[] sql = generator.generateSql( statement, database, null);
String theSql = sql[0].toSql();
assertTrue(theSql.contains("INSERT INTO mycatalog.mytable (pk_col1, col2) VALUES ('value1', 'value2');"));
assertTrue(theSql.contains("UPDATE mycatalog.mytable"));
String[] sqlLines = theSql.split("\n");
int lineToCheck = 0;
assertEquals("DECLARE", sqlLines[lineToCheck].trim());
lineToCheck++;
assertEquals("v_reccount NUMBER := 0;", sqlLines[lineToCheck].trim());
lineToCheck++;
assertEquals("BEGIN", sqlLines[lineToCheck].trim());
lineToCheck++;
assertEquals("SELECT COUNT(*) INTO v_reccount FROM mycatalog.mytable WHERE pk_col1 = 'value1';", sqlLines[lineToCheck].trim());
lineToCheck++;
assertEquals("IF v_reccount = 0 THEN", sqlLines[lineToCheck].trim());
lineToCheck++;
assertEquals("INSERT INTO mycatalog.mytable (pk_col1, col2) VALUES ('value1', 'value2');", sqlLines[lineToCheck]);
lineToCheck++;
assertEquals("ELSIF v_reccount = 1 THEN", sqlLines[lineToCheck].trim());
lineToCheck++;
assertEquals("UPDATE mycatalog.mytable SET col2 = 'value2' WHERE pk_col1 = 'value1';", sqlLines[lineToCheck].trim());
lineToCheck++;
assertEquals("END IF;", sqlLines[lineToCheck].trim());
lineToCheck++;
assertEquals("END;", sqlLines[lineToCheck].trim());
/*
DECLARE
v_prodcount NUMBER := 0;
BEGIN
-- Check if product with this name already exists
SELECT COUNT (*)
INTO v_prodcount
FROM books WHERE isbn = 12345678;
-- Product does not exist
IF v_prodcount = 0 THEN
-- Insert row into PRODUCT based on arguments passed
INSERT INTO books
VALUES
( 12345678,
98765432,
'Working with Liquibase');
-- Product with this name already exists
ELSIF v_prodcount = 1 THEN
-- Update the existing product with values
-- passed as arguments
UPDATE books
SET author_id = 98765432,
title = 'Working with liquibase'
WHERE isbn = 12345678;
END IF;
END;*/
}
@Test
public void testOnlyUpdateFlag() {
OracleDatabase database = new OracleDatabase();
InsertOrUpdateGeneratorOracle generator = new InsertOrUpdateGeneratorOracle();
InsertOrUpdateStatement statement = new InsertOrUpdateStatement("mycatalog", "myschema", "mytable", "pk_col1", true);
statement.addColumnValue("pk_col1", "value1");
statement.addColumnValue("col2", "value2");
Sql[] sql = generator.generateSql(statement, database, null);
String theSql = sql[0].toSql();
assertFalse("should not have had insert statement", theSql.contains("INSERT INTO mycatalog.mytable (pk_col1, col2) VALUES ('value1', 'value2');"));
assertTrue("missing update statement", theSql.contains("UPDATE mycatalog.mytable"));
String[] sqlLines = theSql.split("\n");
int lineToCheck = 0;
assertEquals("UPDATE mycatalog.mytable SET col2 = 'value2' WHERE pk_col1 = 'value1'", sqlLines[lineToCheck].trim());
assertEquals("Wrong number of lines", 1, sqlLines.length);
}
private String prepareInsertStatement(DatabaseFunction databaseSchemaBasedFunction) {
OracleDatabase database = new OracleDatabase();
database.setObjectQuotingStrategy(ObjectQuotingStrategy.LEGACY);
InsertGenerator generator = new InsertGenerator();
InsertStatement statement = new InsertStatement("mycatalog", "myschema", "mytable");
ColumnConfig columnConfig = new ColumnConfig();
if (databaseSchemaBasedFunction instanceof SequenceNextValueFunction) {
columnConfig.setValueSequenceNext((SequenceNextValueFunction) databaseSchemaBasedFunction);
} else if (databaseSchemaBasedFunction instanceof SequenceCurrentValueFunction) {
columnConfig.setValueSequenceCurrent((SequenceCurrentValueFunction) databaseSchemaBasedFunction);
}
columnConfig.setName("col3");
statement.addColumn(columnConfig);
Sql[] sql = generator.generateSql(statement, database, null);
return sql[0].toSql();
}
private String prepareUpdateStatement(SequenceNextValueFunction sequenceNextValueFunction) {
OracleDatabase database = new OracleDatabase();
database.setObjectQuotingStrategy(ObjectQuotingStrategy.LEGACY);
UpdateGenerator generator = new UpdateGenerator();
UpdateStatement statement = new UpdateStatement("mycatalog", "myschema", "mytable");
statement.addNewColumnValue("col3", sequenceNextValueFunction);
Sql[] sql = generator.generateSql(statement, database, null);
return sql[0].toSql();
}
@Test
public void testInsertSequenceValWithSchema() {
SequenceNextValueFunction sequenceNext = new SequenceNextValueFunction("myschema", "my_seq");
assertEquals(
"INSERT INTO mycatalog.mytable (col3) VALUES (myschema.my_seq.nextval)",
prepareInsertStatement(sequenceNext));
}
@Test
public void testInsertSequenceValWithSchemaInWholeStatement() {
SequenceNextValueFunction sequenceNext = new SequenceNextValueFunction("myschema", "my_seq");
assertEquals(
"INSERT INTO mycatalog.mytable (col3) VALUES (myschema.my_seq.nextval)",
prepareInsertStatement(sequenceNext));
}
@Test
public void testUpdateSequenceValWithSchema() {
SequenceNextValueFunction sequenceNext = new SequenceNextValueFunction("myschema", "my_seq");
assertEquals(
"UPDATE mycatalog.mytable SET col3 = myschema.my_seq.nextval",
prepareUpdateStatement(sequenceNext));
}
@Test
public void testUpdateSequenceValWithSchemaInWholeStatement() {
SequenceNextValueFunction sequenceNext = new SequenceNextValueFunction("myschema", "my_seq");
assertEquals(
"UPDATE mycatalog.mytable SET col3 = myschema.my_seq.nextval",
prepareUpdateStatement(sequenceNext));
}
}
| apache-2.0 |
consulo/consulo-metrics | src/com/sixrr/metrics/ui/dialogs/ExplanationDialog.java | 4055 | /*
* Copyright 2005-2011 Sixth and Red River Software, Bas Leijdekkers
*
* 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.sixrr.metrics.ui.dialogs;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.io.IOException;
import java.net.URL;
import javax.swing.Action;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextPane;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.Nullable;
import com.intellij.ide.BrowserUtil;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.ui.HyperlinkLabel;
import com.intellij.ui.ScrollPaneFactory;
import com.sixrr.metrics.Metric;
import com.sixrr.metrics.utils.MetricsReloadedBundle;
public class ExplanationDialog extends DialogWrapper
{
private static final Action[] EMPTY_ACTION_ARRAY = new Action[0];
private final JTextPane textPane = new JTextPane();
private final HyperlinkLabel urlLabel = new HyperlinkLabel();
private final JLabel moreInformationLabel = new JLabel(MetricsReloadedBundle.message("for.more.information.go.to"));
public ExplanationDialog(Project project)
{
super(project, false);
setModal(true);
init();
pack();
}
public void run(Metric metric)
{
@NonNls final String descriptionName = "/metricsDescriptions/" + metric.getID() + ".html";
final boolean resourceFound = setDescriptionFromResource(descriptionName, metric);
if(!resourceFound)
{
setDescriptionFromResource("/metricsDescriptions/UnderConstruction.html", metric);
}
setTitle(MetricsReloadedBundle.message("explanation.dialog.title", metric.getDisplayName()));
final String helpString = metric.getHelpDisplayString();
final String helpURL = metric.getHelpURL();
if(helpString == null)
{
urlLabel.setVisible(false);
moreInformationLabel.setVisible(false);
}
else
{
urlLabel.setHyperlinkText(helpString);
urlLabel.setVisible(true);
moreInformationLabel.setVisible(true);
}
urlLabel.addHyperlinkListener(new HyperlinkListener()
{
@Override
public void hyperlinkUpdate(HyperlinkEvent e)
{
if(helpURL != null)
{
BrowserUtil.launchBrowser("http://" + helpURL);
}
}
});
show();
}
private boolean setDescriptionFromResource(@NonNls String resourceName, Metric metric)
{
try
{
final URL resourceURL = metric.getClass().getResource(resourceName);
textPane.setPage(resourceURL);
return true;
}
catch(IOException ignored)
{
return false;
}
}
@Override
@NonNls
protected String getDimensionServiceKey()
{
return "MetricsReloaded.ExplanationDialog";
}
@Override
public Action[] createActions()
{
return EMPTY_ACTION_ARRAY;
}
@Override
@Nullable
protected JComponent createCenterPanel()
{
final JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
final GridBagConstraints constraints = new GridBagConstraints();
constraints.weightx = 1.0;
constraints.weighty = 1.0;
constraints.gridwidth = 2;
constraints.fill = GridBagConstraints.BOTH;
panel.add(ScrollPaneFactory.createScrollPane(textPane), constraints);
constraints.gridwidth = 1;
constraints.weightx = 0.0;
constraints.weighty = 0.0;
constraints.gridy = 1;
panel.add(moreInformationLabel, constraints);
constraints.gridx = 1;
constraints.insets.left = 5;
panel.add(urlLabel, constraints);
return panel;
}
}
| apache-2.0 |
gdefias/JavaDemo | InitJava/base/src/main/java/Init/Enum/TestEnumStates.java | 3956 | package Init.Enum;
import Generics.Generator;
import java.util.EnumMap;
import java.util.Iterator;
import static Init.Enum.Input.*;
import static Init.Print.print;
/**
* Created by Defias on 2020/07.
* Description: 使用enum的状态机
*
*/
public class TestEnumStates {
public static void main(String[] args) {
Generator<Input> gen = new RandomInputGenerator();
VendingMachine.run(gen);
}
}
class VendingMachine {
private static State state = State.RESTING;
private static int amount = 0;
private static Input selection = null;
enum StateDuration { TRANSIENT } // Tagging enum
enum State {
RESTING {
void next(Input input) {
switch(Category.categorize(input)) {
case MONEY:
amount += input.amount();
state = ADDING_MONEY;
break;
case SHUT_DOWN:
state = TERMINAL;
default:
}
}
},
ADDING_MONEY {
void next(Input input) {
switch(Category.categorize(input)) {
case MONEY:
amount += input.amount();
break;
case ITEM_SELECTION:
selection = input;
if(amount < selection.amount())
print("Insufficient money for " + selection);
else state = DISPENSING;
break;
case QUIT_TRANSACTION:
state = GIVING_CHANGE;
break;
case SHUT_DOWN:
state = TERMINAL;
default:
}
}
},
DISPENSING(StateDuration.TRANSIENT) {
void next() {
print("here is your " + selection);
amount -= selection.amount();
state = GIVING_CHANGE;
}
},
GIVING_CHANGE(StateDuration.TRANSIENT) {
void next() {
if(amount > 0) {
print("Your change: " + amount);
amount = 0;
}
state = RESTING;
}
},
TERMINAL { void output() { print("Halted"); }};
private boolean isTransient = false;
State() {}
State(StateDuration trans) {
isTransient = true;
}
void next(Input input) {
throw new RuntimeException("Only call " +
"next(Input input) for non-transient states");
}
void next() {
throw new RuntimeException("Only call next() for " +
"StateDuration.TRANSIENT states");
}
void output() { print(amount); }
}
static void run(Generator<Input> gen) {
while(state != State.TERMINAL) {
state.next(gen.next());
while(state.isTransient)
state.next();
state.output();
}
}
}
// For a basic sanity check:
class RandomInputGenerator implements Generator<Input> {
public Input next() {
return Input.randomSelection();
}
}
enum Category {
MONEY(NICKEL, DIME, QUARTER, DOLLAR),
ITEM_SELECTION(TOOTHPASTE, CHIPS, SODA, SOAP),
QUIT_TRANSACTION(ABORT_TRANSACTION),
SHUT_DOWN(STOP);
private Input[] values;
Category(Input... types) {
values = types;
}
private static EnumMap<Input,Category> categories =
new EnumMap<Input,Category>(Input.class);
static {
for(Category c : Category.class.getEnumConstants())
for(Input type : c.values)
categories.put(type, c);
}
public static Category categorize(Input input) {
return categories.get(input);
}
}
| apache-2.0 |
MarSik/bugautomation | src/main/java/org/marsik/bugautomation/rest/RestApplication.java | 495 | package org.marsik.bugautomation.rest;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
@ApplicationPath("/")
public class RestApplication extends Application {
@Override
public Set<Class<?>> getClasses() {
final HashSet<Class<?>> classes = new HashSet<>();
classes.add(MetricsEndpoint.class);
classes.add(InfoEndpoint.class);
return classes;
}
}
| apache-2.0 |
markus1978/citygml4emf | de.hub.citygml.emf.ecore.edit/src/net/opengis/gml/provider/TopoVolumeTypeItemProvider.java | 6438 | /**
* <copyright>
* </copyright>
*
* $Id$
*/
package net.opengis.gml.provider;
import java.util.Collection;
import java.util.List;
import net.opengis.gml.GmlFactory;
import net.opengis.gml.GmlPackage;
import net.opengis.gml.TopoVolumeType;
import org.eclipse.emf.common.notify.AdapterFactory;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.emf.ecore.util.FeatureMap;
import org.eclipse.emf.ecore.util.FeatureMapUtil;
import org.eclipse.emf.edit.provider.IEditingDomainItemProvider;
import org.eclipse.emf.edit.provider.IItemLabelProvider;
import org.eclipse.emf.edit.provider.IItemPropertyDescriptor;
import org.eclipse.emf.edit.provider.IItemPropertySource;
import org.eclipse.emf.edit.provider.IStructuredItemContentProvider;
import org.eclipse.emf.edit.provider.ITreeItemContentProvider;
import org.eclipse.emf.edit.provider.ViewerNotification;
/**
* This is the item provider adapter for a {@link net.opengis.gml.TopoVolumeType} object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public class TopoVolumeTypeItemProvider
extends AbstractTopologyTypeItemProvider
implements
IEditingDomainItemProvider,
IStructuredItemContentProvider,
ITreeItemContentProvider,
IItemLabelProvider,
IItemPropertySource {
/**
* This constructs an instance from a factory and a notifier.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public TopoVolumeTypeItemProvider(AdapterFactory adapterFactory) {
super(adapterFactory);
}
/**
* This returns the property descriptors for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object) {
if (itemPropertyDescriptors == null) {
super.getPropertyDescriptors(object);
}
return itemPropertyDescriptors;
}
/**
* This specifies how to implement {@link #getChildren} and is used to deduce an appropriate feature for an
* {@link org.eclipse.emf.edit.command.AddCommand}, {@link org.eclipse.emf.edit.command.RemoveCommand} or
* {@link org.eclipse.emf.edit.command.MoveCommand} in {@link #createCommand}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Collection<? extends EStructuralFeature> getChildrenFeatures(Object object) {
if (childrenFeatures == null) {
super.getChildrenFeatures(object);
childrenFeatures.add(GmlPackage.eINSTANCE.getTopoVolumeType_DirectedTopoSolid());
}
return childrenFeatures;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EStructuralFeature getChildFeature(Object object, Object child) {
// Check the type of the specified child object and return the proper feature to use for
// adding (see {@link AddCommand}) it as a child.
return super.getChildFeature(object, child);
}
/**
* This returns TopoVolumeType.gif.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object getImage(Object object) {
return overlayImage(object, getResourceLocator().getImage("full/obj16/TopoVolumeType"));
}
/**
* This returns the label text for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String getText(Object object) {
String label = ((TopoVolumeType)object).getId();
return label == null || label.length() == 0 ?
getString("_UI_TopoVolumeType_type") :
getString("_UI_TopoVolumeType_type") + " " + label;
}
/**
* This handles model notifications by calling {@link #updateChildren} to update any cached
* children and by creating a viewer notification, which it passes to {@link #fireNotifyChanged}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void notifyChanged(Notification notification) {
updateChildren(notification);
switch (notification.getFeatureID(TopoVolumeType.class)) {
case GmlPackage.TOPO_VOLUME_TYPE__DIRECTED_TOPO_SOLID:
fireNotifyChanged(new ViewerNotification(notification, notification.getNotifier(), true, false));
return;
}
super.notifyChanged(notification);
}
/**
* This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children
* that can be created under this object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object) {
super.collectNewChildDescriptors(newChildDescriptors, object);
newChildDescriptors.add
(createChildParameter
(GmlPackage.eINSTANCE.getTopoVolumeType_DirectedTopoSolid(),
GmlFactory.eINSTANCE.createDirectedTopoSolidPropertyType()));
}
/**
* This returns the label text for {@link org.eclipse.emf.edit.command.CreateChildCommand}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String getCreateChildText(Object owner, Object feature, Object child, Collection<?> selection) {
Object childFeature = feature;
Object childObject = child;
if (childFeature instanceof EStructuralFeature && FeatureMapUtil.isFeatureMap((EStructuralFeature)childFeature)) {
FeatureMap.Entry entry = (FeatureMap.Entry)childObject;
childFeature = entry.getEStructuralFeature();
childObject = entry.getValue();
}
boolean qualify =
childFeature == GmlPackage.eINSTANCE.getAbstractGMLType_Name() ||
childFeature == GmlPackage.eINSTANCE.getDocumentRoot_CoordinateOperationName() ||
childFeature == GmlPackage.eINSTANCE.getDocumentRoot_CsName() ||
childFeature == GmlPackage.eINSTANCE.getDocumentRoot_DatumName() ||
childFeature == GmlPackage.eINSTANCE.getDocumentRoot_EllipsoidName() ||
childFeature == GmlPackage.eINSTANCE.getDocumentRoot_GroupName() ||
childFeature == GmlPackage.eINSTANCE.getDocumentRoot_MeridianName() ||
childFeature == GmlPackage.eINSTANCE.getDocumentRoot_MethodName() ||
childFeature == GmlPackage.eINSTANCE.getDocumentRoot_ParameterName() ||
childFeature == GmlPackage.eINSTANCE.getDocumentRoot_SrsName();
if (qualify) {
return getString
("_UI_CreateChild_text2",
new Object[] { getTypeText(childObject), getFeatureText(childFeature), getTypeText(owner) });
}
return super.getCreateChildText(owner, feature, child, selection);
}
}
| apache-2.0 |
android/android-test | espresso/core/javatests/androidx/test/espresso/action/GeneralLocationTest.java | 4547 | /*
* 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 androidx.test.espresso.action;
import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation;
import static junit.framework.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.spy;
import android.view.View;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.filters.SmallTest;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
/** Unit tests for {@link GeneralLocation}. */
@SmallTest
@RunWith(AndroidJUnit4.class)
public class GeneralLocationTest {
private static final int VIEW_POSITION_X = 100;
private static final int VIEW_POSITION_Y = 50;
private static final int VIEW_WIDTH = 150;
private static final int VIEW_HEIGHT = 300;
private static final int AXIS_X = 0;
private static final int AXIS_Y = 1;
private View mockView;
@Before
public void setUp() throws Exception {
mockView = spy(new View(getInstrumentation().getContext()));
doAnswer(
new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
int[] array = (int[]) invocation.getArguments()[0];
array[AXIS_X] = VIEW_POSITION_X;
array[AXIS_Y] = VIEW_POSITION_Y;
return null;
}
})
.when(mockView)
.getLocationOnScreen(any(int[].class));
mockView.layout(
VIEW_POSITION_X,
VIEW_POSITION_Y,
VIEW_POSITION_X + VIEW_WIDTH,
VIEW_POSITION_Y + VIEW_HEIGHT);
}
@Test
public void leftLocationsX() {
assertPositionEquals(VIEW_POSITION_X, GeneralLocation.TOP_LEFT, AXIS_X);
assertPositionEquals(VIEW_POSITION_X, GeneralLocation.CENTER_LEFT, AXIS_X);
assertPositionEquals(VIEW_POSITION_X, GeneralLocation.BOTTOM_LEFT, AXIS_X);
}
@Test
public void rightLocationsX() {
assertPositionEquals(VIEW_POSITION_X + VIEW_WIDTH - 1, GeneralLocation.TOP_RIGHT, AXIS_X);
assertPositionEquals(VIEW_POSITION_X + VIEW_WIDTH - 1, GeneralLocation.CENTER_RIGHT, AXIS_X);
assertPositionEquals(VIEW_POSITION_X + VIEW_WIDTH - 1, GeneralLocation.BOTTOM_RIGHT, AXIS_X);
}
@Test
public void topLocationsY() {
assertPositionEquals(VIEW_POSITION_Y, GeneralLocation.TOP_LEFT, AXIS_Y);
assertPositionEquals(VIEW_POSITION_Y, GeneralLocation.TOP_CENTER, AXIS_Y);
assertPositionEquals(VIEW_POSITION_Y, GeneralLocation.TOP_RIGHT, AXIS_Y);
}
@Test
public void bottomLocationsY() {
assertPositionEquals(VIEW_POSITION_Y + VIEW_HEIGHT - 1, GeneralLocation.BOTTOM_LEFT, AXIS_Y);
assertPositionEquals(VIEW_POSITION_Y + VIEW_HEIGHT - 1, GeneralLocation.BOTTOM_CENTER, AXIS_Y);
assertPositionEquals(VIEW_POSITION_Y + VIEW_HEIGHT - 1, GeneralLocation.BOTTOM_RIGHT, AXIS_Y);
}
@Test
public void centerLocationsX() {
assertPositionEquals(VIEW_POSITION_X + (VIEW_WIDTH - 1) / 2.0f, GeneralLocation.CENTER, AXIS_X);
assertPositionEquals(
VIEW_POSITION_X + (VIEW_WIDTH - 1) / 2.0f, GeneralLocation.TOP_CENTER, AXIS_X);
assertPositionEquals(
VIEW_POSITION_X + (VIEW_WIDTH - 1) / 2.0f, GeneralLocation.BOTTOM_CENTER, AXIS_X);
}
@Test
public void centerLocationsY() {
assertPositionEquals(
VIEW_POSITION_Y + (VIEW_HEIGHT - 1) / 2.0f, GeneralLocation.CENTER, AXIS_Y);
assertPositionEquals(
VIEW_POSITION_Y + (VIEW_HEIGHT - 1) / 2.0f, GeneralLocation.CENTER_LEFT, AXIS_Y);
assertPositionEquals(
VIEW_POSITION_Y + (VIEW_HEIGHT - 1) / 2.0f, GeneralLocation.CENTER_RIGHT, AXIS_Y);
}
private void assertPositionEquals(float expected, GeneralLocation location, int axis) {
assertEquals(expected, location.calculateCoordinates(mockView)[axis], 0.1f);
}
}
| apache-2.0 |
doom369/netty | transport-native-unix-common/src/main/java/io/netty/channel/unix/Unix.java | 3285 | /*
* Copyright 2014 The Netty Project
*
* The Netty 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:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package io.netty.channel.unix;
import io.netty.util.internal.ClassInitializerUtil;
import io.netty.util.internal.UnstableApi;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.PortUnreachableException;
import java.nio.channels.ClosedChannelException;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Tells if <a href="https://netty.io/wiki/native-transports.html">{@code netty-transport-native-unix}</a> is
* supported.
*/
public final class Unix {
private static final AtomicBoolean registered = new AtomicBoolean();
static {
// Preload all classes that will be used in the OnLoad(...) function of JNI to eliminate the possiblity of a
// class-loader deadlock. This is a workaround for https://github.com/netty/netty/issues/11209.
// This needs to match all the classes that are loaded via NETTY_JNI_UTIL_LOAD_CLASS or looked up via
// NETTY_JNI_UTIL_FIND_CLASS.
ClassInitializerUtil.tryLoadClasses(Unix.class,
// netty_unix_errors
OutOfMemoryError.class, RuntimeException.class, ClosedChannelException.class,
IOException.class, PortUnreachableException.class,
// netty_unix_socket
DatagramSocketAddress.class, InetSocketAddress.class
);
}
/**
* Internal method... Should never be called from the user.
*
* @param registerTask
*/
@UnstableApi
public static void registerInternal(Runnable registerTask) {
if (registered.compareAndSet(false, true)) {
registerTask.run();
Socket.initialize();
}
}
/**
* Returns {@code true} if and only if the <a href="https://netty.io/wiki/native-transports.html">{@code
* netty_transport_native_unix}</a> is available.
*/
@Deprecated
public static boolean isAvailable() {
return false;
}
/**
* Ensure that <a href="https://netty.io/wiki/native-transports.html">{@code netty_transport_native_unix}</a> is
* available.
*
* @throws UnsatisfiedLinkError if unavailable
*/
@Deprecated
public static void ensureAvailability() {
throw new UnsupportedOperationException();
}
/**
* Returns the cause of unavailability of <a href="https://netty.io/wiki/native-transports.html">
* {@code netty_transport_native_unix}</a>.
*
* @return the cause if unavailable. {@code null} if available.
*/
@Deprecated
public static Throwable unavailabilityCause() {
return new UnsupportedOperationException();
}
private Unix() {
}
}
| apache-2.0 |
googleapis/google-api-java-client-services | clients/google-api-services-dialogflow/v3/1.31.0/com/google/api/services/dialogflow/v3/model/GoogleCloudDialogflowCxV3ListAgentsResponse.java | 3689 | /*
* 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.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.dialogflow.v3.model;
/**
* The response message for Agents.ListAgents.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Dialogflow API. For a detailed explanation see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class GoogleCloudDialogflowCxV3ListAgentsResponse extends com.google.api.client.json.GenericJson {
/**
* The list of agents. There will be a maximum number of items returned based on the page_size
* field in the request.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<GoogleCloudDialogflowCxV3Agent> agents;
static {
// hack to force ProGuard to consider GoogleCloudDialogflowCxV3Agent used, since otherwise it would be stripped out
// see https://github.com/google/google-api-java-client/issues/543
com.google.api.client.util.Data.nullOf(GoogleCloudDialogflowCxV3Agent.class);
}
/**
* Token to retrieve the next page of results, or empty if there are no more results in the list.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String nextPageToken;
/**
* The list of agents. There will be a maximum number of items returned based on the page_size
* field in the request.
* @return value or {@code null} for none
*/
public java.util.List<GoogleCloudDialogflowCxV3Agent> getAgents() {
return agents;
}
/**
* The list of agents. There will be a maximum number of items returned based on the page_size
* field in the request.
* @param agents agents or {@code null} for none
*/
public GoogleCloudDialogflowCxV3ListAgentsResponse setAgents(java.util.List<GoogleCloudDialogflowCxV3Agent> agents) {
this.agents = agents;
return this;
}
/**
* Token to retrieve the next page of results, or empty if there are no more results in the list.
* @return value or {@code null} for none
*/
public java.lang.String getNextPageToken() {
return nextPageToken;
}
/**
* Token to retrieve the next page of results, or empty if there are no more results in the list.
* @param nextPageToken nextPageToken or {@code null} for none
*/
public GoogleCloudDialogflowCxV3ListAgentsResponse setNextPageToken(java.lang.String nextPageToken) {
this.nextPageToken = nextPageToken;
return this;
}
@Override
public GoogleCloudDialogflowCxV3ListAgentsResponse set(String fieldName, Object value) {
return (GoogleCloudDialogflowCxV3ListAgentsResponse) super.set(fieldName, value);
}
@Override
public GoogleCloudDialogflowCxV3ListAgentsResponse clone() {
return (GoogleCloudDialogflowCxV3ListAgentsResponse) super.clone();
}
}
| apache-2.0 |
deleidos/de-pipeline-tool | de-framework-monitoring/src/main/java/com/deleidos/framework/monitoring/response/InfoResponse.java | 1247 | package com.deleidos.framework.monitoring.response;
public class InfoResponse {
public static final String PATH = "/proxy/${APP_ID}/ws/v2/stram/info";
public static class Stats {
public int allocatedContainers;
public int plannedContainers;
public int totalVCoresAllocated;
public int vcoresRequired;
public int memoryRequired;
public int tuplesProcessedPSMA;
public long totalTuplesProcessed;
public int tuplesEmittedPSMA;
public long totalTuplesEmitted;
public int totalMemoryAllocated;
public int totalBufferServerReadBytesPSMA;
public int totalBufferServerWriteBytesPSMA;
public int[] criticalPath;
public int latency;
public long windowStartMillis;
public int numOperators;
public int failedContainers;
public long currentWindowId;
public long recoveryWindowId;
}
public String name;
public String user;
public long startTime;
public long elapsedTime;
public String appPath;
public String gatewayAddress;
public boolean gatewayConnected;
public Object[] appDataSources;
public Object metrics;
public Object attributes;
public String appMasterTrackingUrl;
public String version;
public Stats stats;
public String id;
//public String state; // Can't get this from this request
}
| apache-2.0 |
openphacts/queryExpander | query.expander.implementation/test/uk/ac/manchester/cs/openphacts/queryexpander/queryLoader/OpsReplacemeentTest.java | 1764 | package uk.ac.manchester.cs.openphacts.queryexpander.queryLoader;
import java.util.List;
import java.util.Set;
import org.bridgedb.uri.tools.GraphResolver;
import org.bridgedb.utils.Reporter;
import static org.junit.Assert.*;
import org.junit.Test;
import uk.ac.manchester.cs.openphacts.queryexpander.QueryUtils;
import uk.ac.manchester.cs.openphacts.queryexpander.api.QueryExpander;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Christian
*/
public abstract class OpsReplacemeentTest {
protected QueryExpander queryExpander;
private final String NO_LENS = null;
@Test
public void testAllNoMapping() throws Exception{
GraphResolver.addTestMappings();
QueryCaseLoader loader = new OpsReplacementLoader();
Set<String> queryKeys = loader.keySet();
for (String queryKey:queryKeys){
Reporter.println("Testing " + loader.getQueryName(queryKey));
String originalQuery = loader.getOriginalQuery(queryKey);
String targetQuery = loader.getTextReplaceQuery(queryKey);
List<String> parameters = loader.getParameters(queryKey);
String inputURI = loader.getInsertURI(queryKey);
//ystem.out.println(originalQuery);
//ystem.out.println(parameters);
String newQuery = queryExpander.expand(originalQuery, parameters, inputURI, NO_LENS, false);
//System.out.println(newQuery);
if (!QueryUtils.sameTupleExpr(targetQuery, newQuery, false, loader.getQueryName(queryKey))){
assertTrue(QueryUtils.sameTupleExpr(targetQuery, newQuery, true, loader.getQueryName(queryKey)));
}
}
}
}
| apache-2.0 |
youdonghai/intellij-community | java/java-impl/src/com/intellij/codeInspection/util/IteratorDeclaration.java | 7121 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* 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.intellij.codeInspection.util;
import com.intellij.psi.*;
import com.intellij.psi.controlFlow.DefUseUtil;
import com.intellij.psi.search.searches.ReferencesSearch;
import com.intellij.psi.util.InheritanceUtil;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import com.siyeh.ig.psiutils.ExpressionUtils;
import one.util.streamex.MoreCollectors;
import one.util.streamex.StreamEx;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* Represents the iterator which traverses the iterable within the loop
*
* @author Tagir Valeev
*/
public class IteratorDeclaration {
private final @NotNull PsiLocalVariable myIterator;
private final @Nullable PsiExpression myIterable;
private final boolean myCollection;
private IteratorDeclaration(@NotNull PsiLocalVariable iterator, @Nullable PsiExpression iterable, boolean collection) {
myIterator = iterator;
myIterable = iterable;
myCollection = collection;
}
@NotNull
public PsiLocalVariable getIterator() {
return myIterator;
}
@Nullable
public PsiExpression getIterable() {
return myIterable;
}
public boolean isCollection() {
return myCollection;
}
public boolean isHasNextCall(PsiExpression condition) {
return isIteratorMethodCall(condition, "hasNext");
}
@Nullable
public PsiElement findOnlyIteratorRef(PsiExpression parent) {
PsiElement element = PsiUtil.getVariableCodeBlock(myIterator, null);
PsiCodeBlock block =
element instanceof PsiCodeBlock ? (PsiCodeBlock)element : PsiTreeUtil.getParentOfType(element, PsiCodeBlock.class);
if (block == null) return null;
return StreamEx.of(DefUseUtil.getRefs(block, myIterator, myIterator.getInitializer()))
.filter(e -> PsiTreeUtil.isAncestor(parent, e, false))
.collect(MoreCollectors.onlyOne()).orElse(null);
}
public boolean isIteratorMethodCall(PsiElement candidate, String method) {
if (!(candidate instanceof PsiMethodCallExpression)) return false;
PsiMethodCallExpression call = (PsiMethodCallExpression)candidate;
if (call.getArgumentList().getExpressions().length != 0) return false;
PsiReferenceExpression expression = call.getMethodExpression();
return method.equals(expression.getReferenceName()) && ExpressionUtils.isReferenceTo(expression.getQualifierExpression(), myIterator);
}
public PsiVariable getNextElementVariable(PsiStatement statement) {
if (!(statement instanceof PsiDeclarationStatement)) return null;
PsiDeclarationStatement declaration = (PsiDeclarationStatement)statement;
if (declaration.getDeclaredElements().length != 1) return null;
PsiElement element = declaration.getDeclaredElements()[0];
if (!(element instanceof PsiLocalVariable)) return null;
PsiLocalVariable var = (PsiLocalVariable)element;
if (!isIteratorMethodCall(var.getInitializer(), "next")) return null;
return var;
}
@Contract("null -> null")
private static IteratorDeclaration extract(PsiStatement statement) {
if (!(statement instanceof PsiDeclarationStatement)) return null;
PsiDeclarationStatement declaration = (PsiDeclarationStatement)statement;
if (declaration.getDeclaredElements().length != 1) return null;
PsiElement element = declaration.getDeclaredElements()[0];
if (!(element instanceof PsiLocalVariable)) return null;
PsiLocalVariable variable = (PsiLocalVariable)element;
PsiExpression initializer = variable.getInitializer();
if (!(initializer instanceof PsiMethodCallExpression)) return null;
PsiMethodCallExpression call = (PsiMethodCallExpression)initializer;
if (call.getArgumentList().getExpressions().length != 0) return null;
PsiReferenceExpression methodExpression = call.getMethodExpression();
if (!"iterator".equals(methodExpression.getReferenceName())) return null;
PsiMethod method = call.resolveMethod();
if (method == null || !InheritanceUtil.isInheritor(method.getContainingClass(), CommonClassNames.JAVA_LANG_ITERABLE)) return null;
boolean isCollection = InheritanceUtil.isInheritor(method.getContainingClass(), CommonClassNames.JAVA_UTIL_COLLECTION);
PsiType type = variable.getType();
if (!(type instanceof PsiClassType) || !((PsiClassType)type).rawType().equalsToText(CommonClassNames.JAVA_UTIL_ITERATOR)) return null;
return new IteratorDeclaration(variable, methodExpression.getQualifierExpression(), isCollection);
}
@Nullable
private static IteratorDeclaration fromForLoop(PsiForStatement statement) {
if (statement.getUpdate() != null) return null;
PsiStatement initialization = statement.getInitialization();
IteratorDeclaration declaration = extract(initialization);
if (declaration == null || !declaration.isHasNextCall(statement.getCondition())) return null;
return declaration;
}
@Nullable
private static IteratorDeclaration fromWhileLoop(PsiWhileStatement statement) {
PsiElement previous = PsiTreeUtil.skipSiblingsBackward(statement, PsiComment.class, PsiWhiteSpace.class);
if (!(previous instanceof PsiDeclarationStatement)) return null;
IteratorDeclaration declaration = extract((PsiStatement)previous);
if (declaration == null || !declaration.isHasNextCall(statement.getCondition())) return null;
if (!ReferencesSearch.search(declaration.myIterator, declaration.myIterator.getUseScope()).forEach(ref -> {
return PsiTreeUtil.isAncestor(statement, ref.getElement(), true);
})) {
return null;
}
return declaration;
}
/**
* Creates {@code IteratorDeclaration} if the loop follows one of these patterns:
*
* <pre>{@code
* Iterator<T> it = iterable.iterator();
* while(it.hasNext()) {
* ...
* }
* // And iterator is not reused after the loop
* }</pre>
*
* or
*
* <pre>{@code
* for(Iterator<T> it = iterable.iterator();it.hasNext();) {
* ...
* }
* }</pre>
*
* @param statement loop to create the {@code IteratorDeclaration} from
* @return created IteratorDeclaration or null if the loop pattern is not recognized.
*/
@Contract("null -> null")
public static IteratorDeclaration fromLoop(PsiLoopStatement statement) {
if(statement instanceof PsiWhileStatement) {
return fromWhileLoop((PsiWhileStatement)statement);
}
if(statement instanceof PsiForStatement) {
return fromForLoop((PsiForStatement)statement);
}
return null;
}
}
| apache-2.0 |
yetwish/Reading | reading/src/main/java/com/xidian/yetwish/reading/ui/SplashActivity.java | 1907 | package com.xidian.yetwish.reading.ui;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import com.xidian.yetwish.reading.R;
import com.xidian.yetwish.reading.framework.utils.SharedPreferencesUtils;
import com.xidian.yetwish.reading.ui.main.ReadingActivity;
/**
* splash activity
* Created by Yetwish on 2016/4/8 0008.
*/
public class SplashActivity extends BaseActivity {
private static final int MSG_SPLASH = 0x01;
private Handler mHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what){
case MSG_SPLASH:
ReadingActivity.startActivity(SplashActivity.this);
finish();
break;
}
}
};
public static void startActivity(Context context,boolean splash){
Intent intent = new Intent(context,SplashActivity.class);
intent.putExtra(SharedPreferencesUtils.EXTRA_SPLASH,splash);
context.startActivity(intent);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
drawStatusBar();
boolean splash = getIntent().getBooleanExtra(SharedPreferencesUtils.EXTRA_SPLASH,true);
if(splash){
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000);
}catch (InterruptedException e){
//TODO catch exception
}finally {
mHandler.sendEmptyMessage(MSG_SPLASH);
}
}
}).start();
}
}
}
| apache-2.0 |
lesaint/experimenting-annotation-processing | experimenting-rounds/massive-count-of-annotated-classes/src/main/java/fr/javatronic/blog/massive/annotation1/sub1/Class_5188.java | 151 | package fr.javatronic.blog.massive.annotation1.sub1;
import fr.javatronic.blog.processor.Annotation_001;
@Annotation_001
public class Class_5188 {
}
| apache-2.0 |
krasserm/ipf | platform-camel/core/src/main/java/org/openehealth/ipf/platform/camel/core/management/ProcessorManagementNamingStrategy.java | 2034 | /*
* Copyright 2011 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.openehealth.ipf.platform.camel.core.management;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import org.apache.camel.CamelContext;
import org.apache.camel.Processor;
import org.apache.camel.management.DefaultManagementNamingStrategy;
import org.apache.camel.model.ProcessorDefinition;
import org.apache.camel.model.ProcessorDefinitionHelper;
import org.apache.camel.model.RouteDefinition;
/**
* @author Reinhard Luft
*/
public class ProcessorManagementNamingStrategy extends
DefaultManagementNamingStrategy {
public static final String KEY_ROUTE = "route";
public ObjectName getObjectNameForProcessor(CamelContext context,
Processor processor, ProcessorDefinition<?> definition)
throws MalformedObjectNameException {
StringBuilder buffer = new StringBuilder();
buffer.append(domainName).append(":");
buffer.append(KEY_CONTEXT + "=").append(getContextId(context)).append(",");
buffer.append(KEY_TYPE + "=").append(TYPE_PROCESSOR).append(",");
RouteDefinition route = ProcessorDefinitionHelper.getRoute(definition);
if (route != null) {
buffer.append(KEY_ROUTE + "=").append(route.getId()).append(",");
}
buffer.append(KEY_NAME + "=").append(ObjectName.quote(definition.getId()));
return createObjectName(buffer);
}
}
| apache-2.0 |
buddycloud/buddycloud-android | src/com/buddycloud/utils/InputUtils.java | 620 | package com.buddycloud.utils;
import android.app.Activity;
import android.content.Context;
import android.view.inputmethod.InputMethodManager;
public class InputUtils {
public static void hideKeyboard(Activity activity) {
InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
}
public static boolean isActive(Activity activity) {
InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
return imm.isActive();
}
}
| apache-2.0 |
infinitiessoft/keystone4j | keystone4j-core/src/main/java/com/infinities/keystone4j/contrib/revoke/driver/RevokeDriver.java | 1112 | /*******************************************************************************
* # Copyright 2015 InfinitiesSoft Solutions 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.infinities.keystone4j.contrib.revoke.driver;
import java.util.Calendar;
import java.util.List;
import com.infinities.keystone4j.contrib.revoke.model.RevokeEvent;
public interface RevokeDriver {
// lastFetch=null
List<RevokeEvent> getEvents(Calendar lastFetch);
void revoke(RevokeEvent event);
}
| apache-2.0 |
wangshijun101/JavaSenior | CoreJava/src/main/java/com/flying/promotion/javatuning/future/jdk/RealData.java | 610 | package com.flying.promotion.javatuning.future.jdk;
import java.util.concurrent.Callable;
/**
* Created by Joseph on 7/25/2016.
*/
public class RealData implements Callable<String>{
private String para;
public RealData(String para){
this.para=para;
}
@Override
public String call() throws Exception {
StringBuffer sb=new StringBuffer();
for (int i = 0; i < 10; i++) {
sb.append(para);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
}
return sb.toString();
}
}
| apache-2.0 |
bric3/assertj-core | src/main/java/org/assertj/core/util/introspection/PropertySupport.java | 8633 | /**
* 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.
*
* Copyright 2012-2017 the original author or authors.
*/
package org.assertj.core.util.introspection;
import static java.lang.String.format;
import static java.util.Collections.emptyList;
import static java.util.Collections.unmodifiableList;
import static org.assertj.core.util.IterableUtil.isNullOrEmpty;
import static org.assertj.core.util.Preconditions.checkArgument;
import static org.assertj.core.util.introspection.Introspection.getPropertyGetter;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import org.assertj.core.util.VisibleForTesting;
/**
* Utility methods for properties access.
*
* @author Joel Costigliola
* @author Alex Ruiz
* @author Nicolas François
* @author Florent Biville
*/
public class PropertySupport {
private static final String SEPARATOR = ".";
private static final PropertySupport INSTANCE = new PropertySupport();
/**
* Returns the singleton instance of this class.
*
* @return the singleton instance of this class.
*/
public static PropertySupport instance() {
return INSTANCE;
}
@VisibleForTesting
PropertySupport() {
}
/**
* Returns a <code>{@link List}</code> containing the values of the given property name, from the elements of the
* given <code>{@link Iterable}</code>. If the given {@code Iterable} is empty or {@code null}, this method will
* return an empty {@code List}. This method supports nested properties (e.g. "address.street.number").
*
* @param propertyName the name of the property. It may be a nested property. It is left to the clients to validate
* for {@code null} or empty.
* @param target the given {@code Iterable}.
* @return an {@code Iterable} containing the values of the given property name, from the elements of the given
* {@code Iterable}.
* @throws IntrospectionError if an element in the given {@code Iterable} does not have a property with a matching
* name.
*/
public <T> List<T> propertyValues(String propertyName, Class<T> clazz, Iterable<?> target) {
if (isNullOrEmpty(target)) {
return emptyList();
}
if (isNestedProperty(propertyName)) {
String firstPropertyName = popPropertyNameFrom(propertyName);
Iterable<Object> propertyValues = propertyValues(firstPropertyName, Object.class, target);
// extract next sub-property values until reaching the last sub-property
return propertyValues(nextPropertyNameFrom(propertyName), clazz, propertyValues);
}
return simplePropertyValues(propertyName, clazz, target);
}
/**
* Static variant of {@link #propertyValueOf(String, Class, Object)} for syntactic sugar.
* <p>
*
* @param propertyName the name of the property. It may be a nested property. It is left to the clients to validate
* for {@code null} or empty.
* @param target the given object
* @param clazz type of property
* @return a the values of the given property name
* @throws IntrospectionError if the given target does not have a property with a matching name.
*/
public static <T> T propertyValueOf(String propertyName, Object target, Class<T> clazz) {
return instance().propertyValueOf(propertyName, clazz, target);
}
private <T> List<T> simplePropertyValues(String propertyName, Class<T> clazz, Iterable<?> target) {
List<T> propertyValues = new ArrayList<>();
for (Object e : target) {
propertyValues.add(e == null ? null : propertyValue(propertyName, clazz, e));
}
return unmodifiableList(propertyValues);
}
private String popPropertyNameFrom(String propertyNameChain) {
if (!isNestedProperty(propertyNameChain)) {
return propertyNameChain;
}
return propertyNameChain.substring(0, propertyNameChain.indexOf(SEPARATOR));
}
private String nextPropertyNameFrom(String propertyNameChain) {
if (!isNestedProperty(propertyNameChain)) {
return "";
}
return propertyNameChain.substring(propertyNameChain.indexOf(SEPARATOR) + 1);
}
/**
* <pre><code class='java'> isNestedProperty("address.street"); // true
* isNestedProperty("address.street.name"); // true
* isNestedProperty("person"); // false
* isNestedProperty(".name"); // false
* isNestedProperty("person."); // false
* isNestedProperty("person.name."); // false
* isNestedProperty(".person.name"); // false
* isNestedProperty("."); // false
* isNestedProperty(""); // false</code></pre>
*/
private boolean isNestedProperty(String propertyName) {
return propertyName.contains(SEPARATOR) && !propertyName.startsWith(SEPARATOR) && !propertyName.endsWith(SEPARATOR);
}
/**
* Return the value of a simple property from a target object.
* <p>
* This only works for simple property, nested property are not supported ! use
* {@link #propertyValueOf(String, Class, Object)}
*
* @param propertyName the name of the property. It may be a nested property. It is left to the clients to validate
* for {@code null} or empty.
* @param target the given object
* @param clazz type of property
* @return a the values of the given property name
* @throws IntrospectionError if the given target does not have a property with a matching name.
*/
@SuppressWarnings("unchecked")
public <T> T propertyValue(String propertyName, Class<T> clazz, Object target) {
Method getter = getPropertyGetter(propertyName, target);
try {
return (T) getter.invoke(target);
} catch (ClassCastException e) {
String msg = format("Unable to obtain the value of the property <'%s'> from <%s> - wrong property type specified <%s>",
propertyName, target, clazz);
throw new IntrospectionError(msg, e);
} catch (Exception unexpected) {
String msg = format("Unable to obtain the value of the property <'%s'> from <%s>", propertyName, target);
throw new IntrospectionError(msg, unexpected);
}
}
/**
* Returns the value of the given property name given target. If the given object is {@code null}, this method will
* return null.<br>
* This method supports nested properties (e.g. "address.street.number").
*
* @param propertyName the name of the property. It may be a nested property. It is left to the clients to validate
* for {@code null} or empty.
* @param clazz the class of property.
* @param target the given Object to extract property from.
* @return the value of the given property name given target.
* @throws IntrospectionError if target object does not have a property with a matching name.
* @throws IllegalArgumentException if propertyName is null.
*/
public <T> T propertyValueOf(String propertyName, Class<T> clazz, Object target) {
checkArgument(propertyName != null, "the property name should not be null.");
// returns null if target is null as we can't extract a property from a null object
// but don't want to raise an exception if we were looking at a nested property
if (target == null) return null;
if (isNestedProperty(propertyName)) {
String firstPropertyName = popPropertyNameFrom(propertyName);
Object propertyValue = propertyValue(firstPropertyName, Object.class, target);
// extract next sub-property values until reaching the last sub-property
return propertyValueOf(nextPropertyNameFrom(propertyName), clazz, propertyValue);
}
return propertyValue(propertyName, clazz, target);
}
/**
* just delegates to {@link #propertyValues(String, Class, Iterable)} with Class being Object.class
*/
public List<Object> propertyValues(String fieldOrPropertyName, Iterable<?> objects) {
return propertyValues(fieldOrPropertyName, Object.class, objects);
}
public boolean publicGetterExistsFor(String fieldName, Object actual) {
try {
getPropertyGetter(fieldName, actual);
} catch (IntrospectionError e) {
return false;
}
return true;
}
}
| apache-2.0 |
tuliobraga/tech-gallery | src/main/java/com/ciandt/techgallery/servlets/ViewTech.java | 587 | package com.ciandt.techgallery.servlets;
import java.io.IOException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@SuppressWarnings("serial")
public class ViewTech extends HttpServlet {
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String urlPage = "/viewTech.html";
if(!req.getQueryString().isEmpty()){
urlPage += "?" + req.getQueryString();
}
resp.setContentType("text/html");
resp.sendRedirect(urlPage);
}
}
| apache-2.0 |
inbloom/secure-data-service | tools/data-tools/src/org/slc/sli/test/edfi/entities/meta/GradeBookEntryMeta.java | 2017 | /*
* Copyright 2012-2013 inBloom, Inc. and its affiliates.
*
* 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.slc.sli.test.edfi.entities.meta;
import java.util.List;
public class GradeBookEntryMeta {
String id;
List<String> learningObjectiveIds;
GradingPeriodMeta gradingPeriod;
SectionMeta section;
String gradebookEntryType;
String dateAssigned;
public void setLearningObjectiveIds(List<String> learningObjectiveIds) {
this.learningObjectiveIds = learningObjectiveIds;
}
public List<String> getLearningObjectiveIds() {
return learningObjectiveIds;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public GradingPeriodMeta getGradingPeriod() {
return gradingPeriod;
}
public void setGradingPeriod(GradingPeriodMeta gradingPeriod) {
this.gradingPeriod = gradingPeriod;
}
public SectionMeta getSection() {
return section;
}
public void setSection(SectionMeta section) {
this.section = section;
}
public String getGradebookEntryType() {
return gradebookEntryType;
}
public void setGradebookEntryType(String gradebookEntryType) {
this.gradebookEntryType = gradebookEntryType;
}
public String getDateAssigned() {
return dateAssigned;
}
public void setDateAssigned(String dateAssigned) {
this.dateAssigned = dateAssigned;
}
}
| apache-2.0 |
joshlong/adaptive-spring | core/src/test/java/savetheenvironment/profiles/mocking/Main.java | 2787 | package savetheenvironment.profiles.mocking;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.StandardEnvironment;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Main {
static AnnotationConfigApplicationContext runWithApplicationContext() {
AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext();
ac.getEnvironment().setActiveProfiles(ServiceConfiguration.PROFILE_VIDEO_YOUTUBE);
ac.register(ServiceConfiguration.class);
ac.refresh();
return ac;
}
public static void main(String[] arrrImAPirate) throws Throwable {
ApplicationContext applicationContext = runWithApplicationContext();
//showEnvironment(applicationContext);
//showPropertySource(applicationContext);
showVideos(applicationContext);
}
private static void showPropertySource(ApplicationContext applicationContext) {
System.out.println();
System.out.println("************ Property Source ***********");
Map<String, Object> map = new HashMap<String, Object>();
map.put("db.username", "scott");
map.put("db.password", "tiger");
MapPropertySource mapPropertySource = new MapPropertySource("dbConfig", map);
((StandardEnvironment) applicationContext.getEnvironment()).getPropertySources().addFirst(mapPropertySource);
System.out.println("DB Username: " + applicationContext.getEnvironment().getProperty("db.username"));
System.out.println("DB Password: " + applicationContext.getEnvironment().getProperty("db.password"));
System.out.println();
System.out.println("DB Url from @PropertySource: " + applicationContext.getEnvironment().getProperty("db.url"));
System.out.println();
}
private static void showVideos(ApplicationContext applicationContext) throws Exception {
VideoSearch videoSearch = applicationContext.getBean(VideoSearch.class);
List<String> videoTitles = videoSearch.lookupVideo("Kevin Nilson");
System.out.println();
System.out.println("************** VIDEO SEARCH RESULTS - YOUTUBE ************** ");
for (String title : videoTitles) {
System.out.println(title);
}
}
private static void showEnvironment(ApplicationContext applicationContext) {
System.out.println();
System.out.println("************ Environment ***********");
System.out.println("User Dir: " + applicationContext.getEnvironment().getProperty("user.dir"));
System.out.println();
}
} | apache-2.0 |
myrosicky/projects | weibo/src/main/java/rmi/MyRemoteClass.java | 932 | package rmi;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
public class MyRemoteClass implements MyRemoteInterface {
public String[] sayYourName(String name) throws RemoteException {
System.err.println("remote reference");
return new String[] { "kick", name };
}
public static void main(String[] args) {
try {
MyRemoteClass myRemoteClass = new MyRemoteClass();
MyRemoteInterface myRemoteInterface = (MyRemoteInterface) UnicastRemoteObject
.exportObject(myRemoteClass, 0);
Registry registry = LocateRegistry.getRegistry();
registry.rebind("myRemoteInterface", myRemoteInterface);
System.err.println("system ready!!");
} catch (RemoteException e) {
e.printStackTrace();
}
}
public Boolean checkIfSuccess() throws RemoteException {
return true;
}
}
| apache-2.0 |
gabedwrds/cas | support/cas-server-support-electrofence/src/test/java/org/apereo/cas/impl/calcs/DateTimeAuthenticationRequestRiskCalculatorTests.java | 5383 | package org.apereo.cas.impl.calcs;
import org.apereo.cas.api.AuthenticationRiskEvaluator;
import org.apereo.cas.api.AuthenticationRiskScore;
import org.apereo.cas.authentication.Authentication;
import org.apereo.cas.authentication.CoreAuthenticationTestUtils;
import org.apereo.cas.config.CasCoreAuthenticationConfiguration;
import org.apereo.cas.config.CasCoreAuthenticationHandlersConfiguration;
import org.apereo.cas.config.CasCoreAuthenticationMetadataConfiguration;
import org.apereo.cas.config.CasCoreAuthenticationPolicyConfiguration;
import org.apereo.cas.config.CasCoreAuthenticationPrincipalConfiguration;
import org.apereo.cas.config.CasCoreAuthenticationSupportConfiguration;
import org.apereo.cas.config.CasCoreConfiguration;
import org.apereo.cas.config.CasCoreHttpConfiguration;
import org.apereo.cas.config.CasCoreServicesConfiguration;
import org.apereo.cas.config.CasCoreTicketsConfiguration;
import org.apereo.cas.config.CasCoreUtilConfiguration;
import org.apereo.cas.config.CasCoreWebConfiguration;
import org.apereo.cas.config.CasDefaultServiceTicketIdGeneratorsConfiguration;
import org.apereo.cas.config.CasPersonDirectoryConfiguration;
import org.apereo.cas.config.ElectronicFenceConfiguration;
import org.apereo.cas.config.support.CasWebApplicationServiceFactoryConfiguration;
import org.apereo.cas.impl.mock.MockTicketGrantingTicketCreatedEventProducer;
import org.apereo.cas.logout.config.CasCoreLogoutConfiguration;
import org.apereo.cas.services.RegisteredService;
import org.apereo.cas.services.RegisteredServiceTestUtils;
import org.apereo.cas.support.events.config.CasCoreEventsConfiguration;
import org.apereo.cas.support.events.dao.CasEventRepository;
import org.apereo.cas.support.geo.config.GoogleMapsGeoCodingConfiguration;
import org.apereo.cas.web.config.CasCookieConfiguration;
import org.apereo.cas.web.flow.config.CasCoreWebflowConfiguration;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.autoconfigure.RefreshAutoConfiguration;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import static org.junit.Assert.*;
/**
* This is {@link DateTimeAuthenticationRequestRiskCalculatorTests}.
*
* @author Misagh Moayyed
* @since 5.1.0
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {RefreshAutoConfiguration.class,
ElectronicFenceConfiguration.class,
CasWebApplicationServiceFactoryConfiguration.class,
CasDefaultServiceTicketIdGeneratorsConfiguration.class,
CasCoreAuthenticationPrincipalConfiguration.class,
CasCoreAuthenticationPolicyConfiguration.class,
CasCoreAuthenticationMetadataConfiguration.class,
CasCoreAuthenticationSupportConfiguration.class,
CasCoreAuthenticationHandlersConfiguration.class,
CasCoreAuthenticationConfiguration.class,
CasCoreHttpConfiguration.class,
CasPersonDirectoryConfiguration.class,
CasCoreServicesConfiguration.class,
GoogleMapsGeoCodingConfiguration.class,
CasCoreWebConfiguration.class,
CasCoreWebflowConfiguration.class,
CasCoreConfiguration.class,
CasCoreTicketsConfiguration.class,
CasCoreLogoutConfiguration.class,
CasCookieConfiguration.class,
CasCoreUtilConfiguration.class,
CasCoreEventsConfiguration.class})
@TestPropertySource(properties = "cas.authn.adaptive.risk.dateTime.enabled=true")
@DirtiesContext
@EnableScheduling
public class DateTimeAuthenticationRequestRiskCalculatorTests {
@Autowired
@Qualifier("casEventRepository")
private CasEventRepository casEventRepository;
@Autowired
@Qualifier("authenticationRiskEvaluator")
private AuthenticationRiskEvaluator authenticationRiskEvaluator;
@Before
public void prepTest() {
MockTicketGrantingTicketCreatedEventProducer.createEvents(this.casEventRepository);
}
@Test
public void verifyTestWhenNoAuthnEventsFoundForUser() {
final Authentication authentication = CoreAuthenticationTestUtils.getAuthentication("datetimeperson");
final RegisteredService service = RegisteredServiceTestUtils.getRegisteredService("test");
final MockHttpServletRequest request = new MockHttpServletRequest();
final AuthenticationRiskScore score = authenticationRiskEvaluator.eval(authentication, service, request);
assertTrue(score.isHighestRisk());
}
@Test
public void verifyTestWhenAuthnEventsFoundForUser() {
final Authentication authentication = CoreAuthenticationTestUtils.getAuthentication("casuser");
final RegisteredService service = RegisteredServiceTestUtils.getRegisteredService("test");
final MockHttpServletRequest request = new MockHttpServletRequest();
final AuthenticationRiskScore score = authenticationRiskEvaluator.eval(authentication, service, request);
assertTrue(score.isLowestRisk());
}
}
| apache-2.0 |
axeolotl/wsrp4cxf | persistence-xml/src/java/org/apache/wsrp4j/persistence/xml/PersistentInformationXML.java | 3611 | /*
* Copyright 2003-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.
*/
package org.apache.wsrp4j.persistence.xml;
import org.apache.wsrp4j.commons.persistence.PersistentInformation;
/**
* This class defines the interface for persistent information needed
* to store and retrieve PersistentDataObjects with castor XML support.
*
* @version $Id: PersistentInformationXML.java 374672 2006-02-03 14:10:58Z cziegeler $
*/
public interface PersistentInformationXML extends PersistentInformation {
/**
* Set the Store directory for the persistent XML files
*
* @param storeDirectory String name of the store
*/
void setStoreDirectory(String storeDirectory);
/**
* Returns the directory for the persistent XML files
*
* @return String nanme of the store
*/
String getStoreDirectory();
/**
* Set the Castor XML mapping file name, fully qualified
*
* @param mappingFileName String fully qualified filename
*/
void setMappingFileName(String mappingFileName);
/**
* Returns the XML mapping file name, fully qualified
*
* @return String fully qualified filename
*/
String getMappingFileName();
/**
* Set the file name stub for persistent XML files. The name contains the
* store directory followed by a file separator and the class name of the
* object to be restored.
*
* @param stub String file name stub
*/
void setFilenameStub(String stub);
/**
* Returns the file name stub for persistent XML files. @see setFilenameStub
*
* @return String file name stub
*/
String getFilenameStub();
/**
* Returns a fully qualified file name for a persistent XML file.
*
* @return String file name
*/
String getFilename();
/**
* Set the fully qualified file name for a persistent XML file.
*
* @param filename String file name
*/
void setFilename(String filename);
/**
* Updates the file name, enhanced by a string token, like a handle to
* idportlet a unique persistent XML file. If a groupID is set, the
* groupID is used instead of the token to build the filename.
*
* @param token String token, like a handle
*/
void updateFileName(String token);
/**
* Returns the file extension used for persistent XML files
*/
String getExtension();
/**
* Set the file extension for persistent XML files.
*
* @param extension String file extension
*/
void setExtension(String extension);
/**
* Set the Separator, to be used in a fully qualified file name.
*
* @return String Separator character
*/
String getSeparator();
/**
* Set the separator character. (e.g. '@')
*
* @param separator String Separator character
*/
void setSeparator(String separator);
/**
* @return this object as String
*/
String toString();
}
| apache-2.0 |
equella/Equella | Source/Plugins/Core/com.equella.core/src/com/tle/web/copyright/AbstractCopyrightFilestoreFilter.java | 4308 | /*
* Licensed to The Apereo Foundation under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* The Apereo Foundation 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.tle.web.copyright;
import com.tle.beans.item.Item;
import com.tle.beans.item.ItemId;
import com.tle.beans.item.ItemKey;
import com.tle.beans.item.attachments.Attachment;
import com.tle.beans.item.attachments.IAttachment;
import com.tle.core.activation.ActivationConstants;
import com.tle.core.copyright.Holding;
import com.tle.core.copyright.Portion;
import com.tle.core.copyright.Section;
import com.tle.core.copyright.service.AgreementStatus;
import com.tle.core.copyright.service.CopyrightService;
import com.tle.core.security.TLEAclManager;
import com.tle.web.viewitem.FilestoreContentFilter;
import com.tle.web.viewitem.FilestoreContentStream;
import com.tle.web.viewurl.ViewAttachmentUrl;
import com.tle.web.viewurl.ViewItemUrl;
import com.tle.web.viewurl.ViewItemUrlFactory;
import java.io.IOException;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public abstract class AbstractCopyrightFilestoreFilter<
H extends Holding, P extends Portion, S extends Section>
implements FilestoreContentFilter {
private static final Log LOGGER = LogFactory.getLog(AbstractCopyrightFilestoreFilter.class);
@Inject private ViewItemUrlFactory urlFactory;
@Inject private TLEAclManager aclService;
@Override
public FilestoreContentStream filter(
FilestoreContentStream contentStream,
HttpServletRequest request,
HttpServletResponse response)
throws IOException {
String filepath = contentStream.getFilepath();
ItemKey itemKey = contentStream.getItemId();
CopyrightService<H, P, S> copyrightService = getCopyrightService();
ItemId itemId = ItemId.fromKey(itemKey);
Item item = copyrightService.getCopyrightedItem(itemId);
if (item != null) {
Attachment attachment = copyrightService.getSectionAttachmentForFilepath(item, filepath);
if (attachment == null) {
return contentStream;
}
AgreementStatus status;
try {
status = copyrightService.getAgreementStatus(item, attachment);
} catch (IllegalStateException bad) {
LOGGER.error("Error getting AgreementStatus", bad); // $NON-NLS-1$
return contentStream;
}
if (status.isInactive()
&& aclService
.filterNonGrantedPrivileges(ActivationConstants.VIEW_INACTIVE_PORTIONS)
.isEmpty()) {
throw copyrightService.createViolation(item);
}
if (status.isNeedsAgreement()) {
// FIXME: This creates /items/ urls, what if they came from
// /integ/ ?
ViewItemUrl vurl = urlFactory.createFullItemUrl(itemKey);
vurl.add(new ViewAttachmentUrl(attachment.getUuid()));
response.sendRedirect(vurl.getHref());
return null;
}
}
return contentStream;
}
@Override
public boolean canView(Item i, IAttachment attach) {
CopyrightService<H, P, S> copyrightService = getCopyrightService();
Item item = copyrightService.getCopyrightedItem(i.getItemId());
if (item != null) {
AgreementStatus status;
try {
status = copyrightService.getAgreementStatus(item, attach);
} catch (IllegalStateException bad) {
return false;
}
if (status.isNeedsAgreement()) {
return false;
}
}
return true;
}
protected abstract CopyrightService<H, P, S> getCopyrightService();
}
| apache-2.0 |
christophd/citrus | core/citrus-api/src/main/java/com/consol/citrus/validation/DefaultEmptyMessageValidator.java | 2319 | /*
* Copyright 2006-2017 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 com.consol.citrus.validation;
import com.consol.citrus.context.TestContext;
import com.consol.citrus.exceptions.ValidationException;
import com.consol.citrus.message.Message;
import com.consol.citrus.validation.context.ValidationContext;
import org.springframework.util.StringUtils;
/**
* Basic message validator is able to verify empty message payloads. Both received and control message must have
* empty message payloads otherwise ths validator will raise some exception.
*
* @author Christoph Deppisch
*/
public class DefaultEmptyMessageValidator extends DefaultMessageValidator {
@Override
public void validateMessage(Message receivedMessage, Message controlMessage,
TestContext context, ValidationContext validationContext) {
if (controlMessage == null || controlMessage.getPayload() == null) {
log.debug("Skip message payload validation as no control message was defined");
return;
}
if (StringUtils.hasText(controlMessage.getPayload(String.class))) {
throw new ValidationException("Empty message validation failed - control message is not empty!");
}
log.debug("Start to verify empty message payload ...");
if (log.isDebugEnabled()) {
log.debug("Received message:\n" + receivedMessage);
log.debug("Control message:\n" + controlMessage);
}
if (StringUtils.hasText(receivedMessage.getPayload(String.class))) {
throw new ValidationException("Validation failed - received message content is not empty!") ;
}
log.info("Message payload is empty as expected: All values OK");
}
}
| apache-2.0 |
jatin9896/incubator-carbondata | core/src/main/java/org/apache/carbondata/core/datamap/DataMapStoreManager.java | 23372 | /*
* 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.carbondata.core.datamap;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.carbondata.common.annotations.InterfaceAudience;
import org.apache.carbondata.common.exceptions.MetadataProcessException;
import org.apache.carbondata.common.exceptions.sql.MalformedDataMapCommandException;
import org.apache.carbondata.common.exceptions.sql.NoSuchDataMapException;
import org.apache.carbondata.common.logging.LogService;
import org.apache.carbondata.common.logging.LogServiceFactory;
import org.apache.carbondata.core.constants.CarbonCommonConstants;
import org.apache.carbondata.core.datamap.dev.DataMapFactory;
import org.apache.carbondata.core.indexstore.BlockletDetailsFetcher;
import org.apache.carbondata.core.indexstore.SegmentPropertiesFetcher;
import org.apache.carbondata.core.indexstore.blockletindex.BlockletDataMapFactory;
import org.apache.carbondata.core.metadata.AbsoluteTableIdentifier;
import org.apache.carbondata.core.metadata.CarbonMetadata;
import org.apache.carbondata.core.metadata.schema.table.CarbonTable;
import org.apache.carbondata.core.metadata.schema.table.DataMapSchema;
import org.apache.carbondata.core.metadata.schema.table.DataMapSchemaStorageProvider;
import org.apache.carbondata.core.metadata.schema.table.DiskBasedDMSchemaStorageProvider;
import org.apache.carbondata.core.metadata.schema.table.RelationIdentifier;
import org.apache.carbondata.core.mutate.SegmentUpdateDetails;
import org.apache.carbondata.core.mutate.UpdateVO;
import org.apache.carbondata.core.statusmanager.SegmentRefreshInfo;
import org.apache.carbondata.core.statusmanager.SegmentUpdateStatusManager;
import org.apache.carbondata.core.util.CarbonProperties;
import org.apache.carbondata.core.util.CarbonSessionInfo;
import org.apache.carbondata.core.util.ThreadLocalSessionInfo;
import static org.apache.carbondata.core.metadata.schema.datamap.DataMapClassProvider.MV;
import static org.apache.carbondata.core.metadata.schema.datamap.DataMapClassProvider.PREAGGREGATE;
/**
* It maintains all the DataMaps in it.
*/
@InterfaceAudience.Internal
public final class DataMapStoreManager {
private static DataMapStoreManager instance = new DataMapStoreManager();
public Map<String, List<TableDataMap>> getAllDataMaps() {
return allDataMaps;
}
/**
* Contains the list of datamaps for each table.
*/
private Map<String, List<TableDataMap>> allDataMaps = new ConcurrentHashMap<>();
/**
* Contains the datamap catalog for each datamap provider.
*/
private Map<String, DataMapCatalog> dataMapCatalogs = null;
private Map<String, TableSegmentRefresher> segmentRefreshMap = new ConcurrentHashMap<>();
private DataMapSchemaStorageProvider provider = new DiskBasedDMSchemaStorageProvider(
CarbonProperties.getInstance().getSystemFolderLocation());
private static final LogService LOGGER =
LogServiceFactory.getLogService(DataMapStoreManager.class.getName());
private DataMapStoreManager() {
}
/**
* It only gives the visible datamaps
*/
List<TableDataMap> getAllVisibleDataMap(CarbonTable carbonTable) throws IOException {
CarbonSessionInfo sessionInfo = ThreadLocalSessionInfo.getCarbonSessionInfo();
List<TableDataMap> allDataMaps = getAllDataMap(carbonTable);
Iterator<TableDataMap> dataMapIterator = allDataMaps.iterator();
while (dataMapIterator.hasNext()) {
TableDataMap dataMap = dataMapIterator.next();
String dbName = carbonTable.getDatabaseName();
String tableName = carbonTable.getTableName();
String dmName = dataMap.getDataMapSchema().getDataMapName();
// TODO: need support get the visible status of datamap without sessionInfo in the future
if (sessionInfo != null) {
boolean isDmVisible = sessionInfo.getSessionParams().getProperty(
String.format("%s%s.%s.%s", CarbonCommonConstants.CARBON_DATAMAP_VISIBLE,
dbName, tableName, dmName), "true").trim().equalsIgnoreCase("true");
if (!isDmVisible) {
LOGGER.warn(String.format("Ignore invisible datamap %s on table %s.%s",
dmName, dbName, tableName));
dataMapIterator.remove();
}
} else {
String message = "Carbon session info is null";
LOGGER.info(message);
}
}
return allDataMaps;
}
/**
* It gives all datamaps except the default datamap.
*
* @return
*/
public List<TableDataMap> getAllDataMap(CarbonTable carbonTable) throws IOException {
List<DataMapSchema> dataMapSchemas = getDataMapSchemasOfTable(carbonTable);
List<TableDataMap> dataMaps = new ArrayList<>();
if (dataMapSchemas != null) {
for (DataMapSchema dataMapSchema : dataMapSchemas) {
RelationIdentifier identifier = dataMapSchema.getParentTables().get(0);
if (dataMapSchema.isIndexDataMap() && identifier.getTableId()
.equals(carbonTable.getTableId())) {
dataMaps.add(getDataMap(carbonTable, dataMapSchema));
}
}
}
return dataMaps;
}
/**
* It gives all datamap schemas of a given table.
*
*/
public List<DataMapSchema> getDataMapSchemasOfTable(CarbonTable carbonTable) throws IOException {
return provider.retrieveSchemas(carbonTable);
}
/**
* It gives all datamap schemas from store.
*/
public List<DataMapSchema> getAllDataMapSchemas() throws IOException {
return provider.retrieveAllSchemas();
}
public DataMapSchema getDataMapSchema(String dataMapName)
throws NoSuchDataMapException, IOException {
return provider.retrieveSchema(dataMapName);
}
/**
* Saves the datamap schema to storage
* @param dataMapSchema
*/
public void saveDataMapSchema(DataMapSchema dataMapSchema) throws IOException {
provider.saveSchema(dataMapSchema);
}
/**
* Drops the datamap schema from storage
* @param dataMapName
*/
public void dropDataMapSchema(String dataMapName) throws IOException {
provider.dropSchema(dataMapName);
}
/**
* Update the datamap schema after table rename
* This should be invoked after changing table name
* @param dataMapSchemaList
* @param newTableName
*/
public void updateDataMapSchema(List<DataMapSchema> dataMapSchemaList,
String newTableName) throws IOException {
List<DataMapSchema> newDataMapSchemas = new ArrayList<>();
for (DataMapSchema dataMapSchema : dataMapSchemaList) {
RelationIdentifier relationIdentifier = dataMapSchema.getRelationIdentifier();
String dataBaseName = relationIdentifier.getDatabaseName();
String tableId = relationIdentifier.getTableId();
String providerName = dataMapSchema.getProviderName();
// if the preaggregate datamap,not be modified the schema
if (providerName.equalsIgnoreCase(PREAGGREGATE.toString())) {
continue;
}
// if the mv datamap,not be modified the relationIdentifier
if (!providerName.equalsIgnoreCase(MV.toString())) {
RelationIdentifier newRelationIdentifier = new RelationIdentifier(dataBaseName,
newTableName, tableId);
dataMapSchema.setRelationIdentifier(newRelationIdentifier);
}
List<RelationIdentifier> newParentTables = new ArrayList<>();
List<RelationIdentifier> parentTables = dataMapSchema.getParentTables();
for (RelationIdentifier identifier : parentTables) {
RelationIdentifier newParentTableIdentifier = new RelationIdentifier(
identifier.getDatabaseName(), newTableName, identifier.getTableId());
newParentTables.add(newParentTableIdentifier);
}
dataMapSchema.setParentTables(newParentTables);
newDataMapSchemas.add(dataMapSchema);
// frist drop old schema
String dataMapName = dataMapSchema.getDataMapName();
dropDataMapSchema(dataMapName);
}
// save new datamap schema to storage
for (DataMapSchema newDataMapSchema : newDataMapSchemas) {
saveDataMapSchema(newDataMapSchema);
}
}
/**
* Register datamap catalog for the datamap provider
* @param dataMapProvider
* @param dataMapSchema
*/
public synchronized void registerDataMapCatalog(DataMapProvider dataMapProvider,
DataMapSchema dataMapSchema) throws IOException {
initializeDataMapCatalogs(dataMapProvider);
String name = dataMapSchema.getProviderName();
DataMapCatalog dataMapCatalog = dataMapCatalogs.get(name);
if (dataMapCatalog == null) {
dataMapCatalog = dataMapProvider.createDataMapCatalog();
if (dataMapCatalog != null) {
dataMapCatalogs.put(name, dataMapCatalog);
dataMapCatalog.registerSchema(dataMapSchema);
}
} else {
dataMapCatalog.registerSchema(dataMapSchema);
}
}
/**
* Unregister datamap catalog.
* @param dataMapSchema
*/
public synchronized void unRegisterDataMapCatalog(DataMapSchema dataMapSchema) {
if (dataMapCatalogs == null) {
return;
}
String name = dataMapSchema.getProviderName();
DataMapCatalog dataMapCatalog = dataMapCatalogs.get(name);
if (dataMapCatalog != null) {
dataMapCatalog.unregisterSchema(dataMapSchema.getDataMapName());
}
}
/**
* Get the datamap catalog for provider.
* @param providerName
* @return
*/
public synchronized DataMapCatalog getDataMapCatalog(DataMapProvider dataMapProvider,
String providerName) throws IOException {
initializeDataMapCatalogs(dataMapProvider);
return dataMapCatalogs.get(providerName);
}
/**
* Initialize by reading all datamaps from store and re register it
* @param dataMapProvider
*/
private void initializeDataMapCatalogs(DataMapProvider dataMapProvider) throws IOException {
if (dataMapCatalogs == null) {
dataMapCatalogs = new ConcurrentHashMap<>();
List<DataMapSchema> dataMapSchemas = getAllDataMapSchemas();
for (DataMapSchema schema : dataMapSchemas) {
DataMapCatalog dataMapCatalog = dataMapCatalogs.get(schema.getProviderName());
if (dataMapCatalog == null) {
dataMapCatalog = dataMapProvider.createDataMapCatalog();
if (null == dataMapCatalog) {
throw new RuntimeException("Internal Error.");
}
dataMapCatalogs.put(schema.getProviderName(), dataMapCatalog);
}
try {
dataMapCatalog.registerSchema(schema);
} catch (Exception e) {
// Ignore the schema
LOGGER.error(e, "Error while registering schema");
}
}
}
}
/**
* It gives the default datamap of the table. Default datamap of any table is BlockletDataMap
*
* @param table
* @return
*/
public TableDataMap getDefaultDataMap(CarbonTable table) {
return getDataMap(table, BlockletDataMapFactory.DATA_MAP_SCHEMA);
}
/**
* Get the datamap for reading data.
*/
public TableDataMap getDataMap(CarbonTable table, DataMapSchema dataMapSchema) {
String tableUniqueName =
table.getAbsoluteTableIdentifier().getCarbonTableIdentifier().getTableUniqueName();
List<TableDataMap> tableIndices = allDataMaps.get(tableUniqueName);
TableDataMap dataMap = null;
if (tableIndices != null) {
dataMap = getTableDataMap(dataMapSchema.getDataMapName(), tableIndices);
}
if (dataMap == null) {
synchronized (tableUniqueName.intern()) {
tableIndices = allDataMaps.get(tableUniqueName);
if (tableIndices != null) {
dataMap = getTableDataMap(dataMapSchema.getDataMapName(), tableIndices);
}
if (dataMap == null) {
try {
dataMap = createAndRegisterDataMap(table, dataMapSchema);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
}
if (dataMap == null) {
throw new RuntimeException("Datamap does not exist");
}
return dataMap;
}
/**
* Return a new datamap instance and registered in the store manager.
* The datamap is created using datamap name, datamap factory class and table identifier.
*/
public DataMapFactory getDataMapFactoryClass(CarbonTable table, DataMapSchema dataMapSchema)
throws MalformedDataMapCommandException {
try {
// try to create datamap by reflection to test whether it is a valid DataMapFactory class
return (DataMapFactory)
Class.forName(dataMapSchema.getProviderName()).getConstructors()[0]
.newInstance(table, dataMapSchema);
} catch (ClassNotFoundException e) {
// try to create DataMapClassProvider instance by taking providerName as short name
return DataMapRegistry.getDataMapFactoryByShortName(table, dataMapSchema);
} catch (Throwable e) {
throw new MetadataProcessException(
"failed to get DataMap factory for'" + dataMapSchema.getProviderName() + "'", e);
}
}
/**
* registered in the store manager.
* The datamap is created using datamap name, datamap factory class and table identifier.
*/
// TODO: make it private
public TableDataMap createAndRegisterDataMap(CarbonTable table,
DataMapSchema dataMapSchema) throws MalformedDataMapCommandException {
DataMapFactory dataMapFactory = getDataMapFactoryClass(table, dataMapSchema);
return registerDataMap(table, dataMapSchema, dataMapFactory);
}
public TableDataMap registerDataMap(CarbonTable table,
DataMapSchema dataMapSchema, DataMapFactory dataMapFactory) {
String tableUniqueName = table.getCarbonTableIdentifier().getTableUniqueName();
// Just update the segmentRefreshMap with the table if not added.
getTableSegmentRefresher(table);
List<TableDataMap> tableIndices = allDataMaps.get(tableUniqueName);
if (tableIndices == null) {
tableIndices = new ArrayList<>();
}
BlockletDetailsFetcher blockletDetailsFetcher;
SegmentPropertiesFetcher segmentPropertiesFetcher = null;
if (dataMapFactory instanceof BlockletDetailsFetcher) {
blockletDetailsFetcher = (BlockletDetailsFetcher) dataMapFactory;
} else {
blockletDetailsFetcher = getBlockletDetailsFetcher(table);
}
segmentPropertiesFetcher = (SegmentPropertiesFetcher) blockletDetailsFetcher;
TableDataMap dataMap = new TableDataMap(table.getAbsoluteTableIdentifier(),
dataMapSchema, dataMapFactory, blockletDetailsFetcher, segmentPropertiesFetcher);
tableIndices.add(dataMap);
allDataMaps.put(tableUniqueName, tableIndices);
return dataMap;
}
private TableDataMap getTableDataMap(String dataMapName, List<TableDataMap> tableIndices) {
TableDataMap dataMap = null;
for (TableDataMap tableDataMap : tableIndices) {
if (tableDataMap.getDataMapSchema().getDataMapName().equals(dataMapName)) {
dataMap = tableDataMap;
break;
}
}
return dataMap;
}
/**
* Clear the invalid segments from all the datamaps of the table
* @param carbonTable
* @param segments
*/
public void clearInvalidSegments(CarbonTable carbonTable, List<Segment> segments)
throws IOException {
getDefaultDataMap(carbonTable).clear(segments);
List<TableDataMap> allDataMap = getAllDataMap(carbonTable);
for (TableDataMap dataMap: allDataMap) {
dataMap.clear(segments);
}
}
/**
* Clear the datamap/datamaps of a table from memory
*
* @param identifier Table identifier
*/
public void clearDataMaps(AbsoluteTableIdentifier identifier) {
CarbonTable carbonTable = getCarbonTable(identifier);
String tableUniqueName = identifier.getCarbonTableIdentifier().getTableUniqueName();
List<TableDataMap> tableIndices = allDataMaps.get(tableUniqueName);
if (null != carbonTable && tableIndices != null) {
try {
DataMapUtil.executeDataMapJobForClearingDataMaps(carbonTable);
} catch (IOException e) {
LOGGER.error(e, "clear dataMap job failed");
// ignoring the exception
}
}
segmentRefreshMap.remove(identifier.uniqueName());
clearDataMaps(tableUniqueName);
allDataMaps.remove(tableUniqueName);
}
/**
* This method returns the carbonTable from identifier
* @param identifier
* @return
*/
public CarbonTable getCarbonTable(AbsoluteTableIdentifier identifier) {
CarbonTable carbonTable = null;
carbonTable = CarbonMetadata.getInstance()
.getCarbonTable(identifier.getDatabaseName(), identifier.getTableName());
if (carbonTable == null) {
try {
carbonTable = CarbonTable
.buildFromTablePath(identifier.getTableName(), identifier.getDatabaseName(),
identifier.getTablePath(), identifier.getCarbonTableIdentifier().getTableId());
} catch (IOException e) {
LOGGER.error("failed to get carbon table from table Path");
// ignoring exception
}
}
return carbonTable;
}
/**
* this methods clears the datamap of table from memory
*/
public void clearDataMaps(String tableUniqName) {
List<TableDataMap> tableIndices = allDataMaps.get(tableUniqName);
if (tableIndices != null) {
for (TableDataMap tableDataMap : tableIndices) {
if (tableDataMap != null) {
// clear the segmentMap in BlockletDetailsFetcher,else the Segment will remain in executor
// and the query fails as we will check whether the blocklet contains in the index or not
tableDataMap.getBlockletDetailsFetcher().clear();
tableDataMap.clear();
}
}
}
allDataMaps.remove(tableUniqName);
}
/**
* Clear the datamap/datamaps of a table from memory and disk
*
* @param identifier Table identifier
*/
public void clearDataMap(AbsoluteTableIdentifier identifier, String dataMapName) {
CarbonTable carbonTable = getCarbonTable(identifier);
String tableUniqueName = identifier.getCarbonTableIdentifier().getTableUniqueName();
List<TableDataMap> tableIndices = allDataMaps.get(tableUniqueName);
if (tableIndices != null) {
int i = 0;
for (TableDataMap tableDataMap : tableIndices) {
if (carbonTable != null && tableDataMap != null && dataMapName
.equalsIgnoreCase(tableDataMap.getDataMapSchema().getDataMapName())) {
try {
DataMapUtil.executeDataMapJobForClearingDataMaps(carbonTable);
tableDataMap.clear();
} catch (IOException e) {
LOGGER.error(e, "clear dataMap job failed");
// ignoring the exception
}
tableDataMap.deleteDatamapData();
tableIndices.remove(i);
break;
}
i++;
}
allDataMaps.put(tableUniqueName, tableIndices);
}
}
/**
* is datamap exist
* @return true if exist, else return false
*/
public boolean isDataMapExist(String dbName, String tableName, String dmName) {
List<TableDataMap> tableDataMaps = allDataMaps.get(dbName + '_' + tableName);
if (tableDataMaps != null) {
for (TableDataMap dm : tableDataMaps) {
if (dm != null && dmName.equalsIgnoreCase(dm.getDataMapSchema().getDataMapName())) {
return true;
}
}
}
return false;
}
/**
* Get the blocklet datamap factory to get the detail information of blocklets
*
* @param table
* @return
*/
private BlockletDetailsFetcher getBlockletDetailsFetcher(CarbonTable table) {
TableDataMap blockletMap = getDataMap(table, BlockletDataMapFactory.DATA_MAP_SCHEMA);
return (BlockletDetailsFetcher) blockletMap.getDataMapFactory();
}
/**
* Returns the singleton instance
*
* @return
*/
public static DataMapStoreManager getInstance() {
return instance;
}
/**
* Get the TableSegmentRefresher for the table. If not existed then add one and return.
*/
public TableSegmentRefresher getTableSegmentRefresher(CarbonTable table) {
String uniqueName = table.getAbsoluteTableIdentifier().uniqueName();
if (segmentRefreshMap.get(uniqueName) == null) {
segmentRefreshMap.put(uniqueName, new TableSegmentRefresher(table));
}
return segmentRefreshMap.get(uniqueName);
}
/**
* Keep track of the segment refresh time.
*/
public static class TableSegmentRefresher {
// This map stores the latest segment refresh time.So in case of update/delete we check the
// time against this map.
private Map<String, SegmentRefreshInfo> segmentRefreshTime = new HashMap<>();
// This map keeps the manual refresh entries from users. It is mainly used for partition
// altering.
private Map<String, Boolean> manualSegmentRefresh = new HashMap<>();
TableSegmentRefresher(CarbonTable table) {
SegmentUpdateStatusManager statusManager = new SegmentUpdateStatusManager(table);
SegmentUpdateDetails[] updateStatusDetails = statusManager.getUpdateStatusDetails();
for (SegmentUpdateDetails updateDetails : updateStatusDetails) {
UpdateVO updateVO = statusManager.getInvalidTimestampRange(updateDetails.getSegmentName());
segmentRefreshTime.put(updateVO.getSegmentId(),
new SegmentRefreshInfo(updateVO.getCreatedOrUpdatedTimeStamp(), 0));
}
}
public boolean isRefreshNeeded(Segment seg, UpdateVO updateVo) throws IOException {
SegmentRefreshInfo segmentRefreshInfo =
seg.getSegmentRefreshInfo(updateVo);
String segmentId = seg.getSegmentNo();
if (segmentRefreshTime.get(segmentId) == null
&& segmentRefreshInfo.getSegmentUpdatedTimestamp() != null) {
segmentRefreshTime.put(segmentId, segmentRefreshInfo);
return true;
}
if (manualSegmentRefresh.get(segmentId) != null && manualSegmentRefresh.get(segmentId)) {
manualSegmentRefresh.put(segmentId, false);
return true;
}
boolean isRefresh = segmentRefreshInfo.compare(segmentRefreshTime.get(segmentId));
if (isRefresh) {
segmentRefreshTime.remove(segmentId);
}
return isRefresh;
}
public void refreshSegments(List<String> segmentIds) {
for (String segmentId : segmentIds) {
manualSegmentRefresh.put(segmentId, true);
}
}
public boolean isRefreshNeeded(String segmentId) {
if (manualSegmentRefresh.get(segmentId) != null && manualSegmentRefresh.get(segmentId)) {
manualSegmentRefresh.put(segmentId, false);
return true;
} else {
return false;
}
}
}
}
| apache-2.0 |
MikeFot/android-crossy-score | app/src/main/java/com/michaelfotiadis/crossyscore/ui/components/addplayer/avatar/ListAvatarViewHolder.java | 629 | package com.michaelfotiadis.crossyscore.ui.components.addplayer.avatar;
import android.view.View;
import android.widget.ImageView;
import com.michaelfotiadis.crossyscore.R;
import com.michaelfotiadis.crossyscore.ui.core.common.viewholder.BaseViewHolder;
import butterknife.Bind;
public final class ListAvatarViewHolder extends BaseViewHolder {
private static final int LAYOUT_ID = R.layout.list_item_single_image;
@Bind(R.id.image)
protected ImageView image;
public ListAvatarViewHolder(final View view) {
super(view);
}
public static int getLayoutId() {
return LAYOUT_ID;
}
} | apache-2.0 |
roadmaptravel/Rome2RioAndroid | library/src/test/java/com/getroadmap/r2rlib/models/DayFlagsTest.java | 2022 | package com.getroadmap.r2rlib.models;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* Created by jan on 28/08/2017.
* test dayflag bitwise and operator
*/
public class DayFlagsTest {
@Test
public void isSunday() throws Exception {
DayFlags dayFlags = new DayFlags(DayFlags.Companion.getSUNDAY());
assertThat(dayFlags.isDay(DayFlags.Companion.getSUNDAY()), is(true));
}
@Test
public void isWeekday() throws Exception {
DayFlags dayFlags = new DayFlags(DayFlags.Companion.getWEEKDAYS());
assertThat(dayFlags.isDay(DayFlags.Companion.getFRIDAY()), is(true));
}
@Test
public void isNotWeekday() throws Exception {
DayFlags dayFlags = new DayFlags(DayFlags.Companion.getWEEKDAYS());
assertThat(dayFlags.isDay(DayFlags.Companion.getSUNDAY()), is(false));
}
@Test
public void isWeekend() throws Exception {
DayFlags dayFlags = new DayFlags(DayFlags.Companion.getWEEKENDS());
assertThat(dayFlags.isDay(DayFlags.Companion.getSATURDAY()), is(true));
}
@Test
public void isNotWeekend() throws Exception {
DayFlags dayFlags = new DayFlags(DayFlags.Companion.getWEEKENDS());
assertThat(dayFlags.isDay(DayFlags.Companion.getTHURSDAY()), is(false));
}
@Test
public void isAlways() throws Exception {
DayFlags dayFlags = new DayFlags(DayFlags.Companion.getEVERYDAY());
assertThat(dayFlags.isDay(DayFlags.Companion.getSATURDAY()), is(true));
}
@Test
public void isAlwaysWeekend() throws Exception {
DayFlags dayFlags = new DayFlags(DayFlags.Companion.getEVERYDAY());
assertThat(dayFlags.isDay(DayFlags.Companion.getWEEKENDS()), is(true));
}
@Test
public void isNever() throws Exception {
DayFlags dayFlags = new DayFlags(DayFlags.Companion.getNEVER());
assertThat(dayFlags.isDay(DayFlags.Companion.getSATURDAY()), is(false));
}
} | apache-2.0 |
gchq/stroom | stroom-core-client/src/main/java/stroom/util/client/JSONUtil.java | 2742 | /*
* Copyright 2016 Crown Copyright
*
* 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 stroom.util.client;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONNumber;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONString;
import com.google.gwt.json.client.JSONValue;
public class JSONUtil {
private JSONUtil() {
// Utility class.
}
public static JSONValue parse(final String json) {
if (json != null && !json.isEmpty()) {
return JSONParser.parseStrict(json);
}
return null;
}
public static JSONObject getObject(final JSONValue v) {
if (v != null) {
return v.isObject();
}
return null;
}
public static JSONArray getArray(final JSONValue v) {
if (v != null) {
return v.isArray();
}
return null;
}
public static String getString(final JSONValue v) {
if (v != null) {
final JSONString jsonString = v.isString();
if (jsonString != null) {
return jsonString.stringValue();
}
}
return null;
}
public static Integer getInteger(final JSONValue v) {
if (v != null) {
final JSONNumber jsonNumber = v.isNumber();
if (jsonNumber != null) {
return Integer.valueOf((int) jsonNumber.doubleValue());
}
}
return null;
}
public static Double getDouble(final JSONValue v) {
if (v != null) {
final JSONNumber jsonNumber = v.isNumber();
if (jsonNumber != null) {
return Double.valueOf(jsonNumber.doubleValue());
}
}
return null;
}
public static String[] getStrings(final JSONValue v) {
String[] strings = new String[0];
final JSONArray array = getArray(v);
if (array != null) {
strings = new String[array.size()];
for (int i = 0; i < array.size(); i++) {
strings[i] = getString(array.get(i));
}
}
return strings;
}
}
| apache-2.0 |
nbsp-team/MaterialFilePicker | library/src/main/java/com/nbsp/materialfilepicker/ui/DirectoryFragment.java | 3395 | package com.nbsp.materialfilepicker.ui;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import com.nbsp.materialfilepicker.R;
import com.nbsp.materialfilepicker.filter.FileFilter;
import com.nbsp.materialfilepicker.utils.FileUtils;
import com.nbsp.materialfilepicker.widget.EmptyRecyclerView;
import java.io.File;
import static java.util.Objects.requireNonNull;
public class DirectoryFragment extends Fragment {
private static final String ARG_FILE = "arg_file_path";
private static final String ARG_FILTER = "arg_filter";
private View mEmptyView;
private File mFile;
private FileFilter mFilter;
private EmptyRecyclerView mDirectoryRecyclerView;
private DirectoryAdapter mDirectoryAdapter;
private FileClickListener mFileClickListener;
@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
mFileClickListener = (FileClickListener) context;
}
@Override
public void onDetach() {
super.onDetach();
mFileClickListener = null;
}
static DirectoryFragment getInstance(
File file,
FileFilter filter
) {
final DirectoryFragment instance = new DirectoryFragment();
final Bundle args = new Bundle();
args.putSerializable(ARG_FILE, file);
args.putSerializable(ARG_FILTER, filter);
instance.setArguments(args);
return instance;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_directory, container, false);
mDirectoryRecyclerView = view.findViewById(R.id.directory_recycler_view);
mEmptyView = view.findViewById(R.id.directory_empty_view);
return view;
}
@Override
public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
initArgs();
initFilesList();
}
private void initFilesList() {
mDirectoryAdapter = new DirectoryAdapter(FileUtils.getFileList(mFile, mFilter));
mDirectoryAdapter.setOnItemClickListener(new ThrottleClickListener() {
@Override
void onItemClickThrottled(View view, int position) {
if (mFileClickListener != null) {
mFileClickListener.onFileClicked(mDirectoryAdapter.getModel(position));
}
}
});
mDirectoryRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mDirectoryRecyclerView.setAdapter(mDirectoryAdapter);
mDirectoryRecyclerView.setEmptyView(mEmptyView);
}
private void initArgs() {
final Bundle arguments = requireNonNull(getArguments());
if (arguments.containsKey(ARG_FILE)) {
mFile = (File) getArguments().getSerializable(ARG_FILE);
}
mFilter = (FileFilter) getArguments().getSerializable(ARG_FILTER);
}
interface FileClickListener {
void onFileClicked(File clickedFile);
}
}
| apache-2.0 |
aseovic/coherence-tools | core/src/main/java/com/seovic/core/factory/LinkedHashMapFactory.java | 1163 | /*
* Copyright 2009 Aleksandar Seovic
*
* 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.seovic.core.factory;
import com.seovic.core.Factory;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* {@link Factory} implementation that creates a <tt>java.util.LinkedHashMap</tt>
* instance.
*
* @author Aleksandar Seovic 2010.11.08
*/
public class LinkedHashMapFactory<K, V>
extends AbstractFactory<Map<K, V>> {
private static final long serialVersionUID = -2766923385818267291L;
/**
* {@inheritDoc}
*/
@Override
public Map<K, V> create() {
return new LinkedHashMap<K, V>();
}
} | apache-2.0 |
xicmiah/see | src/main/java/see/evaluation/processors/AggregatingProcessor.java | 1669 | /*
* Copyright 2011 Vasily Shiyan
*
* 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 see.evaluation.processors;
import see.evaluation.ValueProcessor;
import see.util.Reduce;
import javax.annotation.Nullable;
import static java.util.Arrays.asList;
import static see.util.Reduce.fold;
public class AggregatingProcessor implements ValueProcessor {
private final Iterable<? extends ValueProcessor> processors;
private AggregatingProcessor(Iterable<? extends ValueProcessor> processors) {
this.processors = processors;
}
@Override
public Object apply(@Nullable Object input) {
return fold(input, processors, new Reduce.FoldFunction<ValueProcessor, Object>() {
@Override
public Object apply(Object prev, ValueProcessor arg) {
return arg.apply(prev);
}
});
}
public static ValueProcessor concat(ValueProcessor... processors) {
return new AggregatingProcessor(asList(processors));
}
public static ValueProcessor concat(Iterable<? extends ValueProcessor> processors) {
return new AggregatingProcessor(processors);
}
}
| apache-2.0 |
camachohoracio/Armadillo.Core | Communication/src/main/java/Armadillo/Communication/Impl/Distributed/DistControllerToWorkerHeartBeat.java | 15386 | package Armadillo.Communication.Impl.Distributed;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import org.joda.time.DateTime;
import org.joda.time.Minutes;
import org.joda.time.Seconds;
import Armadillo.Core.Logger;
import Armadillo.Core.ObjectWrapper;
import Armadillo.Communication.Impl.Topic.SubscriberCallbackDel;
import Armadillo.Communication.Impl.Topic.TopicConstants;
import Armadillo.Communication.Impl.Topic.TopicMessage;
import Armadillo.Communication.Impl.Topic.TopicPublisherCache;
import Armadillo.Communication.Impl.Topic.TopicSubscriberCache;
import Armadillo.Core.Concurrent.ThreadWorker;
import Armadillo.Core.Math.RollingWindowStdDev;
import Armadillo.Core.SelfDescribing.ASelfDescribingClass;
import Armadillo.Core.SelfDescribing.SelfDescribingClass;
import Armadillo.Core.Text.StringHelper;
public class DistControllerToWorkerHeartBeat {
public ConcurrentHashMap<String, String> WorkersStatus;
public RollingWindowStdDev PingLatencySecs;
public ConcurrentHashMap<String, DateTime> WorkersPingTimes;
private String m_strControllerId;
private DistController m_distController;
private ThreadWorker<ObjectWrapper> m_clockThreadWorker;
public ConcurrentHashMap<String, DateTime> WorkersJobsInProgress;
public DistControllerToWorkerHeartBeat(DistController distController)
{
try
{
WorkersJobsInProgress = new ConcurrentHashMap<String, DateTime>();
m_distController = distController;
m_strControllerId = distController.ControllerId;
PingLatencySecs = new RollingWindowStdDev(20);
WorkersPingTimes = new ConcurrentHashMap<String, DateTime>();
WorkersStatus = new ConcurrentHashMap<String, String>();
String strTopic = m_distController.GridTopic + EnumDistributed.TopicWorkerToControllerHeartBeat.toString();
TopicSubscriberCache.GetSubscriber(
distController.ServerName,
TopicConstants.PUBLISHER_HEART_BEAT_PORT).Subscribe(
strTopic,
new SubscriberCallbackDel(){
public void invoke(TopicMessage topicMessage) {
OnTopicWorkerToControllerHeartBeat(topicMessage);
};}
);
TopicSubscriberCache.GetSubscriber(
distController.ServerName,
TopicConstants.PUBLISHER_HEART_BEAT_PORT).Subscribe(
EnumDistributed.WorkerJobsToDoTopic.toString(),
new SubscriberCallbackDel(){
public void invoke(TopicMessage topicMessage) {
try{
String strJobId = (String)topicMessage.EventData;
WorkersJobsInProgress.put(strJobId, DateTime.now());
}
catch(Exception ex){
Logger.log(ex);
}
};}
);
m_clockThreadWorker = new ThreadWorker<ObjectWrapper>(){
@Override
public void runTask(ObjectWrapper item) {
try{
while(true)
{
try{
OnClockTick();
}
catch(Exception ex){
Logger.log(ex);
}
finally{
Thread.sleep(3000);
}
}
}
catch(Exception ex){
Logger.log(ex);
}
}
};
m_clockThreadWorker.work();
}
catch (Exception ex)
{
Logger.log(ex);
}
}
private void OnTopicWorkerToControllerHeartBeat(TopicMessage topicmessage)
{
try
{
ASelfDescribingClass workerResponse = (ASelfDescribingClass)(topicmessage.EventData);
String strWorkerId = workerResponse.GetStrValue(EnumDistributed.WorkerId);
DateTime timeSent = new DateTime(workerResponse.GetDateValue(EnumDistributed.TimeControllerToWorker));
DateTime now = DateTime.now();
PingLatencySecs.Update(
Seconds.secondsBetween(timeSent, now).getSeconds());
if (!WorkersPingTimes.containsKey(strWorkerId))
{
String strMessage = "Connected worker [" + strWorkerId + "]";
DistGuiHelper.PublishControllerLog(m_distController, strMessage);
}
WorkersPingTimes.put(strWorkerId, now);
}
catch (Exception ex)
{
Logger.log(ex);
}
}
private void OnClockTick()
{
DistGuiHelper.PublishControllerLog(m_distController, "Started worker pinger...");
while (true)
{
try
{
PingWorker();
CheckAliveWorkers();
//
// flush old jobs in progress
//
ArrayList<String> keysToDelete = new ArrayList<String>();
for(Entry<String, DateTime> kvp : WorkersJobsInProgress.entrySet()){
int intMinutes = Minutes.minutesBetween(
kvp.getValue(),
DateTime.now()).getMinutes();
if(intMinutes > 60){
keysToDelete.add(kvp.getKey());
}
}
for(String strKey : keysToDelete){
WorkersJobsInProgress.remove(strKey);
}
}
catch (Exception ex)
{
Logger.log(ex);
}
try {
Thread.sleep(1000 * DistConstants.PING_WORKER_TIME_SECS);
} catch (InterruptedException e) {
Logger.log(e);
}
}
}
public void CheckWorkersJobsInProgress(
String strJobId,
String strWorkerId) {
try{
if(!WorkersJobsInProgress.containsKey(strJobId)){
WorkersJobsInProgress.put(strJobId, DateTime.now());
}
DateTime lastPingTime = WorkersJobsInProgress.get(strJobId);
int intTotalSeconds = Seconds.secondsBetween(lastPingTime, DateTime.now()).getSeconds();
if(intTotalSeconds > 120){
//
// job is no longer being done by worker
//
RemoveWorker(strWorkerId, intTotalSeconds);
WorkersPingTimes.remove(strWorkerId);
}
}
catch(Exception ex){
Logger.log(ex);
}
}
private void CheckAliveWorkers()
{
try
{
DateTime now = DateTime.now();
for (Map.Entry<String, DateTime> kvp : WorkersPingTimes.entrySet())
{
int intTotalSeconds = (int) Seconds.secondsBetween(kvp.getValue(), now).getSeconds();
if (intTotalSeconds > DistConstants.ALIVE_WORKER_TIME_SECS)
{
RemoveWorker(kvp.getKey(), intTotalSeconds);
WorkersPingTimes.remove(kvp.getKey());
}
else
{
WorkersStatus.put(kvp.getKey(), EnumDistributed.Connected.toString());
}
}
}
catch (Exception ex)
{
Logger.log(ex);
}
}
public void RemoveJobsInProgressFromRequestor(String strRequestorName)
{
try
{
Set<Entry<String, ASelfDescribingClass>> jobsInProgressArr;
synchronized (m_distController.DistControllerJobPull.JobsInProgressLock)
{
jobsInProgressArr = m_distController.JobsToDoMap.entrySet();
}
for (Entry<String, ASelfDescribingClass> kvp : jobsInProgressArr)
{
boolean blnDoRemove = false;
String strJobId = kvp.getKey();
ASelfDescribingClass currParams = kvp.getValue();
String strCurrRequestorName = currParams.TryGetStrValue(
EnumDistributed.RequestorName);
if (!StringHelper.IsNullOrEmpty(strCurrRequestorName))
{
if (strCurrRequestorName.equals(strRequestorName))
{
blnDoRemove = true;
}
}
else
{
blnDoRemove = true;
}
if (blnDoRemove)
{
synchronized (m_distController.DistControllerJobPull.JobsInProgressLock)
{
ASelfDescribingClass resultTsEv;
if (m_distController.JobsToDoMap.containsKey(
kvp.getKey()))
{
resultTsEv = m_distController.JobsToDoMap.get(
kvp.getKey());
m_distController.JobsToDoMap.remove(
kvp.getKey());
String strMessage = "Calc engine successfully flushed job [" + strJobId +
"] from client [" + strRequestorName + "]";
SelfDescribingClass resultObj = new SelfDescribingClass();
resultObj.SetClassName(
getClass().getName() + "_ResultFlush");
DistGuiHelper.PublishControllerLog(
m_distController,
strMessage);
resultObj.SetBlnValue(
EnumCalcCols.IsClientDisconnected,
true);
resultObj.SetStrValue(
EnumCalcCols.Error,
strMessage);
resultTsEv.SetObjValueToDict(
EnumCalcCols.Result,
resultObj);
}
if(m_distController.DistControllerJobPull.MapJobIdToWorkerId.containsKey(
strJobId)){
ASelfDescribingClass jobLog = m_distController.DistControllerJobPull.MapJobIdToWorkerId.get(
strJobId);
m_distController.DistControllerJobPull.MapJobIdToWorkerId.remove(
strJobId);
DistGuiHelper.PublishJobLogStatus(
m_distController,
jobLog,
"Removed");
}
}
}
}
}
catch (Exception ex)
{
Logger.log(ex);
}
}
public boolean IsWorkerConnected(String strWorkerId)
{
if(!WorkersStatus.containsKey(strWorkerId))
{
return true;
}
String workerStatus = WorkersStatus.get(strWorkerId);
return workerStatus.equals(EnumDistributed.Connected.toString());
}
private void RemoveWorker(
String strWorkerId,
int intTotalSeconds)
{
try
{
DistGuiHelper.PublishControllerLog(
m_distController,
"Disconnected worker[" +
strWorkerId + "][" + intTotalSeconds + "]secs");
WorkersStatus.put(strWorkerId, EnumDistributed.Disconnected.toString());
List<String> assignedJobs = new ArrayList<String>();
for(Entry<String, ASelfDescribingClass> kvp2 :
m_distController.DistControllerJobPull.MapJobIdToWorkerId.entrySet()){
if(DistControllerJobLogger.GetWorkerId(kvp2.getValue()).equals(strWorkerId)){
assignedJobs.add(kvp2.getKey());
}
}
// (from n in m_distController.DistControllerJobPull.MapJobIdToWorkerId
// where DistControllerJobLogger.GetWorkerId(n.Value).Equals(strWorkerId)
// select n.Key).ToList();
for(String strJobId : assignedJobs)
{
if(m_distController.DistControllerJobPull.MapJobIdToWorkerId.containsKey(strJobId))
{
ASelfDescribingClass jobLog =
m_distController.DistControllerJobPull.MapJobIdToWorkerId.get(strJobId);
m_distController.DistControllerJobPull.MapJobIdToWorkerId.remove(
strJobId);
DistGuiHelper.PublishJobLogStatus(
m_distController,
jobLog,
"ClientDisconnected");
DistGuiHelper.PublishControllerLog(m_distController,
"Removed worker[" +
strWorkerId + "]. Job id [" +
strJobId +"]");
}
}
}
catch (Exception ex)
{
Logger.log(ex);
}
}
private void PingWorker()
{
try
{
if(m_distController.DistTopicQueue == null)
{
return;
}
SelfDescribingClass calcParams = new SelfDescribingClass();
calcParams.SetClassName(EnumDistributed.HeartBeatWorkerClass);
calcParams.SetStrValue(
EnumDistributed.ControllerId,
m_strControllerId);
calcParams.SetDateValue(
EnumDistributed.TimeControllerToWorker,
DateTime.now().toDate());
calcParams.SetDateValue(
EnumDistributed.Time,
DateTime.now().toDate());
String strTopic = m_distController.GridTopic +
EnumDistributed.TopicControllerToWorkerHeartBeat.toString();
TopicPublisherCache.GetPublisher(
m_distController.ServerName,
TopicConstants.SUBSCRIBER_HEART_BEAT_PORT).SendMessageImmediately(
calcParams,
strTopic);
}
catch (Exception ex)
{
Logger.log(ex);
}
}
public void Dispose()
{
if(WorkersStatus != null)
{
WorkersStatus.clear();
WorkersStatus = null;
}
if(PingLatencySecs != null)
{
PingLatencySecs.Dispose();
PingLatencySecs = null;
}
if(WorkersPingTimes != null)
{
WorkersPingTimes.clear();
WorkersPingTimes = null;
}
m_distController = null;
if(m_clockThreadWorker != null)
{
m_clockThreadWorker.Dispose();
m_clockThreadWorker = null;
}
}
}
| apache-2.0 |
dbeaver/dbeaver | plugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/model/navigator/DBNNodeExtendable.java | 987 | /*
* DBeaver - Universal Database Manager
* 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.model.navigator;
import org.jkiss.code.NotNull;
import java.util.List;
/**
* DBNNodeExtendable
*/
public interface DBNNodeExtendable
{
@NotNull
List<DBNNode> getExtraNodes();
void addExtraNode(@NotNull DBNNode node, boolean reflect);
void removeExtraNode(@NotNull DBNNode node);
} | apache-2.0 |
FTFL02-ANDROID/Faravy | iCareFaravy/src/com/faravy/icare/ViewDoctorActivity.java | 5472 | package com.faravy.icare;
import java.util.ArrayList;
import android.app.ActionBar;
import android.app.Activity;
import android.content.ContentProviderOperation;
import android.content.Intent;
import android.content.OperationApplicationException;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.RemoteException;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.CommonDataKinds.StructuredName;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.RawContacts;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.faravy.database.DoctorDataSource;
import com.faravy.modelclass.Doctor;
public class ViewDoctorActivity extends Activity {
Doctor mDoctor;
DoctorDataSource mDataSource;
TextView mEtName;
TextView mEtDetail;
TextView mEtDate;
TextView mEtPhone;
TextView mEtEmail;
String mID = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_doctor);
ActionBar ab = getActionBar();
ColorDrawable colorDrawable = new ColorDrawable(
Color.parseColor("#0080FF"));
ab.setBackgroundDrawable(colorDrawable);
mEtName = (TextView) findViewById(R.id.addName);
mEtDetail = (TextView) findViewById(R.id.addDetails);
mEtDate = (TextView) findViewById(R.id.addAppointment);
mEtPhone = (TextView) findViewById(R.id.addPhone);
mEtEmail = (TextView) findViewById(R.id.addEmail);
Intent mActivityIntent = getIntent();
mID = mActivityIntent.getStringExtra("mId");
mDataSource = new DoctorDataSource(this);
mDoctor = mDataSource.singleDoctor(mID);
String name = mDoctor.getmName();
String detail = mDoctor.getmDetails();
String date = mDoctor.getmAppoinment();
String phone = mDoctor.getmPhone();
String email = mDoctor.getmEmail();
mEtName.setText(name);
mEtDetail.setText(detail);
mEtDate.setText(date);
mEtPhone.setText(phone);
mEtEmail.setText(email);
}
public void makeCall(View v) {
String number = mEtPhone.getText().toString().trim();
Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:"
+ number));
startActivity(callIntent);
}
public void sendSms(View v) {
String number = mEtPhone.getText().toString().trim();
Intent smsIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("sms:"
+ number));
startActivity(smsIntent);
}
public void sendEmail(View v) {
String email = mEtEmail.getText().toString();
/*Intent emailIntent = new Intent(Intent.ACTION_SEND,
Uri.parse("mailto:"));
emailIntent.setType("text/plain");
emailIntent.putExtra(Intent.EXTRA_EMAIL, email);
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Your subject");
emailIntent.putExtra(Intent.EXTRA_TEXT, "Email message goes here");
startActivity(Intent.createChooser(emailIntent, "Send mail..."));*/
Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(
"mailto", email, null));
startActivity(Intent.createChooser(intent, "Send email..."));
}
public void addToContact(View v) {
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
int rawContactInsertIndex = ops.size();
ops.add(ContentProviderOperation.newInsert(RawContacts.CONTENT_URI)
.withValue(RawContacts.ACCOUNT_TYPE, null)
.withValue(RawContacts.ACCOUNT_NAME, null).build());
ops.add(ContentProviderOperation
.newInsert(Data.CONTENT_URI)
.withValueBackReference(Data.RAW_CONTACT_ID,
rawContactInsertIndex)
.withValue(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE)
.withValue(StructuredName.DISPLAY_NAME,
mEtName.getText().toString()) // Name of the
// person
.build());
ops.add(ContentProviderOperation
.newInsert(Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID,
rawContactInsertIndex)
.withValue(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE)
.withValue(Phone.NUMBER, mEtPhone.getText().toString()) // Number
// of
// the
// person
.withValue(Phone.TYPE, Phone.TYPE_MOBILE).build()); // Type of
// mobile
// number
try {
getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
Toast.makeText(getApplicationContext(),
"Successfully Contract Added !!!!!!!", Toast.LENGTH_LONG)
.show();
} catch (RemoteException e) {
// error
} catch (OperationApplicationException e) {
// error
}
Intent contacts = new Intent(Intent.ACTION_VIEW,
ContactsContract.Contacts.CONTENT_URI);
startActivity(contacts);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.view_doctor, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
| apache-2.0 |
jiro-aqua/JotaTextEditor | app/src/main/java/jp/sblo/pandora/jota/text/EditableInputConnection.java | 4042 | /*
* Copyright (C) 2007-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 jp.sblo.pandora.jota.text;
import android.os.Bundle;
import android.text.Editable;
import android.text.method.KeyListener;
import android.util.Log;
import android.view.inputmethod.BaseInputConnection;
import android.view.inputmethod.CompletionInfo;
import android.view.inputmethod.ExtractedText;
import android.view.inputmethod.ExtractedTextRequest;
public class EditableInputConnection extends BaseInputConnection {
private static final boolean DEBUG = false;
private static final String TAG = "EditableInputConnection";
private final TextView mTextView;
public EditableInputConnection(TextView textview) {
super(textview, true);
mTextView = textview;
}
public Editable getEditable() {
TextView tv = mTextView;
if (tv != null) {
return tv.getEditableText();
}
return null;
}
public boolean beginBatchEdit() {
mTextView.beginBatchEdit();
return true;
}
public boolean endBatchEdit() {
mTextView.endBatchEdit();
return true;
}
public boolean clearMetaKeyStates(int states) {
final Editable content = getEditable();
if (content == null) return false;
KeyListener kl = mTextView.getKeyListener();
if (kl != null) {
try {
kl.clearMetaKeyState(mTextView, content, states);
} catch (AbstractMethodError e) {
// This is an old listener that doesn't implement the
// new method.
}
}
return true;
}
public boolean commitCompletion(CompletionInfo text) {
if (DEBUG) Log.v(TAG, "commitCompletion " + text);
mTextView.beginBatchEdit();
mTextView.onCommitCompletion(text);
mTextView.endBatchEdit();
return true;
}
public boolean performEditorAction(int actionCode) {
if (DEBUG) Log.v(TAG, "performEditorAction " + actionCode);
mTextView.onEditorAction(actionCode);
return true;
}
public boolean performContextMenuAction(int id) {
if (DEBUG) Log.v(TAG, "performContextMenuAction " + id);
mTextView.beginBatchEdit();
mTextView.onTextContextMenuItem(id);
mTextView.endBatchEdit();
return true;
}
public ExtractedText getExtractedText(ExtractedTextRequest request, int flags) {
if (mTextView != null) {
ExtractedText et = new ExtractedText();
if (mTextView.extractText(request, et)) {
if ((flags&GET_EXTRACTED_TEXT_MONITOR) != 0) {
mTextView.setExtracting(request);
}
return et;
}
}
return null;
}
public boolean performPrivateCommand(String action, Bundle data) {
mTextView.onPrivateIMECommand(action, data);
return true;
}
@Override
public boolean commitText(CharSequence text, int newCursorPosition) {
if (mTextView == null) {
return super.commitText(text, newCursorPosition);
}
CharSequence errorBefore = mTextView.getError();
boolean success = super.commitText(text, newCursorPosition);
CharSequence errorAfter = mTextView.getError();
if (errorAfter != null && errorBefore == errorAfter) {
mTextView.setError(null, null);
}
return success;
}
}
| apache-2.0 |
kvr000/zbynek-java-exp | netty-exp/netty5-exp/netty5-datagram-listener-exp/src/main/java/cz/znj/kvr/sw/exp/java/netty/netty/MyEmbeddedEventLoop.java | 7288 | package cz.znj.kvr.sw.exp.java.netty.netty;
/*
* Copyright 2012 The Netty Project
*
* The Netty 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.
*/
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelHandlerInvoker;
import io.netty.channel.ChannelPromise;
import io.netty.channel.DefaultChannelPromise;
import io.netty.channel.EventLoop;
import io.netty.channel.EventLoopGroup;
import io.netty.util.concurrent.AbstractScheduledEventExecutor;
import io.netty.util.concurrent.EventExecutor;
import io.netty.util.concurrent.Future;
import java.net.SocketAddress;
import java.util.ArrayDeque;
import java.util.Queue;
import java.util.concurrent.TimeUnit;
import static io.netty.channel.ChannelHandlerInvokerUtil.invokeBindNow;
import static io.netty.channel.ChannelHandlerInvokerUtil.invokeChannelActiveNow;
import static io.netty.channel.ChannelHandlerInvokerUtil.invokeChannelInactiveNow;
import static io.netty.channel.ChannelHandlerInvokerUtil.invokeChannelReadCompleteNow;
import static io.netty.channel.ChannelHandlerInvokerUtil.invokeChannelReadNow;
import static io.netty.channel.ChannelHandlerInvokerUtil.invokeChannelRegisteredNow;
import static io.netty.channel.ChannelHandlerInvokerUtil.invokeChannelUnregisteredNow;
import static io.netty.channel.ChannelHandlerInvokerUtil.invokeChannelWritabilityChangedNow;
import static io.netty.channel.ChannelHandlerInvokerUtil.invokeCloseNow;
import static io.netty.channel.ChannelHandlerInvokerUtil.invokeConnectNow;
import static io.netty.channel.ChannelHandlerInvokerUtil.invokeDeregisterNow;
import static io.netty.channel.ChannelHandlerInvokerUtil.invokeDisconnectNow;
import static io.netty.channel.ChannelHandlerInvokerUtil.invokeExceptionCaughtNow;
import static io.netty.channel.ChannelHandlerInvokerUtil.invokeFlushNow;
import static io.netty.channel.ChannelHandlerInvokerUtil.invokeReadNow;
import static io.netty.channel.ChannelHandlerInvokerUtil.invokeUserEventTriggeredNow;
import static io.netty.channel.ChannelHandlerInvokerUtil.invokeWriteNow;
public final class MyEmbeddedEventLoop extends AbstractScheduledEventExecutor implements ChannelHandlerInvoker, EventLoop
{
public static MyEmbeddedEventLoop getInstance()
{
return instance;
}
private static MyEmbeddedEventLoop instance = new MyEmbeddedEventLoop();
private final Queue<Runnable> tasks = new ArrayDeque<Runnable>(2);
@Override
public EventLoop unwrap() {
return this;
}
@Override
public EventLoopGroup parent() {
return (EventLoopGroup) super.parent();
}
@Override
public EventLoop next() {
return (EventLoop) super.next();
}
@Override
public void execute(Runnable command) {
if (command == null) {
throw new NullPointerException("command");
}
tasks.add(command);
}
void runTasks() {
for (;;) {
Runnable task = tasks.poll();
if (task == null) {
break;
}
task.run();
}
}
long runScheduledTasks() {
long time = AbstractScheduledEventExecutor.nanoTime();
for (;;) {
Runnable task = pollScheduledTask(time);
if (task == null) {
return nextScheduledTaskNano();
}
task.run();
}
}
long nextScheduledTask() {
return nextScheduledTaskNano();
}
@Override
protected void cancelScheduledTasks() {
super.cancelScheduledTasks();
}
@Override
public Future<?> shutdownGracefully(long quietPeriod, long timeout, TimeUnit unit) {
throw new UnsupportedOperationException();
}
@Override
public Future<?> terminationFuture() {
throw new UnsupportedOperationException();
}
@Override
@Deprecated
public void shutdown() {
throw new UnsupportedOperationException();
}
@Override
public boolean isShuttingDown() {
return false;
}
@Override
public boolean isShutdown() {
return false;
}
@Override
public boolean isTerminated() {
return false;
}
@Override
public boolean awaitTermination(long timeout, TimeUnit unit) {
return false;
}
@Override
public ChannelFuture register(Channel channel) {
return register(channel, new DefaultChannelPromise(channel, this));
}
@Override
public ChannelFuture register(Channel channel, ChannelPromise promise) {
channel.unsafe().register(this, promise);
return promise;
}
@Override
public boolean inEventLoop() {
return true;
}
@Override
public boolean inEventLoop(Thread thread) {
return true;
}
@Override
public ChannelHandlerInvoker asInvoker() {
return this;
}
@Override
public EventExecutor executor() {
return this;
}
@Override
public void invokeChannelRegistered(ChannelHandlerContext ctx) {
invokeChannelRegisteredNow(ctx);
}
@Override
public void invokeChannelUnregistered(ChannelHandlerContext ctx) {
invokeChannelUnregisteredNow(ctx);
}
@Override
public void invokeChannelActive(ChannelHandlerContext ctx) {
invokeChannelActiveNow(ctx);
}
@Override
public void invokeChannelInactive(ChannelHandlerContext ctx) {
invokeChannelInactiveNow(ctx);
}
@Override
public void invokeExceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
invokeExceptionCaughtNow(ctx, cause);
}
@Override
public void invokeUserEventTriggered(ChannelHandlerContext ctx, Object event) {
invokeUserEventTriggeredNow(ctx, event);
}
@Override
public void invokeChannelRead(ChannelHandlerContext ctx, Object msg) {
invokeChannelReadNow(ctx, msg);
}
@Override
public void invokeChannelReadComplete(ChannelHandlerContext ctx) {
invokeChannelReadCompleteNow(ctx);
}
@Override
public void invokeChannelWritabilityChanged(ChannelHandlerContext ctx) {
invokeChannelWritabilityChangedNow(ctx);
}
@Override
public void invokeBind(ChannelHandlerContext ctx, SocketAddress localAddress, ChannelPromise promise) {
invokeBindNow(ctx, localAddress, promise);
}
@Override
public void invokeConnect(
ChannelHandlerContext ctx,
SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise) {
invokeConnectNow(ctx, remoteAddress, localAddress, promise);
}
@Override
public void invokeDisconnect(ChannelHandlerContext ctx, ChannelPromise promise) {
invokeDisconnectNow(ctx, promise);
}
@Override
public void invokeClose(ChannelHandlerContext ctx, ChannelPromise promise) {
invokeCloseNow(ctx, promise);
}
@Override
public void invokeDeregister(ChannelHandlerContext ctx, final ChannelPromise promise) {
invokeDeregisterNow(ctx, promise);
}
@Override
public void invokeRead(ChannelHandlerContext ctx) {
invokeReadNow(ctx);
}
@Override
public void invokeWrite(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
invokeWriteNow(ctx, msg, promise);
}
@Override
public void invokeFlush(ChannelHandlerContext ctx) {
invokeFlushNow(ctx);
}
}
| apache-2.0 |
googlemaps/android-maps-utils | demo/src/v3/java/com/google/maps/android/utils/demo/DistanceDemoActivity.java | 3517 | /**
* DO NOT EDIT THIS FILE.
*
* This source code was autogenerated from source code within the `demo/src/gms` directory
* and is not intended for modifications. If any edits should be made, please do so in the
* corresponding file under the `demo/src/gms` directory.
*/
/*
* Copyright 2013 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.maps.android.utils.demo;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.libraries.maps.CameraUpdateFactory;
import com.google.android.libraries.maps.GoogleMap;
import com.google.android.libraries.maps.model.LatLng;
import com.google.android.libraries.maps.model.Marker;
import com.google.android.libraries.maps.model.MarkerOptions;
import com.google.android.libraries.maps.model.Polyline;
import com.google.android.libraries.maps.model.PolylineOptions;
import com.google.maps.android.SphericalUtil;
import java.util.Arrays;
public class DistanceDemoActivity extends BaseDemoActivity implements GoogleMap.OnMarkerDragListener {
private TextView mTextView;
private Marker mMarkerA;
private Marker mMarkerB;
private Polyline mPolyline;
@Override
protected int getLayoutId() {
return R.layout.distance_demo;
}
@Override
protected void startDemo(boolean isRestore) {
mTextView = findViewById(R.id.textView);
if (!isRestore) {
getMap().moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(-33.8256, 151.2395), 10));
}
getMap().setOnMarkerDragListener(this);
mMarkerA = getMap().addMarker(new MarkerOptions().position(new LatLng(-33.9046, 151.155)).draggable(true));
mMarkerB = getMap().addMarker(new MarkerOptions().position(new LatLng(-33.8291, 151.248)).draggable(true));
mPolyline = getMap().addPolyline(new PolylineOptions().geodesic(true));
Toast.makeText(this, "Drag the markers!", Toast.LENGTH_LONG).show();
showDistance();
}
private void showDistance() {
double distance = SphericalUtil.computeDistanceBetween(mMarkerA.getPosition(), mMarkerB.getPosition());
mTextView.setText("The markers are " + formatNumber(distance) + " apart.");
}
private void updatePolyline() {
mPolyline.setPoints(Arrays.asList(mMarkerA.getPosition(), mMarkerB.getPosition()));
}
private String formatNumber(double distance) {
String unit = "m";
if (distance < 1) {
distance *= 1000;
unit = "mm";
} else if (distance > 1000) {
distance /= 1000;
unit = "km";
}
return String.format("%4.3f%s", distance, unit);
}
@Override
public void onMarkerDragEnd(Marker marker) {
showDistance();
updatePolyline();
}
@Override
public void onMarkerDragStart(Marker marker) {
}
@Override
public void onMarkerDrag(Marker marker) {
showDistance();
updatePolyline();
}
}
| apache-2.0 |
sekigor/hawkular-agent | hawkular-wildfly-agent/src/main/java/org/hawkular/agent/monitor/extension/RemoteJMXAttributes.java | 3027 | /*
* Copyright 2015 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hawkular.agent.monitor.extension;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.SimpleAttributeDefinition;
import org.jboss.as.controller.SimpleAttributeDefinitionBuilder;
import org.jboss.as.controller.registry.AttributeAccess;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ModelType;
public interface RemoteJMXAttributes {
SimpleAttributeDefinition ENABLED = new SimpleAttributeDefinitionBuilder("enabled",
ModelType.BOOLEAN)
.setAllowNull(true)
.setDefaultValue(new ModelNode(true))
.setAllowExpression(true)
.addFlag(AttributeAccess.Flag.RESTART_RESOURCE_SERVICES)
.build();
SimpleAttributeDefinition URL = new SimpleAttributeDefinitionBuilder("url",
ModelType.STRING)
.setAllowNull(false)
.setAllowExpression(true)
.addFlag(AttributeAccess.Flag.RESTART_RESOURCE_SERVICES)
.build();
SimpleAttributeDefinition USERNAME = new SimpleAttributeDefinitionBuilder("username",
ModelType.STRING)
.setAllowNull(true)
.setAllowExpression(true)
.addFlag(AttributeAccess.Flag.RESTART_RESOURCE_SERVICES)
.build();
SimpleAttributeDefinition PASSWORD = new SimpleAttributeDefinitionBuilder("password",
ModelType.STRING)
.setAllowNull(true)
.setAllowExpression(true)
.addFlag(AttributeAccess.Flag.RESTART_RESOURCE_SERVICES)
.build();
SimpleAttributeDefinition SECURITY_REALM = new SimpleAttributeDefinitionBuilder("securityRealm",
ModelType.STRING)
.setAllowNull(true)
.setAllowExpression(true)
.addFlag(AttributeAccess.Flag.RESTART_RESOURCE_SERVICES)
.build();
SimpleAttributeDefinition RESOURCE_TYPE_SETS = new SimpleAttributeDefinitionBuilder(
"resourceTypeSets",
ModelType.STRING)
.setAllowNull(true)
.setAllowExpression(true)
.addFlag(AttributeAccess.Flag.RESTART_RESOURCE_SERVICES)
.build();
AttributeDefinition[] ATTRIBUTES = {
ENABLED,
URL,
USERNAME,
PASSWORD,
SECURITY_REALM,
RESOURCE_TYPE_SETS
};
}
| apache-2.0 |
epam/DLab | integration-tests/src/main/java/com/epam/dlab/automation/http/HttpStatusCode.java | 1003 | /***************************************************************************
Copyright (c) 2016, EPAM SYSTEMS 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.epam.dlab.automation.http;
public class HttpStatusCode {
public static final int OK = 200;
public static final int UNAUTHORIZED = 401;
public static final int ACCEPTED = 202;
public static final int NOT_FOUND = 404;
private HttpStatusCode() {
}
}
| apache-2.0 |
clafonta/canyon | test/service/org/tll/canyon/service/AssetRoleManagerTest.java | 3376 |
package org.tll.canyon.service;
import java.util.List;
import java.util.ArrayList;
import org.jmock.Mock;
import org.springframework.orm.ObjectRetrievalFailureException;
import org.tll.canyon.dao.AssetRoleDao;
import org.tll.canyon.model.AssetRole;
import org.tll.canyon.service.BaseManagerTestCase;
import org.tll.canyon.service.impl.AssetRoleManagerImpl;
public class AssetRoleManagerTest extends BaseManagerTestCase {
private final String assetRoleId = "1";
private AssetRoleManagerImpl assetRoleManager = new AssetRoleManagerImpl();
private Mock assetRoleDao = null;
protected void setUp() throws Exception {
super.setUp();
assetRoleDao = new Mock(AssetRoleDao.class);
assetRoleManager.setAssetRoleDao((AssetRoleDao) assetRoleDao.proxy());
}
protected void tearDown() throws Exception {
super.tearDown();
assetRoleManager = null;
}
public void testGetAssetRoles() throws Exception {
List results = new ArrayList();
AssetRole assetRole = new AssetRole();
results.add(assetRole);
// set expected behavior on dao
assetRoleDao.expects(once()).method("getAssetRoles")
.will(returnValue(results));
List assetRoles = assetRoleManager.getAssetRoles(null);
assertTrue(assetRoles.size() == 1);
assetRoleDao.verify();
}
public void testGetAssetRole() throws Exception {
// set expected behavior on dao
assetRoleDao.expects(once()).method("getAssetRole")
.will(returnValue(new AssetRole()));
AssetRole assetRole = assetRoleManager.getAssetRole(assetRoleId);
assertTrue(assetRole != null);
assetRoleDao.verify();
}
public void testSaveAssetRole() throws Exception {
AssetRole assetRole = new AssetRole();
// set expected behavior on dao
assetRoleDao.expects(once()).method("saveAssetRole")
.with(same(assetRole)).isVoid();
assetRoleManager.saveAssetRole(assetRole);
assetRoleDao.verify();
}
public void testAddAndRemoveAssetRole() throws Exception {
AssetRole assetRole = new AssetRole();
// set required fields
// set expected behavior on dao
assetRoleDao.expects(once()).method("saveAssetRole")
.with(same(assetRole)).isVoid();
assetRoleManager.saveAssetRole(assetRole);
assetRoleDao.verify();
// reset expectations
assetRoleDao.reset();
assetRoleDao.expects(once()).method("removeAssetRole").with(eq(new Long(assetRoleId)));
assetRoleManager.removeAssetRole(assetRoleId);
assetRoleDao.verify();
// reset expectations
assetRoleDao.reset();
// remove
Exception ex = new ObjectRetrievalFailureException(AssetRole.class, assetRole.getId());
assetRoleDao.expects(once()).method("removeAssetRole").isVoid();
assetRoleDao.expects(once()).method("getAssetRole").will(throwException(ex));
assetRoleManager.removeAssetRole(assetRoleId);
try {
assetRoleManager.getAssetRole(assetRoleId);
fail("AssetRole with identifier '" + assetRoleId + "' found in database");
} catch (ObjectRetrievalFailureException e) {
assertNotNull(e.getMessage());
}
assetRoleDao.verify();
}
}
| apache-2.0 |
dxjia/GifAssistant | app/src/main/java/com/wind/gifassistant/ui/GifProductsListFragment.java | 4062 | package com.wind.gifassistant.ui;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.special.ResideMenu.ResideMenu;
import com.wind.gifassistant.R;
import com.wind.gifassistant.data.GifProductsScanTask;
import com.wind.gifassistant.utils.AppUtils;
import java.util.ArrayList;
public class GifProductsListFragment extends Fragment implements DataLoadCallBack {
private View mParentView;
private ResideMenu mResideMenu;
private PullToRefreshListView mGifPullListView;
private TextView mGifEmptyNoteView;
private GifProductsListAdapter mGifProductsListAdapter;
private ArrayList<String> mGifListItem = new ArrayList<String>();
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mParentView = inflater.inflate(R.layout.main_screen_pager_fragment, container, false);
setUpViews();
return mParentView;
}
private void setUpViews() {
MainActivity parentActivity = (MainActivity) getActivity();
mResideMenu = parentActivity.getResideMenu();
// gif list
mGifPullListView = (PullToRefreshListView) mParentView.findViewById(R.id.pull_refresh_list);
mGifEmptyNoteView = (TextView) mParentView.findViewById(R.id.empty_list_text);
mGifProductsListAdapter = new GifProductsListAdapter(parentActivity, mGifListItem);
mGifPullListView.setAdapter(mGifProductsListAdapter);
final Context vContext = parentActivity;
// set refresh listener
mGifPullListView.setOnRefreshListener(new OnRefreshListener<ListView>() {
@Override
public void onRefresh(PullToRefreshBase<ListView> refreshView) {
// 先隐藏empty note text
mGifEmptyNoteView.setVisibility(View.GONE);
String label = DateUtils.formatDateTime(vContext, System.currentTimeMillis(),
DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
// Update the LastUpdatedLabel
refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
// Do work to refresh the list here.
new GifProductsScanTask(vContext, mGifListItem, mGifEmptyNoteView, mGifPullListView, mGifProductsListAdapter, true).execute();
}
});
// click
ListView actualListView = mGifPullListView.getRefreshableView();
actualListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
int index = 0;
if(position > 0 && position <= mGifListItem.size()) {
index = position - 1;
}
String path = mGifListItem.get(index);
if (TextUtils.isEmpty(path)) {
return;
}
Intent intent = new Intent(vContext, GifShowActivity.class);
intent.putExtra(AppUtils.KEY_PATH, path);
vContext.startActivity(intent);
}
});
/*ListContextMenuListener gifListMenuCreateListener = new ListContextMenuListener(
vContext, mGifProductsListAdapter, AppUtils.FILE_TYPE_GIF,
this, mResideMenu);
actualListView.setOnCreateContextMenuListener(gifListMenuCreateListener);*/
loadData(vContext);
}
public void loadData(Context context) {
// load list
if (mGifProductsListAdapter != null) {
new GifProductsScanTask(context, mGifListItem, mGifEmptyNoteView,
mGifPullListView, mGifProductsListAdapter, false).execute();
}
}
@Override
public void onResume() {
loadData(getActivity());
super.onResume();
}
}
| apache-2.0 |
leepc12/BigDataScript | src/org/bds/lang/nativeMethods/string/MethodNative_string_isEmpty.java | 871 | package org.bds.lang.nativeMethods.string;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import org.bds.lang.Parameters;
import org.bds.lang.Type;
import org.bds.lang.TypeList;
import org.bds.lang.nativeMethods.MethodNative;
import org.bds.run.BdsThread;
import org.bds.task.Task;
import org.bds.util.Gpr;
public class MethodNative_string_isEmpty extends MethodNative {
public MethodNative_string_isEmpty() {
super();
}
@Override
protected void initMethod() {
functionName = "isEmpty";
classType = Type.STRING;
returnType = Type.BOOL;
String argNames[] = { "this" };
Type argTypes[] = { Type.STRING };
parameters = Parameters.get(argTypes, argNames);
addNativeMethodToClassScope();
}
@Override
protected Object runMethodNative(BdsThread csThread, Object objThis) {
return objThis.toString().isEmpty();
}
}
| apache-2.0 |
ConsecroMUD/ConsecroMUD | com/suscipio_solutions/consecro_mud/Items/BasicTech/GenKineticField.java | 2625 | package com.suscipio_solutions.consecro_mud.Items.BasicTech;
import com.suscipio_solutions.consecro_mud.Common.interfaces.CMMsg;
import com.suscipio_solutions.consecro_mud.Common.interfaces.PhyStats;
import com.suscipio_solutions.consecro_mud.Items.interfaces.Technical;
import com.suscipio_solutions.consecro_mud.Items.interfaces.Weapon;
import com.suscipio_solutions.consecro_mud.MOBS.interfaces.MOB;
import com.suscipio_solutions.consecro_mud.core.CMStrings;
public class GenKineticField extends GenPersonalShield
{
@Override public String ID(){ return "GenKineticField";}
public GenKineticField()
{
super();
setName("a kinetic field generator");
setDisplayText("a kinetic field generator sits here.");
setDescription("The kinetic field generator is worn about the body and activated to use. It neutralizes melee and physical projectile damage. ");
}
@Override
protected String fieldOnStr(MOB viewerM)
{
return (owner() instanceof MOB)?
"An powerful energy field surrounds <O-NAME>.":
"An powerful energy field surrounds <T-NAME>.";
}
@Override
protected String fieldDeadStr(MOB viewerM)
{
return (owner() instanceof MOB)?
"The powerful energy field around <O-NAME> flickers and dies out.":
"The powerful energy field around <T-NAME> flickers and dies out.";
}
@Override
protected boolean doShield(MOB mob, CMMsg msg, double successFactor)
{
mob.phyStats().setSensesMask(mob.phyStats().sensesMask()|PhyStats.CAN_NOT_HEAR);
if(mob.location()!=null)
{
if(msg.tool() instanceof Weapon)
{
final String s="^F"+((Weapon)msg.tool()).hitString(0)+"^N";
if(s.indexOf("<DAMAGE> <T-HIM-HER>")>0)
mob.location().show(msg.source(),msg.target(),msg.tool(),CMMsg.MSG_OK_VISUAL,CMStrings.replaceAll(s, "<DAMAGE>", "it`s stopped by the shield around"));
else
if(s.indexOf("<DAMAGES> <T-HIM-HER>")>0)
mob.location().show(msg.source(),msg.target(),msg.tool(),CMMsg.MSG_OK_VISUAL,CMStrings.replaceAll(s, "<DAMAGES>", "is stopped by the shield around"));
else
mob.location().show(mob,msg.source(),msg.tool(),CMMsg.MSG_OK_VISUAL,L("The field around <S-NAME> stops the <O-NAMENOART> damage."));
}
else
mob.location().show(mob,msg.source(),msg.tool(),CMMsg.MSG_OK_VISUAL,L("The field around <S-NAME> stops the <O-NAMENOART> damage."));
}
return false;
}
@Override
protected boolean doesShield(MOB mob, CMMsg msg, double successFactor)
{
if(!activated())
return false;
if((!(msg.tool() instanceof Technical))
&& (msg.tool() instanceof Weapon)
&& (Math.random() >= successFactor))
{
return true;
}
return false;
}
}
| apache-2.0 |
Sargul/dbeaver | plugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/model/sql/SQLQueryResult.java | 4467 | /*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2021 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.model.sql;
import org.jkiss.code.NotNull;
import org.jkiss.code.Nullable;
import org.jkiss.dbeaver.model.exec.DBCExecutionResult;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* SQLQueryResult
*/
public class SQLQueryResult implements DBCExecutionResult
{
public static class ExecuteResult {
private boolean resultSet;
private Long rowCount;
private Long updateCount;
private String resultSetName;
public ExecuteResult(boolean resultSet) {
this.resultSet = resultSet;
}
public boolean isResultSet() {
return resultSet;
}
@Nullable
public Long getRowCount()
{
return rowCount;
}
public void setRowCount(Long rowCount)
{
this.rowCount = rowCount;
}
@Nullable
public Long getUpdateCount()
{
return updateCount;
}
public void setUpdateCount(Long updateCount)
{
this.updateCount = updateCount;
}
@Nullable
public String getResultSetName()
{
return resultSetName;
}
public void setResultSetName(String resultSetName)
{
this.resultSetName = resultSetName;
}
}
private SQLQuery statement;
private Long rowOffset;
private boolean hasResultSet;
private Throwable error;
private long queryTime;
private List<Throwable> warnings;
private List<ExecuteResult> executeResults = new ArrayList<>();
public SQLQueryResult(@NotNull SQLQuery statement)
{
this.statement = statement;
}
@NotNull
public SQLQuery getStatement() {
return statement;
}
public Long getRowOffset() {
return rowOffset;
}
public void setRowOffset(Long rowOffset) {
this.rowOffset = rowOffset;
}
public boolean hasResultSet()
{
return hasResultSet;
}
public void setHasResultSet(boolean hasResultSet)
{
this.hasResultSet = hasResultSet;
}
public boolean hasError()
{
return error != null;
}
@Nullable
public Throwable getError()
{
return error;
}
public void setError(Throwable error)
{
this.error = error;
}
public long getQueryTime()
{
return queryTime;
}
public void setQueryTime(long queryTime)
{
this.queryTime = queryTime;
}
public List<Throwable> getWarnings() {
return warnings;
}
public void addWarnings(Throwable[] warnings) {
if (warnings == null) {
return;
}
if (this.warnings == null) {
this.warnings = new ArrayList<>();
}
Collections.addAll(this.warnings, warnings);
}
public ExecuteResult addExecuteResult(boolean resultSet) {
ExecuteResult executeResult = new ExecuteResult(resultSet);
executeResults.add(executeResult);
return executeResult;
}
public List<ExecuteResult> getExecuteResults() {
return executeResults;
}
public ExecuteResult getExecuteResults(int order, boolean resultSets) {
int rsIndex = -1;
for (int i = 0; i < executeResults.size(); i++) {
if (resultSets && !executeResults.get(i).isResultSet()) {
continue;
}
rsIndex++;
if (rsIndex == order) {
return executeResults.get(i);
}
}
return null;
}
}
| apache-2.0 |
sawer1208/algs | src/chapter1_3/DeleteTail.java | 498 | package chapter1_3;
public class DeleteTail<Item> {
private Node<Item> first;
private int N;
public int getN(){
return N;
}
private static class Node<Item>{
private Item item;
private Node<Item> next;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
DeleteTail<String> dt = new DeleteTail<String>();
Node<String> p = new Node<String>();
for(int i = 0; i < dt.getN()-1; i++){
p = p.next;
}
Node<String> q = p.next;
p.next = null;
}
}
| apache-2.0 |
tfisher1226/ARIES | nam/nam-view/src/main/java/nam/model/transactionScope/TransactionScopeListObject.java | 1750 | package nam.model.transactionScope;
import java.io.Serializable;
import org.aries.ui.AbstractListObject;
import nam.model.TransactionScope;
public class TransactionScopeListObject extends AbstractListObject<TransactionScope> implements Comparable<TransactionScopeListObject>, Serializable {
private TransactionScope transactionScope;
public TransactionScopeListObject(TransactionScope transactionScope) {
this.transactionScope = transactionScope;
}
public TransactionScope getTransactionScope() {
return transactionScope;
}
@Override
public Object getKey() {
return getKey(transactionScope);
}
public Object getKey(TransactionScope transactionScope) {
return transactionScope.value();
}
@Override
public String getLabel() {
return getLabel(transactionScope);
}
public String getLabel(TransactionScope transactionScope) {
return transactionScope.name();
}
@Override
public String toString() {
return toString(transactionScope);
}
@Override
public String toString(TransactionScope transactionScope) {
return transactionScope.name();
}
@Override
public int compareTo(TransactionScopeListObject other) {
Object thisKey = getKey(this.transactionScope);
Object otherKey = getKey(other.transactionScope);
String thisText = thisKey.toString();
String otherText = otherKey.toString();
if (thisText == null)
return -1;
if (otherText == null)
return 1;
return thisText.compareTo(otherText);
}
@Override
public boolean equals(Object object) {
TransactionScopeListObject other = (TransactionScopeListObject) object;
String thisText = toString(this.transactionScope);
String otherText = toString(other.transactionScope);
return thisText.equals(otherText);
}
}
| apache-2.0 |
dbflute-test/dbflute-test-dbms-oracle | src/main/java/org/docksidestage/oracle/dbflute/bsentity/BsVendor$Dollar.java | 6829 | package org.docksidestage.oracle.dbflute.bsentity;
import java.util.List;
import java.util.ArrayList;
import org.dbflute.dbmeta.DBMeta;
import org.dbflute.dbmeta.AbstractEntity;
import org.dbflute.dbmeta.accessory.DomainEntity;
import org.docksidestage.oracle.dbflute.allcommon.DBMetaInstanceHandler;
import org.docksidestage.oracle.dbflute.exentity.*;
/**
* The entity of VENDOR_$_DOLLAR as TABLE. <br>
* <pre>
* [primary-key]
* VENDOR_$_DOLLAR_ID
*
* [column]
* VENDOR_$_DOLLAR_ID, VENDOR_$_DOLLAR_NAME
*
* [sequence]
*
*
* [identity]
*
*
* [version-no]
*
*
* [foreign table]
*
*
* [referrer table]
*
*
* [foreign property]
*
*
* [referrer property]
*
*
* [get/set template]
* /= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
* Long vendor$DollarId = entity.getVendor$DollarId();
* String vendor$DollarName = entity.getVendor$DollarName();
* entity.setVendor$DollarId(vendor$DollarId);
* entity.setVendor$DollarName(vendor$DollarName);
* = = = = = = = = = =/
* </pre>
* @author oracleman
*/
public abstract class BsVendor$Dollar extends AbstractEntity implements DomainEntity {
// ===================================================================================
// Definition
// ==========
/** The serial version UID for object serialization. (Default) */
private static final long serialVersionUID = 1L;
// ===================================================================================
// Attribute
// =========
/** VENDOR_$_DOLLAR_ID: {PK, NotNull, NUMBER(16)} */
protected Long _vendor$DollarId;
/** VENDOR_$_DOLLAR_NAME: {NotNull, VARCHAR2(32)} */
protected String _vendor$DollarName;
// ===================================================================================
// DB Meta
// =======
/** {@inheritDoc} */
public DBMeta asDBMeta() {
return DBMetaInstanceHandler.findDBMeta(asTableDbName());
}
/** {@inheritDoc} */
public String asTableDbName() {
return "VENDOR_$_DOLLAR";
}
// ===================================================================================
// Key Handling
// ============
/** {@inheritDoc} */
public boolean hasPrimaryKeyValue() {
if (_vendor$DollarId == null) { return false; }
return true;
}
// ===================================================================================
// Foreign Property
// ================
// ===================================================================================
// Referrer Property
// =================
protected <ELEMENT> List<ELEMENT> newReferrerList() { // overriding to import
return new ArrayList<ELEMENT>();
}
// ===================================================================================
// Basic Override
// ==============
@Override
protected boolean doEquals(Object obj) {
if (obj instanceof BsVendor$Dollar) {
BsVendor$Dollar other = (BsVendor$Dollar)obj;
if (!xSV(_vendor$DollarId, other._vendor$DollarId)) { return false; }
return true;
} else {
return false;
}
}
@Override
protected int doHashCode(int initial) {
int hs = initial;
hs = xCH(hs, asTableDbName());
hs = xCH(hs, _vendor$DollarId);
return hs;
}
@Override
protected String doBuildStringWithRelation(String li) {
return "";
}
@Override
protected String doBuildColumnString(String dm) {
StringBuilder sb = new StringBuilder();
sb.append(dm).append(xfND(_vendor$DollarId));
sb.append(dm).append(xfND(_vendor$DollarName));
if (sb.length() > dm.length()) {
sb.delete(0, dm.length());
}
sb.insert(0, "{").append("}");
return sb.toString();
}
@Override
protected String doBuildRelationString(String dm) {
return "";
}
@Override
public Vendor$Dollar clone() {
return (Vendor$Dollar)super.clone();
}
// ===================================================================================
// Accessor
// ========
/**
* [get] VENDOR_$_DOLLAR_ID: {PK, NotNull, NUMBER(16)} <br>
* @return The value of the column 'VENDOR_$_DOLLAR_ID'. (basically NotNull if selected: for the constraint)
*/
public Long getVendor$DollarId() {
checkSpecifiedProperty("vendor$DollarId");
return _vendor$DollarId;
}
/**
* [set] VENDOR_$_DOLLAR_ID: {PK, NotNull, NUMBER(16)} <br>
* @param vendor$DollarId The value of the column 'VENDOR_$_DOLLAR_ID'. (basically NotNull if update: for the constraint)
*/
public void setVendor$DollarId(Long vendor$DollarId) {
registerModifiedProperty("vendor$DollarId");
_vendor$DollarId = vendor$DollarId;
}
/**
* [get] VENDOR_$_DOLLAR_NAME: {NotNull, VARCHAR2(32)} <br>
* @return The value of the column 'VENDOR_$_DOLLAR_NAME'. (basically NotNull if selected: for the constraint)
*/
public String getVendor$DollarName() {
checkSpecifiedProperty("vendor$DollarName");
return _vendor$DollarName;
}
/**
* [set] VENDOR_$_DOLLAR_NAME: {NotNull, VARCHAR2(32)} <br>
* @param vendor$DollarName The value of the column 'VENDOR_$_DOLLAR_NAME'. (basically NotNull if update: for the constraint)
*/
public void setVendor$DollarName(String vendor$DollarName) {
registerModifiedProperty("vendor$DollarName");
_vendor$DollarName = vendor$DollarName;
}
}
| apache-2.0 |
jesty/orientdb-microservices | nut-corelationid/src/main/java/com/nutcore/nut/correlationid/ClientProducer.java | 419 | package com.nutcore.nut.correlationid;
import javax.enterprise.inject.Produces;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
/**
* Created by davidecerbo on 14/11/2016.
*/
public class ClientProducer
{
@Produces
public Client newClient()
{
return ClientBuilder
.newClient()
.register(new CorrelationIdClientRequestFilter());
}
}
| apache-2.0 |
didi/DoraemonKit | Android/app/src/main/java/com/didichuxing/doraemondemo/dokit/SimpleDokitView.java | 3618 | package com.didichuxing.doraemondemo.dokit;
import android.content.Context;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.TextView;
import com.blankj.utilcode.util.ConvertUtils;
import com.didichuxing.doraemondemo.R;
import com.didichuxing.doraemonkit.DoKit;
import com.didichuxing.doraemonkit.kit.core.AbsDokitView;
import com.didichuxing.doraemonkit.kit.core.DokitViewLayoutParams;
/**
* @Author: changzuozhen
* @Date: 2020-12-22
* <p>
* 悬浮窗,支持折叠
* @see SimpleDokitView
* 启动工具函数
*/
public abstract class SimpleDokitView extends AbsDokitView {
private static final String TAG = "SimpleBaseFloatPage";
int mWidth;
int mHeight;
int mDp50InPx;
private WindowManager mWindowManager;
private FrameLayout mFloatContainer;
private Switch mShowSwitch;
private Context mContext;
@Override
public void onEnterForeground() {
super.onEnterForeground();
getParentView().setVisibility(View.VISIBLE);
}
@Override
public void onEnterBackground() {
super.onEnterBackground();
getParentView().setVisibility(View.GONE);
}
public void showContainer(boolean isChecked) {
mFloatContainer.setVisibility(isChecked ? View.VISIBLE : View.GONE);
immInvalidate();
}
@Override
public void onCreate(Context context) {
mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics outMetrics = new DisplayMetrics();
mWindowManager.getDefaultDisplay().getMetrics(outMetrics);
mDp50InPx = ConvertUtils.dp2px(50);
mWidth = outMetrics.widthPixels - mDp50InPx;
mHeight = outMetrics.heightPixels - mDp50InPx;
}
@Override
public View onCreateView(Context context, FrameLayout rootView) {
mContext = context;
return LayoutInflater.from(context).inflate(R.layout.dk_layout_simple_dokit_float_view, rootView, false);
}
@Override
public void onViewCreated(FrameLayout rootView) {
mFloatContainer = findViewById(R.id.floatContainer);
LayoutInflater.from(mContext).inflate(getLayoutId(), mFloatContainer);
mShowSwitch = findViewById(R.id.showHideSwitch);
TextView title = findViewById(R.id.floatPageTitle);
ImageView close = findViewById(R.id.floatClose);
close.setOnClickListener(v -> DoKit.removeFloating(this));
title.setText(getTag());
mShowSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
showContainer(isChecked);
}
});
initView();
}
protected abstract int getLayoutId();
@Override
public void initDokitViewLayoutParams(DokitViewLayoutParams params) {
params.width = DokitViewLayoutParams.WRAP_CONTENT;
params.height = DokitViewLayoutParams.WRAP_CONTENT;
params.gravity = Gravity.TOP | Gravity.LEFT;
params.x = 200;
params.y = 200;
}
@Override
public boolean onBackPressed() {
mShowSwitch.setChecked(false);
return false;
}
@Override
public boolean shouldDealBackKey() {
return true;
}
protected void initView() {
}
} | apache-2.0 |
robjcaskey/Unofficial-Coffee-Mud-Upstream | com/planet_ink/coffee_mud/Commands/Value.java | 3508 | package com.planet_ink.coffee_mud.Commands;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
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.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.*;
/*
Copyright 2000-2010 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.
*/
@SuppressWarnings("unchecked")
public class Value extends StdCommand
{
public Value(){}
private String[] access={"VALUE","VAL","V"};
public String[] getAccessWords(){return access;}
public boolean execute(MOB mob, Vector commands, int metaFlags)
throws java.io.IOException
{
Environmental shopkeeper=CMLib.english().parseShopkeeper(mob,commands,"Value what with whom?");
if(shopkeeper==null) return false;
if(commands.size()==0)
{
mob.tell("Value what?");
return false;
}
int maxToDo=Integer.MAX_VALUE;
if((commands.size()>1)
&&(CMath.s_int((String)commands.firstElement())>0))
{
maxToDo=CMath.s_int((String)commands.firstElement());
commands.setElementAt("all",0);
}
String whatName=CMParms.combine(commands,0);
Vector V=new Vector();
boolean allFlag=((String)commands.elementAt(0)).equalsIgnoreCase("all");
if(whatName.toUpperCase().startsWith("ALL.")){ allFlag=true; whatName="ALL "+whatName.substring(4);}
if(whatName.toUpperCase().endsWith(".ALL")){ allFlag=true; whatName="ALL "+whatName.substring(0,whatName.length()-4);}
int addendum=1;
String addendumStr="";
do
{
Item itemToDo=mob.fetchCarried(null,whatName+addendumStr);
if(itemToDo==null) break;
if((CMLib.flags().canBeSeenBy(itemToDo,mob))
&&(!V.contains(itemToDo)))
V.addElement(itemToDo);
addendumStr="."+(++addendum);
}
while((allFlag)&&(addendum<=maxToDo));
if(V.size()==0)
mob.tell("You don't seem to have '"+whatName+"'.");
else
for(int v=0;v<V.size();v++)
{
Item thisThang=(Item)V.elementAt(v);
CMMsg newMsg=CMClass.getMsg(mob,shopkeeper,thisThang,CMMsg.MSG_VALUE,null);
if(mob.location().okMessage(mob,newMsg))
mob.location().send(mob,newMsg);
}
return false;
}
public double combatActionsCost(MOB mob, Vector cmds){return CMath.div(CMProps.getIntVar(CMProps.SYSTEMI_DEFCOMCMDTIME),100.0);}
public double actionsCost(MOB mob, Vector cmds){return CMath.div(CMProps.getIntVar(CMProps.SYSTEMI_DEFCMDTIME),100.0);}
public boolean canBeOrdered(){return true;}
}
| apache-2.0 |
ampproject/validator-java | src/main/java/dev/amp/validator/visitor/InvalidRuleVisitor.java | 6111 | /*
*
* ====================================================================
* 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.
* ====================================================================
*/
/*
* Changes to the original project are Copyright 2019, Verizon Media Inc..
*/
package dev.amp.validator.visitor;
import dev.amp.validator.ValidatorProtos;
import dev.amp.validator.css.AtRule;
import dev.amp.validator.css.CssValidationException;
import dev.amp.validator.css.Declaration;
import dev.amp.validator.Context;
import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.List;
import static dev.amp.validator.utils.CssSpecUtils.allowedDeclarationsString;
import static dev.amp.validator.utils.CssSpecUtils.isDeclarationValid;
import static dev.amp.validator.utils.TagSpecUtils.getTagSpecName;
import static dev.amp.validator.utils.CssSpecUtils.stripVendorPrefix;
/**
* Extension of RuleVisitor used to handle an invalid css rule.
*
* @author nhant01
* @author GeorgeLuo
*/
public class InvalidRuleVisitor implements RuleVisitor {
/**
* Initialize an InvalidRuleVisitor.
*
* @param tagSpec to validate against.
* @param cssSpec to validate against.
* @param context provides global information related to html validation.
* @param result the validation result to populate.
*/
public InvalidRuleVisitor(@Nonnull final ValidatorProtos.TagSpec tagSpec, @Nonnull final ValidatorProtos.CssSpec cssSpec,
@Nonnull final Context context,
@Nonnull final ValidatorProtos.ValidationResult.Builder result) {
super();
this.tagSpec = tagSpec;
this.cssSpec = cssSpec;
this.context = context;
this.result = result;
}
/**
* Visit an atRule
*
* @param atRule to visit
*/
@Override
public void visitAtRule(@Nonnull final AtRule atRule) throws CssValidationException {
if (!isAtRuleValid(this.cssSpec, atRule.getName())) {
List<String> params = new ArrayList<>();
params.add(getTagSpecName(this.tagSpec));
params.add(atRule.getName());
this.context.addError(
ValidatorProtos.ValidationError.Code.CSS_SYNTAX_INVALID_AT_RULE,
context.getLineCol().getLineNumber() + atRule.getLine(),
context.getLineCol().getColumnNumber() + atRule.getCol(),
params,
"",
this.result);
}
}
/**
* Returns true if the given AT rule is considered valid.
*
* @param cssSpec to validate against
* @param atRuleName the rule to validate
* @return true iff rule is valid
*/
public boolean isAtRuleValid(@Nonnull final ValidatorProtos.CssSpec cssSpec,
@Nonnull final String atRuleName) {
for (final ValidatorProtos.AtRuleSpec atRuleSpec : cssSpec.getAtRuleSpecList()) {
// "-moz-document" is specified in the list of allowed rules with an
// explicit vendor prefix. The idea here is that only this specific vendor
// prefix is allowed, not "-ms-document" or even "document". We first
// search the allowed list for the seen `at_rule_name` with stripped
// vendor prefix, then if not found, we search again without sripping the
// vendor prefix.
if (atRuleSpec.getName().equals(stripVendorPrefix(atRuleName))) {
return true;
}
}
return false;
}
/**
* Touches a Declaration
*
* @param declaration to visit
*/
@Override
public void visitDeclaration(@Nonnull final Declaration declaration) {
if (!isDeclarationValid(this.cssSpec, declaration.getName())) {
final String declarationsStr = allowedDeclarationsString(this.cssSpec);
if (declarationsStr.equals("")) {
List<String> params = new ArrayList<>();
params.add(getTagSpecName(this.tagSpec));
params.add(declaration.getName());
this.context.addError(
ValidatorProtos.ValidationError.Code.CSS_SYNTAX_INVALID_PROPERTY_NOLIST,
context.getLineCol().getLineNumber() + declaration.getLine(),
context.getLineCol().getColumnNumber() + declaration.getCol(),
params,
"",
this.result);
} else {
List<String> params = new ArrayList<>();
params.add(getTagSpecName(this.tagSpec));
params.add(declaration.getName());
params.add(declaration.getName());
allowedDeclarationsString(this.cssSpec);
this.context.addError(
ValidatorProtos.ValidationError.Code.CSS_SYNTAX_INVALID_PROPERTY,
context.getLineCol().getLineNumber() + declaration.getLine(),
context.getLineCol().getColumnNumber() + declaration.getCol(),
params,
"",
this.result);
}
}
}
/** Tag spec. */
private final ValidatorProtos.TagSpec tagSpec;
/** Css spec. */
private final ValidatorProtos.CssSpec cssSpec;
/** Context. */
private final Context context;
/** Result builder. */
private final ValidatorProtos.ValidationResult.Builder result;
}
| apache-2.0 |