text
stringlengths 7
1.01M
|
|---|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.databoxedge.implementation;
import com.azure.core.http.rest.PagedIterable;
import com.azure.core.http.rest.Response;
import com.azure.core.http.rest.SimpleResponse;
import com.azure.core.util.Context;
import com.azure.core.util.logging.ClientLogger;
import com.azure.resourcemanager.databoxedge.fluent.AlertsClient;
import com.azure.resourcemanager.databoxedge.fluent.models.AlertInner;
import com.azure.resourcemanager.databoxedge.models.Alert;
import com.azure.resourcemanager.databoxedge.models.Alerts;
import com.fasterxml.jackson.annotation.JsonIgnore;
public final class AlertsImpl implements Alerts {
@JsonIgnore private final ClientLogger logger = new ClientLogger(AlertsImpl.class);
private final AlertsClient innerClient;
private final com.azure.resourcemanager.databoxedge.DataBoxEdgeManager serviceManager;
public AlertsImpl(
AlertsClient innerClient, com.azure.resourcemanager.databoxedge.DataBoxEdgeManager serviceManager) {
this.innerClient = innerClient;
this.serviceManager = serviceManager;
}
public PagedIterable<Alert> listByDataBoxEdgeDevice(String deviceName, String resourceGroupName) {
PagedIterable<AlertInner> inner = this.serviceClient().listByDataBoxEdgeDevice(deviceName, resourceGroupName);
return Utils.mapPage(inner, inner1 -> new AlertImpl(inner1, this.manager()));
}
public PagedIterable<Alert> listByDataBoxEdgeDevice(String deviceName, String resourceGroupName, Context context) {
PagedIterable<AlertInner> inner =
this.serviceClient().listByDataBoxEdgeDevice(deviceName, resourceGroupName, context);
return Utils.mapPage(inner, inner1 -> new AlertImpl(inner1, this.manager()));
}
public Alert get(String deviceName, String name, String resourceGroupName) {
AlertInner inner = this.serviceClient().get(deviceName, name, resourceGroupName);
if (inner != null) {
return new AlertImpl(inner, this.manager());
} else {
return null;
}
}
public Response<Alert> getWithResponse(String deviceName, String name, String resourceGroupName, Context context) {
Response<AlertInner> inner = this.serviceClient().getWithResponse(deviceName, name, resourceGroupName, context);
if (inner != null) {
return new SimpleResponse<>(
inner.getRequest(),
inner.getStatusCode(),
inner.getHeaders(),
new AlertImpl(inner.getValue(), this.manager()));
} else {
return null;
}
}
private AlertsClient serviceClient() {
return this.innerClient;
}
private com.azure.resourcemanager.databoxedge.DataBoxEdgeManager manager() {
return this.serviceManager;
}
}
|
package com.pedro.rtplibrary.base;
import android.content.Context;
import android.hardware.Camera;
import android.media.MediaCodec;
import android.media.MediaFormat;
import android.os.Build;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceView;
import android.view.TextureView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import com.pedro.encoder.Frame;
import com.pedro.encoder.audio.AudioEncoder;
import com.pedro.encoder.audio.GetAacData;
import com.pedro.encoder.input.audio.CustomAudioEffect;
import com.pedro.encoder.input.audio.GetMicrophoneData;
import com.pedro.encoder.input.audio.MicrophoneManager;
import com.pedro.encoder.input.video.Camera1ApiManager;
import com.pedro.encoder.input.video.CameraCallbacks;
import com.pedro.encoder.input.video.CameraHelper;
import com.pedro.encoder.input.video.CameraOpenException;
import com.pedro.encoder.input.video.GetCameraData;
import com.pedro.encoder.utils.CodecUtil;
import com.pedro.encoder.video.FormatVideoEncoder;
import com.pedro.encoder.video.GetVideoData;
import com.pedro.encoder.video.VideoEncoder;
import com.pedro.rtplibrary.util.FpsListener;
import com.pedro.rtplibrary.util.RecordController;
import com.pedro.rtplibrary.view.GlInterface;
import com.pedro.rtplibrary.view.LightOpenGlView;
import com.pedro.rtplibrary.view.OffScreenGlThread;
import com.pedro.rtplibrary.view.OpenGlView;
import java.io.FileDescriptor;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.List;
/**
* Wrapper to stream with camera1 api and microphone. Support stream with SurfaceView, TextureView
* and OpenGlView(Custom SurfaceView that use OpenGl). SurfaceView and TextureView use buffer to
* buffer encoding mode for H264 and OpenGlView use Surface to buffer mode(This mode is generally
* better because skip buffer processing).
*
* API requirements:
* SurfaceView and TextureView mode: API 16+.
* OpenGlView: API 18+.
*
* Created by pedro on 7/07/17.
*/
public abstract class Camera1Base
implements GetAacData, GetCameraData, GetVideoData, GetMicrophoneData {
private static final String TAG = "Camera1Base";
private Context context;
private Camera1ApiManager cameraManager;
protected VideoEncoder videoEncoder;
private MicrophoneManager microphoneManager;
private AudioEncoder audioEncoder;
private GlInterface glInterface;
private boolean streaming = false;
private boolean videoEnabled = true;
private boolean onPreview = false;
protected RecordController recordController;
private int previewWidth, previewHeight;
private FpsListener fpsListener = new FpsListener();
public Camera1Base(SurfaceView surfaceView) {
context = surfaceView.getContext();
cameraManager = new Camera1ApiManager(surfaceView, this);
init();
}
public Camera1Base(TextureView textureView) {
context = textureView.getContext();
cameraManager = new Camera1ApiManager(textureView, this);
init();
}
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
public Camera1Base(OpenGlView openGlView) {
context = openGlView.getContext();
this.glInterface = openGlView;
this.glInterface.init();
cameraManager = new Camera1ApiManager(glInterface.getSurfaceTexture(), context);
init();
}
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
public Camera1Base(LightOpenGlView lightOpenGlView) {
context = lightOpenGlView.getContext();
this.glInterface = lightOpenGlView;
this.glInterface.init();
cameraManager = new Camera1ApiManager(glInterface.getSurfaceTexture(), context);
init();
}
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
public Camera1Base(Context context) {
this.context = context;
glInterface = new OffScreenGlThread(context);
glInterface.init();
cameraManager = new Camera1ApiManager(glInterface.getSurfaceTexture(), context);
init();
}
private void init() {
videoEncoder = new VideoEncoder(this);
microphoneManager = new MicrophoneManager(this);
audioEncoder = new AudioEncoder(this);
recordController = new RecordController();
}
public void setCameraCallbacks(CameraCallbacks callbacks) {
cameraManager.setCameraCallbacks(callbacks);
}
/**
* Set an audio effect modifying microphone's PCM buffer.
*/
public void setCustomAudioEffect(CustomAudioEffect customAudioEffect) {
microphoneManager.setCustomAudioEffect(customAudioEffect);
}
/**
* @param callback get fps while record or stream
*/
public void setFpsListener(FpsListener.Callback callback) {
fpsListener.setCallback(callback);
}
/**
* Experimental
*/
public void enableFaceDetection(Camera1ApiManager.FaceDetectorCallback faceDetectorCallback) {
cameraManager.enableFaceDetection(faceDetectorCallback);
}
/**
* Experimental
*/
public void disableFaceDetection() {
cameraManager.disableFaceDetection();
}
/**
* Experimental
*/
public boolean isFaceDetectionEnabled() {
return cameraManager.isFaceDetectionEnabled();
}
public boolean isFrontCamera() {
return cameraManager.isFrontCamera();
}
public void enableLantern() throws Exception {
cameraManager.enableLantern();
}
public void disableLantern() {
cameraManager.disableLantern();
}
public boolean isLanternEnabled() {
return cameraManager.isLanternEnabled();
}
public void enableAutoFocus() {
cameraManager.enableAutoFocus();
}
public void disableAutoFocus() {
cameraManager.disableAutoFocus();
}
public boolean isAutoFocusEnabled() {
return cameraManager.isAutoFocusEnabled();
}
/**
* Basic auth developed to work with Wowza. No tested with other server
*
* @param user auth.
* @param password auth.
*/
public abstract void setAuthorization(String user, String password);
/**
* Call this method before use @startStream. If not you will do a stream without video. NOTE:
* Rotation with encoder is silence ignored in some devices.
*
* @param width resolution in px.
* @param height resolution in px.
* @param fps frames per second of the stream.
* @param bitrate H264 in bps.
* @param rotation could be 90, 180, 270 or 0. You should use CameraHelper.getCameraOrientation
* with SurfaceView or TextureView and 0 with OpenGlView or LightOpenGlView. NOTE: Rotation with
* encoder is silence ignored in some devices.
* @return true if success, false if you get a error (Normally because the encoder selected
* doesn't support any configuration seated or your device hasn't a H264 encoder).
*/
public boolean prepareVideo(int width, int height, int fps, int bitrate, int iFrameInterval,
int rotation, int avcProfile, int avcProfileLevel) {
if (onPreview && width != previewWidth || height != previewHeight) {
stopPreview();
onPreview = true;
}
FormatVideoEncoder formatVideoEncoder =
glInterface == null ? FormatVideoEncoder.YUV420Dynamical : FormatVideoEncoder.SURFACE;
return videoEncoder.prepareVideoEncoder(width, height, fps, bitrate, rotation, iFrameInterval,
formatVideoEncoder, avcProfile, avcProfileLevel);
}
/**
* backward compatibility reason
*/
public boolean prepareVideo(int width, int height, int fps, int bitrate, int iFrameInterval,
int rotation) {
return prepareVideo(width, height, fps, bitrate, iFrameInterval, rotation, -1, -1);
}
public boolean prepareVideo(int width, int height, int fps, int bitrate, int rotation) {
return prepareVideo(width, height, fps, bitrate, 2, rotation);
}
public boolean prepareVideo(int width, int height, int bitrate) {
int rotation = CameraHelper.getCameraOrientation(context);
return prepareVideo(width, height, 30, bitrate, 2, rotation);
}
protected abstract void prepareAudioRtp(boolean isStereo, int sampleRate);
/**
* Call this method before use @startStream. If not you will do a stream without audio.
*
* @param bitrate AAC in kb.
* @param sampleRate of audio in hz. Can be 8000, 16000, 22500, 32000, 44100.
* @param isStereo true if you want Stereo audio (2 audio channels), false if you want Mono audio
* (1 audio channel).
* @param echoCanceler true enable echo canceler, false disable.
* @param noiseSuppressor true enable noise suppressor, false disable.
* @return true if success, false if you get a error (Normally because the encoder selected
* doesn't support any configuration seated or your device hasn't a AAC encoder).
*/
public boolean prepareAudio(int bitrate, int sampleRate, boolean isStereo, boolean echoCanceler,
boolean noiseSuppressor) {
microphoneManager.createMicrophone(sampleRate, isStereo, echoCanceler, noiseSuppressor);
prepareAudioRtp(isStereo, sampleRate);
return audioEncoder.prepareAudioEncoder(bitrate, sampleRate, isStereo,
microphoneManager.getMaxInputSize());
}
public boolean prepareAudio(int bitrate, int sampleRate, boolean isStereo) {
return prepareAudio(bitrate, sampleRate, isStereo, false, false);
}
/**
* Same to call: rotation = 0; if (Portrait) rotation = 90; prepareVideo(640, 480, 30, 1200 *
* 1024, false, rotation);
*
* @return true if success, false if you get a error (Normally because the encoder selected
* doesn't support any configuration seated or your device hasn't a H264 encoder).
*/
public boolean prepareVideo() {
int rotation = CameraHelper.getCameraOrientation(context);
return prepareVideo(640, 480, 30, 1200 * 1024, rotation);
}
/**
* Same to call: prepareAudio(64 * 1024, 32000, true, false, false);
*
* @return true if success, false if you get a error (Normally because the encoder selected
* doesn't support any configuration seated or your device hasn't a AAC encoder).
*/
public boolean prepareAudio() {
return prepareAudio(64 * 1024, 32000, true, false, false);
}
/**
* @param forceVideo force type codec used. FIRST_COMPATIBLE_FOUND, SOFTWARE, HARDWARE
* @param forceAudio force type codec used. FIRST_COMPATIBLE_FOUND, SOFTWARE, HARDWARE
*/
public void setForce(CodecUtil.Force forceVideo, CodecUtil.Force forceAudio) {
videoEncoder.setForce(forceVideo);
audioEncoder.setForce(forceAudio);
}
/**
* Starts recording an MP4 video. Needs to be called while streaming.
*
* @param path Where file will be saved.
* @throws IOException If initialized before a stream.
*/
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
public void startRecord(@NonNull final String path, @Nullable RecordController.Listener listener)
throws IOException {
recordController.startRecord(path, listener);
if (!streaming) {
startEncoders();
} else if (videoEncoder.isRunning()) {
resetVideoEncoder();
}
}
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
public void startRecord(@NonNull final String path) throws IOException {
startRecord(path, null);
}
/**
* Starts recording an MP4 video. Needs to be called while streaming.
*
* @param fd Where the file will be saved.
* @throws IOException If initialized before a stream.
*/
@RequiresApi(api = Build.VERSION_CODES.O)
public void startRecord(@NonNull final FileDescriptor fd, @Nullable RecordController.Listener listener) throws IOException {
recordController.startRecord(fd, listener);
if (!streaming) {
startEncoders();
} else if (videoEncoder.isRunning()) {
resetVideoEncoder();
}
}
@RequiresApi(api = Build.VERSION_CODES.O)
public void startRecord(@NonNull final FileDescriptor fd) throws IOException{
startRecord(fd, null);
}
/**
* Stop record MP4 video started with @startRecord. If you don't call it file will be unreadable.
*/
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
public void stopRecord() {
recordController.stopRecord();
if (!streaming) stopStream();
}
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
public void replaceView(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
replaceGlInterface(new OffScreenGlThread(context));
}
}
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
public void replaceView(OpenGlView openGlView) {
replaceGlInterface(openGlView);
}
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
public void replaceView(LightOpenGlView lightOpenGlView) {
replaceGlInterface(lightOpenGlView);
}
/**
* Replace glInterface used on fly. Ignored if you use SurfaceView or TextureView
*/
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
private void replaceGlInterface(GlInterface glInterface) {
if (this.glInterface != null && Build.VERSION.SDK_INT >= 18) {
if (isStreaming() || isRecording() || isOnPreview()) {
cameraManager.stop();
this.glInterface.removeMediaCodecSurface();
this.glInterface.stop();
this.glInterface = glInterface;
this.glInterface.init();
boolean isPortrait = CameraHelper.isPortrait(context);
if (isPortrait) {
this.glInterface.setEncoderSize(videoEncoder.getHeight(), videoEncoder.getWidth());
} else {
this.glInterface.setEncoderSize(videoEncoder.getWidth(), videoEncoder.getHeight());
}
this.glInterface.setRotation(0);
this.glInterface.start();
if (isStreaming() || isRecording()) {
this.glInterface.addMediaCodecSurface(videoEncoder.getInputSurface());
}
cameraManager.setSurfaceTexture(glInterface.getSurfaceTexture());
cameraManager.setRotation(videoEncoder.getRotation());
cameraManager.start(videoEncoder.getWidth(), videoEncoder.getHeight(),
videoEncoder.getFps());
} else {
this.glInterface = glInterface;
}
}
}
/**
* Start camera preview. Ignored, if stream or preview is started.
*
* @param cameraFacing front or back camera. Like: {@link com.pedro.encoder.input.video.CameraHelper.Facing#BACK}
* {@link com.pedro.encoder.input.video.CameraHelper.Facing#FRONT}
* @param width of preview in px.
* @param height of preview in px.
* @param rotation camera rotation (0, 90, 180, 270). Recommended: {@link
* com.pedro.encoder.input.video.CameraHelper#getCameraOrientation(Context)}
*/
public void startPreview(CameraHelper.Facing cameraFacing, int width, int height, int rotation) {
if (!isStreaming() && !onPreview && !(glInterface instanceof OffScreenGlThread)) {
previewWidth = width;
previewHeight = height;
if (glInterface != null && Build.VERSION.SDK_INT >= 18) {
boolean isPortrait = CameraHelper.isPortrait(context);
if (isPortrait) {
glInterface.setEncoderSize(height, width);
} else {
glInterface.setEncoderSize(width, height);
}
glInterface.setRotation(0);
glInterface.start();
cameraManager.setSurfaceTexture(glInterface.getSurfaceTexture());
}
cameraManager.setRotation(rotation);
cameraManager.start(cameraFacing, width, height, videoEncoder.getFps());
onPreview = true;
} else {
Log.e(TAG, "Streaming or preview started, ignored");
}
}
public void startPreview(CameraHelper.Facing cameraFacing, int width, int height) {
startPreview(cameraFacing, width, height, CameraHelper.getCameraOrientation(context));
}
public void startPreview(CameraHelper.Facing cameraFacing) {
startPreview(cameraFacing, 640, 480);
}
public void startPreview(int width, int height) {
startPreview(CameraHelper.Facing.BACK, width, height);
}
public void startPreview() {
startPreview(CameraHelper.Facing.BACK);
}
/**
* Stop camera preview. Ignored if streaming or already stopped. You need call it after
*
* @stopStream to release camera properly if you will close activity.
*/
public void stopPreview() {
if (!isStreaming()
&& !isRecording()
&& onPreview
&& !(glInterface instanceof OffScreenGlThread)) {
if (glInterface != null && Build.VERSION.SDK_INT >= 18) {
glInterface.stop();
}
cameraManager.stop();
onPreview = false;
previewWidth = 0;
previewHeight = 0;
} else {
Log.e(TAG, "Streaming or preview stopped, ignored");
}
}
/**
* Change preview orientation can be called while stream.
*
* @param orientation of the camera preview. Could be 90, 180, 270 or 0.
*/
public void setPreviewOrientation(int orientation) {
cameraManager.setPreviewOrientation(orientation);
}
/**
* Set zoomIn or zoomOut to camera.
*
* @param event motion event. Expected to get event.getPointerCount() > 1
*/
public void setZoom(MotionEvent event) {
cameraManager.setZoom(event);
}
protected abstract void startStreamRtp(String url);
/**
* Need be called after @prepareVideo or/and @prepareAudio. This method override resolution of
*
* @param url of the stream like: protocol://ip:port/application/streamName
*
* RTSP: rtsp://192.168.1.1:1935/live/pedroSG94 RTSPS: rtsps://192.168.1.1:1935/live/pedroSG94
* RTMP: rtmp://192.168.1.1:1935/live/pedroSG94 RTMPS: rtmps://192.168.1.1:1935/live/pedroSG94
* @startPreview to resolution seated in @prepareVideo. If you never startPreview this method
* startPreview for you to resolution seated in @prepareVideo.
*/
public void startStream(String url) {
streaming = true;
if (!recordController.isRunning()) {
startEncoders();
} else {
resetVideoEncoder();
}
startStreamRtp(url);
onPreview = true;
}
private void startEncoders() {
videoEncoder.start();
audioEncoder.start();
prepareGlView();
microphoneManager.start();
cameraManager.setRotation(videoEncoder.getRotation());
if (!cameraManager.isRunning() && videoEncoder.getWidth() != previewWidth
|| videoEncoder.getHeight() != previewHeight) {
cameraManager.start(videoEncoder.getWidth(), videoEncoder.getHeight(), videoEncoder.getFps());
}
onPreview = true;
}
private void resetVideoEncoder() {
if (glInterface != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
glInterface.removeMediaCodecSurface();
}
videoEncoder.reset();
if (glInterface != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
glInterface.addMediaCodecSurface(videoEncoder.getInputSurface());
}
}
private void prepareGlView() {
if (glInterface != null && Build.VERSION.SDK_INT >= 18) {
if (glInterface instanceof OffScreenGlThread) {
glInterface = new OffScreenGlThread(context);
glInterface.init();
}
glInterface.setFps(videoEncoder.getFps());
if (videoEncoder.getRotation() == 90 || videoEncoder.getRotation() == 270) {
glInterface.setEncoderSize(videoEncoder.getHeight(), videoEncoder.getWidth());
} else {
glInterface.setEncoderSize(videoEncoder.getWidth(), videoEncoder.getHeight());
}
glInterface.setRotation(0);
if (!cameraManager.isRunning() && videoEncoder.getWidth() != previewWidth
|| videoEncoder.getHeight() != previewHeight) {
glInterface.start();
}
if (videoEncoder.getInputSurface() != null) {
glInterface.addMediaCodecSurface(videoEncoder.getInputSurface());
}
cameraManager.setSurfaceTexture(glInterface.getSurfaceTexture());
}
}
protected abstract void stopStreamRtp();
/**
* Stop stream started with @startStream.
*/
public void stopStream() {
if (streaming) {
streaming = false;
stopStreamRtp();
}
if (!recordController.isRecording()) {
microphoneManager.stop();
if (glInterface != null && Build.VERSION.SDK_INT >= 18) {
glInterface.removeMediaCodecSurface();
if (glInterface instanceof OffScreenGlThread) {
glInterface.stop();
cameraManager.stop();
}
}
videoEncoder.stop();
audioEncoder.stop();
recordController.resetFormats();
}
}
public boolean reTry(long delay, String reason) {
boolean result = shouldRetry(reason);
if (result) {
reTry(delay);
}
return result;
}
/**
* Replace with reTry(long delay, String reason);
*/
@Deprecated
public void reTry(long delay) {
resetVideoEncoder();
reConnect(delay);
}
/**
* Replace with reTry(long delay, String reason);
*/
@Deprecated
public abstract boolean shouldRetry(String reason);
public abstract void setReTries(int reTries);
protected abstract void reConnect(long delay);
//cache control
public abstract void resizeCache(int newSize) throws RuntimeException;
public abstract int getCacheSize();
public abstract long getSentAudioFrames();
public abstract long getSentVideoFrames();
public abstract long getDroppedAudioFrames();
public abstract long getDroppedVideoFrames();
public abstract void resetSentAudioFrames();
public abstract void resetSentVideoFrames();
public abstract void resetDroppedAudioFrames();
public abstract void resetDroppedVideoFrames();
/**
* Get supported preview resolutions of back camera in px.
*
* @return list of preview resolutions supported by back camera
*/
public List<Camera.Size> getResolutionsBack() {
return cameraManager.getPreviewSizeBack();
}
/**
* Get supported preview resolutions of front camera in px.
*
* @return list of preview resolutions supported by front camera
*/
public List<Camera.Size> getResolutionsFront() {
return cameraManager.getPreviewSizeFront();
}
/**
* Mute microphone, can be called before, while and after stream.
*/
public void disableAudio() {
microphoneManager.mute();
}
/**
* Enable a muted microphone, can be called before, while and after stream.
*/
public void enableAudio() {
microphoneManager.unMute();
}
/**
* Get mute state of microphone.
*
* @return true if muted, false if enabled
*/
public boolean isAudioMuted() {
return microphoneManager.isMuted();
}
/**
* Get video camera state
*
* @return true if disabled, false if enabled
*/
public boolean isVideoEnabled() {
return videoEnabled;
}
public int getBitrate() {
return videoEncoder.getBitRate();
}
public int getResolutionValue() {
return videoEncoder.getWidth() * videoEncoder.getHeight();
}
public int getStreamWidth() {
return videoEncoder.getWidth();
}
public int getStreamHeight() {
return videoEncoder.getHeight();
}
/**
* Switch camera used. Can be called on preview or while stream, ignored with preview off.
*
* @throws CameraOpenException If the other camera doesn't support same resolution.
*/
public void switchCamera() throws CameraOpenException {
if (isStreaming() || onPreview) {
cameraManager.switchCamera();
}
}
public GlInterface getGlInterface() {
if (glInterface != null) {
return glInterface;
} else {
throw new RuntimeException("You can't do it. You are not using Opengl");
}
}
/**
* Set video bitrate of H264 in bits per second while stream.
*
* @param bitrate H264 in bits per second.
*/
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
public void setVideoBitrateOnFly(int bitrate) {
videoEncoder.setVideoBitrateOnFly(bitrate);
}
/**
* Set limit FPS while stream. This will be override when you call to prepareVideo method. This
* could produce a change in iFrameInterval.
*
* @param fps frames per second
*/
public void setLimitFPSOnFly(int fps) {
videoEncoder.setFps(fps);
}
/**
* Get stream state.
*
* @return true if streaming, false if not streaming.
*/
public boolean isStreaming() {
return streaming;
}
/**
* Get preview state.
*
* @return true if enabled, false if disabled.
*/
public boolean isOnPreview() {
return onPreview;
}
/**
* Get record state.
*
* @return true if recording, false if not recoding.
*/
public boolean isRecording() {
return recordController.isRunning();
}
public void pauseRecord() {
recordController.pauseRecord();
}
public void resumeRecord() {
recordController.resumeRecord();
}
public RecordController.Status getRecordStatus() {
return recordController.getStatus();
}
protected abstract void getAacDataRtp(ByteBuffer aacBuffer, MediaCodec.BufferInfo info);
@Override
public void getAacData(ByteBuffer aacBuffer, MediaCodec.BufferInfo info) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
recordController.recordAudio(aacBuffer, info);
}
if (streaming) getAacDataRtp(aacBuffer, info);
}
protected abstract void onSpsPpsVpsRtp(ByteBuffer sps, ByteBuffer pps, ByteBuffer vps);
@Override
public void onSpsPps(ByteBuffer sps, ByteBuffer pps) {
if (streaming) onSpsPpsVpsRtp(sps, pps, null);
}
@Override
public void onSpsPpsVps(ByteBuffer sps, ByteBuffer pps, ByteBuffer vps) {
if (streaming) onSpsPpsVpsRtp(sps, pps, vps);
}
protected abstract void getH264DataRtp(ByteBuffer h264Buffer, MediaCodec.BufferInfo info);
@Override
public void getVideoData(ByteBuffer h264Buffer, MediaCodec.BufferInfo info) {
fpsListener.calculateFps();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
recordController.recordVideo(h264Buffer, info);
}
if (streaming) getH264DataRtp(h264Buffer, info);
}
@Override
public void inputPCMData(Frame frame) {
audioEncoder.inputPCMData(frame);
}
@Override
public void inputYUVData(Frame frame) {
videoEncoder.inputYUVData(frame);
}
@Override
public void onVideoFormat(MediaFormat mediaFormat) {
recordController.setVideoFormat(mediaFormat);
}
@Override
public void onAudioFormat(MediaFormat mediaFormat) {
recordController.setAudioFormat(mediaFormat);
}
public abstract void setLogs(boolean enable);
}
|
package dao;
import java.util.Date;
public class Resume_Edu {
int r_num;
String m_id;
String r_title;
String r_pic;
String r_file;
Date r_date;
int edu_num;
String myedu_sdate;
String myedu_edate;
String edu_type;
String edu_school;
String edu_job;
public int getR_num() {
return r_num;
}
public void setR_num(int r_num) {
this.r_num = r_num;
}
public String getM_id() {
return m_id;
}
public void setM_id(String m_id) {
this.m_id = m_id;
}
public String getR_title() {
return r_title;
}
public void setR_title(String r_title) {
this.r_title = r_title;
}
public String getR_pic() {
return r_pic;
}
public void setR_pic(String r_pic) {
this.r_pic = r_pic;
}
public String getR_file() {
return r_file;
}
public void setR_file(String r_file) {
this.r_file = r_file;
}
public Date getR_date() {
return r_date;
}
public void setR_date(Date r_date) {
this.r_date = r_date;
}
public int getEdu_num() {
return edu_num;
}
public void setEdu_num(int edu_num) {
this.edu_num = edu_num;
}
public String getEdu_type() {
return edu_type;
}
public void setEdu_type(String edu_type) {
this.edu_type = edu_type;
}
public String getEdu_school() {
return edu_school;
}
public void setEdu_school(String edu_school) {
this.edu_school = edu_school;
}
public String getEdu_job() {
return edu_job;
}
public void setEdu_job(String edu_job) {
this.edu_job = edu_job;
}
public String getMyedu_sdate() {
return myedu_sdate;
}
public void setMyedu_sdate(String myedu_sdate) {
this.myedu_sdate = myedu_sdate;
}
public String getMyedu_edate() {
return myedu_edate;
}
public void setMyedu_edate(String myedu_edate) {
this.myedu_edate = myedu_edate;
}
}
|
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/datastore/v1/entity.proto
package com.google.datastore.v1;
/**
*
*
* <pre>
* An array value.
* </pre>
*
* Protobuf type {@code google.datastore.v1.ArrayValue}
*/
public final class ArrayValue extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.datastore.v1.ArrayValue)
ArrayValueOrBuilder {
private static final long serialVersionUID = 0L;
// Use ArrayValue.newBuilder() to construct.
private ArrayValue(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private ArrayValue() {
values_ = java.util.Collections.emptyList();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet getUnknownFields() {
return this.unknownFields;
}
private ArrayValue(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
if (!((mutable_bitField0_ & 0x00000001) != 0)) {
values_ = new java.util.ArrayList<com.google.datastore.v1.Value>();
mutable_bitField0_ |= 0x00000001;
}
values_.add(
input.readMessage(com.google.datastore.v1.Value.parser(), extensionRegistry));
break;
}
default:
{
if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this);
} finally {
if (((mutable_bitField0_ & 0x00000001) != 0)) {
values_ = java.util.Collections.unmodifiableList(values_);
}
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.datastore.v1.EntityProto
.internal_static_google_datastore_v1_ArrayValue_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.datastore.v1.EntityProto
.internal_static_google_datastore_v1_ArrayValue_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.datastore.v1.ArrayValue.class,
com.google.datastore.v1.ArrayValue.Builder.class);
}
public static final int VALUES_FIELD_NUMBER = 1;
private java.util.List<com.google.datastore.v1.Value> values_;
/**
*
*
* <pre>
* Values in the array.
* The order of this array may not be preserved if it contains a mix of
* indexed and unindexed values.
* </pre>
*
* <code>repeated .google.datastore.v1.Value values = 1;</code>
*/
public java.util.List<com.google.datastore.v1.Value> getValuesList() {
return values_;
}
/**
*
*
* <pre>
* Values in the array.
* The order of this array may not be preserved if it contains a mix of
* indexed and unindexed values.
* </pre>
*
* <code>repeated .google.datastore.v1.Value values = 1;</code>
*/
public java.util.List<? extends com.google.datastore.v1.ValueOrBuilder> getValuesOrBuilderList() {
return values_;
}
/**
*
*
* <pre>
* Values in the array.
* The order of this array may not be preserved if it contains a mix of
* indexed and unindexed values.
* </pre>
*
* <code>repeated .google.datastore.v1.Value values = 1;</code>
*/
public int getValuesCount() {
return values_.size();
}
/**
*
*
* <pre>
* Values in the array.
* The order of this array may not be preserved if it contains a mix of
* indexed and unindexed values.
* </pre>
*
* <code>repeated .google.datastore.v1.Value values = 1;</code>
*/
public com.google.datastore.v1.Value getValues(int index) {
return values_.get(index);
}
/**
*
*
* <pre>
* Values in the array.
* The order of this array may not be preserved if it contains a mix of
* indexed and unindexed values.
* </pre>
*
* <code>repeated .google.datastore.v1.Value values = 1;</code>
*/
public com.google.datastore.v1.ValueOrBuilder getValuesOrBuilder(int index) {
return values_.get(index);
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
for (int i = 0; i < values_.size(); i++) {
output.writeMessage(1, values_.get(i));
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
for (int i = 0; i < values_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, values_.get(i));
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.datastore.v1.ArrayValue)) {
return super.equals(obj);
}
com.google.datastore.v1.ArrayValue other = (com.google.datastore.v1.ArrayValue) obj;
if (!getValuesList().equals(other.getValuesList())) return false;
if (!unknownFields.equals(other.unknownFields)) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (getValuesCount() > 0) {
hash = (37 * hash) + VALUES_FIELD_NUMBER;
hash = (53 * hash) + getValuesList().hashCode();
}
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.datastore.v1.ArrayValue parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.datastore.v1.ArrayValue parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.datastore.v1.ArrayValue parseFrom(com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.datastore.v1.ArrayValue parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.datastore.v1.ArrayValue parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.datastore.v1.ArrayValue parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.datastore.v1.ArrayValue parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.datastore.v1.ArrayValue parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.datastore.v1.ArrayValue parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.datastore.v1.ArrayValue parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.datastore.v1.ArrayValue parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.datastore.v1.ArrayValue parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.datastore.v1.ArrayValue prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* An array value.
* </pre>
*
* Protobuf type {@code google.datastore.v1.ArrayValue}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.datastore.v1.ArrayValue)
com.google.datastore.v1.ArrayValueOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.datastore.v1.EntityProto
.internal_static_google_datastore_v1_ArrayValue_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.datastore.v1.EntityProto
.internal_static_google_datastore_v1_ArrayValue_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.datastore.v1.ArrayValue.class,
com.google.datastore.v1.ArrayValue.Builder.class);
}
// Construct using com.google.datastore.v1.ArrayValue.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getValuesFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
if (valuesBuilder_ == null) {
values_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
} else {
valuesBuilder_.clear();
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.datastore.v1.EntityProto
.internal_static_google_datastore_v1_ArrayValue_descriptor;
}
@java.lang.Override
public com.google.datastore.v1.ArrayValue getDefaultInstanceForType() {
return com.google.datastore.v1.ArrayValue.getDefaultInstance();
}
@java.lang.Override
public com.google.datastore.v1.ArrayValue build() {
com.google.datastore.v1.ArrayValue result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.datastore.v1.ArrayValue buildPartial() {
com.google.datastore.v1.ArrayValue result = new com.google.datastore.v1.ArrayValue(this);
int from_bitField0_ = bitField0_;
if (valuesBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
values_ = java.util.Collections.unmodifiableList(values_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.values_ = values_;
} else {
result.values_ = valuesBuilder_.build();
}
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.datastore.v1.ArrayValue) {
return mergeFrom((com.google.datastore.v1.ArrayValue) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.datastore.v1.ArrayValue other) {
if (other == com.google.datastore.v1.ArrayValue.getDefaultInstance()) return this;
if (valuesBuilder_ == null) {
if (!other.values_.isEmpty()) {
if (values_.isEmpty()) {
values_ = other.values_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureValuesIsMutable();
values_.addAll(other.values_);
}
onChanged();
}
} else {
if (!other.values_.isEmpty()) {
if (valuesBuilder_.isEmpty()) {
valuesBuilder_.dispose();
valuesBuilder_ = null;
values_ = other.values_;
bitField0_ = (bitField0_ & ~0x00000001);
valuesBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getValuesFieldBuilder()
: null;
} else {
valuesBuilder_.addAllMessages(other.values_);
}
}
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.datastore.v1.ArrayValue parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (com.google.datastore.v1.ArrayValue) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int bitField0_;
private java.util.List<com.google.datastore.v1.Value> values_ =
java.util.Collections.emptyList();
private void ensureValuesIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
values_ = new java.util.ArrayList<com.google.datastore.v1.Value>(values_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.datastore.v1.Value,
com.google.datastore.v1.Value.Builder,
com.google.datastore.v1.ValueOrBuilder>
valuesBuilder_;
/**
*
*
* <pre>
* Values in the array.
* The order of this array may not be preserved if it contains a mix of
* indexed and unindexed values.
* </pre>
*
* <code>repeated .google.datastore.v1.Value values = 1;</code>
*/
public java.util.List<com.google.datastore.v1.Value> getValuesList() {
if (valuesBuilder_ == null) {
return java.util.Collections.unmodifiableList(values_);
} else {
return valuesBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* Values in the array.
* The order of this array may not be preserved if it contains a mix of
* indexed and unindexed values.
* </pre>
*
* <code>repeated .google.datastore.v1.Value values = 1;</code>
*/
public int getValuesCount() {
if (valuesBuilder_ == null) {
return values_.size();
} else {
return valuesBuilder_.getCount();
}
}
/**
*
*
* <pre>
* Values in the array.
* The order of this array may not be preserved if it contains a mix of
* indexed and unindexed values.
* </pre>
*
* <code>repeated .google.datastore.v1.Value values = 1;</code>
*/
public com.google.datastore.v1.Value getValues(int index) {
if (valuesBuilder_ == null) {
return values_.get(index);
} else {
return valuesBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* Values in the array.
* The order of this array may not be preserved if it contains a mix of
* indexed and unindexed values.
* </pre>
*
* <code>repeated .google.datastore.v1.Value values = 1;</code>
*/
public Builder setValues(int index, com.google.datastore.v1.Value value) {
if (valuesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureValuesIsMutable();
values_.set(index, value);
onChanged();
} else {
valuesBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* Values in the array.
* The order of this array may not be preserved if it contains a mix of
* indexed and unindexed values.
* </pre>
*
* <code>repeated .google.datastore.v1.Value values = 1;</code>
*/
public Builder setValues(int index, com.google.datastore.v1.Value.Builder builderForValue) {
if (valuesBuilder_ == null) {
ensureValuesIsMutable();
values_.set(index, builderForValue.build());
onChanged();
} else {
valuesBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Values in the array.
* The order of this array may not be preserved if it contains a mix of
* indexed and unindexed values.
* </pre>
*
* <code>repeated .google.datastore.v1.Value values = 1;</code>
*/
public Builder addValues(com.google.datastore.v1.Value value) {
if (valuesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureValuesIsMutable();
values_.add(value);
onChanged();
} else {
valuesBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* Values in the array.
* The order of this array may not be preserved if it contains a mix of
* indexed and unindexed values.
* </pre>
*
* <code>repeated .google.datastore.v1.Value values = 1;</code>
*/
public Builder addValues(int index, com.google.datastore.v1.Value value) {
if (valuesBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureValuesIsMutable();
values_.add(index, value);
onChanged();
} else {
valuesBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* Values in the array.
* The order of this array may not be preserved if it contains a mix of
* indexed and unindexed values.
* </pre>
*
* <code>repeated .google.datastore.v1.Value values = 1;</code>
*/
public Builder addValues(com.google.datastore.v1.Value.Builder builderForValue) {
if (valuesBuilder_ == null) {
ensureValuesIsMutable();
values_.add(builderForValue.build());
onChanged();
} else {
valuesBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Values in the array.
* The order of this array may not be preserved if it contains a mix of
* indexed and unindexed values.
* </pre>
*
* <code>repeated .google.datastore.v1.Value values = 1;</code>
*/
public Builder addValues(int index, com.google.datastore.v1.Value.Builder builderForValue) {
if (valuesBuilder_ == null) {
ensureValuesIsMutable();
values_.add(index, builderForValue.build());
onChanged();
} else {
valuesBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* Values in the array.
* The order of this array may not be preserved if it contains a mix of
* indexed and unindexed values.
* </pre>
*
* <code>repeated .google.datastore.v1.Value values = 1;</code>
*/
public Builder addAllValues(
java.lang.Iterable<? extends com.google.datastore.v1.Value> values) {
if (valuesBuilder_ == null) {
ensureValuesIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, values_);
onChanged();
} else {
valuesBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* Values in the array.
* The order of this array may not be preserved if it contains a mix of
* indexed and unindexed values.
* </pre>
*
* <code>repeated .google.datastore.v1.Value values = 1;</code>
*/
public Builder clearValues() {
if (valuesBuilder_ == null) {
values_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
valuesBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* Values in the array.
* The order of this array may not be preserved if it contains a mix of
* indexed and unindexed values.
* </pre>
*
* <code>repeated .google.datastore.v1.Value values = 1;</code>
*/
public Builder removeValues(int index) {
if (valuesBuilder_ == null) {
ensureValuesIsMutable();
values_.remove(index);
onChanged();
} else {
valuesBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* Values in the array.
* The order of this array may not be preserved if it contains a mix of
* indexed and unindexed values.
* </pre>
*
* <code>repeated .google.datastore.v1.Value values = 1;</code>
*/
public com.google.datastore.v1.Value.Builder getValuesBuilder(int index) {
return getValuesFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* Values in the array.
* The order of this array may not be preserved if it contains a mix of
* indexed and unindexed values.
* </pre>
*
* <code>repeated .google.datastore.v1.Value values = 1;</code>
*/
public com.google.datastore.v1.ValueOrBuilder getValuesOrBuilder(int index) {
if (valuesBuilder_ == null) {
return values_.get(index);
} else {
return valuesBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* Values in the array.
* The order of this array may not be preserved if it contains a mix of
* indexed and unindexed values.
* </pre>
*
* <code>repeated .google.datastore.v1.Value values = 1;</code>
*/
public java.util.List<? extends com.google.datastore.v1.ValueOrBuilder>
getValuesOrBuilderList() {
if (valuesBuilder_ != null) {
return valuesBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(values_);
}
}
/**
*
*
* <pre>
* Values in the array.
* The order of this array may not be preserved if it contains a mix of
* indexed and unindexed values.
* </pre>
*
* <code>repeated .google.datastore.v1.Value values = 1;</code>
*/
public com.google.datastore.v1.Value.Builder addValuesBuilder() {
return getValuesFieldBuilder().addBuilder(com.google.datastore.v1.Value.getDefaultInstance());
}
/**
*
*
* <pre>
* Values in the array.
* The order of this array may not be preserved if it contains a mix of
* indexed and unindexed values.
* </pre>
*
* <code>repeated .google.datastore.v1.Value values = 1;</code>
*/
public com.google.datastore.v1.Value.Builder addValuesBuilder(int index) {
return getValuesFieldBuilder()
.addBuilder(index, com.google.datastore.v1.Value.getDefaultInstance());
}
/**
*
*
* <pre>
* Values in the array.
* The order of this array may not be preserved if it contains a mix of
* indexed and unindexed values.
* </pre>
*
* <code>repeated .google.datastore.v1.Value values = 1;</code>
*/
public java.util.List<com.google.datastore.v1.Value.Builder> getValuesBuilderList() {
return getValuesFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.datastore.v1.Value,
com.google.datastore.v1.Value.Builder,
com.google.datastore.v1.ValueOrBuilder>
getValuesFieldBuilder() {
if (valuesBuilder_ == null) {
valuesBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.datastore.v1.Value,
com.google.datastore.v1.Value.Builder,
com.google.datastore.v1.ValueOrBuilder>(
values_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean());
values_ = null;
}
return valuesBuilder_;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.datastore.v1.ArrayValue)
}
// @@protoc_insertion_point(class_scope:google.datastore.v1.ArrayValue)
private static final com.google.datastore.v1.ArrayValue DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.datastore.v1.ArrayValue();
}
public static com.google.datastore.v1.ArrayValue getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<ArrayValue> PARSER =
new com.google.protobuf.AbstractParser<ArrayValue>() {
@java.lang.Override
public ArrayValue parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new ArrayValue(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<ArrayValue> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<ArrayValue> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.datastore.v1.ArrayValue getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
/*
* Copyright 2014 Red Hat, Inc. and/or 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.drools.workbench.screens.guided.dtree.backend.server.indexing;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import org.apache.lucene.search.Query;
import org.drools.workbench.screens.guided.dtree.type.GuidedDTreeResourceTypeDefinition;
import org.guvnor.common.services.project.categories.Decision;
import org.junit.Test;
import org.kie.workbench.common.services.refactoring.backend.server.BaseIndexingTest;
import org.kie.workbench.common.services.refactoring.backend.server.TestIndexer;
import org.kie.workbench.common.services.refactoring.backend.server.query.builder.SingleTermQueryBuilder;
import org.kie.workbench.common.services.refactoring.model.index.terms.valueterms.ValueIndexTerm.TermSearchType;
import org.kie.workbench.common.services.refactoring.model.index.terms.valueterms.ValueResourceIndexTerm;
import org.kie.workbench.common.services.refactoring.service.ResourceType;
import org.uberfire.ext.metadata.io.KObjectUtil;
import org.uberfire.java.nio.file.Path;
public class IndexRuleTest extends BaseIndexingTest<GuidedDTreeResourceTypeDefinition> {
@Test
public void testIndexDrlRules() throws IOException, InterruptedException {
//Add test files
final Path path = basePath.resolve( "drl1.tdrl" );
final String drl = loadText( "drl1.tdrl" );
ioService().write( path,
drl );
Thread.sleep( 5000 ); //wait for events to be consumed from jgit -> (notify changes -> watcher -> index) -> lucene index
List<String> index = Arrays.asList(KObjectUtil.toKCluster(basePath).getClusterId());
{
final Query query = new SingleTermQueryBuilder( new ValueResourceIndexTerm( "*myRule", ResourceType.RULE, TermSearchType.WILDCARD ) )
.build();
searchFor(index, query, 1);
}
}
@Override
protected TestIndexer getIndexer() {
return new TestGuidedDecisionTreeFileIndexer();
}
@Override
protected GuidedDTreeResourceTypeDefinition getResourceTypeDefinition() {
return new GuidedDTreeResourceTypeDefinition(new Decision());
}
@Override
protected String getRepositoryName() {
return this.getClass().getSimpleName();
}
}
|
/*
* Copyright (C) 2011 Clearspring Technologies, 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.clearspring.analytics.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import com.clearspring.analytics.stream.cardinality.AdaptiveCounting;
import com.clearspring.analytics.stream.cardinality.ICardinality;
/**
* Simple cardinality estimation command line utility
* <p/>
* Usage:
* > obycount [update-rate]
* <p/>
* update-rate: output results after every update-rate elements/lines
* <p/>
* Example:
* > cat elements.txt | obycount
*/
public class ObyCount {
public static void usage() {
System.err.println
(
"obycount [update-rate]\n" +
"\n" +
"update-rate: output results after every update-rate elements/lines" +
"\n" +
"Example:" +
"> cat elements.txt | obycount" +
"\n"
);
System.exit(-1);
}
public static void main(String[] args) throws IOException {
long updateRate = -1;
long count = 0;
if (args.length > 0) {
try {
updateRate = Long.parseLong(args[0]);
} catch (NumberFormatException e) {
System.err.print("Bad update rate: '" + args[0] + "' Update rate must be an integer.");
usage();
}
}
ICardinality card = AdaptiveCounting.Builder.obyCount(Integer.MAX_VALUE).build();
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line = null;
while ((line = in.readLine()) != null) {
card.offer(line);
count++;
if (updateRate > 0 && count % updateRate == 0) {
System.out.println(formatSummary(count, card.cardinality()));
}
}
System.out.println(formatSummary(count, card.cardinality()));
}
protected static String formatSummary(long count, long cardinality) {
String cntStr = Long.toString(count);
int len = cntStr.length();
int l1 = Math.max(len, 10);
int l2 = Math.max(len, 20);
String fmt = "%" + l1 + "s %" + l2 + "s";
StringBuilder sb = new StringBuilder();
sb.append(String.format(fmt, "Item Count", "Cardinality Estimate")).append('\n');
sb.append(String.format(fmt, TopK.string('-', l1), TopK.string('-', l2))).append('\n');
sb.append(String.format(fmt, count, cardinality)).append('\n');
return sb.toString();
}
}
|
package com.taotao.cloud.java.javase.day17.chap17_3;
/**
* 单例第三种写法:静态内部类写法
* @author shuigedeng
*
*/
public class SingleTon3 {
private SingleTon3() {}
private static class Holder{
static SingleTon3 instance=new SingleTon3();
}
public static SingleTon3 getInstance() {
return Holder.instance;
}
}
|
/*
* Copyright 2016 Red Hat, Inc. and/or 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.kie.dmn.feel.lang.ast;
import org.antlr.v4.runtime.ParserRuleContext;
import org.kie.dmn.feel.lang.EvaluationContext;
import org.kie.dmn.feel.lang.Type;
public class ContextEntryNode
extends BaseNode {
private BaseNode name;
private BaseNode value;
public ContextEntryNode(ParserRuleContext ctx) {
super( ctx );
}
public ContextEntryNode(ParserRuleContext ctx, BaseNode name, BaseNode value) {
super( ctx );
this.name = name;
this.value = value;
}
public BaseNode getName() {
return name;
}
public void setName(BaseNode name) {
this.name = name;
}
public BaseNode getValue() {
return value;
}
public void setValue(BaseNode value) {
this.value = value;
}
public String evaluateName( EvaluationContext ctx ) {
return (String) name.evaluate( ctx );
}
@Override
public Object evaluate(EvaluationContext ctx) {
return value.evaluate( ctx );
}
@Override
public Type getResultType() {
return value.getResultType();
}
}
|
/*
* Copyright (c) 2015 Falko Schumann
* Released under the terms of the MIT License.
*/
package de.muspellheim.datenverteiler.betriebsmeldungen;
import de.bsvrz.dav.daf.main.config.SystemObject;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotSame;
import static org.mockito.Mockito.mock;
public class BetriebsmeldungTest {
@Test
public void testCloneEqualsHashcode() {
Betriebsmeldung meldung = new Betriebsmeldung();
meldung.setApplikationsId(1);
meldung.setLaufendeNummer(2);
SystemObject applikationstyp = mock(SystemObject.class, "typ.applikation");
meldung.setApplikationstyp(applikationstyp);
meldung.setApplikationskennung("Foo");
meldung.setId("mq.mq0001");
meldung.setTyp(Meldungstyp.FACH);
meldung.setTypzusatz("-");
meldung.setKlasse(Meldungsklasse.INFORMATION);
SystemObject mq = mock(SystemObject.class, "typ.messQuerschnitt");
meldung.setReferenz(mq);
meldung.setStatus(Meldungsstatus.MELDUNG);
meldung.setText("");
SystemObject benutzer = mock(SystemObject.class, "Tester");
meldung.getUrlasser().setBenutzer(benutzer);
meldung.getUrlasser().setUrsache("Test");
meldung.getUrlasser().setVeranlasser("JUnit");
Betriebsmeldung klon = meldung.clone();
assertNotSame(klon, meldung);
assertEquals(klon, meldung);
assertEquals(klon.hashCode(), meldung.hashCode());
}
}
|
package com.majing.learning.elasticsearch.pool;
/**
* @author : jingma2
* @date : 2018/7/21
* @description
*/
public class HostAndPort {
private String nodeName;
private String host ;
private int port ;
private String schema;
public HostAndPort(String nodeName, String host, int port, String schema) {
this.nodeName = nodeName;
this.host = host;
this.port = port;
this.schema = schema;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public String getSchema() {
return schema;
}
public void setSchema(String schema) {
this.schema = schema;
}
}
|
package common.zeroquest;
import common.zeroquest.entity.EntityDarkZertum;
import common.zeroquest.entity.EntityDestroZertum;
import common.zeroquest.entity.EntityJakan;
import common.zeroquest.entity.EntityJakanPrime;
import common.zeroquest.entity.EntityRedZertum;
import common.zeroquest.entity.EntityZertum;
import common.zeroquest.entity.projectile.EntityFlamingPoisonball;
import common.zeroquest.tileentity.TileEntityNileTable;
import net.minecraft.entity.EntityList;
import net.minecraft.entity.EnumCreatureType;
import cpw.mods.fml.common.registry.EntityRegistry;
import cpw.mods.fml.common.registry.GameRegistry;
public class ModEntities {
public static int startEntityId = 300;
public static final String tag = "EntityName";
//Put Creature Entities in CustomEntityList//
//Put Renderers in ClientProxy//
//Put Guis in CommonProxy//
public static void loadCreatures() {
registerEntity(EntityZertum.class, "Zertum", 0);
EntityRegistry.addSpawn(EntityZertum.class, 10, 2, 5, EnumCreatureType.creature);
registerEntity(EntityRedZertum.class, "RedZertum", 1);
EntityRegistry.addSpawn(EntityRedZertum.class, 10, 3, 6, EnumCreatureType.creature);
registerEntity(EntityDestroZertum.class, "DestroZertum", 2);
EntityRegistry.addSpawn(EntityDestroZertum.class, 10, 3, 6, EnumCreatureType.creature);
registerEntity(EntityJakan.class, "Jakan", 3);
EntityRegistry.addSpawn(EntityJakan.class, 10, 3, 6, EnumCreatureType.creature);
registerEntity(EntityJakanPrime.class, "JakanPrime", 4);
EntityRegistry.addSpawn(EntityJakanPrime.class, 10, 3, 6, EnumCreatureType.creature);
}
public static void loadDarkCreatures(){
registerEntity(EntityDarkZertum.class, "DarkZertum", 30);
EntityRegistry.addSpawn(EntityDarkZertum.class, 10, 3, 6, EnumCreatureType.creature);
}
public static void loadTileEntities() {
GameRegistry.registerTileEntity(TileEntityNileTable.class, "Nile Worktable");
}
public static void loadProjectiles() {
registerProjectileEntity(EntityFlamingPoisonball.class, "FPoisonball", 400);
//EntityRegistry.registerGlobalEntityID(EntityFlamingPoisonball.class, "FPoisonball", EntityRegistry.findGlobalUniqueEntityId());
}
public static void registerEntity(Class entityClass, String saveName, int id) {
EntityRegistry.registerModEntity(entityClass, saveName, id, ZeroQuest.instance, 80, 3, false);
}
public static void registerProjectileEntity(Class entityClass, String saveName, int id) {
EntityRegistry.registerModEntity(entityClass, saveName, id, ZeroQuest.instance, 128, 1, true);
}
public static int getUniqueEntityId()
{
do
{
startEntityId++;
}
while(EntityList.getStringFromID(startEntityId) != null);
return startEntityId;
}
}
|
/*
This file is part of the iText (R) project.
Copyright (c) 1998-2020 iText Group NV
Authors: iText Software.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation with the addition of the
following permission added to Section 15 as permitted in Section 7(a):
FOR ANY PART OF THE COVERED WORK IN WHICH THE COPYRIGHT IS OWNED BY
ITEXT GROUP. ITEXT GROUP DISCLAIMS THE WARRANTY OF NON INFRINGEMENT
OF THIRD PARTY RIGHTS
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program; if not, see http://www.gnu.org/licenses or write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA, 02110-1301 USA, or download the license from the following URL:
http://itextpdf.com/terms-of-use/
The interactive user interfaces in modified source and object code versions
of this program must display Appropriate Legal Notices, as required under
Section 5 of the GNU Affero General Public License.
In accordance with Section 7(b) of the GNU Affero General Public License,
a covered work must retain the producer line in every PDF that is created
or manipulated using iText.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the iText software without
disclosing the source code of your own applications.
These activities include: offering paid services to customers as an ASP,
serving PDFs on the fly in a web application, shipping iText with a closed
source product.
For more information, please contact iText Software Corp. at this
address: sales@itextpdf.com
*/
package com.itextpdf.kernel.colors;
/**
* Class containing predefined {@link DeviceRgb} colors.
* Color space specific classes should be used for the advanced handling of colors.
* The most common ones are {@link DeviceGray}, {@link DeviceCmyk} and {@link DeviceRgb}.
*/
public class ColorConstants {
/**
* Predefined black DeviceRgb color
*/
public static final Color BLACK = DeviceRgb.BLACK;
/**
* Predefined blue DeviceRgb color
*/
public static final Color BLUE = DeviceRgb.BLUE;
/**
* Predefined cyan DeviceRgb color
*/
public static final Color CYAN = new DeviceRgb(0, 255, 255);
/**
* Predefined dark gray DeviceRgb color
*/
public static final Color DARK_GRAY = new DeviceRgb(64, 64, 64);
/**
* Predefined gray DeviceRgb color
*/
public static final Color GRAY = new DeviceRgb(128, 128, 128);
/**
* Predefined green DeviceRgb color
*/
public static final Color GREEN = DeviceRgb.GREEN;
/**
* Predefined light gray DeviceRgb color
*/
public static final Color LIGHT_GRAY = new DeviceRgb(192, 192, 192);
/**
* Predefined magenta DeviceRgb color
*/
public static final Color MAGENTA = new DeviceRgb(255, 0, 255);
/**
* Predefined orange DeviceRgb color
*/
public static final Color ORANGE = new DeviceRgb(255, 200, 0);
/**
* Predefined pink DeviceRgb color
*/
public static final Color PINK = new DeviceRgb(255, 175, 175);
/**
* Predefined red DeviceRgb color
*/
public static final Color RED = DeviceRgb.RED;
/**
* Predefined white DeviceRgb color
*/
public static final Color WHITE = DeviceRgb.WHITE;
/**
* Predefined yellow DeviceRgb color
*/
public static final Color YELLOW = new DeviceRgb(255, 255, 0);
}
|
package cn.e3mall.solrj;
import java.util.List;
import java.util.Map;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;
import org.junit.Test;
public class TestSolrj {
@Test
public void addDocument() throws Exception {
//创建一个solrserver对象,创建一个连接。参数solr服务的url
SolrServer solrServer = new HttpSolrServer("http://192.168.25.128:8081/solr/collection1");
//创建一个文档对象,solrinputdocument
SolrInputDocument document = new SolrInputDocument();
//向文档对象中添加域。文档中必须包含一个id域,所有的域的名称必须在scheme.xml中定义
document.addField("id", "doc01");
document.addField("item_title", "测试商品01");
document.addField("item_price", 999);
//把文档写入索引库
solrServer.add(document);
//提交
solrServer.commit();
}
@Test
public void delDocument() throws Exception {
//创建一个solrserver对象,创建一个连接。参数solr服务的url
SolrServer solrServer = new HttpSolrServer("http://192.168.25.128:8081/solr/collection1");
//删除文档
solrServer.deleteById("doc01");
//提交
solrServer.commit();
}
@Test
public void queryIndex() throws Exception{
//创建一个solrserver对象
SolrServer solrServer = new HttpSolrServer("http://192.168.25.128:8081/solr/collection1");
//创建一个solrquery对象
SolrQuery solrQuery = new SolrQuery();
//设置查询条件
solrQuery.setQuery("*:*");
//执行查询,queryresponse对象
QueryResponse queryResponse = solrServer.query(solrQuery);
//取文档列表。取查询结果的总记录数
SolrDocumentList results = queryResponse.getResults();
long num = results.getNumFound();
System.out.println("总数" + num);
//遍历文档列表,从取域的内容
for (SolrDocument solrDocument : results) {
System.out.println(solrDocument.get("id"));
System.out.println(solrDocument.get("item_title"));
System.out.println(solrDocument.get("item_sell_point"));
System.out.println(solrDocument.get("item_price"));
System.out.println(solrDocument.get("item_image"));
System.out.println(solrDocument.get("item_category_name"));
System.out.println("__________________________________");
}
}
@Test
public void queryIndexComplicate() throws Exception{
//创建一个solrserver对象
SolrServer solrServer = new HttpSolrServer("http://192.168.25.128:8081/solr/collection1");
//创建一个solrquery对象
SolrQuery solrQuery = new SolrQuery();
//设置查询条件
solrQuery.setQuery("手机");
solrQuery.setStart(0);
solrQuery.setRows(20);
solrQuery.set("df", "item_title");
solrQuery.setHighlight(true);
solrQuery.addHighlightField("item_title");
solrQuery.setHighlightSimplePre("<em>");
solrQuery.setHighlightSimplePost("</em>");
//执行查询,queryresponse对象
QueryResponse queryResponse = solrServer.query(solrQuery);
//取文档列表。取查询结果的总记录数
SolrDocumentList results = queryResponse.getResults();
long num = results.getNumFound();
System.out.println("总数" + num);
//遍历文档列表,从取域的内容
for (SolrDocument solrDocument : results) {
System.out.println(solrDocument.get("id"));
//取高亮显示
Map<String, Map<String, List<String>>> highlighting = queryResponse.getHighlighting();
List<String> list = highlighting.get(solrDocument.get("id")).get("item_title");
String title = "";
if (list != null && list.size() > 0) {
title = list.get(0);
}else {
title = (String)solrDocument.get("item_title");
}
System.out.println(title);
System.out.println(solrDocument.get("item_sell_point"));
System.out.println(solrDocument.get("item_price"));
System.out.println(solrDocument.get("item_image"));
System.out.println(solrDocument.get("item_category_name"));
System.out.println("__________________________________");
}
}
}
|
/*
* Copyright 2015-2020 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.config.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.Request;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.config.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.protocol.*;
import com.amazonaws.protocol.Protocol;
import com.amazonaws.annotation.SdkInternalApi;
/**
* DeleteConfigurationAggregatorRequest Marshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class DeleteConfigurationAggregatorRequestProtocolMarshaller implements
Marshaller<Request<DeleteConfigurationAggregatorRequest>, DeleteConfigurationAggregatorRequest> {
private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.AWS_JSON).requestUri("/")
.httpMethodName(HttpMethodName.POST).hasExplicitPayloadMember(false).hasPayloadMembers(true)
.operationIdentifier("StarlingDoveService.DeleteConfigurationAggregator").serviceName("AmazonConfig").build();
private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory;
public DeleteConfigurationAggregatorRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) {
this.protocolFactory = protocolFactory;
}
public Request<DeleteConfigurationAggregatorRequest> marshall(DeleteConfigurationAggregatorRequest deleteConfigurationAggregatorRequest) {
if (deleteConfigurationAggregatorRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
final ProtocolRequestMarshaller<DeleteConfigurationAggregatorRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller(
SDK_OPERATION_BINDING, deleteConfigurationAggregatorRequest);
protocolMarshaller.startMarshalling();
DeleteConfigurationAggregatorRequestMarshaller.getInstance().marshall(deleteConfigurationAggregatorRequest, protocolMarshaller);
return protocolMarshaller.finishMarshalling();
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
|
package commandGenerator.arguments.command.arguments;
import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import javax.swing.JCheckBox;
import javax.swing.JPanel;
import commandGenerator.arguments.command.Argument;
import commandGenerator.gui.helper.components.CEntry;
import commandGenerator.main.DisplayHelper;
public class StringArgument extends Argument
{
private JCheckBox box;
private CEntry entry;
private boolean spacesAllowed;
public StringArgument(String id, boolean isCompulsery)
{
super(id, isCompulsery);
this.spacesAllowed = false;
}
@Override
public String generateCommand()
{
String name = this.entry.getText();
if (!this.spacesAllowed && (name.equals("") || name.contains(" ")))
{
DisplayHelper.warningName();
return null;
}
return name;
}
@Override
public Component generateComponent()
{
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
panel.add(this.box, gbc);
gbc.gridx++;
panel.add(this.entry, gbc);
return panel;
}
@Override
public void initGui()
{
this.entry = new CEntry("GUI:" + this.getId(), "");
this.box = new JCheckBox();
this.box.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0)
{
entry.setEnabledContent(box.isSelected());
}
});
this.entry.setEnabledContent(this.isCompulsery());
this.box.setVisible(!this.isCompulsery());
}
@Override
public boolean isUsed()
{
return this.isCompulsery() || this.box.isSelected();
}
@Override
public boolean matches(List<String> data)
{
return true;
}
@Override
public void setupFrom(List<String> data)
{
this.box.setSelected(true);
this.entry.setEnabledContent(true);
String text = "";
for (int i = 0; i < data.size(); i++)
{
if (i > 0) text += " ";
text += data.get(i);
}
this.entry.setTextField(text);
}
@Override
public void synchronize(Argument toMatch)
{
if (!(toMatch instanceof StringArgument)) return;
if (!this.isCompulsery()) this.box.setSelected(toMatch.isUsed());
this.entry.setTextField(((StringArgument) toMatch).entry.getText());
}
@Override
public void reset()
{
this.entry.reset();
if (!this.isCompulsery())
{
this.box.setSelected(false);
this.entry.setEnabledContent(false);
}
}
public StringArgument setSpacesAllowed()
{
this.spacesAllowed = true;
this.setMaximumLength(100);
return this;
}
}
|
/*
* Copyright (C) 2018 Shehab Salah
*
* 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.shehabsalah.movieappmvp.data.source.remote.response;
import com.shehabsalah.movieappmvp.data.MovieReviews;
import java.util.ArrayList;
/**
* Created by ShehabSalah on 1/12/18.
*
*/
public class ReviewsResponse extends GeneralResponse{
private ArrayList<MovieReviews> results;
public ReviewsResponse(String result, String message) {
super(result, message);
}
public ArrayList<MovieReviews> getResults() {
return results;
}
public void setResults(ArrayList<MovieReviews> results) {
this.results = results;
}
}
|
package net.siisise.rss;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.DateFormat;
import javax.xml.parsers.ParserConfigurationException;
import org.junit.jupiter.api.Test;
import org.xml.sax.SAXException;
/**
*
* @author okome
*/
public class RSS10Test {
String[] rss = {
"https://pc.watch.impress.co.jp/data/rss/1.0/pcw/feed.rdf",
"https://www.soumu.go.jp/news.rdf", // 総務省
"https://www.mhlw.go.jp/stf/news.rdf", // 厚生労働省
// "https://www.fsa.go.jp/fsaNewsListAll_rss2.xml",
"https://www.caa.go.jp/news.rss", // 消費者庁
"https://ascii.jp/rss.xml",
"https://ascii.jp/digital/rss.xml",
"https://news.yahoo.co.jp/rss/topics/it.xml",
"https://news.mynavi.jp/rss/digital/kaden/audio",
"https://rss.itmedia.co.jp/rss/2.0/itmedia_all.xml",
"https://www.gizmodo.jp/index.xml",
"https://srad.jp/sradjp.rss"
// 読めない 2020-12-18
// "https://www.e-gov.go.jp/news/news.xml",
// "https://developer.e-gov.go.jp/contents/news/news.xml"
};
public RSS10Test() {
}
@Test
public void testSomeMethod() throws URISyntaxException, ParserConfigurationException, SAXException, IOException {
System.out.println("read");
String[] argv = null;
DateFormat df = DateFormat.getDateTimeInstance();
Channel ch = new Channel();
for ( String rsss : rss ) {
URI uri = new URI(rsss);
System.out.println(rsss);
new RSS().read(ch, uri);
// System.out.println(JSON2.valueOf(ch));
}
for ( Item item : ch.items ) {
System.out.println("たいとる:" + item.title);
System.out.println("りんく:" + item.link);
if ( item.pubDate != null ) {
System.out.println("にちじ:" + df.format(item.pubDate));
}
System.out.println(item.description);
}
// TODO review the generated test code and remove the default call to fail.
// fail("The test case is a prototype.");
}
}
|
package org.apereo.cas.webauthn.web.flow;
import org.apereo.cas.configuration.CasConfigurationProperties;
import org.apereo.cas.util.CollectionUtils;
import org.apereo.cas.web.flow.CasWebflowConstants;
import org.apereo.cas.web.flow.configurer.AbstractCasMultifactorWebflowConfigurer;
import org.apereo.cas.web.flow.configurer.CasMultifactorWebflowCustomizer;
import org.apereo.cas.webauthn.WebAuthnCredential;
import lombok.val;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.util.StringUtils;
import org.springframework.webflow.definition.registry.FlowDefinitionRegistry;
import org.springframework.webflow.engine.builder.support.FlowBuilderServices;
import java.util.List;
import java.util.Map;
import java.util.Optional;
/**
* This is {@link WebAuthnMultifactorWebflowConfigurer}.
*
* @author Misagh Moayyed
* @since 6.1.0
*/
public class WebAuthnMultifactorWebflowConfigurer extends AbstractCasMultifactorWebflowConfigurer {
/**
* Webflow event id.
*/
public static final String MFA_WEB_AUTHN_EVENT_ID = "mfa-webauthn";
private static final String TRANSITION_ID_VALIDATE_WEBAUTHN = "validateWebAuthn";
public WebAuthnMultifactorWebflowConfigurer(final FlowBuilderServices flowBuilderServices,
final FlowDefinitionRegistry loginFlowDefinitionRegistry,
final FlowDefinitionRegistry flowDefinitionRegistry,
final ConfigurableApplicationContext applicationContext,
final CasConfigurationProperties casProperties,
final List<CasMultifactorWebflowCustomizer> mfaFlowCustomizers) {
super(flowBuilderServices, loginFlowDefinitionRegistry, applicationContext,
casProperties, Optional.of(flowDefinitionRegistry), mfaFlowCustomizers);
}
@Override
protected void doInitialize() {
multifactorAuthenticationFlowDefinitionRegistries.forEach(registry -> {
val flow = getFlow(registry, MFA_WEB_AUTHN_EVENT_ID);
createFlowVariable(flow, CasWebflowConstants.VAR_ID_CREDENTIAL, WebAuthnCredential.class);
flow.getStartActionList().add(createEvaluateAction(CasWebflowConstants.ACTION_ID_INITIAL_FLOW_SETUP));
createEndState(flow, CasWebflowConstants.STATE_ID_SUCCESS);
val initLoginFormState = createActionState(flow, CasWebflowConstants.STATE_ID_INIT_LOGIN_FORM,
createEvaluateAction(CasWebflowConstants.ACTION_ID_INIT_LOGIN_ACTION));
createTransitionForState(initLoginFormState, CasWebflowConstants.TRANSITION_ID_SUCCESS, "accountRegistrationCheck");
setStartState(flow, initLoginFormState);
val acctRegCheckState = createActionState(flow, "accountRegistrationCheck",
createEvaluateAction("webAuthnCheckAccountRegistrationAction"));
createTransitionForState(acctRegCheckState, CasWebflowConstants.TRANSITION_ID_REGISTER, "viewRegistrationWebAuthn");
createTransitionForState(acctRegCheckState, CasWebflowConstants.TRANSITION_ID_SUCCESS,
CasWebflowConstants.STATE_ID_VIEW_LOGIN_FORM);
val setPrincipalAction = createSetAction("viewScope.principal", "conversationScope.authentication.principal");
val viewRegState = createViewState(flow, "viewRegistrationWebAuthn", "casWebAuthnRegistrationView");
viewRegState.getEntryActionList().addAll(createEvaluateAction("webAuthnStartRegistrationAction"), setPrincipalAction);
createTransitionForState(viewRegState, CasWebflowConstants.TRANSITION_ID_SUBMIT, "saveRegistration");
val saveState = createActionState(flow, "saveRegistration", "webAuthnSaveAccountRegistrationAction");
createTransitionForState(saveState, CasWebflowConstants.TRANSITION_ID_SUCCESS, "accountRegistrationCheck");
createTransitionForState(saveState, CasWebflowConstants.TRANSITION_ID_ERROR, CasWebflowConstants.STATE_ID_STOP_WEBFLOW);
val loginProperties = CollectionUtils.wrapList("token");
val loginBinder = createStateBinderConfiguration(loginProperties);
val viewLoginFormState = createViewState(flow,
CasWebflowConstants.STATE_ID_VIEW_LOGIN_FORM, "casWebAuthnLoginView", loginBinder);
createStateModelBinding(viewLoginFormState, CasWebflowConstants.VAR_ID_CREDENTIAL, WebAuthnCredential.class);
viewLoginFormState.getEntryActionList().addAll(
createEvaluateAction("webAuthnStartAuthenticationAction"), setPrincipalAction);
createTransitionForState(viewLoginFormState, TRANSITION_ID_VALIDATE_WEBAUTHN,
CasWebflowConstants.STATE_ID_REAL_SUBMIT, Map.of("bind", Boolean.TRUE, "validate", Boolean.TRUE));
val realSubmitState = createActionState(flow, CasWebflowConstants.STATE_ID_REAL_SUBMIT,
createEvaluateAction("webAuthnAuthenticationWebflowAction"));
createTransitionForState(realSubmitState, CasWebflowConstants.TRANSITION_ID_SUCCESS, CasWebflowConstants.STATE_ID_SUCCESS);
createTransitionForState(realSubmitState, CasWebflowConstants.TRANSITION_ID_ERROR, CasWebflowConstants.STATE_ID_VIEW_LOGIN_FORM);
createViewState(flow, CasWebflowConstants.STATE_ID_STOP_WEBFLOW, CasWebflowConstants.VIEW_ID_ERROR);
});
val webAuthn = casProperties.getAuthn().getMfa().getWebAuthn();
registerMultifactorProviderAuthenticationWebflow(getLoginFlow(), MFA_WEB_AUTHN_EVENT_ID, webAuthn.getId());
val flow = getLoginFlow();
if (flow != null && webAuthn.isAllowPrimaryAuthentication()) {
val setAppIdAction = createSetAction("flowScope." + WebAuthnStartRegistrationAction.FLOW_SCOPE_WEB_AUTHN_APPLICATION_ID,
StringUtils.quote(webAuthn.getApplicationId()));
flow.getStartActionList().add(setAppIdAction);
val setPrimaryAuthAction = createSetAction("flowScope.webAuthnPrimaryAuthenticationEnabled", "true");
flow.getStartActionList().add(setPrimaryAuthAction);
val viewLoginFormState = getState(flow, CasWebflowConstants.STATE_ID_VIEW_LOGIN_FORM);
createTransitionForState(viewLoginFormState, TRANSITION_ID_VALIDATE_WEBAUTHN, "validateWebAuthnToken");
val validateAction = createActionState(flow, "validateWebAuthnToken", "webAuthnValidateSessionCredentialTokenAction");
validateAction.getEntryActionList()
.add(createSetAction("flowScope.".concat(CasWebflowConstants.VAR_ID_MFA_PROVIDER_ID), StringUtils.quote(webAuthn.getId())));
createTransitionForState(validateAction,
CasWebflowConstants.TRANSITION_ID_FINALIZE, CasWebflowConstants.STATE_ID_REAL_SUBMIT);
}
}
}
|
/*
* 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.myfaces.tobago.internal.taglib.component;
import org.apache.myfaces.tobago.apt.annotation.Behavior;
import org.apache.myfaces.tobago.apt.annotation.BodyContentDescription;
import org.apache.myfaces.tobago.apt.annotation.Facet;
import org.apache.myfaces.tobago.apt.annotation.Markup;
import org.apache.myfaces.tobago.apt.annotation.Tag;
import org.apache.myfaces.tobago.apt.annotation.UIComponentTag;
import org.apache.myfaces.tobago.component.ClientBehaviors;
import org.apache.myfaces.tobago.component.Facets;
import org.apache.myfaces.tobago.component.RendererTypes;
import org.apache.myfaces.tobago.internal.taglib.declaration.HasAccessKey;
import org.apache.myfaces.tobago.internal.taglib.declaration.HasAction;
import org.apache.myfaces.tobago.internal.taglib.declaration.HasActionListener;
import org.apache.myfaces.tobago.internal.taglib.declaration.HasConfirmation;
import org.apache.myfaces.tobago.internal.taglib.declaration.HasFragment;
import org.apache.myfaces.tobago.internal.taglib.declaration.HasIdBindingAndRendered;
import org.apache.myfaces.tobago.internal.taglib.declaration.HasImage;
import org.apache.myfaces.tobago.internal.taglib.declaration.HasLabel;
import org.apache.myfaces.tobago.internal.taglib.declaration.HasLink;
import org.apache.myfaces.tobago.internal.taglib.declaration.HasOutcome;
import org.apache.myfaces.tobago.internal.taglib.declaration.HasTabIndex;
import org.apache.myfaces.tobago.internal.taglib.declaration.HasTarget;
import org.apache.myfaces.tobago.internal.taglib.declaration.HasTip;
import org.apache.myfaces.tobago.internal.taglib.declaration.IsDefaultCommand;
import org.apache.myfaces.tobago.internal.taglib.declaration.IsDisabledBySecurity;
import org.apache.myfaces.tobago.internal.taglib.declaration.IsImmediateCommand;
import org.apache.myfaces.tobago.internal.taglib.declaration.IsOmit;
import org.apache.myfaces.tobago.internal.taglib.declaration.IsTransition;
import org.apache.myfaces.tobago.internal.taglib.declaration.IsVisual;
import javax.faces.component.UICommand;
/**
* Renders a button element.
*/
@Tag(name = "button")
@BodyContentDescription(anyTagOf = "facestag")
@UIComponentTag(
uiComponent = "org.apache.myfaces.tobago.component.UIButton",
uiComponentFacesClass = "javax.faces.component.UICommand",
interfaces = {
"org.apache.myfaces.tobago.component.SupportsAccessKey"
},
componentFamily = UICommand.COMPONENT_FAMILY,
rendererType = RendererTypes.BUTTON,
allowedChildComponenents = "NONE",
facets = {
@Facet(
name = Facets.CONFIRMATION,
description = "Contains a UIOutput instance with the confirmation message.",
allowedChildComponenents = "org.apache.myfaces.tobago.Out")
},
behaviors = {
@Behavior(
name = ClientBehaviors.CLICK,
description = "Behavior of a click event.",
isDefault = true),
@Behavior(
name = ClientBehaviors.DBLCLICK),
@Behavior(
name = ClientBehaviors.FOCUS),
@Behavior(
name = ClientBehaviors.BLUR)
},
markups = {
@Markup(
name = org.apache.myfaces.tobago.context.Markup.STRING_PRIMARY,
description = "Set button color to primary color of the theme."
),
@Markup(
name = org.apache.myfaces.tobago.context.Markup.STRING_SECONDARY,
description = "Set button color to secondary color of the theme."
),
@Markup(
name = org.apache.myfaces.tobago.context.Markup.STRING_SUCCESS,
description = "Set button color to success color of the theme."
),
@Markup(
name = org.apache.myfaces.tobago.context.Markup.STRING_DANGER,
description = "Set button color to danger color of the theme."
),
@Markup(
name = org.apache.myfaces.tobago.context.Markup.STRING_WARNING,
description = "Set button color to warning color of the theme."
),
@Markup(
name = org.apache.myfaces.tobago.context.Markup.STRING_INFO,
description = "Set button color to info color of the theme."
),
@Markup(
name = org.apache.myfaces.tobago.context.Markup.STRING_LIGHT,
description = "Set button color to light color of the theme."
),
@Markup(
name = org.apache.myfaces.tobago.context.Markup.STRING_DARK,
description = "Set button color to dark color of the theme."
),
@Markup(
name = org.apache.myfaces.tobago.context.Markup.STRING_NONE,
description = "Colorless button."
),
@Markup(
name = org.apache.myfaces.tobago.context.Markup.STRING_BADGE,
description = "Display the button as a badge."
),
@Markup(
name = org.apache.myfaces.tobago.context.Markup.STRING_PILL,
description = "Make badges more rounded if button is displayed as a badge."
)
})
public interface ButtonTagDeclaration
extends HasIdBindingAndRendered, HasAction, HasActionListener, IsImmediateCommand, HasConfirmation,
HasLink, HasOutcome, HasFragment, IsTransition, HasTarget, IsDisabledBySecurity,
IsOmit, IsVisual, HasLabel, HasAccessKey, HasTip, HasImage,
IsDefaultCommand, HasTabIndex {
}
|
/*
* Copyright 2014-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.android;
import com.facebook.buck.cxx.ClangCompiler;
import com.facebook.buck.cxx.ClangPreprocessor;
import com.facebook.buck.cxx.CxxPlatform;
import com.facebook.buck.cxx.DebugPathSanitizer;
import com.facebook.buck.cxx.DefaultCompiler;
import com.facebook.buck.cxx.DefaultPreprocessor;
import com.facebook.buck.cxx.GnuArchiver;
import com.facebook.buck.cxx.GnuLinker;
import com.facebook.buck.cxx.Linker;
import com.facebook.buck.cxx.PosixNmSymbolNameTool;
import com.facebook.buck.cxx.Preprocessor;
import com.facebook.buck.cxx.VersionedTool;
import com.facebook.buck.io.ExecutableFinder;
import com.facebook.buck.io.ProjectFilesystem;
import com.facebook.buck.model.Flavor;
import com.facebook.buck.model.ImmutableFlavor;
import com.facebook.buck.rules.Tool;
import com.facebook.buck.util.HumanReadableException;
import com.facebook.buck.util.environment.Platform;
import com.facebook.buck.util.immutables.BuckStyleImmutable;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Charsets;
import com.google.common.base.Joiner;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableBiMap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import org.immutables.value.Value;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Set;
@Value.Enclosing
@BuckStyleImmutable
public class NdkCxxPlatforms {
/**
* Magic path prefix we use to denote the machine-specific location of the Android NDK. Why "@"?
* It's uncommon enough to mark that path element as special while not being a metacharacter in
* either make, shell, or regular expression syntax.
*
* We also have prefixes for tool specific paths, even though they're sub-paths of
* `@ANDROID_NDK_ROOT@`. This is to sanitize host-specific sub-directories in the toolchain
* (e.g. darwin-x86_64) which would otherwise break determinism and caching when using
* cross-compilation.
*/
public static final String ANDROID_NDK_ROOT = "@ANDROID_NDK_ROOT@";
/**
* Magic string we substitute into debug paths in place of the build-host name, erasing the
* difference between say, building on Darwin and building on Linux.
*/
public static final String BUILD_HOST_SUBST = "@BUILD_HOST@";
public static final NdkCxxPlatforms.Compiler.Type DEFAULT_COMPILER_TYPE =
NdkCxxPlatforms.Compiler.Type.GCC;
public static final String DEFAULT_GCC_VERSION = "4.8";
public static final String DEFAULT_CLANG_VERSION = "3.5";
public static final String DEFAULT_TARGET_APP_PLATFORM = "android-9";
public static final ImmutableSet<String> DEFAULT_CPU_ABIS =
ImmutableSet.of("arm", "armv7", "x86");
public static final NdkCxxPlatforms.CxxRuntime DEFAULT_CXX_RUNTIME =
NdkCxxPlatforms.CxxRuntime.GNUSTL;
private static final ImmutableMap<Platform, Host> BUILD_PLATFORMS =
ImmutableMap.of(
Platform.LINUX, Host.LINUX_X86_64,
Platform.MACOS, Host.DARWIN_X86_64,
Platform.WINDOWS, Host.WINDOWS_X86_64);
// Utility class, do not instantiate.
private NdkCxxPlatforms() { }
public static ImmutableMap<TargetCpuType, NdkCxxPlatform> getPlatforms(
ProjectFilesystem ndkRoot,
Compiler compiler,
CxxRuntime cxxRuntime,
String androidPlatform,
Set<String> cpuAbis,
Platform platform) {
return getPlatforms(
ndkRoot,
compiler,
cxxRuntime,
androidPlatform,
cpuAbis,
platform,
new ExecutableFinder());
}
/**
* @return the map holding the available {@link NdkCxxPlatform}s.
*/
public static ImmutableMap<TargetCpuType, NdkCxxPlatform> getPlatforms(
ProjectFilesystem ndkRoot,
Compiler compiler,
CxxRuntime cxxRuntime,
String androidPlatform,
Set<String> cpuAbis,
Platform platform,
ExecutableFinder executableFinder) {
ImmutableMap.Builder<TargetCpuType, NdkCxxPlatform> ndkCxxPlatformBuilder =
ImmutableMap.builder();
// ARM Platform
if (cpuAbis.contains("arm")) {
ImmutableList<String> armeabiArchFlags =
ImmutableList.of(
"-march=armv5te",
"-mtune=xscale",
"-msoft-float",
"-mthumb");
NdkCxxPlatform armeabi =
build(
ImmutableFlavor.of("android-arm"),
platform,
ndkRoot,
ImmutableNdkCxxPlatforms.TargetConfiguration.builder()
.setToolchain(Toolchain.ARM_LINUX_ADNROIDEABI)
.setTargetArch(TargetArch.ARM)
.setTargetArchAbi(TargetArchAbi.ARMEABI)
.setTargetAppPlatform(androidPlatform)
.setCompiler(compiler)
.setToolchainTarget(ToolchainTarget.ARM_LINUX_ANDROIDEABI)
.putAssemblerFlags(Compiler.Type.GCC, armeabiArchFlags)
.putAssemblerFlags(
Compiler.Type.CLANG,
ImmutableList.<String>builder()
.add("-target", "armv5te-none-linux-androideabi")
.addAll(armeabiArchFlags)
.build())
.putCompilerFlags(
Compiler.Type.GCC,
ImmutableList.<String>builder()
.add("-Os")
.addAll(armeabiArchFlags)
.build())
.putCompilerFlags(
Compiler.Type.CLANG,
ImmutableList.<String>builder()
.add("-target", "armv5te-none-linux-androideabi", "-Os")
.addAll(armeabiArchFlags)
.build())
.putLinkerFlags(
Compiler.Type.GCC,
ImmutableList.of(
"-march=armv5te",
"-Wl,--fix-cortex-a8"))
.putLinkerFlags(
Compiler.Type.CLANG,
ImmutableList.of(
"-target", "armv5te-none-linux-androideabi",
"-march=armv5te",
"-Wl,--fix-cortex-a8"))
.build(),
cxxRuntime,
executableFinder);
ndkCxxPlatformBuilder.put(TargetCpuType.ARM, armeabi);
}
// ARMv7 Platform
if (cpuAbis.contains("armv7")) {
ImmutableList<String> armeabiv7ArchFlags =
ImmutableList.of(
"-march=armv7-a",
"-mfpu=vfpv3-d16",
"-mfloat-abi=softfp",
"-mthumb");
NdkCxxPlatform armeabiv7 =
build(
ImmutableFlavor.of("android-armv7"),
platform,
ndkRoot,
ImmutableNdkCxxPlatforms.TargetConfiguration.builder()
.setToolchain(Toolchain.ARM_LINUX_ADNROIDEABI)
.setTargetArch(TargetArch.ARM)
.setTargetArchAbi(TargetArchAbi.ARMEABI_V7A)
.setTargetAppPlatform(androidPlatform)
.setCompiler(compiler)
.setToolchainTarget(ToolchainTarget.ARM_LINUX_ANDROIDEABI)
.putAssemblerFlags(Compiler.Type.GCC, armeabiv7ArchFlags)
.putAssemblerFlags(
Compiler.Type.CLANG,
ImmutableList.<String>builder()
.add("-target", "armv7-none-linux-androideabi")
.addAll(armeabiv7ArchFlags)
.build())
.putCompilerFlags(
Compiler.Type.GCC,
ImmutableList.<String>builder()
.add("-finline-limit=64", "-Os")
.addAll(armeabiv7ArchFlags)
.build())
.putCompilerFlags(
Compiler.Type.CLANG,
ImmutableList.<String>builder()
.add("-target", "armv7-none-linux-androideabi", "-Os")
.addAll(armeabiv7ArchFlags)
.build())
.putLinkerFlags(
Compiler.Type.GCC,
ImmutableList.<String>of())
.putLinkerFlags(
Compiler.Type.CLANG,
ImmutableList.of("-target", "armv7-none-linux-androideabi"))
.build(),
cxxRuntime,
executableFinder);
ndkCxxPlatformBuilder.put(TargetCpuType.ARMV7, armeabiv7);
}
// x86 Platform
if (cpuAbis.contains("x86")) {
NdkCxxPlatform x86 =
build(
ImmutableFlavor.of("android-x86"),
platform,
ndkRoot,
ImmutableNdkCxxPlatforms.TargetConfiguration.builder()
.setToolchain(Toolchain.X86)
.setTargetArch(TargetArch.X86)
.setTargetArchAbi(TargetArchAbi.X86)
.setTargetAppPlatform(androidPlatform)
.setCompiler(compiler)
.setToolchainTarget(ToolchainTarget.I686_LINUX_ANDROID)
.putAssemblerFlags(Compiler.Type.GCC, ImmutableList.<String>of())
.putAssemblerFlags(Compiler.Type.CLANG, ImmutableList.<String>of())
.putCompilerFlags(
Compiler.Type.GCC,
ImmutableList.of(
"-funswitch-loops",
"-finline-limit=300",
"-O2"))
.putCompilerFlags(
Compiler.Type.CLANG,
ImmutableList.of(
"-target", "i686-none-linux-android",
"-O2"))
.putLinkerFlags(
Compiler.Type.GCC,
ImmutableList.<String>of())
.putLinkerFlags(
Compiler.Type.CLANG,
ImmutableList.of(
"-target", "i686-none-linux-android"))
.build(),
cxxRuntime,
executableFinder);
ndkCxxPlatformBuilder.put(TargetCpuType.X86, x86);
}
return ndkCxxPlatformBuilder.build();
}
@VisibleForTesting
static NdkCxxPlatform build(
Flavor flavor,
Platform platform,
ProjectFilesystem ndk,
TargetConfiguration targetConfiguration,
CxxRuntime cxxRuntime,
ExecutableFinder executableFinder) {
Path ndkRoot = ndk.getRootPath();
// Create a version string to use when generating rule keys via the NDK tools we'll generate
// below. This will be used in lieu of hashing the contents of the tools, so that builds from
// different host platforms (which produce identical output) will share the cache with one
// another.
Compiler.Type compilerType = targetConfiguration.getCompiler().getType();
String version =
Joiner.on('-').join(
ImmutableList.of(
readVersion(ndk),
targetConfiguration.getToolchain(),
targetConfiguration.getTargetAppPlatform(),
compilerType,
targetConfiguration.getCompiler().getVersion(),
targetConfiguration.getCompiler().getGccVersion(),
cxxRuntime));
Host host = Preconditions.checkNotNull(BUILD_PLATFORMS.get(platform));
// Build up the map of paths that must be sanitized.
ImmutableBiMap.Builder<Path, Path> sanitizePaths = ImmutableBiMap.builder();
sanitizePaths.put(
getNdkToolRoot(ndkRoot, targetConfiguration, host.toString()),
getNdkToolRoot(Paths.get(ANDROID_NDK_ROOT), targetConfiguration, BUILD_HOST_SUBST));
if (compilerType != Compiler.Type.GCC) {
sanitizePaths.put(
getNdkGccToolRoot(ndkRoot, targetConfiguration, host.toString()),
getNdkGccToolRoot(Paths.get(ANDROID_NDK_ROOT), targetConfiguration, BUILD_HOST_SUBST));
}
sanitizePaths.put(
ndkRoot,
Paths.get(ANDROID_NDK_ROOT));
CxxPlatform.Builder cxxPlatformBuilder = CxxPlatform.builder();
cxxPlatformBuilder
.setFlavor(flavor)
.setAs(getGccTool(ndkRoot, targetConfiguration, host, "as", version, executableFinder))
.addAllAsflags(getAsflags(ndkRoot, targetConfiguration, host))
.setAspp(
compilerType.preprocessorFromTool(
getCTool(
ndkRoot,
targetConfiguration,
host,
compilerType.getCc(),
version,
executableFinder)))
.setCc(
compilerType.compilerFromTool(
getCTool(
ndkRoot,
targetConfiguration,
host,
compilerType.getCc(),
version,
executableFinder)))
.addAllCflags(getCflagsInternal(ndkRoot, targetConfiguration, host))
.setCpp(
compilerType.preprocessorFromTool(
getCTool(
ndkRoot,
targetConfiguration,
host,
compilerType.getCc(),
version,
executableFinder)))
.addAllCppflags(getCppflags(ndkRoot, targetConfiguration, host))
.setCxx(
compilerType.compilerFromTool(
getCTool(
ndkRoot,
targetConfiguration,
host,
compilerType.getCxx(),
version,
executableFinder)))
.addAllCxxflags(getCxxflagsInternal(ndkRoot, targetConfiguration, host))
.setCxxpp(
compilerType.preprocessorFromTool(
getCTool(
ndkRoot,
targetConfiguration,
host,
compilerType.getCxx(),
version,
executableFinder)))
.addAllCxxppflags(getCxxppflags(ndkRoot, targetConfiguration, host, cxxRuntime))
.setLd(
getCcLinkTool(
ndkRoot,
targetConfiguration,
host,
cxxRuntime,
compilerType.getCxx(),
version,
executableFinder))
.addAllLdflags(
targetConfiguration.getLinkerFlags(compilerType))
// Default linker flags added by the NDK
.addLdflags(
// Add a deterministic build ID to Android builds.
// We use it to find symbols from arbitrary binaries.
"-Wl,--build-id",
// Enforce the NX (no execute) security feature
"-Wl,-z,noexecstack",
// Strip unused code
"-Wl,--gc-sections",
// Refuse to produce dynamic objects with undefined symbols
"-Wl,-z,defs",
// Forbid dangerous copy "relocations"
"-Wl,-z,nocopyreloc",
// We always pass the runtime library on the command line, so setting this flag
// means the resulting link will only use it if it was actually needed it.
"-Wl,--as-needed")
.setStrip(
getGccTool(ndkRoot, targetConfiguration, host, "strip", version, executableFinder))
.setSymbolNameTool(
new PosixNmSymbolNameTool(
getGccTool(ndkRoot, targetConfiguration, host, "nm", version, executableFinder)))
.setAr(
new GnuArchiver(
getGccTool(ndkRoot, targetConfiguration, host, "ar", version, executableFinder)))
.setRanlib(
getGccTool(ndkRoot, targetConfiguration, host, "ranlib", version, executableFinder))
// NDK builds are cross compiled, so the header is the same regardless of the host platform.
.setDebugPathSanitizer(
new DebugPathSanitizer(
250,
File.separatorChar,
Paths.get("."),
sanitizePaths.build()))
.setSharedLibraryExtension("so")
.setSharedLibraryVersionedExtensionFormat("so.%s")
;
if (cxxRuntime != CxxRuntime.SYSTEM) {
cxxPlatformBuilder.putRuntimeLdflags(
Linker.LinkableDepType.SHARED, "-l" + cxxRuntime.getSharedName());
cxxPlatformBuilder.putRuntimeLdflags(
Linker.LinkableDepType.STATIC, "-l" + cxxRuntime.getStaticName());
}
CxxPlatform cxxPlatform = cxxPlatformBuilder.build();
return NdkCxxPlatform.builder()
.setCxxPlatform(cxxPlatform)
.setCxxRuntime(cxxRuntime)
.setCxxSharedRuntimePath(
getCxxRuntimeLibsDirectory(ndkRoot, targetConfiguration, cxxRuntime)
.resolve(cxxRuntime.getSoname()))
.build();
}
// Read the NDK version from the "RELEASE.TXT" at the NDK root.
private static String readVersion(ProjectFilesystem ndkRoot) {
try (InputStream input = ndkRoot.newFileInputStream(Paths.get("RELEASE.TXT"));
BufferedReader reader = new BufferedReader(new InputStreamReader(input, Charsets.UTF_8))) {
// TODO(#8085133): Added to work around an issue where the linux release of r10e is mislabeled
// as r10e-rc4. Remove this once there is a fixed release.
return reader.readLine().trim().replace("r10e-rc4", "r10e");
} catch (IOException e) {
throw new HumanReadableException(
e,
"could not extract version from NDK repository at %s: %s",
ndkRoot,
e.getMessage());
}
}
/**
* @return the path to use as the system root, targeted to the given target platform and
* architecture.
*/
private static Path getSysroot(
Path ndkRoot,
TargetConfiguration targetConfiguration) {
return ndkRoot
.resolve("platforms")
.resolve(targetConfiguration.getTargetAppPlatform())
.resolve("arch-" + targetConfiguration.getTargetArch());
}
private static Path getNdkGccToolRoot(
Path ndkRoot,
TargetConfiguration targetConfiguration,
String hostName) {
return ndkRoot
.resolve("toolchains")
.resolve(
String.format(
"%s-%s",
targetConfiguration.getToolchain(),
targetConfiguration.getCompiler().getGccVersion()))
.resolve("prebuilt")
.resolve(hostName);
}
private static Path getNdkToolRoot(
Path ndkRoot,
TargetConfiguration targetConfiguration,
String hostName) {
return ndkRoot
.resolve("toolchains")
.resolve(
String.format(
"%s-%s",
targetConfiguration.getCompiler().getType() == Compiler.Type.CLANG ?
"llvm" :
targetConfiguration.getToolchain(),
targetConfiguration.getCompiler().getVersion()))
.resolve("prebuilt")
.resolve(hostName);
}
private static Path getLibexecGccToolPath(
Path ndkRoot,
TargetConfiguration targetConfiguration,
Host host) {
return getNdkToolRoot(ndkRoot, targetConfiguration, host.toString())
.resolve("libexec")
.resolve("gcc")
.resolve(targetConfiguration.getToolchain().toString())
.resolve(targetConfiguration.getCompiler().getVersion());
}
private static Path getToolchainBinPath(
Path ndkRoot,
TargetConfiguration targetConfiguration,
Host host) {
return getNdkToolRoot(ndkRoot, targetConfiguration, host.toString())
.resolve(
targetConfiguration.getCompiler().getType() == Compiler.Type.GCC ?
targetConfiguration.getToolchainTarget().toString() :
"")
.resolve("bin");
}
private static Path getToolPath(
Path ndkRoot,
TargetConfiguration targetConfiguration,
Host host,
String tool,
ExecutableFinder executableFinder) {
Path expected =
getNdkToolRoot(ndkRoot, targetConfiguration, host.toString())
.resolve("bin")
.resolve(
(targetConfiguration.getCompiler().getType() == Compiler.Type.GCC ?
targetConfiguration.getToolchainTarget().toString() + "-" :
"") + tool);
Optional<Path> path =
executableFinder.getOptionalExecutable(expected, ImmutableMap.<String, String>of());
Preconditions.checkState(path.isPresent(), expected.toString());
return path.get();
}
private static Path getGccToolchainBinPath(
Path ndkRoot,
TargetConfiguration targetConfiguration,
Host host) {
return getNdkGccToolRoot(ndkRoot, targetConfiguration, host.toString())
.resolve(targetConfiguration.getToolchainTarget().toString())
.resolve("bin");
}
private static Path getGccToolPath(
Path ndkRoot,
TargetConfiguration targetConfiguration,
Host host,
String tool,
ExecutableFinder executableFinder) {
Path expected =
getGccToolchainBinPath(ndkRoot, targetConfiguration, host)
.resolve(tool);
Optional<Path> path =
executableFinder.getOptionalExecutable(expected, ImmutableMap.<String, String>of());
Preconditions.checkState(path.isPresent(), expected.toString());
return path.get();
}
private static Tool getGccTool(
Path ndkRoot,
TargetConfiguration targetConfiguration,
Host host,
String tool,
String version,
ExecutableFinder executableFinder) {
return new VersionedTool(
getGccToolPath(ndkRoot, targetConfiguration, host, tool, executableFinder),
ImmutableList.<String>of(),
tool,
version);
}
private static Tool getCTool(
Path ndkRoot,
TargetConfiguration targetConfiguration,
Host host,
String tool,
String version,
ExecutableFinder executableFinder) {
return new VersionedTool(
getToolPath(ndkRoot, targetConfiguration, host, tool, executableFinder),
ImmutableList.<String>of(),
tool,
version);
}
private static Path getCxxRuntimeDirectory(
Path ndkRoot,
TargetConfiguration targetConfiguration,
CxxRuntime cxxRuntime) {
return ndkRoot
.resolve("sources")
.resolve("cxx-stl")
.resolve(cxxRuntime.getName())
.resolve(
cxxRuntime == CxxRuntime.GNUSTL ?
targetConfiguration.getCompiler().getGccVersion() :
"");
}
private static ImmutableList<String> getCxxRuntimeIncludeFlags(
Path ndkRoot,
TargetConfiguration targetConfiguration,
CxxRuntime cxxRuntime) {
ImmutableList.Builder<String> flags = ImmutableList.builder();
switch (cxxRuntime) {
case GNUSTL:
flags.add(
"-isystem",
getCxxRuntimeDirectory(ndkRoot, targetConfiguration, cxxRuntime)
.resolve("include")
.toString());
flags.add(
"-isystem",
getCxxRuntimeDirectory(ndkRoot, targetConfiguration, cxxRuntime)
.resolve("libs")
.resolve(targetConfiguration.getTargetArchAbi().toString())
.resolve("include")
.toString());
break;
case LIBCXX:
flags.add(
"-isystem",
getCxxRuntimeDirectory(ndkRoot, targetConfiguration, cxxRuntime)
.resolve("libcxx")
.resolve("include")
.toString());
flags.add(
"-isystem",
getCxxRuntimeDirectory(ndkRoot, targetConfiguration, cxxRuntime)
.getParent()
.resolve("llvm-libc++abi")
.resolve("libcxxabi")
.resolve("include")
.toString());
flags.add(
"-isystem",
ndkRoot
.resolve("sources")
.resolve("android")
.resolve("support")
.resolve("include")
.toString());
break;
// $CASES-OMITTED$
default:
flags.add(
"-isystem",
getCxxRuntimeDirectory(ndkRoot, targetConfiguration, cxxRuntime)
.resolve("include")
.toString());
}
return flags.build();
}
private static Path getCxxRuntimeLibsDirectory(
Path ndkRoot,
TargetConfiguration targetConfiguration,
CxxRuntime cxxRuntime) {
return getCxxRuntimeDirectory(ndkRoot, targetConfiguration, cxxRuntime)
.resolve("libs")
.resolve(targetConfiguration.getTargetArchAbi().toString());
}
private static Linker getCcLinkTool(
Path ndkRoot,
TargetConfiguration targetConfiguration,
Host host,
CxxRuntime cxxRuntime,
String tool,
String version,
ExecutableFinder executableFinder) {
ImmutableList.Builder<String> flags = ImmutableList.builder();
// Clang still needs to find GCC tools.
if (targetConfiguration.getCompiler().getType() == Compiler.Type.CLANG) {
flags.add(
"-gcc-toolchain",
getNdkGccToolRoot(ndkRoot, targetConfiguration, host.toString()).toString());
}
// Set the sysroot to the platform-specific path.
flags.add("--sysroot=" + getSysroot(ndkRoot, targetConfiguration));
// TODO(#7264008): This was added for windows support but it's not clear why it's needed.
if (targetConfiguration.getCompiler().getType() == Compiler.Type.GCC) {
flags.add(
"-B" + getLibexecGccToolPath(ndkRoot, targetConfiguration, host),
"-B" + getNdkToolRoot(ndkRoot, targetConfiguration, host.toString())
.resolve("lib")
.resolve(targetConfiguration.getCompiler().getType().getName())
.resolve(
targetConfiguration.getCompiler().getType() == Compiler.Type.GCC ?
targetConfiguration.getToolchainTarget().toString() :
"")
.resolve(targetConfiguration.getCompiler().getVersion()));
}
// Add the path to the C/C++ runtime libraries.
flags.add(
"-L" + getCxxRuntimeLibsDirectory(ndkRoot, targetConfiguration, cxxRuntime).toString());
return new GnuLinker(
new VersionedTool(
getToolPath(ndkRoot, targetConfiguration, host, tool, executableFinder),
flags.build(),
tool,
version));
}
/**
* Flags to be used when either preprocessing or compiling C or C++ sources.
*/
private static ImmutableList<String> getCommonFlags(
Path ndkRoot,
TargetConfiguration targetConfiguration,
Host host) {
ImmutableList.Builder<String> flags = ImmutableList.builder();
// Clang still needs to find the GCC tools.
if (targetConfiguration.getCompiler().getType() == Compiler.Type.CLANG) {
flags.add(
"-gcc-toolchain",
getNdkGccToolRoot(ndkRoot, targetConfiguration, host.toString()).toString());
}
// TODO(#7264008): This was added for windows support but it's not clear why it's needed.
if (targetConfiguration.getCompiler().getType() == Compiler.Type.GCC) {
flags.add(
"-B" + getLibexecGccToolPath(ndkRoot, targetConfiguration, host),
"-B" + getToolchainBinPath(ndkRoot, targetConfiguration, host));
}
// Enable default warnings and turn them into errors.
flags.add(
"-Wall",
"-Werror");
// NOTE: We pass all compiler flags to the preprocessor to make sure any necessary internal
// macros get defined and we also pass the include paths to the to the compiler since we're
// not whether we're doing combined preprocessing/compiling or not.
if (targetConfiguration.getCompiler().getType() == Compiler.Type.CLANG) {
flags.add("-Wno-unused-command-line-argument");
}
// NDK builds enable stack protector and debug symbols by default.
flags.add(
"-fstack-protector",
"-g3");
return flags.build();
}
/**
* Flags to be used when either preprocessing or compiling C sources.
*/
private static ImmutableList<String> getCommonCFlags() {
return ImmutableList.of(
// Default to the newer C11 standard. This is *not* a default set in the NDK.
// Since this flag can be used multiple times, and because the compiler just uses
// whichever standard was specified last, cxx_library rules can override this from
// their BUCK-file definitions.
"-std=gnu11");
}
/**
* Flags to be used when either preprocessing or compiling C++ sources.
*/
private static ImmutableList<String> getCommonCxxFlags() {
return ImmutableList.of(
// Default to the newer C++11 standard. This is *not* a default set in the NDK.
// Since this flag can be used multiple times, and because the compiler just uses
// whichever standard was specified last, cxx_library rules can override this from
// their BUCK-file definitions.
"-std=gnu++11",
// By default, Android builds disable exceptions and runtime type identification.
"-fno-exceptions",
"-fno-rtti");
}
/**
* Flags to be used when preprocessing C or C++ sources.
*/
private static ImmutableList<String> getCommonPreprocessorFlags() {
return ImmutableList.of(
// Disable searching for headers provided by the system. This limits headers to just
// those provided by the NDK and any library dependencies.
"-nostdinc",
// Default macro definitions applied to all builds.
"-DNDEBUG",
"-DANDROID");
}
private static ImmutableList<String> getCommonIncludes(
Path ndkRoot,
TargetConfiguration targetConfiguration,
Host host) {
return ImmutableList.of(
"-isystem",
getNdkToolRoot(ndkRoot, targetConfiguration, host.toString())
.resolve("include")
.toString(),
"-isystem",
getNdkToolRoot(ndkRoot, targetConfiguration, host.toString())
.resolve("lib")
.resolve(targetConfiguration.getCompiler().getType().getName())
.resolve(
targetConfiguration.getCompiler().getType() == Compiler.Type.GCC ?
targetConfiguration.getToolchainTarget().toString() :
"")
.resolve(targetConfiguration.getCompiler().getVersion())
.resolve("include")
.toString(),
"-isystem",
getSysroot(ndkRoot, targetConfiguration)
.resolve("usr")
.resolve("include")
.toString(),
"-isystem",
getSysroot(ndkRoot, targetConfiguration)
.resolve("usr")
.resolve("include")
.resolve("linux")
.toString());
}
private static ImmutableList<String> getAsflags(
Path ndkRoot,
TargetConfiguration targetConfiguration,
Host host) {
return ImmutableList.<String>builder()
.addAll(getCommonFlags(ndkRoot, targetConfiguration, host))
// Default assembler flags added by the NDK to enforce the NX (no execute) security feature.
.add("-Xassembler", "--noexecstack")
.addAll(targetConfiguration.getAssemblerFlags(targetConfiguration.getCompiler().getType()))
.build();
}
private static ImmutableList<String> getCppflags(
Path ndkRoot,
TargetConfiguration targetConfiguration,
Host host) {
return ImmutableList.<String>builder()
.addAll(getCommonIncludes(ndkRoot, targetConfiguration, host))
.addAll(getCommonPreprocessorFlags())
.addAll(getCommonFlags(ndkRoot, targetConfiguration, host))
.addAll(getCommonCFlags())
.addAll(targetConfiguration.getCompilerFlags(targetConfiguration.getCompiler().getType()))
.build();
}
private static ImmutableList<String> getCxxppflags(
Path ndkRoot,
TargetConfiguration targetConfiguration,
Host host,
CxxRuntime cxxRuntime) {
ImmutableList.Builder<String> flags = ImmutableList.builder();
flags.addAll(getCxxRuntimeIncludeFlags(ndkRoot, targetConfiguration, cxxRuntime));
flags.addAll(getCommonIncludes(ndkRoot, targetConfiguration, host));
flags.addAll(getCommonPreprocessorFlags());
flags.addAll(getCommonFlags(ndkRoot, targetConfiguration, host));
flags.addAll(getCommonCxxFlags());
if (targetConfiguration.getCompiler().getType() == Compiler.Type.GCC) {
flags.add("-Wno-literal-suffix");
}
flags.addAll(targetConfiguration.getCompilerFlags(targetConfiguration.getCompiler().getType()));
return flags.build();
}
/**
* Flags used when compiling either C or C++ sources.
*/
private static ImmutableList<String> getCommonCompilerFlags() {
return ImmutableList.of(
// Default compiler flags provided by the NDK build makefiles.
"-ffunction-sections",
"-funwind-tables",
"-fomit-frame-pointer",
"-fno-strict-aliasing");
}
private static ImmutableList<String> getCflagsInternal(
Path ndkRoot,
TargetConfiguration targetConfiguration,
Host host) {
return ImmutableList.<String>builder()
.addAll(
targetConfiguration.getCompilerFlags(targetConfiguration.getCompiler().getType()))
.addAll(getCommonCFlags())
.addAll(getCommonFlags(ndkRoot, targetConfiguration, host))
.addAll(getCommonCompilerFlags())
.build();
}
private static ImmutableList<String> getCxxflagsInternal(
Path ndkRoot,
TargetConfiguration targetConfiguration,
Host host) {
return ImmutableList.<String>builder()
.addAll(
targetConfiguration.getCompilerFlags(targetConfiguration.getCompiler().getType()))
.addAll(getCommonCxxFlags())
.addAll(getCommonFlags(ndkRoot, targetConfiguration, host))
.addAll(getCommonCompilerFlags())
.build();
}
/**
* The CPU architectures to target.
*/
public enum TargetCpuType {
ARM,
ARMV7,
X86,
MIPS,
}
/**
* The build toolchain, named (including compiler version) after the target platform/arch.
*/
public enum Toolchain {
X86("x86"),
ARM_LINUX_ADNROIDEABI("arm-linux-androideabi"),
;
private final String value;
Toolchain(String value) {
this.value = Preconditions.checkNotNull(value);
}
@Override
public String toString() {
return value;
}
}
/**
* Name of the target CPU architecture.
*/
public enum TargetArch {
X86("x86"),
ARM("arm"),
;
private final String value;
TargetArch(String value) {
this.value = Preconditions.checkNotNull(value);
}
@Override
public String toString() {
return value;
}
}
/**
* Name of the target CPU + ABI.
*/
public enum TargetArchAbi {
X86("x86"),
ARMEABI("armeabi"),
ARMEABI_V7A("armeabi-v7a"),
;
private final String value;
TargetArchAbi(String value) {
this.value = Preconditions.checkNotNull(value);
}
@Override
public String toString() {
return value;
}
}
/**
* The OS and Architecture that we're building on.
*/
public enum Host {
DARWIN_X86_64("darwin-x86_64"),
LINUX_X86_64("linux-x86_64"),
WINDOWS_X86_64("windows-x86_64"),
;
private final String value;
Host(String value) {
this.value = Preconditions.checkNotNull(value);
}
@Override
public String toString() {
return value;
}
}
/**
* The C/C++ runtime library to link against.
*/
public enum CxxRuntime {
SYSTEM("system", "system", "system"),
GABIXX("gabi++", "gabi++_shared", "gabi++_static"),
STLPORT("stlport", "stlport_shared", "stlport_static"),
GNUSTL("gnu-libstdc++", "gnustl_shared", "gnustl_static"),
LIBCXX("llvm-libc++", "c++_shared", "c++_static"),
;
private final String name;
private final String sharedName;
private final String staticName;
/**
* @param name the runtimes directory name in the NDK.
* @param sharedName the shared library name used for this runtime.
* @param staticName the the static library used for this runtime.
*/
CxxRuntime(String name, String sharedName, String staticName) {
this.name = name;
this.sharedName = sharedName;
this.staticName = staticName;
}
public String getName() {
return name;
}
public String getStaticName() {
return staticName;
}
public String getSharedName() {
return sharedName;
}
public String getSoname() {
return "lib" + sharedName + ".so";
}
}
/**
* The toolchains name for the platform being targeted.
*/
public enum ToolchainTarget {
I686_LINUX_ANDROID("i686-linux-android"),
ARM_LINUX_ANDROIDEABI("arm-linux-androideabi"),
;
private final String value;
ToolchainTarget(String value) {
this.value = Preconditions.checkNotNull(value);
}
@Override
public String toString() {
return value;
}
}
@Value.Immutable
public interface Compiler {
Type getType();
/**
* @return the compiler version, corresponding to either `gcc_version` or `clang_version`
* from the .buckconfig settings, depending on which compiler family was selected.
*/
String getVersion();
/**
*
* @return the GCC compiler version. Since even runtimes which are not GCC-based need to use
* GCC tools (e.g. ar, as,, ld.gold), we need to *always* have a version of GCC.
*/
String getGccVersion();
enum Type {
GCC("gcc", "gcc", "g++"),
CLANG("clang", "clang", "clang++"),
;
private final String name;
private final String cc;
private final String cxx;
Type(String name, String cc, String cxx) {
this.name = name;
this.cc = cc;
this.cxx = cxx;
}
public String getName() {
return name;
}
public String getCc() {
return cc;
}
public String getCxx() {
return cxx;
}
public com.facebook.buck.cxx.Compiler compilerFromTool(Tool tool) {
switch (this) {
case GCC:
return new DefaultCompiler(tool);
case CLANG:
return new ClangCompiler(tool);
}
throw new RuntimeException("Invalid compiler type");
}
public Preprocessor preprocessorFromTool(Tool tool) {
switch (this) {
case GCC:
return new DefaultPreprocessor(tool);
case CLANG:
return new ClangPreprocessor(tool);
}
throw new RuntimeException("Invalid compiler type");
}
}
}
/**
* A container for all configuration settings needed to define a build target.
*/
@Value.Immutable
public abstract static class TargetConfiguration {
public abstract Toolchain getToolchain();
public abstract ToolchainTarget getToolchainTarget();
public abstract TargetArch getTargetArch();
public abstract TargetArchAbi getTargetArchAbi();
public abstract String getTargetAppPlatform();
public abstract Compiler getCompiler();
public abstract ImmutableMap<Compiler.Type, ImmutableList<String>> getCompilerFlags();
public abstract ImmutableMap<Compiler.Type, ImmutableList<String>> getAssemblerFlags();
public abstract ImmutableMap<Compiler.Type, ImmutableList<String>> getLinkerFlags();
public ImmutableList<String> getAssemblerFlags(Compiler.Type type) {
return Optional.fromNullable(getAssemblerFlags().get(type)).or(ImmutableList.<String>of());
}
public ImmutableList<String> getCompilerFlags(Compiler.Type type) {
return Optional.fromNullable(getCompilerFlags().get(type)).or(ImmutableList.<String>of());
}
public ImmutableList<String> getLinkerFlags(Compiler.Type type) {
return Optional.fromNullable(getLinkerFlags().get(type)).or(ImmutableList.<String>of());
}
}
}
|
/*
* 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.hadoop.hbase.coprocessor;
import static org.junit.Assert.assertEquals;
import java.math.BigDecimal;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.*;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.client.Durability;
import org.apache.hadoop.hbase.client.coprocessor.AggregationClient;
import org.apache.hadoop.hbase.client.coprocessor.BigDecimalColumnInterpreter;
import org.apache.hadoop.hbase.filter.Filter;
import org.apache.hadoop.hbase.filter.PrefixFilter;
import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.BigDecimalMsg;
import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.EmptyMsg;
import org.apache.hadoop.hbase.util.Bytes;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;
/**
* A test class to test BigDecimalColumnInterpreter for AggregationsProtocol
*/
@Category(MediumTests.class)
public class TestBigDecimalColumnInterpreter {
protected static Log myLog = LogFactory.getLog(TestBigDecimalColumnInterpreter.class);
/**
* Creating the test infrastructure.
*/
private static final byte[] TEST_TABLE = Bytes.toBytes("TestTable");
private static final byte[] TEST_FAMILY = Bytes.toBytes("TestFamily");
private static final byte[] TEST_QUALIFIER = Bytes.toBytes("TestQualifier");
private static final byte[] TEST_MULTI_CQ = Bytes.toBytes("TestMultiCQ");
private static byte[] ROW = Bytes.toBytes("testRow");
private static final int ROWSIZE = 20;
private static final int rowSeperator1 = 5;
private static final int rowSeperator2 = 12;
private static byte[][] ROWS = makeN(ROW, ROWSIZE);
private static HBaseTestingUtility util = new HBaseTestingUtility();
private static Configuration conf = util.getConfiguration();
/**
* A set up method to start the test cluster. AggregateProtocolImpl is registered and will be
* loaded during region startup.
* @throws Exception
*/
@BeforeClass
public static void setupBeforeClass() throws Exception {
conf.set(CoprocessorHost.REGION_COPROCESSOR_CONF_KEY,
"org.apache.hadoop.hbase.coprocessor.AggregateImplementation");
util.startMiniCluster(2);
HTable table = util.createTable(TEST_TABLE, TEST_FAMILY);
util.createMultiRegions(util.getConfiguration(), table, TEST_FAMILY, new byte[][] {
HConstants.EMPTY_BYTE_ARRAY, ROWS[rowSeperator1], ROWS[rowSeperator2] });
/**
* The testtable has one CQ which is always populated and one variable CQ for each row rowkey1:
* CF:CQ CF:CQ1 rowKey2: CF:CQ CF:CQ2
*/
for (int i = 0; i < ROWSIZE; i++) {
Put put = new Put(ROWS[i]);
put.setDurability(Durability.SKIP_WAL);
BigDecimal bd = new BigDecimal(i);
put.add(TEST_FAMILY, TEST_QUALIFIER, Bytes.toBytes(bd));
table.put(put);
Put p2 = new Put(ROWS[i]);
put.setDurability(Durability.SKIP_WAL);
p2.add(TEST_FAMILY, Bytes.add(TEST_MULTI_CQ, Bytes.toBytes(bd)),
Bytes.toBytes(bd.multiply(new BigDecimal("0.10"))));
table.put(p2);
}
table.close();
}
/**
* Shutting down the cluster
* @throws Exception
*/
@AfterClass
public static void tearDownAfterClass() throws Exception {
util.shutdownMiniCluster();
}
/**
* an infrastructure method to prepare rows for the testtable.
* @param base
* @param n
* @return
*/
private static byte[][] makeN(byte[] base, int n) {
byte[][] ret = new byte[n][];
for (int i = 0; i < n; i++) {
ret[i] = Bytes.add(base, Bytes.toBytes(i));
}
return ret;
}
/**
* ****************** Test cases for Median **********************
*/
/**
* @throws Throwable
*/
@Test
public void testMedianWithValidRange() throws Throwable {
AggregationClient aClient = new AggregationClient(conf);
Scan scan = new Scan();
scan.addColumn(TEST_FAMILY, TEST_QUALIFIER);
final ColumnInterpreter<BigDecimal, BigDecimal, EmptyMsg, BigDecimalMsg, BigDecimalMsg> ci =
new BigDecimalColumnInterpreter();
BigDecimal median = aClient.median(TEST_TABLE, ci, scan);
assertEquals(new BigDecimal("8.00"), median);
}
/**
* ***************Test cases for Maximum *******************
*/
/**
* give max for the entire table.
* @throws Throwable
*/
@Test
public void testMaxWithValidRange() throws Throwable {
AggregationClient aClient = new AggregationClient(conf);
Scan scan = new Scan();
scan.addColumn(TEST_FAMILY, TEST_QUALIFIER);
final ColumnInterpreter<BigDecimal, BigDecimal, EmptyMsg, BigDecimalMsg, BigDecimalMsg> ci =
new BigDecimalColumnInterpreter();
BigDecimal maximum = aClient.max(TEST_TABLE, ci, scan);
assertEquals(new BigDecimal("19.00"), maximum);
}
/**
* @throws Throwable
*/
@Test
public void testMaxWithValidRange2() throws Throwable {
AggregationClient aClient = new AggregationClient(conf);
Scan scan = new Scan();
scan.addColumn(TEST_FAMILY, TEST_QUALIFIER);
scan.setStartRow(ROWS[5]);
scan.setStopRow(ROWS[15]);
final ColumnInterpreter<BigDecimal, BigDecimal, EmptyMsg, BigDecimalMsg, BigDecimalMsg> ci =
new BigDecimalColumnInterpreter();
BigDecimal max = aClient.max(TEST_TABLE, ci, scan);
assertEquals(new BigDecimal("14.00"), max);
}
@Test
public void testMaxWithValidRangeWithNoCQ() throws Throwable {
AggregationClient aClient = new AggregationClient(conf);
Scan scan = new Scan();
scan.addFamily(TEST_FAMILY);
final ColumnInterpreter<BigDecimal, BigDecimal, EmptyMsg, BigDecimalMsg, BigDecimalMsg> ci =
new BigDecimalColumnInterpreter();
BigDecimal maximum = aClient.max(TEST_TABLE, ci, scan);
assertEquals(new BigDecimal("19.00"), maximum);
}
@Test
public void testMaxWithValidRange2WithNoCQ() throws Throwable {
AggregationClient aClient = new AggregationClient(conf);
Scan scan = new Scan();
scan.addFamily(TEST_FAMILY);
scan.setStartRow(ROWS[6]);
scan.setStopRow(ROWS[7]);
final ColumnInterpreter<BigDecimal, BigDecimal, EmptyMsg, BigDecimalMsg, BigDecimalMsg> ci =
new BigDecimalColumnInterpreter();
BigDecimal max = aClient.max(TEST_TABLE, ci, scan);
assertEquals(new BigDecimal("6.00"), max);
}
@Test
public void testMaxWithValidRangeWithNullCF() {
AggregationClient aClient = new AggregationClient(conf);
final ColumnInterpreter<BigDecimal, BigDecimal, EmptyMsg, BigDecimalMsg, BigDecimalMsg> ci =
new BigDecimalColumnInterpreter();
Scan scan = new Scan();
BigDecimal max = null;
try {
max = aClient.max(TEST_TABLE, ci, scan);
} catch (Throwable e) {
max = null;
}
assertEquals(null, max);// CP will throw an IOException about the
// null column family, and max will be set to 0
}
@Test
public void testMaxWithInvalidRange() {
AggregationClient aClient = new AggregationClient(conf);
final ColumnInterpreter<BigDecimal, BigDecimal, EmptyMsg, BigDecimalMsg, BigDecimalMsg> ci =
new BigDecimalColumnInterpreter();
Scan scan = new Scan();
scan.setStartRow(ROWS[4]);
scan.setStopRow(ROWS[2]);
scan.addColumn(TEST_FAMILY, TEST_QUALIFIER);
BigDecimal max = new BigDecimal(Long.MIN_VALUE);
;
try {
max = aClient.max(TEST_TABLE, ci, scan);
} catch (Throwable e) {
max = BigDecimal.ZERO;
}
assertEquals(BigDecimal.ZERO, max);// control should go to the catch block
}
@Test
public void testMaxWithInvalidRange2() throws Throwable {
BigDecimal max = new BigDecimal(Long.MIN_VALUE);
Scan scan = new Scan();
scan.addColumn(TEST_FAMILY, TEST_QUALIFIER);
scan.setStartRow(ROWS[4]);
scan.setStopRow(ROWS[4]);
try {
AggregationClient aClient = new AggregationClient(conf);
final ColumnInterpreter<BigDecimal, BigDecimal, EmptyMsg, BigDecimalMsg, BigDecimalMsg> ci =
new BigDecimalColumnInterpreter();
max = aClient.max(TEST_TABLE, ci, scan);
} catch (Exception e) {
max = BigDecimal.ZERO;
}
assertEquals(BigDecimal.ZERO, max);// control should go to the catch block
}
@Test
public void testMaxWithFilter() throws Throwable {
BigDecimal max = BigDecimal.ZERO;
AggregationClient aClient = new AggregationClient(conf);
Scan scan = new Scan();
scan.addColumn(TEST_FAMILY, TEST_QUALIFIER);
Filter f = new PrefixFilter(Bytes.toBytes("foo:bar"));
scan.setFilter(f);
final ColumnInterpreter<BigDecimal, BigDecimal, EmptyMsg, BigDecimalMsg, BigDecimalMsg> ci =
new BigDecimalColumnInterpreter();
max = aClient.max(TEST_TABLE, ci, scan);
assertEquals(null, max);
}
/**
* **************************Test cases for Minimum ***********************
*/
/**
* @throws Throwable
*/
@Test
public void testMinWithValidRange() throws Throwable {
AggregationClient aClient = new AggregationClient(conf);
Scan scan = new Scan();
scan.addColumn(TEST_FAMILY, TEST_QUALIFIER);
scan.setStartRow(HConstants.EMPTY_START_ROW);
scan.setStopRow(HConstants.EMPTY_END_ROW);
final ColumnInterpreter<BigDecimal, BigDecimal, EmptyMsg, BigDecimalMsg, BigDecimalMsg> ci =
new BigDecimalColumnInterpreter();
BigDecimal min = aClient.min(TEST_TABLE, ci, scan);
assertEquals(new BigDecimal("0.00"), min);
}
/**
* @throws Throwable
*/
@Test
public void testMinWithValidRange2() throws Throwable {
AggregationClient aClient = new AggregationClient(conf);
Scan scan = new Scan();
scan.addColumn(TEST_FAMILY, TEST_QUALIFIER);
scan.setStartRow(ROWS[5]);
scan.setStopRow(ROWS[15]);
final ColumnInterpreter<BigDecimal, BigDecimal, EmptyMsg, BigDecimalMsg, BigDecimalMsg> ci =
new BigDecimalColumnInterpreter();
BigDecimal min = aClient.min(TEST_TABLE, ci, scan);
assertEquals(new BigDecimal("5.00"), min);
}
@Test
public void testMinWithValidRangeWithNoCQ() throws Throwable {
AggregationClient aClient = new AggregationClient(conf);
Scan scan = new Scan();
scan.addFamily(TEST_FAMILY);
scan.setStartRow(HConstants.EMPTY_START_ROW);
scan.setStopRow(HConstants.EMPTY_END_ROW);
final ColumnInterpreter<BigDecimal, BigDecimal, EmptyMsg, BigDecimalMsg, BigDecimalMsg> ci =
new BigDecimalColumnInterpreter();
BigDecimal min = aClient.min(TEST_TABLE, ci, scan);
assertEquals(new BigDecimal("0.00"), min);
}
@Test
public void testMinWithValidRange2WithNoCQ() throws Throwable {
AggregationClient aClient = new AggregationClient(conf);
Scan scan = new Scan();
scan.addFamily(TEST_FAMILY);
scan.setStartRow(ROWS[6]);
scan.setStopRow(ROWS[7]);
final ColumnInterpreter<BigDecimal, BigDecimal, EmptyMsg, BigDecimalMsg, BigDecimalMsg> ci =
new BigDecimalColumnInterpreter();
BigDecimal min = aClient.min(TEST_TABLE, ci, scan);
assertEquals(new BigDecimal("0.60"), min);
}
@Test
public void testMinWithValidRangeWithNullCF() {
AggregationClient aClient = new AggregationClient(conf);
Scan scan = new Scan();
scan.setStartRow(ROWS[5]);
scan.setStopRow(ROWS[15]);
final ColumnInterpreter<BigDecimal, BigDecimal, EmptyMsg, BigDecimalMsg, BigDecimalMsg> ci =
new BigDecimalColumnInterpreter();
BigDecimal min = null;
try {
min = aClient.min(TEST_TABLE, ci, scan);
} catch (Throwable e) {
}
assertEquals(null, min);// CP will throw an IOException about the
// null column family, and max will be set to 0
}
@Test
public void testMinWithInvalidRange() {
AggregationClient aClient = new AggregationClient(conf);
BigDecimal min = null;
Scan scan = new Scan();
scan.addFamily(TEST_FAMILY);
scan.setStartRow(ROWS[4]);
scan.setStopRow(ROWS[2]);
final ColumnInterpreter<BigDecimal, BigDecimal, EmptyMsg, BigDecimalMsg, BigDecimalMsg> ci =
new BigDecimalColumnInterpreter();
try {
min = aClient.min(TEST_TABLE, ci, scan);
} catch (Throwable e) {
}
assertEquals(null, min);// control should go to the catch block
}
@Test
public void testMinWithInvalidRange2() {
AggregationClient aClient = new AggregationClient(conf);
Scan scan = new Scan();
scan.addFamily(TEST_FAMILY);
scan.setStartRow(ROWS[6]);
scan.setStopRow(ROWS[6]);
final ColumnInterpreter<BigDecimal, BigDecimal, EmptyMsg, BigDecimalMsg, BigDecimalMsg> ci =
new BigDecimalColumnInterpreter();
BigDecimal min = null;
try {
min = aClient.min(TEST_TABLE, ci, scan);
} catch (Throwable e) {
}
assertEquals(null, min);// control should go to the catch block
}
@Test
public void testMinWithFilter() throws Throwable {
AggregationClient aClient = new AggregationClient(conf);
Scan scan = new Scan();
scan.addColumn(TEST_FAMILY, TEST_QUALIFIER);
Filter f = new PrefixFilter(Bytes.toBytes("foo:bar"));
scan.setFilter(f);
final ColumnInterpreter<BigDecimal, BigDecimal, EmptyMsg, BigDecimalMsg, BigDecimalMsg> ci =
new BigDecimalColumnInterpreter();
BigDecimal min = null;
min = aClient.min(TEST_TABLE, ci, scan);
assertEquals(null, min);
}
/**
* *************** Test cases for Sum *********************
*/
/**
* @throws Throwable
*/
@Test
public void testSumWithValidRange() throws Throwable {
AggregationClient aClient = new AggregationClient(conf);
Scan scan = new Scan();
scan.addColumn(TEST_FAMILY, TEST_QUALIFIER);
final ColumnInterpreter<BigDecimal, BigDecimal, EmptyMsg, BigDecimalMsg, BigDecimalMsg> ci =
new BigDecimalColumnInterpreter();
BigDecimal sum = aClient.sum(TEST_TABLE, ci, scan);
assertEquals(new BigDecimal("190.00"), sum);
}
/**
* @throws Throwable
*/
@Test
public void testSumWithValidRange2() throws Throwable {
AggregationClient aClient = new AggregationClient(conf);
Scan scan = new Scan();
scan.addColumn(TEST_FAMILY, TEST_QUALIFIER);
scan.setStartRow(ROWS[5]);
scan.setStopRow(ROWS[15]);
final ColumnInterpreter<BigDecimal, BigDecimal, EmptyMsg, BigDecimalMsg, BigDecimalMsg> ci =
new BigDecimalColumnInterpreter();
BigDecimal sum = aClient.sum(TEST_TABLE, ci, scan);
assertEquals(new BigDecimal("95.00"), sum);
}
@Test
public void testSumWithValidRangeWithNoCQ() throws Throwable {
AggregationClient aClient = new AggregationClient(conf);
Scan scan = new Scan();
scan.addFamily(TEST_FAMILY);
final ColumnInterpreter<BigDecimal, BigDecimal, EmptyMsg, BigDecimalMsg, BigDecimalMsg> ci =
new BigDecimalColumnInterpreter();
BigDecimal sum = aClient.sum(TEST_TABLE, ci, scan);
assertEquals(new BigDecimal("209.00"), sum); // 190 + 19
}
@Test
public void testSumWithValidRange2WithNoCQ() throws Throwable {
AggregationClient aClient = new AggregationClient(conf);
Scan scan = new Scan();
scan.addFamily(TEST_FAMILY);
scan.setStartRow(ROWS[6]);
scan.setStopRow(ROWS[7]);
final ColumnInterpreter<BigDecimal, BigDecimal, EmptyMsg, BigDecimalMsg, BigDecimalMsg> ci =
new BigDecimalColumnInterpreter();
BigDecimal sum = aClient.sum(TEST_TABLE, ci, scan);
assertEquals(new BigDecimal("6.60"), sum); // 6 + 60
}
@Test
public void testSumWithValidRangeWithNullCF() {
AggregationClient aClient = new AggregationClient(conf);
Scan scan = new Scan();
scan.setStartRow(ROWS[6]);
scan.setStopRow(ROWS[7]);
final ColumnInterpreter<BigDecimal, BigDecimal, EmptyMsg, BigDecimalMsg, BigDecimalMsg> ci =
new BigDecimalColumnInterpreter();
BigDecimal sum = null;
try {
sum = aClient.sum(TEST_TABLE, ci, scan);
} catch (Throwable e) {
}
assertEquals(null, sum);// CP will throw an IOException about the
// null column family, and max will be set to 0
}
@Test
public void testSumWithInvalidRange() {
AggregationClient aClient = new AggregationClient(conf);
Scan scan = new Scan();
scan.addFamily(TEST_FAMILY);
scan.setStartRow(ROWS[6]);
scan.setStopRow(ROWS[2]);
final ColumnInterpreter<BigDecimal, BigDecimal, EmptyMsg, BigDecimalMsg, BigDecimalMsg> ci =
new BigDecimalColumnInterpreter();
BigDecimal sum = null;
try {
sum = aClient.sum(TEST_TABLE, ci, scan);
} catch (Throwable e) {
}
assertEquals(null, sum);// control should go to the catch block
}
@Test
public void testSumWithFilter() throws Throwable {
AggregationClient aClient = new AggregationClient(conf);
Filter f = new PrefixFilter(Bytes.toBytes("foo:bar"));
Scan scan = new Scan();
scan.addFamily(TEST_FAMILY);
scan.setFilter(f);
final ColumnInterpreter<BigDecimal, BigDecimal, EmptyMsg, BigDecimalMsg, BigDecimalMsg> ci =
new BigDecimalColumnInterpreter();
BigDecimal sum = null;
sum = aClient.sum(TEST_TABLE, ci, scan);
assertEquals(null, sum);
}
/**
* ****************************** Test Cases for Avg **************
*/
/**
* @throws Throwable
*/
@Test
public void testAvgWithValidRange() throws Throwable {
AggregationClient aClient = new AggregationClient(conf);
Scan scan = new Scan();
scan.addColumn(TEST_FAMILY, TEST_QUALIFIER);
final ColumnInterpreter<BigDecimal, BigDecimal, EmptyMsg, BigDecimalMsg, BigDecimalMsg> ci =
new BigDecimalColumnInterpreter();
double avg = aClient.avg(TEST_TABLE, ci, scan);
assertEquals(9.5, avg, 0);
}
/**
* @throws Throwable
*/
@Test
public void testAvgWithValidRange2() throws Throwable {
AggregationClient aClient = new AggregationClient(conf);
Scan scan = new Scan();
scan.addColumn(TEST_FAMILY, TEST_QUALIFIER);
scan.setStartRow(ROWS[5]);
scan.setStopRow(ROWS[15]);
final ColumnInterpreter<BigDecimal, BigDecimal, EmptyMsg, BigDecimalMsg, BigDecimalMsg> ci =
new BigDecimalColumnInterpreter();
double avg = aClient.avg(TEST_TABLE, ci, scan);
assertEquals(9.5, avg, 0);
}
@Test
public void testAvgWithValidRangeWithNoCQ() throws Throwable {
AggregationClient aClient = new AggregationClient(conf);
Scan scan = new Scan();
scan.addFamily(TEST_FAMILY);
final ColumnInterpreter<BigDecimal, BigDecimal, EmptyMsg, BigDecimalMsg, BigDecimalMsg> ci =
new BigDecimalColumnInterpreter();
double avg = aClient.avg(TEST_TABLE, ci, scan);
assertEquals(10.45, avg, 0.01);
}
@Test
public void testAvgWithValidRange2WithNoCQ() throws Throwable {
AggregationClient aClient = new AggregationClient(conf);
Scan scan = new Scan();
scan.addFamily(TEST_FAMILY);
scan.setStartRow(ROWS[6]);
scan.setStopRow(ROWS[7]);
final ColumnInterpreter<BigDecimal, BigDecimal, EmptyMsg, BigDecimalMsg, BigDecimalMsg> ci =
new BigDecimalColumnInterpreter();
double avg = aClient.avg(TEST_TABLE, ci, scan);
assertEquals(6 + 0.60, avg, 0);
}
@Test
public void testAvgWithValidRangeWithNullCF() {
AggregationClient aClient = new AggregationClient(conf);
Scan scan = new Scan();
final ColumnInterpreter<BigDecimal, BigDecimal, EmptyMsg, BigDecimalMsg, BigDecimalMsg> ci =
new BigDecimalColumnInterpreter();
Double avg = null;
try {
avg = aClient.avg(TEST_TABLE, ci, scan);
} catch (Throwable e) {
}
assertEquals(null, avg);// CP will throw an IOException about the
// null column family, and max will be set to 0
}
@Test
public void testAvgWithInvalidRange() {
AggregationClient aClient = new AggregationClient(conf);
Scan scan = new Scan();
scan.addColumn(TEST_FAMILY, TEST_QUALIFIER);
scan.setStartRow(ROWS[5]);
scan.setStopRow(ROWS[1]);
final ColumnInterpreter<BigDecimal, BigDecimal, EmptyMsg, BigDecimalMsg, BigDecimalMsg> ci =
new BigDecimalColumnInterpreter();
Double avg = null;
try {
avg = aClient.avg(TEST_TABLE, ci, scan);
} catch (Throwable e) {
}
assertEquals(null, avg);// control should go to the catch block
}
@Test
public void testAvgWithFilter() throws Throwable {
AggregationClient aClient = new AggregationClient(conf);
Scan scan = new Scan();
scan.addColumn(TEST_FAMILY, TEST_QUALIFIER);
Filter f = new PrefixFilter(Bytes.toBytes("foo:bar"));
scan.setFilter(f);
final ColumnInterpreter<BigDecimal, BigDecimal, EmptyMsg, BigDecimalMsg, BigDecimalMsg> ci =
new BigDecimalColumnInterpreter();
Double avg = null;
avg = aClient.avg(TEST_TABLE, ci, scan);
assertEquals(Double.NaN, avg, 0);
}
/**
* ****************** Test cases for STD **********************
*/
/**
* @throws Throwable
*/
@Test
public void testStdWithValidRange() throws Throwable {
AggregationClient aClient = new AggregationClient(conf);
Scan scan = new Scan();
scan.addColumn(TEST_FAMILY, TEST_QUALIFIER);
final ColumnInterpreter<BigDecimal, BigDecimal, EmptyMsg, BigDecimalMsg, BigDecimalMsg> ci =
new BigDecimalColumnInterpreter();
double std = aClient.std(TEST_TABLE, ci, scan);
assertEquals(5.766, std, 0.05d);
}
/**
* need to change this
* @throws Throwable
*/
@Test
public void testStdWithValidRange2() throws Throwable {
AggregationClient aClient = new AggregationClient(conf);
Scan scan = new Scan();
scan.addColumn(TEST_FAMILY, TEST_QUALIFIER);
scan.setStartRow(ROWS[5]);
scan.setStopRow(ROWS[15]);
final ColumnInterpreter<BigDecimal, BigDecimal, EmptyMsg, BigDecimalMsg, BigDecimalMsg> ci =
new BigDecimalColumnInterpreter();
double std = aClient.std(TEST_TABLE, ci, scan);
assertEquals(2.87, std, 0.05d);
}
/**
* need to change this
* @throws Throwable
*/
@Test
public void testStdWithValidRangeWithNoCQ() throws Throwable {
AggregationClient aClient = new AggregationClient(conf);
Scan scan = new Scan();
scan.addFamily(TEST_FAMILY);
final ColumnInterpreter<BigDecimal, BigDecimal, EmptyMsg, BigDecimalMsg, BigDecimalMsg> ci =
new BigDecimalColumnInterpreter();
double std = aClient.std(TEST_TABLE, ci, scan);
assertEquals(6.342, std, 0.05d);
}
@Test
public void testStdWithValidRange2WithNoCQ() throws Throwable {
AggregationClient aClient = new AggregationClient(conf);
Scan scan = new Scan();
scan.addFamily(TEST_FAMILY);
scan.setStartRow(ROWS[6]);
scan.setStopRow(ROWS[7]);
final ColumnInterpreter<BigDecimal, BigDecimal, EmptyMsg, BigDecimalMsg, BigDecimalMsg> ci =
new BigDecimalColumnInterpreter();
double std = aClient.std(TEST_TABLE, ci, scan);
System.out.println("std is:" + std);
assertEquals(0, std, 0.05d);
}
@Test
public void testStdWithValidRangeWithNullCF() {
AggregationClient aClient = new AggregationClient(conf);
Scan scan = new Scan();
scan.setStartRow(ROWS[6]);
scan.setStopRow(ROWS[17]);
final ColumnInterpreter<BigDecimal, BigDecimal, EmptyMsg, BigDecimalMsg, BigDecimalMsg> ci =
new BigDecimalColumnInterpreter();
Double std = null;
try {
std = aClient.std(TEST_TABLE, ci, scan);
} catch (Throwable e) {
}
assertEquals(null, std);// CP will throw an IOException about the
// null column family, and max will be set to 0
}
@Test
public void testStdWithInvalidRange() {
AggregationClient aClient = new AggregationClient(conf);
Scan scan = new Scan();
scan.addFamily(TEST_FAMILY);
scan.setStartRow(ROWS[6]);
scan.setStopRow(ROWS[1]);
final ColumnInterpreter<BigDecimal, BigDecimal, EmptyMsg, BigDecimalMsg, BigDecimalMsg> ci =
new BigDecimalColumnInterpreter();
Double std = null;
try {
std = aClient.std(TEST_TABLE, ci, scan);
} catch (Throwable e) {
}
assertEquals(null, std);// control should go to the catch block
}
@Test
public void testStdWithFilter() throws Throwable {
AggregationClient aClient = new AggregationClient(conf);
Filter f = new PrefixFilter(Bytes.toBytes("foo:bar"));
Scan scan = new Scan();
scan.addFamily(TEST_FAMILY);
scan.setFilter(f);
final ColumnInterpreter<BigDecimal, BigDecimal, EmptyMsg, BigDecimalMsg, BigDecimalMsg> ci =
new BigDecimalColumnInterpreter();
Double std = null;
std = aClient.std(TEST_TABLE, ci, scan);
assertEquals(Double.NaN, std, 0);
}
}
|
package com.neuralquest.server.base;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import com.neuralquest.server.dao.iface.AssocDAO;
import org.hibernate.criterion.Order;
/**
* This is an automatically generated DAO class which should not be edited.
*/
public abstract class BaseAssocDAO extends com.neuralquest.server.dao._RootDAO {
public BaseAssocDAO () {}
public BaseAssocDAO (Session session) {
super(session);
}
// query name references
public static AssocDAO instance;
/**
* Return a singleton of the DAO
*/
public static AssocDAO getInstance () {
if (null == instance) instance = new com.neuralquest.server.dao.AssocDAO();
return instance;
}
public Class getReferenceClass () {
return com.neuralquest.server.Assoc.class;
}
public Order getDefaultOrder () {
return null;
}
/**
* Cast the object as a com.neuralquest.server.Assoc
*/
public com.neuralquest.server.Assoc cast (Object object) {
return (com.neuralquest.server.Assoc) object;
}
public com.neuralquest.server.Assoc get(long key)
{
return (com.neuralquest.server.Assoc) get(getReferenceClass(), new java.lang.Long(key));
}
public com.neuralquest.server.Assoc get(long key, Session s)
{
return (com.neuralquest.server.Assoc) get(getReferenceClass(), new java.lang.Long(key), s);
}
public com.neuralquest.server.Assoc load(long key)
{
return (com.neuralquest.server.Assoc) load(getReferenceClass(), new java.lang.Long(key));
}
public com.neuralquest.server.Assoc load(long key, Session s)
{
return (com.neuralquest.server.Assoc) load(getReferenceClass(), new java.lang.Long(key), s);
}
public com.neuralquest.server.Assoc loadInitialize(long key, Session s)
{
com.neuralquest.server.Assoc obj = load(key, s);
if (!Hibernate.isInitialized(obj)) {
Hibernate.initialize(obj);
}
return obj;
}
/* Generic methods */
/**
* Return all objects related to the implementation of this DAO with no filter.
*/
public java.util.List findAll () {
return super.findAll();
}
/**
* Return all objects related to the implementation of this DAO with no filter.
*/
public java.util.List findAll (Order defaultOrder) {
return super.findAll(defaultOrder);
}
/**
* Return all objects related to the implementation of this DAO with no filter.
* Use the session given.
* @param s the Session
*/
public java.util.List findAll (Session s, Order defaultOrder) {
return super.findAll(s, defaultOrder);
}
/**
* Persist the given transient instance, first assigning a generated identifier. (Or using the current value
* of the identifier property if the assigned generator is used.)
* @param assoc a transient instance of a persistent class
* @return the class identifier
*/
public java.lang.Long save(com.neuralquest.server.Assoc assoc)
{
return (java.lang.Long) super.save(assoc);
}
/**
* Persist the given transient instance, first assigning a generated identifier. (Or using the current value
* of the identifier property if the assigned generator is used.)
* Use the Session given.
* @param assoc a transient instance of a persistent class
* @param s the Session
* @return the class identifier
*/
public java.lang.Long save(com.neuralquest.server.Assoc assoc, Session s)
{
return (java.lang.Long) save((Object) assoc, s);
}
/**
* Either save() or update() the given instance, depending upon the value of its identifier property. By default
* the instance is always saved. This behaviour may be adjusted by specifying an unsaved-value attribute of the
* identifier property mapping.
* @param assoc a transient instance containing new or updated state
*/
public void saveOrUpdate(com.neuralquest.server.Assoc assoc)
{
saveOrUpdate((Object) assoc);
}
/**
* Either save() or update() the given instance, depending upon the value of its identifier property. By default the
* instance is always saved. This behaviour may be adjusted by specifying an unsaved-value attribute of the identifier
* property mapping.
* Use the Session given.
* @param assoc a transient instance containing new or updated state.
* @param s the Session.
*/
public void saveOrUpdate(com.neuralquest.server.Assoc assoc, Session s)
{
saveOrUpdate((Object) assoc, s);
}
/**
* Update the persistent state associated with the given identifier. An exception is thrown if there is a persistent
* instance with the same identifier in the current session.
* @param assoc a transient instance containing updated state
*/
public void update(com.neuralquest.server.Assoc assoc)
{
update((Object) assoc);
}
/**
* Update the persistent state associated with the given identifier. An exception is thrown if there is a persistent
* instance with the same identifier in the current session.
* Use the Session given.
* @param assoc a transient instance containing updated state
* @param the Session
*/
public void update(com.neuralquest.server.Assoc assoc, Session s)
{
update((Object) assoc, s);
}
/**
* Remove a persistent instance from the datastore. The argument may be an instance associated with the receiving
* Session or a transient instance with an identifier associated with existing persistent state.
* @param id the instance ID to be removed
*/
public void delete(long id)
{
delete((Object) load(id));
}
/**
* Remove a persistent instance from the datastore. The argument may be an instance associated with the receiving
* Session or a transient instance with an identifier associated with existing persistent state.
* Use the Session given.
* @param id the instance ID to be removed
* @param s the Session
*/
public void delete(long id, Session s)
{
delete((Object) load(id, s), s);
}
/**
* Remove a persistent instance from the datastore. The argument may be an instance associated with the receiving
* Session or a transient instance with an identifier associated with existing persistent state.
* @param assoc the instance to be removed
*/
public void delete(com.neuralquest.server.Assoc assoc)
{
delete((Object) assoc);
}
/**
* Remove a persistent instance from the datastore. The argument may be an instance associated with the receiving
* Session or a transient instance with an identifier associated with existing persistent state.
* Use the Session given.
* @param assoc the instance to be removed
* @param s the Session
*/
public void delete(com.neuralquest.server.Assoc assoc, Session s)
{
delete((Object) assoc, s);
}
/**
* Re-read the state of the given instance from the underlying database. It is inadvisable to use this to implement
* long-running sessions that span many business tasks. This method is, however, useful in certain special circumstances.
* For example
* <ul>
* <li>where a database trigger alters the object state upon insert or update</li>
* <li>after executing direct SQL (eg. a mass update) in the same session</li>
* <li>after inserting a Blob or Clob</li>
* </ul>
*/
public void refresh (com.neuralquest.server.Assoc assoc, Session s)
{
refresh((Object) assoc, s);
}
}
|
/*
* Copyright 2015, Jakob Korherr
*
* 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.mascherl.example;
import org.mascherl.application.MascherlApplication;
import javax.ws.rs.core.Application;
import java.util.HashSet;
import java.util.Set;
/**
* JAX-RS application for Mascherl.
*
* @author Jakob Korherr
*/
public class MascherlJaxRsApplication extends Application {
@Override
public Set<Class<?>> getClasses() {
Set<Class<?>> classes = new HashSet<>();
classes.addAll(MascherlApplication.getJaxRsClasses());
classes.add(OverviewPage.class);
return classes;
}
}
|
/**
* Copyright (c) 2011 Source Auditor 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.spdx.rdfparser;
import com.hp.hpl.jena.graph.Node;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.Resource;
import java.util.ArrayList;
/**
* Special class of license to represent no asserted license license in the file or packages
* @author Gary O'Neall
*
*/
public class SpdxNoAssertionLicense extends SPDXLicenseInfo {
static final int NO_ASSERTION_HASHCODE = 89; // prime number - all NoAssertion licenses should have the same hashcode
/**
* @param model
* @param licenseInfoNode
* @throws InvalidSPDXAnalysisException
*/
public SpdxNoAssertionLicense(Model model, Node licenseInfoNode)
throws InvalidSPDXAnalysisException {
super(model, licenseInfoNode);
}
/**
*
*/
public SpdxNoAssertionLicense() {
super();
}
/* (non-Javadoc)
* @see org.spdx.rdfparser.SPDXLicenseInfo#_createResource(com.hp.hpl.jena.rdf.model.Model)
*/
@Override
protected Resource _createResource(Model model) {
return model.createResource(SpdxRdfConstants.SPDX_NAMESPACE+SpdxRdfConstants.TERM_LICENSE_NOASSERTION);
}
/* (non-Javadoc)
* @see org.spdx.rdfparser.SPDXLicenseInfo#toString()
*/
@Override
public String toString() {
return SPDXLicenseInfoFactory.NOASSERTION_LICENSE_NAME;
}
@Override
public int hashCode() {
return NO_ASSERTION_HASHCODE;
}
/* (non-Javadoc)
* @see org.spdx.rdfparser.SPDXLicenseInfo#equals(java.lang.Object)
*/
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
}
return (o instanceof SpdxNoAssertionLicense); // All instances of this type are considered equal
}
/* (non-Javadoc)
* @see org.spdx.rdfparser.SPDXLicenseInfo#verify()
*/
@Override
public ArrayList<String> verify() {
return new ArrayList<String>();
}
}
|
/*
* Copyright (c) 2009 University of Durham, England All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met: *
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer. * Redistributions in binary
* form must reproduce the above copyright notice, this list of conditions and
* the following disclaimer in the documentation and/or other materials provided
* with the distribution. * Neither the name of 'SynergyNet' nor the names of
* its contributors may be used to endorse or promote products derived from this
* software without specific prior written permission. THIS SOFTWARE IS PROVIDED
* BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package synergynetframework.config.table;
import java.util.prefs.Preferences;
import javax.swing.JPanel;
import synergynetframework.config.PreferencesItem;
import core.ConfigurationSystem;
/**
* The Class TableConfigPrefsItem.
*/
public class TableConfigPrefsItem implements PreferencesItem {
/**
* The Enum MenuType.
*/
public static enum MenuType {
/** The automatic. */
AUTOMATIC,
/** The combo. */
COMBO,
/** The manual. */
MANUAL
}
/**
* The Enum TableType.
*/
public static enum TableType {
/** The evoluce. */
EVOLUCE,
/** The jmedirect. */
JMEDIRECT,
/** The tuio. */
TUIO,
/** The tuiosim. */
TUIOSIM,
/** The WI n7. */
WIN7,
/** The WI n7_64bit java. */
WIN7_64bitJava,
/** The JWinPosition. */
ALTWIN
}
/** The Constant prefs. */
private static final Preferences prefs = ConfigurationSystem
.getPreferences(TableConfigPrefsItem.class);
/** The Constant PREFS_MENU_TYPE. */
public static final String PREFS_MENU_TYPE = "MENU_TYPE";
/** The Constant PREFS_TABLE_TYPE. */
public static final String PREFS_TABLE_TYPE = "TABLE_TYPE";
/** The Constant TUIO_PORT. */
public static final String TUIO_PORT = "TUIO_PORT";
/*
* (non-Javadoc)
* @see synergynetframework.config.PreferencesItem#getConfigurationPanel()
*/
@Override
public JPanel getConfigurationPanel() {
return new TableConfigPrefsPanel(this);
}
/**
* Gets the menu type.
*
* @return the menu type
*/
public MenuType getMenuType() {
return MenuType.valueOf(prefs.get(PREFS_MENU_TYPE,
MenuType.COMBO.name()));
}
/*
* (non-Javadoc)
* @see synergynetframework.config.PreferencesItem#getName()
*/
@Override
public String getName() {
return "Table Type";
}
/**
* Gets the table type.
*
* @return the table type
*/
public TableType getTableType() {
return TableType.valueOf(prefs.get(PREFS_TABLE_TYPE,
TableType.JMEDIRECT.name()));
}
/**
* Gets the tuio port.
*
* @return the tuio port
*/
public int getTuioPort() {
return prefs.getInt(TUIO_PORT, 3333);
}
/**
* Sets the menu type.
*
* @param type
* the new menu type
*/
public void setMenuType(MenuType type) {
prefs.put(PREFS_MENU_TYPE, type.name());
}
/**
* Sets the table type.
*
* @param type
* the new table type
*/
public void setTableType(TableType type) {
prefs.put(PREFS_TABLE_TYPE, type.name());
}
/**
* Sets the tuio port.
*
* @param port
* the new tuio port
*/
public void setTuioPort(int port) {
prefs.putInt(TUIO_PORT, port);
}
}
|
package com.springlearning.dubbobasic;
import com.springlearning.dubbobasic.service.DemoService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class ConsumerMain {
public static void main(String[] args) {
DemoService demoService = null;
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:META-INF/spring/application.xml");
demoService = context.getBean(DemoService.class);
int count = 0;
while (true) {
count++;
// 调用服务
System.out.println(demoService.sayHello("ABCD123456" + " - " + count));
try {
Thread.sleep(200);
} catch (Exception e) {
//
}
}
}
}
|
/*
* Zed Attack Proxy (ZAP) and its related class files.
*
* ZAP is an HTTP/HTTPS proxy for assessing web application security.
*
* Copyright 2013 The ZAP Development Team
*
* 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.zaproxy.zap.extension.api;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import org.apache.commons.httpclient.URI;
import org.apache.log4j.Logger;
import org.parosproxy.paros.Constant;
import org.parosproxy.paros.model.Model;
import org.parosproxy.paros.model.SiteNode;
import org.zaproxy.zap.authentication.AuthenticationMethod;
import org.zaproxy.zap.authentication.AuthenticationMethod.AuthCheckingStrategy;
import org.zaproxy.zap.authentication.AuthenticationMethod.AuthPollFrequencyUnits;
import org.zaproxy.zap.authentication.AuthenticationMethodType;
import org.zaproxy.zap.extension.api.ApiException.Type;
import org.zaproxy.zap.extension.authorization.AuthorizationDetectionMethod;
import org.zaproxy.zap.model.Context;
import org.zaproxy.zap.model.IllegalContextNameException;
import org.zaproxy.zap.model.Tech;
import org.zaproxy.zap.model.TechSet;
import org.zaproxy.zap.utils.ApiUtils;
import org.zaproxy.zap.utils.JsonUtil;
public class ContextAPI extends ApiImplementor {
private static final Logger log = Logger.getLogger(ContextAPI.class);
private static final String PREFIX = "context";
private static final String TECH_NAME = "technologyName";
private static final String ACTION_EXCLUDE_FROM_CONTEXT_REGEX = "excludeFromContext";
private static final String ACTION_INCLUDE_IN_CONTEXT_REGEX = "includeInContext";
private static final String ACTION_SET_CONTEXT_REGEXS = "setContextRegexs";
private static final String ACTION_SET_CONTEXT_CHECKING_STRATEGY = "setContextCheckingStrategy";
private static final String ACTION_NEW_CONTEXT = "newContext";
private static final String ACTION_REMOVE_CONTEXT = "removeContext";
private static final String ACTION_SET_CONTEXT_IN_SCOPE = "setContextInScope";
private static final String ACTION_EXPORT_CONTEXT = "exportContext";
private static final String ACTION_IMPORT_CONTEXT = "importContext";
private static final String ACTION_INCLUDE_TECHS = "includeContextTechnologies";
private static final String ACTION_INCLUDE_ALL_TECHS = "includeAllContextTechnologies";
private static final String ACTION_EXCLUDE_TECHS = "excludeContextTechnologies";
private static final String ACTION_EXCLUDE_ALL_TECHS = "excludeAllContextTechnologies";
private static final String VIEW_EXCLUDE_REGEXS = "excludeRegexs";
private static final String VIEW_INCLUDE_REGEXS = "includeRegexs";
private static final String VIEW_CONTEXT_LIST = "contextList";
private static final String VIEW_CONTEXT = "context";
private static final String VIEW_ALL_TECHS = "technologyList";
private static final String VIEW_INCLUDED_TECHS = "includedTechnologyList";
private static final String VIEW_EXCLUDED_TECHS = "excludedTechnologyList";
private static final String VIEW_URLS = "urls";
private static final String REGEX_PARAM = "regex";
private static final String INC_REGEXS_PARAM = "incRegexs";
private static final String EXC_REGEXS_PARAM = "excRegexs";
private static final String CONTEXT_NAME = "contextName";
private static final String IN_SCOPE = "booleanInScope";
private static final String CONTEXT_FILE_PARAM = "contextFile";
private static final String CONTEXT_ID = "contextId";
private static final String PARAM_TECH_NAMES = "technologyNames";
private static final String PARAM_CHECKING_STRATEGRY = "checkingStrategy";
private static final String PARAM_POLL_URL = "pollUrl";
private static final String PARAM_POLL_DATA = "pollData";
private static final String PARAM_POLL_HEADERS = "pollHeaders";
private static final String PARAM_POLL_FREQ = "pollFrequency";
private static final String PARAM_POLL_FREQ_UNITS = "pollFrequencyUnits";
public ContextAPI() {
List<String> contextNameAndRegexParam = new ArrayList<>(2);
contextNameAndRegexParam.add(CONTEXT_NAME);
contextNameAndRegexParam.add(REGEX_PARAM);
List<String> contextNameOnlyParam = new ArrayList<>(1);
contextNameOnlyParam.add((CONTEXT_NAME));
String[] contextNameAndTechNames = new String[] {CONTEXT_NAME, PARAM_TECH_NAMES};
this.addApiAction(
new ApiAction(ACTION_EXCLUDE_FROM_CONTEXT_REGEX, contextNameAndRegexParam));
this.addApiAction(new ApiAction(ACTION_INCLUDE_IN_CONTEXT_REGEX, contextNameAndRegexParam));
this.addApiAction(
new ApiAction(
ACTION_SET_CONTEXT_REGEXS,
new String[] {CONTEXT_NAME, INC_REGEXS_PARAM, EXC_REGEXS_PARAM}));
this.addApiAction(
new ApiAction(
ACTION_SET_CONTEXT_CHECKING_STRATEGY,
new String[] {CONTEXT_NAME, PARAM_CHECKING_STRATEGRY},
new String[] {
PARAM_POLL_URL,
PARAM_POLL_DATA,
PARAM_POLL_HEADERS,
PARAM_POLL_FREQ,
PARAM_POLL_FREQ_UNITS
}));
this.addApiAction(new ApiAction(ACTION_NEW_CONTEXT, contextNameOnlyParam));
this.addApiAction(new ApiAction(ACTION_REMOVE_CONTEXT, contextNameOnlyParam));
this.addApiAction(
new ApiAction(
ACTION_EXPORT_CONTEXT,
new String[] {CONTEXT_NAME, CONTEXT_FILE_PARAM},
null));
this.addApiAction(
new ApiAction(ACTION_IMPORT_CONTEXT, new String[] {CONTEXT_FILE_PARAM}, null));
this.addApiAction(new ApiAction(ACTION_INCLUDE_TECHS, contextNameAndTechNames));
this.addApiAction(new ApiAction(ACTION_INCLUDE_ALL_TECHS, contextNameOnlyParam));
this.addApiAction(new ApiAction(ACTION_EXCLUDE_TECHS, contextNameAndTechNames));
this.addApiAction(new ApiAction(ACTION_EXCLUDE_ALL_TECHS, contextNameOnlyParam));
List<String> contextInScopeParams = new ArrayList<>(2);
contextInScopeParams.add(CONTEXT_NAME);
contextInScopeParams.add(IN_SCOPE);
this.addApiAction(new ApiAction(ACTION_SET_CONTEXT_IN_SCOPE, contextInScopeParams));
this.addApiView(new ApiView(VIEW_CONTEXT_LIST));
this.addApiView(new ApiView(VIEW_EXCLUDE_REGEXS, contextNameOnlyParam));
this.addApiView(new ApiView(VIEW_INCLUDE_REGEXS, contextNameOnlyParam));
this.addApiView(new ApiView(VIEW_CONTEXT, contextNameOnlyParam));
this.addApiView(new ApiView(VIEW_ALL_TECHS));
this.addApiView(new ApiView(VIEW_INCLUDED_TECHS, contextNameOnlyParam));
this.addApiView(new ApiView(VIEW_EXCLUDED_TECHS, contextNameOnlyParam));
this.addApiView(new ApiView(VIEW_URLS, contextNameOnlyParam));
}
@Override
public String getPrefix() {
return PREFIX;
}
@Override
public ApiResponse handleApiAction(String name, JSONObject params) throws ApiException {
log.debug("handleApiAction " + name + " " + params.toString());
Context context;
TechSet techSet;
String[] techNames;
String filename;
File f;
switch (name) {
case ACTION_EXCLUDE_FROM_CONTEXT_REGEX:
try {
addExcludeToContext(getContext(params), params.getString(REGEX_PARAM));
} catch (IllegalArgumentException e) {
throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, REGEX_PARAM, e);
}
break;
case ACTION_INCLUDE_IN_CONTEXT_REGEX:
try {
addIncludeToContext(getContext(params), params.getString(REGEX_PARAM));
} catch (IllegalArgumentException e) {
throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, REGEX_PARAM, e);
}
break;
case ACTION_SET_CONTEXT_REGEXS:
context = getContext(params);
JSONArray incRegexs;
JSONArray excRegexs;
try {
incRegexs = JSONArray.fromObject(params.get(INC_REGEXS_PARAM));
context.setIncludeInContextRegexs(JsonUtil.toStringList(incRegexs));
} catch (JSONException e1) {
throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, INC_REGEXS_PARAM);
}
try {
excRegexs = JSONArray.fromObject(params.get(EXC_REGEXS_PARAM));
context.setExcludeFromContextRegexs(JsonUtil.toStringList(excRegexs));
} catch (Exception e1) {
throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, EXC_REGEXS_PARAM);
}
Model.getSingleton().getSession().saveContext(context);
break;
case ACTION_SET_CONTEXT_CHECKING_STRATEGY:
context = getContext(params);
AuthCheckingStrategy checkingStrategy;
try {
checkingStrategy =
AuthCheckingStrategy.valueOf(
params.getString(PARAM_CHECKING_STRATEGRY));
} catch (Exception e1) {
throw new ApiException(
ApiException.Type.ILLEGAL_PARAMETER, PARAM_CHECKING_STRATEGRY);
}
if (AuthCheckingStrategy.POLL_URL.equals(checkingStrategy)) {
AuthPollFrequencyUnits units;
try {
units =
AuthPollFrequencyUnits.valueOf(
params.getString(PARAM_POLL_FREQ_UNITS));
} catch (Exception e) {
throw new ApiException(
ApiException.Type.ILLEGAL_PARAMETER, PARAM_POLL_FREQ_UNITS);
}
int freq;
String pollUrl = params.getString(PARAM_POLL_URL);
String pollData = params.getString(PARAM_POLL_DATA);
String pollHeaders = params.getString(PARAM_POLL_HEADERS);
if (pollUrl == null || pollUrl.isEmpty()) {
throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_POLL_URL);
}
try {
new URI(pollUrl, true);
} catch (Exception e) {
throw new ApiException(ApiException.Type.ILLEGAL_PARAMETER, PARAM_POLL_URL);
}
try {
freq = params.getInt(PARAM_POLL_FREQ);
} catch (Exception e) {
throw new ApiException(
ApiException.Type.ILLEGAL_PARAMETER, PARAM_POLL_FREQ);
}
if (freq <= 0) {
throw new ApiException(
ApiException.Type.ILLEGAL_PARAMETER, PARAM_POLL_FREQ);
}
context.getAuthenticationMethod().setPollUrl(pollUrl);
context.getAuthenticationMethod().setPollData(pollData);
context.getAuthenticationMethod().setPollHeaders(pollHeaders);
context.getAuthenticationMethod().setPollFrequency(freq);
context.getAuthenticationMethod().setPollFrequencyUnits(units);
}
context.getAuthenticationMethod().setAuthCheckingStrategy(checkingStrategy);
Model.getSingleton().getSession().saveContext(context);
break;
case ACTION_NEW_CONTEXT:
String contextName = params.getString(CONTEXT_NAME);
try {
context = Model.getSingleton().getSession().getNewContext(contextName);
} catch (IllegalContextNameException e) {
throw new ApiException(ApiException.Type.ALREADY_EXISTS, contextName, e);
}
Model.getSingleton().getSession().saveContext(context);
return new ApiResponseElement(CONTEXT_ID, String.valueOf(context.getId()));
case ACTION_REMOVE_CONTEXT:
context = getContext(params);
Model.getSingleton().getSession().deleteContext(context);
break;
case ACTION_SET_CONTEXT_IN_SCOPE:
context = getContext(params);
context.setInScope(params.getBoolean(IN_SCOPE));
Model.getSingleton().getSession().saveContext(context);
break;
case ACTION_IMPORT_CONTEXT:
filename = params.getString(CONTEXT_FILE_PARAM);
f = new File(filename);
if (!f.exists()) {
// Try relative to the contexts dir
f = new File(Constant.getContextsDir(), filename);
}
if (!f.exists()) {
throw new ApiException(ApiException.Type.DOES_NOT_EXIST, f.getAbsolutePath());
} else {
try {
context = Model.getSingleton().getSession().importContext(f);
} catch (IllegalContextNameException e) {
throw new ApiException(ApiException.Type.BAD_EXTERNAL_DATA, e);
} catch (Exception e) {
log.error(e.getMessage(), e);
throw new ApiException(ApiException.Type.INTERNAL_ERROR, e.getMessage());
}
}
return new ApiResponseElement(CONTEXT_ID, String.valueOf(context.getId()));
case ACTION_EXPORT_CONTEXT:
filename = params.getString(CONTEXT_FILE_PARAM);
context = getContext(params);
f = new File(filename);
if (!f.getAbsolutePath().equals(filename)) {
// Not an absolute filename, use one relative to the contexts dir
f = new File(Constant.getContextsDir(), filename);
}
if (!f.getParentFile().canWrite()) {
// Cant write to the parent dir so not looking good
throw new ApiException(ApiException.Type.NO_ACCESS, f.getAbsolutePath());
} else {
try {
Model.getSingleton().getSession().exportContext(context, f);
} catch (Exception e) {
throw new ApiException(ApiException.Type.INTERNAL_ERROR, e.getMessage());
}
}
break;
case ACTION_INCLUDE_TECHS:
context = getContext(params);
techSet = context.getTechSet();
techNames = getParam(params, PARAM_TECH_NAMES, "").split(",");
for (String techName : techNames) {
techSet.include(getTech(techName));
}
context.save();
break;
case ACTION_INCLUDE_ALL_TECHS:
context = getContext(params);
techSet = new TechSet(Tech.builtInTech);
context.setTechSet(techSet);
context.save();
break;
case ACTION_EXCLUDE_TECHS:
context = getContext(params);
techSet = context.getTechSet();
techNames = getParam(params, PARAM_TECH_NAMES, "").split(",");
for (String techName : techNames) {
techSet.exclude(getTech(techName));
}
context.save();
break;
case ACTION_EXCLUDE_ALL_TECHS:
context = getContext(params);
techSet = context.getTechSet();
for (Tech tech : Tech.builtInTech) {
techSet.exclude(tech);
}
context.save();
break;
default:
throw new ApiException(Type.BAD_ACTION);
}
return ApiResponseElement.OK;
}
private void addExcludeToContext(Context context, String regex) {
List<String> incRegexes = new ArrayList<String>(context.getIncludeInContextRegexs());
if (incRegexes.remove(regex)) {
// Its already explicitly included, removing it from the include list is safer and more
// useful
context.setIncludeInContextRegexs(incRegexes);
} else {
context.addExcludeFromContextRegex(regex);
}
Model.getSingleton().getSession().saveContext(context);
}
private void addIncludeToContext(Context context, String regex) {
context.addIncludeInContextRegex(regex);
Model.getSingleton().getSession().saveContext(context);
}
@Override
public ApiResponse handleApiView(String name, JSONObject params) throws ApiException {
log.debug("handleApiView " + name + " " + params.toString());
ApiResponse result;
ApiResponseList resultList;
TechSet techSet;
switch (name) {
case VIEW_EXCLUDE_REGEXS:
resultList = new ApiResponseList(name);
for (String regex : getContext(params).getExcludeFromContextRegexs()) {
resultList.addItem(new ApiResponseElement(REGEX_PARAM, regex));
}
result = resultList;
break;
case VIEW_INCLUDE_REGEXS:
resultList = new ApiResponseList(name);
for (String regex : getContext(params).getIncludeInContextRegexs()) {
resultList.addItem(new ApiResponseElement(REGEX_PARAM, regex));
}
result = resultList;
break;
case VIEW_CONTEXT_LIST:
resultList = new ApiResponseList(name);
for (Context context : Model.getSingleton().getSession().getContexts()) {
resultList.addItem(new ApiResponseElement(CONTEXT_NAME, context.getName()));
}
result = resultList;
break;
case VIEW_CONTEXT:
result = new ApiResponseElement(buildResponseFromContext(getContext(params)));
break;
case VIEW_ALL_TECHS:
resultList = new ApiResponseList(name);
for (Tech tech : Tech.builtInTech) {
resultList.addItem(new ApiResponseElement(TECH_NAME, tech.toString()));
}
result = resultList;
break;
case VIEW_INCLUDED_TECHS:
resultList = new ApiResponseList(name);
techSet = getContext(params).getTechSet();
for (Tech tech : techSet.getIncludeTech()) {
resultList.addItem(new ApiResponseElement(TECH_NAME, tech.toString()));
}
result = resultList;
break;
case VIEW_EXCLUDED_TECHS:
resultList = new ApiResponseList(name);
techSet = getContext(params).getTechSet();
for (Tech tech : techSet.getExcludeTech()) {
resultList.addItem(new ApiResponseElement(TECH_NAME, tech.toString()));
}
result = resultList;
break;
case VIEW_URLS:
resultList = new ApiResponseList(name);
Set<String> addedUrls = new HashSet<>();
for (SiteNode node : getContext(params).getNodesInContextFromSiteTree()) {
String uri = node.getHistoryReference().getURI().toString();
if (!addedUrls.contains(uri)) {
resultList.addItem(new ApiResponseElement("url", uri));
addedUrls.add(uri);
}
}
result = resultList;
break;
default:
throw new ApiException(Type.BAD_VIEW);
}
return result;
}
/**
* Returns the {@code Context} with the given name. The context's name is obtained from the
* given parameters, whose name is {@value #CONTEXT_NAME}.
*
* <p>The parameter must exist, that is, it should be a mandatory parameter, otherwise a runtime
* exception is thrown.
*
* @param params the parameters that contain the context's name
* @return the {@code Context} with the given name
* @throws ApiException If the context with the given name does not exist
* @see JSONObject#getString(String)
*/
private Context getContext(JSONObject params) throws ApiException {
return ApiUtils.getContextByName(params, CONTEXT_NAME);
}
/**
* Builds the response describing an Context.
*
* @param c the context
* @return the api response
*/
private ApiResponse buildResponseFromContext(Context c) {
Map<String, String> fields = new HashMap<>();
fields.put("name", c.getName());
fields.put("id", Integer.toString(c.getId()));
fields.put("description", c.getDescription());
fields.put("inScope", Boolean.toString(c.isInScope()));
fields.put("excludeRegexs", jsonEncodeList(c.getExcludeFromContextRegexs()));
fields.put("includeRegexs", jsonEncodeList(c.getIncludeInContextRegexs()));
AuthenticationMethod authenticationMethod = c.getAuthenticationMethod();
if (authenticationMethod != null) {
Pattern pattern = authenticationMethod.getLoggedInIndicatorPattern();
fields.put("loggedInPattern", pattern == null ? "" : pattern.toString());
pattern = authenticationMethod.getLoggedOutIndicatorPattern();
fields.put("loggedOutPattern", pattern == null ? "" : pattern.toString());
AuthenticationMethodType type = authenticationMethod.getType();
fields.put("authType", type == null ? "" : type.getName());
AuthCheckingStrategy strategy = authenticationMethod.getAuthCheckingStrategy();
fields.put(PARAM_CHECKING_STRATEGRY, strategy == null ? "" : strategy.name());
if (AuthCheckingStrategy.POLL_URL.equals(strategy)) {
fields.put(PARAM_POLL_URL, authenticationMethod.getPollUrl());
fields.put(PARAM_POLL_DATA, authenticationMethod.getPollData());
fields.put(PARAM_POLL_HEADERS, authenticationMethod.getPollData());
fields.put(
PARAM_POLL_FREQ, Integer.toString(authenticationMethod.getPollFrequency()));
AuthPollFrequencyUnits units = authenticationMethod.getPollFrequencyUnits();
fields.put(PARAM_POLL_FREQ_UNITS, units == null ? "" : units.name());
}
}
AuthorizationDetectionMethod authorizationDetectionMethod =
c.getAuthorizationDetectionMethod();
if (authorizationDetectionMethod != null) {
fields.put(
"authenticationDetectionMethodId",
String.valueOf(authorizationDetectionMethod.getMethodUniqueIdentifier()));
}
fields.put("urlParameterParserClass", c.getUrlParamParser().getClass().getCanonicalName());
fields.put("urlParameterParserConfig", c.getUrlParamParser().getConfig());
fields.put(
"postParameterParserClass", c.getPostParamParser().getClass().getCanonicalName());
fields.put("postParameterParserConfig", c.getPostParamParser().getConfig());
return new ApiResponseSet<String>("context", fields);
}
private String jsonEncodeList(List<String> list) {
JSONArray js = new JSONArray();
for (String item : list) {
js.add(item);
}
return js.toString();
}
/**
* Gets the tech that matches the techName or throws an exception if no tech matches
*
* @param techName the name of the tech
* @return the matching tech
* @throws ApiException the api exception
*/
private Tech getTech(String techName) throws ApiException {
String trimmedTechName = techName.trim();
for (Tech tech : Tech.builtInTech) {
if (tech.toString().equalsIgnoreCase(trimmedTechName)) return tech;
}
throw new ApiException(
Type.ILLEGAL_PARAMETER, "The tech '" + trimmedTechName + "' does not exist");
}
}
|
package de.jpaw.bonaparte.jpa;
import java.sql.Types;
import org.eclipse.persistence.internal.helper.DatabaseField;
import org.eclipse.persistence.mappings.DatabaseMapping;
import org.eclipse.persistence.mappings.converters.Converter;
import org.eclipse.persistence.mappings.foundation.AbstractDirectMapping;
import org.eclipse.persistence.sessions.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import de.jpaw.bonaparte.core.BonaparteJsonEscaper;
import de.jpaw.bonaparte.jpa.json.NativeJsonObject;
import de.jpaw.json.JsonException;
import de.jpaw.json.JsonParser;
// convert between the Java type "NativeJsonObject(Map<String, Object>)" and a text, which in the database will be used as JSON
// a type cast is required on the database to avoid Postgres's type errors!
// see http://stackoverflow.com/questions/32238884/storing-json-jsonb-hstore-xml-enum-ipaddr-etc-fails-with-column-x-is-of
//CREATE OR REPLACE FUNCTION json_intext(text) RETURNS json AS $$
//SELECT json_in($1::cstring);
//$$ LANGUAGE SQL IMMUTABLE;
//
//CREATE CAST (text AS json)
//WITH FUNCTION json_intext(text) AS IMPLICIT;
public class JsonConverter extends AbstractConverter implements Converter {
private static final long serialVersionUID = 166786L;
protected static final Logger LOGGER = LoggerFactory.getLogger(JsonConverter.class);
// parse String to Map (inside NativeJsonObject)
@Override
public Object convertDataValueToObjectValue(Object dataValue, Session session) {
try {
return dataValue == null ? null : new NativeJsonObject(new JsonParser((String) dataValue, false).parseObject());
} catch (JsonException e) {
LOGGER.error("Cannot parse JSON data: {}", e.getMessage());
throw new RuntimeException(e);
}
}
// print Map in JSON format, also expand any BonaPortables included
@Override
public Object convertObjectValueToDataValue(Object objectValue, Session session) {
return objectValue == null ? null : BonaparteJsonEscaper.asJson(((NativeJsonObject) objectValue).getData());
}
@Override
public void initialize(DatabaseMapping mapping, Session session) {
((AbstractDirectMapping) mapping).setFieldType(Types.NVARCHAR); // candidates are JAVA_OBJECT, OTHER, NVARCHAR etc...
// field type setting adapted from http://stackoverflow.com/questions/13346089/using-uuid-with-eclipselink-and-postgresql
final DatabaseField field = mapping.getField();
if (field != null) {
LOGGER.info("mapping.getField is not null");
if (isPostgres(session)) {
field.setColumnDefinition("jsonb");
// field.setType(NativeJsonObject.class);
// field.setTypeName("java.util.Map");
}
}
}
@Override
public boolean isMutable() {
return true;
}
}
|
package day3;
import java.util.Scanner;
public class Pattern6 {
/*
1
2*3
4*5*6
7*8*9*10
7*8*9*10
4*5*6
2*3
1
// increasing
rows: n
numbers: i + 1
// decreasing
rows: n
numbers: n - i
number(j): first_number_in_row(i) + j
first_number_in_row(i):
7, 7 - 3 = 4, 4 - 2 = 2, 2 - 1 = 1
0 + 1 + 2 + 3 + (n-1) = n * (n - 1) / 2 + 1
*/
/*
time complexity: O(rows^2)
space complexity: O(1)
*/
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int rows = scanner.nextInt();
// increasing
for (int i = 0, number = 1 ; i < rows ; i++) {
for (int j = 0 ; j < i + 1 ; j++) {
System.out.print(number++ + (j == i ? "" : "*"));
// number = 7
// 7 + (3 == 4 ? "" : "*")
// number++ --> number = 8
// 7 + ("*")
// 7 + "*"
// "7" + "*"
// "7*"
}
System.out.println();
}
// decreasing
for (int i = 0, number = (rows * (rows - 1)) / 2 + 1 ; i < rows ; number -= rows - 1 - i, i++) {
for (int j = 0 ; j < rows - i ; j++) {
System.out.print(number + j + (j == rows - i - 1 ? "" : "*"));
}
System.out.println();
}
}
}
|
package com.refinitiv.eta.json.converter;
import com.fasterxml.jackson.databind.JsonNode;
import com.refinitiv.eta.codec.DataTypes;
import com.refinitiv.eta.codec.Date;
import com.refinitiv.eta.codec.DecodeIterator;
import com.refinitiv.eta.codec.EncodeIterator;
import com.refinitiv.eta.json.util.JsonFactory;
import static com.refinitiv.eta.codec.CodecReturnCodes.SUCCESS;
class JsonDateConverter extends AbstractPrimitiveTypeConverter {
JsonDateConverter(JsonAbstractConverter converter) {
super(converter);
dataTypes = new int[] { DataTypes.DATE, DataTypes.DATE_4 };
}
@Override
Object getPrimitiveType() {
return JsonFactory.createDate();
}
@Override
void releasePrimitiveType(Object type) {
JsonFactory.releaseDate((Date) type);
}
@Override
int decode(DecodeIterator decIter, Object type) {
Date date = (Date) type;
date.clear();
return date.decode(decIter);
}
@Override
boolean writeToJson(JsonBuffer outBuffer, Object type, JsonConverterError error) {
return BasicPrimitiveConverter.writeDate((Date) type, outBuffer, error);
}
@Override
protected void decodeJson(JsonNode node, Object msg, JsonConverterError error) {
Date date = (Date) msg;
date.clear();
if (node.isNull()) {
date.blank();
} else {
int ret = date.value(node.textValue());
if (ret < SUCCESS)
error.setError(JsonConverterErrorCodes.JSON_ERROR_UNEXPECTED_VALUE, "Invalid date value: " + node.textValue() + ", code = " + ret);
}
}
@Override
protected void encodeRWF(JsonNode dataNode, String key, EncodeIterator iter, JsonConverterError error) {
if (dataNode.isNull())
return;
Date date = JsonFactory.createDate();
try {
decodeJson(dataNode, date, error);
int result = date.encode(iter);
if (result != SUCCESS) {
error.setEncodeError(result, key);
return;
}
} finally {
JsonFactory.releaseDate(date);
}
}
}
|
package org.finos.springbot.symphony.controller;
import static org.mockito.Mockito.atMost;
import java.io.File;
import java.io.FileInputStream;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.finos.springbot.entityjson.EntityJson;
import org.finos.springbot.symphony.SymphonyMockConfiguration;
import org.finos.springbot.symphony.SymphonyWorkflowConfig;
import org.finos.springbot.symphony.content.HashTag;
import org.finos.springbot.symphony.content.SymphonyUser;
import org.finos.springbot.symphony.form.ElementsHandler;
import org.finos.springbot.symphony.messages.PresentationMLHandler;
import org.finos.springbot.tests.controller.AbstractHandlerMappingTest;
import org.finos.springbot.tests.controller.OurController;
import org.finos.springbot.workflow.actions.Action;
import org.finos.springbot.workflow.actions.SimpleMessageAction;
import org.finos.springbot.workflow.annotations.ChatRequest;
import org.finos.springbot.workflow.content.Message;
import org.finos.springbot.workflow.content.User;
import org.finos.springbot.workflow.data.EntityJsonConverter;
import org.finos.springbot.workflow.form.ButtonList;
import org.finos.springbot.workflow.java.mapping.ChatMapping;
import org.finos.springbot.workflow.java.mapping.ChatRequestChatHandlerMapping;
import org.finos.springbot.workflow.response.WorkResponse;
import org.glassfish.jersey.media.multipart.file.FileDataBodyPart;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.util.StreamUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.symphony.api.agent.MessagesApi;
import com.symphony.api.model.StreamType;
import com.symphony.api.model.V4Event;
import com.symphony.api.model.V4Initiator;
import com.symphony.api.model.V4Message;
import com.symphony.api.model.V4MessageSent;
import com.symphony.api.model.V4Payload;
import com.symphony.api.model.V4Stream;
import com.symphony.api.model.V4SymphonyElementsAction;
import com.symphony.api.model.V4User;
@SpringBootTest(classes = {
SymphonyMockConfiguration.class,
SymphonyWorkflowConfig.class,
})
public class SymphonyHandlerMappingTest extends AbstractHandlerMappingTest {
@Autowired
ChatRequestChatHandlerMapping hm;
@Autowired
PresentationMLHandler mc;
@Autowired
ElementsHandler eh;
@Autowired
EntityJsonConverter ejc;
@MockBean
MessagesApi messagesApi;
@Autowired
OurController oc;
ArgumentCaptor<String> msg;
ArgumentCaptor<String> data;
ArgumentCaptor<Object> att;
@Override
protected List<ChatMapping<ChatRequest>> getMappingsFor(Message m) throws Exception {
EntityJson jsonObjects = new EntityJson();
Action a = new SimpleMessageAction(null, null, m, jsonObjects);
return hm.getHandlers(a);
}
@Override
protected void execute(String s) throws Exception {
oc.lastArguments = null;
oc.lastMethod = null;
s = s.replace("@gaurav","<span class=\"entity\" data-entity-id=\"1\">@gaurav</span>");
Mockito.clearAllCaches();
EntityJson jsonObjects = new EntityJson();
jsonObjects.put("1", new SymphonyUser(123l, "gaurav", "gaurav@example.com"));
jsonObjects.put("2", new HashTag("SomeTopic"));
String dataStr = ejc.writeValue(jsonObjects);
V4Event event = new V4Event()
.payload(new V4Payload()
.messageSent(new V4MessageSent()
.message(new V4Message()
.user(new V4User()
.displayName(ROB_NAME)
.email(ROB_EXAMPLE_EMAIL)
.userId(ROB_EXAMPLE_ID))
.stream(new V4Stream()
.streamType(StreamType.TypeEnum.ROOM.getValue())
.streamId(CHAT_ID))
.message("<messageML>/"+s+"</messageML>")
.data(dataStr))));
msg = ArgumentCaptor.forClass(String.class);
data = ArgumentCaptor.forClass(String.class);
att = ArgumentCaptor.forClass(Object.class);
mc.accept(event);
Mockito.verify(messagesApi, atMost(1)).v4StreamSidMessageCreatePost(
Mockito.nullable(String.class),
Mockito.matches(CHAT_ID),
msg.capture(),
data.capture(),
Mockito.isNull(),
att.capture(),
Mockito.isNull(),
Mockito.isNull());
}
@Override
protected String getMessageData() {
return data.getValue();
}
@Override
protected String getMessageContent() {
return msg.getValue();
}
@Override
protected void pressButton(String s) {
oc.lastArguments = null;
oc.lastMethod = null;
Mockito.clearAllCaches();
Map<String, Object> values = new HashMap<>();
values.put("action", s);
V4Event event = new V4Event()
.initiator(new V4Initiator().user(new V4User()
.displayName(ROB_NAME)
.email(ROB_EXAMPLE_EMAIL)
.userId(ROB_EXAMPLE_ID)))
.payload(new V4Payload()
.symphonyElementsAction(new V4SymphonyElementsAction()
.formValues(values)
.stream(new V4Stream()
.streamType(StreamType.TypeEnum.ROOM.getValue())
.streamId(CHAT_ID))));
msg = ArgumentCaptor.forClass(String.class);
data = ArgumentCaptor.forClass(String.class);
att = ArgumentCaptor.forClass(Object.class);
eh.accept(event);
Mockito.verify(messagesApi, atMost(1)).v4StreamSidMessageCreatePost(
Mockito.nullable(String.class),
Mockito.matches(CHAT_ID),
msg.capture(),
data.capture(),
Mockito.isNull(),
att.capture(),
Mockito.isNull(),
Mockito.isNull());
}
@Override
protected void assertHelpResponse() throws Exception {
String msg = getMessageContent();
String data = getMessageData();
JsonNode node = new ObjectMapper().readTree(data);
System.out.println(msg);
System.out.println(data);
Assertions.assertEquals(14, node.get(WorkResponse.OBJECT_KEY).get("commands").size());
Assertions.assertTrue(data.contains(" {\n"
+ " \"type\" : \"org.finos.springbot.workflow.help.commandDescription\",\n"
+ " \"version\" : \"1.0\",\n"
+ " \"description\" : \"Display this help page\",\n"
+ " \"examples\" : [ \"help\" ]\n"
+ " }"));
Assertions.assertTrue(msg.contains("Description"));
}
@Test
public void testAttachmentResponse() throws Exception {
execute("attachment");
FileDataBodyPart fdbp = (FileDataBodyPart) att.getValue();
String contents = StreamUtils.copyToString(
new FileInputStream((File) fdbp.getEntity()),
Charset.defaultCharset());
Assertions.assertEquals("payload", contents);
}
@Test
public void testHashtagMapping() throws Exception {
execute("add @gaurav to <span class=\"entity\" data-entity-id=\"2\">#SomeTopic</span>");
Assertions.assertEquals("addUserToTopic", oc.lastMethod);
Assertions.assertEquals(2, oc.lastArguments.size());
Object firstArgument = oc.lastArguments.get(0);
Assertions.assertTrue(User.class.isAssignableFrom(firstArgument.getClass()));
Assertions.assertEquals("gaurav", ((User)firstArgument).getName());
Object secondArgument = oc.lastArguments.get(1);
Assertions.assertTrue(HashTag.class.isAssignableFrom(secondArgument.getClass()));
Assertions.assertEquals("SomeTopic", ((HashTag)secondArgument).getName());
}
@Override
protected void assertNoButtons() {
try {
String data = getMessageData();
JsonNode node = new ObjectMapper().readTree(data);
JsonNode buttons = node.get(ButtonList.KEY).get("contents");
Assertions.assertTrue(buttons.size() == 0);
Assertions.assertFalse(getMessageContent().contains("<form"));
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
}
|
package oca.chap4MethodsAndEncapsulation.lambdas;
public interface CheckTwoParameters {
boolean test(Animal a, Animal b);
}
|
package br.com.zupacademy.fabiano.mercadolivre.detalhe;
import br.com.zupacademy.fabiano.mercadolivre.produto.ImagemProduto;
public class DetalheImagemProduto {
private String link;
public DetalheImagemProduto(ImagemProduto imagem) {
this.link = imagem.getLink();
}
public String getLink() {
return link;
}
}
|
/*
* This file is part of LuckPerms, licensed under the MIT License.
*
* Copyright (c) lucko (Luck) <luck@lucko.me>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package me.lucko.luckperms.common.dependencies;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSetMultimap;
import com.google.common.collect.SetMultimap;
import com.google.gson.JsonElement;
import me.lucko.luckperms.common.config.ConfigKeys;
import me.lucko.luckperms.common.dependencies.relocation.Relocation;
import me.lucko.luckperms.common.dependencies.relocation.RelocationHandler;
import me.lucko.luckperms.common.plugin.LuckPermsPlugin;
import me.lucko.luckperms.common.storage.StorageType;
import net.luckperms.api.platform.Platform;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
/**
* Applies LuckPerms specific behaviour for {@link Dependency}s.
*/
public class DependencyRegistry {
private static final SetMultimap<StorageType, Dependency> STORAGE_DEPENDENCIES = ImmutableSetMultimap.<StorageType, Dependency>builder()
.putAll(StorageType.YAML, Dependency.CONFIGURATE_CORE, Dependency.CONFIGURATE_YAML, Dependency.SNAKEYAML)
.putAll(StorageType.YAML_COMBINED, Dependency.CONFIGURATE_CORE, Dependency.CONFIGURATE_YAML, Dependency.SNAKEYAML)
.putAll(StorageType.JSON, Dependency.CONFIGURATE_CORE, Dependency.CONFIGURATE_GSON)
.putAll(StorageType.JSON_COMBINED, Dependency.CONFIGURATE_CORE, Dependency.CONFIGURATE_GSON)
.putAll(StorageType.HOCON, Dependency.CONFIGURATE_CORE, Dependency.CONFIGURATE_HOCON, Dependency.HOCON_CONFIG)
.putAll(StorageType.HOCON_COMBINED, Dependency.CONFIGURATE_CORE, Dependency.CONFIGURATE_HOCON, Dependency.HOCON_CONFIG)
.putAll(StorageType.TOML, Dependency.CONFIGURATE_CORE, Dependency.CONFIGURATE_TOML, Dependency.TOML4J)
.putAll(StorageType.TOML_COMBINED, Dependency.CONFIGURATE_CORE, Dependency.CONFIGURATE_TOML, Dependency.TOML4J)
.putAll(StorageType.MONGODB, Dependency.MONGODB_DRIVER_CORE, Dependency.MONGODB_DRIVER_LEGACY, Dependency.MONGODB_DRIVER_SYNC, Dependency.MONGODB_DRIVER_BSON)
.putAll(StorageType.MARIADB, Dependency.SLF4J_API, Dependency.SLF4J_SIMPLE, Dependency.HIKARI, Dependency.MARIADB_DRIVER)
.putAll(StorageType.MYSQL, Dependency.SLF4J_API, Dependency.SLF4J_SIMPLE, Dependency.HIKARI, Dependency.MYSQL_DRIVER)
.putAll(StorageType.POSTGRESQL, Dependency.SLF4J_API, Dependency.SLF4J_SIMPLE, Dependency.HIKARI, Dependency.POSTGRESQL_DRIVER)
.putAll(StorageType.SQLITE, Dependency.SQLITE_DRIVER)
.putAll(StorageType.H2, Dependency.H2_DRIVER)
.build();
private static final Set<Platform.Type> SNAKEYAML_PROVIDED_BY_PLATFORM = ImmutableSet.of(
Platform.Type.BUKKIT, Platform.Type.BUNGEECORD, Platform.Type.SPONGE, Platform.Type.NUKKIT
);
private final LuckPermsPlugin plugin;
public DependencyRegistry(LuckPermsPlugin plugin) {
this.plugin = plugin;
}
public Set<Dependency> resolveStorageDependencies(Set<StorageType> storageTypes) {
Set<Dependency> dependencies = new LinkedHashSet<>();
for (StorageType storageType : storageTypes) {
dependencies.addAll(STORAGE_DEPENDENCIES.get(storageType));
}
if (this.plugin.getConfiguration().get(ConfigKeys.REDIS_ENABLED)) {
dependencies.add(Dependency.COMMONS_POOL_2);
dependencies.add(Dependency.JEDIS);
dependencies.add(Dependency.SLF4J_API);
dependencies.add(Dependency.SLF4J_SIMPLE);
}
if (this.plugin.getConfiguration().get(ConfigKeys.RABBITMQ_ENABLED)) {
dependencies.add(Dependency.RABBITMQ);
}
// don't load slf4j if it's already present
if ((dependencies.contains(Dependency.SLF4J_API) || dependencies.contains(Dependency.SLF4J_SIMPLE)) && slf4jPresent()) {
dependencies.remove(Dependency.SLF4J_API);
dependencies.remove(Dependency.SLF4J_SIMPLE);
}
// don't load snakeyaml if it's provided by the platform
if (dependencies.contains(Dependency.SNAKEYAML) && SNAKEYAML_PROVIDED_BY_PLATFORM.contains(this.plugin.getBootstrap().getType())) {
dependencies.remove(Dependency.SNAKEYAML);
}
return dependencies;
}
public void applyRelocationSettings(Dependency dependency, List<Relocation> relocations) {
Platform.Type type = this.plugin.getBootstrap().getType();
// support for LuckPerms legacy (bukkit 1.7.10)
if (!RelocationHandler.DEPENDENCIES.contains(dependency) && isGsonRelocated()) {
relocations.add(Relocation.of("guava", "com{}google{}common"));
relocations.add(Relocation.of("gson", "com{}google{}gson"));
}
// relocate yaml within configurate if its being provided by LP
if (dependency == Dependency.CONFIGURATE_YAML && !SNAKEYAML_PROVIDED_BY_PLATFORM.contains(type)) {
relocations.add(Relocation.of("yaml", "org{}yaml{}snakeyaml"));
}
}
public boolean shouldAutoLoad(Dependency dependency) {
switch (dependency) {
// all used within 'isolated' classloaders, and are therefore not
// relocated.
case ASM:
case ASM_COMMONS:
case JAR_RELOCATOR:
case H2_DRIVER:
case SQLITE_DRIVER:
return false;
default:
return true;
}
}
@SuppressWarnings("ConstantConditions")
public static boolean isGsonRelocated() {
return JsonElement.class.getName().startsWith("me.lucko");
}
private static boolean classExists(String className) {
try {
Class.forName(className);
return true;
} catch (ClassNotFoundException e) {
return false;
}
}
private static boolean slf4jPresent() {
return classExists("org.slf4j.Logger") && classExists("org.slf4j.LoggerFactory");
}
}
|
/*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/monitoring/v3/notification.proto
package com.google.monitoring.v3;
/**
*
*
* <pre>
* A description of a notification channel. The descriptor includes
* the properties of the channel and the set of labels or fields that
* must be specified to configure channels of a given type.
* </pre>
*
* Protobuf type {@code google.monitoring.v3.NotificationChannelDescriptor}
*/
public final class NotificationChannelDescriptor extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.monitoring.v3.NotificationChannelDescriptor)
NotificationChannelDescriptorOrBuilder {
private static final long serialVersionUID = 0L;
// Use NotificationChannelDescriptor.newBuilder() to construct.
private NotificationChannelDescriptor(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private NotificationChannelDescriptor() {
name_ = "";
type_ = "";
displayName_ = "";
description_ = "";
labels_ = java.util.Collections.emptyList();
supportedTiers_ = java.util.Collections.emptyList();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet getUnknownFields() {
return this.unknownFields;
}
private NotificationChannelDescriptor(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
java.lang.String s = input.readStringRequireUtf8();
type_ = s;
break;
}
case 18:
{
java.lang.String s = input.readStringRequireUtf8();
displayName_ = s;
break;
}
case 26:
{
java.lang.String s = input.readStringRequireUtf8();
description_ = s;
break;
}
case 34:
{
if (!((mutable_bitField0_ & 0x00000010) != 0)) {
labels_ = new java.util.ArrayList<com.google.api.LabelDescriptor>();
mutable_bitField0_ |= 0x00000010;
}
labels_.add(
input.readMessage(com.google.api.LabelDescriptor.parser(), extensionRegistry));
break;
}
case 40:
{
int rawValue = input.readEnum();
if (!((mutable_bitField0_ & 0x00000020) != 0)) {
supportedTiers_ = new java.util.ArrayList<java.lang.Integer>();
mutable_bitField0_ |= 0x00000020;
}
supportedTiers_.add(rawValue);
break;
}
case 42:
{
int length = input.readRawVarint32();
int oldLimit = input.pushLimit(length);
while (input.getBytesUntilLimit() > 0) {
int rawValue = input.readEnum();
if (!((mutable_bitField0_ & 0x00000020) != 0)) {
supportedTiers_ = new java.util.ArrayList<java.lang.Integer>();
mutable_bitField0_ |= 0x00000020;
}
supportedTiers_.add(rawValue);
}
input.popLimit(oldLimit);
break;
}
case 50:
{
java.lang.String s = input.readStringRequireUtf8();
name_ = s;
break;
}
default:
{
if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this);
} finally {
if (((mutable_bitField0_ & 0x00000010) != 0)) {
labels_ = java.util.Collections.unmodifiableList(labels_);
}
if (((mutable_bitField0_ & 0x00000020) != 0)) {
supportedTiers_ = java.util.Collections.unmodifiableList(supportedTiers_);
}
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.monitoring.v3.NotificationProto
.internal_static_google_monitoring_v3_NotificationChannelDescriptor_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.monitoring.v3.NotificationProto
.internal_static_google_monitoring_v3_NotificationChannelDescriptor_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.monitoring.v3.NotificationChannelDescriptor.class,
com.google.monitoring.v3.NotificationChannelDescriptor.Builder.class);
}
private int bitField0_;
public static final int NAME_FIELD_NUMBER = 6;
private volatile java.lang.Object name_;
/**
*
*
* <pre>
* The full REST resource name for this descriptor. The syntax is:
* projects/[PROJECT_ID]/notificationChannelDescriptors/[TYPE]
* In the above, `[TYPE]` is the value of the `type` field.
* </pre>
*
* <code>string name = 6;</code>
*/
public java.lang.String getName() {
java.lang.Object ref = name_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
name_ = s;
return s;
}
}
/**
*
*
* <pre>
* The full REST resource name for this descriptor. The syntax is:
* projects/[PROJECT_ID]/notificationChannelDescriptors/[TYPE]
* In the above, `[TYPE]` is the value of the `type` field.
* </pre>
*
* <code>string name = 6;</code>
*/
public com.google.protobuf.ByteString getNameBytes() {
java.lang.Object ref = name_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
name_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int TYPE_FIELD_NUMBER = 1;
private volatile java.lang.Object type_;
/**
*
*
* <pre>
* The type of notification channel, such as "email", "sms", etc.
* Notification channel types are globally unique.
* </pre>
*
* <code>string type = 1;</code>
*/
public java.lang.String getType() {
java.lang.Object ref = type_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
type_ = s;
return s;
}
}
/**
*
*
* <pre>
* The type of notification channel, such as "email", "sms", etc.
* Notification channel types are globally unique.
* </pre>
*
* <code>string type = 1;</code>
*/
public com.google.protobuf.ByteString getTypeBytes() {
java.lang.Object ref = type_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
type_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int DISPLAY_NAME_FIELD_NUMBER = 2;
private volatile java.lang.Object displayName_;
/**
*
*
* <pre>
* A human-readable name for the notification channel type. This
* form of the name is suitable for a user interface.
* </pre>
*
* <code>string display_name = 2;</code>
*/
public java.lang.String getDisplayName() {
java.lang.Object ref = displayName_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
displayName_ = s;
return s;
}
}
/**
*
*
* <pre>
* A human-readable name for the notification channel type. This
* form of the name is suitable for a user interface.
* </pre>
*
* <code>string display_name = 2;</code>
*/
public com.google.protobuf.ByteString getDisplayNameBytes() {
java.lang.Object ref = displayName_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
displayName_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int DESCRIPTION_FIELD_NUMBER = 3;
private volatile java.lang.Object description_;
/**
*
*
* <pre>
* A human-readable description of the notification channel
* type. The description may include a description of the properties
* of the channel and pointers to external documentation.
* </pre>
*
* <code>string description = 3;</code>
*/
public java.lang.String getDescription() {
java.lang.Object ref = description_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
description_ = s;
return s;
}
}
/**
*
*
* <pre>
* A human-readable description of the notification channel
* type. The description may include a description of the properties
* of the channel and pointers to external documentation.
* </pre>
*
* <code>string description = 3;</code>
*/
public com.google.protobuf.ByteString getDescriptionBytes() {
java.lang.Object ref = description_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
description_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int LABELS_FIELD_NUMBER = 4;
private java.util.List<com.google.api.LabelDescriptor> labels_;
/**
*
*
* <pre>
* The set of labels that must be defined to identify a particular
* channel of the corresponding type. Each label includes a
* description for how that field should be populated.
* </pre>
*
* <code>repeated .google.api.LabelDescriptor labels = 4;</code>
*/
public java.util.List<com.google.api.LabelDescriptor> getLabelsList() {
return labels_;
}
/**
*
*
* <pre>
* The set of labels that must be defined to identify a particular
* channel of the corresponding type. Each label includes a
* description for how that field should be populated.
* </pre>
*
* <code>repeated .google.api.LabelDescriptor labels = 4;</code>
*/
public java.util.List<? extends com.google.api.LabelDescriptorOrBuilder>
getLabelsOrBuilderList() {
return labels_;
}
/**
*
*
* <pre>
* The set of labels that must be defined to identify a particular
* channel of the corresponding type. Each label includes a
* description for how that field should be populated.
* </pre>
*
* <code>repeated .google.api.LabelDescriptor labels = 4;</code>
*/
public int getLabelsCount() {
return labels_.size();
}
/**
*
*
* <pre>
* The set of labels that must be defined to identify a particular
* channel of the corresponding type. Each label includes a
* description for how that field should be populated.
* </pre>
*
* <code>repeated .google.api.LabelDescriptor labels = 4;</code>
*/
public com.google.api.LabelDescriptor getLabels(int index) {
return labels_.get(index);
}
/**
*
*
* <pre>
* The set of labels that must be defined to identify a particular
* channel of the corresponding type. Each label includes a
* description for how that field should be populated.
* </pre>
*
* <code>repeated .google.api.LabelDescriptor labels = 4;</code>
*/
public com.google.api.LabelDescriptorOrBuilder getLabelsOrBuilder(int index) {
return labels_.get(index);
}
public static final int SUPPORTED_TIERS_FIELD_NUMBER = 5;
private java.util.List<java.lang.Integer> supportedTiers_;
private static final com.google.protobuf.Internal.ListAdapter.Converter<
java.lang.Integer, com.google.monitoring.v3.ServiceTier>
supportedTiers_converter_ =
new com.google.protobuf.Internal.ListAdapter.Converter<
java.lang.Integer, com.google.monitoring.v3.ServiceTier>() {
public com.google.monitoring.v3.ServiceTier convert(java.lang.Integer from) {
@SuppressWarnings("deprecation")
com.google.monitoring.v3.ServiceTier result =
com.google.monitoring.v3.ServiceTier.valueOf(from);
return result == null ? com.google.monitoring.v3.ServiceTier.UNRECOGNIZED : result;
}
};
/**
*
*
* <pre>
* The tiers that support this notification channel; the project service tier
* must be one of the supported_tiers.
* </pre>
*
* <code>repeated .google.monitoring.v3.ServiceTier supported_tiers = 5 [deprecated = true];
* </code>
*/
@java.lang.Deprecated
public java.util.List<com.google.monitoring.v3.ServiceTier> getSupportedTiersList() {
return new com.google.protobuf.Internal.ListAdapter<
java.lang.Integer, com.google.monitoring.v3.ServiceTier>(
supportedTiers_, supportedTiers_converter_);
}
/**
*
*
* <pre>
* The tiers that support this notification channel; the project service tier
* must be one of the supported_tiers.
* </pre>
*
* <code>repeated .google.monitoring.v3.ServiceTier supported_tiers = 5 [deprecated = true];
* </code>
*/
@java.lang.Deprecated
public int getSupportedTiersCount() {
return supportedTiers_.size();
}
/**
*
*
* <pre>
* The tiers that support this notification channel; the project service tier
* must be one of the supported_tiers.
* </pre>
*
* <code>repeated .google.monitoring.v3.ServiceTier supported_tiers = 5 [deprecated = true];
* </code>
*/
@java.lang.Deprecated
public com.google.monitoring.v3.ServiceTier getSupportedTiers(int index) {
return supportedTiers_converter_.convert(supportedTiers_.get(index));
}
/**
*
*
* <pre>
* The tiers that support this notification channel; the project service tier
* must be one of the supported_tiers.
* </pre>
*
* <code>repeated .google.monitoring.v3.ServiceTier supported_tiers = 5 [deprecated = true];
* </code>
*/
@java.lang.Deprecated
public java.util.List<java.lang.Integer> getSupportedTiersValueList() {
return supportedTiers_;
}
/**
*
*
* <pre>
* The tiers that support this notification channel; the project service tier
* must be one of the supported_tiers.
* </pre>
*
* <code>repeated .google.monitoring.v3.ServiceTier supported_tiers = 5 [deprecated = true];
* </code>
*/
@java.lang.Deprecated
public int getSupportedTiersValue(int index) {
return supportedTiers_.get(index);
}
private int supportedTiersMemoizedSerializedSize;
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
getSerializedSize();
if (!getTypeBytes().isEmpty()) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, type_);
}
if (!getDisplayNameBytes().isEmpty()) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, displayName_);
}
if (!getDescriptionBytes().isEmpty()) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 3, description_);
}
for (int i = 0; i < labels_.size(); i++) {
output.writeMessage(4, labels_.get(i));
}
if (getSupportedTiersList().size() > 0) {
output.writeUInt32NoTag(42);
output.writeUInt32NoTag(supportedTiersMemoizedSerializedSize);
}
for (int i = 0; i < supportedTiers_.size(); i++) {
output.writeEnumNoTag(supportedTiers_.get(i));
}
if (!getNameBytes().isEmpty()) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 6, name_);
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!getTypeBytes().isEmpty()) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, type_);
}
if (!getDisplayNameBytes().isEmpty()) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, displayName_);
}
if (!getDescriptionBytes().isEmpty()) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, description_);
}
for (int i = 0; i < labels_.size(); i++) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(4, labels_.get(i));
}
{
int dataSize = 0;
for (int i = 0; i < supportedTiers_.size(); i++) {
dataSize +=
com.google.protobuf.CodedOutputStream.computeEnumSizeNoTag(supportedTiers_.get(i));
}
size += dataSize;
if (!getSupportedTiersList().isEmpty()) {
size += 1;
size += com.google.protobuf.CodedOutputStream.computeUInt32SizeNoTag(dataSize);
}
supportedTiersMemoizedSerializedSize = dataSize;
}
if (!getNameBytes().isEmpty()) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(6, name_);
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.monitoring.v3.NotificationChannelDescriptor)) {
return super.equals(obj);
}
com.google.monitoring.v3.NotificationChannelDescriptor other =
(com.google.monitoring.v3.NotificationChannelDescriptor) obj;
if (!getName().equals(other.getName())) return false;
if (!getType().equals(other.getType())) return false;
if (!getDisplayName().equals(other.getDisplayName())) return false;
if (!getDescription().equals(other.getDescription())) return false;
if (!getLabelsList().equals(other.getLabelsList())) return false;
if (!supportedTiers_.equals(other.supportedTiers_)) return false;
if (!unknownFields.equals(other.unknownFields)) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + NAME_FIELD_NUMBER;
hash = (53 * hash) + getName().hashCode();
hash = (37 * hash) + TYPE_FIELD_NUMBER;
hash = (53 * hash) + getType().hashCode();
hash = (37 * hash) + DISPLAY_NAME_FIELD_NUMBER;
hash = (53 * hash) + getDisplayName().hashCode();
hash = (37 * hash) + DESCRIPTION_FIELD_NUMBER;
hash = (53 * hash) + getDescription().hashCode();
if (getLabelsCount() > 0) {
hash = (37 * hash) + LABELS_FIELD_NUMBER;
hash = (53 * hash) + getLabelsList().hashCode();
}
if (getSupportedTiersCount() > 0) {
hash = (37 * hash) + SUPPORTED_TIERS_FIELD_NUMBER;
hash = (53 * hash) + supportedTiers_.hashCode();
}
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.monitoring.v3.NotificationChannelDescriptor parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.monitoring.v3.NotificationChannelDescriptor parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.monitoring.v3.NotificationChannelDescriptor parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.monitoring.v3.NotificationChannelDescriptor parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.monitoring.v3.NotificationChannelDescriptor parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.monitoring.v3.NotificationChannelDescriptor parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.monitoring.v3.NotificationChannelDescriptor parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.monitoring.v3.NotificationChannelDescriptor parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.monitoring.v3.NotificationChannelDescriptor parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.monitoring.v3.NotificationChannelDescriptor parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.monitoring.v3.NotificationChannelDescriptor parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.monitoring.v3.NotificationChannelDescriptor parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.monitoring.v3.NotificationChannelDescriptor prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* A description of a notification channel. The descriptor includes
* the properties of the channel and the set of labels or fields that
* must be specified to configure channels of a given type.
* </pre>
*
* Protobuf type {@code google.monitoring.v3.NotificationChannelDescriptor}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.monitoring.v3.NotificationChannelDescriptor)
com.google.monitoring.v3.NotificationChannelDescriptorOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.monitoring.v3.NotificationProto
.internal_static_google_monitoring_v3_NotificationChannelDescriptor_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.monitoring.v3.NotificationProto
.internal_static_google_monitoring_v3_NotificationChannelDescriptor_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.monitoring.v3.NotificationChannelDescriptor.class,
com.google.monitoring.v3.NotificationChannelDescriptor.Builder.class);
}
// Construct using com.google.monitoring.v3.NotificationChannelDescriptor.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getLabelsFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
name_ = "";
type_ = "";
displayName_ = "";
description_ = "";
if (labelsBuilder_ == null) {
labels_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000010);
} else {
labelsBuilder_.clear();
}
supportedTiers_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000020);
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.monitoring.v3.NotificationProto
.internal_static_google_monitoring_v3_NotificationChannelDescriptor_descriptor;
}
@java.lang.Override
public com.google.monitoring.v3.NotificationChannelDescriptor getDefaultInstanceForType() {
return com.google.monitoring.v3.NotificationChannelDescriptor.getDefaultInstance();
}
@java.lang.Override
public com.google.monitoring.v3.NotificationChannelDescriptor build() {
com.google.monitoring.v3.NotificationChannelDescriptor result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.monitoring.v3.NotificationChannelDescriptor buildPartial() {
com.google.monitoring.v3.NotificationChannelDescriptor result =
new com.google.monitoring.v3.NotificationChannelDescriptor(this);
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
result.name_ = name_;
result.type_ = type_;
result.displayName_ = displayName_;
result.description_ = description_;
if (labelsBuilder_ == null) {
if (((bitField0_ & 0x00000010) != 0)) {
labels_ = java.util.Collections.unmodifiableList(labels_);
bitField0_ = (bitField0_ & ~0x00000010);
}
result.labels_ = labels_;
} else {
result.labels_ = labelsBuilder_.build();
}
if (((bitField0_ & 0x00000020) != 0)) {
supportedTiers_ = java.util.Collections.unmodifiableList(supportedTiers_);
bitField0_ = (bitField0_ & ~0x00000020);
}
result.supportedTiers_ = supportedTiers_;
result.bitField0_ = to_bitField0_;
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.monitoring.v3.NotificationChannelDescriptor) {
return mergeFrom((com.google.monitoring.v3.NotificationChannelDescriptor) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.monitoring.v3.NotificationChannelDescriptor other) {
if (other == com.google.monitoring.v3.NotificationChannelDescriptor.getDefaultInstance())
return this;
if (!other.getName().isEmpty()) {
name_ = other.name_;
onChanged();
}
if (!other.getType().isEmpty()) {
type_ = other.type_;
onChanged();
}
if (!other.getDisplayName().isEmpty()) {
displayName_ = other.displayName_;
onChanged();
}
if (!other.getDescription().isEmpty()) {
description_ = other.description_;
onChanged();
}
if (labelsBuilder_ == null) {
if (!other.labels_.isEmpty()) {
if (labels_.isEmpty()) {
labels_ = other.labels_;
bitField0_ = (bitField0_ & ~0x00000010);
} else {
ensureLabelsIsMutable();
labels_.addAll(other.labels_);
}
onChanged();
}
} else {
if (!other.labels_.isEmpty()) {
if (labelsBuilder_.isEmpty()) {
labelsBuilder_.dispose();
labelsBuilder_ = null;
labels_ = other.labels_;
bitField0_ = (bitField0_ & ~0x00000010);
labelsBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getLabelsFieldBuilder()
: null;
} else {
labelsBuilder_.addAllMessages(other.labels_);
}
}
}
if (!other.supportedTiers_.isEmpty()) {
if (supportedTiers_.isEmpty()) {
supportedTiers_ = other.supportedTiers_;
bitField0_ = (bitField0_ & ~0x00000020);
} else {
ensureSupportedTiersIsMutable();
supportedTiers_.addAll(other.supportedTiers_);
}
onChanged();
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.monitoring.v3.NotificationChannelDescriptor parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage =
(com.google.monitoring.v3.NotificationChannelDescriptor) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int bitField0_;
private java.lang.Object name_ = "";
/**
*
*
* <pre>
* The full REST resource name for this descriptor. The syntax is:
* projects/[PROJECT_ID]/notificationChannelDescriptors/[TYPE]
* In the above, `[TYPE]` is the value of the `type` field.
* </pre>
*
* <code>string name = 6;</code>
*/
public java.lang.String getName() {
java.lang.Object ref = name_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
name_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* The full REST resource name for this descriptor. The syntax is:
* projects/[PROJECT_ID]/notificationChannelDescriptors/[TYPE]
* In the above, `[TYPE]` is the value of the `type` field.
* </pre>
*
* <code>string name = 6;</code>
*/
public com.google.protobuf.ByteString getNameBytes() {
java.lang.Object ref = name_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
name_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* The full REST resource name for this descriptor. The syntax is:
* projects/[PROJECT_ID]/notificationChannelDescriptors/[TYPE]
* In the above, `[TYPE]` is the value of the `type` field.
* </pre>
*
* <code>string name = 6;</code>
*/
public Builder setName(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
name_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* The full REST resource name for this descriptor. The syntax is:
* projects/[PROJECT_ID]/notificationChannelDescriptors/[TYPE]
* In the above, `[TYPE]` is the value of the `type` field.
* </pre>
*
* <code>string name = 6;</code>
*/
public Builder clearName() {
name_ = getDefaultInstance().getName();
onChanged();
return this;
}
/**
*
*
* <pre>
* The full REST resource name for this descriptor. The syntax is:
* projects/[PROJECT_ID]/notificationChannelDescriptors/[TYPE]
* In the above, `[TYPE]` is the value of the `type` field.
* </pre>
*
* <code>string name = 6;</code>
*/
public Builder setNameBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
name_ = value;
onChanged();
return this;
}
private java.lang.Object type_ = "";
/**
*
*
* <pre>
* The type of notification channel, such as "email", "sms", etc.
* Notification channel types are globally unique.
* </pre>
*
* <code>string type = 1;</code>
*/
public java.lang.String getType() {
java.lang.Object ref = type_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
type_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* The type of notification channel, such as "email", "sms", etc.
* Notification channel types are globally unique.
* </pre>
*
* <code>string type = 1;</code>
*/
public com.google.protobuf.ByteString getTypeBytes() {
java.lang.Object ref = type_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
type_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* The type of notification channel, such as "email", "sms", etc.
* Notification channel types are globally unique.
* </pre>
*
* <code>string type = 1;</code>
*/
public Builder setType(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
type_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* The type of notification channel, such as "email", "sms", etc.
* Notification channel types are globally unique.
* </pre>
*
* <code>string type = 1;</code>
*/
public Builder clearType() {
type_ = getDefaultInstance().getType();
onChanged();
return this;
}
/**
*
*
* <pre>
* The type of notification channel, such as "email", "sms", etc.
* Notification channel types are globally unique.
* </pre>
*
* <code>string type = 1;</code>
*/
public Builder setTypeBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
type_ = value;
onChanged();
return this;
}
private java.lang.Object displayName_ = "";
/**
*
*
* <pre>
* A human-readable name for the notification channel type. This
* form of the name is suitable for a user interface.
* </pre>
*
* <code>string display_name = 2;</code>
*/
public java.lang.String getDisplayName() {
java.lang.Object ref = displayName_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
displayName_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* A human-readable name for the notification channel type. This
* form of the name is suitable for a user interface.
* </pre>
*
* <code>string display_name = 2;</code>
*/
public com.google.protobuf.ByteString getDisplayNameBytes() {
java.lang.Object ref = displayName_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
displayName_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* A human-readable name for the notification channel type. This
* form of the name is suitable for a user interface.
* </pre>
*
* <code>string display_name = 2;</code>
*/
public Builder setDisplayName(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
displayName_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* A human-readable name for the notification channel type. This
* form of the name is suitable for a user interface.
* </pre>
*
* <code>string display_name = 2;</code>
*/
public Builder clearDisplayName() {
displayName_ = getDefaultInstance().getDisplayName();
onChanged();
return this;
}
/**
*
*
* <pre>
* A human-readable name for the notification channel type. This
* form of the name is suitable for a user interface.
* </pre>
*
* <code>string display_name = 2;</code>
*/
public Builder setDisplayNameBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
displayName_ = value;
onChanged();
return this;
}
private java.lang.Object description_ = "";
/**
*
*
* <pre>
* A human-readable description of the notification channel
* type. The description may include a description of the properties
* of the channel and pointers to external documentation.
* </pre>
*
* <code>string description = 3;</code>
*/
public java.lang.String getDescription() {
java.lang.Object ref = description_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
description_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* A human-readable description of the notification channel
* type. The description may include a description of the properties
* of the channel and pointers to external documentation.
* </pre>
*
* <code>string description = 3;</code>
*/
public com.google.protobuf.ByteString getDescriptionBytes() {
java.lang.Object ref = description_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
description_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* A human-readable description of the notification channel
* type. The description may include a description of the properties
* of the channel and pointers to external documentation.
* </pre>
*
* <code>string description = 3;</code>
*/
public Builder setDescription(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
description_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* A human-readable description of the notification channel
* type. The description may include a description of the properties
* of the channel and pointers to external documentation.
* </pre>
*
* <code>string description = 3;</code>
*/
public Builder clearDescription() {
description_ = getDefaultInstance().getDescription();
onChanged();
return this;
}
/**
*
*
* <pre>
* A human-readable description of the notification channel
* type. The description may include a description of the properties
* of the channel and pointers to external documentation.
* </pre>
*
* <code>string description = 3;</code>
*/
public Builder setDescriptionBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
description_ = value;
onChanged();
return this;
}
private java.util.List<com.google.api.LabelDescriptor> labels_ =
java.util.Collections.emptyList();
private void ensureLabelsIsMutable() {
if (!((bitField0_ & 0x00000010) != 0)) {
labels_ = new java.util.ArrayList<com.google.api.LabelDescriptor>(labels_);
bitField0_ |= 0x00000010;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.api.LabelDescriptor,
com.google.api.LabelDescriptor.Builder,
com.google.api.LabelDescriptorOrBuilder>
labelsBuilder_;
/**
*
*
* <pre>
* The set of labels that must be defined to identify a particular
* channel of the corresponding type. Each label includes a
* description for how that field should be populated.
* </pre>
*
* <code>repeated .google.api.LabelDescriptor labels = 4;</code>
*/
public java.util.List<com.google.api.LabelDescriptor> getLabelsList() {
if (labelsBuilder_ == null) {
return java.util.Collections.unmodifiableList(labels_);
} else {
return labelsBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* The set of labels that must be defined to identify a particular
* channel of the corresponding type. Each label includes a
* description for how that field should be populated.
* </pre>
*
* <code>repeated .google.api.LabelDescriptor labels = 4;</code>
*/
public int getLabelsCount() {
if (labelsBuilder_ == null) {
return labels_.size();
} else {
return labelsBuilder_.getCount();
}
}
/**
*
*
* <pre>
* The set of labels that must be defined to identify a particular
* channel of the corresponding type. Each label includes a
* description for how that field should be populated.
* </pre>
*
* <code>repeated .google.api.LabelDescriptor labels = 4;</code>
*/
public com.google.api.LabelDescriptor getLabels(int index) {
if (labelsBuilder_ == null) {
return labels_.get(index);
} else {
return labelsBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* The set of labels that must be defined to identify a particular
* channel of the corresponding type. Each label includes a
* description for how that field should be populated.
* </pre>
*
* <code>repeated .google.api.LabelDescriptor labels = 4;</code>
*/
public Builder setLabels(int index, com.google.api.LabelDescriptor value) {
if (labelsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureLabelsIsMutable();
labels_.set(index, value);
onChanged();
} else {
labelsBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The set of labels that must be defined to identify a particular
* channel of the corresponding type. Each label includes a
* description for how that field should be populated.
* </pre>
*
* <code>repeated .google.api.LabelDescriptor labels = 4;</code>
*/
public Builder setLabels(int index, com.google.api.LabelDescriptor.Builder builderForValue) {
if (labelsBuilder_ == null) {
ensureLabelsIsMutable();
labels_.set(index, builderForValue.build());
onChanged();
} else {
labelsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The set of labels that must be defined to identify a particular
* channel of the corresponding type. Each label includes a
* description for how that field should be populated.
* </pre>
*
* <code>repeated .google.api.LabelDescriptor labels = 4;</code>
*/
public Builder addLabels(com.google.api.LabelDescriptor value) {
if (labelsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureLabelsIsMutable();
labels_.add(value);
onChanged();
} else {
labelsBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* The set of labels that must be defined to identify a particular
* channel of the corresponding type. Each label includes a
* description for how that field should be populated.
* </pre>
*
* <code>repeated .google.api.LabelDescriptor labels = 4;</code>
*/
public Builder addLabels(int index, com.google.api.LabelDescriptor value) {
if (labelsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureLabelsIsMutable();
labels_.add(index, value);
onChanged();
} else {
labelsBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* The set of labels that must be defined to identify a particular
* channel of the corresponding type. Each label includes a
* description for how that field should be populated.
* </pre>
*
* <code>repeated .google.api.LabelDescriptor labels = 4;</code>
*/
public Builder addLabels(com.google.api.LabelDescriptor.Builder builderForValue) {
if (labelsBuilder_ == null) {
ensureLabelsIsMutable();
labels_.add(builderForValue.build());
onChanged();
} else {
labelsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The set of labels that must be defined to identify a particular
* channel of the corresponding type. Each label includes a
* description for how that field should be populated.
* </pre>
*
* <code>repeated .google.api.LabelDescriptor labels = 4;</code>
*/
public Builder addLabels(int index, com.google.api.LabelDescriptor.Builder builderForValue) {
if (labelsBuilder_ == null) {
ensureLabelsIsMutable();
labels_.add(index, builderForValue.build());
onChanged();
} else {
labelsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* The set of labels that must be defined to identify a particular
* channel of the corresponding type. Each label includes a
* description for how that field should be populated.
* </pre>
*
* <code>repeated .google.api.LabelDescriptor labels = 4;</code>
*/
public Builder addAllLabels(
java.lang.Iterable<? extends com.google.api.LabelDescriptor> values) {
if (labelsBuilder_ == null) {
ensureLabelsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, labels_);
onChanged();
} else {
labelsBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* The set of labels that must be defined to identify a particular
* channel of the corresponding type. Each label includes a
* description for how that field should be populated.
* </pre>
*
* <code>repeated .google.api.LabelDescriptor labels = 4;</code>
*/
public Builder clearLabels() {
if (labelsBuilder_ == null) {
labels_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000010);
onChanged();
} else {
labelsBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* The set of labels that must be defined to identify a particular
* channel of the corresponding type. Each label includes a
* description for how that field should be populated.
* </pre>
*
* <code>repeated .google.api.LabelDescriptor labels = 4;</code>
*/
public Builder removeLabels(int index) {
if (labelsBuilder_ == null) {
ensureLabelsIsMutable();
labels_.remove(index);
onChanged();
} else {
labelsBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* The set of labels that must be defined to identify a particular
* channel of the corresponding type. Each label includes a
* description for how that field should be populated.
* </pre>
*
* <code>repeated .google.api.LabelDescriptor labels = 4;</code>
*/
public com.google.api.LabelDescriptor.Builder getLabelsBuilder(int index) {
return getLabelsFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* The set of labels that must be defined to identify a particular
* channel of the corresponding type. Each label includes a
* description for how that field should be populated.
* </pre>
*
* <code>repeated .google.api.LabelDescriptor labels = 4;</code>
*/
public com.google.api.LabelDescriptorOrBuilder getLabelsOrBuilder(int index) {
if (labelsBuilder_ == null) {
return labels_.get(index);
} else {
return labelsBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* The set of labels that must be defined to identify a particular
* channel of the corresponding type. Each label includes a
* description for how that field should be populated.
* </pre>
*
* <code>repeated .google.api.LabelDescriptor labels = 4;</code>
*/
public java.util.List<? extends com.google.api.LabelDescriptorOrBuilder>
getLabelsOrBuilderList() {
if (labelsBuilder_ != null) {
return labelsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(labels_);
}
}
/**
*
*
* <pre>
* The set of labels that must be defined to identify a particular
* channel of the corresponding type. Each label includes a
* description for how that field should be populated.
* </pre>
*
* <code>repeated .google.api.LabelDescriptor labels = 4;</code>
*/
public com.google.api.LabelDescriptor.Builder addLabelsBuilder() {
return getLabelsFieldBuilder()
.addBuilder(com.google.api.LabelDescriptor.getDefaultInstance());
}
/**
*
*
* <pre>
* The set of labels that must be defined to identify a particular
* channel of the corresponding type. Each label includes a
* description for how that field should be populated.
* </pre>
*
* <code>repeated .google.api.LabelDescriptor labels = 4;</code>
*/
public com.google.api.LabelDescriptor.Builder addLabelsBuilder(int index) {
return getLabelsFieldBuilder()
.addBuilder(index, com.google.api.LabelDescriptor.getDefaultInstance());
}
/**
*
*
* <pre>
* The set of labels that must be defined to identify a particular
* channel of the corresponding type. Each label includes a
* description for how that field should be populated.
* </pre>
*
* <code>repeated .google.api.LabelDescriptor labels = 4;</code>
*/
public java.util.List<com.google.api.LabelDescriptor.Builder> getLabelsBuilderList() {
return getLabelsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.api.LabelDescriptor,
com.google.api.LabelDescriptor.Builder,
com.google.api.LabelDescriptorOrBuilder>
getLabelsFieldBuilder() {
if (labelsBuilder_ == null) {
labelsBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.api.LabelDescriptor,
com.google.api.LabelDescriptor.Builder,
com.google.api.LabelDescriptorOrBuilder>(
labels_, ((bitField0_ & 0x00000010) != 0), getParentForChildren(), isClean());
labels_ = null;
}
return labelsBuilder_;
}
private java.util.List<java.lang.Integer> supportedTiers_ = java.util.Collections.emptyList();
private void ensureSupportedTiersIsMutable() {
if (!((bitField0_ & 0x00000020) != 0)) {
supportedTiers_ = new java.util.ArrayList<java.lang.Integer>(supportedTiers_);
bitField0_ |= 0x00000020;
}
}
/**
*
*
* <pre>
* The tiers that support this notification channel; the project service tier
* must be one of the supported_tiers.
* </pre>
*
* <code>repeated .google.monitoring.v3.ServiceTier supported_tiers = 5 [deprecated = true];
* </code>
*/
@java.lang.Deprecated
public java.util.List<com.google.monitoring.v3.ServiceTier> getSupportedTiersList() {
return new com.google.protobuf.Internal.ListAdapter<
java.lang.Integer, com.google.monitoring.v3.ServiceTier>(
supportedTiers_, supportedTiers_converter_);
}
/**
*
*
* <pre>
* The tiers that support this notification channel; the project service tier
* must be one of the supported_tiers.
* </pre>
*
* <code>repeated .google.monitoring.v3.ServiceTier supported_tiers = 5 [deprecated = true];
* </code>
*/
@java.lang.Deprecated
public int getSupportedTiersCount() {
return supportedTiers_.size();
}
/**
*
*
* <pre>
* The tiers that support this notification channel; the project service tier
* must be one of the supported_tiers.
* </pre>
*
* <code>repeated .google.monitoring.v3.ServiceTier supported_tiers = 5 [deprecated = true];
* </code>
*/
@java.lang.Deprecated
public com.google.monitoring.v3.ServiceTier getSupportedTiers(int index) {
return supportedTiers_converter_.convert(supportedTiers_.get(index));
}
/**
*
*
* <pre>
* The tiers that support this notification channel; the project service tier
* must be one of the supported_tiers.
* </pre>
*
* <code>repeated .google.monitoring.v3.ServiceTier supported_tiers = 5 [deprecated = true];
* </code>
*/
@java.lang.Deprecated
public Builder setSupportedTiers(int index, com.google.monitoring.v3.ServiceTier value) {
if (value == null) {
throw new NullPointerException();
}
ensureSupportedTiersIsMutable();
supportedTiers_.set(index, value.getNumber());
onChanged();
return this;
}
/**
*
*
* <pre>
* The tiers that support this notification channel; the project service tier
* must be one of the supported_tiers.
* </pre>
*
* <code>repeated .google.monitoring.v3.ServiceTier supported_tiers = 5 [deprecated = true];
* </code>
*/
@java.lang.Deprecated
public Builder addSupportedTiers(com.google.monitoring.v3.ServiceTier value) {
if (value == null) {
throw new NullPointerException();
}
ensureSupportedTiersIsMutable();
supportedTiers_.add(value.getNumber());
onChanged();
return this;
}
/**
*
*
* <pre>
* The tiers that support this notification channel; the project service tier
* must be one of the supported_tiers.
* </pre>
*
* <code>repeated .google.monitoring.v3.ServiceTier supported_tiers = 5 [deprecated = true];
* </code>
*/
@java.lang.Deprecated
public Builder addAllSupportedTiers(
java.lang.Iterable<? extends com.google.monitoring.v3.ServiceTier> values) {
ensureSupportedTiersIsMutable();
for (com.google.monitoring.v3.ServiceTier value : values) {
supportedTiers_.add(value.getNumber());
}
onChanged();
return this;
}
/**
*
*
* <pre>
* The tiers that support this notification channel; the project service tier
* must be one of the supported_tiers.
* </pre>
*
* <code>repeated .google.monitoring.v3.ServiceTier supported_tiers = 5 [deprecated = true];
* </code>
*/
@java.lang.Deprecated
public Builder clearSupportedTiers() {
supportedTiers_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000020);
onChanged();
return this;
}
/**
*
*
* <pre>
* The tiers that support this notification channel; the project service tier
* must be one of the supported_tiers.
* </pre>
*
* <code>repeated .google.monitoring.v3.ServiceTier supported_tiers = 5 [deprecated = true];
* </code>
*/
@java.lang.Deprecated
public java.util.List<java.lang.Integer> getSupportedTiersValueList() {
return java.util.Collections.unmodifiableList(supportedTiers_);
}
/**
*
*
* <pre>
* The tiers that support this notification channel; the project service tier
* must be one of the supported_tiers.
* </pre>
*
* <code>repeated .google.monitoring.v3.ServiceTier supported_tiers = 5 [deprecated = true];
* </code>
*/
@java.lang.Deprecated
public int getSupportedTiersValue(int index) {
return supportedTiers_.get(index);
}
/**
*
*
* <pre>
* The tiers that support this notification channel; the project service tier
* must be one of the supported_tiers.
* </pre>
*
* <code>repeated .google.monitoring.v3.ServiceTier supported_tiers = 5 [deprecated = true];
* </code>
*/
@java.lang.Deprecated
public Builder setSupportedTiersValue(int index, int value) {
ensureSupportedTiersIsMutable();
supportedTiers_.set(index, value);
onChanged();
return this;
}
/**
*
*
* <pre>
* The tiers that support this notification channel; the project service tier
* must be one of the supported_tiers.
* </pre>
*
* <code>repeated .google.monitoring.v3.ServiceTier supported_tiers = 5 [deprecated = true];
* </code>
*/
@java.lang.Deprecated
public Builder addSupportedTiersValue(int value) {
ensureSupportedTiersIsMutable();
supportedTiers_.add(value);
onChanged();
return this;
}
/**
*
*
* <pre>
* The tiers that support this notification channel; the project service tier
* must be one of the supported_tiers.
* </pre>
*
* <code>repeated .google.monitoring.v3.ServiceTier supported_tiers = 5 [deprecated = true];
* </code>
*/
@java.lang.Deprecated
public Builder addAllSupportedTiersValue(java.lang.Iterable<java.lang.Integer> values) {
ensureSupportedTiersIsMutable();
for (int value : values) {
supportedTiers_.add(value);
}
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.monitoring.v3.NotificationChannelDescriptor)
}
// @@protoc_insertion_point(class_scope:google.monitoring.v3.NotificationChannelDescriptor)
private static final com.google.monitoring.v3.NotificationChannelDescriptor DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.monitoring.v3.NotificationChannelDescriptor();
}
public static com.google.monitoring.v3.NotificationChannelDescriptor getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<NotificationChannelDescriptor> PARSER =
new com.google.protobuf.AbstractParser<NotificationChannelDescriptor>() {
@java.lang.Override
public NotificationChannelDescriptor parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new NotificationChannelDescriptor(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<NotificationChannelDescriptor> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<NotificationChannelDescriptor> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.monitoring.v3.NotificationChannelDescriptor getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
package com.avaje.tests.timezone;
import com.avaje.ebean.Ebean;
import com.avaje.ebean.Transaction;
import org.junit.Ignore;
import org.junit.Test;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.TimeZone;
/**
* Must run this manually with various JVM timezones for insert and fetch.
*/
public class TimezoneTests {
private final Timestamp nowTs = new Timestamp(1460000000000L);
public TimezoneTests() {
}
@Ignore
@Test
public void rawJdbc() throws SQLException {
// insert("Local");
// insert("UTC");
// insert("America/Los_Angeles");
// System.out.println("Local");
// fetch();
// System.out.println("UTC");
// setZone("UTC");
// fetch();
System.out.println("LA");
setZone("America/Los_Angeles");
fetch();
}
private void fetch() throws SQLException {
Transaction transaction = Ebean.beginTransaction();
Connection connection = transaction.getConnection();
PreparedStatement statement = connection.prepareStatement("select * from tztest");
ResultSet resultSet = statement.executeQuery();
while (resultSet.next()) {
System.out.println(" zone:"+resultSet.getString("zone"));
System.out.println(" ts:"+tsof(resultSet.getTimestamp("ts")));
System.out.println(" tstz:"+tsof(resultSet.getTimestamp("tstz")));
System.out.println(" ts1:"+tsof(resultSet.getTimestamp("ts1", cal())));
System.out.println("tstz1:"+tsof(resultSet.getTimestamp("tstz1", cal())));
}
System.out.println("");
resultSet.close();
statement.close();
transaction.end();
}
private String tsof(Timestamp timestamp) {
return ""+timestamp.getTime()+", "+timestamp.toString()+", "+timestamp.toInstant();
}
private void setZone(String zone) {
TimeZone.setDefault(TimeZone.getTimeZone(zone));
}
private void insert(String zone) throws SQLException {
String insert = "insert into tztest (zone, ts, tstz, ts1, tstz1) values (?,?,?,?,?)";
if (!zone.equalsIgnoreCase("local")) {
setZone(zone);
}
Transaction transaction = Ebean.beginTransaction();
Connection connection = transaction.getConnection();
PreparedStatement statement = connection.prepareStatement(insert);
statement.setString(1, zone);
statement.setTimestamp(2, nowTs);
statement.setTimestamp(3, nowTs);
statement.setTimestamp(4, nowTs, cal());
statement.setTimestamp(5, nowTs, cal());
statement.executeUpdate();
transaction.commit();
}
private Calendar cal() {
Calendar instance = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
//Calendar instance = Calendar.getInstance(TimeZone.getDefault());
return (Calendar) instance.clone();
}
}
|
package net.iponweb.disthene.reader.graphite.functions;
import net.iponweb.disthene.reader.beans.TimeSeries;
import net.iponweb.disthene.reader.exceptions.EvaluationException;
import net.iponweb.disthene.reader.exceptions.InvalidArgumentException;
import net.iponweb.disthene.reader.exceptions.TimeSeriesNotAlignedException;
import net.iponweb.disthene.reader.graphite.Target;
import net.iponweb.disthene.reader.graphite.evaluation.TargetEvaluator;
import net.iponweb.disthene.reader.utils.TimeSeriesUtils;
import java.util.ArrayList;
import java.util.List;
/**
* @author Andrei Ivanov
*/
public class InvertFunction extends DistheneFunction {
public InvertFunction(String text) {
super(text, "invert");
}
@Override
public List<TimeSeries> evaluate(TargetEvaluator evaluator) throws EvaluationException {
List<TimeSeries> processedArguments = new ArrayList<>(evaluator.eval((Target) arguments.get(0)));
if (processedArguments.size() == 0) return new ArrayList<>();
if (!TimeSeriesUtils.checkAlignment(processedArguments)) {
throw new TimeSeriesNotAlignedException();
}
int length = processedArguments.get(0).getValues().length;
for (TimeSeries ts : processedArguments) {
for (int i = 0; i < length; i++) {
if (ts.getValues()[i] != null) {
double y = Math.pow(ts.getValues()[i], -1);
ts.getValues()[i] = Double.isNaN(y) ? null : y;
}
}
setResultingName(ts);
}
return processedArguments;
}
@Override
public void checkArguments() throws InvalidArgumentException {
if (arguments.size() != 1) throw new InvalidArgumentException("invert: number of arguments is " + arguments.size() + ". Must be 1.");
if (!(arguments.get(0) instanceof Target)) throw new InvalidArgumentException("invert: argument is " + arguments.get(0).getClass().getName() + ". Must be series");
}
}
|
package spring.project.bot.service.handlers;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;
import spring.project.bot.model.DataMessage;
import java.util.List;
@Service
@AllArgsConstructor
public class MessageBotHandlerRunnerImpl implements MessageBotHandlerRunner {
private final List<MessageBotHandler> handlers;
@Override
@SneakyThrows
public void run(DataMessage dataMessage) {
for (var handler : handlers) {
if (!handler.next(dataMessage)) break;
}
}
}
|
/*
* Copyright (c) 2008-2019, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.jet.impl.connector;
import com.hazelcast.jet.JetException;
import com.hazelcast.jet.core.Inbox;
import com.hazelcast.jet.core.Outbox;
import com.hazelcast.jet.core.Processor;
import com.hazelcast.jet.core.Watermark;
import com.hazelcast.jet.core.processor.SinkProcessors;
import com.hazelcast.jet.function.FunctionEx;
import com.hazelcast.jet.function.BiConsumerEx;
import com.hazelcast.jet.function.ConsumerEx;
import com.hazelcast.jet.function.SupplierEx;
import javax.annotation.Nonnull;
import java.util.function.Consumer;
import static com.hazelcast.jet.impl.util.Util.checkSerializable;
public final class WriteBufferedP<B, T> implements Processor {
private final FunctionEx<? super Context, B> createFn;
private final ConsumerEx<? super B> flushFn;
private final ConsumerEx<? super B> destroyFn;
private B buffer;
private final Consumer<Object> inboxConsumer;
WriteBufferedP(
@Nonnull FunctionEx<? super Context, B> createFn,
@Nonnull BiConsumerEx<? super B, ? super T> onReceiveFn,
@Nonnull ConsumerEx<? super B> flushFn,
@Nonnull ConsumerEx<? super B> destroyFn
) {
this.createFn = createFn;
this.flushFn = flushFn;
this.destroyFn = destroyFn;
inboxConsumer = item -> onReceiveFn.accept(buffer, (T) item);
}
@Override
public void init(@Nonnull Outbox outbox, @Nonnull Context context) {
buffer = createFn.apply(context);
if (buffer == null) {
throw new JetException("Null buffer created");
}
}
@Override
public void process(int ordinal, @Nonnull Inbox inbox) {
inbox.drain(inboxConsumer);
flushFn.accept(buffer);
}
@Override
public boolean tryProcessWatermark(@Nonnull Watermark watermark) {
// we're a sink, no need to forward the watermarks
return true;
}
@Override
public boolean complete() {
return true;
}
@Override
public void close() {
if (buffer != null) {
destroyFn.accept(buffer);
}
}
@Override
public boolean isCooperative() {
return false;
}
/**
* This is private API. Call {@link SinkProcessors#writeBufferedP} instead.
*/
@Nonnull
public static <B, T> SupplierEx<Processor> supplier(
@Nonnull FunctionEx<? super Context, ? extends B> createFn,
@Nonnull BiConsumerEx<? super B, ? super T> onReceiveFn,
@Nonnull ConsumerEx<? super B> flushFn,
@Nonnull ConsumerEx<? super B> destroyFn
) {
checkSerializable(createFn, "createFn");
checkSerializable(onReceiveFn, "onReceiveFn");
checkSerializable(flushFn, "flushFn");
checkSerializable(destroyFn, "destroyFn");
return () -> new WriteBufferedP<>(createFn, onReceiveFn, flushFn, destroyFn);
}
}
|
package c1_4_thread.cn.enjoyedu.ch2;
import java.util.Random;
import java.util.concurrent.LinkedBlockingDeque;
/*工作密取*/
public class SecretWorkFetch {
private static class Work implements Runnable{
private static Object object=new Object();
private static int count=0;
public final int id;
private long putThread;
public Work(){
synchronized(object){
id=count++;
}
}
@Override
public void run() {
if(Thread.currentThread().getId()!=putThread){
System.out.println("===================================================");
}
System.out.println(Thread.currentThread().getId()+":"+putThread+"// finish job "+id);
}
public long getPutThread() {
return putThread;
}
public void setPutThread(long putThread) {
this.putThread = putThread;
}
}
public static Work generateWork(){
return new Work();
}
private static class ConsumerAndProducer implements Runnable{
private Random random=new Random();
private final LinkedBlockingDeque<Work> deque;
private final LinkedBlockingDeque<Work> otherWork;
public ConsumerAndProducer(LinkedBlockingDeque<Work> deque,LinkedBlockingDeque<Work> otherWork){
this.deque=deque;
this.otherWork=otherWork;
}
@Override
public void run() {
while(!Thread.interrupted()){
try {
Thread.sleep(200);
if(random.nextBoolean()){
int count=random.nextInt(5);
for(int i=0;i<count;i++){
Work w=generateWork();
w.setPutThread(Thread.currentThread().getId());
deque.putLast(w);
}
}
//System.out.println(" yss otherWork.isEmpty(): "+otherWork.isEmpty());
if(deque.isEmpty()){
if(!otherWork.isEmpty()){
System.out.println("otherWork is run:");
otherWork.takeLast().run();;
}
}else{
deque.takeFirst().run();
}
} catch (InterruptedException e) {
}
}
}
}
public static void main(String[] args) {
LinkedBlockingDeque<Work> deque=new LinkedBlockingDeque<Work>();
LinkedBlockingDeque<Work> other=new LinkedBlockingDeque<Work>();
new Thread(new ConsumerAndProducer(deque,other)).start();
new Thread(new ConsumerAndProducer(deque,other)).start();
new Thread(new ConsumerAndProducer(other,deque)).start();
new Thread(new ConsumerAndProducer(other,deque)).start();
}
}
|
package com.catalog.freezer.repository;
import java.util.Date;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.data.domain.Pageable;
import com.catalog.freezer.model.Food;
@Repository
public interface FoodRepository extends JpaRepository<Food, Long> {
public Page<Food> findByNameOrFoodType_NameOrCreatedAtBetweenAllIgnoreCase(
String name,
String foodTypeName,
Date createdAt,
Date createdAtEnd,
Pageable pageable);
@Query("Select f FROM Food f WHERE "
+ "( f.createdAt between coalesce(:createdAtStart, now()) and coalesce(:createdAtEnd, now()) ) "
+ "or LOWER(f.name) = LOWER(:name) "
+ "or LOWER(f.foodType.name) = LOWER(:foodTypeName) ")
public Page<Food> search(
@Param("name") String name,
@Param("foodTypeName") String FoodTypeName,
@Param("createdAtStart") Date createdAtStart,
@Param("createdAtEnd") Date createdAtEnd,
Pageable pageable);
}
|
package com.lilithsthrone.game.character.npc.misc;
import java.time.Month;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import com.lilithsthrone.game.Game;
import com.lilithsthrone.game.character.CharacterImportSetting;
import com.lilithsthrone.game.character.CharacterUtils;
import com.lilithsthrone.game.character.EquipClothingSetting;
import com.lilithsthrone.game.character.GameCharacter;
import com.lilithsthrone.game.character.attributes.Attribute;
import com.lilithsthrone.game.character.body.types.HornType;
import com.lilithsthrone.game.character.body.types.LegType;
import com.lilithsthrone.game.character.body.types.TailType;
import com.lilithsthrone.game.character.body.types.WingType;
import com.lilithsthrone.game.character.body.valueEnums.AreolaeSize;
import com.lilithsthrone.game.character.body.valueEnums.AssSize;
import com.lilithsthrone.game.character.body.valueEnums.BodyMaterial;
import com.lilithsthrone.game.character.body.valueEnums.BodySize;
import com.lilithsthrone.game.character.body.valueEnums.BreastShape;
import com.lilithsthrone.game.character.body.valueEnums.Capacity;
import com.lilithsthrone.game.character.body.valueEnums.ClitorisSize;
import com.lilithsthrone.game.character.body.valueEnums.CupSize;
import com.lilithsthrone.game.character.body.valueEnums.HipSize;
import com.lilithsthrone.game.character.body.valueEnums.LabiaSize;
import com.lilithsthrone.game.character.body.valueEnums.LipSize;
import com.lilithsthrone.game.character.body.valueEnums.Muscle;
import com.lilithsthrone.game.character.body.valueEnums.NippleSize;
import com.lilithsthrone.game.character.body.valueEnums.OrificeElasticity;
import com.lilithsthrone.game.character.body.valueEnums.OrificePlasticity;
import com.lilithsthrone.game.character.body.valueEnums.TongueLength;
import com.lilithsthrone.game.character.body.valueEnums.Wetness;
import com.lilithsthrone.game.character.body.valueEnums.WingSize;
import com.lilithsthrone.game.character.effects.AbstractPerk;
import com.lilithsthrone.game.character.fetishes.Fetish;
import com.lilithsthrone.game.character.gender.Gender;
import com.lilithsthrone.game.character.npc.NPC;
import com.lilithsthrone.game.character.persona.Name;
import com.lilithsthrone.game.character.persona.Occupation;
import com.lilithsthrone.game.character.persona.SexualOrientation;
import com.lilithsthrone.game.character.race.Race;
import com.lilithsthrone.game.character.race.RaceStage;
import com.lilithsthrone.game.character.race.Subspecies;
import com.lilithsthrone.game.combat.SpellSchool;
import com.lilithsthrone.game.dialogue.DialogueNode;
import com.lilithsthrone.game.dialogue.utils.UtilText;
import com.lilithsthrone.game.inventory.CharacterInventory;
import com.lilithsthrone.game.sex.PregnancyDescriptor;
import com.lilithsthrone.main.Main;
import com.lilithsthrone.world.WorldType;
import com.lilithsthrone.world.places.PlaceType;
/**
* @since 0.2.4
* @version 0.3.4
* @author Innoxia
*/
public class Elemental extends NPC {
private String summonerID;
public Elemental(boolean isImported) {
this(Gender.F_V_B_FEMALE, null, isImported);
}
public Elemental(Gender gender, GameCharacter summoner, boolean isImported) {
super(isImported, null, null, "", summoner==null?18:summoner.getAgeValue(), summoner==null?Month.JANUARY:summoner.getBirthMonth(), summoner==null?1:summoner.getDayOfBirth(), 20, gender, Subspecies.DEMON, RaceStage.GREATER,
new CharacterInventory(10), WorldType.EMPTY, PlaceType.GENERIC_EMPTY_TILE, false);
if(!isImported) {
this.setLocation(summoner, false);
setLevel(summoner.getLevel());
this.setSummoner(summoner);
this.setStartingBody(true);
this.setLegType(LegType.DEMON_COMMON);
this.setHistory(Occupation.ELEMENTAL_ARCANE);
// RACE & NAME:
setSexualOrientation(SexualOrientation.AMBIPHILIC);
setName(Name.getRandomTriplet(Race.DEMON));
this.setPlayerKnowsName(true);
// INVENTORY:
resetInventory(true);
this.addFetish(Fetish.FETISH_EXHIBITIONIST);
this.setAttribute(Attribute.MAJOR_PHYSIQUE, 0);
this.setAttribute(Attribute.MAJOR_ARCANE, 0);
this.setAttribute(Attribute.MAJOR_CORRUPTION, 0);
initHealthAndManaToMax();
}
}
@Override
public Element saveAsXML(Element parentElement, Document doc) {
Element properties = super.saveAsXML(parentElement, doc);
Element npcSpecific = doc.createElement("elementalSpecial");
properties.appendChild(npcSpecific);
CharacterUtils.createXMLElementWithValue(doc, npcSpecific, "summoner", this.getSummoner().getId());
return properties;
}
@Override
public void loadFromXML(Element parentElement, Document doc, CharacterImportSetting... settings) {
loadNPCVariablesFromXML(this, null, parentElement, doc, settings);
Element npcSpecificElement = (Element) parentElement.getElementsByTagName("elementalSpecial").item(0);
this.setSummoner(((Element)npcSpecificElement.getElementsByTagName("summoner").item(0)).getAttribute("value"));
if(Main.isVersionOlderThan(Game.loadingVersion, "0.2.11.6")) {
this.setAttribute(Attribute.MAJOR_PHYSIQUE, 0);
this.setAttribute(Attribute.MAJOR_ARCANE, 0);
this.setAttribute(Attribute.MAJOR_CORRUPTION, 0);
this.resetPerksMap(true);
}
if(Main.isVersionOlderThan(Game.loadingVersion, "0.2.12")) {
this.setElementalSchool(this.getCurrentSchool());
}
}
@Override
public void setStartingBody(boolean setPersona) {
GameCharacter summoner = this.getSummoner();
if(summoner==null) {
return;
}
// Body:
this.setAgeAppearanceDifferenceToAppearAsAge(summoner.getAppearsAsAgeValue());
this.setTailType(TailType.DEMON_COMMON);
this.setWingType(WingType.DEMON_COMMON);
this.setWingSize(WingSize.THREE_LARGE.getValue());
this.setLegType(LegType.DEMON_COMMON);
if(summoner.getHornType().equals(HornType.NONE) || summoner.getHornType().getRace()==Race.DEMON) {
this.setHornType(summoner.getHornType());
} else if(this.isFeminine()) {
this.setHornType(HornType.SWEPT_BACK);
} else {
this.setHornType(HornType.STRAIGHT);
}
// Core:
this.setHeight(summoner.getHeightValue());
this.setFemininity(75);
this.setMuscle(Muscle.TWO_TONED.getMedianValue());
this.setBodySize(BodySize.ZERO_SKINNY.getMedianValue());
// Coverings:
// this.setEyeCovering(new Covering(BodyCoveringType.EYE_DEMON_COMMON, Colour.EYE_RED));
// this.setSkinCovering(new Covering(BodyCoveringType.DEMON_COMMON, Colour.SKIN_PALE), true);
//
// this.setSkinCovering(new Covering(BodyCoveringType.HORN, Colour.HORN_WHITE), false);
//
// this.setHairCovering(new Covering(BodyCoveringType.HAIR_DEMON, Colour.COVERING_BROWN_DARK), true);
// this.setHairLength(HairLength.FOUR_MID_BACK.getMedianValue());
// this.setHairStyle(HairStyle.LOOSE);
//
// this.setHairCovering(new Covering(BodyCoveringType.BODY_HAIR_DEMON, Colour.COVERING_BLACK), false);
// this.setUnderarmHair(BodyHair.ZERO_NONE);
// this.setAssHair(BodyHair.ZERO_NONE);
// this.setPubicHair(BodyHair.ZERO_NONE);
// this.setFacialHair(BodyHair.ZERO_NONE);
//
// this.setFootNailPolish(new Covering(BodyCoveringType.MAKEUP_NAIL_POLISH_FEET, Colour.COVERING_PURPLE));
// this.setHandNailPolish(new Covering(BodyCoveringType.MAKEUP_NAIL_POLISH_HANDS, Colour.COVERING_PURPLE));
// this.setBlusher(new Covering(BodyCoveringType.MAKEUP_BLUSHER, Colour.COVERING_BLACK));
// this.setLipstick(new Covering(BodyCoveringType.MAKEUP_LIPSTICK, Colour.COVERING_RED));
// this.setEyeLiner(new Covering(BodyCoveringType.MAKEUP_EYE_LINER, Colour.COVERING_BLACK));
// this.setEyeShadow(new Covering(BodyCoveringType.MAKEUP_EYE_SHADOW, Colour.COVERING_BLACK));
// Face:
this.setFaceVirgin(true);
this.setLipSize(LipSize.TWO_FULL);
this.setFaceCapacity(Capacity.ONE_EXTREMELY_TIGHT, true);
// Throat settings and modifiers
this.setTongueLength(TongueLength.ZERO_NORMAL.getMedianValue());
// Tongue modifiers
// Chest:
this.setNippleVirgin(true);
if(summoner.hasBreasts()) {
this.setBreastSize(summoner.getBreastSize());
this.setBreastShape(summoner.getBreastShape());
this.setNippleSize(summoner.getNippleSize());
this.setAreolaeSize(summoner.getAreolaeSize());
} else {
this.setBreastSize(CupSize.F.getMeasurement());
this.setBreastShape(BreastShape.ROUND);
this.setNippleSize(NippleSize.THREE_LARGE);
this.setAreolaeSize(AreolaeSize.THREE_LARGE);
}
// Nipple settings and modifiers
// Ass:
this.setAssVirgin(true);
this.setAssBleached(false);
this.setAssSize(AssSize.FOUR_LARGE);
this.setHipSize(HipSize.FOUR_WOMANLY);
// Anus settings and modifiers
// Penis:
// n/a
// Vagina:
this.setVaginaVirgin(true);
this.setVaginaClitorisSize(ClitorisSize.ZERO_AVERAGE);
this.setVaginaLabiaSize(LabiaSize.ZERO_TINY);
this.setVaginaSquirter(true);
this.setVaginaCapacity(Capacity.ONE_EXTREMELY_TIGHT, true);
this.setVaginaWetness(Wetness.THREE_WET);
this.setVaginaElasticity(OrificeElasticity.TWO_FIRM.getValue());
this.setVaginaPlasticity(OrificePlasticity.SIX_MALLEABLE.getValue());
// Feet:
// Foot shape
}
@Override
public void equipClothing(List<EquipClothingSetting> settings) {
// Not needed
}
@Override
public boolean isUnique() {
return false;
}
@Override
public String getSurname() {
if(this.getSummoner()!=null) {
return this.getSummoner().getNameIgnoresPlayerKnowledge()+"kamu"; // Akkadian for bind
} else {
return "kamu";
}
}
@Override
public String getDescription() {
return UtilText.parse(this, getSummoner(), "");
}
@Override
protected int getTrueLevel() {
if(this.getSummoner()==null) {
return level;
}
return getSummoner().getLevel();
}
@Override
public int getLevel() {
return getTrueLevel();
}
@Override
public void changeFurryLevel(){
}
@Override
public DialogueNode getEncounterDialogue() {
return null;
}
@Override
public String rollForPregnancy(GameCharacter partner, float cum, boolean directSexInsemination) {
return PregnancyDescriptor.NO_CHANCE.getDescriptor(this, partner, directSexInsemination)
+"<p style='text-align:center;'>[style.italicsMinorBad(Elementals cannot get pregnant!)]<br/>[style.italicsDisabled(I will add support for impregnating/being impregnated by elementals soon!)]</p>";
}
@Override
public String incrementExperience(int increment, boolean withExtraModifiers) {
return ""; // Elementals don't gain experience, but instead automatically level up alongside their summoner.
}
@Override
public boolean addPerk(int row, AbstractPerk perk) {
perks.putIfAbsent(row, new HashSet<>());
if (perks.get(row).contains(perk)) {
return false;
}
perks.get(row).add(perk);
if(!perk.isEquippableTrait()) {
applyPerkGainEffects(perk);
}
calculateSpells(getCurrentSchool());
return true;
}
private void calculateSpells(SpellSchool school) {
this.resetSpells();
// Add spells:
for(Set<AbstractPerk> perkSet : this.getPerksMap().values()) {
for(AbstractPerk p : perkSet) {
if(p.getSchool()==school) {
if(p.getSpellUpgrade()!=null) {
this.addSpellUpgrade(p.getSpellUpgrade());
} else {
this.addSpell(p.getSpell());
}
}
}
}
}
public SpellSchool getCurrentSchool() {
switch(this.getBodyMaterial()) {
case AIR:
return SpellSchool.AIR;
case ARCANE:
return SpellSchool.ARCANE;
case FIRE:
return SpellSchool.FIRE;
case FLESH:
case SLIME:
break;
case RUBBER:
case STONE:
return SpellSchool.EARTH;
case ICE:
case WATER:
return SpellSchool.WATER;
}
return SpellSchool.ARCANE;
}
public void setElementalSchool(SpellSchool school) {
setElementalSchool(school, null);
}
public void setElementalSchool(SpellSchool school, BodyMaterial preferredMaterial) {
switch(school) {
case AIR:
this.setBodyMaterial(BodyMaterial.AIR);
this.setHistory(Occupation.ELEMENTAL_AIR);
break;
case ARCANE:
this.setBodyMaterial(BodyMaterial.ARCANE);
this.setHistory(Occupation.ELEMENTAL_ARCANE);
break;
case EARTH:
if(preferredMaterial==BodyMaterial.RUBBER) {
this.setBodyMaterial(BodyMaterial.RUBBER);
} else {
this.setBodyMaterial(BodyMaterial.STONE);
}
this.setHistory(Occupation.ELEMENTAL_EARTH);
break;
case FIRE:
this.setBodyMaterial(BodyMaterial.FIRE);
this.setHistory(Occupation.ELEMENTAL_FIRE);
break;
case WATER:
if(preferredMaterial==BodyMaterial.ICE) {
this.setBodyMaterial(BodyMaterial.ICE);
} else {
this.setBodyMaterial(BodyMaterial.WATER);
}
this.setHistory(Occupation.ELEMENTAL_WATER);
break;
}
calculateSpells(school);
}
public GameCharacter getSummoner() {
try {
return Main.game.getNPCById(summonerID);
} catch (Exception e) {
// Util.logGetNpcByIdError("getSummoner()", id);
return null;
// throw new NullPointerException();
}
}
public void setSummoner(String summonerID) {
this.summonerID = summonerID;
}
public void setSummoner(GameCharacter summoner) {
this.summonerID = summoner.getId();
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package autopilot;
import xplane.XplaneInputOutput;
import gui.ControlPanel;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author jvila
*/
public class Autopilot extends Thread {
public static final int ROLLOUT = 1;
public static final int ROTATE = 2;
public static final int CLIMB = 3;
public static final int CRUISE = 4;
XplaneInputOutput xplane;
ControlPanel mygui;
private boolean running;
private int sampleRate;
private DataXplane data;
private DataXplane data2;
private ActionXplane action;
private PhaseController pController;
private Rollout rollOut;
private Rotate rotate;
private Climb climb;
private Cruise cruise;
public Autopilot(ControlPanel mygui) {
this.xplane = new XplaneInputOutput();
this.mygui = mygui;
try {
Thread.sleep(1000); // wait a few before send actions
} catch (InterruptedException ex) {
Logger.getLogger(ControlPanel.class.getName()).log(Level.SEVERE, null, ex);
}
rollOut = new Rollout(); // inicialize phases
rotate = new Rotate();
climb = new Climb();
cruise = new Cruise();
running = true;
sampleRate = 200;
this.start();
}
@Override
public void run() {
pController = rollOut; // initial phase Acordarnos que esto debe ser así, NO EMPEZAR EN CRUISE
//pController = cruise;
while (running) { // control loop
data = xplane.read();
mygui.display(data);
action = pController.computeAction(data);
xplane.write(action);
mygui.display(action);
switch (action.getPhase()) {
case ROLLOUT:
pController = rollOut;
break;
case ROTATE:
pController = rotate;
break;
case CLIMB:
pController = climb;
break;
case CRUISE:
pController = cruise;
break;
}
try {
Thread.sleep(sampleRate);
} catch (InterruptedException ex) {
Logger.getLogger(ControlPanel.class.getName()).log(Level.SEVERE, null, ex);
}
}
xplane.stop();
}
public void stopMe(){
running = false;
}
}
|
package org.hzero.plugin.platform.hr.api.controller;
import java.util.List;
import org.hzero.core.base.BaseConstants;
import org.hzero.core.base.BaseController;
import org.hzero.core.util.Results;
import org.hzero.mybatis.helper.SecurityTokenHelper;
import org.hzero.plugin.platform.hr.api.dto.EmployeeDTO;
import org.hzero.plugin.platform.hr.api.dto.PositionDTO;
import org.hzero.plugin.platform.hr.app.service.PositionService;
import org.hzero.plugin.platform.hr.config.EnablePlatformHrPlugin;
import org.hzero.plugin.platform.hr.domain.entity.Employee;
import org.hzero.plugin.platform.hr.domain.entity.Position;
import org.hzero.plugin.platform.hr.domain.repository.PositionRepository;
import org.hzero.starter.keyencrypt.core.Encrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import io.choerodon.core.domain.Page;
import io.choerodon.core.iam.ResourceLevel;
import io.choerodon.mybatis.pagehelper.annotation.SortDefault;
import io.choerodon.mybatis.pagehelper.domain.PageRequest;
import io.choerodon.mybatis.pagehelper.domain.Sort;
import io.choerodon.swagger.annotation.CustomPageRequest;
import io.choerodon.swagger.annotation.Permission;
import io.swagger.annotations.*;
import springfox.documentation.annotations.ApiIgnore;
/**
* <p>
* 组织架构岗位管理接口
* </p>
*
* @author qingsheng.chen 2018/6/20 星期三 13:51
*/
@Api(tags = EnablePlatformHrPlugin.POSITION)
@RestController("positionController.v1")
@RequestMapping("/v1")
public class PositionController extends BaseController {
private PositionService positionService;
private PositionRepository positionRepository;
@Autowired
public PositionController(PositionService positionService, PositionRepository positionRepository) {
this.positionService = positionService;
this.positionRepository = positionRepository;
}
@ApiOperation("查询岗位")
@GetMapping("/{organizationId}/companies/units/positions/{positionId}")
@Permission(level = ResourceLevel.ORGANIZATION)
public ResponseEntity<Position> queryPosition(
@PathVariable @ApiParam(value = "岗位ID", required = true) @Encrypt long positionId) {
return ResponseEntity.ok(positionService.queryPosition(positionId));
}
@ApiOperation("查询所有岗位树")
@GetMapping("/{organizationId}/companies/units/{unitId}/positions")
@Permission(level = ResourceLevel.ORGANIZATION)
public ResponseEntity<List<PositionDTO>> listPosition(
@PathVariable @ApiParam(value = "租户ID", required = true) long organizationId,
@PathVariable @ApiParam(value = "部门ID", required = true) @Encrypt long unitId,
@RequestParam(required = false) @ApiParam(value = "岗位编码") String positionCode,
@RequestParam(required = false) @ApiParam(value = "岗位名称") String positionName) {
return ResponseEntity.ok(positionService.treePosition(organizationId, unitId, positionCode, positionName));
}
@ApiOperation(value = "拉取最近更新过的记录")
@Permission(level = ResourceLevel.ORGANIZATION)
@GetMapping("/companies/recent")
public ResponseEntity<List<Position>> listRecentPosition(
@ApiParam("租户ID") @RequestParam(required = false) Long tenantId,
@ApiParam("过去多久内(单位:ms,默认5min)") @RequestParam(required = false,
defaultValue = "300000") long before) {
return Results.success(positionService.listRecentPosition(tenantId, before));
}
@ApiOperation("新增岗位")
@PostMapping("/{organizationId}/companies/{unitCompanyId}/units/{unitId}/position")
@Permission(level = ResourceLevel.ORGANIZATION)
public ResponseEntity<Position> createPosition(
@PathVariable @ApiParam(value = "租户ID", required = true) long organizationId,
@PathVariable @ApiParam(value = "公司ID", required = true) @Encrypt long unitCompanyId,
@PathVariable @ApiParam(value = "部门ID", required = true) @Encrypt long unitId,
@RequestBody @Encrypt Position position) {
this.validObject(position);
return ResponseEntity.status(HttpStatus.CREATED).body(positionService.createPosition(
position.setTenantId(organizationId).setUnitCompanyId(unitCompanyId).setUnitId(unitId)));
}
@ApiOperation("批量新增岗位")
@PostMapping("/{organizationId}/companies/{unitCompanyId}/units/{unitId}/positions")
@Permission(level = ResourceLevel.ORGANIZATION)
public ResponseEntity<List<Position>> batchCreatePosition(
@PathVariable @ApiParam(value = "租户ID", required = true) long organizationId,
@PathVariable @ApiParam(value = "公司ID", required = true) @Encrypt long unitCompanyId,
@PathVariable @ApiParam(value = "部门ID", required = true) @Encrypt long unitId,
@RequestBody @Encrypt List<Position> positionList) {
this.validList(positionList);
return ResponseEntity.status(HttpStatus.CREATED)
.body(positionService.batchCreatePosition(organizationId, unitCompanyId, unitId, positionList));
}
@ApiOperation("更新岗位")
@PutMapping("/{organizationId}/companies/{unitCompanyId}/units/{unitId}/positions/{positionId}")
@Permission(level = ResourceLevel.ORGANIZATION)
public ResponseEntity<Position> updatePosition(
@PathVariable @ApiParam(value = "租户ID", required = true) long organizationId,
@PathVariable @ApiParam(value = "公司ID", required = true) @Encrypt long unitCompanyId,
@PathVariable @ApiParam(value = "部门ID", required = true) @Encrypt long unitId,
@PathVariable @ApiParam(value = "岗位ID", required = true) @Encrypt long positionId,
@RequestBody @Encrypt Position position) {
SecurityTokenHelper.validToken(position);
this.validObject(position);
return ResponseEntity.ok(positionService.updatePosition(position.setPositionId(positionId)
.setUnitCompanyId(unitCompanyId).setTenantId(organizationId).setUnitId(unitId)));
}
@ApiOperation("批量更新岗位")
@PutMapping("/{organizationId}/companies/{unitCompanyId}/units/{unitId}/positions")
@Permission(level = ResourceLevel.ORGANIZATION)
public ResponseEntity<List<Position>> batchUpdatePosition(
@PathVariable @ApiParam(value = "租户ID", required = true) long organizationId,
@PathVariable @ApiParam(value = "公司ID", required = true) @Encrypt long unitCompanyId,
@PathVariable @ApiParam(value = "部门ID", required = true) @Encrypt long unitId,
@RequestBody @Encrypt List<Position> positionList) {
SecurityTokenHelper.validToken(positionList);
this.validList(positionList);
return ResponseEntity
.ok(positionService.batchUpdatePosition(organizationId, unitCompanyId, unitId, positionList));
}
@ApiOperation("启用岗位")
@PostMapping("/{organizationId}/companies/{unitCompanyId}/units/{unitId}/positions/enable/{positionId}")
@Permission(level = ResourceLevel.ORGANIZATION)
public ResponseEntity<List<Position>> enablePosition(
@PathVariable @ApiParam(value = "租户ID", required = true) long organizationId,
@PathVariable @ApiParam(value = "公司ID", required = true) @Encrypt long unitCompanyId,
@PathVariable @ApiParam(value = "部门ID", required = true) @Encrypt long unitId,
@PathVariable @ApiParam(value = "岗位ID", required = true) @Encrypt long positionId,
@RequestBody @Encrypt Position position) {
SecurityTokenHelper.validToken(position.setTenantId(organizationId).setUnitCompanyId(unitCompanyId).setUnitId(unitId).setPositionId(positionId));
Assert.notNull(position.getObjectVersionNumber(), BaseConstants.ErrorCode.OPTIMISTIC_LOCK);
return ResponseEntity.ok(positionService.enablePosition(position));
}
@ApiOperation("禁用岗位")
@PostMapping("/{organizationId}/companies/{unitCompanyId}/units/{unitId}/positions/disable/{positionId}")
@Permission(level = ResourceLevel.ORGANIZATION)
public ResponseEntity<List<Position>> disablePosition(
@PathVariable @ApiParam(value = "租户ID", required = true) long organizationId,
@PathVariable @ApiParam(value = "公司ID", required = true) @Encrypt long unitCompanyId,
@PathVariable @ApiParam(value = "部门ID", required = true) @Encrypt long unitId,
@PathVariable @ApiParam(value = "岗位ID", required = true) @Encrypt long positionId,
@RequestBody @Encrypt Position position) {
SecurityTokenHelper.validToken(position.setTenantId(organizationId).setUnitCompanyId(unitCompanyId).setUnitId(unitId).setPositionId(positionId));
Assert.notNull(position.getObjectVersionNumber(), BaseConstants.ErrorCode.OPTIMISTIC_LOCK);
return ResponseEntity.ok(positionService.disablePosition(position));
}
@ApiOperation("通过岗位编码查询岗位")
@GetMapping("/{organizationId}/companies/units/positions/position-code")
@Permission(level = ResourceLevel.ORGANIZATION)
public ResponseEntity<Position> queryPositionByCode(@PathVariable("organizationId") Long organizationId,
@RequestParam String positionCode) {
return ResponseEntity.ok(positionRepository.queryPositionByCode(positionCode, organizationId));
}
@ApiOperation("全量查询租户下的岗位信息")
@GetMapping("/{organizationId}/companies/tenant/positions/all")
@Permission(level = ResourceLevel.ORGANIZATION)
public ResponseEntity<List<Position>> queryAllPositions(@PathVariable("organizationId") Long tenantId) {
return ResponseEntity.ok(positionRepository.queryAllPositionsByTenant(tenantId));
}
@ApiOperation("新版组织架构-全量查询组织下的岗位信息")
@GetMapping("/{organizationId}/positions/{unitId}")
@Permission(level = ResourceLevel.ORGANIZATION)
@CustomPageRequest
public ResponseEntity<Page<Position>> queryPositionsByUnit(@PathVariable("organizationId") Long tenantId,
@PathVariable("unitId") @Encrypt(ignoreValue = "0") Long unitId,
@RequestParam(required = false) @ApiParam(value = "组织编码/组织名称") String keyWord,
@ApiIgnore @SortDefault(value = Position.FIELD_POSITION_ID, direction = Sort.Direction.ASC) PageRequest pageRequest) {
return ResponseEntity.ok(positionRepository.pagePositionByUnit(pageRequest, tenantId, unitId,keyWord));
}
@ApiOperation(value = "新版组织架构-树形查询岗位")
@ApiImplicitParams({@ApiImplicitParam(name = "organizationId", paramType = "path", value = "租户ID", required = true),
@ApiImplicitParam(name = "unitCompanyId", paramType = "query", value = "岗位所属公司"),
@ApiImplicitParam(name = "unitId", paramType = "query", value = "岗位所属部门"),
@ApiImplicitParam(name = "keyWord", paramType = "query", value = "岗位代码/岗位名称")})
@Permission(level = ResourceLevel.ORGANIZATION)
@GetMapping("/{organizationId}/positions")
public ResponseEntity<List<PositionDTO>> listPlusPositionTree(@RequestParam(required = false) String keyWord,
@RequestParam(required = false) @Encrypt(ignoreValue = "0") Long unitCompanyId,
@RequestParam(required = false) @Encrypt(ignoreValue = "0") Long unitId,
@PathVariable("organizationId") Long tenantId) {
Assert.notNull(tenantId, BaseConstants.ErrorCode.DATA_INVALID);
return Results.success(positionService.selectPlusPositionTree(tenantId,unitCompanyId, unitId,keyWord));
}
@ApiOperation("新版组织架构-批量查询岗位下的用户信息")
@Permission(level = ResourceLevel.ORGANIZATION)
@GetMapping("/{organizationId}/positions/user/{positionId}")
@CustomPageRequest
public ResponseEntity<Page<EmployeeDTO>> pageUnitUsers(@ApiParam(required = true, value = "租户ID") @PathVariable("organizationId") Long tenantId,
@ApiParam(required = true, value = "岗位ID") @PathVariable("positionId") @Encrypt(ignoreValue = "0") Long positionId,
@RequestParam(required = false) String keyWord,
@RequestParam(required = false) String status,
@RequestParam(required = false) Integer primaryPositionFlag,
@ApiIgnore @SortDefault(value = Employee.FIELD_EMPLOYEE_NUM, direction = Sort.Direction.ASC) PageRequest pageRequest) {
return Results.success(positionService.pagePositionUsers(tenantId, positionId, keyWord, status, primaryPositionFlag, pageRequest));
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.jme3.shader.layout;
import com.jme3.util.SafeArrayList;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
/**
* Extracts layout data relevant for getting opengl buffer data written
* correctly using reflection
*
* @author Alexander Kasigkeit
*/
public class ReflectionLayoutGenerator {
private Map<String, Map<String, FieldInfo>> layouts = new HashMap<>();
private Map<String, SafeArrayList<FieldInfo>> layoutsList = new HashMap<>();
public ReflectionLayoutGenerator() {
}
public Map<String, SafeArrayList<FieldInfo>> getLayoutLists() {
return layoutsList;
}
public <T extends Struct> void registerStruct(Class<T> struct) {
String name = struct.getSimpleName();
Map<String, FieldInfo> infoMap = layouts.get(name);
if (infoMap != null) {
throw new IllegalArgumentException("struct of same type has already been registered: " + name);
}
Field[] fields = struct.getDeclaredFields();
if (fields.length == 0) {
throw new IllegalArgumentException("provided struct (" + name + ") does not declare any fields");
}
infoMap = new HashMap<>(fields.length);
SafeArrayList<FieldInfo> infoList = new SafeArrayList<>(FieldInfo.class, fields.length);
for (Field field : fields) {
field.setAccessible(true);
Member m = field.getDeclaredAnnotation(Member.class);
if (m != null) {
String fieldName = field.getName();
BlockVarType type = m.type();
if (type == null || type == BlockVarType.AutoDetect) {
type = BlockVarType.fromClass(field.getType());
if (type == null) { //not a well known one, check if it is a struct or struct array
if (field.getType().isArray() && Struct.class.isAssignableFrom(field.getType().getComponentType())) {
type = BlockVarType.StructArray;
} else if (Struct.class.isAssignableFrom(field.getType())) {
type = BlockVarType.Struct;
}
}
}
if (type == null) {
throw new IllegalArgumentException("cannot detect type of field: " + field.getName());
}
String maps = m.maps();
if (maps == null || Member.AUTOMAPPING.equals(maps)) {
maps = fieldName;
}
FieldInfo info = new FieldInfo(fieldName, field, type, maps);
infoMap.put(fieldName, info);
infoList.add(info);
}
}
int memFieldCount = infoMap.size();
if (memFieldCount < 1) {
throw new IllegalArgumentException("provided class (" + name + ") does not declare any member fields. Please use annotation @Member");
}
layoutsList.put(name, infoList);
layouts.put(name, infoMap);
}
public Map<String, FieldInfo> getLayoutInformation(String structName) {
return layouts.get(structName);
}
public SafeArrayList<FieldInfo> getLayoutInformationList(String structName) {
return layoutsList.get(structName);
}
public static class FieldInfo {
private final String name;
private final Field field;
private final String maps;
private final BlockVarType type;
private FieldInfo(String name, Field field, BlockVarType type, String maps) {
this.name = name;
this.field = field;
this.type = type;
this.maps = maps;
}
/**
* Returns the glsl name of this field
*
* @return the glsl name
*/
public String getNameInShader() {
return maps;
}
/**
* Returns the cpu-side name of this field
*
* @return the cpu-side name
*/
public String getName() {
return name;
}
/**
* Returns the Field used for reflection
*
* @return field for reflection
*/
public Field getField() {
return field;
}
/**
* Returns the BlockVarType of this Field
*
* @return the blockVarType
*/
public BlockVarType getType() {
return type;
}
}
}
|
package com.ejoy.tool.ui.data.adapter;
import android.app.Activity;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.ejoy.tool.scaffold.utils.GlideUtils;
import com.github.chrisbanes.photoview.OnPhotoTapListener;
import com.github.chrisbanes.photoview.PhotoView;
import java.util.List;
public class PreviewAdapter extends PagerAdapter {
private List<String> mFilePathData;
private int mChildCount;
private Activity mActivity;
public PreviewAdapter(List<String> filePathData, @NonNull Activity activity) {
this.mFilePathData = filePathData;
this.mActivity = activity;
}
@Override
public int getCount() {
return mFilePathData == null ? 0 : mFilePathData.size();
}
@Override
public void notifyDataSetChanged() {
mChildCount = getCount();
super.notifyDataSetChanged();
}
@Override
public int getItemPosition(@NonNull Object object) {
if (mChildCount > 0) {
mChildCount--;
return POSITION_NONE;
}
return super.getItemPosition(object);
}
@Override
public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
return view == object;
}
@Override
public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
container.removeView((View) object);
}
@NonNull
@Override
public PhotoView instantiateItem(@NonNull ViewGroup container, int position) {
PhotoView photoView = new PhotoView(container.getContext());
container.addView(photoView);
ViewGroup.LayoutParams layoutParams = photoView.getLayoutParams();
layoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT;
layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
photoView.setLayoutParams(layoutParams);
GlideUtils.showImage(container.getContext(), mFilePathData.get(position), photoView);
photoView.setOnPhotoTapListener(new OnPhotoTapListener() {
@Override
public void onPhotoTap(ImageView view, float x, float y) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mActivity.finishAfterTransition();
}else {
mActivity.finish();
}
}
});
return photoView;
}
public static class PreviewPageTransformer implements ViewPager.PageTransformer {
private ViewPager viewPager;
@Override
public void transformPage(@NonNull View view, float position) {
if (viewPager == null) {
viewPager = (ViewPager) view.getParent();
}
int leftInScreen = view.getLeft() - viewPager.getScrollX();
float offsetRate = (float) leftInScreen * 0.08f / viewPager.getMeasuredWidth();
float scaleFactor = 1 - Math.abs(offsetRate);
if (scaleFactor > 0) {
view.setScaleX(scaleFactor);
}
}
}
}
|
/*
* Copyright (C) 2014 Google, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.testing.compile;
import static com.google.common.collect.Iterables.getOnlyElement;
import static com.google.common.truth.Truth.assertThat;
import com.google.common.collect.ImmutableList;
import com.google.testing.compile.Parser.ParseResult;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.Tree;
import com.sun.source.util.TreePath;
import java.util.Objects;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/**
* A test for {@link DetailedEqualityScanner}
*/
@RunWith(JUnit4.class)
public class TreeDifferTest {
@Rule public final ExpectedException expectedExn = ExpectedException.none();
private static final CompilationUnitTree EXPECTED_TREE =
MoreTrees.parseLinesToTree("package test;",
"import java.util.Set;",
"",
"final class TestClass {",
" public String toString() {",
" Object variable = new Object();",
" return \"literal\" + variable;",
" }",
"",
" public void nonsense() {",
" int[] numbers = {0, 1, 2, 3, 4};",
" loop: for (int x : numbers) {",
" if (x % 2 == 0) {",
" throw new IllegalStateException();",
" }",
" break loop;",
" }",
" }",
"}");
private static final CompilationUnitTree ACTUAL_TREE =
MoreTrees.parseLinesToTree("package test;",
"import java.util.List;",
"",
"final class TestClass {",
" public String toString() {",
" Object variable = new Object();",
" return \"literal\" + variable;",
" }",
"",
" public void nonsense() {",
" int[] numberz = {0, 1, 2, 3, 4, 5};",
" loop: for (int x : numberz) {",
" if (x % 2 == 0) {",
" throw new RuntimeException();",
" }",
" break;",
" }",
" }",
" public int extraNonsense() {",
" return 0;",
" }",
"}");
private static final CompilationUnitTree ASSERT_TREE_WITH_MESSAGE =
MoreTrees.parseLinesToTree("package test;",
"final class TestClass {",
" private void fail() {",
" assert false : \"details\";",
" }",
"}");
private static final CompilationUnitTree ASSERT_TREE_WITHOUT_MESSAGE =
MoreTrees.parseLinesToTree("package test;",
"final class TestClass {",
" private void fail() {",
" assert false;",
" }",
"}");
// These are used to test null tree iterators.
// getInitializers() on NewArrayTrees will return null if the array is dimension-defined.
private static final CompilationUnitTree NEW_ARRAY_SIZE_THREE =
MoreTrees.parseLinesToTree("package test;",
"final class TestClass {",
" private static final int[] myArray = new int[3];",
"}");
private static final CompilationUnitTree NEW_ARRAY_SIZE_FOUR =
MoreTrees.parseLinesToTree("package test;",
"final class TestClass {",
" private static final int[] myArray = new int[4];",
"}");
private static final CompilationUnitTree NEW_ARRAY_STATIC_INITIALIZER =
MoreTrees.parseLinesToTree("package test;",
"final class TestClass {",
" private static final int[] myArray = {1, 2, 3};",
"}");
private static final CompilationUnitTree LAMBDA_1 =
MoreTrees.parseLinesToTree("package test;",
"final class TestClass {",
" private static final Consumer<Integer> NEWLINE = (int i) -> System.out.println(i);",
"}");
private static final CompilationUnitTree LAMBDA_2 =
MoreTrees.parseLinesToTree("package test;",
"final class TestClass {",
" private static final Consumer<Integer> NEWLINE =",
" (int i) -> System.out.println(i);",
"}");
private static final CompilationUnitTree LAMBDA_IMPLICIT_ARG_TYPE =
MoreTrees.parseLinesToTree("package test;",
"final class TestClass {",
" private static final Consumer<Integer> NEWLINE =",
" (i) -> System.out.println(i);",
"}");
private static final CompilationUnitTree LAMBDA_IMPLICIT_ARG_TYPE_NO_PARENS =
MoreTrees.parseLinesToTree("package test;",
"final class TestClass {",
" private static final Consumer<Integer> NEWLINE =",
" i -> System.out.println(i);",
"}");
private static final CompilationUnitTree METHOD_REFERENCE =
MoreTrees.parseLinesToTree("package test;",
"final class TestClass {",
" private static final Runnable NEWLINE = System.out::println;",
"}");
private static final CompilationUnitTree ANONYMOUS_CLASS =
MoreTrees.parseLinesToTree("package test;",
"final class TestClass {",
" private static final Runnable NEWLINE = new Runnable() {",
" public void run() { System.out.println(); }",
" };",
"}");
@Test
public void scan_differingCompilationUnits() {
TreeDifference diff = TreeDiffer.diffCompilationUnits(EXPECTED_TREE, ACTUAL_TREE);
assertThat(diff.isEmpty()).isFalse();
ImmutableList<SimplifiedDiff> extraNodesExpected = ImmutableList.of(
new SimplifiedDiff(Tree.Kind.INT_LITERAL, ""),
new SimplifiedDiff(Tree.Kind.METHOD, ""));
ImmutableList<SimplifiedDiff> differingNodesExpected = ImmutableList.of(
new SimplifiedDiff(Tree.Kind.MEMBER_SELECT,
"Expected member identifier to be <Set> but was <List>."),
new SimplifiedDiff(Tree.Kind.VARIABLE,
"Expected variable name to be <numbers> but was <numberz>."),
new SimplifiedDiff(Tree.Kind.IDENTIFIER,
"Expected identifier to be <numbers> but was <numberz>."),
new SimplifiedDiff(Tree.Kind.IDENTIFIER,
"Expected identifier to be <IllegalStateException> but was <RuntimeException>."),
new SimplifiedDiff(Tree.Kind.BREAK,
"Expected label on break statement to be <loop> but was <null>."));
assertThat(diff.getExtraExpectedNodes().isEmpty()).isTrue();
assertThat(diff.getExtraActualNodes().size()).isEqualTo(extraNodesExpected.size());
ImmutableList.Builder<SimplifiedDiff> extraNodesFound =
new ImmutableList.Builder<SimplifiedDiff>();
for (TreeDifference.OneWayDiff extraNode : diff.getExtraActualNodes()) {
extraNodesFound.add(SimplifiedDiff.create(extraNode));
}
assertThat(extraNodesFound.build()).containsExactlyElementsIn(extraNodesExpected).inOrder();
ImmutableList.Builder<SimplifiedDiff> differingNodesFound =
new ImmutableList.Builder<SimplifiedDiff>();
for (TreeDifference.TwoWayDiff differingNode : diff.getDifferingNodes()) {
differingNodesFound.add(SimplifiedDiff.create(differingNode));
}
assertThat(differingNodesFound.build())
.containsExactlyElementsIn(differingNodesExpected)
.inOrder();
}
@Test
public void scan_testExtraFields() {
TreeDifference diff =
TreeDiffer.diffCompilationUnits(ASSERT_TREE_WITH_MESSAGE, ASSERT_TREE_WITHOUT_MESSAGE);
assertThat(diff.isEmpty()).isFalse();
diff = TreeDiffer.diffCompilationUnits(ASSERT_TREE_WITHOUT_MESSAGE, ASSERT_TREE_WITH_MESSAGE);
assertThat(diff.isEmpty()).isFalse();
}
@Test
public void scan_sameCompilationUnit() {
assertThat(TreeDiffer.diffCompilationUnits(EXPECTED_TREE, EXPECTED_TREE).isEmpty()).isTrue();
}
@Test
public void scan_identicalMethods() {
assertThat(TreeDiffer.diffSubtrees(baseToStringTree(), diffToStringTree())
.isEmpty()).isTrue();
}
@Test
public void scan_differentTypes() {
TreeDifference diff = TreeDiffer.diffSubtrees(asPath(EXPECTED_TREE), diffToStringTree());
assertThat(diff.isEmpty()).isFalse();
for (TreeDifference.TwoWayDiff differingNode : diff.getDifferingNodes()) {
assertThat(differingNode.getDetails()).contains("Expected node kind to be");
}
}
@Test
public void scan_testTwoNullIterableTrees() {
TreeDifference diff =
TreeDiffer.diffCompilationUnits(NEW_ARRAY_SIZE_THREE, NEW_ARRAY_SIZE_FOUR);
assertThat(diff.isEmpty()).isFalse();
for (TreeDifference.TwoWayDiff differingNode : diff.getDifferingNodes()) {
assertThat(differingNode.getDetails())
.contains("Expected literal value to be <3> but was <4>");
}
}
@Test
public void scan_testExpectedNullIterableTree() {
TreeDifference diff =
TreeDiffer.diffCompilationUnits(NEW_ARRAY_SIZE_THREE, NEW_ARRAY_STATIC_INITIALIZER);
assertThat(diff.isEmpty()).isFalse();
}
@Test
public void scan_testActualNullIterableTree() {
TreeDifference diff =
TreeDiffer.diffCompilationUnits(NEW_ARRAY_STATIC_INITIALIZER, NEW_ARRAY_SIZE_FOUR);
assertThat(diff.isEmpty()).isFalse();
}
@Test
public void scan_testLambdas() {
TreeDifference diff =
TreeDiffer.diffCompilationUnits(LAMBDA_1, LAMBDA_2);
assertThat(diff.isEmpty()).isTrue();
}
@Test
public void scan_testLambdasExplicitVsImplicit() {
TreeDifference diff =
TreeDiffer.diffCompilationUnits(LAMBDA_1, LAMBDA_IMPLICIT_ARG_TYPE);
assertThat(diff.isEmpty()).isFalse();
}
@Test
public void scan_testLambdasParensVsNone() {
TreeDifference diff =
TreeDiffer.diffCompilationUnits(
LAMBDA_IMPLICIT_ARG_TYPE, LAMBDA_IMPLICIT_ARG_TYPE_NO_PARENS);
assertThat(diff.isEmpty()).isTrue();
}
@Test
public void scan_testLambdaVersusMethodReference() {
TreeDifference diff =
TreeDiffer.diffCompilationUnits(LAMBDA_1, METHOD_REFERENCE);
assertThat(diff.isEmpty()).isFalse();
}
@Test
public void scan_testLambdaVersusAnonymousClass() {
TreeDifference diff =
TreeDiffer.diffCompilationUnits(LAMBDA_1, ANONYMOUS_CLASS);
assertThat(diff.isEmpty()).isFalse();
}
@Test
public void matchCompilationUnits() {
ParseResult actual =
MoreTrees.parseLines(
"package test;",
"",
"import not.NotUsed;",
"import is.IsUsed;",
"",
"public class HasExtras { ",
" private NotUsed skipped;",
" private Object matched;",
" private IsUsed usedFromImport;",
" private Object skipped2;",
"",
" HasExtras() {}",
" HasExtras(int overloadedConstructor) {}",
"",
" public String skippedMethod() { return null; }",
" public String matchedMethod() { return null; }",
" public Object overloadedMethod(int skipWithDifferentSignature) { return null; }",
" public String overloadedMethod(int i, Double d) { return null; }",
" public String overloadedMethod(int i, Double d, IsUsed u) { return null; }",
"",
" class NestedClass {",
" int matchMe = 0;",
" double ignoreMe = 0;",
" }",
"",
" class IgnoredNestedClass {}",
"}");
ParseResult pattern =
MoreTrees.parseLines(
"package test;",
"",
"import is.IsUsed;",
"",
"public class HasExtras { ",
" private Object matched;",
" private IsUsed usedFromImport;",
"",
" HasExtras(int overloadedConstructor) {}",
"",
" public String matchedMethod() { return null; }",
" public String overloadedMethod(int i, Double d) { return null; }",
" public String overloadedMethod(int i, Double d, IsUsed u) { return null; }",
"",
" class NestedClass {",
" int matchMe = 0;",
" }",
"}");
TreeDifference diff =
TreeDiffer.matchCompilationUnits(
getOnlyElement(pattern.compilationUnits()),
pattern.trees(),
getOnlyElement(actual.compilationUnits()),
actual.trees());
assertThat(diff.isEmpty()).isTrue();
}
@Test
public void matchCompilationUnits_unresolvedTypeInPattern() {
ParseResult actual =
MoreTrees.parseLines(
"package test;",
"",
"import is.IsUsed;",
"",
"public class HasExtras { ",
" private IsUsed usedFromImport;",
"}");
ParseResult pattern =
MoreTrees.parseLines(
"package test;",
"",
"public class HasExtras { ",
" private IsUsed usedFromImport;",
"}");
TreeDifference diff =
TreeDiffer.matchCompilationUnits(
getOnlyElement(pattern.compilationUnits()),
pattern.trees(),
getOnlyElement(actual.compilationUnits()),
actual.trees());
assertThat(diff.isEmpty()).isTrue();
}
@Test
public void matchCompilationUnits_sameSignature_differentReturnType() {
ParseResult actual =
MoreTrees.parseLines(
"package test;",
"public class HasExtras { ",
" private Object method(int i, double d) { return null; };",
"}");
ParseResult pattern =
MoreTrees.parseLines(
"package test;",
"",
"public class HasExtras { ",
" private String method(int i, double d) { return null; };",
"}");
TreeDifference diff =
TreeDiffer.matchCompilationUnits(
getOnlyElement(pattern.compilationUnits()),
pattern.trees(),
getOnlyElement(actual.compilationUnits()),
actual.trees());
assertThat(diff.getDifferingNodes()).isNotEmpty();
}
@Test
public void matchCompilationUnits_sameSignature_differentParameterNames() {
ParseResult actual =
MoreTrees.parseLines(
"package test;",
"public class HasExtras { ",
" private Object method(int i, double d) { return null; };",
"}");
ParseResult pattern =
MoreTrees.parseLines(
"package test;",
"",
"public class HasExtras { ",
" private Object method(int i2, double d2) { return null; };",
"}");
TreeDifference diff =
TreeDiffer.matchCompilationUnits(
getOnlyElement(pattern.compilationUnits()),
pattern.trees(),
getOnlyElement(actual.compilationUnits()),
actual.trees());
assertThat(diff.getDifferingNodes()).isNotEmpty();
}
@Test
public void matchCompilationUnits_sameSignature_differentParameters() {
ParseResult actual =
MoreTrees.parseLines(
"package test;",
"public class HasExtras { ",
" private Object method(int i, Object o) { return null; };",
"}");
ParseResult pattern =
MoreTrees.parseLines(
"package test;",
"",
"public class HasExtras { ",
" private Object method(int i2, @Nullable Object o) { return null; };",
"}");
TreeDifference diff =
TreeDiffer.matchCompilationUnits(
getOnlyElement(pattern.compilationUnits()),
pattern.trees(),
getOnlyElement(actual.compilationUnits()),
actual.trees());
assertThat(diff.getDifferingNodes()).isNotEmpty();
}
@Test
public void matchCompilationUnits_sameSignature_differentModifiers() {
ParseResult actual =
MoreTrees.parseLines(
"package test;",
"public class HasExtras { ",
" private Object method(int i, Object o) { return null; };",
"}");
ParseResult pattern =
MoreTrees.parseLines(
"package test;",
"",
"public class HasExtras { ",
" public Object method(int i2, @Nullable Object o) { return null; };",
"}");
TreeDifference diff =
TreeDiffer.matchCompilationUnits(
getOnlyElement(pattern.compilationUnits()),
pattern.trees(),
getOnlyElement(actual.compilationUnits()),
actual.trees());
assertThat(diff.getDifferingNodes()).isNotEmpty();
}
@Test
public void matchCompilationUnits_sameSignature_differentThrows() {
ParseResult actual =
MoreTrees.parseLines(
"package test;",
"public class HasExtras { ",
" private void method() throws RuntimeException {}",
"}");
ParseResult pattern =
MoreTrees.parseLines(
"package test;",
"",
"public class HasExtras { ",
" private void method() throws Error {}",
"}");
TreeDifference diff =
TreeDiffer.matchCompilationUnits(
getOnlyElement(pattern.compilationUnits()),
pattern.trees(),
getOnlyElement(actual.compilationUnits()),
actual.trees());
assertThat(diff.getDifferingNodes()).isNotEmpty();
}
@Test
public void matchCompilationUnits_variablesWithDifferentTypes() {
ParseResult actual =
MoreTrees.parseLines(
"package test;",
"public class HasExtras { ",
" private Object field;",
"}");
ParseResult pattern =
MoreTrees.parseLines(
"package test;",
"",
"public class HasExtras { ",
" private String field;",
"}");
TreeDifference diff =
TreeDiffer.matchCompilationUnits(
getOnlyElement(pattern.compilationUnits()),
pattern.trees(),
getOnlyElement(actual.compilationUnits()),
actual.trees());
assertThat(diff.getDifferingNodes()).isNotEmpty();
}
@Test
public void matchCompilationUnits_importsWithSameSimpleName() {
ParseResult actual =
MoreTrees.parseLines(
"package test;",
"",
"import foo.Imported;",
"",
"public class HasExtras { ",
" private Imported field;",
"}");
ParseResult pattern =
MoreTrees.parseLines(
"package test;",
"",
"import bar.Imported;",
"",
"public class HasExtras { ",
" private Imported field;",
"}");
TreeDifference diff =
TreeDiffer.matchCompilationUnits(
getOnlyElement(pattern.compilationUnits()),
pattern.trees(),
getOnlyElement(actual.compilationUnits()),
actual.trees());
assertThat(diff.getExtraExpectedNodes()).isNotEmpty();
assertThat(diff.getExtraActualNodes()).isEmpty();
}
@Test
public void matchCompilationUnits_wrongOrder() {
ParseResult actual =
MoreTrees.parseLines(
"package test;",
"",
"class Foo {",
" private String method1() { return new String(); }",
" private String method2() { return new String(); }",
"}");
ParseResult pattern =
MoreTrees.parseLines(
"package test;",
"",
"class Foo {",
" private String method2() { return new String(); }",
" private String method1() { return new String(); }",
"}");
TreeDifference diff =
TreeDiffer.matchCompilationUnits(
getOnlyElement(pattern.compilationUnits()),
pattern.trees(),
getOnlyElement(actual.compilationUnits()),
actual.trees());
assertThat(diff.getDifferingNodes()).isNotEmpty();
}
@Test
public void matchCompilationUnits_missingParameter() {
ParseResult actual =
MoreTrees.parseLines(
"package test;",
"",
"class Foo {",
" private String method1(String s) { return s; }",
" private String method2() { return new String(); }",
"}");
ParseResult pattern =
MoreTrees.parseLines(
"package test;",
"",
"class Foo {",
" private String method1() { return s; }",
"}");
TreeDifference diff =
TreeDiffer.matchCompilationUnits(
getOnlyElement(pattern.compilationUnits()),
pattern.trees(),
getOnlyElement(actual.compilationUnits()),
actual.trees());
assertThat(diff.getExtraExpectedNodes()).isNotEmpty();
assertThat(diff.getExtraActualNodes()).isEmpty();
}
@Test
public void matchCompilationUnits_missingMethodBodyStatement() {
ParseResult actual =
MoreTrees.parseLines(
"package test;",
"",
"class Foo {",
" private String method1(String s) { ",
" System.out.println(s);",
" return s;",
" }",
" private String method2() { return new String(); }",
"}");
ParseResult pattern =
MoreTrees.parseLines(
"package test;",
"",
"class Foo {",
" private String method1(String s) { ",
" return s;",
" }",
"}");
TreeDifference diff =
TreeDiffer.matchCompilationUnits(
getOnlyElement(pattern.compilationUnits()),
pattern.trees(),
getOnlyElement(actual.compilationUnits()),
actual.trees());
assertThat(diff.getExtraActualNodes()).isNotEmpty();
}
@Test
public void matchCompilationUnits_skipsImports() {
ParseResult actual =
MoreTrees.parseLines(
"package test;",
"",
"import bar.Bar;",
"",
"class Foo {",
" private Bar bar;",
"}");
ParseResult pattern =
MoreTrees.parseLines(
"package test;",
"",
"class Foo {",
" private Bar bar;",
"}");
TreeDifference diff =
TreeDiffer.matchCompilationUnits(
getOnlyElement(pattern.compilationUnits()),
pattern.trees(),
getOnlyElement(actual.compilationUnits()),
actual.trees());
assertThat(diff.isEmpty()).isTrue();
}
private TreePath asPath(CompilationUnitTree compilationUnit) {
return MoreTrees.findSubtreePath(compilationUnit, Tree.Kind.COMPILATION_UNIT);
}
private TreePath baseToStringTree() {
return MoreTrees.findSubtreePath(EXPECTED_TREE, Tree.Kind.METHOD, "toString");
}
private TreePath diffToStringTree() {
return MoreTrees.findSubtreePath(ACTUAL_TREE, Tree.Kind.METHOD, "toString");
}
private static class SimplifiedDiff {
private final Tree.Kind kind;
private final String details;
SimplifiedDiff(Tree.Kind kind, String details) {
this.kind = kind;
this.details = details;
}
Tree.Kind getKind() {
return kind;
}
String getDetails() {
return details;
}
static SimplifiedDiff create(TreeDifference.OneWayDiff other) {
return new SimplifiedDiff(other.getNodePath().getLeaf().getKind(), other.getDetails());
}
static SimplifiedDiff create(TreeDifference.TwoWayDiff other) {
return new SimplifiedDiff(
other.getExpectedNodePath().getLeaf().getKind(), other.getDetails());
}
@Override
public String toString() {
return String.format("%s: %s", this.kind.toString(), this.details.toString());
}
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
} else if (o instanceof SimplifiedDiff) {
SimplifiedDiff that = (SimplifiedDiff) o;
return this.kind.equals(that.kind)
&& this.details.equals(that.details);
} else {
return false;
}
}
@Override
public int hashCode() {
return Objects.hash(kind, details);
}
}
}
|
/*
* 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.hadoop.ozone.om.snapshot;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.hadoop.hdds.conf.OzoneConfiguration;
import org.apache.hadoop.ozone.MiniOzoneCluster;
import org.apache.hadoop.ozone.MiniOzoneHAClusterImpl;
import org.apache.hadoop.ozone.client.ObjectStore;
import org.apache.hadoop.ozone.client.OzoneBucket;
import org.apache.hadoop.ozone.client.OzoneClientFactory;
import org.apache.hadoop.ozone.client.OzoneVolume;
import org.apache.hadoop.ozone.client.VolumeArgs;
import org.apache.hadoop.ozone.om.OMConfigKeys;
import org.apache.hadoop.ozone.om.OzoneManager;
import org.apache.hadoop.utils.db.DBCheckpoint;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.Timeout;
import java.util.UUID;
/**
* Test OM's snapshot provider service.
*/
public class TestOzoneManagerSnapshotProvider {
private MiniOzoneHAClusterImpl cluster = null;
private ObjectStore objectStore;
private OzoneConfiguration conf;
private String clusterId;
private String scmId;
private int numOfOMs = 3;
@Rule
public Timeout timeout = new Timeout(300_000);
/**
* Create a MiniDFSCluster for testing.
*/
@Before
public void init() throws Exception {
conf = new OzoneConfiguration();
clusterId = UUID.randomUUID().toString();
scmId = UUID.randomUUID().toString();
conf.setBoolean(OMConfigKeys.OZONE_OM_HTTP_ENABLED_KEY, true);
conf.setBoolean(OMConfigKeys.OZONE_OM_RATIS_ENABLE_KEY, true);
cluster = (MiniOzoneHAClusterImpl) MiniOzoneCluster.newHABuilder(conf)
.setClusterId(clusterId)
.setScmId(scmId)
.setOMServiceId("om-service-test1")
.setNumOfOzoneManagers(numOfOMs)
.build();
cluster.waitForClusterToBeReady();
objectStore = OzoneClientFactory.getRpcClient(conf).getObjectStore();
}
/**
* Shutdown MiniDFSCluster.
*/
@After
public void shutdown() {
if (cluster != null) {
cluster.shutdown();
}
}
@Test
public void testDownloadCheckpoint() throws Exception {
String userName = "user" + RandomStringUtils.randomNumeric(5);
String adminName = "admin" + RandomStringUtils.randomNumeric(5);
String volumeName = "volume" + RandomStringUtils.randomNumeric(5);
String bucketName = "bucket" + RandomStringUtils.randomNumeric(5);
VolumeArgs createVolumeArgs = VolumeArgs.newBuilder()
.setOwner(userName)
.setAdmin(adminName)
.build();
objectStore.createVolume(volumeName, createVolumeArgs);
OzoneVolume retVolumeinfo = objectStore.getVolume(volumeName);
retVolumeinfo.createBucket(bucketName);
OzoneBucket ozoneBucket = retVolumeinfo.getBucket(bucketName);
String leaderOMNodeId = objectStore.getClientProxy().getOMProxyProvider()
.getCurrentProxyOMNodeId();
OzoneManager ozoneManager = cluster.getOzoneManager(leaderOMNodeId);
// Get a follower OM
String followerNodeId = ozoneManager.getPeerNodes().get(0).getOMNodeId();
OzoneManager followerOM = cluster.getOzoneManager(followerNodeId);
// Download latest checkpoint from leader OM to follower OM
DBCheckpoint omSnapshot = followerOM.getOmSnapshotProvider()
.getOzoneManagerDBSnapshot(leaderOMNodeId);
long leaderSnapshotIndex = ozoneManager.getRatisSnapshotIndex();
long downloadedSnapshotIndex = omSnapshot.getRatisSnapshotIndex();
// The snapshot index downloaded from leader OM should match the ratis
// snapshot index on the leader OM
Assert.assertEquals("The snapshot index downloaded from leader OM does " +
"not match its ratis snapshot index",
leaderSnapshotIndex, downloadedSnapshotIndex);
}
}
|
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* PricingModel.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter.
*/
package com.google.api.ads.admanager.axis.v201905;
public class PricingModel implements java.io.Serializable {
private java.lang.String _value_;
private static java.util.HashMap _table_ = new java.util.HashMap();
// Constructor
protected PricingModel(java.lang.String value) {
_value_ = value;
_table_.put(_value_,this);
}
public static final java.lang.String _NET = "NET";
public static final java.lang.String _GROSS = "GROSS";
public static final java.lang.String _UNKNOWN = "UNKNOWN";
public static final PricingModel NET = new PricingModel(_NET);
public static final PricingModel GROSS = new PricingModel(_GROSS);
public static final PricingModel UNKNOWN = new PricingModel(_UNKNOWN);
public java.lang.String getValue() { return _value_;}
public static PricingModel fromValue(java.lang.String value)
throws java.lang.IllegalArgumentException {
PricingModel enumeration = (PricingModel)
_table_.get(value);
if (enumeration==null) throw new java.lang.IllegalArgumentException();
return enumeration;
}
public static PricingModel fromString(java.lang.String value)
throws java.lang.IllegalArgumentException {
return fromValue(value);
}
public boolean equals(java.lang.Object obj) {return (obj == this);}
public int hashCode() { return toString().hashCode();}
public java.lang.String toString() { return _value_;}
public java.lang.Object readResolve() throws java.io.ObjectStreamException { return fromValue(_value_);}
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.EnumSerializer(
_javaType, _xmlType);
}
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.EnumDeserializer(
_javaType, _xmlType);
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(PricingModel.class);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201905", "PricingModel"));
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
}
|
public class Muestra {
int idmuestra;
String codigo;
public Muestra(int idmuestra, String codigo) {
this.idmuestra = idmuestra;
this.codigo = codigo;
}
public int getIdmuestra() {
return idmuestra;
}
public void setIdmuestra(int idmuestra) {
this.idmuestra = idmuestra;
}
public String getCodigo() {
return codigo;
}
public void setCodigo(String codigo) {
this.codigo = codigo;
}
}
|
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package de.plushnikov.intellij.plugin.jps;
import com.intellij.compiler.server.BuildProcessParametersProvider;
import com.intellij.openapi.application.ReadAction;
import com.intellij.openapi.project.Project;
import de.plushnikov.intellij.plugin.Version;
import de.plushnikov.intellij.plugin.settings.ProjectSettings;
import de.plushnikov.intellij.plugin.util.LombokLibraryUtil;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public final class LombokBuildProcessParametersProvider extends BuildProcessParametersProvider {
private final Project myProject;
public LombokBuildProcessParametersProvider(@NotNull Project project) {
myProject = project;
}
@Override
public @NotNull List<String> getVMArguments() {
if(!ReadAction.nonBlocking(() -> LombokLibraryUtil.hasLombokLibrary(myProject)).executeSynchronously()) {
return Collections.emptyList();
}
List<String> result = new ArrayList<>();
final String lombokVersion = LombokLibraryUtil.getLombokVersionCached(myProject);
if (ProjectSettings.isEnabled(myProject, ProjectSettings.IS_LOMBOK_JPS_FIX_ENABLED) &&
Version.isLessThan(lombokVersion, Version.LAST_LOMBOK_VERSION_WITH_JPS_FIX)) {
result.add("-Djps.track.ap.dependencies=false");
}
return result;
}
}
|
package org.openplacereviews.opendb.service;
import org.junit.After;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.Spy;
import org.openplacereviews.opendb.OpenDBServer;
import org.openplacereviews.opendb.ops.OpBlock;
import org.openplacereviews.opendb.ops.OpBlockChain;
import org.openplacereviews.opendb.ops.OpBlockchainGettersTest;
import org.openplacereviews.opendb.psql.PostgreSQLServer;
import org.openplacereviews.opendb.util.JsonFormatter;
import org.openplacereviews.opendb.util.exception.FailedVerificationException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.SingleConnectionDataSource;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.transaction.support.TransactionTemplate;
import java.sql.Connection;
import java.sql.SQLException;
import static org.mockito.ArgumentMatchers.any;
import static org.openplacereviews.opendb.ObjectGeneratorTest.generateMetadataDB;
import static org.openplacereviews.opendb.VariableHelperTest.serverKeyPair;
import static org.openplacereviews.opendb.VariableHelperTest.serverName;
public class OpBlockchainGettersDbAccessTest {
@ClassRule
public static final PostgreSQLServer databaseServer = new PostgreSQLServer();
@Spy
@InjectMocks
private DBConsensusManager dbConsensusManager;
@Spy
@InjectMocks
private DBSchemaManager dbSchemaManager;
@Spy
@InjectMocks
private FileBackupManager fileBackupManager;
@Spy
private JsonFormatter jsonFormatter;
private OpBlockchainGettersTest opBlockchainGettersTest;
private JdbcTemplate jdbcTemplate;
private OpenDBServer.MetadataDb metadataDb;
@Before
public void beforeEachTest() throws SQLException, FailedVerificationException {
MockitoAnnotations.initMocks(this);
Connection connection = databaseServer.getConnection();
this.jdbcTemplate = new JdbcTemplate(new SingleConnectionDataSource(connection, false));
this.opBlockchainGettersTest = new OpBlockchainGettersTest();
this.opBlockchainGettersTest.beforeEachTestMethod();
DataSourceTransactionManager txManager = new DataSourceTransactionManager();
txManager.setDataSource(jdbcTemplate.getDataSource());
TransactionTemplate txTemplate = new TransactionTemplate();
txTemplate.setTransactionManager(txManager);
ReflectionTestUtils.setField(dbConsensusManager, "jdbcTemplate", jdbcTemplate);
ReflectionTestUtils.setField(dbConsensusManager, "dbSchema", dbSchemaManager);
ReflectionTestUtils.setField(dbConsensusManager, "backupManager", fileBackupManager);
ReflectionTestUtils.setField(dbConsensusManager, "txTemplate", txTemplate);
Mockito.doCallRealMethod().when(dbConsensusManager).insertBlock(any());
Mockito.doNothing().when(fileBackupManager).init();
metadataDb = new OpenDBServer.MetadataDb();
generateMetadataDB(metadataDb, jdbcTemplate);
dbConsensusManager.init(metadataDb);
}
@After
public void afterEachTest() throws Exception {
databaseServer.wipeDatabase();
}
@Test
public void testGetLastBlockFullHashIfBlockExistWithDBAccess() throws FailedVerificationException {
opBlockchainGettersTest.blc.createBlock(serverName, serverKeyPair);
OpBlockChain blockChain = generateBlockchainWithDBAccess();
opBlockchainGettersTest.testGetLastBlockFullHashIfBlockExist(blockChain);
}
@Test
public void testGetLastBlockFullHashIfBlockIsNotExistWithDBAccess() {
OpBlockChain blockChain = generateBlockchainWithDBAccess();
opBlockchainGettersTest.testGetLastBlockFullHashIfBlockIsNotExist(blockChain);
}
@Test
public void testGetLastBlockRawHashHashIfBlockExistWithDBAccess() throws FailedVerificationException {
opBlockchainGettersTest.blc.createBlock(serverName, serverKeyPair);
OpBlockChain blockChain = generateBlockchainWithDBAccess();
opBlockchainGettersTest.testGetLastBlockRawHashHashIfBlockExist(blockChain);
}
@Test
public void testGetLastBlockRawHashIfBlockIsNotExistWithDBAccess() {
OpBlockChain blockChain = generateBlockchainWithDBAccess();
opBlockchainGettersTest.testGetLastBlockRawHashIfBlockIsNotExist(blockChain);
}
@Test
public void testGetSuperBlockHashWithDBAccess() throws FailedVerificationException {
opBlockchainGettersTest.blc.createBlock(serverName, serverKeyPair);
OpBlockChain blockChain = generateBlockchainWithDBAccess();
opBlockchainGettersTest.testGetSuperBlockHash(blockChain);
}
@Test
public void testGetSuperBlockHashIfSuperBlockWasNotCreatedWithDBAccess() {
OpBlockChain blockChain = generateBlockchainWithDBAccess();
opBlockchainGettersTest.testGetSuperBlockHashIfSuperBlockWasNotCreated(blockChain);
}
@Test
public void testGetSuperBlockSizeWithDBAccess() throws FailedVerificationException {
opBlockchainGettersTest.blc.createBlock(serverName, serverKeyPair);
OpBlockChain blockChain = generateBlockchainWithDBAccess();
opBlockchainGettersTest.testGetSuperBlockSize(blockChain);
}
@Test
public void testGetSuperblockHeadersIfBlockWasNotCreatedWithDBAccess() {
OpBlockChain blockChain = generateBlockchainWithDBAccess();
opBlockchainGettersTest.testGetSuperblockHeadersIfBlockWasNotCreated(blockChain);
}
@Test
public void testGetSuperblockHeadersWithDBAccess() throws FailedVerificationException {
opBlockchainGettersTest.blc.createBlock(serverName, serverKeyPair);
OpBlockChain blockChain = generateBlockchainWithDBAccess();
opBlockchainGettersTest.testGetSuperblockHeaders(blockChain);
}
@Test
public void testGetSuperblockFullBlocksIfBlockWasNotCreatedWithDBAccess() {
OpBlockChain blockChain = generateBlockchainWithDBAccess();
opBlockchainGettersTest.testGetSuperblockFullBlocksIfBlockWasNotCreated(blockChain);
}
@Test
public void testGetSuperblockFullBlocksWithDBAccess() throws FailedVerificationException {
OpBlock opBlock = opBlockchainGettersTest.blc.createBlock(serverName, serverKeyPair);
opBlock.getOperations().forEach(opOperation -> dbConsensusManager.insertOperation(opOperation));
dbConsensusManager.insertBlock(opBlock);
OpBlockChain blockChain = generateBlockchainWithDBAccess();
opBlockchainGettersTest.testGetSuperblockFullBlocks(blockChain);
}
public void testGetSuperblockObjectsWithDBAccess() throws FailedVerificationException {
opBlockchainGettersTest.blc.createBlock(serverName, serverKeyPair);
OpBlockChain blockChain = generateBlockchainWithDBAccess();
opBlockchainGettersTest.testGetSuperblockObjects(blockChain);
}
@Test
public void testGetBlockHeadersWithDBAccess() throws FailedVerificationException {
opBlockchainGettersTest.blc.createBlock(serverName, serverKeyPair);
OpBlockChain blockChain = generateBlockchainWithDBAccess();
opBlockchainGettersTest.testGetBlockHeaders(blockChain);
}
@Test
public void testGetBlockHeadersByIdWithDBAccess() throws FailedVerificationException {
opBlockchainGettersTest.blc.createBlock(serverName, serverKeyPair);
OpBlockChain blockChain = generateBlockchainWithDBAccess();
opBlockchainGettersTest.testGetBlockHeadersById(blockChain);
}
@Test
public void testGetBlockHeadersByNotExistingIdWithDBAccess() {
OpBlockChain blockChain = generateBlockchainWithDBAccess();
opBlockchainGettersTest.testGetBlockHeadersByNotExistingId(blockChain);
}
@Test
public void testGetBlockHeaderByRawHashWithDBAccess() throws FailedVerificationException {
opBlockchainGettersTest.blc.createBlock(serverName, serverKeyPair);
OpBlockChain blockChain = generateBlockchainWithDBAccess();
opBlockchainGettersTest.testGetBlockHeaderByRawHash(blockChain);
}
@Test
public void testGetBlockHeaderByNotExistingRawHashWithDBAccess() {
OpBlockChain blockChain = generateBlockchainWithDBAccess();
opBlockchainGettersTest.testGetBlockHeaderByNotExistingRawHash(blockChain);
}
@Test
public void testGetFullBlockByRawHashWithDBAccess() throws FailedVerificationException {
OpBlock opBlock = opBlockchainGettersTest.blc.createBlock(serverName, serverKeyPair);
opBlock.getOperations().forEach(opOperation1 -> dbConsensusManager.insertOperation(opOperation1));
OpBlockChain blockChain = generateBlockchainWithDBAccess();
dbConsensusManager.insertBlock(opBlock);
opBlockchainGettersTest.testGetFullBlockByRawHash(blockChain);
}
@Test
public void testGetFullBlockByNotExistingRawHashWithDBAccess() {
OpBlockChain blockChain = generateBlockchainWithDBAccess();
opBlockchainGettersTest.testGetFullBlockByNotExistingRawHash(blockChain);
}
@Test
public void testGetOperationByNotExistingHashWithDBAccess() {
OpBlockChain blockChain = generateBlockchainWithDBAccess();
opBlockchainGettersTest.testGetOperationByNotExistingHash(blockChain,
"10c5978d2466b67505d2d94a9a0f29695e03bf11893a4a5cac3cd700aa757dd9");
}
private OpBlockChain generateBlockchainWithDBAccess() {
return new OpBlockChain(opBlockchainGettersTest.blc.getParent(), opBlockchainGettersTest.blc.getBlockHeaders(0),
dbConsensusManager.createDbAccess(
opBlockchainGettersTest.blc.getSuperBlockHash(),
opBlockchainGettersTest.blc.getSuperblockHeaders()), opBlockchainGettersTest.blc.getRules());
}
}
|
package org.hl7.fhir.r5.model.codesystems;
/*
* #%L
* org.hl7.fhir.r5
* %%
* Copyright (C) 2014 - 2019 Health Level 7
* %%
* 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.
* #L%
*/
/*
Copyright (c) 2011+, HL7, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
// Generated on Thu, Oct 17, 2019 09:42+1100 for FHIR v4.1.0
import org.hl7.fhir.exceptions.FHIRException;
public enum DiagnosticReportStatus {
/**
* The existence of the report is registered, but there is nothing yet available.
*/
REGISTERED,
/**
* This is a partial (e.g. initial, interim or preliminary) report: data in the report may be incomplete or unverified.
*/
PARTIAL,
/**
* Verified early results are available, but not all results are final.
*/
PRELIMINARY,
/**
* The report is complete and verified by an authorized person.
*/
FINAL,
/**
* Subsequent to being final, the report has been modified. This includes any change in the results, diagnosis, narrative text, or other content of a report that has been issued.
*/
AMENDED,
/**
* Subsequent to being final, the report has been modified to correct an error in the report or referenced results.
*/
CORRECTED,
/**
* Subsequent to being final, the report has been modified by adding new content. The existing content is unchanged.
*/
APPENDED,
/**
* The report is unavailable because the measurement was not started or not completed (also sometimes called "aborted").
*/
CANCELLED,
/**
* The report has been withdrawn following a previous final release. This electronic record should never have existed, though it is possible that real-world decisions were based on it. (If real-world activity has occurred, the status should be "cancelled" rather than "entered-in-error".).
*/
ENTEREDINERROR,
/**
* The authoring/source system does not know which of the status values currently applies for this observation. Note: This concept is not to be used for "other" - one of the listed statuses is presumed to apply, but the authoring/source system does not know which.
*/
UNKNOWN,
/**
* added to help the parsers
*/
NULL;
public static DiagnosticReportStatus fromCode(String codeString) throws FHIRException {
if (codeString == null || "".equals(codeString))
return null;
if ("registered".equals(codeString))
return REGISTERED;
if ("partial".equals(codeString))
return PARTIAL;
if ("preliminary".equals(codeString))
return PRELIMINARY;
if ("final".equals(codeString))
return FINAL;
if ("amended".equals(codeString))
return AMENDED;
if ("corrected".equals(codeString))
return CORRECTED;
if ("appended".equals(codeString))
return APPENDED;
if ("cancelled".equals(codeString))
return CANCELLED;
if ("entered-in-error".equals(codeString))
return ENTEREDINERROR;
if ("unknown".equals(codeString))
return UNKNOWN;
throw new FHIRException("Unknown DiagnosticReportStatus code '"+codeString+"'");
}
public String toCode() {
switch (this) {
case REGISTERED: return "registered";
case PARTIAL: return "partial";
case PRELIMINARY: return "preliminary";
case FINAL: return "final";
case AMENDED: return "amended";
case CORRECTED: return "corrected";
case APPENDED: return "appended";
case CANCELLED: return "cancelled";
case ENTEREDINERROR: return "entered-in-error";
case UNKNOWN: return "unknown";
default: return "?";
}
}
public String getSystem() {
return "http://hl7.org/fhir/diagnostic-report-status";
}
public String getDefinition() {
switch (this) {
case REGISTERED: return "The existence of the report is registered, but there is nothing yet available.";
case PARTIAL: return "This is a partial (e.g. initial, interim or preliminary) report: data in the report may be incomplete or unverified.";
case PRELIMINARY: return "Verified early results are available, but not all results are final.";
case FINAL: return "The report is complete and verified by an authorized person.";
case AMENDED: return "Subsequent to being final, the report has been modified. This includes any change in the results, diagnosis, narrative text, or other content of a report that has been issued.";
case CORRECTED: return "Subsequent to being final, the report has been modified to correct an error in the report or referenced results.";
case APPENDED: return "Subsequent to being final, the report has been modified by adding new content. The existing content is unchanged.";
case CANCELLED: return "The report is unavailable because the measurement was not started or not completed (also sometimes called \"aborted\").";
case ENTEREDINERROR: return "The report has been withdrawn following a previous final release. This electronic record should never have existed, though it is possible that real-world decisions were based on it. (If real-world activity has occurred, the status should be \"cancelled\" rather than \"entered-in-error\".).";
case UNKNOWN: return "The authoring/source system does not know which of the status values currently applies for this observation. Note: This concept is not to be used for \"other\" - one of the listed statuses is presumed to apply, but the authoring/source system does not know which.";
default: return "?";
}
}
public String getDisplay() {
switch (this) {
case REGISTERED: return "Registered";
case PARTIAL: return "Partial";
case PRELIMINARY: return "Preliminary";
case FINAL: return "Final";
case AMENDED: return "Amended";
case CORRECTED: return "Corrected";
case APPENDED: return "Appended";
case CANCELLED: return "Cancelled";
case ENTEREDINERROR: return "Entered in Error";
case UNKNOWN: return "Unknown";
default: return "?";
}
}
}
|
package pinacolada.cards.fool.series.Elsword;
import com.badlogic.gdx.graphics.Color;
import com.megacrit.cardcrawl.cards.AbstractCard;
import com.megacrit.cardcrawl.cards.CardGroup;
import com.megacrit.cardcrawl.cards.DamageInfo;
import com.megacrit.cardcrawl.characters.AbstractPlayer;
import com.megacrit.cardcrawl.core.AbstractCreature;
import com.megacrit.cardcrawl.monsters.AbstractMonster;
import eatyourbeets.actions.special.RefreshHandLayout;
import eatyourbeets.powers.CombatStats;
import pinacolada.cards.base.CardUseInfo;
import pinacolada.cards.base.PCLAffinity;
import pinacolada.cards.base.PCLCardData;
import pinacolada.cards.base.PCLCardPreview;
import pinacolada.cards.fool.FoolCard;
import pinacolada.cards.fool.special.Eve_Drone;
import pinacolada.cards.fool.special.OrbCore;
import pinacolada.effects.AttackEffects;
import pinacolada.effects.SFX;
import pinacolada.effects.VFX;
import pinacolada.powers.FoolClickablePower;
import pinacolada.powers.PCLCombatStats;
import pinacolada.powers.PowerTriggerConditionType;
import pinacolada.utilities.PCLActions;
import pinacolada.utilities.PCLGameEffects;
import pinacolada.utilities.PCLJUtils;
import java.util.UUID;
public class Eve extends FoolCard
{
public static final PCLCardData DATA = Register(Eve.class)
.SetPower(3, CardRarity.RARE)
.SetMaxCopies(1)
.SetSeriesFromClassPackage()
.SetMultiformData(2, false)
.PostInitialize(data ->
{
data.AddPreview(new Eve_Drone(0), false);
for (OrbCore core : OrbCore.GetAllCores())
{
data.AddPreview(core, false);
}
});
public static final PCLCardPreview DRONE_PREVIEW_ALT = new PCLCardPreview(new Eve_Drone(1), false);
private static final int POWER_ENERGY_COST = 2;
private static final int CHOICES = 3;
public Eve()
{
super(DATA);
Initialize(0, 0, 2, 0);
SetUpgrade(0,0,0,1);
SetAffinity_Blue(1);
SetAffinity_Light(1);
SetAffinity_Dark(1);
SetAffinity_Silver(1);
SetDelayed(true);
SetRetainOnce(true);
}
@Override
public int SetForm(Integer form, int timesUpgraded) {
if (form == 1) {
LoadImage("_Light");
}
else {
LoadImage(null);
}
return super.SetForm(form, timesUpgraded);
}
@Override
public PCLCardPreview GetCardPreview()
{
return auxiliaryData.form == 1 && cardData.previews.GetIndex() == 0 ? DRONE_PREVIEW_ALT : super.GetCardPreview();
}
@Override
public void OnUse(AbstractPlayer p, AbstractMonster m, CardUseInfo info)
{
PCLActions.Bottom.Add(OrbCore.SelectCoreAction(name, 1)
.AddCallback(c -> {if (c.size() > 0) {
PCLActions.Bottom.PlayCard(c.get(0), m);}}));
if (secondaryValue > 0)
{
PCLActions.Bottom.GainOrbSlots(secondaryValue);
}
PCLActions.Bottom.StackPower(new EvePower(p, magicNumber, auxiliaryData.form));
}
public static class EvePower extends FoolClickablePower
{
private static int[] availableChoices = new int[] {0, 0};
private static UUID battleID;
public EvePower(AbstractCreature owner, int amount, int option)
{
super(owner, Eve.DATA, PowerTriggerConditionType.Energy, POWER_ENERGY_COST);
if (CombatStats.BattleID != battleID)
{
battleID = CombatStats.BattleID;
availableChoices = new int[] {0, 0};
}
availableChoices[option] = 1;
this.triggerCondition.SetOneUsePerPower(true);
Initialize(amount);
}
@Override
public void OnUse(AbstractMonster m, int cost)
{
super.OnUse(m, cost);
final CardGroup choice = new CardGroup(CardGroup.CardGroupType.UNSPECIFIED);
if (availableChoices[0] == 1) {
choice.addToTop(new Eve_Drone(0));
}
if (availableChoices[1] == 1) {
choice.addToTop(new Eve_Drone(1));
}
PCLActions.Bottom.SelectFromPile(name, 1, choice)
.SetOptions(false, false)
.AddCallback(cards ->
{
PCLActions.Bottom.MakeCardInDrawPile(cards.get(0));
PCLActions.Bottom.MakeCardInHand(cards.get(0));
PCLActions.Bottom.Add(new RefreshHandLayout());
});
}
@Override
public void onAfterCardPlayed(AbstractCard usedCard)
{
super.onAfterCardPlayed(usedCard);
if (PCLCombatStats.MatchingSystem.IsSynergizing(usedCard))
{
PCLAffinity lowestAffinity = PCLJUtils.FindMin(PCLAffinity.Extended(), af -> PCLCombatStats.MatchingSystem.GetAffinityLevel(af,true));
final int damage = PCLCombatStats.MatchingSystem.GetAffinityLevel(lowestAffinity,true);
if (damage > 0)
{
//GameEffects.Queue.BorderFlash(Color.SKY);
for (int i = 0; i < amount; i++)
{
PCLActions.Bottom.DealDamageToRandomEnemy(damage, DamageInfo.DamageType.THORNS, AttackEffects.NONE)
.SetDamageEffect(enemy ->
{
SFX.Play(SFX.ATTACK_MAGIC_BEAM_SHORT, 0.9f, 1.1f);
PCLGameEffects.List.Add(VFX.SmallLaser(owner.hb, enemy.hb, Color.CYAN));
return 0f;
});
}
this.flash();
this.updateDescription();
}
}
}
@Override
public String GetUpdatedDescription()
{
return FormatDescription(0, availableChoices[0] == 1 && availableChoices[1] == 1 ? DATA.Strings.EXTENDED_DESCRIPTION[1] : "");
}
}
}
|
/*
* Copyright (c) 2017 m2049r
*
* 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.m2049r.xmrwallet.fragment.send;
import android.content.Context;
import android.nfc.NfcManager;
import android.os.Bundle;
import android.text.Editable;
import android.text.Html;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.Patterns;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import com.google.android.material.textfield.TextInputLayout;
import com.m2049r.xmrwallet.R;
import com.m2049r.xmrwallet.data.BarcodeData;
import com.m2049r.xmrwallet.data.Crypto;
import com.m2049r.xmrwallet.data.TxData;
import com.m2049r.xmrwallet.data.TxDataBtc;
import com.m2049r.xmrwallet.data.UserNotes;
import com.m2049r.xmrwallet.model.PendingTransaction;
import com.m2049r.xmrwallet.model.Wallet;
import com.m2049r.xmrwallet.util.Helper;
import com.m2049r.xmrwallet.util.OpenAliasHelper;
import com.m2049r.xmrwallet.util.ServiceHelper;
import com.m2049r.xmrwallet.util.validator.BitcoinAddressType;
import com.m2049r.xmrwallet.util.validator.BitcoinAddressValidator;
import com.m2049r.xmrwallet.util.validator.EthAddressValidator;
import com.unstoppabledomains.exceptions.ns.NamingServiceException;
import com.unstoppabledomains.resolution.DomainResolution;
import com.unstoppabledomains.resolution.Resolution;
import com.unstoppabledomains.resolution.naming.service.NamingServiceType;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import timber.log.Timber;
public class SendAddressWizardFragment extends SendWizardFragment {
static final int INTEGRATED_ADDRESS_LENGTH = 106;
public static SendAddressWizardFragment newInstance(Listener listener) {
SendAddressWizardFragment instance = new SendAddressWizardFragment();
instance.setSendListener(listener);
return instance;
}
Listener sendListener;
public void setSendListener(Listener listener) {
this.sendListener = listener;
}
public interface Listener {
void setBarcodeData(BarcodeData data);
BarcodeData getBarcodeData();
BarcodeData popBarcodeData();
void setMode(SendFragment.Mode mode);
TxData getTxData();
}
private EditText etDummy;
private TextInputLayout etAddress;
private TextInputLayout etNotes;
private TextView tvXmrTo;
private Map<Crypto, ImageButton> ibCrypto;
final private Set<Crypto> possibleCryptos = new HashSet<>();
private Crypto selectedCrypto = null;
private boolean resolvingOA = false;
OnScanListener onScanListener;
public interface OnScanListener {
void onScan();
}
private Crypto getCryptoForButton(ImageButton button) {
for (Map.Entry<Crypto, ImageButton> entry : ibCrypto.entrySet()) {
if (entry.getValue() == button) return entry.getKey();
}
return null;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Timber.d("onCreateView() %s", (String.valueOf(savedInstanceState)));
View view = inflater.inflate(R.layout.fragment_send_address, container, false);
if (Helper.ALLOW_SHIFT) {
tvXmrTo = view.findViewById(R.id.tvXmrTo);
ibCrypto = new HashMap<>();
for (Crypto crypto : Crypto.values()) {
final ImageButton button = view.findViewById(crypto.getButtonId());
ibCrypto.put(crypto, button);
button.setOnClickListener(v -> {
if (possibleCryptos.contains(crypto)) {
selectedCrypto = crypto;
updateCryptoButtons(false);
} else {
// show help what to do:
if (button.getId() != R.id.ibXMR) {
final String name = getResources().getStringArray(R.array.cryptos)[crypto.ordinal()];
final String symbol = getCryptoForButton(button).getSymbol();
tvXmrTo.setText(Html.fromHtml(getString(R.string.info_xmrto_help, name, symbol)));
tvXmrTo.setVisibility(View.VISIBLE);
} else {
tvXmrTo.setText(Html.fromHtml(getString(R.string.info_xmrto_help_xmr)));
tvXmrTo.setVisibility(View.VISIBLE);
}
}
});
}
updateCryptoButtons(true);
} else {
view.findViewById(R.id.llExchange).setVisibility(View.GONE);
}
etAddress = view.findViewById(R.id.etAddress);
etAddress.getEditText().setRawInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
etAddress.getEditText().setOnEditorActionListener(new TextView.OnEditorActionListener() {
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
// ignore ENTER
return ((event != null) && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER));
}
});
etAddress.getEditText().setOnFocusChangeListener((v, hasFocus) -> {
if (!hasFocus) {
String enteredAddress = etAddress.getEditText().getText().toString().trim();
goToOpenAlias(enteredAddress);
}
});
etAddress.getEditText().addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable editable) {
Timber.d("AFTER: %s", editable.toString());
etAddress.setError(null);
possibleCryptos.clear();
selectedCrypto = null;
final String address = etAddress.getEditText().getText().toString();
if (isIntegratedAddress(address)) {
Timber.d("isIntegratedAddress");
possibleCryptos.add(Crypto.XMR);
selectedCrypto = Crypto.XMR;
etAddress.setError(getString(R.string.info_paymentid_integrated));
sendListener.setMode(SendFragment.Mode.XMR);
} else if (isStandardAddress(address)) {
Timber.d("isStandardAddress");
possibleCryptos.add(Crypto.XMR);
selectedCrypto = Crypto.XMR;
sendListener.setMode(SendFragment.Mode.XMR);
}
if (!Helper.ALLOW_SHIFT) return;
if ((selectedCrypto == null) && isEthAddress(address)) {
Timber.d("isEthAddress");
possibleCryptos.add(Crypto.ETH);
selectedCrypto = Crypto.ETH;
tvXmrTo.setVisibility(View.VISIBLE);
sendListener.setMode(SendFragment.Mode.BTC);
}
if (possibleCryptos.isEmpty()) {
Timber.d("isBitcoinAddress");
for (BitcoinAddressType type : BitcoinAddressType.values()) {
if (BitcoinAddressValidator.validate(address, type)) {
possibleCryptos.add(Crypto.valueOf(type.name()));
}
}
if (!possibleCryptos.isEmpty()) // found something in need of shifting!
sendListener.setMode(SendFragment.Mode.BTC);
if (possibleCryptos.size() == 1) {
selectedCrypto = (Crypto) possibleCryptos.toArray()[0];
}
}
if (possibleCryptos.isEmpty()) {
Timber.d("other");
// Makes the height of tvXmrTo consistent when invisible
tvXmrTo.setText(Html.fromHtml(getString(R.string.info_xmrto_help_xmr)));
tvXmrTo.setVisibility(View.INVISIBLE);
sendListener.setMode(SendFragment.Mode.XMR);
}
updateCryptoButtons(address.isEmpty());
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
});
final ImageButton bPasteAddress = view.findViewById(R.id.bPasteAddress);
bPasteAddress.setOnClickListener(v -> {
final String clip = Helper.getClipBoardText(getActivity());
if (clip == null) return;
// clean it up
final String address = clip.replaceAll("( +)|(\\r?\\n?)", "");
BarcodeData.fromString(address, (bc) -> requireActivity().runOnUiThread(() -> {
if (bc != null) {
processScannedData(bc);
final EditText et = etAddress.getEditText();
et.setSelection(et.getText().length());
etAddress.requestFocus();
} else {
Toast.makeText(getActivity(), getString(R.string.send_address_invalid), Toast.LENGTH_SHORT).show();
}
}));
});
etNotes = view.findViewById(R.id.etNotes);
etNotes.getEditText().setRawInputType(InputType.TYPE_CLASS_TEXT);
etNotes.getEditText().
setOnEditorActionListener((v, actionId, event) -> {
if ((event != null && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER) && (event.getAction() == KeyEvent.ACTION_DOWN))
|| (actionId == EditorInfo.IME_ACTION_DONE)) {
etDummy.requestFocus();
return true;
}
return false;
});
final View cvScan = view.findViewById(R.id.bScan);
cvScan.setOnClickListener(v -> onScanListener.onScan());
etDummy = view.findViewById(R.id.etDummy);
etDummy.setRawInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
etDummy.requestFocus();
View tvNfc = view.findViewById(R.id.tvNfc);
NfcManager manager = (NfcManager) getContext().getSystemService(Context.NFC_SERVICE);
if ((manager != null) && (manager.getDefaultAdapter() != null))
tvNfc.setVisibility(View.VISIBLE);
return view;
}
private void selectedCrypto(Crypto crypto) {
final ImageButton button = ibCrypto.get(crypto);
button.setImageResource(crypto.getIconEnabledId());
button.setImageAlpha(255);
button.setEnabled(true);
}
private void possibleCrypto(Crypto crypto) {
final ImageButton button = ibCrypto.get(crypto);
button.setImageResource(crypto.getIconDisabledId());
button.setImageAlpha(255);
button.setEnabled(true);
}
private void impossibleCrypto(Crypto crypto) {
final ImageButton button = ibCrypto.get(crypto);
button.setImageResource(crypto.getIconDisabledId());
button.setImageAlpha(128);
button.setEnabled(true);
}
private void updateCryptoButtons(boolean noAddress) {
if (!Helper.ALLOW_SHIFT) return;
for (Crypto crypto : Crypto.values()) {
if (crypto == selectedCrypto) {
selectedCrypto(crypto);
} else if (possibleCryptos.contains(crypto)) {
possibleCrypto(crypto);
} else {
impossibleCrypto(crypto);
}
}
if ((selectedCrypto != null) && (selectedCrypto != Crypto.XMR)) {
tvXmrTo.setText(Html.fromHtml(getString(R.string.info_xmrto, selectedCrypto.getSymbol())));
tvXmrTo.setVisibility(View.VISIBLE);
} else if ((selectedCrypto == null) && (possibleCryptos.size() > 1)) {
tvXmrTo.setText(Html.fromHtml(getString(R.string.info_xmrto_ambiguous)));
tvXmrTo.setVisibility(View.VISIBLE);
} else {
// Makes the height of tvXmrTo consistent when invisible
tvXmrTo.setText(Html.fromHtml(getString(R.string.info_xmrto_help_xmr)));
tvXmrTo.setVisibility(View.INVISIBLE);
}
if (noAddress) {
selectedCrypto(Crypto.XMR);
}
}
private void goToOpenAlias(String enteredAddress) {
String dnsOA = dnsFromOpenAlias(enteredAddress);
Timber.d("OpenAlias is %s", dnsOA);
if (dnsOA != null) {
processOpenAlias(dnsOA);
} else if (enteredAddress.length() == 0 || checkAddressNoError()) {
etAddress.setErrorEnabled(false);
} else {
// Not all UD address match Patterns.DOMAIN_NAME (eg. .888, .x)
processUD(enteredAddress);
}
}
private void processOpenAlias(String dnsOA) {
if (resolvingOA) return; // already resolving - just wait
sendListener.popBarcodeData();
resolvingOA = true;
etAddress.setError(getString(R.string.send_address_resolve_openalias));
OpenAliasHelper.resolve(dnsOA, new OpenAliasHelper.OnResolvedListener() {
@Override
public void onResolved(Map<Crypto, BarcodeData> dataMap) {
resolvingOA = false;
BarcodeData barcodeData = dataMap.get(Crypto.XMR);
if (barcodeData == null) barcodeData = dataMap.get(Crypto.BTC);
if (barcodeData != null) {
Timber.d("Security=%s, %s", barcodeData.security.toString(), barcodeData.address);
processScannedData(barcodeData);
} else {
Timber.d("NO XMR OPENALIAS TXT FOUND");
processUD(dnsOA);
}
}
@Override
public void onFailure() {
resolvingOA = false;
Timber.e("OA FAILED");
processUD(dnsOA);
}
});
}
private void processUD(String udString) {
sendListener.popBarcodeData();
DomainResolution resolution = Resolution.builder()
.providerUrl(NamingServiceType.ENS, "https://cloudflare-eth.com")
.build();
final boolean[] domainIsUD = {false};
final String[] address = {null};
final Crypto[] crypto = {null};
etAddress.setError(getString(R.string.send_address_resolve_ud));
new Thread(() -> {
for (Crypto currentCrypto: Crypto.values()) {
try {
address[0] = resolution.getAddress(udString, currentCrypto.getSymbol().toLowerCase());
crypto[0] = currentCrypto;
domainIsUD[0] = true;
break;
} catch (NamingServiceException e) {
Timber.d(e.getLocalizedMessage());
switch (e.getCode()) {
case UnknownCurrency:
case RecordNotFound:
domainIsUD[0] = true;
break;
default:
domainIsUD[0] = false;
break;
}
}
}
requireActivity().runOnUiThread(() -> {
if (domainIsUD[0]) {
if (crypto[0] == null) {
Timber.d("Unsupported UD address %s", udString);
etAddress.setError(getString(R.string.send_address_no_ud_records));
} else {
BarcodeData barcodeData = new BarcodeData(crypto[0], address[0], udString,
null, null, BarcodeData.Security.NORMAL);
processScannedData(barcodeData);
}
} else {
Timber.d("Non ENS / UD address %s", udString);
etAddress.setError(getString(R.string.send_address_not_openalias));
}
});
}).start();
}
private boolean checkAddressNoError() {
return selectedCrypto != null;
}
private boolean checkAddress() {
boolean ok = checkAddressNoError();
if (possibleCryptos.isEmpty()) {
etAddress.setError(getString(R.string.send_address_invalid));
} else {
etAddress.setError(null);
}
return ok;
}
private boolean isStandardAddress(String address) {
return Wallet.isAddressValid(address);
}
private boolean isIntegratedAddress(String address) {
return (address.length() == INTEGRATED_ADDRESS_LENGTH)
&& Wallet.isAddressValid(address);
}
private boolean isBitcoinishAddress(String address) {
return BitcoinAddressValidator.validate(address, BitcoinAddressType.BTC)
||
BitcoinAddressValidator.validate(address, BitcoinAddressType.LTC)
||
BitcoinAddressValidator.validate(address, BitcoinAddressType.DASH);
}
private boolean isEthAddress(String address) {
return EthAddressValidator.validate(address);
}
private void shakeAddress() {
if (possibleCryptos.size() > 1) { // address ambiguous
for (Crypto crypto : Crypto.values()) {
if (possibleCryptos.contains(crypto)) {
ibCrypto.get(crypto).startAnimation(Helper.getShakeAnimation(getContext()));
}
}
} else {
etAddress.startAnimation(Helper.getShakeAnimation(getContext()));
}
}
@Override
public boolean onValidateFields() {
if (!checkAddressNoError()) {
shakeAddress();
String enteredAddress = etAddress.getEditText().getText().toString().trim();
goToOpenAlias(enteredAddress);
return false;
}
if (sendListener != null) {
TxData txData = sendListener.getTxData();
if (txData instanceof TxDataBtc) {
((TxDataBtc) txData).setBtcAddress(etAddress.getEditText().getText().toString());
((TxDataBtc) txData).setBtcSymbol(selectedCrypto.getSymbol());
txData.setDestinationAddress(null);
ServiceHelper.ASSET = selectedCrypto.getSymbol().toLowerCase();
} else {
txData.setDestinationAddress(etAddress.getEditText().getText().toString());
ServiceHelper.ASSET = null;
}
txData.setUserNotes(new UserNotes(etNotes.getEditText().getText().toString()));
txData.setPriority(PendingTransaction.Priority.Priority_Default);
txData.setMixin(SendFragment.MIXIN);
}
return true;
}
@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
if (context instanceof OnScanListener) {
onScanListener = (OnScanListener) context;
} else {
throw new ClassCastException(context.toString()
+ " must implement ScanListener");
}
}
// QR Scan Stuff
@Override
public void onResume() {
super.onResume();
Timber.d("onResume");
processScannedData();
}
public void processScannedData(BarcodeData barcodeData) {
sendListener.setBarcodeData(barcodeData);
if (isResumed())
processScannedData();
}
public void processScannedData() {
BarcodeData barcodeData = sendListener.getBarcodeData();
if (barcodeData != null) {
Timber.d("GOT DATA");
if (!Helper.ALLOW_SHIFT && (barcodeData.asset != Crypto.XMR)) {
Timber.d("BUT ONLY XMR SUPPORTED");
barcodeData = null;
sendListener.setBarcodeData(barcodeData);
}
if (barcodeData.address != null) {
etAddress.getEditText().setText(barcodeData.address);
possibleCryptos.clear();
selectedCrypto = null;
if (barcodeData.isAmbiguous()) {
possibleCryptos.addAll(barcodeData.ambiguousAssets);
} else {
possibleCryptos.add(barcodeData.asset);
selectedCrypto = barcodeData.asset;
}
if (Helper.ALLOW_SHIFT)
updateCryptoButtons(false);
if (checkAddress()) {
if (barcodeData.security == BarcodeData.Security.OA_NO_DNSSEC)
etAddress.setError(getString(R.string.send_address_no_dnssec));
else if (barcodeData.security == BarcodeData.Security.OA_DNSSEC)
etAddress.setError(getString(R.string.send_address_openalias));
}
} else {
etAddress.getEditText().getText().clear();
etAddress.setError(null);
}
String scannedNotes = barcodeData.addressName;
if (scannedNotes == null) {
scannedNotes = barcodeData.description;
} else if (barcodeData.description != null) {
scannedNotes = scannedNotes + ": " + barcodeData.description;
}
if (scannedNotes != null) {
etNotes.getEditText().setText(scannedNotes);
} else {
etNotes.getEditText().getText().clear();
etNotes.setError(null);
}
} else
Timber.d("barcodeData=null");
}
@Override
public void onResumeFragment() {
super.onResumeFragment();
Timber.d("onResumeFragment()");
etDummy.requestFocus();
}
String dnsFromOpenAlias(String openalias) {
Timber.d("checking openalias candidate %s", openalias);
if (Patterns.DOMAIN_NAME.matcher(openalias).matches()) return openalias;
if (Patterns.EMAIL_ADDRESS.matcher(openalias).matches()) {
openalias = openalias.replaceFirst("@", ".");
if (Patterns.DOMAIN_NAME.matcher(openalias).matches()) return openalias;
}
return null; // not an openalias
}
}
|
package com.github.zhve.ideaplugin;
/*
* 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.
*/
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.factory.ArtifactFactory;
import org.apache.maven.artifact.metadata.ArtifactMetadataSource;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.resolver.*;
import org.apache.maven.artifact.resolver.filter.ExcludesArtifactFilter;
import org.apache.maven.artifact.versioning.InvalidVersionSpecificationException;
import org.apache.maven.artifact.versioning.VersionRange;
import org.apache.maven.model.Dependency;
import org.apache.maven.model.Exclusion;
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.project.MavenProject;
import java.io.File;
import java.util.*;
/**
* @author Vasiliy Zhukov
* @since 5/31/2014
*/
public class ArtifactDependencyResolver {
private Log log;
private ArtifactFactory artifactFactory;
private ArtifactResolver artifactResolver;
private ArtifactRepository localRepository;
private ArtifactMetadataSource artifactMetadataSource;
public ArtifactDependencyResolver(Log log, ArtifactFactory artifactFactory, ArtifactResolver artifactResolver, ArtifactRepository localRepository, ArtifactMetadataSource artifactMetadataSource) {
this.log = log;
this.artifactFactory = artifactFactory;
this.artifactResolver = artifactResolver;
this.localRepository = localRepository;
this.artifactMetadataSource = artifactMetadataSource;
}
public Map<MavenProject, DependencyData> findDependencies(List<MavenProject> reactorProjects) throws InvalidVersionSpecificationException {
// collect ids
Set<Artifact> reactorArtifacts = new HashSet<Artifact>();
log.info("");
log.info("Reactor Artifacts");
log.info("");
for (MavenProject reactorProject : reactorProjects) {
log.info(reactorProject.getArtifact().getId());
reactorArtifacts.add(reactorProject.getArtifact());
}
// Resolve reactor dependencies
Map<MavenProject, DependencyData> dependencyDataMap = findDependencies(log, artifactFactory, reactorArtifacts, reactorProjects);
// Resolve remote dependency transitively
Map<MavenProject, DependencyData> dependencyDataNewMap = new LinkedHashMap<MavenProject, DependencyData>();
for (Map.Entry<MavenProject, DependencyData> entry : dependencyDataMap.entrySet()) {
MavenProject project = entry.getKey();
log.info("");
log.info("Resolve Transitively: " + project.getArtifact().getId());
log.info("");
DependencyData dependencyData = entry.getValue();
List<Artifact> remoteData = new ArrayList<Artifact>();
List<Artifact> reactorData = new ArrayList<Artifact>(dependencyData.getReactorList());
List<Artifact> remoteUnresolvedList = new ArrayList<Artifact>(dependencyData.getRemoteList());
tryResolve(project, reactorArtifacts, remoteData, reactorData, remoteUnresolvedList);
dependencyDataNewMap.put(project, new DependencyData(remoteData, reactorData));
}
return dependencyDataNewMap;
}
/**
* Transitive resolve all dependencies for reactor projects
*
* @param artifactFactory standard Maven's factory to create artifacts
* @param reactorArtifacts reactor artifacts
* @param reactorProjects reactor projects
* @return dependency map: reactor project -> dependency data
* @throws InvalidVersionSpecificationException error
*/
private Map<MavenProject, DependencyData> findDependencies(Log log, ArtifactFactory artifactFactory, Set<Artifact> reactorArtifacts, List<MavenProject> reactorProjects) throws InvalidVersionSpecificationException {
// artifact -> all transitive dependencies
Map<Artifact, DependencyData> dependencyMap = new HashMap<Artifact, DependencyData>();
log.info("");
log.info("Detect Dependencies");
for (MavenProject project : reactorProjects) {
log.info("");
log.info(project.getId());
List<Artifact> remoteData = new ArrayList<Artifact>();
List<Artifact> reactorData = new ArrayList<Artifact>();
for (Object object : project.getDependencies()) {
Dependency dependency = (Dependency) object;
Artifact dependencyArtifact = toDependencyArtifact(artifactFactory, dependency);
boolean reactor = reactorArtifacts.contains(dependencyArtifact);
String id = dependencyArtifact.getId() + ":" + dependencyArtifact.getScope();
if ("jar".equals(dependencyArtifact.getType())) {
if (reactor) {
log.info("R " + id);
reactorData.add(dependencyArtifact);
} else {
log.info(" " + id);
remoteData.add(dependencyArtifact);
}
} else {
log.info("O " + id + " (type=" + dependencyArtifact.getType() + ")");
}
}
// save dependency data for project
dependencyMap.put(project.getArtifact(), new DependencyData(remoteData, reactorData));
}
log.info("");
log.info("Resolve Dependencies");
Map<MavenProject, DependencyData> result = new LinkedHashMap<MavenProject, DependencyData>();
for (MavenProject project : reactorProjects) {
log.info("");
log.info(project.getId());
Map<String, Artifact> reactorData = new LinkedHashMap<String, Artifact>();
Map<String, Artifact> remoteData = new LinkedHashMap<String, Artifact>();
Queue<Artifact> queue = new LinkedList<Artifact>();
queue.add(project.getArtifact());
while (!queue.isEmpty()) {
Artifact artifact = queue.poll();
log.info("# " + artifact.getId() + ":" + artifact.getScope());
DependencyData artifactDependencyData = dependencyMap.get(artifact);
// analyze all remote dependencies for given level
for (Artifact dependency : artifactDependencyData.getRemoteList()) {
String dependencyConflictId = dependency.getDependencyConflictId();
Artifact dependencyArtifact = toDependencyArtifact(artifactFactory, dependency, artifact.getScope());
if (dependencyArtifact != null) {
String fullName = dependencyArtifact.getId() + ":" + dependencyArtifact.getScope();
Artifact prevArtifact = remoteData.get(dependencyConflictId);
if (prevArtifact == null) {
// new remote dependency
log.info(" " + fullName);
remoteData.put(dependencyConflictId, dependencyArtifact);
} else {
// we have already added this remote dependency
if (prevArtifact.getId().equals(dependencyArtifact.getId())) {
log.info("D " + fullName);
} else {
log.info("C " + fullName);
log.info(" " + project.getArtifact().getId());
log.info(" " + "+-" + prevArtifact.getId() + ":" + prevArtifact.getScope());
log.info(" " + "+-" + artifact.getId() + ":" + artifact.getScope());
log.info(" " + " \\-" + fullName);
}
}
} else {
log.info("O " + dependency.getId() + ":" + dependency.getScope() + " (inherit=" + artifact.getId() + ":" + artifact.getScope() + ")");
}
}
// analyze all reactor dependencies for given level
for (Artifact dependency : artifactDependencyData.getReactorList()) {
String dependencyConflictId = dependency.getDependencyConflictId();
Artifact dependencyArtifact = toDependencyArtifact(artifactFactory, dependency, artifact.getScope());
if (dependencyArtifact != null) {
String fullName = dependencyArtifact.getId() + ":" + dependencyArtifact.getScope();
Artifact prevArtifact = reactorData.get(dependencyConflictId);
if (prevArtifact == null) {
// new reactor dependency
log.info("R " + fullName);
reactorData.put(dependencyConflictId, dependencyArtifact);
// go deep
queue.add(dependencyArtifact);
} else {
// we have already added this remote dependency
if (prevArtifact.getId().equals(dependencyArtifact.getId())) {
log.info("D " + fullName);
} else {
log.info("C " + fullName);
log.info(" " + project.getArtifact().getId());
log.info(" " + "+-" + prevArtifact.getId() + ":" + prevArtifact.getScope());
log.info(" " + "+-" + artifact.getId() + ":" + artifact.getScope());
log.info(" " + " \\-" + fullName);
}
}
} else {
log.info("O " + dependency.getId() + ":" + dependency.getScope() + " (inherit=" + artifact.getId() + ":" + artifact.getScope() + ")");
}
}
}
result.put(project, new DependencyData(new ArrayList<Artifact>(remoteData.values()), new ArrayList<Artifact>(reactorData.values())));
}
return result;
}
/**
* Convert Dependency to Artifact
*
* @param artifactFactory standard Maven's factory to create artifacts
* @param dependency dependency
* @return artifact
* @throws InvalidVersionSpecificationException if VersionRange is invalid
*/
private Artifact toDependencyArtifact(ArtifactFactory artifactFactory, Dependency dependency) throws InvalidVersionSpecificationException {
// instantiate
Artifact dependencyArtifact = artifactFactory.createDependencyArtifact(dependency.getGroupId(),
dependency.getArtifactId(),
VersionRange.createFromVersionSpec(dependency.getVersion()),
dependency.getType(),
dependency.getClassifier(),
dependency.getScope() == null ? Artifact.SCOPE_COMPILE : dependency.getScope(),
null,
dependency.isOptional()
);
// apply exclusions is needed
if (!dependency.getExclusions().isEmpty()) {
List<String> exclusions = new ArrayList<String>();
for (Exclusion exclusion : dependency.getExclusions())
exclusions.add(exclusion.getGroupId() + ":" + exclusion.getArtifactId());
dependencyArtifact.setDependencyFilter(new ExcludesArtifactFilter(exclusions));
}
// additional
if (Artifact.SCOPE_SYSTEM.equalsIgnoreCase(dependency.getScope()))
dependencyArtifact.setFile(new File(dependency.getSystemPath()));
return dependencyArtifact;
}
private static Artifact toDependencyArtifact(ArtifactFactory artifactFactory, Artifact dependency, String inheritedScope) {
Artifact dependencyArtifact = artifactFactory.createDependencyArtifact(dependency.getGroupId(),
dependency.getArtifactId(),
dependency.getVersionRange(),
dependency.getType(),
dependency.getClassifier(),
dependency.getScope(),
inheritedScope,
dependency.isOptional()
);
if (dependencyArtifact != null)
dependencyArtifact.setDependencyFilter(dependency.getDependencyFilter());
return dependencyArtifact;
}
private void tryResolve(MavenProject project, Set<Artifact> reactorArtifacts, List<Artifact> remoteData, List<Artifact> reactorData, List<Artifact> remoteUnresolvedList) {
// search
ArtifactResolutionResult resolutionResult;
log.info("Before:");
for (Artifact a : remoteUnresolvedList)
log.info(" " + a.getId() + ":" + a.getScope());
log.info("");
try {
resolutionResult = artifactResolver.resolveTransitively(
new LinkedHashSet<Artifact>(remoteUnresolvedList),
project.getArtifact(),
project.getManagedVersionMap(),
localRepository,
project.getRemoteArtifactRepositories(),
artifactMetadataSource
);
// save search result
log.info("After:");
for (Object resolutionNode : resolutionResult.getArtifactResolutionNodes()) {
Artifact art = ((ResolutionNode) resolutionNode).getArtifact();
if (reactorArtifacts.contains(art)) {
if (!reactorData.contains(art)) {
reactorData.add(art);
log.info("R " + art.getId() + ":" + art.getScope());
} else {
log.info("D " + art.getId() + ":" + art.getScope());
}
} else {
log.info(" " + art.getId() + ":" + art.getScope());
remoteData.add(art);
}
}
// clear unresolved
remoteUnresolvedList.clear();
} catch (ArtifactResolutionException e) {
log.error(e.getMessage());
remoteData.addAll(remoteUnresolvedList);
} catch (ArtifactNotFoundException e) {
throw new RuntimeException(e.getMessage(), e);
}
}
// Classes
public static class DependencyData {
private final List<Artifact> remoteList;
private final List<Artifact> reactorList;
public DependencyData(List<Artifact> remoteList, List<Artifact> reactorList) {
this.remoteList = Collections.unmodifiableList(remoteList);
this.reactorList = Collections.unmodifiableList(reactorList);
}
public List<Artifact> getRemoteList() {
return remoteList;
}
public List<Artifact> getReactorList() {
return reactorList;
}
}
}
|
/*
* 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.guacamole.auth.ldap.conf;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
import org.apache.guacamole.GuacamoleException;
import org.apache.guacamole.properties.GuacamoleProperty;
/**
* A GuacamoleProperty whose value is a List of Strings. The string value
* parsed to produce this list is a comma-delimited list. Duplicate values are
* ignored, as is any whitespace following delimiters. To maintain
* compatibility with the behavior of Java properties in general, only
* whitespace at the beginning of each value is ignored; trailing whitespace
* becomes part of the value.
*/
public abstract class StringListProperty implements GuacamoleProperty<List<String>> {
/**
* A pattern which matches against the delimiters between values. This is
* currently simply a comma and any following whitespace. Parts of the
* input string which match this pattern will not be included in the parsed
* result.
*/
private static final Pattern DELIMITER_PATTERN = Pattern.compile(",\\s*");
@Override
public List<String> parseValue(String values) throws GuacamoleException {
// If no property provided, return null.
if (values == null)
return null;
// Split string into a list of individual values
List<String> stringValues = Arrays.asList(DELIMITER_PATTERN.split(values));
if (stringValues.isEmpty())
return null;
return stringValues;
}
}
|
/*
* 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.flink.api.java;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import org.apache.commons.lang3.Validate;
import org.apache.flink.api.common.ExecutionConfig;
import org.apache.flink.api.common.InvalidProgramException;
import org.apache.flink.api.common.JobExecutionResult;
import org.apache.flink.api.common.Plan;
import org.apache.flink.api.common.cache.DistributedCache.DistributedCacheEntry;
import org.apache.flink.api.common.io.FileInputFormat;
import org.apache.flink.api.common.io.InputFormat;
import org.apache.flink.api.common.typeinfo.BasicTypeInfo;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.java.io.CollectionInputFormat;
import org.apache.flink.api.java.io.CsvReader;
import org.apache.flink.api.java.io.IteratorInputFormat;
import org.apache.flink.api.java.io.ParallelIteratorInputFormat;
import org.apache.flink.api.java.io.PrimitiveInputFormat;
import org.apache.flink.api.java.io.TextInputFormat;
import org.apache.flink.api.java.io.TextValueInputFormat;
import org.apache.flink.api.java.operators.DataSink;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.operators.Operator;
import org.apache.flink.api.java.operators.OperatorTranslation;
import org.apache.flink.api.java.operators.translation.JavaPlan;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.api.java.typeutils.ResultTypeQueryable;
import org.apache.flink.api.java.typeutils.TypeExtractor;
import org.apache.flink.api.java.typeutils.ValueTypeInfo;
import org.apache.flink.core.fs.Path;
import org.apache.flink.types.StringValue;
import org.apache.flink.util.NumberSequenceIterator;
import org.apache.flink.util.SplittableIterator;
/**
* The ExecutionEnviroment is the context in which a program is executed. A
* {@link LocalEnvironment} will cause execution in the current JVM, a
* {@link RemoteEnvironment} will cause execution on a remote setup.
* <p>
* The environment provides methods to control the job execution (such as setting the parallelism)
* and to interact with the outside world (data access).
* <p>
* Please note that the execution environment needs strong type information for the input and return types
* of all operations that are executed. This means that the environments needs to know that the return
* value of an operation is for example a Tuple of String and Integer.
* Because the Java compiler throws much of the generic type information away, most methods attempt to re-
* obtain that information using reflection. In certain cases, it may be necessary to manually supply that
* information to some of the methods.
*
* @see LocalEnvironment
* @see RemoteEnvironment
*/
public abstract class ExecutionEnvironment {
/** The environment of the context (local by default, cluster if invoked through command line) */
private static ExecutionEnvironmentFactory contextEnvironmentFactory;
/** The default parallelism used by local environments */
private static int defaultLocalDop = Runtime.getRuntime().availableProcessors();
/** flag to disable local executor when using the ContextEnvironment */
private static boolean allowLocalExecution = true;
// --------------------------------------------------------------------------------------------
private final UUID executionId;
private final List<DataSink<?>> sinks = new ArrayList<DataSink<?>>();
private final List<Tuple2<String, DistributedCacheEntry>> cacheFile = new ArrayList<Tuple2<String, DistributedCacheEntry>>();
private ExecutionConfig config = new ExecutionConfig();
// --------------------------------------------------------------------------------------------
// Constructor and Properties
// --------------------------------------------------------------------------------------------
/**
* Creates a new Execution Environment.
*/
protected ExecutionEnvironment() {
this.executionId = UUID.randomUUID();
}
/**
* Sets the config object.
*/
public void setConfig(ExecutionConfig config) {
Validate.notNull(config);
this.config = config;
}
/**
* Gets the config object.
*/
public ExecutionConfig getConfig() {
return config;
}
/**
* Gets the degree of parallelism with which operation are executed by default. Operations can
* individually override this value to use a specific degree of parallelism via
* {@link Operator#setParallelism(int)}. Other operations may need to run with a different
* degree of parallelism - for example calling
* {@link DataSet#reduce(org.apache.flink.api.common.functions.ReduceFunction)} over the entire
* set will insert eventually an operation that runs non-parallel (degree of parallelism of one).
*
* @return The degree of parallelism used by operations, unless they override that value. This method
* returns {@code -1}, if the environments default parallelism should be used.
*/
public int getDegreeOfParallelism() {
return config.getDegreeOfParallelism();
}
/**
* Sets the degree of parallelism (DOP) for operations executed through this environment.
* Setting a DOP of x here will cause all operators (such as join, map, reduce) to run with
* x parallel instances.
* <p>
* This method overrides the default parallelism for this environment.
* The {@link LocalEnvironment} uses by default a value equal to the number of hardware
* contexts (CPU cores / threads). When executing the program via the command line client
* from a JAR file, the default degree of parallelism is the one configured for that setup.
*
* @param degreeOfParallelism The degree of parallelism
*/
public void setDegreeOfParallelism(int degreeOfParallelism) {
config.setDegreeOfParallelism(degreeOfParallelism);
}
/**
* Sets the number of times that failed tasks are re-executed. A value of zero
* effectively disables fault tolerance. A value of {@code -1} indicates that the system
* default value (as defined in the configuration) should be used.
*
* @param numberOfExecutionRetries The number of times the system will try to re-execute failed tasks.
*/
public void setNumberOfExecutionRetries(int numberOfExecutionRetries) {
config.setNumberOfExecutionRetries(numberOfExecutionRetries);
}
/**
* Gets the number of times the system will try to re-execute failed tasks. A value
* of {@code -1} indicates that the system default value (as defined in the configuration)
* should be used.
*
* @return The number of times the system will try to re-execute failed tasks.
*/
public int getNumberOfExecutionRetries() {
return config.getNumberOfExecutionRetries();
}
/**
* Gets the UUID by which this environment is identified. The UUID sets the execution context
* in the cluster or local environment.
*
* @return The UUID of this environment.
* @see #getIdString()
*/
public UUID getId() {
return this.executionId;
}
/**
* Gets the UUID by which this environment is identified, as a string.
*
* @return The UUID as a string.
* @see #getId()
*/
public String getIdString() {
return this.executionId.toString();
}
// --------------------------------------------------------------------------------------------
// Data set creations
// --------------------------------------------------------------------------------------------
// ---------------------------------- Text Input Format ---------------------------------------
/**
* Creates a DataSet that represents the Strings produced by reading the given file line wise.
* The file will be read with the system's default character set.
*
* @param filePath The path of the file, as a URI (e.g., "file:///some/local/file" or "hdfs://host:port/file/path").
* @return A DataSet that represents the data read from the given file as text lines.
*/
public DataSource<String> readTextFile(String filePath) {
Validate.notNull(filePath, "The file path may not be null.");
return new DataSource<String>(this, new TextInputFormat(new Path(filePath)), BasicTypeInfo.STRING_TYPE_INFO, Utils.getCallLocationName());
}
/**
* Creates a DataSet that represents the Strings produced by reading the given file line wise.
* The {@link java.nio.charset.Charset} with the given name will be used to read the files.
*
* @param filePath The path of the file, as a URI (e.g., "file:///some/local/file" or "hdfs://host:port/file/path").
* @param charsetName The name of the character set used to read the file.
* @return A DataSet that represents the data read from the given file as text lines.
*/
public DataSource<String> readTextFile(String filePath, String charsetName) {
Validate.notNull(filePath, "The file path may not be null.");
TextInputFormat format = new TextInputFormat(new Path(filePath));
format.setCharsetName(charsetName);
return new DataSource<String>(this, format, BasicTypeInfo.STRING_TYPE_INFO, Utils.getCallLocationName());
}
// -------------------------- Text Input Format With String Value------------------------------
/**
* Creates a DataSet that represents the Strings produced by reading the given file line wise.
* This method is similar to {@link #readTextFile(String)}, but it produces a DataSet with mutable
* {@link StringValue} objects, rather than Java Strings. StringValues can be used to tune implementations
* to be less object and garbage collection heavy.
* <p>
* The file will be read with the system's default character set.
*
* @param filePath The path of the file, as a URI (e.g., "file:///some/local/file" or "hdfs://host:port/file/path").
* @return A DataSet that represents the data read from the given file as text lines.
*/
public DataSource<StringValue> readTextFileWithValue(String filePath) {
Validate.notNull(filePath, "The file path may not be null.");
return new DataSource<StringValue>(this, new TextValueInputFormat(new Path(filePath)), new ValueTypeInfo<StringValue>(StringValue.class), Utils.getCallLocationName());
}
/**
* Creates a DataSet that represents the Strings produced by reading the given file line wise.
* This method is similar to {@link #readTextFile(String, String)}, but it produces a DataSet with mutable
* {@link StringValue} objects, rather than Java Strings. StringValues can be used to tune implementations
* to be less object and garbage collection heavy.
* <p>
* The {@link java.nio.charset.Charset} with the given name will be used to read the files.
*
* @param filePath The path of the file, as a URI (e.g., "file:///some/local/file" or "hdfs://host:port/file/path").
* @param charsetName The name of the character set used to read the file.
* @param skipInvalidLines A flag to indicate whether to skip lines that cannot be read with the given character set.
*
* @return A DataSet that represents the data read from the given file as text lines.
*/
public DataSource<StringValue> readTextFileWithValue(String filePath, String charsetName, boolean skipInvalidLines) {
Validate.notNull(filePath, "The file path may not be null.");
TextValueInputFormat format = new TextValueInputFormat(new Path(filePath));
format.setCharsetName(charsetName);
format.setSkipInvalidLines(skipInvalidLines);
return new DataSource<StringValue>(this, format, new ValueTypeInfo<StringValue>(StringValue.class), Utils.getCallLocationName());
}
// ----------------------------------- Primitive Input Format ---------------------------------------
/**
* Creates a DataSet that represents the primitive type produced by reading the given file line wise.
* This method is similar to {@link #readCsvFile(String)} with single field, but it produces a DataSet not through
* {@link org.apache.flink.api.java.tuple.Tuple1}.
*
* @param filePath The path of the file, as a URI (e.g., "file:///some/local/file" or "hdfs://host:port/file/path").
* @param typeClass The primitive type class to be read.
* @return A DataSet that represents the data read from the given file as primitive type.
*/
public <X> DataSource<X> readFileOfPrimitives(String filePath, Class<X> typeClass) {
Validate.notNull(filePath, "The file path may not be null.");
return new DataSource<X>(this, new PrimitiveInputFormat<X>(new Path(filePath), typeClass), TypeExtractor.getForClass(typeClass), Utils.getCallLocationName());
}
/**
* Creates a DataSet that represents the primitive type produced by reading the given file in delimited way.
* This method is similar to {@link #readCsvFile(String)} with single field, but it produces a DataSet not through
* {@link org.apache.flink.api.java.tuple.Tuple1}.
*
* @param filePath The path of the file, as a URI (e.g., "file:///some/local/file" or "hdfs://host:port/file/path").
* @param delimiter The delimiter of the given file.
* @param typeClass The primitive type class to be read.
* @return A DataSet that represents the data read from the given file as primitive type.
*/
public <X> DataSource<X> readFileOfPrimitives(String filePath, String delimiter, Class<X> typeClass) {
Validate.notNull(filePath, "The file path may not be null.");
return new DataSource<X>(this, new PrimitiveInputFormat<X>(new Path(filePath), delimiter, typeClass), TypeExtractor.getForClass(typeClass), Utils.getCallLocationName());
}
// ----------------------------------- CSV Input Format ---------------------------------------
/**
* Creates a CSV reader to read a comma separated value (CSV) file. The reader has options to
* define parameters and field types and will eventually produce the DataSet that corresponds to
* the read and parsed CSV input.
*
* @param filePath The path of the CSV file.
* @return A CsvReader that can be used to configure the CSV input.
*/
public CsvReader readCsvFile(String filePath) {
return new CsvReader(filePath, this);
}
// ------------------------------------ File Input Format -----------------------------------------
public <X> DataSource<X> readFile(FileInputFormat<X> inputFormat, String filePath) {
if (inputFormat == null) {
throw new IllegalArgumentException("InputFormat must not be null.");
}
if (filePath == null) {
throw new IllegalArgumentException("The file path must not be null.");
}
inputFormat.setFilePath(new Path(filePath));
try {
return createInput(inputFormat, TypeExtractor.getInputFormatTypes(inputFormat));
}
catch (Exception e) {
throw new InvalidProgramException("The type returned by the input format could not be automatically determined. " +
"Please specify the TypeInformation of the produced type explicitly.");
}
}
// ----------------------------------- Generic Input Format ---------------------------------------
/**
* Generic method to create an input DataSet with in {@link InputFormat}. The DataSet will not be
* immediately created - instead, this method returns a DataSet that will be lazily created from
* the input format once the program is executed.
* <p>
* Since all data sets need specific information about their types, this method needs to determine
* the type of the data produced by the input format. It will attempt to determine the data type
* by reflection, unless the the input format implements the {@link ResultTypeQueryable} interface.
* In the latter case, this method will invoke the {@link ResultTypeQueryable#getProducedType()}
* method to determine data type produced by the input format.
*
* @param inputFormat The input format used to create the data set.
* @return A DataSet that represents the data created by the input format.
*
* @see #createInput(InputFormat, TypeInformation)
*/
public <X> DataSource<X> createInput(InputFormat<X, ?> inputFormat) {
if (inputFormat == null) {
throw new IllegalArgumentException("InputFormat must not be null.");
}
try {
return createInput(inputFormat, TypeExtractor.getInputFormatTypes(inputFormat));
}
catch (Exception e) {
throw new InvalidProgramException("The type returned by the input format could not be automatically determined. " +
"Please specify the TypeInformation of the produced type explicitly.");
}
}
/**
* Generic method to create an input DataSet with in {@link InputFormat}. The DataSet will not be
* immediately created - instead, this method returns a DataSet that will be lazily created from
* the input format once the program is executed.
* <p>
* The data set is typed to the given TypeInformation. This method is intended for input formats that
* where the return type cannot be determined by reflection analysis, and that do not implement the
* {@link ResultTypeQueryable} interface.
*
* @param inputFormat The input format used to create the data set.
* @return A DataSet that represents the data created by the input format.
*
* @see #createInput(InputFormat)
*/
public <X> DataSource<X> createInput(InputFormat<X, ?> inputFormat, TypeInformation<X> producedType) {
if (inputFormat == null) {
throw new IllegalArgumentException("InputFormat must not be null.");
}
if (producedType == null) {
throw new IllegalArgumentException("Produced type information must not be null.");
}
return new DataSource<X>(this, inputFormat, producedType, Utils.getCallLocationName());
}
// ----------------------------------- Collection ---------------------------------------
/**
* Creates a DataSet from the given non-empty collection. The type of the data set is that
* of the elements in the collection. The elements need to be serializable (as defined by
* {@link java.io.Serializable}), because the framework may move the elements into the cluster
* if needed.
* <p>
* The framework will try and determine the exact type from the collection elements.
* In case of generic elements, it may be necessary to manually supply the type information
* via {@link #fromCollection(Collection, TypeInformation)}.
* <p>
* Note that this operation will result in a non-parallel data source, i.e. a data source with
* a degree of parallelism of one.
*
* @param data The collection of elements to create the data set from.
* @return A DataSet representing the given collection.
*
* @see #fromCollection(Collection, TypeInformation)
*/
public <X> DataSource<X> fromCollection(Collection<X> data) {
if (data == null) {
throw new IllegalArgumentException("The data must not be null.");
}
if (data.size() == 0) {
throw new IllegalArgumentException("The size of the collection must not be empty.");
}
X firstValue = data.iterator().next();
TypeInformation<X> type = TypeExtractor.getForObject(firstValue);
CollectionInputFormat.checkCollection(data, type.getTypeClass());
return new DataSource<X>(this, new CollectionInputFormat<X>(data, type.createSerializer()), type, Utils.getCallLocationName());
}
/**
* Creates a DataSet from the given non-empty collection. The type of the data set is that
* of the elements in the collection. The elements need to be serializable (as defined by
* {@link java.io.Serializable}), because the framework may move the elements into the cluster
* if needed.
* <p>
* Note that this operation will result in a non-parallel data source, i.e. a data source with
* a degree of parallelism of one.
* <p>
* The returned DataSet is typed to the given TypeInformation.
*
* @param data The collection of elements to create the data set from.
* @param type The TypeInformation for the produced data set.
* @return A DataSet representing the given collection.
*
* @see #fromCollection(Collection)
*/
public <X> DataSource<X> fromCollection(Collection<X> data, TypeInformation<X> type) {
return fromCollection(data, type, Utils.getCallLocationName());
}
private <X> DataSource<X> fromCollection(Collection<X> data, TypeInformation<X> type, String callLocationName) {
CollectionInputFormat.checkCollection(data, type.getTypeClass());
return new DataSource<X>(this, new CollectionInputFormat<X>(data, type.createSerializer()), type, callLocationName);
}
/**
* Creates a DataSet from the given iterator. Because the iterator will remain unmodified until
* the actual execution happens, the type of data returned by the iterator must be given
* explicitly in the form of the type class (this is due to the fact that the Java compiler
* erases the generic type information).
* <p>
* The iterator must be serializable (as defined in {@link java.io.Serializable}), because the
* framework may move it to a remote environment, if needed.
* <p>
* Note that this operation will result in a non-parallel data source, i.e. a data source with
* a degree of parallelism of one.
*
* @param data The collection of elements to create the data set from.
* @param type The class of the data produced by the iterator. Must not be a generic class.
* @return A DataSet representing the elements in the iterator.
*
* @see #fromCollection(Iterator, TypeInformation)
*/
public <X> DataSource<X> fromCollection(Iterator<X> data, Class<X> type) {
return fromCollection(data, TypeExtractor.getForClass(type));
}
/**
* Creates a DataSet from the given iterator. Because the iterator will remain unmodified until
* the actual execution happens, the type of data returned by the iterator must be given
* explicitly in the form of the type information. This method is useful for cases where the type
* is generic. In that case, the type class (as given in {@link #fromCollection(Iterator, Class)}
* does not supply all type information.
* <p>
* The iterator must be serializable (as defined in {@link java.io.Serializable}), because the
* framework may move it to a remote environment, if needed.
* <p>
* Note that this operation will result in a non-parallel data source, i.e. a data source with
* a degree of parallelism of one.
*
* @param data The collection of elements to create the data set from.
* @param type The TypeInformation for the produced data set.
* @return A DataSet representing the elements in the iterator.
*
* @see #fromCollection(Iterator, Class)
*/
public <X> DataSource<X> fromCollection(Iterator<X> data, TypeInformation<X> type) {
if (!(data instanceof Serializable)) {
throw new IllegalArgumentException("The iterator must be serializable.");
}
return new DataSource<X>(this, new IteratorInputFormat<X>(data), type, Utils.getCallLocationName());
}
/**
* Creates a new data set that contains the given elements. The elements must all be of the same type,
* for example, all of the {@link String} or {@link Integer}. The sequence of elements must not be empty.
* Furthermore, the elements must be serializable (as defined in {@link java.io.Serializable}, because the
* execution environment may ship the elements into the cluster.
* <p>
* The framework will try and determine the exact type from the collection elements.
* In case of generic elements, it may be necessary to manually supply the type information
* via {@link #fromCollection(Collection, TypeInformation)}.
* <p>
* Note that this operation will result in a non-parallel data source, i.e. a data source with
* a degree of parallelism of one.
*
* @param data The elements to make up the data set.
* @return A DataSet representing the given list of elements.
*/
public <X> DataSource<X> fromElements(X... data) {
if (data == null) {
throw new IllegalArgumentException("The data must not be null.");
}
if (data.length == 0) {
throw new IllegalArgumentException("The number of elements must not be zero.");
}
return fromCollection(Arrays.asList(data), TypeExtractor.getForObject(data[0]), Utils.getCallLocationName());
}
/**
* Creates a new data set that contains elements in the iterator. The iterator is splittable, allowing the
* framework to create a parallel data source that returns the elements in the iterator.
* The iterator must be serializable (as defined in {@link java.io.Serializable}, because the
* execution environment may ship the elements into the cluster.
* <p>
* Because the iterator will remain unmodified until the actual execution happens, the type of data
* returned by the iterator must be given explicitly in the form of the type class (this is due to the
* fact that the Java compiler erases the generic type information).
*
* @param iterator The iterator that produces the elements of the data set.
* @param type The class of the data produced by the iterator. Must not be a generic class.
* @return A DataSet representing the elements in the iterator.
*
* @see #fromParallelCollection(SplittableIterator, TypeInformation)
*/
public <X> DataSource<X> fromParallelCollection(SplittableIterator<X> iterator, Class<X> type) {
return fromParallelCollection(iterator, TypeExtractor.getForClass(type));
}
/**
* Creates a new data set that contains elements in the iterator. The iterator is splittable, allowing the
* framework to create a parallel data source that returns the elements in the iterator.
* The iterator must be serializable (as defined in {@link java.io.Serializable}, because the
* execution environment may ship the elements into the cluster.
* <p>
* Because the iterator will remain unmodified until the actual execution happens, the type of data
* returned by the iterator must be given explicitly in the form of the type information.
* This method is useful for cases where the type is generic. In that case, the type class
* (as given in {@link #fromParallelCollection(SplittableIterator, Class)} does not supply all type information.
*
* @param iterator The iterator that produces the elements of the data set.
* @param type The TypeInformation for the produced data set.
* @return A DataSet representing the elements in the iterator.
*
* @see #fromParallelCollection(SplittableIterator, Class)
*/
public <X> DataSource<X> fromParallelCollection(SplittableIterator<X> iterator, TypeInformation<X> type) {
return fromParallelCollection(iterator, type, Utils.getCallLocationName());
}
// private helper for passing different call location names
private <X> DataSource<X> fromParallelCollection(SplittableIterator<X> iterator, TypeInformation<X> type, String callLocationName) {
return new DataSource<X>(this, new ParallelIteratorInputFormat<X>(iterator), type, callLocationName);
}
/**
* Creates a new data set that contains a sequence of numbers. The data set will be created in parallel,
* so there is no guarantee about the oder of the elements.
*
* @param from The number to start at (inclusive).
* @param to The number to stop at (inclusive).
* @return A DataSet, containing all number in the {@code [from, to]} interval.
*/
public DataSource<Long> generateSequence(long from, long to) {
return fromParallelCollection(new NumberSequenceIterator(from, to), BasicTypeInfo.LONG_TYPE_INFO, Utils.getCallLocationName());
}
// --------------------------------------------------------------------------------------------
// Executing
// --------------------------------------------------------------------------------------------
/**
* Triggers the program execution. The environment will execute all parts of the program that have
* resulted in a "sink" operation. Sink operations are for example printing results ({@link DataSet#print()},
* writing results (e.g. {@link DataSet#writeAsText(String)},
* {@link DataSet#write(org.apache.flink.api.common.io.FileOutputFormat, String)}, or other generic
* data sinks created with {@link DataSet#output(org.apache.flink.api.common.io.OutputFormat)}.
* <p>
* The program execution will be logged and displayed with a generated default name.
*
* @return The result of the job execution, containing elapsed time and accumulators.
* @throws Exception Thrown, if the program executions fails.
*/
public JobExecutionResult execute() throws Exception {
return execute(getDefaultName());
}
/**
* Triggers the program execution. The environment will execute all parts of the program that have
* resulted in a "sink" operation. Sink operations are for example printing results ({@link DataSet#print()},
* writing results (e.g. {@link DataSet#writeAsText(String)},
* {@link DataSet#write(org.apache.flink.api.common.io.FileOutputFormat, String)}, or other generic
* data sinks created with {@link DataSet#output(org.apache.flink.api.common.io.OutputFormat)}.
* <p>
* The program execution will be logged and displayed with the given job name.
*
* @return The result of the job execution, containing elapsed time and accumulators.
* @throws Exception Thrown, if the program executions fails.
*/
public abstract JobExecutionResult execute(String jobName) throws Exception;
/**
* Creates the plan with which the system will execute the program, and returns it as
* a String using a JSON representation of the execution data flow graph.
* Note that this needs to be called, before the plan is executed.
*
* @return The execution plan of the program, as a JSON String.
* @throws Exception Thrown, if the compiler could not be instantiated, or the master could not
* be contacted to retrieve information relevant to the execution planning.
*/
public abstract String getExecutionPlan() throws Exception;
/**
* Registers a file at the distributed cache under the given name. The file will be accessible
* from any user-defined function in the (distributed) runtime under a local path. Files
* may be local files (as long as all relevant workers have access to it), or files in a distributed file system.
* The runtime will copy the files temporarily to a local cache, if needed.
* <p>
* The {@link org.apache.flink.api.common.functions.RuntimeContext} can be obtained inside UDFs via
* {@link org.apache.flink.api.common.functions.RichFunction#getRuntimeContext()} and provides access
* {@link org.apache.flink.api.common.cache.DistributedCache} via
* {@link org.apache.flink.api.common.functions.RuntimeContext#getDistributedCache()}.
*
* @param filePath The path of the file, as a URI (e.g. "file:///some/path" or "hdfs://host:port/and/path")
* @param name The name under which the file is registered.
*/
public void registerCachedFile(String filePath, String name){
registerCachedFile(filePath, name, false);
}
/**
* Registers a file at the distributed cache under the given name. The file will be accessible
* from any user-defined function in the (distributed) runtime under a local path. Files
* may be local files (as long as all relevant workers have access to it), or files in a distributed file system.
* The runtime will copy the files temporarily to a local cache, if needed.
* <p>
* The {@link org.apache.flink.api.common.functions.RuntimeContext} can be obtained inside UDFs via
* {@link org.apache.flink.api.common.functions.RichFunction#getRuntimeContext()} and provides access
* {@link org.apache.flink.api.common.cache.DistributedCache} via
* {@link org.apache.flink.api.common.functions.RuntimeContext#getDistributedCache()}.
*
* @param filePath The path of the file, as a URI (e.g. "file:///some/path" or "hdfs://host:port/and/path")
* @param name The name under which the file is registered.
* @param executable flag indicating whether the file should be executable
*/
public void registerCachedFile(String filePath, String name, boolean executable){
this.cacheFile.add(new Tuple2<String, DistributedCacheEntry>(name, new DistributedCacheEntry(filePath, executable)));
}
/**
* Registers all files that were registered at this execution environment's cache registry of the
* given plan's cache registry.
*
* @param p The plan to register files at.
* @throws IOException Thrown if checks for existence and sanity fail.
*/
protected void registerCachedFilesWithPlan(Plan p) throws IOException {
for (Tuple2<String, DistributedCacheEntry> entry : cacheFile) {
p.registerCachedFile(entry.f0, entry.f1);
}
}
/**
* Creates the program's {@link Plan}. The plan is a description of all data sources, data sinks,
* and operations and how they interact, as an isolated unit that can be executed with a
* {@link org.apache.flink.api.common.PlanExecutor}. Obtaining a plan and starting it with an
* executor is an alternative way to run a program and is only possible if the program consists
* only of distributed operations.
* This automatically starts a new stage of execution.
*
* @return The program's plan.
*/
public JavaPlan createProgramPlan() {
return createProgramPlan(null);
}
/**
* Creates the program's {@link Plan}. The plan is a description of all data sources, data sinks,
* and operations and how they interact, as an isolated unit that can be executed with a
* {@link org.apache.flink.api.common.PlanExecutor}. Obtaining a plan and starting it with an
* executor is an alternative way to run a program and is only possible if the program consists
* only of distributed operations.
* This automatically starts a new stage of execution.
*
* @param jobName The name attached to the plan (displayed in logs and monitoring).
* @return The program's plan.
*/
public JavaPlan createProgramPlan(String jobName) {
return createProgramPlan(jobName, true);
}
/**
* Creates the program's {@link Plan}. The plan is a description of all data sources, data sinks,
* and operations and how they interact, as an isolated unit that can be executed with a
* {@link org.apache.flink.api.common.PlanExecutor}. Obtaining a plan and starting it with an
* executor is an alternative way to run a program and is only possible if the program consists
* only of distributed operations.
*
* @param jobName The name attached to the plan (displayed in logs and monitoring).
* @param clearSinks Whether or not to start a new stage of execution.
* @return The program's plan.
*/
public JavaPlan createProgramPlan(String jobName, boolean clearSinks) {
if (this.sinks.isEmpty()) {
throw new RuntimeException("No data sinks have been created yet. A program needs at least one sink that consumes data. Examples are writing the data set or printing it.");
}
if (jobName == null) {
jobName = getDefaultName();
}
OperatorTranslation translator = new OperatorTranslation();
JavaPlan plan = translator.translateToPlan(this.sinks, jobName);
if (getDegreeOfParallelism() > 0) {
plan.setDefaultParallelism(getDegreeOfParallelism());
}
plan.setExecutionConfig(getConfig());
try {
registerCachedFilesWithPlan(plan);
} catch (Exception e) {
throw new RuntimeException("Error while registering cached files: " + e.getMessage(), e);
}
// clear all the sinks such that the next execution does not redo everything
if (clearSinks) {
this.sinks.clear();
}
return plan;
}
/**
* Adds the given sink to this environment. Only sinks that have been added will be executed once
* the {@link #execute()} or {@link #execute(String)} method is called.
*
* @param sink The sink to add for execution.
*/
void registerDataSink(DataSink<?> sink) {
this.sinks.add(sink);
}
/**
* Gets a default job name, based on the timestamp when this method is invoked.
*
* @return A default job name.
*/
private static String getDefaultName() {
return "Flink Java Job at " + Calendar.getInstance().getTime();
}
// --------------------------------------------------------------------------------------------
// Instantiation of Execution Contexts
// --------------------------------------------------------------------------------------------
/**
* Creates an execution environment that represents the context in which the program is currently executed.
* If the program is invoked standalone, this method returns a local execution environment, as returned by
* {@link #createLocalEnvironment()}. If the program is invoked from within the command line client to be
* submitted to a cluster, this method returns the execution environment of this cluster.
*
* @return The execution environment of the context in which the program is executed.
*/
public static ExecutionEnvironment getExecutionEnvironment() {
return contextEnvironmentFactory == null ?
createLocalEnvironment() : contextEnvironmentFactory.createExecutionEnvironment();
}
/**
* Creates a {@link LocalEnvironment}. The local execution environment will run the program in a
* multi-threaded fashion in the same JVM as the environment was created in. The default degree of
* parallelism of the local environment is the number of hardware contexts (CPU cores / threads),
* unless it was specified differently by {@link #setDefaultLocalParallelism(int)}.
*
* @return A local execution environment.
*/
public static LocalEnvironment createLocalEnvironment() {
return createLocalEnvironment(defaultLocalDop);
}
/**
* Creates a {@link LocalEnvironment}. The local execution environment will run the program in a
* multi-threaded fashion in the same JVM as the environment was created in. It will use the
* degree of parallelism specified in the parameter.
*
* @param degreeOfParallelism The degree of parallelism for the local environment.
* @return A local execution environment with the specified degree of parallelism.
*/
public static LocalEnvironment createLocalEnvironment(int degreeOfParallelism) {
LocalEnvironment lee = new LocalEnvironment();
lee.setDegreeOfParallelism(degreeOfParallelism);
return lee;
}
/**
* Creates a {@link RemoteEnvironment}. The remote environment sends (parts of) the program
* to a cluster for execution. Note that all file paths used in the program must be accessible from the
* cluster. The execution will use the cluster's default degree of parallelism, unless the parallelism is
* set explicitly via {@link ExecutionEnvironment#setDegreeOfParallelism(int)}.
*
* @param host The host name or address of the master (JobManager), where the program should be executed.
* @param port The port of the master (JobManager), where the program should be executed.
* @param jarFiles The JAR files with code that needs to be shipped to the cluster. If the program uses
* user-defined functions, user-defined input formats, or any libraries, those must be
* provided in the JAR files.
* @return A remote environment that executes the program on a cluster.
*/
public static ExecutionEnvironment createRemoteEnvironment(String host, int port, String... jarFiles) {
return new RemoteEnvironment(host, port, jarFiles);
}
/**
* Creates a {@link RemoteEnvironment}. The remote environment sends (parts of) the program
* to a cluster for execution. Note that all file paths used in the program must be accessible from the
* cluster. The execution will use the specified degree of parallelism.
*
* @param host The host name or address of the master (JobManager), where the program should be executed.
* @param port The port of the master (JobManager), where the program should be executed.
* @param degreeOfParallelism The degree of parallelism to use during the execution.
* @param jarFiles The JAR files with code that needs to be shipped to the cluster. If the program uses
* user-defined functions, user-defined input formats, or any libraries, those must be
* provided in the JAR files.
* @return A remote environment that executes the program on a cluster.
*/
public static ExecutionEnvironment createRemoteEnvironment(String host, int port, int degreeOfParallelism, String... jarFiles) {
RemoteEnvironment rec = new RemoteEnvironment(host, port, jarFiles);
rec.setDegreeOfParallelism(degreeOfParallelism);
return rec;
}
/**
* Sets the default parallelism that will be used for the local execution environment created by
* {@link #createLocalEnvironment()}.
*
* @param degreeOfParallelism The degree of parallelism to use as the default local parallelism.
*/
public static void setDefaultLocalParallelism(int degreeOfParallelism) {
defaultLocalDop = degreeOfParallelism;
}
// --------------------------------------------------------------------------------------------
// Methods to control the context and local environments for execution from packaged programs
// --------------------------------------------------------------------------------------------
protected static void initializeContextEnvironment(ExecutionEnvironmentFactory ctx) {
contextEnvironmentFactory = ctx;
}
protected static boolean isContextEnvironmentSet() {
return contextEnvironmentFactory != null;
}
protected static void enableLocalExecution(boolean enabled) {
allowLocalExecution = enabled;
}
public static boolean localExecutionIsAllowed() {
return allowLocalExecution;
}
}
|
/*
* Copyright (C) Lightbend Inc. <https://www.lightbend.com>
*/
package play.components;
import akka.actor.ActorSystem;
import akka.actor.typed.Scheduler;
import play.api.libs.concurrent.AkkaSchedulerProvider;
/** Akka Typed components. */
public interface AkkaTypedComponents {
ActorSystem actorSystem();
default Scheduler scheduler() {
return new AkkaSchedulerProvider(actorSystem()).get();
}
}
|
/*
*
* * Copyright 2010-2016 OrientDB LTD (http://orientdb.com)
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*/
package com.orientechnologies.lucene.test;
import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.orient.core.command.script.OCommandScript;
import com.orientechnologies.orient.core.metadata.OMetadataInternal;
import com.orientechnologies.orient.core.sql.OCommandSQL;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.assertj.core.api.Assertions;
import org.junit.Test;
import java.io.InputStream;
import java.util.logging.Level;
/**
* Created by enricorisa on 26/09/14.
*/
public class LuceneDropClusterTest extends BaseLuceneTest {
@Test
public void shouldRemoveCluster() throws Exception {
OLogManager.instance().setConsoleLevel(Level.FINE.getName());
InputStream stream = ClassLoader.getSystemResourceAsStream("testLuceneIndex.sql");
db.command(new OCommandScript("sql", getScriptFromStream(stream))).execute();
db.command(new OCommandSQL(
"create index Song.title on Song (title) FULLTEXT ENGINE LUCENE METADATA {\"default\":\"" + StandardAnalyzer.class.getName()
+ "\"}")).execute();
db.command(new OCommandSQL(
"create index Song.author on Song (author) FULLTEXT ENGINE LUCENE METADATA {\"default\":\"" + StandardAnalyzer.class
.getName() + "\"}")).execute();
OMetadataInternal metadata = db.getMetadata();
long initialIndexSize = metadata.getIndexManagerInternal().getIndex(db, "Song.title").getSize();
int[] clusterIds = metadata.getSchema().getClass("Song").getClusterIds();
db.dropCluster(clusterIds[1]);
long afterDropIndexSize = metadata.getIndexManagerInternal().getIndex(db, "Song.title").getSize();
Assertions.assertThat(afterDropIndexSize).isLessThan(initialIndexSize);
}
}
|
package com.mygdx.game;
import com.badlogic.gdx.Application;
import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.utils.viewport.ScreenViewport;
import com.mygdx.game.Managers.ResourceManager;
import com.mygdx.game.UI.*;
/**
* Contains class instances of game UI screens.
*/
public class PirateGame extends Game {
public MenuScreen menu;
public GameScreen game;
public EndScreen end;
public Stage stage;
public Skin skin;
public ShopScreen shop;
public PowerupScreen powerup;
public QuitConfirmationScreen quitConfirm;
/**
* Create instances of game stage and UI screens.
*/
@Override
public void create() {
// load resources
int id_ship = ResourceManager.addTexture("ship.png");
int id_map = ResourceManager.addTileMap("Map.tmx");
int atlas_id = ResourceManager.addTextureAtlas("Boats.txt");
int extras_id = ResourceManager.addTextureAtlas("UISkin/skin.atlas");
int buildings_id = ResourceManager.addTextureAtlas("Buildings.txt");
ResourceManager.addTexture("menuBG.jpg");
ResourceManager.addTexture("newmenuBG.jpg");
ResourceManager.addTexture("shopBG.jpg");
ResourceManager.addTexture("Chest.png");
ResourceManager.addTexture("powerups/powerup1.png");
ResourceManager.addTexture("powerups/powerup2.png");
ResourceManager.addTexture("powerups/powerup3.png");
ResourceManager.addTexture("powerups/powerup4.png");
ResourceManager.addTexture("powerups/powerup5.png");
ResourceManager.addTexture("powerups/powerup6.png");
ResourceManager.addTexture("points.png");
ResourceManager.loadAssets();
// cant load any more resources after this point (just functionally I choose not to implement)
if(!(Application.ApplicationType.HeadlessDesktop == Gdx.app.getType())){
stage = new Stage(new ScreenViewport());
}
createSkin();
menu = new MenuScreen(this);
shop = new ShopScreen(this);
game = new GameScreen(this, id_map);
end = new EndScreen(this);
powerup = new PowerupScreen(this);
quitConfirm = new QuitConfirmationScreen(this);
setScreen(menu);
}
/**
* Clean up prevent memory leeks
*/
@Override
public void dispose() {
menu.dispose();
shop.dispose();
game.dispose();
stage.dispose();
skin.dispose();
powerup.dispose();
quitConfirm.dispose();
}
/**
* load ui skin from assets
*/
private void createSkin() {
skin = new Skin(Gdx.files.internal("UISkin/skin.json"));
}
}
|
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.contacts.editor;
import android.content.Context;
import android.graphics.Rect;
import android.os.Parcel;
import android.os.Parcelable;
import android.provider.ContactsContract;
import android.text.Editable;
import android.text.InputType;
import android.text.Spannable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.TtsSpan;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import com.android.contacts.R;
import com.android.contacts.common.model.RawContactDelta;
import com.android.contacts.common.compat.PhoneNumberUtilsCompat;
import com.android.contacts.common.ContactsUtils;
import com.android.contacts.common.model.ValuesDelta;
import com.android.contacts.common.model.account.AccountType.EditField;
import com.android.contacts.common.model.dataitem.DataKind;
import com.android.contacts.common.util.PhoneNumberFormatter;
/**
* Simple editor that handles labels and any {@link EditField} defined for the
* entry. Uses {@link ValuesDelta} to read any existing {@link RawContact} values,
* and to correctly write any changes values.
*/
public class TextFieldsEditorView extends LabeledEditorView {
private static final String TAG = TextFieldsEditorView.class.getSimpleName();
private EditText[] mFieldEditTexts = null;
private ViewGroup mFields = null;
private View mExpansionViewContainer;
private ImageView mExpansionView;
private boolean mHideOptional = true;
private boolean mHasShortAndLongForms;
private int mMinFieldHeight;
private int mPreviousViewHeight;
private int mHintTextColorUnfocused;
public TextFieldsEditorView(Context context) {
super(context);
}
public TextFieldsEditorView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public TextFieldsEditorView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
/** {@inheritDoc} */
@Override
protected void onFinishInflate() {
super.onFinishInflate();
setDrawingCacheEnabled(true);
setAlwaysDrawnWithCacheEnabled(true);
mMinFieldHeight = getContext().getResources().getDimensionPixelSize(
R.dimen.editor_min_line_item_height);
mFields = (ViewGroup) findViewById(R.id.editors);
mHintTextColorUnfocused = getResources().getColor(R.color.editor_disabled_text_color);
mExpansionView = (ImageView) findViewById(R.id.expansion_view);
mExpansionViewContainer = findViewById(R.id.expansion_view_container);
if (mExpansionViewContainer != null) {
mExpansionViewContainer.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mPreviousViewHeight = mFields.getHeight();
// Save focus
final View focusedChild = getFocusedChild();
final int focusedViewId = focusedChild == null ? -1 : focusedChild.getId();
// Reconfigure GUI
mHideOptional = !mHideOptional;
onOptionalFieldVisibilityChange();
rebuildValues();
// Restore focus
View newFocusView = findViewById(focusedViewId);
if (newFocusView == null || newFocusView.getVisibility() == GONE) {
// find first visible child
newFocusView = TextFieldsEditorView.this;
}
newFocusView.requestFocus();
EditorAnimator.getInstance().slideAndFadeIn(mFields, mPreviousViewHeight);
}
});
}
}
@Override
public void editNewlyAddedField() {
// Some editors may have multiple fields (eg: first-name/last-name), but since the user
// has not selected a particular one, it is reasonable to simply pick the first.
final View editor = mFields.getChildAt(0);
// Show the soft-keyboard.
InputMethodManager imm =
(InputMethodManager)getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
if (!imm.showSoftInput(editor, InputMethodManager.SHOW_IMPLICIT)) {
Log.w(TAG, "Failed to show soft input method.");
}
}
}
@Override
public void setEnabled(boolean enabled) {
super.setEnabled(enabled);
if (mFieldEditTexts != null) {
for (int index = 0; index < mFieldEditTexts.length; index++) {
mFieldEditTexts[index].setEnabled(!isReadOnly() && enabled);
}
}
if (mExpansionView != null) {
mExpansionView.setEnabled(!isReadOnly() && enabled);
}
}
private OnFocusChangeListener mTextFocusChangeListener = new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (getEditorListener() != null) {
getEditorListener().onRequest(EditorListener.EDITOR_FOCUS_CHANGED);
}
// Rebuild the label spinner using the new colors.
rebuildLabel();
}
};
/**
* Creates or removes the type/label button. Doesn't do anything if already correctly configured
*/
private void setupExpansionView(boolean shouldExist, boolean collapsed) {
mExpansionView.setImageResource(collapsed
? R.drawable.ic_menu_expander_minimized_holo_light
: R.drawable.ic_menu_expander_maximized_holo_light);
mExpansionViewContainer.setVisibility(shouldExist ? View.VISIBLE : View.INVISIBLE);
}
@Override
protected void requestFocusForFirstEditField() {
if (mFieldEditTexts != null && mFieldEditTexts.length != 0) {
EditText firstField = null;
boolean anyFieldHasFocus = false;
for (EditText editText : mFieldEditTexts) {
if (firstField == null && editText.getVisibility() == View.VISIBLE) {
firstField = editText;
}
if (editText.hasFocus()) {
anyFieldHasFocus = true;
break;
}
}
if (!anyFieldHasFocus && firstField != null) {
firstField.requestFocus();
}
}
}
public void setValue(int field, String value) {
mFieldEditTexts[field].setText(value);
}
@Override
public void setValues(DataKind kind, ValuesDelta entry, RawContactDelta state, boolean readOnly,
ViewIdGenerator vig) {
super.setValues(kind, entry, state, readOnly, vig);
// Remove edit texts that we currently have
if (mFieldEditTexts != null) {
for (EditText fieldEditText : mFieldEditTexts) {
mFields.removeView(fieldEditText);
}
}
boolean hidePossible = false;
int fieldCount = kind.fieldList == null ? 0 : kind.fieldList.size();
mFieldEditTexts = new EditText[fieldCount];
for (int index = 0; index < fieldCount; index++) {
final EditField field = kind.fieldList.get(index);
final EditText fieldView = new EditText(getContext());
fieldView.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
fieldView.setTextSize(TypedValue.COMPLEX_UNIT_PX,
getResources().getDimension(R.dimen.editor_form_text_size));
fieldView.setHintTextColor(mHintTextColorUnfocused);
mFieldEditTexts[index] = fieldView;
fieldView.setId(vig.getId(state, kind, entry, index));
if (field.titleRes > 0) {
fieldView.setHint(field.titleRes);
}
int inputType = field.inputType;
fieldView.setInputType(inputType);
if (inputType == InputType.TYPE_CLASS_PHONE) {
PhoneNumberFormatter.setPhoneNumberFormattingTextWatcher(
getContext(), fieldView, /* formatAfterWatcherSet =*/ false);
fieldView.setTextDirection(View.TEXT_DIRECTION_LTR);
}
fieldView.setTextAlignment(View.TEXT_ALIGNMENT_VIEW_START);
// Set either a minimum line requirement or a minimum height (because {@link TextView}
// only takes one or the other at a single time).
if (field.minLines > 1) {
fieldView.setMinLines(field.minLines);
} else {
// This needs to be called after setInputType. Otherwise, calling setInputType
// will unset this value.
fieldView.setMinHeight(mMinFieldHeight);
}
// Show the "next" button in IME to navigate between text fields
// TODO: Still need to properly navigate to/from sections without text fields,
// See Bug: 5713510
fieldView.setImeOptions(EditorInfo.IME_ACTION_NEXT);
// Read current value from state
final String column = field.column;
final String value = entry.getAsString(column);
if (ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE.equals(kind.mimeType)) {
fieldView.setText(PhoneNumberUtilsCompat.createTtsSpannable(value));
} else {
fieldView.setText(value);
}
// Show the delete button if we have a non-empty value
setDeleteButtonVisible(!TextUtils.isEmpty(value));
// Prepare listener for writing changes
fieldView.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {
// Trigger event for newly changed value
onFieldChanged(column, s.toString());
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (!ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE.equals(
getKind().mimeType) || !(s instanceof Spannable)) {
return;
}
final Spannable spannable = (Spannable) s;
final TtsSpan[] spans = spannable.getSpans(0, s.length(), TtsSpan.class);
for (int i = 0; i < spans.length; i++) {
spannable.removeSpan(spans[i]);
}
PhoneNumberUtilsCompat.addTtsSpan(spannable, 0, s.length());
}
});
fieldView.setEnabled(isEnabled() && !readOnly);
fieldView.setOnFocusChangeListener(mTextFocusChangeListener);
if (field.shortForm) {
hidePossible = true;
mHasShortAndLongForms = true;
fieldView.setVisibility(mHideOptional ? View.VISIBLE : View.GONE);
} else if (field.longForm) {
hidePossible = true;
mHasShortAndLongForms = true;
fieldView.setVisibility(mHideOptional ? View.GONE : View.VISIBLE);
} else {
// Hide field when empty and optional value
final boolean couldHide = (!ContactsUtils.isGraphic(value) && field.optional);
final boolean willHide = (mHideOptional && couldHide);
fieldView.setVisibility(willHide ? View.GONE : View.VISIBLE);
hidePossible = hidePossible || couldHide;
}
mFields.addView(fieldView);
}
if (mExpansionView != null) {
// When hiding fields, place expandable
setupExpansionView(hidePossible, mHideOptional);
mExpansionView.setEnabled(!readOnly && isEnabled());
}
updateEmptiness();
}
@Override
public boolean isEmpty() {
for (int i = 0; i < mFields.getChildCount(); i++) {
EditText editText = (EditText) mFields.getChildAt(i);
if (!TextUtils.isEmpty(editText.getText())) {
return false;
}
}
return true;
}
/**
* Returns true if the editor is currently configured to show optional fields.
*/
public boolean areOptionalFieldsVisible() {
return !mHideOptional;
}
public boolean hasShortAndLongForms() {
return mHasShortAndLongForms;
}
/**
* Populates the bound rectangle with the bounds of the last editor field inside this view.
*/
public void acquireEditorBounds(Rect bounds) {
if (mFieldEditTexts != null) {
for (int i = mFieldEditTexts.length; --i >= 0;) {
EditText editText = mFieldEditTexts[i];
if (editText.getVisibility() == View.VISIBLE) {
bounds.set(editText.getLeft(), editText.getTop(), editText.getRight(),
editText.getBottom());
return;
}
}
}
}
/**
* Saves the visibility of the child EditTexts, and mHideOptional.
*/
@Override
protected Parcelable onSaveInstanceState() {
Parcelable superState = super.onSaveInstanceState();
SavedState ss = new SavedState(superState);
ss.mHideOptional = mHideOptional;
final int numChildren = mFieldEditTexts == null ? 0 : mFieldEditTexts.length;
ss.mVisibilities = new int[numChildren];
for (int i = 0; i < numChildren; i++) {
ss.mVisibilities[i] = mFieldEditTexts[i].getVisibility();
}
return ss;
}
/**
* Restores the visibility of the child EditTexts, and mHideOptional.
*/
@Override
protected void onRestoreInstanceState(Parcelable state) {
SavedState ss = (SavedState) state;
super.onRestoreInstanceState(ss.getSuperState());
mHideOptional = ss.mHideOptional;
int numChildren = Math.min(mFieldEditTexts == null ? 0 : mFieldEditTexts.length,
ss.mVisibilities == null ? 0 : ss.mVisibilities.length);
for (int i = 0; i < numChildren; i++) {
mFieldEditTexts[i].setVisibility(ss.mVisibilities[i]);
}
}
private static class SavedState extends BaseSavedState {
public boolean mHideOptional;
public int[] mVisibilities;
SavedState(Parcelable superState) {
super(superState);
}
private SavedState(Parcel in) {
super(in);
mVisibilities = new int[in.readInt()];
in.readIntArray(mVisibilities);
}
@Override
public void writeToParcel(Parcel out, int flags) {
super.writeToParcel(out, flags);
out.writeInt(mVisibilities.length);
out.writeIntArray(mVisibilities);
}
@SuppressWarnings({"unused", "hiding" })
public static final Parcelable.Creator<SavedState> CREATOR
= new Parcelable.Creator<SavedState>() {
@Override
public SavedState createFromParcel(Parcel in) {
return new SavedState(in);
}
@Override
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
@Override
public void clearAllFields() {
if (mFieldEditTexts != null) {
for (EditText fieldEditText : mFieldEditTexts) {
// Update UI (which will trigger a state change through the {@link TextWatcher})
fieldEditText.setText("");
}
}
}
}
|
package com.oath.cyclops.jackson.serializers;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import cyclops.data.tuple.Tuple2;
import cyclops.data.tuple.Tuple3;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import java.io.IOException;
public class Tuple3Serializer extends JsonSerializer<Tuple3<?,?,?>> {
private static final long serialVersionUID = 1L;
@Override
public void serialize(Tuple3<?,?,?> value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
Object[] array = new Object[]{value._1(),value._2(),value._3()};
gen.writeStartArray();
for(Object o : array) {
JsonSerializer<Object> ser = serializers.findTypedValueSerializer(o.getClass(),true,null);
ser.serialize(o, gen, serializers);
}
gen.writeEndArray();
}
}
|
import java.io.*;
import java.util.*;
public class solutionOfLab11A {
static class node{
long L;
long R;
long N;
node(){};
node(long L,long R,long N){
this.L = L;
this.R = R;
this.N = N;
}
}
static ArrayList<node> table = new ArrayList<>();
public static void main(String[] args) throws IOException {
Reader in = new Reader();
PrintWriter out = new PrintWriter(System.out);
int N = in.nextInt();
long[] list = new long[N];
long max = 0;
table.add(new node(1,0,0));
for(int i =0;i<N;i++){
long data = in.nextLong();
list[i] = data;
max = Math.max(data,max);
}
long level = findN(max);
for(int i =0;i<N;i++){
long[] ans = countLRN(list[i]);
System.out.println(ans[0]+" "+ans[1]+" "+ans[2]);
}
}
static long[] countLRN(long len){
if(len == 0){
return new long[]{0, 0, 0};
}
long index = (long)(Math.log(len)/Math.log(2));
node a = table.get((int) index);
long[] LRN1 = new long[3];
LRN1[0] =a.L;
LRN1[1] = a.R;
LRN1[2] = a.N;
long[] LRN2 = countLRN(len-(long)Math.pow(2,index));
long[] LRN3 = new long[3];
LRN3[0] = LRN1[0] + LRN2[2];
LRN3[1] = LRN1[1] + LRN2[0];
LRN3[2] = LRN1[2] + LRN2[1];
return LRN3;
}
static long findN(long index){
long n = 1;
long len = 2;
while(len<=index){
len *=2;
node a = new node();
node node1 = table.get((int) (n-1));
a.L = node1.L + node1.N;
a.R = node1.R + node1.L;
a.N = node1.N + node1.R;
table.add(a);
n++;
}
return n;
}
static class Reader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;
public Reader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public Reader(String file_name) throws IOException {
din = new DataInputStream(new FileInputStream(file_name));
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}
public String readLine() throws IOException {
byte[] buf = new byte[64]; // line length
int cnt = 0, c;
while ((c = read()) != -1) {
if (c == '\n')
break;
buf[cnt++] = (byte) c;
}
return new String(buf, 0, cnt);
}
public int nextInt() throws IOException {
int ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
} while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public long nextLong() throws IOException {
long ret = 0;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (neg)
return -ret;
return ret;
}
public double nextDouble() throws IOException {
double ret = 0, div = 1;
byte c = read();
while (c <= ' ')
c = read();
boolean neg = (c == '-');
if (neg)
c = read();
do {
ret = ret * 10 + c - '0';
}
while ((c = read()) >= '0' && c <= '9');
if (c == '.') {
while ((c = read()) >= '0' && c <= '9') {
ret += (c - '0') / (div *= 10);
}
}
if (neg)
return -ret;
return ret;
}
private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}
private byte read() throws IOException {
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
public void close() throws IOException {
if (din == null)
return;
din.close();
}
}
}
|
package com.algorithm.programmers.level2;
public class StockPrice {
public static void main(String[] args) {
// 문제 설명
// 초 단위로 기록된 주식가격이 담긴 배열 prices가 매개변수로 주어질 때, 가격이 떨어지지 않은 기간은 몇 초인지를 return 하도록 solution 함수를 완성하세요.
//
// 제한사항
// prices의 각 가격은 1 이상 10,000 이하인 자연수입니다.
// prices의 길이는 2 이상 100,000 이하입니다.
// 입출력 예
// prices return
// [1, 2, 3, 2, 3] [4, 3, 1, 1, 0]
// 입출력 예 설명
// 1초 시점의 ₩1은 끝까지 가격이 떨어지지 않았습니다.
// 2초 시점의 ₩2은 끝까지 가격이 떨어지지 않았습니다.
// 3초 시점의 ₩3은 1초뒤에 가격이 떨어집니다. 따라서 1초간 가격이 떨어지지 않은 것으로 봅니다.
// 4초 시점의 ₩2은 1초간 가격이 떨어지지 않았습니다.
// 5초 시점의 ₩3은 0초간 가격이 떨어지지 않았습니다.
// ※ 공지 - 2019년 2월 28일 지문이 리뉴얼되었습니다.
System.out.println("3월 8일");
}
}
|
package seedu.address.logic.parser;
import static seedu.address.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import seedu.address.commons.core.index.Index;
import seedu.address.logic.commands.DeleteNoteCommand;
import seedu.address.logic.parser.exceptions.ParseException;
/**
* Parses input arguments and creates a new DeleteCommand object
*/
public class DeleteNoteCommandParser implements Parser<DeleteNoteCommand> {
/**
* Parses the given {@code String} of arguments in the context of the DeleteCommand
* and returns a DeleteCommand object for execution.
* @throws ParseException if the user input does not conform the expected format
*/
public DeleteNoteCommand parse(String args) throws ParseException {
try {
Index index = ParserUtil.parseIndex(args);
return new DeleteNoteCommand(index);
} catch (ParseException pe) {
throw new ParseException(
String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteNoteCommand.MESSAGE_USAGE), pe);
}
}
}
|
/* Copyright 2002-2021 CS GROUP
* Licensed to CS GROUP (CS) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* CS 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.orekit.utils;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.hipparchus.Field;
import org.hipparchus.RealFieldElement;
import org.hipparchus.analysis.differentiation.DSFactory;
import org.hipparchus.analysis.differentiation.DerivativeStructure;
import org.hipparchus.analysis.differentiation.FieldDerivativeStructure;
import org.hipparchus.analysis.differentiation.FieldUnivariateDerivative1;
import org.hipparchus.analysis.differentiation.FieldUnivariateDerivative2;
import org.hipparchus.analysis.polynomials.PolynomialFunction;
import org.hipparchus.geometry.euclidean.threed.FieldVector3D;
import org.hipparchus.util.Decimal64;
import org.hipparchus.util.Decimal64Field;
import org.hipparchus.util.FastMath;
import org.junit.Assert;
import org.junit.Test;
import org.orekit.Utils;
import org.orekit.time.AbsoluteDate;
import org.orekit.time.FieldAbsoluteDate;
public class TimeStampedFieldPVCoordinatesTest {
@Test
public void testLinearConstructors() {
DSFactory factory = new DSFactory(6, 1);
TimeStampedFieldPVCoordinates<DerivativeStructure> pv1 =
new TimeStampedFieldPVCoordinates<>(AbsoluteDate.CCSDS_EPOCH,
createVector( 1, 0.1, 10, 6),
createVector(-1, -0.1, -10, 6),
createVector(10, 1.0, 100, 6));
TimeStampedFieldPVCoordinates<DerivativeStructure> pv2 =
new TimeStampedFieldPVCoordinates<>(AbsoluteDate.FIFTIES_EPOCH,
createVector( 2, 0.2, 20, 6),
createVector(-2, -0.2, -20, 6),
createVector(20, 2.0, 200, 6));
TimeStampedFieldPVCoordinates<DerivativeStructure> pv3 =
new TimeStampedFieldPVCoordinates<>(AbsoluteDate.GALILEO_EPOCH,
createVector( 3, 0.3, 30, 6),
createVector(-3, -0.3, -30, 6),
createVector(30, 3.0, 300, 6));
TimeStampedFieldPVCoordinates<DerivativeStructure> pv4 =
new TimeStampedFieldPVCoordinates<>(AbsoluteDate.JULIAN_EPOCH,
createVector( 4, 0.4, 40, 6),
createVector(-4, -0.4, -40, 6),
createVector(40, 4.0, 400, 6));
checkPV(pv4, new TimeStampedFieldPVCoordinates<>(AbsoluteDate.JULIAN_EPOCH, 4, pv1), 1.0e-15);
checkPV(pv4, new TimeStampedFieldPVCoordinates<>(AbsoluteDate.JULIAN_EPOCH, factory.constant(4), pv1), 1.0e-15);
checkPV(pv4, new TimeStampedFieldPVCoordinates<>(AbsoluteDate.JULIAN_EPOCH, factory.constant(4), pv1.toPVCoordinates()), 1.0e-15);
checkPV(pv2, new TimeStampedFieldPVCoordinates<>(AbsoluteDate.FIFTIES_EPOCH, pv1, pv3), 1.0e-15);
checkPV(pv3, new TimeStampedFieldPVCoordinates<>(AbsoluteDate.GALILEO_EPOCH, 1, pv1, 1, pv2), 1.0e-15);
checkPV(pv3,
new TimeStampedFieldPVCoordinates<>(AbsoluteDate.GALILEO_EPOCH,
factory.constant(1), pv1,
factory.constant(1), pv2),
1.0e-15);
checkPV(pv3,
new TimeStampedFieldPVCoordinates<>(AbsoluteDate.GALILEO_EPOCH,
factory.constant(1), pv1.toPVCoordinates(),
factory.constant(1), pv2.toPVCoordinates()),
1.0e-15);
checkPV(new TimeStampedFieldPVCoordinates<>(AbsoluteDate.J2000_EPOCH, 2, pv4),
new TimeStampedFieldPVCoordinates<>(AbsoluteDate.J2000_EPOCH, 3, pv1, 1, pv2, 1, pv3),
1.0e-15);
checkPV(new TimeStampedFieldPVCoordinates<>(AbsoluteDate.J2000_EPOCH, 3, pv3),
new TimeStampedFieldPVCoordinates<>(AbsoluteDate.J2000_EPOCH, 3, pv1, 1, pv2, 1, pv4),
1.0e-15);
checkPV(new TimeStampedFieldPVCoordinates<>(AbsoluteDate.J2000_EPOCH, 3, pv3),
new TimeStampedFieldPVCoordinates<>(AbsoluteDate.J2000_EPOCH,
factory.constant(3), pv1,
factory.constant(1), pv2,
factory.constant(1), pv4),
1.0e-15);
checkPV(new TimeStampedFieldPVCoordinates<>(AbsoluteDate.J2000_EPOCH, 3, pv3),
new TimeStampedFieldPVCoordinates<>(AbsoluteDate.J2000_EPOCH,
factory.constant(3), pv1.toPVCoordinates(),
factory.constant(1), pv2.toPVCoordinates(),
factory.constant(1), pv4.toPVCoordinates()),
1.0e-15);
checkPV(new TimeStampedFieldPVCoordinates<>(AbsoluteDate.J2000_EPOCH, 5, pv4),
new TimeStampedFieldPVCoordinates<>(AbsoluteDate.J2000_EPOCH, 4, pv1, 3, pv2, 2, pv3, 1, pv4), 1.0e-15);
checkPV(new TimeStampedFieldPVCoordinates<>(AbsoluteDate.J2000_EPOCH, 5, pv4),
new TimeStampedFieldPVCoordinates<>(AbsoluteDate.J2000_EPOCH,
factory.constant(4), pv1,
factory.constant(3), pv2,
factory.constant(2), pv3,
factory.constant(1), pv4),
1.0e-15);
checkPV(new TimeStampedFieldPVCoordinates<>(AbsoluteDate.J2000_EPOCH, 5, pv4),
new TimeStampedFieldPVCoordinates<>(AbsoluteDate.J2000_EPOCH,
factory.constant(4), pv1.toPVCoordinates(),
factory.constant(3), pv2.toPVCoordinates(),
factory.constant(2), pv3.toPVCoordinates(),
factory.constant(1), pv4.toPVCoordinates()),
1.0e-15);
}
@Test
public void testToDerivativeStructureVector1() {
FieldVector3D<FieldDerivativeStructure<Decimal64>> fv =
new TimeStampedFieldPVCoordinates<>(FieldAbsoluteDate.getGalileoEpoch(Decimal64Field.getInstance()),
new FieldVector3D<>(new Decimal64( 1), new Decimal64( 0.1), new Decimal64( 10)),
new FieldVector3D<>(new Decimal64(-1), new Decimal64(-0.1), new Decimal64(-10)),
new FieldVector3D<>(new Decimal64(10), new Decimal64(-1.0), new Decimal64(-100))).
toDerivativeStructureVector(1);
Assert.assertEquals(1, fv.getX().getFreeParameters());
Assert.assertEquals(1, fv.getX().getOrder());
Assert.assertEquals( 1.0, fv.getX().getReal(), 1.0e-10);
Assert.assertEquals( 0.1, fv.getY().getReal(), 1.0e-10);
Assert.assertEquals( 10.0, fv.getZ().getReal(), 1.0e-10);
Assert.assertEquals( -1.0, fv.getX().getPartialDerivative(1).doubleValue(), 1.0e-15);
Assert.assertEquals( -0.1, fv.getY().getPartialDerivative(1).doubleValue(), 1.0e-15);
Assert.assertEquals( -10.0, fv.getZ().getPartialDerivative(1).doubleValue(), 1.0e-15);
checkPV(new TimeStampedFieldPVCoordinates<>(FieldAbsoluteDate.getGalileoEpoch(Decimal64Field.getInstance()),
new FieldVector3D<>(new Decimal64( 1), new Decimal64( 0.1), new Decimal64( 10)),
new FieldVector3D<>(new Decimal64(-1), new Decimal64(-0.1), new Decimal64(-10)),
FieldVector3D.getZero(Decimal64Field.getInstance())),
new TimeStampedFieldPVCoordinates<>(FieldAbsoluteDate.getGalileoEpoch(Decimal64Field.getInstance()), fv), 1.0e-15);
for (double dt = 0; dt < 10; dt += 0.125) {
FieldVector3D<Decimal64> p = new FieldPVCoordinates<>(new FieldVector3D<>(new Decimal64( 1), new Decimal64( 0.1), new Decimal64( 10)),
new FieldVector3D<>(new Decimal64(-1), new Decimal64(-0.1), new Decimal64(-10))).
shiftedBy(dt).getPosition();
Assert.assertEquals(p.getX().doubleValue(), fv.getX().taylor(dt).doubleValue(), 1.0e-14);
Assert.assertEquals(p.getY().doubleValue(), fv.getY().taylor(dt).doubleValue(), 1.0e-14);
Assert.assertEquals(p.getZ().doubleValue(), fv.getZ().taylor(dt).doubleValue(), 1.0e-14);
}
TimeStampedFieldPVCoordinates<Decimal64> fpv =
new TimeStampedFieldPVCoordinates<>(FieldAbsoluteDate.getGalileoEpoch(Decimal64Field.getInstance()),
fv);
Assert.assertEquals( 1.0, fpv.getPosition().getX().getReal(), 1.0e-10);
Assert.assertEquals( 0.1, fpv.getPosition().getY().getReal(), 1.0e-10);
Assert.assertEquals( 10.0, fpv.getPosition().getZ().getReal(), 1.0e-10);
Assert.assertEquals( -1.0, fpv.getVelocity().getX().getReal(), 1.0e-15);
Assert.assertEquals( -0.1, fpv.getVelocity().getY().getReal(), 1.0e-15);
Assert.assertEquals( -10.0, fpv.getVelocity().getZ().getReal(), 1.0e-15);
}
@Test
public void testToDerivativeStructureVector2() {
FieldVector3D<FieldDerivativeStructure<Decimal64>> fv =
new TimeStampedFieldPVCoordinates<>(FieldAbsoluteDate.getGalileoEpoch(Decimal64Field.getInstance()),
new FieldVector3D<>(new Decimal64( 1), new Decimal64( 0.1), new Decimal64( 10)),
new FieldVector3D<>(new Decimal64(-1), new Decimal64(-0.1), new Decimal64(-10)),
new FieldVector3D<>(new Decimal64(10), new Decimal64(-1.0), new Decimal64(-100))).
toDerivativeStructureVector(2);
Assert.assertEquals(1, fv.getX().getFreeParameters());
Assert.assertEquals(2, fv.getX().getOrder());
Assert.assertEquals( 1.0, fv.getX().getReal(), 1.0e-10);
Assert.assertEquals( 0.1, fv.getY().getReal(), 1.0e-10);
Assert.assertEquals( 10.0, fv.getZ().getReal(), 1.0e-10);
Assert.assertEquals( -1.0, fv.getX().getPartialDerivative(1).doubleValue(), 1.0e-15);
Assert.assertEquals( -0.1, fv.getY().getPartialDerivative(1).doubleValue(), 1.0e-15);
Assert.assertEquals( -10.0, fv.getZ().getPartialDerivative(1).doubleValue(), 1.0e-15);
Assert.assertEquals( 10.0, fv.getX().getPartialDerivative(2).doubleValue(), 1.0e-15);
Assert.assertEquals( -1.0, fv.getY().getPartialDerivative(2).doubleValue(), 1.0e-15);
Assert.assertEquals(-100.0, fv.getZ().getPartialDerivative(2).doubleValue(), 1.0e-15);
checkPV(new TimeStampedFieldPVCoordinates<>(FieldAbsoluteDate.getGalileoEpoch(Decimal64Field.getInstance()),
new FieldVector3D<>(new Decimal64( 1), new Decimal64( 0.1), new Decimal64( 10)),
new FieldVector3D<>(new Decimal64(-1), new Decimal64(-0.1), new Decimal64(-10)),
new FieldVector3D<>(new Decimal64(10), new Decimal64(-1.0), new Decimal64(-100))),
new TimeStampedFieldPVCoordinates<>(FieldAbsoluteDate.getGalileoEpoch(Decimal64Field.getInstance()), fv), 1.0e-15);
for (double dt = 0; dt < 10; dt += 0.125) {
FieldVector3D<Decimal64> p = new FieldPVCoordinates<>(new FieldVector3D<>(new Decimal64( 1), new Decimal64( 0.1), new Decimal64( 10)),
new FieldVector3D<>(new Decimal64(-1), new Decimal64(-0.1), new Decimal64(-10)),
new FieldVector3D<>(new Decimal64(10), new Decimal64(-1.0), new Decimal64(-100))).
shiftedBy(dt).getPosition();
Assert.assertEquals(p.getX().doubleValue(), fv.getX().taylor(dt).doubleValue(), 1.0e-14);
Assert.assertEquals(p.getY().doubleValue(), fv.getY().taylor(dt).doubleValue(), 1.0e-14);
Assert.assertEquals(p.getZ().doubleValue(), fv.getZ().taylor(dt).doubleValue(), 1.0e-14);
}
TimeStampedFieldPVCoordinates<Decimal64> fpv =
new TimeStampedFieldPVCoordinates<>(FieldAbsoluteDate.getGalileoEpoch(Decimal64Field.getInstance()),
fv);
Assert.assertEquals( 1.0, fpv.getPosition().getX().getReal(), 1.0e-10);
Assert.assertEquals( 0.1, fpv.getPosition().getY().getReal(), 1.0e-10);
Assert.assertEquals( 10.0, fpv.getPosition().getZ().getReal(), 1.0e-10);
Assert.assertEquals( -1.0, fpv.getVelocity().getX().getReal(), 1.0e-15);
Assert.assertEquals( -0.1, fpv.getVelocity().getY().getReal(), 1.0e-15);
Assert.assertEquals( -10.0, fpv.getVelocity().getZ().getReal(), 1.0e-15);
Assert.assertEquals( 10.0, fpv.getAcceleration().getX().getReal(), 1.0e-15);
Assert.assertEquals( -1.0, fpv.getAcceleration().getY().getReal(), 1.0e-15);
Assert.assertEquals(-100.0, fpv.getAcceleration().getZ().getReal(), 1.0e-15);
}
@Test
public void testToUnivariateDerivative1Vector() {
FieldVector3D<FieldUnivariateDerivative1<Decimal64>> fv =
new TimeStampedFieldPVCoordinates<>(FieldAbsoluteDate.getGalileoEpoch(Decimal64Field.getInstance()),
new FieldVector3D<>(new Decimal64( 1), new Decimal64( 0.1), new Decimal64( 10)),
new FieldVector3D<>(new Decimal64(-1), new Decimal64(-0.1), new Decimal64(-10)),
new FieldVector3D<>(new Decimal64(10), new Decimal64(-1.0), new Decimal64(-100))).
toUnivariateDerivative1Vector();
Assert.assertEquals(1, fv.getX().getFreeParameters());
Assert.assertEquals(1, fv.getX().getOrder());
Assert.assertEquals( 1.0, fv.getX().getReal(), 1.0e-10);
Assert.assertEquals( 0.1, fv.getY().getReal(), 1.0e-10);
Assert.assertEquals( 10.0, fv.getZ().getReal(), 1.0e-10);
Assert.assertEquals( -1.0, fv.getX().getPartialDerivative(1).doubleValue(), 1.0e-15);
Assert.assertEquals( -0.1, fv.getY().getPartialDerivative(1).doubleValue(), 1.0e-15);
Assert.assertEquals( -10.0, fv.getZ().getPartialDerivative(1).doubleValue(), 1.0e-15);
checkPV(new TimeStampedFieldPVCoordinates<>(FieldAbsoluteDate.getGalileoEpoch(Decimal64Field.getInstance()),
new FieldVector3D<>(new Decimal64( 1), new Decimal64( 0.1), new Decimal64( 10)),
new FieldVector3D<>(new Decimal64(-1), new Decimal64(-0.1), new Decimal64(-10)),
FieldVector3D.getZero(Decimal64Field.getInstance())),
new TimeStampedFieldPVCoordinates<>(FieldAbsoluteDate.getGalileoEpoch(Decimal64Field.getInstance()), fv), 1.0e-15);
for (double dt = 0; dt < 10; dt += 0.125) {
FieldVector3D<Decimal64> p = new FieldPVCoordinates<>(new FieldVector3D<>(new Decimal64( 1), new Decimal64( 0.1), new Decimal64( 10)),
new FieldVector3D<>(new Decimal64(-1), new Decimal64(-0.1), new Decimal64(-10))).
shiftedBy(dt).getPosition();
Assert.assertEquals(p.getX().doubleValue(), fv.getX().taylor(dt).doubleValue(), 1.0e-14);
Assert.assertEquals(p.getY().doubleValue(), fv.getY().taylor(dt).doubleValue(), 1.0e-14);
Assert.assertEquals(p.getZ().doubleValue(), fv.getZ().taylor(dt).doubleValue(), 1.0e-14);
}
TimeStampedFieldPVCoordinates<Decimal64> fpv =
new TimeStampedFieldPVCoordinates<>(FieldAbsoluteDate.getGalileoEpoch(Decimal64Field.getInstance()),
fv);
Assert.assertEquals( 1.0, fpv.getPosition().getX().getReal(), 1.0e-10);
Assert.assertEquals( 0.1, fpv.getPosition().getY().getReal(), 1.0e-10);
Assert.assertEquals( 10.0, fpv.getPosition().getZ().getReal(), 1.0e-10);
Assert.assertEquals( -1.0, fpv.getVelocity().getX().getReal(), 1.0e-15);
Assert.assertEquals( -0.1, fpv.getVelocity().getY().getReal(), 1.0e-15);
Assert.assertEquals( -10.0, fpv.getVelocity().getZ().getReal(), 1.0e-15);
}
@Test
public void testToUnivariateDerivative2Vector() {
FieldVector3D<FieldUnivariateDerivative2<Decimal64>> fv =
new TimeStampedFieldPVCoordinates<>(FieldAbsoluteDate.getGalileoEpoch(Decimal64Field.getInstance()),
new FieldVector3D<>(new Decimal64( 1), new Decimal64( 0.1), new Decimal64( 10)),
new FieldVector3D<>(new Decimal64(-1), new Decimal64(-0.1), new Decimal64(-10)),
new FieldVector3D<>(new Decimal64(10), new Decimal64(-1.0), new Decimal64(-100))).
toUnivariateDerivative2Vector();
Assert.assertEquals(1, fv.getX().getFreeParameters());
Assert.assertEquals(2, fv.getX().getOrder());
Assert.assertEquals( 1.0, fv.getX().getReal(), 1.0e-10);
Assert.assertEquals( 0.1, fv.getY().getReal(), 1.0e-10);
Assert.assertEquals( 10.0, fv.getZ().getReal(), 1.0e-10);
Assert.assertEquals( -1.0, fv.getX().getPartialDerivative(1).doubleValue(), 1.0e-15);
Assert.assertEquals( -0.1, fv.getY().getPartialDerivative(1).doubleValue(), 1.0e-15);
Assert.assertEquals( -10.0, fv.getZ().getPartialDerivative(1).doubleValue(), 1.0e-15);
Assert.assertEquals( 10.0, fv.getX().getPartialDerivative(2).doubleValue(), 1.0e-15);
Assert.assertEquals( -1.0, fv.getY().getPartialDerivative(2).doubleValue(), 1.0e-15);
Assert.assertEquals(-100.0, fv.getZ().getPartialDerivative(2).doubleValue(), 1.0e-15);
checkPV(new TimeStampedFieldPVCoordinates<>(FieldAbsoluteDate.getGalileoEpoch(Decimal64Field.getInstance()),
new FieldVector3D<>(new Decimal64( 1), new Decimal64( 0.1), new Decimal64( 10)),
new FieldVector3D<>(new Decimal64(-1), new Decimal64(-0.1), new Decimal64(-10)),
new FieldVector3D<>(new Decimal64(10), new Decimal64(-1.0), new Decimal64(-100))),
new TimeStampedFieldPVCoordinates<>(FieldAbsoluteDate.getGalileoEpoch(Decimal64Field.getInstance()), fv), 1.0e-15);
for (double dt = 0; dt < 10; dt += 0.125) {
FieldVector3D<Decimal64> p = new FieldPVCoordinates<>(new FieldVector3D<>(new Decimal64( 1), new Decimal64( 0.1), new Decimal64( 10)),
new FieldVector3D<>(new Decimal64(-1), new Decimal64(-0.1), new Decimal64(-10)),
new FieldVector3D<>(new Decimal64(10), new Decimal64(-1.0), new Decimal64(-100))).
shiftedBy(dt).getPosition();
Assert.assertEquals(p.getX().doubleValue(), fv.getX().taylor(dt).doubleValue(), 1.0e-14);
Assert.assertEquals(p.getY().doubleValue(), fv.getY().taylor(dt).doubleValue(), 1.0e-14);
Assert.assertEquals(p.getZ().doubleValue(), fv.getZ().taylor(dt).doubleValue(), 1.0e-14);
}
TimeStampedFieldPVCoordinates<Decimal64> fpv =
new TimeStampedFieldPVCoordinates<>(FieldAbsoluteDate.getGalileoEpoch(Decimal64Field.getInstance()),
fv);
Assert.assertEquals( 1.0, fpv.getPosition().getX().getReal(), 1.0e-10);
Assert.assertEquals( 0.1, fpv.getPosition().getY().getReal(), 1.0e-10);
Assert.assertEquals( 10.0, fpv.getPosition().getZ().getReal(), 1.0e-10);
Assert.assertEquals( -1.0, fpv.getVelocity().getX().getReal(), 1.0e-15);
Assert.assertEquals( -0.1, fpv.getVelocity().getY().getReal(), 1.0e-15);
Assert.assertEquals( -10.0, fpv.getVelocity().getZ().getReal(), 1.0e-15);
Assert.assertEquals( 10.0, fpv.getAcceleration().getX().getReal(), 1.0e-15);
Assert.assertEquals( -1.0, fpv.getAcceleration().getY().getReal(), 1.0e-15);
Assert.assertEquals(-100.0, fpv.getAcceleration().getZ().getReal(), 1.0e-15);
}
@Test
public void testShift() {
FieldVector3D<DerivativeStructure> p1 = createVector( 1, 0.1, 10, 4);
FieldVector3D<DerivativeStructure> v1 = createVector( -1, -0.1, -10, 4);
FieldVector3D<DerivativeStructure> a1 = createVector( 10, 1.0, 100, 4);
FieldVector3D<DerivativeStructure> p2 = createVector( 7, 0.7, 70, 4);
FieldVector3D<DerivativeStructure> v2 = createVector(-11, -1.1, -110, 4);
FieldVector3D<DerivativeStructure> a2 = createVector( 10, 1.0, 100, 4);
checkPV(new TimeStampedFieldPVCoordinates<>(AbsoluteDate.J2000_EPOCH, p2, v2, a2),
new TimeStampedFieldPVCoordinates<>(AbsoluteDate.J2000_EPOCH.shiftedBy(1.0), p1, v1, a1).shiftedBy(-1.0), 1.0e-15);
Assert.assertEquals(0.0,
TimeStampedFieldPVCoordinates.estimateVelocity(p1, p2, -1.0).subtract(createVector(-6, -0.6, -60, 4)).getNorm().getReal(),
1.0e-15);
}
@Test
public void testToString() {
Utils.setDataRoot("regular-data");
TimeStampedFieldPVCoordinates<DerivativeStructure> pv =
new TimeStampedFieldPVCoordinates<>(AbsoluteDate.J2000_EPOCH,
createVector( 1, 0.1, 10, 4),
createVector(-1, -0.1, -10, 4),
createVector(10, 1.0, 100, 4));
Assert.assertEquals("{2000-01-01T11:58:55.816, P(1.0, 0.1, 10.0), V(-1.0, -0.1, -10.0), A(10.0, 1.0, 100.0)}", pv.toString());
}
@Test
public void testInterpolatePolynomialPVA() {
Random random = new Random(0xfe3945fcb8bf47cel);
AbsoluteDate t0 = AbsoluteDate.J2000_EPOCH;
for (int i = 0; i < 20; ++i) {
PolynomialFunction px = randomPolynomial(5, random);
PolynomialFunction py = randomPolynomial(5, random);
PolynomialFunction pz = randomPolynomial(5, random);
PolynomialFunction pxDot = px.polynomialDerivative();
PolynomialFunction pyDot = py.polynomialDerivative();
PolynomialFunction pzDot = pz.polynomialDerivative();
PolynomialFunction pxDotDot = pxDot.polynomialDerivative();
PolynomialFunction pyDotDot = pyDot.polynomialDerivative();
PolynomialFunction pzDotDot = pzDot.polynomialDerivative();
List<TimeStampedFieldPVCoordinates<DerivativeStructure>> sample =
new ArrayList<TimeStampedFieldPVCoordinates<DerivativeStructure>>();
for (double dt : new double[] { 0.0, 0.5, 1.0 }) {
FieldVector3D<DerivativeStructure> position = createVector(px.value(dt), py.value(dt), pz.value(dt), 4);
FieldVector3D<DerivativeStructure> velocity = createVector(pxDot.value(dt), pyDot.value(dt), pzDot.value(dt), 4);
FieldVector3D<DerivativeStructure> acceleration = createVector(pxDotDot.value(dt), pyDotDot.value(dt), pzDotDot.value(dt), 4);
sample.add(new TimeStampedFieldPVCoordinates<>(t0.shiftedBy(dt), position, velocity, acceleration));
}
Field<DerivativeStructure> field = sample.get(0).getDate().getField();
for (double dt = 0; dt < 1.0; dt += 0.01) {
FieldAbsoluteDate<DerivativeStructure> t = new FieldAbsoluteDate<>(field, t0.shiftedBy(dt));
TimeStampedFieldPVCoordinates<DerivativeStructure> interpolated =
TimeStampedFieldPVCoordinates.interpolate(t, CartesianDerivativesFilter.USE_PVA, sample);
FieldVector3D<DerivativeStructure> p = interpolated.getPosition();
FieldVector3D<DerivativeStructure> v = interpolated.getVelocity();
FieldVector3D<DerivativeStructure> a = interpolated.getAcceleration();
Assert.assertEquals(px.value(dt), p.getX().getReal(), 4.0e-16 * p.getNorm().getReal());
Assert.assertEquals(py.value(dt), p.getY().getReal(), 4.0e-16 * p.getNorm().getReal());
Assert.assertEquals(pz.value(dt), p.getZ().getReal(), 4.0e-16 * p.getNorm().getReal());
Assert.assertEquals(pxDot.value(dt), v.getX().getReal(), 9.0e-16 * v.getNorm().getReal());
Assert.assertEquals(pyDot.value(dt), v.getY().getReal(), 9.0e-16 * v.getNorm().getReal());
Assert.assertEquals(pzDot.value(dt), v.getZ().getReal(), 9.0e-16 * v.getNorm().getReal());
Assert.assertEquals(pxDotDot.value(dt), a.getX().getReal(), 6.0e-15 * a.getNorm().getReal());
Assert.assertEquals(pyDotDot.value(dt), a.getY().getReal(), 6.0e-15 * a.getNorm().getReal());
Assert.assertEquals(pzDotDot.value(dt), a.getZ().getReal(), 6.0e-15 * a.getNorm().getReal());
}
}
}
@Test
public void testInterpolatePolynomialPV() {
Random random = new Random(0xae7771c9933407bdl);
AbsoluteDate t0 = AbsoluteDate.J2000_EPOCH;
for (int i = 0; i < 20; ++i) {
PolynomialFunction px = randomPolynomial(5, random);
PolynomialFunction py = randomPolynomial(5, random);
PolynomialFunction pz = randomPolynomial(5, random);
PolynomialFunction pxDot = px.polynomialDerivative();
PolynomialFunction pyDot = py.polynomialDerivative();
PolynomialFunction pzDot = pz.polynomialDerivative();
PolynomialFunction pxDotDot = pxDot.polynomialDerivative();
PolynomialFunction pyDotDot = pyDot.polynomialDerivative();
PolynomialFunction pzDotDot = pzDot.polynomialDerivative();
List<TimeStampedFieldPVCoordinates<DerivativeStructure>> sample =
new ArrayList<TimeStampedFieldPVCoordinates<DerivativeStructure>>();
for (double dt : new double[] { 0.0, 0.5, 1.0 }) {
FieldVector3D<DerivativeStructure> position = createVector(px.value(dt), py.value(dt), pz.value(dt), 4);
FieldVector3D<DerivativeStructure> velocity = createVector(pxDot.value(dt), pyDot.value(dt), pzDot.value(dt), 4);
sample.add(new TimeStampedFieldPVCoordinates<>(t0.shiftedBy(dt), position, velocity, createVector(0, 0, 0, 4)));
}
Field<DerivativeStructure> field = sample.get(0).getDate().getField();
for (double dt = 0; dt < 1.0; dt += 0.01) {
FieldAbsoluteDate<DerivativeStructure> t = new FieldAbsoluteDate<>(field, t0.shiftedBy(dt));
TimeStampedFieldPVCoordinates<DerivativeStructure> interpolated =
TimeStampedFieldPVCoordinates.interpolate(t, CartesianDerivativesFilter.USE_PV, sample);
FieldVector3D<DerivativeStructure> p = interpolated.getPosition();
FieldVector3D<DerivativeStructure> v = interpolated.getVelocity();
FieldVector3D<DerivativeStructure> a = interpolated.getAcceleration();
Assert.assertEquals(px.value(dt), p.getX().getReal(), 4.0e-16 * p.getNorm().getReal());
Assert.assertEquals(py.value(dt), p.getY().getReal(), 4.0e-16 * p.getNorm().getReal());
Assert.assertEquals(pz.value(dt), p.getZ().getReal(), 4.0e-16 * p.getNorm().getReal());
Assert.assertEquals(pxDot.value(dt), v.getX().getReal(), 9.0e-16 * v.getNorm().getReal());
Assert.assertEquals(pyDot.value(dt), v.getY().getReal(), 9.0e-16 * v.getNorm().getReal());
Assert.assertEquals(pzDot.value(dt), v.getZ().getReal(), 9.0e-16 * v.getNorm().getReal());
Assert.assertEquals(pxDotDot.value(dt), a.getX().getReal(), 1.0e-14 * a.getNorm().getReal());
Assert.assertEquals(pyDotDot.value(dt), a.getY().getReal(), 1.0e-14 * a.getNorm().getReal());
Assert.assertEquals(pzDotDot.value(dt), a.getZ().getReal(), 1.0e-14 * a.getNorm().getReal());
}
}
}
@Test
public void testInterpolatePolynomialPositionOnly() {
Random random = new Random(0x88740a12e4299003l);
AbsoluteDate t0 = AbsoluteDate.J2000_EPOCH;
for (int i = 0; i < 20; ++i) {
PolynomialFunction px = randomPolynomial(5, random);
PolynomialFunction py = randomPolynomial(5, random);
PolynomialFunction pz = randomPolynomial(5, random);
PolynomialFunction pxDot = px.polynomialDerivative();
PolynomialFunction pyDot = py.polynomialDerivative();
PolynomialFunction pzDot = pz.polynomialDerivative();
PolynomialFunction pxDotDot = pxDot.polynomialDerivative();
PolynomialFunction pyDotDot = pyDot.polynomialDerivative();
PolynomialFunction pzDotDot = pzDot.polynomialDerivative();
List<TimeStampedFieldPVCoordinates<DerivativeStructure>> sample =
new ArrayList<TimeStampedFieldPVCoordinates<DerivativeStructure>>();
for (double dt : new double[] { 0.0, 0.2, 0.4, 0.6, 0.8, 1.0 }) {
FieldVector3D<DerivativeStructure> position = createVector(px.value(dt), py.value(dt), pz.value(dt), 4);
sample.add(new TimeStampedFieldPVCoordinates<>(t0.shiftedBy(dt),
position,
createVector(0, 0, 0, 4),
createVector(0, 0, 0, 4)));
}
Field<DerivativeStructure> field = sample.get(0).getDate().getField();
for (double dt = 0; dt < 1.0; dt += 0.01) {
FieldAbsoluteDate<DerivativeStructure> t = new FieldAbsoluteDate<>(field, t0.shiftedBy(dt));
TimeStampedFieldPVCoordinates<DerivativeStructure> interpolated =
TimeStampedFieldPVCoordinates.interpolate(t, CartesianDerivativesFilter.USE_P, sample);
FieldVector3D<DerivativeStructure> p = interpolated.getPosition();
FieldVector3D<DerivativeStructure> v = interpolated.getVelocity();
FieldVector3D<DerivativeStructure> a = interpolated.getAcceleration();
Assert.assertEquals(px.value(dt), p.getX().getReal(), 5.0e-16 * p.getNorm().getReal());
Assert.assertEquals(py.value(dt), p.getY().getReal(), 5.0e-16 * p.getNorm().getReal());
Assert.assertEquals(pz.value(dt), p.getZ().getReal(), 5.0e-16 * p.getNorm().getReal());
Assert.assertEquals(pxDot.value(dt), v.getX().getReal(), 7.0e-15 * v.getNorm().getReal());
Assert.assertEquals(pyDot.value(dt), v.getY().getReal(), 7.0e-15 * v.getNorm().getReal());
Assert.assertEquals(pzDot.value(dt), v.getZ().getReal(), 7.0e-15 * v.getNorm().getReal());
Assert.assertEquals(pxDotDot.value(dt), a.getX().getReal(), 2.0e-13 * a.getNorm().getReal());
Assert.assertEquals(pyDotDot.value(dt), a.getY().getReal(), 2.0e-13 * a.getNorm().getReal());
Assert.assertEquals(pzDotDot.value(dt), a.getZ().getReal(), 2.0e-13 * a.getNorm().getReal());
}
}
}
@Test
public void testInterpolateNonPolynomial() {
AbsoluteDate t0 = AbsoluteDate.J2000_EPOCH;
List<TimeStampedFieldPVCoordinates<DerivativeStructure>> sample =
new ArrayList<TimeStampedFieldPVCoordinates<DerivativeStructure>>();
for (double dt : new double[] { 0.0, 0.5, 1.0 }) {
FieldVector3D<DerivativeStructure> position = createVector( FastMath.cos(dt), FastMath.sin(dt), 0.0, 4);
FieldVector3D<DerivativeStructure> velocity = createVector(-FastMath.sin(dt), FastMath.cos(dt), 0.0, 4);
FieldVector3D<DerivativeStructure> acceleration = createVector(-FastMath.cos(dt), -FastMath.sin(dt), 0.0, 4);
sample.add(new TimeStampedFieldPVCoordinates<>(t0.shiftedBy(dt), position, velocity, acceleration));
}
Field<DerivativeStructure> field = sample.get(0).getDate().getField();
for (double dt = 0; dt < 1.0; dt += 0.01) {
FieldAbsoluteDate<DerivativeStructure> t = new FieldAbsoluteDate<>(field, t0.shiftedBy(dt));
TimeStampedFieldPVCoordinates<DerivativeStructure> interpolated =
TimeStampedFieldPVCoordinates.interpolate(t, CartesianDerivativesFilter.USE_PVA, sample);
FieldVector3D<DerivativeStructure> p = interpolated.getPosition();
FieldVector3D<DerivativeStructure> v = interpolated.getVelocity();
FieldVector3D<DerivativeStructure> a = interpolated.getAcceleration();
Assert.assertEquals( FastMath.cos(dt), p.getX().getReal(), 3.0e-10 * p.getNorm().getReal());
Assert.assertEquals( FastMath.sin(dt), p.getY().getReal(), 3.0e-10 * p.getNorm().getReal());
Assert.assertEquals(0, p.getZ().getReal(), 3.0e-10 * p.getNorm().getReal());
Assert.assertEquals(-FastMath.sin(dt), v.getX().getReal(), 3.0e-9 * v.getNorm().getReal());
Assert.assertEquals( FastMath.cos(dt), v.getY().getReal(), 3.0e-9 * v.getNorm().getReal());
Assert.assertEquals(0, v.getZ().getReal(), 3.0e-9 * v.getNorm().getReal());
Assert.assertEquals(-FastMath.cos(dt), a.getX().getReal(), 4.0e-8 * a.getNorm().getReal());
Assert.assertEquals(-FastMath.sin(dt), a.getY().getReal(), 4.0e-8 * a.getNorm().getReal());
Assert.assertEquals(0, a.getZ().getReal(), 4.0e-8 * a.getNorm().getReal());
}
}
@Test
public void testIssue510() {
DSFactory factory = new DSFactory(1, 1);
TimeStampedFieldPVCoordinates<DerivativeStructure> pv =
new TimeStampedFieldPVCoordinates<>(FieldAbsoluteDate.getJ2000Epoch(factory.getDerivativeField()),
new FieldVector3D<>(factory.constant(10.0),
factory.constant(20.0),
factory.constant(30.0)),
new FieldVector3D<>(factory.constant(1.0),
factory.constant(2.0),
factory.constant(3.0)),
FieldVector3D.getZero(factory.getDerivativeField()));
DerivativeStructure dt = factory.variable(0, 1.0);
TimeStampedFieldPVCoordinates<DerivativeStructure> shifted = pv.shiftedBy(dt);
Assert.assertEquals(1.0, shifted.getDate().durationFrom(pv.getDate()).getPartialDerivative(1), 1.0e-15);
Assert.assertEquals(pv.getVelocity().getX().getValue(), shifted.getPosition().getX().getPartialDerivative(1), 1.0e-15);
Assert.assertEquals(pv.getVelocity().getY().getValue(), shifted.getPosition().getY().getPartialDerivative(1), 1.0e-15);
Assert.assertEquals(pv.getVelocity().getZ().getValue(), shifted.getPosition().getZ().getPartialDerivative(1), 1.0e-15);
}
private PolynomialFunction randomPolynomial(int degree, Random random) {
double[] coeff = new double[ 1 + degree];
for (int j = 0; j < degree; ++j) {
coeff[j] = random.nextDouble();
}
return new PolynomialFunction(coeff);
}
private <T extends RealFieldElement<T>> void checkPV(TimeStampedFieldPVCoordinates<T> expected,
TimeStampedFieldPVCoordinates<T> real, double epsilon) {
Assert.assertEquals(expected.getDate(), real.getDate());
Assert.assertEquals(expected.getPosition().getX().getReal(), real.getPosition().getX().getReal(), epsilon);
Assert.assertEquals(expected.getPosition().getY().getReal(), real.getPosition().getY().getReal(), epsilon);
Assert.assertEquals(expected.getPosition().getZ().getReal(), real.getPosition().getZ().getReal(), epsilon);
Assert.assertEquals(expected.getVelocity().getX().getReal(), real.getVelocity().getX().getReal(), epsilon);
Assert.assertEquals(expected.getVelocity().getY().getReal(), real.getVelocity().getY().getReal(), epsilon);
Assert.assertEquals(expected.getVelocity().getZ().getReal(), real.getVelocity().getZ().getReal(), epsilon);
Assert.assertEquals(expected.getAcceleration().getX().getReal(), real.getAcceleration().getX().getReal(), epsilon);
Assert.assertEquals(expected.getAcceleration().getY().getReal(), real.getAcceleration().getY().getReal(), epsilon);
Assert.assertEquals(expected.getAcceleration().getZ().getReal(), real.getAcceleration().getZ().getReal(), epsilon);
}
private FieldVector3D<DerivativeStructure> createVector(double x, double y, double z, int params) {
DSFactory factory = new DSFactory(params, 1);
return new FieldVector3D<>(factory.variable(0, x),
factory.variable(1, y),
factory.variable(2, z));
}
}
|
package com.ihltx.utility.acl.service.impl;
import com.ihltx.utility.acl.config.AclConfig;
import com.ihltx.utility.acl.entity.SysLoginFailure;
import com.ihltx.utility.acl.entity.SysModule;
import com.ihltx.utility.acl.entity.SysUser;
import com.ihltx.utility.acl.mapper.SysLoginFailureMapper;
import com.ihltx.utility.acl.mapper.SysUserMapper;
import com.ihltx.utility.acl.service.UserService;
import com.ihltx.utility.util.DateUtil;
import com.ihltx.utility.util.SecurityUtil;
import com.ihltx.utility.util.StringUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Pattern;
@SuppressWarnings("all")
@Service
@ConditionalOnProperty(prefix = "ihltx.acl" , name = "enable" , havingValue = "true")
public class UserServiceImpl implements UserService {
@Autowired
private AclConfig aclConfig;
@Autowired
private SysUserMapper sysUserMapper;
@Autowired
private SysLoginFailureMapper sysLoginFailureMapper;
/**
* 格式:{
* userId:{
* shopId1: {
* "zh-CN" : List<SysModule>,
* 。。。
* },
* 。。。
* }
* }
*/
private static Map<Long ,Map<Long , Map<String, List<SysModule>>>> cacheUserModules = new ConcurrentHashMap<>();
@Override
@DS("user")
@Transactional
public SysUser login(String userName, String password) {
QueryWrapper<SysUser> qw = new QueryWrapper<>();
qw.eq(true, "userName" , userName);
qw.eq(true, "disabled" , false);
qw.eq(true, "deleted" , false);
qw.last("LIMIT 0,1");
SysUser user = sysUserMapper.selectOne(qw);
if(user!=null){
if(SecurityUtil.md5(password, user.getSalt()).equals(user.getPassword())){
this.clearCache(user.getUserId());
SysUser u = new SysUser();
u.setUserId(user.getUserId());
u.setLastLoginTime(new Date());
sysUserMapper.updateById(u);
return user;
}
}
return null;
}
@Override
@DS("user")
@Transactional
public List<SysModule> getModulesByUserId(Long userId, String language, Long shopId) {
List<SysModule> modules = null;
if(
cacheUserModules.containsKey(userId) &&
cacheUserModules.get(userId)!=null &&
cacheUserModules.get(userId).containsKey(shopId) &&
cacheUserModules.get(userId).get(shopId)!=null &&
cacheUserModules.get(userId).get(shopId).containsKey(language) &&
cacheUserModules.get(userId).get(shopId).get(language)!=null
){
cacheUserModules.get(userId).get(shopId).get(language);
}
modules = sysUserMapper.getModulesByUserId(userId , language , shopId);
Map<Long , Map<String , List<SysModule>>> maps= new ConcurrentHashMap<>();
Map<String , List<SysModule>> subMaps= new ConcurrentHashMap<>();
subMaps.put(language , modules);
maps.put(shopId ,subMaps);
cacheUserModules.put(userId , maps);
return modules;
}
@Override
@DS("user")
@Transactional
public Boolean decide(Long userId, String url, String querystring, String language, Long shopId) {
if(StringUtil.isNullOrEmpty(querystring)){
querystring = "";
}
List<SysModule> modules = getModulesByUserId(userId , language , shopId);
if(modules==null || modules.isEmpty()){
return false;
}
SysModule module = null;
for(SysModule m : modules){
if(m.getModuleUrl().equalsIgnoreCase(url)){
module = m;
break;
}
}
if(module==null){
return false;
}
if(!StringUtil.isNullOrEmpty(module.getModuleQueryString())){
if(!Pattern.compile("^" + module.getModuleQueryString() + "$").matcher(querystring).find()){
return false;
}
}
return true;
}
@Override
public void clearCache(Long userId) {
if(userId!=null){
cacheUserModules.remove(userId);
}
}
@Override
@DS("user")
@Transactional
public void logout(SysUser user) {
}
@Override
@DS("user")
@Transactional
public SysLoginFailure getLoginFailure(String userName , String ip) {
QueryWrapper<SysLoginFailure> qwLoginFailure = new QueryWrapper<>();
qwLoginFailure.eq(true , "userName" , userName);
qwLoginFailure.eq(true , "loginIp" , ip);
qwLoginFailure.last("LIMIT 0,1");
return sysLoginFailureMapper.selectOne(qwLoginFailure);
}
@Override
@DS("user")
@Transactional
public Boolean saveLoginFailure(SysLoginFailure loginFailure) {
QueryWrapper<SysLoginFailure> qwLoginFailure = new QueryWrapper<>();
qwLoginFailure.eq(true , "userName" , loginFailure.getUserName());
qwLoginFailure.eq(true , "loginIp" , loginFailure.getLoginIp());
qwLoginFailure.last("LIMIT 0,1");
SysLoginFailure entity = sysLoginFailureMapper.selectOne(qwLoginFailure);
Boolean rs = false;
if(entity==null){
rs =sysLoginFailureMapper.insert(loginFailure)>0;
}else{
rs = sysLoginFailureMapper.updateById(loginFailure)>=0;
}
return rs;
}
@Override
@DS("user")
@Transactional
public Boolean deleteLoginFailure(String userName ,String ip) {
QueryWrapper<SysLoginFailure> qwLoginFailure = new QueryWrapper<>();
qwLoginFailure.eq(true , "userName" , userName);
qwLoginFailure.eq(true , "loginIp" , ip);
return sysLoginFailureMapper.delete(qwLoginFailure)>=0;
}
@Override
@DS("user")
@Transactional
public Integer getLoginFailureUserNameNumber(String ip, Integer loginSameUserNameRetryTimes, Integer loginLockMinutes) {
QueryWrapper<SysLoginFailure> qwLoginFailure = new QueryWrapper<>();
qwLoginFailure.eq(true , "loginIp" , ip);
qwLoginFailure.ge(true , "failureTimes" , loginSameUserNameRetryTimes);
qwLoginFailure.ge(true , "loginTime" , new Date(DateUtil.getTimeMillis()-loginLockMinutes * 60 * 1000));
return sysLoginFailureMapper.selectCount(qwLoginFailure);
}
}
|
package com.example.trutziwms;
import android.content.Context;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
assertEquals("com.example.trutziwms", appContext.getPackageName());
}
}
|
/**
* <a href="http://www.openolat.org">
* OpenOLAT - Online Learning and Training</a><br>
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); <br>
* you may not use this file except in compliance with the License.<br>
* You may obtain a copy of the License at the
* <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache homepage</a>
* <p>
* Unless required by applicable law or agreed to in writing,<br>
* software distributed under the License is distributed on an "AS IS" BASIS, <br>
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br>
* See the License for the specific language governing permissions and <br>
* limitations under the License.
* <p>
* Initial code contributed and copyrighted by<br>
* frentix GmbH, http://www.frentix.com
* <p>
*/
package org.olat.course.run.userview;
/**
*
* Initial date: 12.02.2016<br>
* @author srosse, stephane.rosse@frentix.com, http://www.frentix.com
*
*/
public class InvisibleTreeFilter implements VisibilityFilter {
@Override
public boolean isVisible(CourseTreeNode node) {
return false;
}
}
|
package com.jamesdube.laravelnewsapp.util;
import android.util.Log;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.jamesdube.laravelnewsapp.App;
import com.jamesdube.laravelnewsapp.models.Author;
import com.jamesdube.laravelnewsapp.models.Category;
import com.jamesdube.laravelnewsapp.models.Post;
import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import io.realm.RealmList;
import static com.jamesdube.laravelnewsapp.util.Constants.AUTHOR;
import static com.jamesdube.laravelnewsapp.util.Constants.CATEGORY;
import static com.jamesdube.laravelnewsapp.util.Constants.COVER_IMAGE;
import static com.jamesdube.laravelnewsapp.util.Constants.DESCRIPTION;
import static com.jamesdube.laravelnewsapp.util.Constants.LINK;
import static com.jamesdube.laravelnewsapp.util.Constants.TITLE;
import static com.jamesdube.laravelnewsapp.util.CustomDateSerializer.dateFormat;
public class PostDeserializer implements JsonDeserializer<Post> {
private Date pubDate = null;
private JsonElement json;
private String title;
private String link;
private String description;
private String coverImage;
private RealmList<Author> authors = new RealmList<>();
private RealmList<Category> categories = new RealmList<>();
@Override
public Post deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
this.json = json;
Post post = new Post();
authors = new RealmList<>();
categories = new RealmList<>();
//if there is one category
parseCategory().parseAuthor()
.parseDate()
.parseTitle()
.parseLink()
.parseDescription()
.parseCoverImage();
post.setPubDate(pubDate);
post.setTitle(title);
post.setLink(link);
post.setCategories(categories);
post.setAuthors(authors);
post.setCoverImage(coverImage);
post.setDescription(prepHtml());
post.setActive(true);
post.setSeen(false);
post.setFavourite(false);
return post;
}
private PostDeserializer parseCategory() {
if(json.getAsJsonObject().get(CATEGORY).isJsonPrimitive()){
String name = json.getAsJsonObject().get(CATEGORY).getAsString();
categories.add(new Category(name.trim()));
}else if(json.getAsJsonObject().get(CATEGORY).isJsonArray()){
for(int i = 0; i < json.getAsJsonObject().get(CATEGORY).getAsJsonArray().size(); i ++){
JsonObject categoryObject = json.getAsJsonObject()
.get(CATEGORY)
.getAsJsonArray()
.get(i)
.getAsJsonObject();
categories.add(new Category(categoryObject.get("content").getAsString().trim()));
}
}
return this;
}
private PostDeserializer parseAuthor() {
if(json.getAsJsonObject().get(AUTHOR).isJsonPrimitive()){
String name = json.getAsJsonObject().get(AUTHOR).getAsString();
authors.add(new Author(name.trim()));
}else if(json.getAsJsonObject().get(AUTHOR).isJsonArray()){
for(int i = 0; i < json.getAsJsonObject().get(AUTHOR).getAsJsonArray().size(); i ++){
JsonObject authorObject = json.getAsJsonObject()
.get(AUTHOR)
.getAsJsonArray()
.get(i)
.getAsJsonObject();
authors.add(new Author(authorObject.get("name").getAsString().trim()));
}
}
return this;
}
private PostDeserializer parseDate() {
try {
pubDate = dateFormat.parse(json
.getAsJsonObject()
.get("pubDate")
.getAsString());
} catch (ParseException e) {
e.printStackTrace();
}
return this;
}
private PostDeserializer parseLink() {
if (json.getAsJsonObject().get(LINK).isJsonPrimitive()) {
link = json.getAsJsonObject().get(LINK).getAsString();
}
return this;
}
private PostDeserializer parseTitle() {
if (json.getAsJsonObject().get(TITLE).isJsonPrimitive()) {
title = json.getAsJsonObject().get(TITLE).getAsString();
}
return this;
}
private PostDeserializer parseDescription() {
if (json.getAsJsonObject().get(DESCRIPTION).isJsonPrimitive()) {
description = json.getAsJsonObject().get(DESCRIPTION).getAsString();
}
return this;
}
private PostDeserializer parseCoverImage(){
JsonElement coverImageElement = json.getAsJsonObject().get(COVER_IMAGE);
if(coverImageElement != null){
if (coverImageElement.isJsonPrimitive()) {
coverImage = coverImageElement.getAsString();
}
}
else if(description != null){
Pattern pattern = Pattern.compile("<img src=\"(.*?)\">");
Matcher matcher = pattern.matcher(description);
if(matcher.find()){
coverImage = matcher.group(1);
}
}
return this;
}
private String prepHtml(){
return "<HTML><HEAD><link href=\"style.css\" type=\"text/css\" rel=\"stylesheet\"/></HEAD><body>" +
"<div class=\"container-fluid\"><div class=\"row\"> <div class=\"col-lg-12\">" +
description.replaceFirst("<img([^<]*)>", "") +
" </div></div></div></body></HTML>";
}
}
|
/****************************************************************
* 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.james.mailbox.backup;
import java.util.Optional;
import org.apache.commons.compress.archivers.zip.ZipShort;
public class UidExtraField extends LongExtraField {
public static final ZipShort ID_AK = new ZipShort(0x6B61); // "ak" in little-endian
public UidExtraField() {
super();
}
public UidExtraField(long value) {
super(value);
}
public UidExtraField(Optional<Long> value) {
super(value);
}
@Override
public ZipShort getHeaderId() {
return ID_AK;
}
}
|
package io.memoria.reactive.core.file;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.nio.file.Path;
import java.time.Duration;
import java.util.ArrayList;
import static io.memoria.reactive.core.file.TestUtils.FILES_COUNT;
import static io.memoria.reactive.core.file.TestUtils.createSomeFilesDelayed;
import static org.awaitility.Awaitility.await;
class RDirWatchTest {
@BeforeEach
void beforeEach() {
RFiles.createDirectory(TestUtils.EMPTY_DIR).subscribe();
RFiles.clean(TestUtils.EMPTY_DIR).subscribe();
}
@Test
void watch() {
// Given
var watchedPaths = new ArrayList<Path>();
// when
new Thread(() -> RDirWatch.watch(TestUtils.EMPTY_DIR).take(FILES_COUNT).subscribe(watchedPaths::add)).start();
createSomeFilesDelayed(Duration.ofMillis(200)).block();
// Then
await().atMost(Duration.ofSeconds(2)).until(() -> watchedPaths.size() == FILES_COUNT);
}
}
|
package org.firstinspires.ftc.teamcode.old;
import com.qualcomm.robotcore.eventloop.opmode.Autonomous;
import com.qualcomm.robotcore.eventloop.opmode.Disabled;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.hardware.CRServo;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.hardware.Servo;
/**
* Created by George on 9/27/2019.
*/
@Disabled
@Autonomous(name = "Blue Middle Park", group = "Competition")
public class BlueMidPark extends LinearOpMode {
DcMotor fr;
DcMotor fl;
DcMotor br;
DcMotor bl;
DcMotor arm;
CRServo wrist;
Servo clamp;
Servo foundr;
Servo foundl;
Servo stone;
@Override
public void runOpMode() {
fr = hardwareMap.dcMotor.get("front right");
fl = hardwareMap.dcMotor.get("front left");
br = hardwareMap.dcMotor.get("back right");
bl = hardwareMap.dcMotor.get("back left");
arm = hardwareMap.dcMotor.get("arm");
wrist = hardwareMap.crservo.get("wrist");
clamp = hardwareMap.servo.get("leftClamp");
foundr = hardwareMap.servo.get("foundation right");
foundl = hardwareMap.servo.get("foundation left");
stone = hardwareMap.servo.get("stone arm");
fr.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
br.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
fl.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
bl.setMode(DcMotor.RunMode.RUN_USING_ENCODER);
waitForStart();
//foundation = 34.5 by 18.5
driveXY(12, 1, "right");
driveXY(26, 1, "forward");
}
public void driveXY(float inches, double speed, String direction) {
//1120 counts per rotation
//13 inches per rotation
//86 countsPerInch counts per X inch
//8 inches per rotation
//140 counts per Y inch
float XcountsPerInch = 86f;
float YcountsPerInch = 140f;
fr.setMode(DcMotor.RunMode.RESET_ENCODERS);
br.setMode(DcMotor.RunMode.RESET_ENCODERS);
fl.setMode(DcMotor.RunMode.RESET_ENCODERS);
bl.setMode(DcMotor.RunMode.RESET_ENCODERS);
if (direction == "forward") {
fr.setTargetPosition(Math.round(inches * XcountsPerInch));
br.setTargetPosition(Math.round(inches * XcountsPerInch));
fl.setTargetPosition(-Math.round(inches * XcountsPerInch));
bl.setTargetPosition(-Math.round(inches * XcountsPerInch));
}
if (direction == "backward") {
fr.setTargetPosition(-Math.round(inches * XcountsPerInch));
br.setTargetPosition(-Math.round(inches * XcountsPerInch));
fl.setTargetPosition(Math.round(inches * XcountsPerInch));
bl.setTargetPosition(Math.round(inches * XcountsPerInch));
}
if (direction == "left") {
fr.setTargetPosition(Math.round(inches * YcountsPerInch));
br.setTargetPosition(-Math.round(inches * YcountsPerInch));
fl.setTargetPosition(Math.round(inches * YcountsPerInch));
bl.setTargetPosition(-Math.round(inches * YcountsPerInch));
}
if (direction == "right") {
fr.setTargetPosition(-Math.round(inches * YcountsPerInch));
br.setTargetPosition(Math.round(inches * YcountsPerInch));
fl.setTargetPosition(-Math.round(inches * YcountsPerInch));
bl.setTargetPosition(Math.round(inches * YcountsPerInch));
}
fr.setMode(DcMotor.RunMode.RUN_TO_POSITION);
br.setMode(DcMotor.RunMode.RUN_TO_POSITION);
fl.setMode(DcMotor.RunMode.RUN_TO_POSITION);
bl.setMode(DcMotor.RunMode.RUN_TO_POSITION);
fr.setPower(speed);
br.setPower(speed);
fl.setPower(speed);
bl.setPower(speed);
while (fr.isBusy() && br.isBusy() && fl.isBusy() && bl.isBusy()) {
}
fr.setPower(0);
br.setPower(0);
fl.setPower(0);
bl.setPower(0);
fr.setMode(DcMotor.RunMode.RESET_ENCODERS);
br.setMode(DcMotor.RunMode.RESET_ENCODERS);
fl.setMode(DcMotor.RunMode.RESET_ENCODERS);
bl.setMode(DcMotor.RunMode.RESET_ENCODERS);
}
public void turn(int degrees, double speed, String direction) {
//1120 counts per rotation
//60 degrees per rotation
//18.6 countsPerDegree counts per degree
float countsPerDegree = 18.666f;
fr.setMode(DcMotor.RunMode.RESET_ENCODERS);
br.setMode(DcMotor.RunMode.RESET_ENCODERS);
fl.setMode(DcMotor.RunMode.RESET_ENCODERS);
bl.setMode(DcMotor.RunMode.RESET_ENCODERS);
if(direction == "left") {
fr.setTargetPosition(Math.round(degrees * countsPerDegree));
br.setTargetPosition(Math.round(degrees * countsPerDegree));
fl.setTargetPosition(Math.round(degrees * countsPerDegree));
bl.setTargetPosition(Math.round(degrees * countsPerDegree));
}
if(direction == "right") {
fr.setTargetPosition(-Math.round(degrees * countsPerDegree));
br.setTargetPosition(-Math.round(degrees * countsPerDegree));
fl.setTargetPosition(-Math.round(degrees * countsPerDegree));
bl.setTargetPosition(-Math.round(degrees * countsPerDegree));
}
fr.setMode(DcMotor.RunMode.RUN_TO_POSITION);
br.setMode(DcMotor.RunMode.RUN_TO_POSITION);
fl.setMode(DcMotor.RunMode.RUN_TO_POSITION);
bl.setMode(DcMotor.RunMode.RUN_TO_POSITION);
fr.setPower(speed);
br.setPower(speed);
fl.setPower(speed);
bl.setPower(speed);
while (fr.isBusy() && br.isBusy() && fl.isBusy() && bl.isBusy()) {
}
fr.setPower(0);
br.setPower(0);
fl.setPower(0);
bl.setPower(0);
fr.setMode(DcMotor.RunMode.RESET_ENCODERS);
br.setMode(DcMotor.RunMode.RESET_ENCODERS);
fl.setMode(DcMotor.RunMode.RESET_ENCODERS);
bl.setMode(DcMotor.RunMode.RESET_ENCODERS);
}
public void arm(int locks, double speed, String direction) {
//1120 counts per rotation
// degrees per rotation
// countsPerLock counts per degree
float countsPerLock = 1260;
arm.setMode(DcMotor.RunMode.RESET_ENCODERS);
if(direction == "down") {
arm.setTargetPosition(Math.round(locks * countsPerLock));
}
if(direction == "up") {
arm.setTargetPosition(-Math.round(locks * countsPerLock));
}
arm.setMode(DcMotor.RunMode.RUN_TO_POSITION);
arm.setPower(speed);
while (arm.isBusy()) {
}
arm.setPower(0);
arm.setMode(DcMotor.RunMode.RESET_ENCODERS);
}
}
|
package org.hitlabnz.sensor_fusion_demo;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import org.hitlabnz.sensor_fusion_demo.orientationProvider.OrientationProvider;
import org.hitlabnz.sensor_fusion_demo.representation.Quaternion;
import android.opengl.GLSurfaceView;
/**
* Class that implements the rendering of a cube with the current rotation of the device that is provided by a
* OrientationProvider
*
* @author Alexander Pacha
*
*/
public class CubeRenderer implements GLSurfaceView.Renderer {
/**
* The colour-cube that is drawn repeatedly
*/
private Cube mCube;
/**
* The current provider of the device orientation.
*/
private OrientationProvider orientationProvider = null;
private Quaternion quaternion = new Quaternion();
/**
* Initialises a new CubeRenderer
*/
public CubeRenderer() {
mCube = new Cube();
}
/**
* Sets the orientationProvider of this renderer. Use this method to change which sensor fusion should be currently
* used for rendering the cube. Simply exchange it with another orientationProvider and the cube will be rendered
* with another approach.
*
* @param orientationProvider The new orientation provider that delivers the current orientation of the device
*/
public void setOrientationProvider(OrientationProvider orientationProvider) {
this.orientationProvider = orientationProvider;
}
/**
* Perform the actual rendering of the cube for each frame
*
* @param gl The surface on which the cube should be rendered
*/
public void onDrawFrame(GL10 gl) {
// clear screen
gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
// set-up modelview matrix
gl.glMatrixMode(GL10.GL_MODELVIEW);
gl.glLoadIdentity();
if (showCubeInsideOut) {
float dist = 3;
gl.glTranslatef(0, 0, -dist);
if (orientationProvider != null) {
// All Orientation providers deliver Quaternion as well as rotation matrix.
// Use your favourite representation:
// Get the rotation from the current orientationProvider as rotation matrix
//gl.glMultMatrixf(orientationProvider.getRotationMatrix().getMatrix(), 0);
// Get the rotation from the current orientationProvider as quaternion
orientationProvider.getQuaternion(quaternion);
gl.glRotatef((float) (2.0f * Math.acos(quaternion.getW()) * 180.0f / Math.PI), quaternion.getX(), quaternion.getY(), quaternion.getZ());
}
// draw our object
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
gl.glEnableClientState(GL10.GL_COLOR_ARRAY);
mCube.draw(gl);
} else {
if (orientationProvider != null) {
// All Orientation providers deliver Quaternion as well as rotation matrix.
// Use your favourite representation:
// Get the rotation from the current orientationProvider as rotation matrix
//gl.glMultMatrixf(orientationProvider.getRotationMatrix().getMatrix(), 0);
// Get the rotation from the current orientationProvider as quaternion
orientationProvider.getQuaternion(quaternion);
gl.glRotatef((float) (2.0f * Math.acos(quaternion.getW()) * 180.0f / Math.PI), quaternion.getX(), quaternion.getY(), quaternion.getZ());
}
float dist = 3;
drawTranslatedCube(gl, 0, 0, -dist);
drawTranslatedCube(gl, 0, 0, dist);
drawTranslatedCube(gl, 0, -dist, 0);
drawTranslatedCube(gl, 0, dist, 0);
drawTranslatedCube(gl, -dist, 0, 0);
drawTranslatedCube(gl, dist, 0, 0);
}
// draw our object
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
gl.glEnableClientState(GL10.GL_COLOR_ARRAY);
mCube.draw(gl);
}
/**
* Draws a translated cube
*
* @param gl the surface
* @param translateX x-translation
* @param translateY y-translation
* @param translateZ z-translation
*/
private void drawTranslatedCube(GL10 gl, float translateX, float translateY, float translateZ) {
gl.glPushMatrix();
gl.glTranslatef(translateX, translateY, translateZ);
// draw our object
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
gl.glEnableClientState(GL10.GL_COLOR_ARRAY);
mCube.draw(gl);
gl.glPopMatrix();
}
/**
* Update view-port with the new surface
*
* @param gl the surface
* @param width new width
* @param height new height
*/
public void onSurfaceChanged(GL10 gl, int width, int height) {
// set view-port
gl.glViewport(0, 0, width, height);
// set projection matrix
float ratio = (float) width / height;
gl.glMatrixMode(GL10.GL_PROJECTION);
gl.glLoadIdentity();
gl.glFrustumf(-ratio, ratio, -1, 1, 1, 10);
}
@Override
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
// dither is enabled by default, we don't need it
gl.glDisable(GL10.GL_DITHER);
// clear screen in black
gl.glClearColor(0, 0, 0, 1);
}
/**
* Flag indicating whether you want to view inside out, or outside in
*/
private boolean showCubeInsideOut = true;
/**
* Toggles whether the cube will be shown inside-out or outside in.
*/
public void toggleShowCubeInsideOut() {
this.showCubeInsideOut = !showCubeInsideOut;
}
}
|
package com.android.billingclient.api;
public final /* synthetic */ class q implements Runnable {
/* renamed from: b reason: collision with root package name */
public final /* synthetic */ s f2769b;
public /* synthetic */ q(s sVar) {
this.f2769b = sVar;
}
public final void run() {
this.f2769b.b();
}
}
|
/*
* Copyright 2014-2019 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.codeguruprofiler.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.Request;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.codeguruprofiler.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.protocol.*;
import com.amazonaws.protocol.Protocol;
import com.amazonaws.annotation.SdkInternalApi;
/**
* DeleteProfilingGroupRequest Marshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class DeleteProfilingGroupRequestProtocolMarshaller implements Marshaller<Request<DeleteProfilingGroupRequest>, DeleteProfilingGroupRequest> {
private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.REST_JSON)
.requestUri("/profilingGroups/{profilingGroupName}").httpMethodName(HttpMethodName.DELETE).hasExplicitPayloadMember(false).hasPayloadMembers(false)
.serviceName("AmazonCodeGuruProfiler").build();
private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory;
public DeleteProfilingGroupRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) {
this.protocolFactory = protocolFactory;
}
public Request<DeleteProfilingGroupRequest> marshall(DeleteProfilingGroupRequest deleteProfilingGroupRequest) {
if (deleteProfilingGroupRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
final ProtocolRequestMarshaller<DeleteProfilingGroupRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller(SDK_OPERATION_BINDING,
deleteProfilingGroupRequest);
protocolMarshaller.startMarshalling();
DeleteProfilingGroupRequestMarshaller.getInstance().marshall(deleteProfilingGroupRequest, protocolMarshaller);
return protocolMarshaller.finishMarshalling();
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
|
package com.jstechnologies.helpinghands.utils;
import com.jstechnologies.helpinghandscloud.CloudRequest;
public class URLs {
private static String ROOT_URL="http://192.168.1.26:3000/api/v1";
public static String getUrlFor(String route, CloudRequest.RequestType requestType)
{
return ROOT_URL+"/"+route+"/"+requestType.name().toLowerCase();
}
}
|
package com.scaleset.cfbuilder.ec2.metadata;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class CFNPackage {
@JsonInclude(JsonInclude.Include.NON_EMPTY)
private Map<String, List<String>> packages;
@JsonIgnore
public String id;
public CFNPackage(String id) {
this.id = id;
this.packages = new HashMap<>();
}
public String getId() {
return this.id;
}
public CFNPackage addPackage(String packageName) {
this.packages.put(packageName, new ArrayList<>());
return this;
}
public CFNPackage addPackage(String packageName, String version) {
ArrayList<String> list = new ArrayList<>();
list.add(version);
this.packages.put(packageName, list);
return this;
}
@JsonAnyGetter
public Map<String, List<String>> getPackages() {
return this.packages;
}
}
|
package kafka.benchmark;
import benchmark.common.Utils;
import benchmark.common.advertising.CampaignProcessorCommon;
import benchmark.common.advertising.RedisAdCampaignCache;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.Options;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.common.serialization.Serdes;
import org.apache.kafka.streams.KafkaStreams;
import org.apache.kafka.streams.KeyValue;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.StreamsConfig;
import org.apache.kafka.streams.kstream.Transformer;
import org.apache.kafka.streams.processor.AbstractProcessor;
import org.apache.kafka.streams.processor.ProcessorContext;
import org.apache.kafka.streams.processor.TimestampExtractor;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Properties;
public class AdvertisingPipeline {
private static final Logger logger = LoggerFactory.getLogger(AdvertisingPipeline.class);
private static int timeDivisor;
private static String redisServerHost;
static class EnrichedData {
EnrichedData(String ad_id, String event_time) {
this.ad_id = ad_id;
this.event_time = event_time;
}
String ad_id;
String campaign_id;
String event_time;
}
public static class RowData implements Serializable {
RowData(String user_id, String page_id, String ad_id, String ad_type, String event_type, String event_time, String ip_address) {
this.user_id = user_id;
this.page_id = page_id;
this.ad_id = ad_id;
this.ad_type = ad_type;
this.event_type = event_type;
this.event_time = event_time;
this.ip_address = ip_address;
}
String user_id;
String page_id;
String ad_id;
String ad_type;
String event_type;
String event_time;
String ip_address;
}
public static void main(final String[] args) throws Exception {
Options opts = new Options();
opts.addOption("conf", true, "Path to the config file.");
CommandLineParser parser = new DefaultParser();
CommandLine cmd = parser.parse(opts, args);
String configPath = cmd.getOptionValue("conf");
Map commonConfig = Utils.findAndReadConfigFile(configPath, true);
redisServerHost = (String) commonConfig.get("redis.host");
String kafkaTopic = (String) commonConfig.get("kafka.topic");
String kafkaServerHosts = Utils.joinHosts((List<String>) commonConfig.get("kafka.brokers"),
Integer.toString((Integer) commonConfig.get("kafka.port")));
timeDivisor = ((Number) commonConfig.get("time.divisor")).intValue();
logger.info("******************");
logger.info(redisServerHost);
Properties config = new Properties();
config.put(StreamsConfig.TIMESTAMP_EXTRACTOR_CLASS_CONFIG, TimestampExtractorImpl.class);
config.put(StreamsConfig.APPLICATION_ID_CONFIG, "kafka-benchmark");
config.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaServerHosts);
config.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass());
config.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass());
StreamsBuilder builder = new StreamsBuilder();
builder.stream(kafkaTopic)
.mapValues(o -> deserializeBolt(o.toString()))
.filter((o, rowData) -> rowData.event_type.equals("view"))
.mapValues(rowData -> new EnrichedData(rowData.ad_id, rowData.event_time))
.transform(RedisJoinBolt::new)
.process(CampaignProcessor::new);
KafkaStreams streams = new KafkaStreams(builder.build(), config);
streams.start();
}
public static class TimestampExtractorImpl implements TimestampExtractor {
public TimestampExtractorImpl() {
}
@Override
public long extract(ConsumerRecord<Object, Object> consumerRecord, long l) {
return new Date().getTime();
}
}
public static class RedisJoinBolt implements Transformer<Object, EnrichedData, KeyValue<String, EnrichedData>> {
RedisAdCampaignCache redisAdCampaignCache;
@Override
@SuppressWarnings("unchecked")
public void init(ProcessorContext context) {
this.redisAdCampaignCache = new RedisAdCampaignCache(redisServerHost);
this.redisAdCampaignCache.prepare();
}
@Override
public KeyValue<String, EnrichedData> transform(final Object s, final EnrichedData input) {
String campaign_id = this.redisAdCampaignCache.execute(input.ad_id);
if (campaign_id == null) {
return null;
}
input.campaign_id = campaign_id;
return KeyValue.pair(null, input);
}
@Override
public KeyValue<String, EnrichedData> punctuate(long l) {
return null;
}
@Override
public void close() {
}
}
public static class CampaignProcessor extends AbstractProcessor<String, EnrichedData> {
CampaignProcessorCommon campaignProcessorCommon;
@Override
@SuppressWarnings("unchecked")
public void init(ProcessorContext context) {
this.campaignProcessorCommon = new CampaignProcessorCommon(redisServerHost, (long) timeDivisor);
this.campaignProcessorCommon.prepare();
}
@Override
public void process(String s, EnrichedData enrichedData) {
this.campaignProcessorCommon.execute(enrichedData.campaign_id, enrichedData.event_time);
}
}
private static RowData deserializeBolt(String value) {
JSONObject obj = new JSONObject(value);
return new RowData(obj.getString("user_id"),
obj.getString("page_id"),
obj.getString("ad_id"),
obj.getString("ad_type"),
obj.getString("event_type"),
obj.getString("event_time"),
obj.getString("ip_address"));
}
}
|
package mage.sets;
import mage.cards.ExpansionSet;
import mage.constants.Rarity;
import mage.constants.SetType;
/**
* @author TheElk801
*/
public final class StrixhavenMysticalArchive extends ExpansionSet {
private static final StrixhavenMysticalArchive instance = new StrixhavenMysticalArchive();
public static StrixhavenMysticalArchive getInstance() {
return instance;
}
private StrixhavenMysticalArchive() {
super("Strixhaven Mystical Archive", "STA", ExpansionSet.buildDate(2021, 4, 23), SetType.SUPPLEMENTAL);
this.hasBoosters = false;
this.hasBasicLands = false;
this.maxCardNumberInBooster = 63;
cards.add(new SetCardInfo("Abundant Harvest", 111, Rarity.RARE, mage.cards.a.AbundantHarvest.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Abundant Harvest", 48, Rarity.RARE, mage.cards.a.AbundantHarvest.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Adventurous Impulse", 112, Rarity.UNCOMMON, mage.cards.a.AdventurousImpulse.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Adventurous Impulse", 49, Rarity.UNCOMMON, mage.cards.a.AdventurousImpulse.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Agonizing Remorse", 24, Rarity.UNCOMMON, mage.cards.a.AgonizingRemorse.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Agonizing Remorse", 87, Rarity.UNCOMMON, mage.cards.a.AgonizingRemorse.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Approach of the Second Sun", 1, Rarity.MYTHIC, mage.cards.a.ApproachOfTheSecondSun.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Approach of the Second Sun", 64, Rarity.MYTHIC, mage.cards.a.ApproachOfTheSecondSun.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Blue Sun's Zenith", 12, Rarity.MYTHIC, mage.cards.b.BlueSunsZenith.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Blue Sun's Zenith", 75, Rarity.MYTHIC, mage.cards.b.BlueSunsZenith.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Brainstorm", 13, Rarity.RARE, mage.cards.b.Brainstorm.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Brainstorm", 76, Rarity.RARE, mage.cards.b.Brainstorm.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Channel", 113, Rarity.MYTHIC, mage.cards.c.Channel.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Channel", 50, Rarity.MYTHIC, mage.cards.c.Channel.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Chaos Warp", 36, Rarity.MYTHIC, mage.cards.c.ChaosWarp.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Chaos Warp", 99, Rarity.MYTHIC, mage.cards.c.ChaosWarp.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Claim the Firstborn", 100, Rarity.UNCOMMON, mage.cards.c.ClaimTheFirstborn.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Claim the Firstborn", 37, Rarity.UNCOMMON, mage.cards.c.ClaimTheFirstborn.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Compulsive Research", 14, Rarity.RARE, mage.cards.c.CompulsiveResearch.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Compulsive Research", 77, Rarity.RARE, mage.cards.c.CompulsiveResearch.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Counterspell", 15, Rarity.RARE, mage.cards.c.Counterspell.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Counterspell", 78, Rarity.RARE, mage.cards.c.Counterspell.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Crux of Fate", 25, Rarity.MYTHIC, mage.cards.c.CruxOfFate.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Crux of Fate", 88, Rarity.MYTHIC, mage.cards.c.CruxOfFate.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Cultivate", 114, Rarity.UNCOMMON, mage.cards.c.Cultivate.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Cultivate", 51, Rarity.UNCOMMON, mage.cards.c.Cultivate.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Dark Ritual", 26, Rarity.RARE, mage.cards.d.DarkRitual.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Dark Ritual", 89, Rarity.RARE, mage.cards.d.DarkRitual.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Day of Judgment", 2, Rarity.MYTHIC, mage.cards.d.DayOfJudgment.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Day of Judgment", 65, Rarity.MYTHIC, mage.cards.d.DayOfJudgment.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Defiant Strike", 3, Rarity.UNCOMMON, mage.cards.d.DefiantStrike.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Defiant Strike", 66, Rarity.UNCOMMON, mage.cards.d.DefiantStrike.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Demonic Tutor", 27, Rarity.MYTHIC, mage.cards.d.DemonicTutor.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Demonic Tutor", 90, Rarity.MYTHIC, mage.cards.d.DemonicTutor.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Despark", 122, Rarity.RARE, mage.cards.d.Despark.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Despark", 59, Rarity.RARE, mage.cards.d.Despark.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Divine Gambit", 4, Rarity.UNCOMMON, mage.cards.d.DivineGambit.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Divine Gambit", 67, Rarity.UNCOMMON, mage.cards.d.DivineGambit.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Doom Blade", 28, Rarity.RARE, mage.cards.d.DoomBlade.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Doom Blade", 91, Rarity.RARE, mage.cards.d.DoomBlade.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Duress", 29, Rarity.UNCOMMON, mage.cards.d.Duress.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Duress", 92, Rarity.UNCOMMON, mage.cards.d.Duress.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Electrolyze", 123, Rarity.RARE, mage.cards.e.Electrolyze.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Electrolyze", 60, Rarity.RARE, mage.cards.e.Electrolyze.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Eliminate", 30, Rarity.UNCOMMON, mage.cards.e.Eliminate.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Eliminate", 93, Rarity.UNCOMMON, mage.cards.e.Eliminate.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Ephemerate", 5, Rarity.RARE, mage.cards.e.Ephemerate.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Ephemerate", 68, Rarity.RARE, mage.cards.e.Ephemerate.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Faithless Looting", 101, Rarity.RARE, mage.cards.f.FaithlessLooting.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Faithless Looting", 38, Rarity.RARE, mage.cards.f.FaithlessLooting.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Gift of Estates", 6, Rarity.RARE, mage.cards.g.GiftOfEstates.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Gift of Estates", 69, Rarity.RARE, mage.cards.g.GiftOfEstates.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Gods Willing", 7, Rarity.RARE, mage.cards.g.GodsWilling.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Gods Willing", 70, Rarity.RARE, mage.cards.g.GodsWilling.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Grapeshot", 102, Rarity.RARE, mage.cards.g.Grapeshot.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Grapeshot", 39, Rarity.RARE, mage.cards.g.Grapeshot.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Growth Spiral", 124, Rarity.RARE, mage.cards.g.GrowthSpiral.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Growth Spiral", 61, Rarity.RARE, mage.cards.g.GrowthSpiral.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Harmonize", 115, Rarity.RARE, mage.cards.h.Harmonize.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Harmonize", 52, Rarity.RARE, mage.cards.h.Harmonize.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Increasing Vengeance", 103, Rarity.MYTHIC, mage.cards.i.IncreasingVengeance.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Increasing Vengeance", 40, Rarity.MYTHIC, mage.cards.i.IncreasingVengeance.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Infuriate", 104, Rarity.UNCOMMON, mage.cards.i.Infuriate.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Infuriate", 41, Rarity.UNCOMMON, mage.cards.i.Infuriate.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Inquisition of Kozilek", 31, Rarity.RARE, mage.cards.i.InquisitionOfKozilek.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Inquisition of Kozilek", 94, Rarity.RARE, mage.cards.i.InquisitionOfKozilek.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Krosan Grip", 116, Rarity.RARE, mage.cards.k.KrosanGrip.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Krosan Grip", 53, Rarity.RARE, mage.cards.k.KrosanGrip.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Lightning Bolt", 105, Rarity.RARE, mage.cards.l.LightningBolt.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Lightning Bolt", 42, Rarity.RARE, mage.cards.l.LightningBolt.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Lightning Helix", 125, Rarity.RARE, mage.cards.l.LightningHelix.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Lightning Helix", 62, Rarity.RARE, mage.cards.l.LightningHelix.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Mana Tithe", 71, Rarity.RARE, mage.cards.m.ManaTithe.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Mana Tithe", 8, Rarity.RARE, mage.cards.m.ManaTithe.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Memory Lapse", 16, Rarity.RARE, mage.cards.m.MemoryLapse.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Memory Lapse", 79, Rarity.RARE, mage.cards.m.MemoryLapse.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Mind's Desire", 17, Rarity.MYTHIC, mage.cards.m.MindsDesire.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Mind's Desire", 80, Rarity.MYTHIC, mage.cards.m.MindsDesire.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Mizzix's Mastery", 106, Rarity.MYTHIC, mage.cards.m.MizzixsMastery.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Mizzix's Mastery", 43, Rarity.MYTHIC, mage.cards.m.MizzixsMastery.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Natural Order", 117, Rarity.MYTHIC, mage.cards.n.NaturalOrder.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Natural Order", 54, Rarity.MYTHIC, mage.cards.n.NaturalOrder.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Negate", 18, Rarity.UNCOMMON, mage.cards.n.Negate.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Negate", 81, Rarity.UNCOMMON, mage.cards.n.Negate.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Opt", 19, Rarity.UNCOMMON, mage.cards.o.Opt.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Opt", 82, Rarity.UNCOMMON, mage.cards.o.Opt.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Primal Command", 118, Rarity.MYTHIC, mage.cards.p.PrimalCommand.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Primal Command", 55, Rarity.MYTHIC, mage.cards.p.PrimalCommand.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Putrefy", 126, Rarity.RARE, mage.cards.p.Putrefy.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Putrefy", 63, Rarity.RARE, mage.cards.p.Putrefy.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Regrowth", 119, Rarity.RARE, mage.cards.r.Regrowth.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Regrowth", 56, Rarity.RARE, mage.cards.r.Regrowth.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Revitalize", 72, Rarity.UNCOMMON, mage.cards.r.Revitalize.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Revitalize", 9, Rarity.UNCOMMON, mage.cards.r.Revitalize.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Shock", 107, Rarity.UNCOMMON, mage.cards.s.Shock.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Shock", 44, Rarity.UNCOMMON, mage.cards.s.Shock.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Sign in Blood", 32, Rarity.RARE, mage.cards.s.SignInBlood.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Sign in Blood", 95, Rarity.RARE, mage.cards.s.SignInBlood.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Snakeskin Veil", 120, Rarity.UNCOMMON, mage.cards.s.SnakeskinVeil.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Snakeskin Veil", 57, Rarity.UNCOMMON, mage.cards.s.SnakeskinVeil.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Stone Rain", 108, Rarity.RARE, mage.cards.s.StoneRain.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Stone Rain", 45, Rarity.RARE, mage.cards.s.StoneRain.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Strategic Planning", 20, Rarity.UNCOMMON, mage.cards.s.StrategicPlanning.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Strategic Planning", 83, Rarity.UNCOMMON, mage.cards.s.StrategicPlanning.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Swords to Plowshares", 10, Rarity.RARE, mage.cards.s.SwordsToPlowshares.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Swords to Plowshares", 73, Rarity.RARE, mage.cards.s.SwordsToPlowshares.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Tainted Pact", 33, Rarity.MYTHIC, mage.cards.t.TaintedPact.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Tainted Pact", 96, Rarity.MYTHIC, mage.cards.t.TaintedPact.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Teferi's Protection", 11, Rarity.MYTHIC, mage.cards.t.TeferisProtection.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Teferi's Protection", 74, Rarity.MYTHIC, mage.cards.t.TeferisProtection.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Tendrils of Agony", 34, Rarity.RARE, mage.cards.t.TendrilsOfAgony.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Tendrils of Agony", 97, Rarity.RARE, mage.cards.t.TendrilsOfAgony.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Tezzeret's Gambit", 21, Rarity.RARE, mage.cards.t.TezzeretsGambit.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Tezzeret's Gambit", 84, Rarity.RARE, mage.cards.t.TezzeretsGambit.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Thrill of Possibility", 109, Rarity.UNCOMMON, mage.cards.t.ThrillOfPossibility.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Thrill of Possibility", 46, Rarity.UNCOMMON, mage.cards.t.ThrillOfPossibility.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Time Warp", 22, Rarity.MYTHIC, mage.cards.t.TimeWarp.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Time Warp", 85, Rarity.MYTHIC, mage.cards.t.TimeWarp.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Urza's Rage", 110, Rarity.RARE, mage.cards.u.UrzasRage.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Urza's Rage", 47, Rarity.RARE, mage.cards.u.UrzasRage.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Village Rites", 35, Rarity.UNCOMMON, mage.cards.v.VillageRites.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Village Rites", 98, Rarity.UNCOMMON, mage.cards.v.VillageRites.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Weather the Storm", 121, Rarity.RARE, mage.cards.w.WeatherTheStorm.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Weather the Storm", 58, Rarity.RARE, mage.cards.w.WeatherTheStorm.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Whirlwind Denial", 23, Rarity.UNCOMMON, mage.cards.w.WhirlwindDenial.class, NON_FULL_USE_VARIOUS));
cards.add(new SetCardInfo("Whirlwind Denial", 86, Rarity.UNCOMMON, mage.cards.w.WhirlwindDenial.class, NON_FULL_USE_VARIOUS));
}
}
|
/*-
* -\-\-
* bigtable-autoscaler
* --
* Copyright (C) 2018 Spotify AB
* --
* 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.spotify.autoscaler.di;
import com.spotify.autoscaler.Application;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import dagger.Module;
import dagger.Provides;
import javax.inject.Singleton;
@Module
public class ConfigModule {
@Provides
@Singleton
public static Config config() {
return ConfigFactory.load(Application.SERVICE_NAME);
}
}
|
/*
* Copyright 2009-2012 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.apache.ibatis.jdbc;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* @author Clinton Begin
* @author Jeff Butler
* @author Adam Gent
*/
public abstract class AbstractSQL<T> {
private static final String AND = ") \nAND (";
private static final String OR = ") \nOR (";
public abstract T getSelf();
public T UPDATE(String table) {
sql().statementType = SQLStatement.StatementType.UPDATE;
sql().tables.add(table);
return getSelf();
}
public T SET(String sets) {
sql().sets.add(sets);
return getSelf();
}
public T INSERT_INTO(String tableName) {
sql().statementType = SQLStatement.StatementType.INSERT;
sql().tables.add(tableName);
return getSelf();
}
public T VALUES(String columns, String values) {
sql().columns.add(columns);
sql().values.add(values);
return getSelf();
}
public T SELECT(String columns) {
sql().statementType = SQLStatement.StatementType.SELECT;
sql().select.add(columns);
return getSelf();
}
public T SELECT_DISTINCT(String columns) {
sql().distinct = true;
SELECT(columns);
return getSelf();
}
public T DELETE_FROM(String table) {
sql().statementType = SQLStatement.StatementType.DELETE;
sql().tables.add(table);
return getSelf();
}
public T FROM(String table) {
sql().tables.add(table);
return getSelf();
}
public T JOIN(String join) {
sql().join.add(join);
return getSelf();
}
public T INNER_JOIN(String join) {
sql().innerJoin.add(join);
return getSelf();
}
public T LEFT_OUTER_JOIN(String join) {
sql().leftOuterJoin.add(join);
return getSelf();
}
public T RIGHT_OUTER_JOIN(String join) {
sql().rightOuterJoin.add(join);
return getSelf();
}
public T OUTER_JOIN(String join) {
sql().outerJoin.add(join);
return getSelf();
}
public T WHERE(String conditions) {
sql().where.add(conditions);
sql().lastList = sql().where;
return getSelf();
}
public T OR() {
sql().lastList.add(OR);
return getSelf();
}
public T AND() {
sql().lastList.add(AND);
return getSelf();
}
public T GROUP_BY(String columns) {
sql().groupBy.add(columns);
return getSelf();
}
public T HAVING(String conditions) {
sql().having.add(conditions);
sql().lastList = sql().having;
return getSelf();
}
public T ORDER_BY(String columns) {
sql().orderBy.add(columns);
return getSelf();
}
private SQLStatement sql = new SQLStatement();
private SQLStatement sql() {
return sql;
}
public <A extends Appendable> A usingAppender(A a) {
sql().sql(a);
return a;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sql().sql(sb);
return sb.toString();
}
private static class SafeAppendable {
private final Appendable a;
private boolean empty = true;
public SafeAppendable(Appendable a) {
super();
this.a = a;
}
public SafeAppendable append(CharSequence s) {
try {
if (empty && s.length() > 0)
empty = false;
a.append(s);
} catch (IOException e) {
throw new RuntimeException(e);
}
return this;
}
public boolean isEmpty() {
return empty;
}
}
private static class SQLStatement {
public enum StatementType {
DELETE, INSERT, SELECT, UPDATE
}
StatementType statementType;
List<String> sets = new ArrayList<String>();
List<String> select = new ArrayList<String>();
List<String> tables = new ArrayList<String>();
List<String> join = new ArrayList<String>();
List<String> innerJoin = new ArrayList<String>();
List<String> outerJoin = new ArrayList<String>();
List<String> leftOuterJoin = new ArrayList<String>();
List<String> rightOuterJoin = new ArrayList<String>();
List<String> where = new ArrayList<String>();
List<String> having = new ArrayList<String>();
List<String> groupBy = new ArrayList<String>();
List<String> orderBy = new ArrayList<String>();
List<String> lastList = new ArrayList<String>();
List<String> columns = new ArrayList<String>();
List<String> values = new ArrayList<String>();
boolean distinct;
private void sqlClause(SafeAppendable builder, String keyword,
List<String> parts, String open, String close,
String conjunction) {
if (!parts.isEmpty()) {
if (!builder.isEmpty())
builder.append("\n");
builder.append(keyword);
builder.append(" ");
builder.append(open);
String last = "________";
for (int i = 0, n = parts.size(); i < n; i++) {
String part = parts.get(i);
if (i > 0 && !part.equals(AND) && !part.equals(OR)
&& !last.equals(AND) && !last.equals(OR)) {
builder.append(conjunction);
}
builder.append(part);
last = part;
}
builder.append(close);
}
}
private String selectSQL(SafeAppendable builder) {
if (distinct) {
sqlClause(builder, "SELECT DISTINCT", select, "", "", ", ");
} else {
sqlClause(builder, "SELECT", select, "", "", ", ");
}
sqlClause(builder, "FROM", tables, "", "", ", ");
sqlClause(builder, "JOIN", join, "", "", "\nJOIN ");
sqlClause(builder, "INNER JOIN", innerJoin, "", "", "\nINNER JOIN ");
sqlClause(builder, "OUTER JOIN", outerJoin, "", "", "\nOUTER JOIN ");
sqlClause(builder, "LEFT OUTER JOIN", leftOuterJoin, "", "",
"\nLEFT OUTER JOIN ");
sqlClause(builder, "RIGHT OUTER JOIN", rightOuterJoin, "", "",
"\nRIGHT OUTER JOIN ");
sqlClause(builder, "WHERE", where, "(", ")", " AND ");
sqlClause(builder, "GROUP BY", groupBy, "", "", ", ");
sqlClause(builder, "HAVING", having, "(", ")", " AND ");
sqlClause(builder, "ORDER BY", orderBy, "", "", ", ");
return builder.toString();
}
private String insertSQL(SafeAppendable builder) {
sqlClause(builder, "INSERT INTO", tables, "", "", "");
sqlClause(builder, "", columns, "(", ")", ", ");
sqlClause(builder, "VALUES", values, "(", ")", ", ");
return builder.toString();
}
private String deleteSQL(SafeAppendable builder) {
sqlClause(builder, "DELETE FROM", tables, "", "", "");
sqlClause(builder, "WHERE", where, "(", ")", " AND ");
return builder.toString();
}
private String updateSQL(SafeAppendable builder) {
sqlClause(builder, "UPDATE", tables, "", "", "");
sqlClause(builder, "SET", sets, "", "", ", ");
sqlClause(builder, "WHERE", where, "(", ")", " AND ");
return builder.toString();
}
public String sql(Appendable a) {
SafeAppendable builder = new SafeAppendable(a);
if (statementType == null) {
return null;
}
String answer;
switch (statementType) {
case DELETE:
answer = deleteSQL(builder);
break;
case INSERT:
answer = insertSQL(builder);
break;
case SELECT:
answer = selectSQL(builder);
break;
case UPDATE:
answer = updateSQL(builder);
break;
default:
answer = null;
}
return answer;
}
}
}
|
package gwt.material.design.client.ui;
/*
* #%L
* GwtMaterial
* %%
* Copyright (C) 2015 GwtMaterialDesign
* %%
* 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.
* #L%
*/
import gwt.material.design.client.base.HasTitle;
import gwt.material.design.client.constants.HeadingSize;
import gwt.material.design.client.ui.html.Div;
import gwt.material.design.client.ui.html.Heading;
import gwt.material.design.client.ui.html.Paragraph;
import com.google.gwt.dom.client.Style.Unit;
//@formatter:off
/**
* Title is a component that will easily add Title and description widgets
*
* <p>
* <h3>UiBinder Usage:</h3>
* <pre>
* {@code
* <m:MaterialTitle title="I love Material Design" description="This is sample description" />
* }
* </pre>
* </p>
*
* @author kevzlou7979
* @author Ben Dol
*/
//@formatter:on
public class MaterialTitle extends Div implements HasTitle {
Heading header = new Heading(HeadingSize.H4);
Paragraph paragraph = new Paragraph();
public MaterialTitle() {
header.setFontWeight(300);
header.getElement().getStyle().setMarginTop(60, Unit.PX);
add(header);
add(paragraph);
}
public MaterialTitle(String title, String description) {
this();
setTitle(title);
setDescription(description);
}
public MaterialTitle(String title) {
this();
setTitle(title);
}
@Override
public void setDescription(String description) {
paragraph.setText(description);
}
@Override
public void setTitle(String title) {
header.getElement().setInnerHTML(title);
}
}
|
package com._4point.aem.docservices.rest_services.server.data;
import static org.junit.jupiter.api.Assertions.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import org.apache.commons.io.IOUtils;
import org.junit.jupiter.api.Test;
import com.adobe.forms.common.service.DataXMLOptions;
class DataCachePrefillServiceTest {
private static final byte[] EXPECTED_DATA_BYTES = ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n"
+ "<form1>\r\n"
+ " <TextField1>Text Field1 Data</TextField1>\r\n"
+ " <TextField2>Text Field2 Data</TextField2>\r\n"
+ "</form1>").getBytes(StandardCharsets.UTF_8);
private DataCachePrefillService underTest = new DataCachePrefillService();
@Test
void testGetDataXMLForDataRef() throws Exception {
// Store data in the cache and then call the preFill service with mock options object that contains the UUID from the cache.
String uuid = addDataToCache(EXPECTED_DATA_BYTES);
InputStream result = underTest.getDataXMLForDataRef(mockDataXmlOptions(uuid));
// Verify the result
assertNotNull(result);
assertArrayEquals(EXPECTED_DATA_BYTES, IOUtils.toByteArray(result), "Expected result to match the data placed in the cache.");
}
@Test
void testGetDataXMLForDataRef_InvalidUuid() throws Exception {
// Send an invalid uuid
String uuid = "foobar";
InputStream result = underTest.getDataXMLForDataRef(mockDataXmlOptions(uuid));
// Verify the result
assertNull(result, "Expect to get null back if an invalid cache id is provided.");
}
@Test
void testGetDataXMLForDataRef_EmptyIdentifier() throws Exception {
// Send an empty UUID
InputStream result = underTest.getDataXMLForDataRef(mockDataXmlOptions(""));
// Verify the result
assertNull(result, "Expect to get null back if an invalid cache id is provided.");
}
@Test
void testGetDataXMLForDataRef_EmptyIdentifier2() throws Exception {
// send service name only
InputStream result = underTest.getDataXMLForDataRef(mockDataXmlOptions(null));
// Verify the result
assertNull(result, "Expect to get null back if an invalid cache id is provided.");
}
@Test
void testGetDataXMLForDataRef_EmptyOptions() throws Exception {
// Send empty DataXmlOptions structure (which is what happens when called from editor).
InputStream result = underTest.getDataXMLForDataRef(new DataXMLOptions());
// Verify the result
assertNull(result, "Expect to get null back if an invalid cache id is provided.");
}
@Test
void testGetDataXMLForDataRef_Null() {
NullPointerException ex = assertThrows(NullPointerException.class, ()->underTest.getDataXMLForDataRef(null));
String msg = ex.getMessage();
assertNotNull(msg);
assertAll(
()->assertThat(msg, containsString("DataXMLOptions")),
()->assertThat(msg, containsString("com._4point.aem.docservices.rest_services.server.data.DataCachePrefillService.getDataXMLForDataRef()."))
);
}
@Test
void testGetServiceName() {
assertEquals("FFPrefillService", underTest.getServiceName());
}
@Test
void testGetServiceDescription() {
assertEquals("Fluent Forms REST Services Prefill Service for Adaptive Forms", underTest.getServiceDescription());
}
private String addDataToCache(byte[] bytes) {
return DataCache.addDataToCache(bytes, "application/xml");
}
private DataXMLOptions mockDataXmlOptions(String identifier) {
DataXMLOptions options = new DataXMLOptions();
options.setDataRef("service://FFPrefillService" + (identifier != null ? "/" + identifier : ""));
return options;
}
}
|
/*
* Copyright 2010-2013 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 org.jetbrains.jet.di;
import com.google.common.collect.Lists;
import org.jetbrains.annotations.NotNull;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
public class GivenExpression implements Expression {
private final String expression;
private final Collection<DiType> typesToImport;
public GivenExpression(@NotNull String expression) {
this(expression, Collections.<DiType>emptyList());
}
public GivenExpression(@NotNull String expression, @NotNull DiType... typesToImport) {
this(expression, Arrays.asList(typesToImport));
}
public GivenExpression(@NotNull String expression, @NotNull Class<?>... typesToImport) {
this(expression, convertClassesToDiTypes(typesToImport));
}
private static Collection<DiType> convertClassesToDiTypes(Class<?>[] typesToImport) {
Collection<DiType> types = Lists.newArrayList();
for (Class<?> aClass : typesToImport) {
types.add(new DiType(aClass));
}
return types;
}
public GivenExpression(@NotNull String expression, @NotNull Collection<DiType> typesToImport) {
this.expression = expression;
this.typesToImport = typesToImport;
}
public String getExpression() {
return expression;
}
@Override
public String toString() {
return "given<" + expression + ">";
}
public DiType getType() {
return null;
}
@NotNull
@Override
public String renderAsCode() {
return expression;
}
@NotNull
@Override
public Collection<DiType> getTypesToImport() {
return typesToImport;
}
}
|
package seedu.addressbook.data.person;
class Contact {
protected String value;
protected boolean isPrivate;
@Override
public int hashCode() {
return value.hashCode();
}
public boolean isPrivate() {
return isPrivate;
}
}
|
package com.github.mygreen.supercsv.cellprocessor.format;
import com.github.mygreen.supercsv.annotation.format.CsvFormat;
/**
* 文字列とオブジェクトの相互変換を行うインタフェースです。
*
* @param <T> オブジェクトのタイプ
* @since 2.0
* @author T.TSUCHIE
*
*/
public interface TextFormatter<T> extends TextParser<T>, TextPrinter<T> {
/**
* パース時のエラーメッセージを設定します。
* <p>{@link CsvFormat#message()}で指定されたメッセージを渡す場合に実装します。
* <br>このメソッドを実装する際には、{@link TextParser#getValidationMessage()}も実装してください。
* </p>
*
* @param validationMessage パース時のエラーメッセージ
*/
void setValidationMessage(String validationMessage);
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.metrics.rest.server.jersey;
import org.glassfish.jersey.CommonProperties;
import javax.ws.rs.core.Feature;
import javax.ws.rs.core.FeatureContext;
import javax.ws.rs.ext.MessageBodyReader;
import javax.ws.rs.ext.MessageBodyWriter;
public class FastJsonFeature implements Feature {
public boolean configure(final FeatureContext context) {
final String disableMoxy = CommonProperties.MOXY_JSON_FEATURE_DISABLE + '.'
+ context.getConfiguration().getRuntimeType().name().toLowerCase();
context.property(disableMoxy, true);
context.register(FastJsonProvider.class, MessageBodyReader.class, MessageBodyWriter.class);
return true;
}
}
|
package uk.co.hmtt.gym.app.service;
import uk.co.hmtt.gym.app.model.Activity;
import uk.co.hmtt.gym.app.model.Exclusion;
import uk.co.hmtt.gym.app.model.User;
import uk.co.hmtt.gym.app.model.UserActivity;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
public interface UserActivityService {
Map<User, Set<UserActivity>> getBookingRequests();
uk.co.hmtt.gym.app.model.UserActivity getBookingRequest(User user, Activity activity);
List<UserActivity> getBookingRequest(User user);
void addBookingRequest(uk.co.hmtt.gym.app.model.UserActivity userActivity);
void removeBookingRequest(uk.co.hmtt.gym.app.model.UserActivity userActivity);
void removeExclusion(uk.co.hmtt.gym.app.model.UserActivity userActivity, Date date);
void addExclusion(final Exclusion exclusion);
Exclusion addExclusion(UserActivity bookingRequest, String date);
void updateBookingRequest(uk.co.hmtt.gym.app.model.UserActivity userActivity);
void createBookingActivity(Activity activity, User user);
void cancelExistingExclusion(String cancelDate, UserActivity bookingRequest);
}
|
package com.example.lulin.todolist.Utils;
import android.content.Context;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.preference.PreferenceManager;
/**
* 4.4 出现 MediaPlayer: Should have subtitle controller already set 错误
* Don't care about this "Exception".
*
* @link https://stackoverflow.com/questions/20087804/should-have-subtitle-controller-already-set-mediaplayer-error-android
*/
public class Sound {
private Context mContext;
private MediaPlayer mMediaPlayer;
private MediaPlayer mNextPlayer;
private OnCompletionListener mOnCompletionListener = new OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
mediaPlayer.stop();
mediaPlayer.release();
mMediaPlayer = mNextPlayer;
setNextMediaPlayer(getMusicid());
}
};
public Sound(Context context) {
mContext = context;
build(getMusicid());
}
/**
* setLooping(true) 虽然能循环播放,但不能做到无缝播放处理,会出现短暂的暂停
* 这里采用 setNextMediaPlayer 来解决这问题
*
* @link https://stackoverflow.com/questions/13409657/how-to-loop-a-sound-without-gaps-in-android
* @link https://developer.android.com/reference/android/media/MediaPlayer.html#setNextMediaPlayer(android.media.MediaPlayer)
*/
private void build(int id) {
mMediaPlayer = MediaPlayer.create(mContext, id);
setNextMediaPlayer(id);
}
private void setNextMediaPlayer(int id) {
mNextPlayer = MediaPlayer.create(mContext, id);
mMediaPlayer.setNextMediaPlayer(mNextPlayer);
mMediaPlayer.setOnCompletionListener(mOnCompletionListener);
}
public void play() {
if (isSoundOn()) {
if (!mMediaPlayer.isPlaying()) {
mMediaPlayer.start();
}
}
}
public void pause() {
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.pause();
}
}
public void resume() {
if (isSoundOn()) {
if (!mMediaPlayer.isPlaying()) {
mMediaPlayer.start();
}
}
}
/**
* 不要调用 MediaPlayer.stop 停止播放音频,调用这个方法后的 MediaPlayer 对象无法再播放音频
*/
public void stop() {
if (mMediaPlayer.isPlaying()) {
release();
build(getMusicid());
}
}
public void release() {
if (mMediaPlayer != null) {
mMediaPlayer.stop();
mMediaPlayer.release();
mMediaPlayer = null;
mNextPlayer.stop();
mNextPlayer.release();
mNextPlayer = null;
}
}
public void reset(){
mMediaPlayer.reset();
build(getMusicid());
}
private boolean isSoundOn() {
return PreferenceManager.getDefaultSharedPreferences(mContext)
.getBoolean("pref_key_tick_sound", true);
}
private int getMusicid(){
return (int)SPUtils.get(mContext, "music_id",1);
}
}
|
/*
* 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.openmetadata.catalog.resources.charts;
import com.google.inject.Inject;
import io.swagger.annotations.Api;
import io.swagger.v3.oas.annotations.ExternalDocumentation;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.ExampleObject;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import org.openmetadata.catalog.api.data.CreateChart;
import org.openmetadata.catalog.entity.data.Chart;
import org.openmetadata.catalog.entity.data.Dashboard;
import org.openmetadata.catalog.jdbi3.ChartRepository;
import org.openmetadata.catalog.resources.Collection;
import org.openmetadata.catalog.security.CatalogAuthorizer;
import org.openmetadata.catalog.security.SecurityUtil;
import org.openmetadata.catalog.type.EntityReference;
import org.openmetadata.catalog.util.EntityUtil;
import org.openmetadata.catalog.util.EntityUtil.Fields;
import org.openmetadata.catalog.util.RestUtil;
import org.openmetadata.catalog.util.RestUtil.PutResponse;
import org.openmetadata.catalog.util.ResultList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.json.JsonPatch;
import javax.validation.Valid;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.PATCH;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.SecurityContext;
import javax.ws.rs.core.UriInfo;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
@Path("/v1/charts")
@Api(value = "Chart data asset collection", tags = "Chart data asset collection")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Collection(name = "charts", repositoryClass = "org.openmetadata.catalog.jdbi3.ChartRepository")
public class ChartResource {
private static final Logger LOG = LoggerFactory.getLogger(ChartResource.class);
private static final String CHART_COLLECTION_PATH = "v1/charts/";
private final ChartRepository dao;
private final CatalogAuthorizer authorizer;
public static void addHref(UriInfo uriInfo, EntityReference ref) {
ref.withHref(RestUtil.getHref(uriInfo, CHART_COLLECTION_PATH, ref.getId()));
}
public static List<Chart> addHref(UriInfo uriInfo, List<Chart> charts) {
Optional.ofNullable(charts).orElse(Collections.emptyList()).forEach(i -> addHref(uriInfo, i));
return charts;
}
public static Chart addHref(UriInfo uriInfo, Chart chart) {
chart.setHref(RestUtil.getHref(uriInfo, CHART_COLLECTION_PATH, chart.getId()));
EntityUtil.addHref(uriInfo, chart.getOwner());
EntityUtil.addHref(uriInfo, chart.getService());
EntityUtil.addHref(uriInfo, chart.getFollowers());
return chart;
}
@Inject
public ChartResource(ChartRepository dao, CatalogAuthorizer authorizer) {
Objects.requireNonNull(dao, "ChartRepository must not be null");
this.dao = dao;
this.authorizer = authorizer;
}
public static class ChartList extends ResultList<Chart> {
@SuppressWarnings("unused")
ChartList() {
// Empty constructor needed for deserialization
}
public ChartList(List<Chart> data, String beforeCursor, String afterCursor, int total)
throws GeneralSecurityException, UnsupportedEncodingException {
super(data, beforeCursor, afterCursor, total);
}
}
static final String FIELDS = "owner,service,followers,tags";
public static final List<String> FIELD_LIST = Arrays.asList(FIELDS.replaceAll(" ", "")
.split(","));
@GET
@Valid
@Operation(summary = "List charts", tags = "charts",
description = "Get a list of charts, optionally filtered by `service` it belongs to. Use `fields` " +
"parameter to get only necessary fields. Use cursor-based pagination to limit the number " +
"entries in the list using `limit` and `before` or `after` query params.",
responses = {
@ApiResponse(responseCode = "200", description = "List of charts",
content = @Content(mediaType = "application/json",
schema = @Schema(implementation = ChartList.class)))
})
public ChartList list(@Context UriInfo uriInfo,
@Context SecurityContext securityContext,
@Parameter(description = "Fields requested in the returned resource",
schema = @Schema(type = "string", example = FIELDS))
@QueryParam("fields") String fieldsParam,
@Parameter(description = "Filter charts by service name",
schema = @Schema(type = "string", example = "superset"))
@QueryParam("service") String serviceParam,
@Parameter(description = "Limit the number charts returned. (1 to 1000000, default = 10)")
@DefaultValue("10")
@Min(1)
@Max(1000000)
@QueryParam("limit") int limitParam,
@Parameter(description = "Returns list of charts before this cursor",
schema = @Schema(type = "string"))
@QueryParam("before") String before,
@Parameter(description = "Returns list of charts after this cursor",
schema = @Schema(type = "string"))
@QueryParam("after") String after
) throws IOException, GeneralSecurityException {
RestUtil.validateCursors(before, after);
Fields fields = new Fields(FIELD_LIST, fieldsParam);
ChartList charts;
if (before != null) { // Reverse paging
charts = dao.listBefore(fields, serviceParam, limitParam, before); // Ask for one extra entry
} else { // Forward paging or first page
charts = dao.listAfter(fields, serviceParam, limitParam, after);
}
addHref(uriInfo, charts.getData());
return charts;
}
@GET
@Path("/{id}")
@Operation(summary = "Get a Chart", tags = "charts",
description = "Get a chart by `id`.",
responses = {
@ApiResponse(responseCode = "200", description = "The chart",
content = @Content(mediaType = "application/json",
schema = @Schema(implementation = Dashboard.class))),
@ApiResponse(responseCode = "404", description = "Chart for instance {id} is not found")
})
public Chart get(@Context UriInfo uriInfo, @PathParam("id") String id,
@Context SecurityContext securityContext,
@Parameter(description = "Fields requested in the returned resource",
schema = @Schema(type = "string", example = FIELDS))
@QueryParam("fields") String fieldsParam) throws IOException {
Fields fields = new Fields(FIELD_LIST, fieldsParam);
return addHref(uriInfo, dao.get(id, fields));
}
@GET
@Path("/name/{fqn}")
@Operation(summary = "Get a chart by name", tags = "charts",
description = "Get a chart by fully qualified name.",
responses = {
@ApiResponse(responseCode = "200", description = "The chart",
content = @Content(mediaType = "application/json",
schema = @Schema(implementation = Chart.class))),
@ApiResponse(responseCode = "404", description = "Chart for instance {id} is not found")
})
public Response getByName(@Context UriInfo uriInfo, @PathParam("fqn") String fqn,
@Context SecurityContext securityContext,
@Parameter(description = "Fields requested in the returned resource",
schema = @Schema(type = "string", example = FIELDS))
@QueryParam("fields") String fieldsParam) throws IOException {
Fields fields = new Fields(FIELD_LIST, fieldsParam);
Chart chart = dao.getByName(fqn, fields);
addHref(uriInfo, chart);
return Response.ok(chart).build();
}
@POST
@Operation(summary = "Create a chart", tags = "charts",
description = "Create a chart under an existing `service`.",
responses = {
@ApiResponse(responseCode = "200", description = "The chart",
content = @Content(mediaType = "application/json",
schema = @Schema(implementation = Chart.class))),
@ApiResponse(responseCode = "400", description = "Bad request")
})
public Response create(@Context UriInfo uriInfo, @Context SecurityContext securityContext,
@Valid CreateChart create) throws IOException {
SecurityUtil.checkAdminOrBotRole(authorizer, securityContext);
Chart chart =
new Chart().withId(UUID.randomUUID()).withName(create.getName()).withDisplayName(create.getDisplayName())
.withDescription(create.getDescription())
.withService(create.getService())
.withChartType(create.getChartType()).withChartUrl(create.getChartUrl())
.withTables(create.getTables()).withTags(create.getTags())
.withOwner(create.getOwner());
chart = addHref(uriInfo, dao.create(chart, create.getService(), create.getOwner()));
return Response.created(chart.getHref()).entity(chart).build();
}
@PATCH
@Path("/{id}")
@Operation(summary = "Update a chart", tags = "charts",
description = "Update an existing chart using JsonPatch.",
externalDocs = @ExternalDocumentation(description = "JsonPatch RFC",
url = "https://tools.ietf.org/html/rfc6902"))
@Consumes(MediaType.APPLICATION_JSON_PATCH_JSON)
public Chart updateDescription(@Context UriInfo uriInfo,
@Context SecurityContext securityContext,
@PathParam("id") String id,
@RequestBody(description = "JsonPatch with array of operations",
content = @Content(mediaType = MediaType.APPLICATION_JSON_PATCH_JSON,
examples = {@ExampleObject("[" +
"{op:remove, path:/a}," +
"{op:add, path: /b, value: val}" +
"]")}))
JsonPatch patch) throws IOException {
Fields fields = new Fields(FIELD_LIST, FIELDS);
Chart chart = dao.get(id, fields);
SecurityUtil.checkAdminRoleOrPermissions(authorizer, securityContext,
EntityUtil.getEntityReference(chart));
chart = dao.patch(id, patch);
return addHref(uriInfo, chart);
}
@PUT
@Operation(summary = "Create or update chart", tags = "charts",
description = "Create a chart, it it does not exist or update an existing chart.",
responses = {
@ApiResponse(responseCode = "200", description = "The updated chart ",
content = @Content(mediaType = "application/json",
schema = @Schema(implementation = Chart.class)))
})
public Response createOrUpdate(@Context UriInfo uriInfo,
@Context SecurityContext securityContext,
@Valid CreateChart create) throws IOException {
Chart chart =
new Chart().withId(UUID.randomUUID()).withName(create.getName()).withDisplayName(create.getDisplayName())
.withDescription(create.getDescription())
.withService(create.getService())
.withChartType(create.getChartType()).withChartUrl(create.getChartUrl())
.withTables(create.getTables()).withTags(create.getTags())
.withOwner(create.getOwner());
PutResponse<Chart> response = dao.createOrUpdate(chart, create.getService(), create.getOwner());
chart = addHref(uriInfo, response.getEntity());
return Response.status(response.getStatus()).entity(chart).build();
}
@PUT
@Path("/{id}/followers")
@Operation(summary = "Add a follower", tags = "charts",
description = "Add a user identified by `userId` as followed of this chart",
responses = {
@ApiResponse(responseCode = "200", description = "OK"),
@ApiResponse(responseCode = "404", description = "Chart for instance {id} is not found")
})
public Response addFollower(@Context UriInfo uriInfo,
@Context SecurityContext securityContext,
@Parameter(description = "Id of the chart", schema = @Schema(type = "string"))
@PathParam("id") String id,
@Parameter(description = "Id of the user to be added as follower",
schema = @Schema(type = "string"))
String userId) throws IOException {
Fields fields = new Fields(FIELD_LIST, "followers");
Response.Status status = dao.addFollower(id, userId);
Chart chart = addHref(uriInfo, dao.get(id, fields));
return Response.status(status).entity(chart).build();
}
@DELETE
@Path("/{id}/followers/{userId}")
@Operation(summary = "Remove a follower", tags = "charts",
description = "Remove the user identified `userId` as a follower of the chart.")
public Chart deleteFollower(@Context UriInfo uriInfo,
@Context SecurityContext securityContext,
@Parameter(description = "Id of the chart",
schema = @Schema(type = "string"))
@PathParam("id") String id,
@Parameter(description = "Id of the user being removed as follower",
schema = @Schema(type = "string"))
@PathParam("userId") String userId) throws IOException {
Fields fields = new Fields(FIELD_LIST, "followers");
dao.deleteFollower(id, userId);
return addHref(uriInfo, dao.get(id, fields));
}
@DELETE
@Path("/{id}")
@Operation(summary = "Delete a Chart", tags = "charts",
description = "Delete a chart by `id`.",
responses = {
@ApiResponse(responseCode = "200", description = "OK"),
@ApiResponse(responseCode = "404", description = "Chart for instance {id} is not found")
})
public Response delete(@Context UriInfo uriInfo, @PathParam("id") String id) {
dao.delete(id);
return Response.ok().build();
}
}
|
package mlkit;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.util.Log;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.FirebaseApp;
import com.google.firebase.ml.vision.FirebaseVision;
import com.google.firebase.ml.vision.cloud.FirebaseVisionCloudDetectorOptions;
import com.google.firebase.ml.vision.cloud.landmark.FirebaseVisionCloudLandmark;
import com.google.firebase.ml.vision.cloud.landmark.FirebaseVisionCloudLandmarkDetector;
import com.google.firebase.ml.vision.common.FirebaseVisionImage;
import com.google.firebase.ml.vision.common.FirebaseVisionLatLng;
import java.io.File;
import mlkit.helpers.MyHelper;
import pl.aprilapps.easyphotopicker.DefaultCallback;
import pl.aprilapps.easyphotopicker.EasyImage;
import stone.breaker.R;
import stone.breaker.mainmenu;
import static android.graphics.BitmapFactory.decodeFile;
public class LandmarkActivity extends BaseActivity {
private TextView mTextView;
FloatingActionButton gallery;
Button back;
private static final String TAG = LandmarkActivity.class.getSimpleName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cloud);
mTextView = findViewById(R.id.text_view);
back = findViewById(R.id.back);
back.setOnClickListener(view -> {
Intent intent = new Intent(LandmarkActivity.this, mainmenu.class);
startActivity(intent);
finish();
});
gallery = findViewById(R.id.gallery);
gallery.setOnClickListener(view -> {
//Opens gallery picker
EasyImage.openGallery(LandmarkActivity.this, 100);
});
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
FirebaseApp.initializeApp(LandmarkActivity.this);
EasyImage.handleActivityResult(requestCode, resultCode, data, this, new DefaultCallback() {
@Override
public void onImagePickerError(Exception e, EasyImage.ImageSource source, int type) {
Toast.makeText(LandmarkActivity.this, "Image picker error", Toast.LENGTH_SHORT).show();
Log.d(TAG, "onImagePickerError: " + "Image picker error");
}
@Override
public void onImagePicked(File imageFile, EasyImage.ImageSource source, int type) {
new BitmapFactory();
new BitmapFactory();
FirebaseVisionImage image = FirebaseVisionImage.fromBitmap(decodeFile(imageFile.getAbsolutePath()));
Toast.makeText(LandmarkActivity.this, "Success, working our magic now!", Toast.LENGTH_LONG).show();
MyHelper.showDialog(LandmarkActivity.this);
FirebaseVisionCloudDetectorOptions options = new FirebaseVisionCloudDetectorOptions.Builder()
.setModelType(FirebaseVisionCloudDetectorOptions.LATEST_MODEL)
.setMaxResults(5)
.build();
FirebaseVisionCloudLandmarkDetector detector = FirebaseVision.getInstance().getVisionCloudLandmarkDetector(options);
detector.detectInImage(image).addOnSuccessListener(firebaseVisionCloudLandmarks -> {
MyHelper.dismissDialog();
StringBuilder result = new StringBuilder();
for (FirebaseVisionCloudLandmark landmark : firebaseVisionCloudLandmarks) {
String landmarkName = landmark.getLandmark();
float confidence = landmark.getConfidence();
result.append("Landmark: ").append(landmarkName).append("\n");
result.append("Confidence: ").append(confidence).append("\n");
for (FirebaseVisionLatLng loc : landmark.getLocations()) {
result.append("Location: ").append(loc.getLatitude()).append(",").append(loc.getLongitude()).append("\n");
}
result.append("\n");
}
if ("".equals(result.toString())) {
mTextView.setText(R.string.error_detect);
} else {
mTextView.setText(result.toString());
}
}).addOnFailureListener(e -> {
MyHelper.dismissDialog();
mTextView.setText(e.getMessage());
});
}
});
}
}
|
package com.atguigu.gmall.ums.entity;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.math.BigDecimal;
import java.io.Serializable;
import java.util.Date;
import lombok.Data;
/**
* 统计信息表
*
* @author lmx
* @email lmx@atguigu.com
* @date 2020-10-28 16:51:38
*/
@Data
@TableName("ums_user_statistics")
public class UserStatisticsEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
* id
*/
@TableId
private Long id;
/**
* 用户id
*/
private Long userId;
/**
* 累计消费金额
*/
private BigDecimal consumeAmount;
/**
* 累计优惠金额
*/
private BigDecimal couponAmount;
/**
* 订单数量
*/
private Integer orderCount;
/**
* 优惠券数量
*/
private Integer couponCount;
/**
* 评价数
*/
private Integer commentCount;
/**
* 退货数量
*/
private Integer returnOrderCount;
/**
* 登录次数
*/
private Integer loginCount;
/**
* 关注数量
*/
private Integer attendCount;
/**
* 粉丝数量
*/
private Integer fansCount;
/**
* 收藏的商品数量
*/
private Integer collectProductCount;
/**
* 收藏的专题活动数量
*/
private Integer collectSubjectCount;
/**
* 收藏的评论数量
*/
private Integer collectCommentCount;
/**
* 邀请的朋友数量
*/
private Integer inviteFriendCount;
}
|
package com.hbird.common.chating.components;
import android.graphics.Color;
import android.graphics.Paint;
import com.hbird.common.chating.utils.Utils;
/**
* Class representing the y-axis labels settings and its entries. Only use the setter methods to
* modify it. Do not
* access public variables directly. Be aware that not all features the YLabels class provides
* are suitable for the
* RadarChart. Customizations that affect the value range of the axis need to be applied before
* setting data for the
* chart.
*
* @author Philipp Jahoda
*/
public class YAxis extends AxisBase {
/**
* indicates if the bottom y-label entry is drawn or not
*/
private boolean mDrawBottomYLabelEntry = true;
/**
* indicates if the top y-label entry is drawn or not
*/
private boolean mDrawTopYLabelEntry = true;
/**
* flag that indicates if the axis is inverted or not
*/
protected boolean mInverted = false;
/**
* flag that indicates if the zero-line should be drawn regardless of other grid lines
*/
protected boolean mDrawZeroLine = false;
/**
* flag indicating that auto scale min restriction should be used
*/
private boolean mUseAutoScaleRestrictionMin = false;
/**
* flag indicating that auto scale max restriction should be used
*/
private boolean mUseAutoScaleRestrictionMax = false;
/**
* Color of the zero line
*/
protected int mZeroLineColor = Color.GRAY;
/**
* Width of the zero line in pixels
*/
protected float mZeroLineWidth = 1f;
/**
* axis space from the largest value to the top in percent of the total axis range
*/
protected float mSpacePercentTop = 10f;
/**
* axis space from the smallest value to the bottom in percent of the total axis range
*/
protected float mSpacePercentBottom = 10f;
/**
* the position of the y-labels relative to the chart
*/
private YAxisLabelPosition mPosition = YAxisLabelPosition.OUTSIDE_CHART;
/**
* enum for the position of the y-labels relative to the chart
*/
public enum YAxisLabelPosition {
OUTSIDE_CHART, INSIDE_CHART
}
/**
* the side this axis object represents
*/
private AxisDependency mAxisDependency;
/**
* the minimum width that the axis should take (in dp).
* <p/>
* default: 0.0
*/
protected float mMinWidth = 0.f;
/**
* the maximum width that the axis can take (in dp).
* use Inifinity for disabling the maximum
* default: Float.POSITIVE_INFINITY (no maximum specified)
*/
protected float mMaxWidth = Float.POSITIVE_INFINITY;
/**
* Enum that specifies the axis a DataSet should be plotted against, either LEFT or RIGHT.
*
* @author Philipp Jahoda
*/
public enum AxisDependency {
LEFT, RIGHT
}
public YAxis() {
super();
// default left
this.mAxisDependency = AxisDependency.LEFT;
this.mYOffset = 0f;
}
public YAxis(AxisDependency position) {
super();
this.mAxisDependency = position;
this.mYOffset = 0f;
}
public AxisDependency getAxisDependency() {
return mAxisDependency;
}
/**
* @return the minimum width that the axis should take (in dp).
*/
public float getMinWidth() {
return mMinWidth;
}
/**
* Sets the minimum width that the axis should take (in dp).
*
* @param minWidth
*/
public void setMinWidth(float minWidth) {
mMinWidth = minWidth;
}
/**
* @return the maximum width that the axis can take (in dp).
*/
public float getMaxWidth() {
return mMaxWidth;
}
/**
* Sets the maximum width that the axis can take (in dp).
*
* @param maxWidth
*/
public void setMaxWidth(float maxWidth) {
mMaxWidth = maxWidth;
}
/**
* returns the position of the y-labels
*/
public YAxisLabelPosition getLabelPosition() {
return mPosition;
}
/**
* sets the position of the y-labels
*
* @param pos
*/
public void setPosition(YAxisLabelPosition pos) {
mPosition = pos;
}
/**
* returns true if drawing the top y-axis label entry is enabled
*
* @return
*/
public boolean isDrawTopYLabelEntryEnabled() {
return mDrawTopYLabelEntry;
}
/**
* returns true if drawing the bottom y-axis label entry is enabled
*
* @return
*/
public boolean isDrawBottomYLabelEntryEnabled() {
return mDrawBottomYLabelEntry;
}
/**
* set this to true to enable drawing the top y-label entry. Disabling this can be helpful
* when the top y-label and
* left x-label interfere with each other. default: true
*
* @param enabled
*/
public void setDrawTopYLabelEntry(boolean enabled) {
mDrawTopYLabelEntry = enabled;
}
/**
* If this is set to true, the y-axis is inverted which means that low values are on top of
* the chart, high values
* on bottom.
*
* @param enabled
*/
public void setInverted(boolean enabled) {
mInverted = enabled;
}
/**
* If this returns true, the y-axis is inverted.
*
* @return
*/
public boolean isInverted() {
return mInverted;
}
/**
* This method is deprecated.
* Use setAxisMinimum(...) / setAxisMaximum(...) instead.
*
* @param startAtZero
*/
@Deprecated
public void setStartAtZero(boolean startAtZero) {
if (startAtZero)
setAxisMinimum(0f);
else
resetAxisMinimum();
}
/**
* Sets the top axis space in percent of the full range. Default 10f
*
* @param percent
*/
public void setSpaceTop(float percent) {
mSpacePercentTop = percent;
}
/**
* Returns the top axis space in percent of the full range. Default 10f
*
* @return
*/
public float getSpaceTop() {
return mSpacePercentTop;
}
/**
* Sets the bottom axis space in percent of the full range. Default 10f
*
* @param percent
*/
public void setSpaceBottom(float percent) {
mSpacePercentBottom = percent;
}
/**
* Returns the bottom axis space in percent of the full range. Default 10f
*
* @return
*/
public float getSpaceBottom() {
return mSpacePercentBottom;
}
public boolean isDrawZeroLineEnabled() {
return mDrawZeroLine;
}
/**
* Set this to true to draw the zero-line regardless of weather other
* grid-lines are enabled or not. Default: false
*
* @param mDrawZeroLine
*/
public void setDrawZeroLine(boolean mDrawZeroLine) {
this.mDrawZeroLine = mDrawZeroLine;
}
public int getZeroLineColor() {
return mZeroLineColor;
}
/**
* Sets the color of the zero line
*
* @param color
*/
public void setZeroLineColor(int color) {
mZeroLineColor = color;
}
public float getZeroLineWidth() {
return mZeroLineWidth;
}
/**
* Sets the width of the zero line in dp
*
* @param width
*/
public void setZeroLineWidth(float width) {
this.mZeroLineWidth = Utils.convertDpToPixel(width);
}
/**
* This is for normal (not horizontal) charts horizontal spacing.
*
* @param p
* @return
*/
public float getRequiredWidthSpace(Paint p) {
p.setTextSize(mTextSize);
String label = getLongestLabel();
float width = (float) Utils.calcTextWidth(p, label) + getXOffset() * 2f;
float minWidth = getMinWidth();
float maxWidth = getMaxWidth();
if (minWidth > 0.f)
minWidth = Utils.convertDpToPixel(minWidth);
if (maxWidth > 0.f && maxWidth != Float.POSITIVE_INFINITY)
maxWidth = Utils.convertDpToPixel(maxWidth);
width = Math.max(minWidth, Math.min(width, maxWidth > 0.0 ? maxWidth : width));
return width;
}
/**
* This is for HorizontalBarChart vertical spacing.
*
* @param p
* @return
*/
public float getRequiredHeightSpace(Paint p) {
p.setTextSize(mTextSize);
String label = getLongestLabel();
return (float) Utils.calcTextHeight(p, label) + getYOffset() * 2f;
}
/**
* Returns true if this axis needs horizontal offset, false if no offset is needed.
*
* @return
*/
public boolean needsOffset() {
if (isEnabled() && isDrawLabelsEnabled() && getLabelPosition() == YAxisLabelPosition
.OUTSIDE_CHART)
return true;
else
return false;
}
/**
* Returns true if autoscale restriction for axis min value is enabled
*/
@Deprecated
public boolean isUseAutoScaleMinRestriction( ) {
return mUseAutoScaleRestrictionMin;
}
/**
* Sets autoscale restriction for axis min value as enabled/disabled
*/
@Deprecated
public void setUseAutoScaleMinRestriction( boolean isEnabled ) {
mUseAutoScaleRestrictionMin = isEnabled;
}
/**
* Returns true if autoscale restriction for axis max value is enabled
*/
@Deprecated
public boolean isUseAutoScaleMaxRestriction() {
return mUseAutoScaleRestrictionMax;
}
/**
* Sets autoscale restriction for axis max value as enabled/disabled
*/
@Deprecated
public void setUseAutoScaleMaxRestriction( boolean isEnabled ) {
mUseAutoScaleRestrictionMax = isEnabled;
}
@Override
public void calculate(float dataMin, float dataMax) {
float min = dataMin;
float max = dataMax;
float range = Math.abs(max - min);
// in case all values are equal
if (range == 0f) {
max = max + 1f;
min = min - 1f;
}
// recalculate
range = Math.abs(max - min);
// calc extra spacing
this.mAxisMinimum = mCustomAxisMin ? this.mAxisMinimum : min - (range / 100f) * getSpaceBottom();
this.mAxisMaximum = mCustomAxisMax ? this.mAxisMaximum : max + (range / 100f) * getSpaceTop();
this.mAxisRange = Math.abs(this.mAxisMinimum - this.mAxisMaximum);
}
}
|
/*
* Copyright 2018 JDCLOUD.COM
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http:#www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Virtual-Private-Cloud
* 私有网络相关接口
*
* OpenAPI spec version: v1
* Contact:
*
* NOTE: This class is auto generated by the jdcloud code generator program.
*/
package com.jdcloud.sdk.service.vpc.model;
import java.util.List;
import java.util.ArrayList;
import com.jdcloud.sdk.service.common.model.Filter;
import com.jdcloud.sdk.annotation.Required;
import com.jdcloud.sdk.service.JdcloudRequest;
/**
* 查询私有网络列表
*/
public class DescribeVpcsRequest extends JdcloudRequest implements java.io.Serializable {
private static final long serialVersionUID = 1L;
/**
* 页码, 默认为1, 取值范围:[1,∞), 页码超过总页数时, 显示最后一页
*/
private Integer pageNumber;
/**
* 分页大小,默认为20,取值范围:[10,100]
*/
private Integer pageSize;
/**
* vpcIds - vpc ID列表,支持多个
vpcNames - vpc名称列表,支持多个
*/
private List<Filter> filters;
/**
* Region ID
* Required:true
*/
@Required
private String regionId;
/**
* get 页码, 默认为1, 取值范围:[1,∞), 页码超过总页数时, 显示最后一页
*
* @return
*/
public Integer getPageNumber() {
return pageNumber;
}
/**
* set 页码, 默认为1, 取值范围:[1,∞), 页码超过总页数时, 显示最后一页
*
* @param pageNumber
*/
public void setPageNumber(Integer pageNumber) {
this.pageNumber = pageNumber;
}
/**
* get 分页大小,默认为20,取值范围:[10,100]
*
* @return
*/
public Integer getPageSize() {
return pageSize;
}
/**
* set 分页大小,默认为20,取值范围:[10,100]
*
* @param pageSize
*/
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
/**
* get vpcIds - vpc ID列表,支持多个
vpcNames - vpc名称列表,支持多个
*
* @return
*/
public List<Filter> getFilters() {
return filters;
}
/**
* set vpcIds - vpc ID列表,支持多个
vpcNames - vpc名称列表,支持多个
*
* @param filters
*/
public void setFilters(List<Filter> filters) {
this.filters = filters;
}
/**
* get Region ID
*
* @return
*/
public String getRegionId() {
return regionId;
}
/**
* set Region ID
*
* @param regionId
*/
public void setRegionId(String regionId) {
this.regionId = regionId;
}
/**
* set 页码, 默认为1, 取值范围:[1,∞), 页码超过总页数时, 显示最后一页
*
* @param pageNumber
*/
public DescribeVpcsRequest pageNumber(Integer pageNumber) {
this.pageNumber = pageNumber;
return this;
}
/**
* set 分页大小,默认为20,取值范围:[10,100]
*
* @param pageSize
*/
public DescribeVpcsRequest pageSize(Integer pageSize) {
this.pageSize = pageSize;
return this;
}
/**
* set vpcIds - vpc ID列表,支持多个
vpcNames - vpc名称列表,支持多个
*
* @param filters
*/
public DescribeVpcsRequest filters(List<Filter> filters) {
this.filters = filters;
return this;
}
/**
* set Region ID
*
* @param regionId
*/
public DescribeVpcsRequest regionId(String regionId) {
this.regionId = regionId;
return this;
}
/**
* add item to vpcIds - vpc ID列表,支持多个
vpcNames - vpc名称列表,支持多个
*
* @param filter
*/
public void addFilter(Filter filter) {
if (this.filters == null) {
this.filters = new ArrayList<>();
}
this.filters.add(filter);
}
}
|
/* Copyright 2019 The TensorFlow Authors. 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.
==============================================================================*/
// Modified by Matthias Mueller - Intel Intelligent Systems Lab - 2020
package org.openbot.tracking;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Paint.Cap;
import android.graphics.Paint.Join;
import android.graphics.Paint.Style;
import android.graphics.RectF;
import android.text.TextUtils;
import android.util.Pair;
import android.util.TypedValue;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Queue;
import org.openbot.CameraActivity.ControlSignal;
import org.openbot.env.BorderedText;
import org.openbot.env.ImageUtils;
import org.openbot.env.Logger;
import org.openbot.tflite.Detector.Recognition;
/** A tracker that handles non-max suppression and matches existing objects to new detections. */
public class MultiBoxTracker {
private static final float TEXT_SIZE_DIP = 18;
private static final float MIN_SIZE = 16.0f;
private static final int[] COLORS = {
Color.BLUE,
Color.RED,
Color.GREEN,
Color.YELLOW,
Color.CYAN,
Color.MAGENTA,
Color.WHITE,
Color.parseColor("#55FF55"),
Color.parseColor("#FFA500"),
Color.parseColor("#FF8888"),
Color.parseColor("#AAAAFF"),
Color.parseColor("#FFFFAA"),
Color.parseColor("#55AAAA"),
Color.parseColor("#AA33AA"),
Color.parseColor("#0D0068")
};
final List<Pair<Float, RectF>> screenRects = new LinkedList<Pair<Float, RectF>>();
private final Logger logger = new Logger();
private final Queue<Integer> availableColors = new LinkedList<Integer>();
private final List<TrackedRecognition> trackedObjects = new LinkedList<TrackedRecognition>();
private final Paint boxPaint = new Paint();
private final float textSizePx;
private final BorderedText borderedText;
private Matrix frameToCanvasMatrix;
private int frameWidth;
private int frameHeight;
private int sensorOrientation;
private float leftControl;
private float rightControl;
public MultiBoxTracker(final Context context) {
for (final int color : COLORS) {
availableColors.add(color);
}
boxPaint.setColor(Color.RED);
boxPaint.setStyle(Style.STROKE);
boxPaint.setStrokeWidth(10.0f);
boxPaint.setStrokeCap(Cap.ROUND);
boxPaint.setStrokeJoin(Join.ROUND);
boxPaint.setStrokeMiter(100);
textSizePx =
TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, TEXT_SIZE_DIP, context.getResources().getDisplayMetrics());
borderedText = new BorderedText(textSizePx);
}
public synchronized void setFrameConfiguration(
final int width, final int height, final int sensorOrientation) {
frameWidth = width;
frameHeight = height;
this.sensorOrientation = sensorOrientation;
}
public synchronized void drawDebug(final Canvas canvas) {
final Paint textPaint = new Paint();
textPaint.setColor(Color.WHITE);
textPaint.setTextSize(60.0f);
final Paint boxPaint = new Paint();
boxPaint.setColor(Color.RED);
boxPaint.setAlpha(200);
boxPaint.setStyle(Style.STROKE);
for (final Pair<Float, RectF> detection : screenRects) {
final RectF rect = detection.second;
canvas.drawRect(rect, boxPaint);
canvas.drawText("" + detection.first, rect.left, rect.top, textPaint);
borderedText.drawText(canvas, rect.centerX(), rect.centerY(), "" + detection.first);
}
}
public synchronized void trackResults(final List<Recognition> results, final long timestamp) {
logger.i("Processing %d results from %d", results.size(), timestamp);
processResults(results);
}
private Matrix getFrameToCanvasMatrix() {
return frameToCanvasMatrix;
}
private void updateFrameToCanvasMatrix(int canvasHeight, int canvasWidth) {
final boolean rotated = sensorOrientation % 180 == 90;
final float multiplier =
Math.min(
canvasHeight / (float) (rotated ? frameWidth : frameHeight),
canvasWidth / (float) (rotated ? frameHeight : frameWidth));
frameToCanvasMatrix =
ImageUtils.getTransformationMatrix(
frameWidth,
frameHeight,
(int) (multiplier * (rotated ? frameHeight : frameWidth)),
(int) (multiplier * (rotated ? frameWidth : frameHeight)),
sensorOrientation,
new RectF(0, 0, 0, 0),
false);
}
public synchronized ControlSignal updateTarget() {
if (!trackedObjects.isEmpty()) {
// Pick person with highest probability
final RectF trackedPos = new RectF(trackedObjects.get(0).location);
final boolean rotated = sensorOrientation % 180 == 90;
float imgWidth = (float) (rotated ? frameHeight : frameWidth);
float centerX = (rotated ? trackedPos.centerY() : trackedPos.centerX());
// Make sure object center is in frame
centerX = Math.max(0.0f, Math.min(centerX, imgWidth));
// Scale relative position along x-axis between -1 and 1
float x_pos_norm = 1.0f - 2.0f * centerX / imgWidth;
// Scale to control signal and account for rotation
float x_pos_scaled = rotated ? -x_pos_norm * 1.0f : x_pos_norm * 1.0f;
//// Scale by "exponential" function: y = x / sqrt(1-x^2)
// Math.max (Math.min(x_pos_norm / Math.sqrt(1 - x_pos_norm * x_pos_norm),2),-2) * 255.0f;
if (x_pos_scaled < 0) {
leftControl = 1.0f;
rightControl = 1.0f + x_pos_scaled;
} else {
leftControl = 1.0f - x_pos_scaled;
rightControl = 1.0f;
}
} else {
leftControl = 0.0f;
rightControl = 0.0f;
}
return new ControlSignal(
(0 > sensorOrientation) ? rightControl : leftControl,
(0 > sensorOrientation) ? leftControl : rightControl);
}
public synchronized void draw(final Canvas canvas) {
updateFrameToCanvasMatrix(canvas.getHeight(), canvas.getWidth());
for (final TrackedRecognition recognition : trackedObjects) {
final RectF trackedPos = new RectF(recognition.location);
getFrameToCanvasMatrix().mapRect(trackedPos);
boxPaint.setColor(recognition.color);
float cornerSize = Math.min(trackedPos.width(), trackedPos.height()) / 8.0f;
canvas.drawRoundRect(trackedPos, cornerSize, cornerSize, boxPaint);
final String labelString =
!TextUtils.isEmpty(recognition.title)
? String.format(
Locale.US, "%s %.2f", recognition.title, (100 * recognition.detectionConfidence))
: String.format(Locale.US, "%.2f", 100 * recognition.detectionConfidence);
borderedText.drawText(
canvas, trackedPos.left + cornerSize, trackedPos.top, labelString + "%", boxPaint);
// if (recognition == trackedObjects.get(0)) {
// borderedText.drawText(
// canvas,
// trackedPos.left + cornerSize,
// trackedPos.top + 40.0f,
// String.format(Locale.US, "%.2f", leftControl) + "," + String.format("%.2f",
// rightControl),
// boxPaint);
// }
}
}
public void clearTrackedObjects() {
trackedObjects.clear();
}
private void processResults(final List<Recognition> results) {
final List<Pair<Float, Recognition>> rectsToTrack = new LinkedList<Pair<Float, Recognition>>();
screenRects.clear();
final Matrix rgbFrameToScreen = new Matrix(getFrameToCanvasMatrix());
for (final Recognition result : results) {
if (result.getLocation() == null) {
continue;
}
final RectF detectionFrameRect = new RectF(result.getLocation());
final RectF detectionScreenRect = new RectF();
rgbFrameToScreen.mapRect(detectionScreenRect, detectionFrameRect);
logger.v(
"Result! Frame: " + result.getLocation() + " mapped to screen:" + detectionScreenRect);
screenRects.add(new Pair<Float, RectF>(result.getConfidence(), detectionScreenRect));
if (detectionFrameRect.width() < MIN_SIZE || detectionFrameRect.height() < MIN_SIZE) {
logger.w("Degenerate rectangle! " + detectionFrameRect);
continue;
}
rectsToTrack.add(new Pair<Float, Recognition>(result.getConfidence(), result));
}
// Clear so objects don't stay if nothing detected.
trackedObjects.clear();
if (rectsToTrack.isEmpty()) {
logger.v("Nothing to track, aborting.");
return;
}
// trackedObjects.clear();
for (final Pair<Float, Recognition> potential : rectsToTrack) {
final TrackedRecognition trackedRecognition = new TrackedRecognition();
trackedRecognition.detectionConfidence = potential.first;
trackedRecognition.location = new RectF(potential.second.getLocation());
trackedRecognition.title = potential.second.getTitle();
trackedRecognition.color = COLORS[trackedObjects.size()];
trackedObjects.add(trackedRecognition);
if (trackedObjects.size() >= COLORS.length) {
break;
}
}
}
private static class TrackedRecognition {
RectF location;
float detectionConfidence;
int color;
String title;
}
}
|
/*
* Copyright 2019 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 software.amazon.smithy.cli;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import software.amazon.smithy.build.SmithyBuildException;
import software.amazon.smithy.utils.FunctionalUtils;
import software.amazon.smithy.utils.SetUtils;
/**
* This builder can be used to build up a Smithy CLI command to
* run `smithy build`.
*
* <p>This builder will take into account the "lib" and "build" classpaths
* that points to JAR files when determining which JARs are added as sources
* and which JARs are added as part of model discovery. This is determined
* based on the value provided for {@link #projectionSource}.
*
* <p>If {@code projectionSource} is not set or set to "source", then classes
* will be loaded using the lib and build classpath. However, models are
* discovered only using the lib classpath, ensuring that consumers of the
* generated JAR can find the required models using only the declared
* dependencies of this package.
*
* <p>If {@code projectionSource} is not set to something other than
* "source", then we build the model and discover models using only the build
* classpath. This provides a layer of isolation between the sources that
* created a projection from the downstream consumers of the projected model.
* {@code projectionSourceTags} can be provided to find JARs in the build
* classpath that have a META-INF/MANIFEST.MF "Smithy-Tags" value that matches
* one or more of the provided tags. This is used to select which models from
* your dependencies should be considered "sources" so that they show up in
* the JAR you're projecting.
*/
public final class BuildParameterBuilder {
private static final Logger LOGGER = Logger.getLogger(BuildParameterBuilder.class.getName());
private static final String SMITHY_TAG_PROPERTY = "Smithy-Tags";
private static final String SOURCE = "source";
private static final String PATH_SEPARATOR = "path.separator";
private String projectionSource = SOURCE;
private Set<String> projectionSourceTags = new LinkedHashSet<>();
private Set<String> buildClasspath = new LinkedHashSet<>();
private Set<String> libClasspath = new LinkedHashSet<>();
private Set<String> sources = new LinkedHashSet<>();
private ClassPathTagMatcher tagMatcher;
private Set<String> configs = new LinkedHashSet<>();
private String output;
private String projection;
private String plugin;
private boolean discover;
private boolean allowUnknownTraits;
private List<String> extraArgs = new ArrayList<>();
/**
* Sets the name of the projection being built as a source.
*
* <p>This means that the given projection is used to populate
* a build artifact (for example, a JAR being built by Gradle).
*
* @param projectionSource Projection name.
* @return Returns the builder.
*/
public BuildParameterBuilder projectionSource(String projectionSource) {
this.projectionSource = projectionSource == null || projectionSource.isEmpty() ? SOURCE : projectionSource;
return this;
}
/**
* Adds a collection of "source" model files.
*
* @param sources Sources to add.
* @return Returns the builder.
*/
public BuildParameterBuilder sources(Collection<String> sources) {
if (sources != null) {
this.sources.addAll(sources);
}
return this;
}
/**
* Adds a collection of "source" model files only if they exist.
*
* @param sources Sources to add.
* @return Returns the builder.
*/
public BuildParameterBuilder addSourcesIfExists(Collection<String> sources) {
if (sources != null) {
for (String source : sources) {
if (!source.isEmpty() && Files.exists(Paths.get(source))) {
this.sources.add(source);
} else {
LOGGER.info("Skipping source that does not exist: " + source);
}
}
}
return this;
}
/**
* Sets the build classpath.
*
* @param buildClasspath Classpath to set.
* @return Returns the builder.
*/
public BuildParameterBuilder buildClasspath(String buildClasspath) {
this.buildClasspath.addAll(splitAndFilterString(System.getProperty(PATH_SEPARATOR), buildClasspath));
return this;
}
private static Set<String> splitAndFilterString(String delimiter, String value) {
if (value == null) {
return SetUtils.of();
}
return Stream.of(value.split(Pattern.quote(delimiter)))
.map(String::trim)
.filter(FunctionalUtils.not(String::isEmpty))
.collect(Collectors.toCollection(LinkedHashSet::new));
}
/**
* Sets the lib classpath.
*
* @param libClasspath Classpath to set.
* @return Returns the builder.
*/
public BuildParameterBuilder libClasspath(String libClasspath) {
this.libClasspath.addAll(splitAndFilterString(System.getProperty(PATH_SEPARATOR), libClasspath));
return this;
}
/**
* Sets the tags to find in the build classpath when projecting a JAR.
*
* <p>Tags can only be provided if {@link #projectionSource} has been set to
* something other than "source".
*
* @param projectionSourceTags Comma separated list of projection tags.
* @return Returns the builder.
*/
public BuildParameterBuilder projectionSourceTags(String projectionSourceTags) {
return projectionSourceTags(splitAndFilterString(",", projectionSourceTags));
}
/**
* Sets the tags to find in the build classpath when projecting a JAR.
*
* <p>Tags can only be provided if {@link #projectionSource} has been set to
* something other than "source".
*
* @param projectionSourceTags Projection tags.
* @return Returns the builder.
*/
public BuildParameterBuilder projectionSourceTags(Collection<String> projectionSourceTags) {
if (projectionSourceTags != null) {
this.projectionSourceTags.addAll(projectionSourceTags);
}
return this;
}
/**
* Sets the implementation used to find JARs with the given tags.
*
* <p>A default implementation that loads JARs is automatically used if
* an explicit implementation is not specified. You probably only need
* to provide a custom implementation for testing.
*
* @param tagMatcher Tag matching implementation.
* @return Returns the builder.
*/
public BuildParameterBuilder tagMatcher(ClassPathTagMatcher tagMatcher) {
this.tagMatcher = Objects.requireNonNull(tagMatcher);
return this;
}
/**
* Adds a configuration file to the builder.
*
* @param pathToConfig Path to the configuration file.
* @return Returns the builder.
*/
public BuildParameterBuilder addConfig(String pathToConfig) {
if (pathToConfig != null && !pathToConfig.isEmpty()) {
configs.add(pathToConfig);
}
return this;
}
/**
* Adds a configuration file to the builder only if it exists.
*
* <p>This method is ignored if the file is null, empty, or does
* not exist.
*
* @param pathToConfig Path to the configuration file.
* @return Returns the builder.
*/
public BuildParameterBuilder addConfigIfExists(String pathToConfig) {
if (pathToConfig == null || pathToConfig.isEmpty()) {
return this;
} else if (!Files.exists(Paths.get(pathToConfig))) {
LOGGER.info("Not setting --config to " + pathToConfig + " because it does not exist");
return this;
}
return addConfig(pathToConfig);
}
/**
* Sets the optional output directory.
*
* @param output Optional output directory to set.
* @return Returns the builder.
*/
public BuildParameterBuilder output(String output) {
this.output = output;
return this;
}
/**
* Ensures that only the given projection is built. All other
* projections are skipped.
*
* <p>This is not the same as calling {@link #projectionSource}.
*
* @param projection Projection to build, excluding others.
* @return Returns the builder.
*/
public BuildParameterBuilder projection(String projection) {
this.projection = projection;
return this;
}
/**
* Ensures that only the given plugin is built in each projection.
* All other plugins are skipped.
*
* @param plugin Plugin to build, excluding others.
* @return Returns the builder.
*/
public BuildParameterBuilder plugin(String plugin) {
this.plugin = plugin;
return this;
}
/**
* Enables model discovery.
*
* @param discover Set to true to enable model discovery.
* @return Returns the builder.
*/
public BuildParameterBuilder discover(boolean discover) {
this.discover = discover;
return this;
}
/**
* Ignores unknown traits when building models.
*
* @param allowUnknownTraits Set to true to allow unknown traits.
* @return Returns the builder.
*/
public BuildParameterBuilder allowUnknownTraits(boolean allowUnknownTraits) {
this.allowUnknownTraits = allowUnknownTraits;
return this;
}
/**
* Adds extra arguments to the CLI arguments before positional arguments.
*
* @param args Arguments to add.
* @return Returns the builder.
*/
public BuildParameterBuilder addExtraArgs(String... args) {
Collections.addAll(extraArgs, Objects.requireNonNull(args));
return this;
}
/**
* Computes the result object that is used when running smithy build.
*
* @return Returns the computed result.
*/
public Result build() {
if (projectionSource.equals(SOURCE)) {
return configureSourceProjection();
}
// Create a default tag matcher.
if (tagMatcher == null) {
tagMatcher = new JarFileClassPathTagMatcher();
}
return configureProjection();
}
/**
* When building the source projection, classes will be loaded using
* the lib and build tool classpath. However, models are discovered only
* using the lib classpath, ensuring that consumers of the generated JAR
* can find the required models using only the declared dependencies of
* this package.
*
* @return Returns the result.
*/
private Result configureSourceProjection() {
LOGGER.info("Configuring SmithyBuild classpaths for the `source` projection");
if (!projectionSourceTags.isEmpty()) {
throw new SmithyBuildException("Projection source tags cannot be set when building a source projection.");
}
// Create a discovery classpath that ensures that sources are not added
// to the discovery classpath.
Set<String> computedDiscovery = new LinkedHashSet<>(libClasspath);
computedDiscovery.removeAll(sources);
if (!discover) {
computedDiscovery.clear();
}
// Create the combined classpath that contains build and lib dependencies.
Set<String> combined = new LinkedHashSet<>(libClasspath);
combined.addAll(buildClasspath);
String discoveryClasspath = String.join(System.getProperty(PATH_SEPARATOR), computedDiscovery);
String classpath = String.join(System.getProperty(PATH_SEPARATOR), combined);
return new Result(this, discoveryClasspath, classpath, sources);
}
/**
* When a projection is applied, we build the model and discover models
* using only the build tool classpath. This provides a layer of isolation
* between the sources that created a projection from the downstream
* consumers of the projected model.
*
* @return Returns the result.
*/
private Result configureProjection() {
if (projectionSourceTags.isEmpty()) {
LOGGER.warning("No projection source tags were set for the projection `" + projection + "`, so the "
+ "projection will not have any sources in it other than files found in the sources of "
+ "the package being built.");
String buildCp = String.join(System.getProperty(PATH_SEPARATOR), buildClasspath);
return new Result(this, buildCp, buildCp, sources);
}
LOGGER.fine("Configuring Smithy classpaths for projection `" + projection + "`");
// Find all JARs that have a matching tag and add them to sources.
Set<String> computedSources = new LinkedHashSet<>(sources);
Set<String> tagSourceJars = tagMatcher.findJarsWithMatchingTags(buildClasspath, projectionSourceTags);
computedSources.addAll(tagSourceJars);
LOGGER.info("Found the following JARs that matched the Smithy projection tags query: " + tagSourceJars);
// Create a discovery classpath that ensures that sources (both explicit and
// discovered through tags) are not added to the discovery classpath.
Set<String> computedDiscovery = new LinkedHashSet<>(buildClasspath);
computedDiscovery.removeAll(computedSources);
String discoveryClasspath = String.join(System.getProperty(PATH_SEPARATOR), computedDiscovery);
String classpath = String.join(System.getProperty(PATH_SEPARATOR), buildClasspath);
return new Result(this, discoveryClasspath, classpath, computedSources);
}
/**
* Result class used to build source and projection JARs.
*/
public static final class Result {
/**
* Smithy Build command line arguments.
*
* <p>This value can be explicitly mutated as needed.
*/
public final List<String> args;
/**
* The set of source models, including computed sources used in the argument list.
*
* <p>This value can be explicitly mutated as needed.
*/
public final Set<String> sources;
/**
* Smithy build classpath string.
*
* <p>This is the classpath that should be used when invoking the CLI.
* The value is a colon (:) separate string.
*/
public final String classpath;
/**
* Smithy build discovery classpath string string.
*
* <p>This is the classpath that is also specified in the arguments list and
* is used for model discovery. The value is a colon (:) separate string.
*/
public final String discoveryClasspath;
private Result(BuildParameterBuilder builder, String discoveryClasspath,
String classpath, Set<String> sources) {
this.classpath = classpath;
this.sources = new LinkedHashSet<>(sources);
args = new ArrayList<>();
args.add("build");
args.addAll(builder.extraArgs);
if (!builder.discover) {
this.discoveryClasspath = "";
} else {
this.discoveryClasspath = discoveryClasspath;
if (!discoveryClasspath.isEmpty()) {
args.add(SmithyCli.DISCOVER_CLASSPATH);
args.add(discoveryClasspath);
} else {
args.add(SmithyCli.DISCOVER);
}
}
if (builder.allowUnknownTraits) {
args.add(SmithyCli.ALLOW_UNKNOWN_TRAITS);
}
builder.configs.forEach(config -> {
args.add("--config");
args.add(config);
});
if (builder.output != null) {
args.add("--output");
args.add(builder.output);
}
if (builder.projection != null) {
args.add("--projection");
args.add(builder.projection);
}
if (builder.plugin != null) {
args.add("--plugin");
args.add(builder.plugin);
}
args.addAll(sources);
}
}
/**
* Interface used to query a classpath for the given projection sources tags.
*/
public interface ClassPathTagMatcher {
/**
* Finds all JARs that contain any of the given set of tags.
*
* @param classpath Set of paths to JARs to search.
* @param tagsToFind Tags to search for in the classpath.
* @return Returns the matching JARs in the classpath.
*/
Set<String> findJarsWithMatchingTags(Set<String> classpath, Set<String> tagsToFind);
}
/**
* Finds JARs by opening each JAR in the classpath and looking for
* "Smithy-Tags" in the META-INF/MANIFEST.MF file.
*/
public static final class JarFileClassPathTagMatcher implements ClassPathTagMatcher {
@Override
public Set<String> findJarsWithMatchingTags(Set<String> classpath, Set<String> tagsToFind) {
Set<String> tagSourceJars = new LinkedHashSet<>();
for (String jar : classpath) {
if (!Files.exists(Paths.get(jar))) {
LOGGER.severe("Classpath entry not found: " + jar);
continue;
}
try (JarFile jarFile = new JarFile(jar)) {
Manifest manifest = jarFile.getManifest();
Attributes.Name name = new Attributes.Name(SMITHY_TAG_PROPERTY);
if (manifest == null || !manifest.getMainAttributes().containsKey(name)) {
continue;
}
Set<String> jarTags = loadTags((String) manifest.getMainAttributes().get(name));
LOGGER.info("Found Smithy-Tags in JAR dependency `" + jar + "`: " + jarTags);
for (String needle : tagsToFind) {
if (jarTags.contains(needle)) {
tagSourceJars.add(jar);
break;
}
}
} catch (IOException e) {
throw new SmithyBuildException(
"Error reading manifest from JAR in build dependencies: " + e.getMessage(), e);
}
}
return tagSourceJars;
}
private Set<String> loadTags(String sourceTagString) {
return splitAndFilterString(",", sourceTagString);
}
}
}
|
package com.applozic.mobicomkit.contact;
import android.content.Context;
import android.graphics.Bitmap;
import android.text.TextUtils;
import com.applozic.mobicomkit.Applozic;
import com.applozic.mobicomkit.api.attachment.FileClientService;
import com.applozic.mobicomkit.api.people.AlGetPeopleTask;
import com.applozic.mobicomkit.broadcast.BroadcastService;
import com.applozic.mobicomkit.cache.MessageSearchCache;
import com.applozic.mobicomkit.channel.service.ChannelService;
import com.applozic.mobicomkit.contact.database.ContactDatabase;
import com.applozic.mobicomkit.listners.AlContactListener;
import com.applozic.mobicommons.ApplozicService;
import com.applozic.mobicommons.commons.image.ImageUtils;
import com.applozic.mobicommons.people.channel.Channel;
import com.applozic.mobicommons.people.contact.Contact;
import java.io.File;
import java.util.Date;
import java.util.List;
/**
* Created by adarsh on 7/7/15.
*/
public class AppContactService implements BaseContactService {
private static final String TAG = "AppContactService";
ContactDatabase contactDatabase;
Context context;
FileClientService fileClientService;
public AppContactService(Context context) {
this.context = ApplozicService.getContext(context);
this.contactDatabase = new ContactDatabase(context);
this.fileClientService = new FileClientService(context);
}
@Override
public void add(Contact contact) {
contactDatabase.addContact(contact);
}
@Override
public void addAll(List<Contact> contactList) {
for (Contact contact : contactList) {
upsert(contact);
}
}
@Override
public void deleteContact(Contact contact) {
contactDatabase.deleteContact(contact);
}
@Override
public void deleteContactById(String contactId) {
contactDatabase.deleteContactById(contactId);
}
@Override
public List<Contact> getAll() {
return contactDatabase.getAllContact();
}
@Override
public Contact getContactById(String contactId) {
Contact contact;
contact = MessageSearchCache.getContactById(contactId);
if (contact == null) {
contact = contactDatabase.getContactById(contactId);
}
if (contact != null) {
contact.processContactNumbers(context);
} else {
contact = new Contact(context, contactId);
upsert(contact);
}
return contact;
}
@Override
public void updateContact(Contact contact) {
if (Applozic.getInstance(context).isDeviceContactSync()) {
contact.processContactNumbers(context);
}
contactDatabase.updateContact(contact);
}
@Override
public void upsert(Contact contact) {
if (Applozic.getInstance(context).isDeviceContactSync()) {
contact.processContactNumbers(context);
if (contact.getDeviceContactType() == null || TextUtils.isEmpty(contact.getFormattedContactNumber())) {
if (contactDatabase.getContactById(contact.getUserId()) == null) {
contactDatabase.addContact(contact);
} else {
contactDatabase.updateContact(contact);
}
} else {
//Need to check if contact no exist
if (contactDatabase.getContactByPhoneNo(contact.getFormattedContactNumber()) != null) {
contactDatabase.updateContactByPhoneNumber(contact);
} else if (contactDatabase.getContactById(contact.getUserId()) == null) {
contactDatabase.addContact(contact);
} else {
contactDatabase.updateContact(contact);
}
}
} else {
if (contactDatabase.getContactById(contact.getUserId()) == null) {
contactDatabase.addContact(contact);
} else {
contactDatabase.updateContact(contact);
}
}
}
@Override
public List<Contact> getContacts(Contact.ContactType contactType) {
return contactDatabase.getContacts(contactType);
}
@Override
public List<Contact> getAllContactListExcludingLoggedInUser() {
return contactDatabase.getAllContactListExcludingLoggedInUser();
}
@Override
public Bitmap downloadContactImage(Context context, Contact contact) {
if (contact != null && TextUtils.isEmpty(contact.getImageURL())) {
return null;
}
Bitmap attachedImage = ImageUtils.getBitMapFromLocalPath(contact.getLocalImageUrl());
if (attachedImage != null) {
return attachedImage;
}
Bitmap bitmap = fileClientService.downloadBitmap(contact, null);
if (bitmap != null) {
File file = FileClientService.getFilePath(contact.getContactIds(), context.getApplicationContext(), "image", true);
String imageLocalPath = ImageUtils.saveImageToInternalStorage(file, bitmap);
contact.setLocalImageUrl(imageLocalPath);
}
if (!TextUtils.isEmpty(contact.getLocalImageUrl())) {
updateLocalImageUri(contact);
}
return bitmap;
}
@Override
public Bitmap downloadGroupImage(Context context, Channel channel) {
if (channel != null && TextUtils.isEmpty(channel.getImageUrl())) {
return null;
}
Bitmap attachedImage = ImageUtils.getBitMapFromLocalPath(channel.getLocalImageUri());
if (attachedImage != null) {
return attachedImage;
}
Bitmap bitmap = fileClientService.downloadBitmap(null, channel);
if (bitmap != null) {
File file = FileClientService.getFilePath(String.valueOf(channel.getKey()), context.getApplicationContext(), "image", true);
String imageLocalPath = ImageUtils.saveImageToInternalStorage(file, bitmap);
channel.setLocalImageUri(imageLocalPath);
}
if (!TextUtils.isEmpty(channel.getLocalImageUri())) {
ChannelService.getInstance(context).updateChannelLocalImageURI(channel.getKey(), channel.getLocalImageUri());
}
return bitmap;
}
public Contact getContactReceiver(List<String> items, List<String> userIds) {
if (userIds != null && !userIds.isEmpty()) {
return getContactById(userIds.get(0));
} else if (items != null && !items.isEmpty()) {
return getContactById(items.get(0));
}
return null;
}
@Override
public boolean isContactExists(String contactId) {
return contactDatabase.getContactById(contactId) != null;
}
@Override
public void updateConnectedStatus(String contactId, Date date, boolean connected) {
Contact contact = contactDatabase.getContactById(contactId);
if (contact != null && contact.isConnected() != connected) {
contactDatabase.updateConnectedOrDisconnectedStatus(contactId, date, connected);
BroadcastService.sendUpdateLastSeenAtTimeBroadcast(context, BroadcastService.INTENT_ACTIONS.UPDATE_LAST_SEEN_AT_TIME.toString(), contactId);
}
}
@Override
public void updateUserBlocked(String userId, boolean userBlocked) {
if (!TextUtils.isEmpty(userId)) {
contactDatabase.updateUserBlockStatus(userId, userBlocked);
BroadcastService.sendUpdateLastSeenAtTimeBroadcast(context, BroadcastService.INTENT_ACTIONS.UPDATE_LAST_SEEN_AT_TIME.toString(), userId);
}
}
@Override
public void updateUserBlockedBy(String userId, boolean userBlockedBy) {
if (!TextUtils.isEmpty(userId)) {
contactDatabase.updateUserBlockByStatus(userId, userBlockedBy);
BroadcastService.sendUpdateLastSeenAtTimeBroadcast(context, BroadcastService.INTENT_ACTIONS.UPDATE_LAST_SEEN_AT_TIME.toString(), userId);
}
}
@Override
public boolean isContactPresent(String userId) {
return contactDatabase.isContactPresent(userId);
}
@Override
public int getChatConversationCount() {
return contactDatabase.getChatUnreadCount();
}
@Override
public int getGroupConversationCount() {
return contactDatabase.getGroupUnreadCount();
}
@Override
public void updateLocalImageUri(Contact contact) {
contactDatabase.updateLocalImageUri(contact);
}
public void getContactByIdAsync(String userId, AlContactListener contactListener) {
new AlGetPeopleTask(context, userId, null, null, null, contactListener, this, null).execute();
}
}
|
package epicsquid.roots.network.fx;
import epicsquid.mysticallib.util.Util;
import epicsquid.roots.particle.ParticleUtil;
import epicsquid.roots.spell.SpellShatter;
import io.netty.buffer.ByteBuf;
import net.minecraft.client.Minecraft;
import net.minecraft.util.math.MathHelper;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.network.simpleimpl.IMessage;
import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler;
import net.minecraftforge.fml.common.network.simpleimpl.MessageContext;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
public class MessageShatterBurstFX implements IMessage {
private double srcX = 0, srcY = 0, srcZ = 0;
private double posX = 0, posY = 0, posZ = 0;
public MessageShatterBurstFX() {
super();
}
public MessageShatterBurstFX(double sx, double sy, double sz, double x, double y, double z) {
super();
this.srcX = sx;
this.srcY = sy;
this.srcZ = sz;
this.posX = x;
this.posY = y;
this.posZ = z;
}
@Override
public void fromBytes(ByteBuf buf) {
srcX = buf.readDouble();
srcY = buf.readDouble();
srcZ = buf.readDouble();
posX = buf.readDouble();
posY = buf.readDouble();
posZ = buf.readDouble();
}
@Override
public void toBytes(ByteBuf buf) {
buf.writeDouble(srcX);
buf.writeDouble(srcY);
buf.writeDouble(srcZ);
buf.writeDouble(posX);
buf.writeDouble(posY);
buf.writeDouble(posZ);
}
public static float getColorCycle(float ticks) {
return (MathHelper.sin((float) Math.toRadians(ticks)) + 1.0f) / 2.0f;
}
public static class MessageHolder implements IMessageHandler<MessageShatterBurstFX, IMessage> {
@SideOnly(Side.CLIENT)
@Override
public IMessage onMessage(final MessageShatterBurstFX message, final MessageContext ctx) {
World world = Minecraft.getMinecraft().world;
for (float i = 0; i < 40; i++) {
double x = (1.0f - i / 40.0f) * message.srcX + (i / 40.0f) * message.posX;
double y = (1.0f - i / 40.0f) * message.srcY + (i / 40.0f) * message.posY;
double z = (1.0f - i / 40.0f) * message.srcZ + (i / 40.0f) * message.posZ;
if (Util.rand.nextBoolean()) {
ParticleUtil.spawnParticleGlow(world, (float) x, (float) y, (float) z, 0, 0, 0, SpellShatter.instance.getRed1() * 255.0f,
SpellShatter.instance.getGreen1() * 255.0f, SpellShatter.instance.getBlue1() * 255.0f, 0.25f * (i / 40.0f), 2.5f, 24);
} else {
ParticleUtil.spawnParticleGlow(world, (float) x, (float) y, (float) z, 0, 0, 0, SpellShatter.instance.getRed2() * 255.0f,
SpellShatter.instance.getGreen2() * 255.0f, SpellShatter.instance.getBlue2() * 255.0f, 0.25f * (i / 40.0f), 2.5f, 24);
}
}
for (int k = 0; k < 20; k++) {
if (Util.rand.nextBoolean()) {
ParticleUtil.spawnParticleGlow(world, (float) message.posX, (float) message.posY, (float) message.posZ, 0.25f * (Util.rand.nextFloat() - 0.5f),
0.25f * (Util.rand.nextFloat() - 0.5f), 0.25f * (Util.rand.nextFloat() - 0.5f), SpellShatter.instance.getRed1() * 255.0f,
SpellShatter.instance.getGreen1() * 255.0f, SpellShatter.instance.getBlue1() * 255.0f, 0.25f, 5f, 12);
} else {
ParticleUtil.spawnParticleGlow(world, (float) message.posX, (float) message.posY, (float) message.posZ, 0.25f * (Util.rand.nextFloat() - 0.5f),
0.25f * (Util.rand.nextFloat() - 0.5f), 0.25f * (Util.rand.nextFloat() - 0.5f), SpellShatter.instance.getRed2() * 255.0f,
SpellShatter.instance.getGreen2() * 255.0f, SpellShatter.instance.getBlue2() * 255.0f, 0.25f, 5f, 12);
}
}
return null;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.